1 /**
2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "types/location.h"
17
18 #include <cfloat>
19 #include <cmath>
20 #include <string>
21
22 #include "utils/expected.h"
23 #include "utils/json_builder.h"
24 #include "utils/json_parser.h"
25
26 #include "types/numeric_id.h"
27
28 using namespace std::literals::string_literals; // NOLINT(google-build-using-namespace)
29
30 namespace ark::tooling::inspector {
FromJsonProperty(const JsonObject & object,const char * propertyName)31 Expected<Location, std::string> Location::FromJsonProperty(const JsonObject &object, const char *propertyName)
32 {
33 auto property = object.GetValue<JsonObject::JsonObjPointer>(propertyName);
34 if (property == nullptr) {
35 return Unexpected("No such property: "s + propertyName);
36 }
37
38 auto scriptId = ParseNumericId<ScriptId>(**property, "scriptId");
39 if (!scriptId) {
40 return Unexpected(scriptId.Error());
41 }
42
43 auto lineNumber = property->get()->GetValue<JsonObject::NumT>("lineNumber");
44 if (lineNumber == nullptr) {
45 return Unexpected("Invalid Location: No 'lineNumber' property"s);
46 }
47
48 auto lineNumberTrunc = std::trunc(*lineNumber);
49 if (*lineNumber < 0 || *lineNumber - lineNumberTrunc > lineNumberTrunc * DBL_EPSILON) {
50 return Unexpected("Invalid line number: " + std::to_string(*lineNumber));
51 }
52
53 return Location(*scriptId, lineNumberTrunc + 1);
54 }
55
Serialize(JsonObjectBuilder & builder) const56 void Location::Serialize(JsonObjectBuilder &builder) const
57 {
58 builder.AddProperty("scriptId", std::to_string(scriptId_));
59 builder.AddProperty("lineNumber", lineNumber_ - 1);
60 }
61
62 } // namespace ark::tooling::inspector
63