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 "location.h"
17 #include "numeric_id.h"
18
19 #include "utils/expected.h"
20 #include "utils/json_builder.h"
21 #include "utils/json_parser.h"
22
23 #include <cfloat>
24 #include <cmath>
25 #include <string>
26
27 using namespace std::literals::string_literals; // NOLINT(google-build-using-namespace)
28
29 namespace ark::tooling::inspector {
FromJsonProperty(const JsonObject & object,const char * propertyName)30 Expected<Location, std::string> Location::FromJsonProperty(const JsonObject &object, const char *propertyName)
31 {
32 auto property = object.GetValue<JsonObject::JsonObjPointer>(propertyName);
33 if (property == nullptr) {
34 return Unexpected("No such property: "s + propertyName);
35 }
36
37 auto scriptId = ParseNumericId<ScriptId>(**property, "scriptId");
38 if (!scriptId) {
39 return Unexpected(scriptId.Error());
40 }
41
42 auto lineNumber = property->get()->GetValue<JsonObject::NumT>("lineNumber");
43 if (lineNumber == nullptr) {
44 return Unexpected("Invalid Location: No 'lineNumber' property"s);
45 }
46
47 auto lineNumberTrunc = std::trunc(*lineNumber);
48 if (*lineNumber < 0 || *lineNumber - lineNumberTrunc > lineNumberTrunc * DBL_EPSILON) {
49 return Unexpected("Invalid line number: " + std::to_string(*lineNumber));
50 }
51
52 return Location(*scriptId, lineNumberTrunc + 1);
53 }
54
ToJson() const55 std::function<void(JsonObjectBuilder &)> Location::ToJson() const
56 {
57 return [this](JsonObjectBuilder &jsonBuilder) {
58 jsonBuilder.AddProperty("scriptId", std::to_string(scriptId_));
59 jsonBuilder.AddProperty("lineNumber", lineNumber_ - 1);
60 };
61 }
62 } // namespace ark::tooling::inspector
63