1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  *
4  * HDF is dual licensed: you can use it either under the terms of
5  * the GPL, or the BSD license, at your option.
6  * See the LICENSE file in the root of this repository for complete details.
7  */
8 
9 #ifndef OHOS_HDI_LEXER_H
10 #define OHOS_HDI_LEXER_H
11 
12 #include <cstdlib>
13 #include <cctype>
14 #include <memory>
15 #include <unordered_map>
16 
17 #include "lexer/token.h"
18 #include "util/file.h"
19 
20 namespace OHOS {
21 namespace HDI {
22 class Lexer {
23 public:
24     enum class ParseMode {
25         DECL_MODE,
26         EXPR_MODE,
27     };
28 
29     Lexer();
30 
31     ~Lexer() = default;
32 
33     bool Reset(const std::string &filePath);
34 
GetFilePath()35     inline std::string GetFilePath() const
36     {
37         return (file_ != nullptr) ? file_->GetPath() : "";
38     }
39 
40     Token PeekToken(bool skipComment = true);
41 
42     Token GetToken(bool skipComment = true);
43 
44     void SkipCurrentLine();
45 
46     bool SkipCurrentLine(char untilChar);
47 
48     void Skip(char untilChar);
49 
50     void SkipToken(TokenType tokenType);
51 
52     void SkipUntilToken(TokenType tokenType);
53 
54     void SkipEof();
55 
SetParseMode(ParseMode mode)56     inline void SetParseMode(ParseMode mode)
57     {
58         mode_ = mode;
59     }
60 
61 private:
62     void ReadToken(Token &token, bool skipComment = true);
63 
64     void InitCurToken(Token &token);
65 
66     void ReadId(Token &token);
67 
68     void ReadNum(Token &token);
69 
70     void ReadBinaryNum(Token &token);
71 
72     void ReadOctNum(Token &token);
73 
74     void ReadHexNum(Token &token);
75 
76     void ReadDecNum(Token &token);
77 
78     void ReadNumSuffix(Token &token);
79 
80     void ReadShiftLeftOp(Token &token);
81 
82     void ReadShiftRightOp(Token &token);
83 
84     void ReadPPlusOp(Token &token);
85 
86     void ReadMMinusOp(Token &token);
87 
88     void ReadComment(Token &token);
89 
90     void ReadLineComment(Token &token);
91 
92     void ReadBlockComment(Token &token);
93 
94     void ReadSymbolToken(Token &token);
95 
96 private:
97     std::string filePath_;
98     std::unique_ptr<File> file_;
99 
100     ParseMode mode_;
101     bool havePeek_;
102     Token curToken_;
103 
104 private:
105     using StrTokenTypeMap = std::unordered_map<std::string, TokenType>;
106     static StrTokenTypeMap keyWords_;
107     static StrTokenTypeMap symbols_;
108 };
109 } // namespace HDI
110 } // namespace OHOS
111 
112 #endif // OHOS_HDI_LEXER_H