1/* 2 * Copyright (c) 2021 - 2023 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 "number.h" 17#include "lexer/lexer.h" 18 19#include <cstdint> 20#include <cstdlib> 21#include <cerrno> 22#include <limits> 23 24namespace ark::es2panda::lexer { 25// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,bugprone-exception-escape) 26Number::Number(util::StringView str, const std::string &utf8, NumberFlags flags) noexcept : str_(str), flags_(flags) 27{ 28 Lexer::ConversionResult res; 29 if ((flags & (NumberFlags::DECIMAL_POINT | NumberFlags::EXPONENT)) == 0) { 30 const int64_t temp = Lexer::StrToNumeric(&std::strtoll, utf8.c_str(), res, 10); 31 32 if (res == Lexer::ConversionResult::SUCCESS) { 33 if (temp <= std::numeric_limits<int32_t>::max() && temp >= std::numeric_limits<int32_t>::min()) { 34 num_ = static_cast<int32_t>(temp); 35 return; 36 } 37 38 num_ = temp; 39 return; 40 } 41 if (res == Lexer::ConversionResult::INVALID_ARGUMENT) { 42 flags_ |= NumberFlags::ERROR; 43 } 44 } 45 46 const double temp = Lexer::StrToNumeric(&std::strtod, utf8.c_str(), res); 47 if (res == Lexer::ConversionResult::SUCCESS) { 48 num_ = temp; 49 } else if (res == Lexer::ConversionResult::INVALID_ARGUMENT) { 50 flags_ |= NumberFlags::ERROR; 51 } else if (res == Lexer::ConversionResult::OUT_OF_RANGE) { 52 num_ = std::numeric_limits<double>::infinity(); 53 } 54} 55} // namespace ark::es2panda::lexer 56