• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 #ifndef ES2PANDA_UTIL_HELPERS_H
17 #define ES2PANDA_UTIL_HELPERS_H
18 
19 #include <cmath>
20 
21 #include <mem/arena_allocator.h>
22 #include <os/file.h>
23 #include <os/library_loader.h>
24 
25 #include <binder/variableFlags.h>
26 #include <programCache.h>
27 #include <util/ustring.h>
28 
29 namespace panda::es2panda::ir {
30 class Expression;
31 class ScriptFunction;
32 class ClassDefinition;
33 class ClassProperty;
34 class Identifier;
35 class AstNode;
36 class ObjectExpression;
37 class StringLiteral;
38 class Statement;
39 }  // namespace panda::es2panda::ir
40 
41 namespace panda::es2panda {
42 struct CompilerOptions;
43 enum class ErrorType;
44 
45 struct PkgInfo {
46     std::string packageName {};
47     std::string version {};
48 };
49 
50 struct CompileContextInfo {
51     std::vector<std::string> compileEntries;
52     std::set<std::string> externalPkgNames;
53     std::map<std::string, PkgInfo> pkgContextInfo;
54     // The key of updateVersionInfo is the package name for an abc file, and the value contains the name of its
55     // dependent pacakge and corresponding package version which need to update version.
56     std::unordered_map<std::string, std::map<std::string, PkgInfo>> updateVersionInfo;
57     /**
58      * When there is an abc file as input and needModifyRecord is true, it is necessary to modify the recordName
59      * in abc2program and modify the ohmurl for dynamic and static imports.
60      **/
61     bool needModifyRecord {false};
62     std::string bundleName {};
63 };
64 }  // namespace panda::es2panda
65 
66 namespace panda::es2panda::binder {
67 class Scope;
68 }
69 namespace panda::pandasm {
70 struct Program;
71 }  // namespace panda::pandasm
72 
73 namespace panda::es2panda::lexer {
74 class LineIndex;
75 class SourcePosition;
76 }
77 
78 namespace panda::es2panda::parser {
79 class Program;
80 }
81 
82 namespace panda::es2panda::util {
83 
84 enum class SignedNumberLiteral {
85     UNRECOGNIZED = 0,
86     POSITIVE = 1,
87     NEGATIVE = 2
88 };
89 
90 class FileSuffix {
91 public:
92     static constexpr std::string_view DLL = ".dll";
93     static constexpr std::string_view SO = ".so";
94     static constexpr std::string_view DYLIB = ".dylib";
95 };
96 
97 template<typename T>
98 class SaveValue {
99 public:
SaveValue(T & value)100     explicit SaveValue(T &value) : ptr_(&value), value_(value) {}
101 
~SaveValue()102     ~SaveValue()
103     {
104         *ptr_ = value_;
105     }
106 private:
107     T *ptr_;
108     T value_;
109 };
110 
111 using AopTransformFuncDef = int (*)(const char *);
112 
113 class Helpers {
114 public:
115     Helpers() = delete;
116 
117     static bool IsGlobalIdentifier(const util::StringView &str);
118     static bool ContainSpreadElement(const ArenaVector<ir::Expression *> &args);
119     static util::StringView LiteralToPropName(ArenaAllocator *allocator, const ir::Expression *lit);
120 
121     template <typename T>
122     static bool IsInteger(double number);
123     static bool IsIndex(double number);
124     static int64_t GetIndex(const util::StringView &str);
125 
126     static bool FileExtensionIs(std::string_view filePath, std::string_view extension);
127     static bool EndsWith(std::string_view str, std::string_view suffix);
128     static std::string DoubleToString(double number);
129     static int32_t GetIntegerSignificandBitCount(double number, int32_t &numberBitCount, char *significandArray);
130     static void GetScientificNotationForDouble(double number, uint32_t significandBitCount, int32_t &numberBitCount,
131                                                char *significandArray, char *sciNotationArray, uint32_t size);
132     static std::string ToString(double number);
133     static util::StringView ToStringView(ArenaAllocator *allocator, double number);
134     static util::StringView ToStringView(ArenaAllocator *allocator, int32_t number);
135     static util::StringView ToStringView(ArenaAllocator *allocator, uint32_t number);
136 
137     static const ir::ScriptFunction *GetContainingConstructor(const ir::AstNode *node);
138     static const ir::ScriptFunction *GetContainingConstructor(const ir::ClassProperty *node);
139     static const ir::ScriptFunction *GetContainingFunction(const ir::AstNode *node);
140     static const ir::ClassDefinition *GetClassDefiniton(const ir::ScriptFunction *node);
141     static bool IsSpecialPropertyKey(const ir::Expression *expr);
142     static bool IsConstantPropertyKey(const ir::Expression *expr, bool isComputed);
143     static bool IsConstantExpr(const ir::Expression *expr);
144     static bool IsBindingPattern(const ir::AstNode *node);
145     static bool IsPattern(const ir::AstNode *node);
146     static std::vector<const ir::Identifier *> CollectBindingNames(const ir::AstNode *node);
147     static util::StringView FunctionName(ArenaAllocator *allocator, const ir::ScriptFunction *func);
148     static util::StringView GetName(ArenaAllocator *allocator, const ir::AstNode *node);
149     static std::tuple<util::StringView, bool> ParamName(ArenaAllocator *allocator, const ir::AstNode *param,
150                                                         uint32_t index);
151     static bool IsChild(const ir::AstNode *parent, const ir::AstNode *child);
152     static bool IsChildScope(const binder::Scope *parent, const binder::Scope *child);
153     static bool IsObjectPropertyValue(const ArenaVector<ir::Expression *> &properties, const ir::AstNode *ident);
154     static SignedNumberLiteral GetSignedNumberLiteral(const ir::Expression *expr);
155 
156     static void SetConstantLocalExportSlots(const std::string &record, const std::unordered_set<uint32_t> &slots);
157     static void AnalysisProgram(panda::pandasm::Program *prog, const std::string &inputFile);
158     static void OptimizeProgram(panda::pandasm::Program *prog, const std::string &inputFile);
159     static bool CheckAopTransformPath(const std::string &libPath);
160     static AopTransformFuncDef LoadAopTransformLibFunc(const std::string &libPath,
161         const std::string &funcName, os::library_loader::LibraryHandle &handler);
162     static bool AopTransform(const std::string &inputFile, const std::string &libPath);
163     template <typename T>
164     static T BaseName(T const &path, T const &delims = std::string(panda::os::file::File::GetPathDelim()));
165     static bool ReadFileToBuffer(const std::string &file, std::stringstream &ss);
166     static void ScanDirectives(ir::ScriptFunction *func, const lexer::LineIndex &lineIndex, bool enableSendableClass,
167                                bool enableSendableFunc);
168     static std::string GetHashString(const std::string &str);
169     static std::wstring Utf8ToUtf16(const std::string &utf8);
170     template <typename T, typename... Args>
171     static T FileStream(const std::string &str, Args &&...args);
172     static void ThrowError(ErrorType type, const parser::Program *program, const lexer::SourcePosition &pos,
173         const std::string_view &msg);
174     static bool IsUseShared(const ir::Statement *statement);
175     static const ir::ClassDefinition *GetContainingSendableClass(const ir::AstNode *node);
176     static bool IsSpecialScopeName(const util::StringView &str);
177     static bool BelongingToRecords(const std::string &name, const std::unordered_set<std::string> &retainRecordSet,
178                                    const std::string &delimiter = std::string(DOT));
179     static void RemoveProgramsRedundantData(std::map<std::string, panda::es2panda::util::ProgramCache*> &progsInfo,
180         const std::map<std::string, std::unordered_set<std::string>> &resolveDepsRelation);
181     static bool IsDefaultApiVersion(int apiVersion, std::string subApiVersion);
182     static bool IsSupportLazyImportVersion(int apiVersion, std::string subApiVersion);
183     static bool IsSupportLazyImportDefaultVersion(int apiVersion);
184     static bool IsEnableExpectedPropertyCountApiVersion(int apiVersion);
185 
186     static const uint32_t MAX_DOUBLE_DIGIT = 310;
187     static const uint32_t MAX_DOUBLE_PRECISION_DIGIT = 17;
188     static const int32_t MAX_DECIMAL_EXPONENT = 21;
189     static const int32_t MIN_DECIMAL_EXPONENT = -6;
190     static const int32_t FAIL_SNPRINTF_S  = -1;
191     static const uint32_t INVALID_INDEX = 4294967295L;
192     static const uint32_t MAX_INT32 = 2147483647;
193     static const uint32_t MAX_INT16 = std::numeric_limits<int16_t>::max();
194     static const uint32_t MAX_INT8 = std::numeric_limits<int8_t>::max();
195     static constexpr std::string_view USE_CONCURRENT = "use concurrent";
196     static constexpr std::string_view USE_SENDABLE = "use sendable";
197     static constexpr std::string_view USE_SHARED = "use shared";
198     static constexpr std::string_view STRING_EMPTY = ""; // Default tag value, or tag of GlobalScope and ModuleScope
199     static constexpr std::string_view CLASS_SCOPE_TAG = "~";
200     static constexpr std::string_view FUNCTION_TAG = "*";
201     static constexpr std::string_view METHOD_TAG = ">";
202     static constexpr std::string_view CTOR_TAG = "=";
203     static constexpr std::string_view NAMESPACE_TAG = "&";
204     static constexpr std::string_view ENUM_TAG = "%";
205     static constexpr std::string_view STATIC_METHOD_TAG = "<";
206     static constexpr std::string_view DUPLICATED_SEPERATOR = "^";
207     static constexpr std::string_view FUNC_NAME_SEPARATOR = "#";
208     static constexpr std::string_view INDEX_NAME_SPICIFIER = "@";
209     static constexpr std::string_view DOT = ".";
210     static constexpr std::string_view BACKSLASH = "\\";
211     static const uint64_t FNV_PRIME = 1099511628211U;
212     static const uint64_t FNV_OFFSET = 14695981039346656037U;
213     static const uint8_t SENDABLE_CLASS_MIN_SUPPORTED_API_VERSION = 11;
214     static const int32_t DEFAULT_TARGET_API_VERSION = 12;
215     static const int32_t ABC_TO_PROGRAM_MIN_SUPPORTED_API_VERSION = 12;
216     static constexpr std::array<uint8_t, panda_file::File::VERSION_SIZE>
217         ABC_TO_PROGRAM_MIN_SUPPORTED_BYTECODE_VERSION {12, 0, 2, 0};
218     static const int32_t SENDABLE_FUNCTION_MIN_SUPPORTED_API_VERSION = 12;
219     static const int32_t LAZY_IMPORT_MIN_SUPPORTED_API_VERSION = 12;
220     static const int32_t LAZY_IMPORT_DEFAULT_MIN_SUPPORTED_API_VERSION = 18;
221     static const int32_t SENDABLE_LAZY_LOADING_MIN_SUPPORTED_API_VERSION = 12;
222     static const int8_t SUPER_CALL_OPT_MIN_SUPPORTED_API_VERSION = 18;
223     static const int8_t SENDABLE_CLASS_USING_LOCAL_MODULE_VAR_MIN_SUPPORTED_API_VERSION = 18;
224     static const int8_t ENABLE_EXPECTED_PROPERTY_COUNT_MIN_SUPPORTED_API_VERSION = 18;
225     static constexpr std::string_view SUB_API_VERSION_1 = "beta1";
226     static constexpr std::string_view SUB_API_VERSION_2 = "beta2";
227     static constexpr std::string_view DEFAULT_SUB_API_VERSION = SUB_API_VERSION_1;
228 
229 private:
230     static bool SetFuncFlagsForDirectives(const ir::StringLiteral *strLit, ir::ScriptFunction *func,
231                                           const lexer::LineIndex &lineIndex, bool enableSendableClass,
232                                           bool enableSendableFunc);
233 };
234 
235 template <typename T>
IsInteger(double number)236 bool Helpers::IsInteger(double number)
237 {
238     if (std::fabs(number) <= static_cast<double>(std::numeric_limits<T>::max())) {
239         T intNum = static_cast<T>(number);
240 
241         if (static_cast<double>(intNum) == number) {
242             return true;
243         }
244     }
245 
246     return false;
247 }
248 
249 template <class T>
BaseName(T const & path,T const & delims)250 T Helpers::BaseName(T const &path, T const &delims)
251 {
252     return path.substr(path.find_last_of(delims) + 1);
253 }
254 
255 template <typename T, typename... Args>
FileStream(const std::string & str,Args &&...args)256 T Helpers::FileStream(const std::string &str, Args &&...args)
257 {
258     T fileStream;
259 #ifdef PANDA_TARGET_WINDOWS
260     std::wstring filename = Helpers::Utf8ToUtf16(str);
261 #else  //for linux and mac
262     std::string filename = str;
263 #endif
264     fileStream.open(filename.c_str(), args...);
265     return fileStream;
266 }
267 
268 }  // namespace panda::es2panda::util
269 
270 #endif
271