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 PANDA_ASSEMBLER_ASSEMBLY_PARSER_H_
17 #define PANDA_ASSEMBLER_ASSEMBLY_PARSER_H_
18
19 #include <iostream>
20 #include <memory>
21 #include <string>
22 #include <string_view>
23
24 #include "assembly-context.h"
25 #include "assembly-emitter.h"
26 #include "assembly-field.h"
27 #include "assembly-function.h"
28 #include "assembly-ins.h"
29 #include "assembly-label.h"
30 #include "assembly-program.h"
31 #include "assembly-record.h"
32 #include "assembly-type.h"
33 #include "define.h"
34 #include "error.h"
35 #include "ide_helpers.h"
36 #include "lexer.h"
37 #include "meta.h"
38 #include "utils/expected.h"
39
40 namespace panda::pandasm {
41
42 using Instructions = std::pair<std::vector<Ins>, Error>;
43
44 using Functions = std::pair<std::unordered_map<std::string, Function>, std::unordered_map<std::string, Record>>;
45
46 class Parser {
47 public:
48 Parser() = default;
49
50 NO_MOVE_SEMANTIC(Parser);
51 NO_COPY_SEMANTIC(Parser);
52
53 ~Parser() = default;
54
55 /*
56 * The main function of parsing, which takes a vector of token vectors and a name of the source file.
57 * Returns a program or an error value: Expected<Program, Error>
58 * This function analyzes code containing several functions:
59 * - Each function used must be declared.
60 * - The correct function declaration looks like this: .function ret_type fun_name([param_type aN,]) [<metadata>]
61 * ([data] shows that this 'data' is optional).
62 * - N in function parameters must increase when number of parameters increases
63 * (Possible: a0, a1,..., aN. Impossible: a1, a10, a13).
64 * - Each function has its own label table.
65 */
66 Expected<Program, Error> Parse(TokenSet &vectors_tokens, const std::string &file_name = "");
67
68 /*
69 * The main function of parsing, which takes a string with source and a name of the source file.
70 * Returns a program or an error value: Expected<Program, Error>
71 */
72 Expected<Program, Error> Parse(const std::string &source, const std::string &file_name = "");
73
74 /*
75 * Returns a set error
76 */
ShowError()77 Error ShowError() const
78 {
79 return err_;
80 }
81
ShowWarnings()82 ErrorList ShowWarnings() const
83 {
84 return war_;
85 }
86
87 private:
88 panda::pandasm::Program program_;
89 std::unordered_map<std::string, panda::pandasm::Label> *label_table_ = nullptr;
90 Metadata *metadata_ = nullptr;
91 Context context_; /* token iterator */
92 panda::pandasm::Record *curr_record_ = nullptr;
93 panda::pandasm::Function *curr_func_ = nullptr;
94 panda::pandasm::Ins *curr_ins_ = nullptr;
95 panda::pandasm::Field *curr_fld_ = nullptr;
96 size_t line_stric_ = 0;
97 panda::pandasm::Error err_;
98 panda::pandasm::ErrorList war_;
99 bool open_ = false; /* flag of being in a code section */
100 bool record_def_ = false;
101 bool func_def_ = false;
102
103 inline Error GetError(const std::string &mess = "", Error::ErrorType err = Error::ErrorType::ERR_NONE,
104 int8_t shift = 0, int token_shift = 0, const std::string &add_mess = "") const
105 {
106 return Error(mess, line_stric_, err, add_mess,
107 context_.tokens[static_cast<int>(context_.number) + token_shift - 1].bound_left + shift,
108 context_.tokens[static_cast<int>(context_.number) + token_shift - 1].bound_right,
109 context_.tokens[static_cast<int>(context_.number) + token_shift - 1].whole_line);
110 }
111
112 inline void GetWarning(const std::string &mess = "", Error::ErrorType err = Error::ErrorType::ERR_NONE,
113 int8_t shift = 0, const std::string &add_mess = "")
114 {
115 war_.emplace_back(mess, line_stric_, err, add_mess,
116 context_.tokens[context_.number - 1].bound_left + static_cast<size_t>(shift),
117 context_.tokens[context_.number - 1].bound_right,
118 context_.tokens[context_.number - 1].whole_line, Error::ErrorClass::WARNING);
119 }
120
GetCurrentPosition(bool left_bound)121 SourcePosition GetCurrentPosition(bool left_bound) const
122 {
123 if (left_bound) {
124 return SourcePosition {line_stric_, context_.tokens[context_.number - 1].bound_left};
125 }
126 return SourcePosition {line_stric_, context_.tokens[context_.number - 1].bound_right};
127 }
128
129 bool LabelValidName();
130 bool TypeValidName();
131 bool RegValidName();
132 bool ParamValidName();
133 bool FunctionValidName();
134 bool ParseFunctionName();
135 bool ParseLabel();
136 bool ParseOperation();
137 bool ParseOperands();
138 bool ParseFunctionCode();
139 bool ParseFunctionInstruction();
140 bool ParseFunctionFullSign();
141 bool ParseFunctionReturn();
142 bool ParseFunctionArg();
143 bool ParseFunctionArgComma(bool &comma);
144 bool ParseFunctionArgs();
145 bool ParseType(Type *type);
146 bool PrefixedValidName();
147 bool ParseMetaListComma(bool &comma, bool eq);
148 bool MeetExpMetaList(bool eq);
149 bool BuildMetaListAttr(bool &eq, std::string &attribute_name, std::string &attribute_value);
150 bool ParseMetaList(bool flag);
151 bool ParseMetaDef();
152 bool ParseRecordFullSign();
153 bool ParseRecordFields();
154 bool ParseRecordField();
155 bool ParseRecordName();
156 bool RecordValidName();
157 bool ParseFieldName();
158 bool ParseFieldType();
159 std::optional<std::string> ParseStringLiteral();
160 int64_t MnemonicToBuiltinId();
161
162 bool ParseOperandVreg();
163 bool ParseOperandComma();
164 bool ParseOperandInteger();
165 bool ParseOperandFloat(bool is_64bit);
166 bool ParseOperandId();
167 bool ParseOperandLabel();
168 bool ParseOperandField();
169 bool ParseOperandType(Type::VerificationType ver_type);
170 bool ParseOperandNone();
171 bool ParseOperandString();
172 bool ParseOperandCall();
173 bool ParseOperandBuiltinMnemonic();
174
175 void SetFunctionInformation();
176 void SetRecordInformation();
177 void SetOperationInformation();
178 void ParseAsCatchall(const std::vector<Token> &tokens);
179 void ParseAsLanguage(const std::vector<Token> &tokens, bool &is_lang_parsed, bool &is_first_statement);
180 void ParseAsRecord(const std::vector<Token> &tokens);
181 void ParseAsFunction(const std::vector<Token> &tokens);
182 void ParseAsBraceRight(const std::vector<Token> &tokens);
183 bool ParseAfterLine(bool &is_first_statement);
184 Expected<Program, Error> ParseAfterMainLoop(const std::string &file_name);
185 void ParseResetFunctionLabelsAndParams();
186 void ParseResetTables();
187 void ParseResetFunctionTable();
188 void ParseResetRecordTable();
189 void ParseAsLanguageDirective();
190 Function::CatchBlock PrepareCatchBlock(bool is_catchall, size_t size, size_t catchall_tokens_num,
191 size_t catch_tokens_num);
192 void ParseAsCatchDirective();
193 void SetError();
194 void SetMetadataContextError(const Metadata::Error &err, bool has_value);
195
196 Expected<char, Error> ParseOctalEscapeSequence(std::string_view s, size_t *i);
197 Expected<char, Error> ParseHexEscapeSequence(std::string_view s, size_t *i);
198 Expected<char, Error> ParseEscapeSequence(std::string_view s, size_t *i);
199
200 template <class T>
TryEmplaceInTable(bool flag,T & item)201 auto TryEmplaceInTable(bool flag, T &item)
202 {
203 return item.try_emplace(std::string(context_.GiveToken().data(), context_.GiveToken().length()),
204 std::string(context_.GiveToken().data(), context_.GiveToken().length()), program_.lang,
205 context_.tokens[context_.number - 1].bound_left,
206 context_.tokens[context_.number - 1].bound_right,
207 context_.tokens[context_.number - 1].whole_line, flag, line_stric_);
208 }
209
210 template <class T>
AddObjectInTable(bool flag,T & item)211 bool AddObjectInTable(bool flag, T &item)
212 {
213 auto [iter, is_inserted] = TryEmplaceInTable(flag, item);
214
215 if (is_inserted) {
216 return true;
217 }
218
219 if (iter->second.file_location->is_defined && flag) {
220 return false;
221 }
222
223 if (!iter->second.file_location->is_defined && flag) {
224 iter->second.file_location->is_defined = true;
225 return true;
226 }
227
228 if (!iter->second.file_location->is_defined) {
229 iter->second.file_location->bound_left = context_.tokens[context_.number - 1].bound_left;
230 iter->second.file_location->bound_right = context_.tokens[context_.number - 1].bound_right;
231 iter->second.file_location->whole_line = context_.tokens[context_.number - 1].whole_line;
232 iter->second.file_location->line_number = line_stric_;
233 }
234
235 return true;
236 }
237 };
238
239 template <>
TryEmplaceInTable(bool flag,std::unordered_map<std::string,panda::pandasm::Label> & item)240 inline auto Parser::TryEmplaceInTable(bool flag, std::unordered_map<std::string, panda::pandasm::Label> &item)
241 {
242 return item.try_emplace(std::string(context_.GiveToken().data(), context_.GiveToken().length()),
243 std::string(context_.GiveToken().data(), context_.GiveToken().length()),
244 context_.tokens[context_.number - 1].bound_left,
245 context_.tokens[context_.number - 1].bound_right,
246 context_.tokens[context_.number - 1].whole_line, flag, line_stric_);
247 }
248
249 } // namespace panda::pandasm
250
251 #endif // PANDA_ASSEMBLER_ASSEMBLY_PARSER_H_
252