1 /*
2  * Copyright (c) 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 #ifndef OHOS_IDL_PREPROCESSOR_H
17 #define OHOS_IDL_PREPROCESSOR_H
18 
19 #include <map>
20 #include <set>
21 #include <unordered_set>
22 #include <vector>
23 
24 #include "lexer/lexer.h"
25 #include "util/string_helper.h"
26 
27 namespace OHOS {
28 namespace Idl {
29 class FileDetail {
30 public:
GetFullName()31     inline std::string GetFullName() const
32     {
33         return StringHelper::Format("%s.%s", packageName_.c_str(), fileName_.c_str());
34     }
35 
36     std::string Dump() const;
37 
38 public:
39     std::string filePath_;
40     std::string fileName_;
41     std::string packageName_;
42     std::unordered_set<std::string> imports_;
43 };
44 
45 using FileDetailMap = std::map<std::string, FileDetail>;
46 
47 class Preprocessor {
48 public:
49     // analyze idl files and return sorted ids files
50     static bool Preprocess(std::vector<FileDetail> &fileDetails);
51 
52     static bool UnitPreprocess(FileDetailMap &fileDetails);
53 
54 private:
55     static bool CheckAllFilesPath(const std::set<std::string> &sourceFiles);
56 
57     static bool AnalyseImportInfo(std::set<std::string> sourceFiles, FileDetailMap &allFileDetails);
58 
59     static bool ParseFileDetail(const std::string &sourceFile, FileDetail &info);
60 
61     static bool ParsePackage(Lexer &lexer, FileDetail &info);
62 
63     static bool ParseImports(Lexer &lexer, FileDetail &info);
64 
65     static bool LoadOtherIdlFiles(
66         const FileDetail &ownerFileDetail, FileDetailMap &allFileDetails, std::set<std::string> &sourceFiles);
67 
68     static bool CheckCircularReference(const FileDetailMap &allFileDetails,
69         std::vector<FileDetail> &compileSourceFiles);
70 
71     static void PrintCyclefInfo(FileDetailMap &allFileDetails);
72 
73     static void FindCycle(const std::string &curNode, FileDetailMap &allFiles, std::vector<std::string> &trace);
74 
75     // check if the file path matches the package name
76     static bool CheckPackageName(const std::string &filePath, const std::string &packageName);
77 };
78 } // namespace Idl
79 } // namespace OHOS
80 
81 #endif // OHOS_IDL_PREPROCESSOR_H