1 // Copyright 2018 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/torque/torque-parser.h"
6
7 #include <algorithm>
8 #include <cctype>
9 #include <set>
10 #include <stdexcept>
11 #include <unordered_map>
12
13 #include "src/flags/flags.h"
14 #include "src/torque/ast.h"
15 #include "src/torque/constants.h"
16 #include "src/torque/declarations.h"
17 #include "src/torque/earley-parser.h"
18 #include "src/torque/utils.h"
19
20 namespace v8 {
21 namespace internal {
22 namespace torque {
23
24 DEFINE_CONTEXTUAL_VARIABLE(CurrentAst)
25
26 using TypeList = std::vector<TypeExpression*>;
27
28 struct ExpressionWithSource {
29 Expression* expression;
30 std::string source;
31 };
32
33 struct TypeswitchCase {
34 SourcePosition pos;
35 base::Optional<std::string> name;
36 TypeExpression* type;
37 Statement* block;
38 };
39
40 struct EnumEntry {
41 Identifier* name;
42 base::Optional<TypeExpression*> type;
43 };
44
45 class BuildFlags : public ContextualClass<BuildFlags> {
46 public:
BuildFlags()47 BuildFlags() {
48 build_flags_["V8_SFI_HAS_UNIQUE_ID"] = V8_SFI_HAS_UNIQUE_ID;
49 build_flags_["TAGGED_SIZE_8_BYTES"] = TAGGED_SIZE_8_BYTES;
50 build_flags_["V8_DOUBLE_FIELDS_UNBOXING"] = V8_DOUBLE_FIELDS_UNBOXING;
51 build_flags_["TRUE_FOR_TESTING"] = true;
52 build_flags_["FALSE_FOR_TESTING"] = false;
53 }
GetFlag(const std::string & name,const char * production)54 static bool GetFlag(const std::string& name, const char* production) {
55 auto it = Get().build_flags_.find(name);
56 if (it == Get().build_flags_.end()) {
57 ReportError("Unknown flag used in ", production, ": ", name,
58 ". Please add it to the list in BuildFlags.");
59 }
60 return it->second;
61 }
62
63 private:
64 std::unordered_map<std::string, bool> build_flags_;
65 };
66 DEFINE_CONTEXTUAL_VARIABLE(BuildFlags)
67
68 template <>
69 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<std::string>::id =
70 ParseResultTypeId::kStdString;
71 template <>
72 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<bool>::id =
73 ParseResultTypeId::kBool;
74 template <>
75 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<int32_t>::id =
76 ParseResultTypeId::kInt32;
77 template <>
78 V8_EXPORT_PRIVATE const ParseResultTypeId
79 ParseResultHolder<std::vector<std::string>>::id =
80 ParseResultTypeId::kStdVectorOfString;
81 template <>
82 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Declaration*>::id =
83 ParseResultTypeId::kDeclarationPtr;
84 template <>
85 V8_EXPORT_PRIVATE const ParseResultTypeId
86 ParseResultHolder<TypeExpression*>::id =
87 ParseResultTypeId::kTypeExpressionPtr;
88 template <>
89 V8_EXPORT_PRIVATE const ParseResultTypeId
90 ParseResultHolder<base::Optional<TypeExpression*>>::id =
91 ParseResultTypeId::kOptionalTypeExpressionPtr;
92 template <>
93 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<TryHandler*>::id =
94 ParseResultTypeId::kTryHandlerPtr;
95 template <>
96 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Expression*>::id =
97 ParseResultTypeId::kExpressionPtr;
98 template <>
99 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Identifier*>::id =
100 ParseResultTypeId::kIdentifierPtr;
101 template <>
102 V8_EXPORT_PRIVATE const ParseResultTypeId
103 ParseResultHolder<base::Optional<Identifier*>>::id =
104 ParseResultTypeId::kOptionalIdentifierPtr;
105 template <>
106 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Statement*>::id =
107 ParseResultTypeId::kStatementPtr;
108 template <>
109 V8_EXPORT_PRIVATE const ParseResultTypeId
110 ParseResultHolder<NameAndTypeExpression>::id =
111 ParseResultTypeId::kNameAndTypeExpression;
112 template <>
113 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<EnumEntry>::id =
114 ParseResultTypeId::kEnumEntry;
115 template <>
116 V8_EXPORT_PRIVATE const ParseResultTypeId
117 ParseResultHolder<std::vector<EnumEntry>>::id =
118 ParseResultTypeId::kStdVectorOfEnumEntry;
119 template <>
120 V8_EXPORT_PRIVATE const ParseResultTypeId
121 ParseResultHolder<NameAndExpression>::id =
122 ParseResultTypeId::kNameAndExpression;
123 template <>
124 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Annotation>::id =
125 ParseResultTypeId::kAnnotation;
126 template <>
127 V8_EXPORT_PRIVATE const ParseResultTypeId
128 ParseResultHolder<std::vector<Annotation>>::id =
129 ParseResultTypeId::kVectorOfAnnotation;
130 template <>
131 V8_EXPORT_PRIVATE const ParseResultTypeId
132 ParseResultHolder<AnnotationParameter>::id =
133 ParseResultTypeId::kAnnotationParameter;
134 template <>
135 V8_EXPORT_PRIVATE const ParseResultTypeId
136 ParseResultHolder<base::Optional<AnnotationParameter>>::id =
137 ParseResultTypeId::kOptionalAnnotationParameter;
138 template <>
139 V8_EXPORT_PRIVATE const ParseResultTypeId
140 ParseResultHolder<ClassFieldExpression>::id =
141 ParseResultTypeId::kClassFieldExpression;
142 template <>
143 V8_EXPORT_PRIVATE const ParseResultTypeId
144 ParseResultHolder<StructFieldExpression>::id =
145 ParseResultTypeId::kStructFieldExpression;
146 template <>
147 V8_EXPORT_PRIVATE const ParseResultTypeId
148 ParseResultHolder<BitFieldDeclaration>::id =
149 ParseResultTypeId::kBitFieldDeclaration;
150 template <>
151 V8_EXPORT_PRIVATE const ParseResultTypeId
152 ParseResultHolder<std::vector<NameAndTypeExpression>>::id =
153 ParseResultTypeId::kStdVectorOfNameAndTypeExpression;
154 template <>
155 V8_EXPORT_PRIVATE const ParseResultTypeId
156 ParseResultHolder<ImplicitParameters>::id =
157 ParseResultTypeId::kImplicitParameters;
158 template <>
159 V8_EXPORT_PRIVATE const ParseResultTypeId
160 ParseResultHolder<base::Optional<ImplicitParameters>>::id =
161 ParseResultTypeId::kOptionalImplicitParameters;
162 template <>
163 V8_EXPORT_PRIVATE const ParseResultTypeId
164 ParseResultHolder<std::vector<NameAndExpression>>::id =
165 ParseResultTypeId::kStdVectorOfNameAndExpression;
166 template <>
167 V8_EXPORT_PRIVATE const ParseResultTypeId
168 ParseResultHolder<std::vector<ClassFieldExpression>>::id =
169 ParseResultTypeId::kStdVectorOfClassFieldExpression;
170 template <>
171 V8_EXPORT_PRIVATE const ParseResultTypeId
172 ParseResultHolder<std::vector<StructFieldExpression>>::id =
173 ParseResultTypeId::kStdVectorOfStructFieldExpression;
174 template <>
175 V8_EXPORT_PRIVATE const ParseResultTypeId
176 ParseResultHolder<std::vector<BitFieldDeclaration>>::id =
177 ParseResultTypeId::kStdVectorOfBitFieldDeclaration;
178 template <>
179 V8_EXPORT_PRIVATE const ParseResultTypeId
180 ParseResultHolder<IncrementDecrementOperator>::id =
181 ParseResultTypeId::kIncrementDecrementOperator;
182 template <>
183 V8_EXPORT_PRIVATE const ParseResultTypeId
184 ParseResultHolder<base::Optional<std::string>>::id =
185 ParseResultTypeId::kOptionalStdString;
186 template <>
187 V8_EXPORT_PRIVATE const ParseResultTypeId
188 ParseResultHolder<std::vector<Statement*>>::id =
189 ParseResultTypeId::kStdVectorOfStatementPtr;
190 template <>
191 V8_EXPORT_PRIVATE const ParseResultTypeId
192 ParseResultHolder<std::vector<Declaration*>>::id =
193 ParseResultTypeId::kStdVectorOfDeclarationPtr;
194 template <>
195 V8_EXPORT_PRIVATE const ParseResultTypeId
196 ParseResultHolder<std::vector<std::vector<Declaration*>>>::id =
197 ParseResultTypeId::kStdVectorOfStdVectorOfDeclarationPtr;
198 template <>
199 V8_EXPORT_PRIVATE const ParseResultTypeId
200 ParseResultHolder<std::vector<Expression*>>::id =
201 ParseResultTypeId::kStdVectorOfExpressionPtr;
202 template <>
203 V8_EXPORT_PRIVATE const ParseResultTypeId
204 ParseResultHolder<ExpressionWithSource>::id =
205 ParseResultTypeId::kExpressionWithSource;
206 template <>
207 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<ParameterList>::id =
208 ParseResultTypeId::kParameterList;
209 template <>
210 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<TypeList>::id =
211 ParseResultTypeId::kTypeList;
212 template <>
213 V8_EXPORT_PRIVATE const ParseResultTypeId
214 ParseResultHolder<base::Optional<TypeList>>::id =
215 ParseResultTypeId::kOptionalTypeList;
216 template <>
217 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<LabelAndTypes>::id =
218 ParseResultTypeId::kLabelAndTypes;
219 template <>
220 V8_EXPORT_PRIVATE const ParseResultTypeId
221 ParseResultHolder<std::vector<LabelAndTypes>>::id =
222 ParseResultTypeId::kStdVectorOfLabelAndTypes;
223 template <>
224 V8_EXPORT_PRIVATE const ParseResultTypeId
225 ParseResultHolder<std::vector<TryHandler*>>::id =
226 ParseResultTypeId::kStdVectorOfTryHandlerPtr;
227 template <>
228 V8_EXPORT_PRIVATE const ParseResultTypeId
229 ParseResultHolder<base::Optional<Statement*>>::id =
230 ParseResultTypeId::kOptionalStatementPtr;
231 template <>
232 V8_EXPORT_PRIVATE const ParseResultTypeId
233 ParseResultHolder<base::Optional<Expression*>>::id =
234 ParseResultTypeId::kOptionalExpressionPtr;
235 template <>
236 V8_EXPORT_PRIVATE const ParseResultTypeId
237 ParseResultHolder<TypeswitchCase>::id = ParseResultTypeId::kTypeswitchCase;
238 template <>
239 V8_EXPORT_PRIVATE const ParseResultTypeId
240 ParseResultHolder<std::vector<TypeswitchCase>>::id =
241 ParseResultTypeId::kStdVectorOfTypeswitchCase;
242 template <>
243 V8_EXPORT_PRIVATE const ParseResultTypeId
244 ParseResultHolder<std::vector<Identifier*>>::id =
245 ParseResultTypeId::kStdVectorOfIdentifierPtr;
246 template <>
247 V8_EXPORT_PRIVATE const ParseResultTypeId
248 ParseResultHolder<base::Optional<ClassBody*>>::id =
249 ParseResultTypeId::kOptionalClassBody;
250 template <>
251 V8_EXPORT_PRIVATE const ParseResultTypeId
252 ParseResultHolder<GenericParameter>::id =
253 ParseResultTypeId::kGenericParameter;
254 template <>
255 V8_EXPORT_PRIVATE const ParseResultTypeId
256 ParseResultHolder<GenericParameters>::id =
257 ParseResultTypeId::kGenericParameters;
258
259 namespace {
260
AddGlobalDeclarations(ParseResultIterator * child_results)261 base::Optional<ParseResult> AddGlobalDeclarations(
262 ParseResultIterator* child_results) {
263 auto declarations = child_results->NextAs<std::vector<Declaration*>>();
264 for (Declaration* declaration : declarations) {
265 CurrentAst::Get().declarations().push_back(declaration);
266 }
267 return base::nullopt;
268 }
269
NamingConventionError(const std::string & type,const std::string & name,const std::string & convention,SourcePosition pos=CurrentSourcePosition::Get ())270 void NamingConventionError(const std::string& type, const std::string& name,
271 const std::string& convention,
272 SourcePosition pos = CurrentSourcePosition::Get()) {
273 Lint(type, " \"", name, "\" does not follow \"", convention,
274 "\" naming convention.")
275 .Position(pos);
276 }
277
NamingConventionError(const std::string & type,const Identifier * name,const std::string & convention)278 void NamingConventionError(const std::string& type, const Identifier* name,
279 const std::string& convention) {
280 NamingConventionError(type, name->value, convention, name->pos);
281 }
282
LintGenericParameters(const GenericParameters & parameters)283 void LintGenericParameters(const GenericParameters& parameters) {
284 for (auto parameter : parameters) {
285 if (!IsUpperCamelCase(parameter.name->value)) {
286 NamingConventionError("Generic parameter", parameter.name,
287 "UpperCamelCase");
288 }
289 }
290 }
291
ConcatList(ParseResultIterator * child_results)292 base::Optional<ParseResult> ConcatList(ParseResultIterator* child_results) {
293 auto list_of_lists =
294 child_results->NextAs<std::vector<std::vector<Declaration*>>>();
295 std::vector<Declaration*> result;
296 for (auto& list : list_of_lists) {
297 result.insert(result.end(), list.begin(), list.end());
298 }
299 return ParseResult{result};
300 }
301
CheckNotDeferredStatement(Statement * statement)302 void CheckNotDeferredStatement(Statement* statement) {
303 CurrentSourcePosition::Scope source_position(statement->pos);
304 if (BlockStatement* block = BlockStatement::DynamicCast(statement)) {
305 if (block->deferred) {
306 Lint(
307 "cannot use deferred with a statement block here, it will have no "
308 "effect");
309 }
310 }
311 }
312
AddConstexpr(TypeExpression * type)313 TypeExpression* AddConstexpr(TypeExpression* type) {
314 BasicTypeExpression* basic = BasicTypeExpression::DynamicCast(type);
315 if (!basic) Error("Unsupported extends clause.").Throw();
316 return MakeNode<BasicTypeExpression>(basic->namespace_qualification,
317 CONSTEXPR_TYPE_PREFIX + basic->name,
318 basic->generic_arguments);
319 }
320
MakeCall(IdentifierExpression * callee,base::Optional<Expression * > target,std::vector<Expression * > arguments,const std::vector<Statement * > & otherwise)321 Expression* MakeCall(IdentifierExpression* callee,
322 base::Optional<Expression*> target,
323 std::vector<Expression*> arguments,
324 const std::vector<Statement*>& otherwise) {
325 std::vector<Identifier*> labels;
326
327 // All IdentifierExpressions are treated as label names and can be directly
328 // used as labels identifiers. All other statements in a call's otherwise
329 // must create intermediate Labels for the otherwise's statement code.
330 size_t label_id = 0;
331 std::vector<TryHandler*> temp_labels;
332 for (auto* statement : otherwise) {
333 if (auto* e = ExpressionStatement::DynamicCast(statement)) {
334 if (auto* id = IdentifierExpression::DynamicCast(e->expression)) {
335 if (id->generic_arguments.size() != 0) {
336 ReportError("An otherwise label cannot have generic parameters");
337 }
338 labels.push_back(id->name);
339 continue;
340 }
341 }
342 auto label_name = std::string("__label") + std::to_string(label_id++);
343 auto label_id = MakeNode<Identifier>(label_name);
344 label_id->pos = SourcePosition::Invalid();
345 labels.push_back(label_id);
346 auto* handler =
347 MakeNode<TryHandler>(TryHandler::HandlerKind::kLabel, label_id,
348 ParameterList::Empty(), statement);
349 temp_labels.push_back(handler);
350 }
351
352 // Create nested try-label expression for all of the temporary Labels that
353 // were created.
354 Expression* result = nullptr;
355 if (target) {
356 result = MakeNode<CallMethodExpression>(*target, callee, arguments, labels);
357 } else {
358 result = MakeNode<CallExpression>(callee, arguments, labels);
359 }
360
361 for (auto* label : temp_labels) {
362 result = MakeNode<TryLabelExpression>(result, label);
363 }
364 return result;
365 }
366
MakeCall(Identifier * callee,const std::vector<TypeExpression * > & generic_arguments,const std::vector<Expression * > & arguments,const std::vector<Statement * > & otherwise)367 Expression* MakeCall(Identifier* callee,
368 const std::vector<TypeExpression*>& generic_arguments,
369 const std::vector<Expression*>& arguments,
370 const std::vector<Statement*>& otherwise) {
371 return MakeCall(MakeNode<IdentifierExpression>(callee, generic_arguments),
372 base::nullopt, arguments, otherwise);
373 }
374
MakeCall(ParseResultIterator * child_results)375 base::Optional<ParseResult> MakeCall(ParseResultIterator* child_results) {
376 auto callee = child_results->NextAs<Expression*>();
377 auto args = child_results->NextAs<std::vector<Expression*>>();
378 auto otherwise = child_results->NextAs<std::vector<Statement*>>();
379 IdentifierExpression* target = IdentifierExpression::cast(callee);
380 return ParseResult{MakeCall(target, base::nullopt, args, otherwise)};
381 }
382
MakeMethodCall(ParseResultIterator * child_results)383 base::Optional<ParseResult> MakeMethodCall(ParseResultIterator* child_results) {
384 auto this_arg = child_results->NextAs<Expression*>();
385 auto callee = child_results->NextAs<std::string>();
386 auto args = child_results->NextAs<std::vector<Expression*>>();
387 auto otherwise = child_results->NextAs<std::vector<Statement*>>();
388 return ParseResult{
389 MakeCall(MakeNode<IdentifierExpression>(MakeNode<Identifier>(callee)),
390 this_arg, args, otherwise)};
391 }
392
MakeNewExpression(ParseResultIterator * child_results)393 base::Optional<ParseResult> MakeNewExpression(
394 ParseResultIterator* child_results) {
395 bool pretenured = child_results->NextAs<bool>();
396
397 auto type = child_results->NextAs<TypeExpression*>();
398 auto initializers = child_results->NextAs<std::vector<NameAndExpression>>();
399
400 Expression* result =
401 MakeNode<NewExpression>(type, std::move(initializers), pretenured);
402 return ParseResult{result};
403 }
404
MakeBinaryOperator(ParseResultIterator * child_results)405 base::Optional<ParseResult> MakeBinaryOperator(
406 ParseResultIterator* child_results) {
407 auto left = child_results->NextAs<Expression*>();
408 auto op = child_results->NextAs<Identifier*>();
409 auto right = child_results->NextAs<Expression*>();
410 return ParseResult{MakeCall(op, TypeList{},
411 std::vector<Expression*>{left, right},
412 std::vector<Statement*>{})};
413 }
414
MakeIntrinsicCallExpression(ParseResultIterator * child_results)415 base::Optional<ParseResult> MakeIntrinsicCallExpression(
416 ParseResultIterator* child_results) {
417 auto callee = child_results->NextAs<Identifier*>();
418 auto generic_arguments =
419 child_results->NextAs<std::vector<TypeExpression*>>();
420 auto args = child_results->NextAs<std::vector<Expression*>>();
421 Expression* result =
422 MakeNode<IntrinsicCallExpression>(callee, generic_arguments, args);
423 return ParseResult{result};
424 }
425
MakeUnaryOperator(ParseResultIterator * child_results)426 base::Optional<ParseResult> MakeUnaryOperator(
427 ParseResultIterator* child_results) {
428 auto op = child_results->NextAs<Identifier*>();
429 auto e = child_results->NextAs<Expression*>();
430 return ParseResult{MakeCall(op, TypeList{}, std::vector<Expression*>{e},
431 std::vector<Statement*>{})};
432 }
433
MakeSpreadExpression(ParseResultIterator * child_results)434 base::Optional<ParseResult> MakeSpreadExpression(
435 ParseResultIterator* child_results) {
436 auto spreadee = child_results->NextAs<Expression*>();
437 Expression* result = MakeNode<SpreadExpression>(spreadee);
438 return ParseResult{result};
439 }
440
MakeImplicitParameterList(ParseResultIterator * child_results)441 base::Optional<ParseResult> MakeImplicitParameterList(
442 ParseResultIterator* child_results) {
443 auto kind = child_results->NextAs<Identifier*>();
444 auto parameters = child_results->NextAs<std::vector<NameAndTypeExpression>>();
445 return ParseResult{ImplicitParameters{kind, parameters}};
446 }
447
AddParameter(ParameterList * parameter_list,const NameAndTypeExpression & param)448 void AddParameter(ParameterList* parameter_list,
449 const NameAndTypeExpression& param) {
450 if (!IsLowerCamelCase(param.name->value)) {
451 NamingConventionError("Parameter", param.name, "lowerCamelCase");
452 }
453 parameter_list->names.push_back(param.name);
454 parameter_list->types.push_back(param.type);
455 }
456
457 template <bool has_varargs, bool has_explicit_parameter_names>
MakeParameterList(ParseResultIterator * child_results)458 base::Optional<ParseResult> MakeParameterList(
459 ParseResultIterator* child_results) {
460 auto implicit_params =
461 child_results->NextAs<base::Optional<ImplicitParameters>>();
462 ParameterList result;
463 result.has_varargs = has_varargs;
464 result.implicit_count = 0;
465 result.implicit_kind = ImplicitKind::kNoImplicit;
466 if (implicit_params) {
467 result.implicit_count = implicit_params->parameters.size();
468 if (implicit_params->kind->value == "implicit") {
469 result.implicit_kind = ImplicitKind::kImplicit;
470 } else {
471 DCHECK_EQ(implicit_params->kind->value, "js-implicit");
472 result.implicit_kind = ImplicitKind::kJSImplicit;
473 }
474 result.implicit_kind_pos = implicit_params->kind->pos;
475 for (NameAndTypeExpression& implicit_param : implicit_params->parameters) {
476 AddParameter(&result, implicit_param);
477 }
478 }
479 if (has_explicit_parameter_names) {
480 auto explicit_params =
481 child_results->NextAs<std::vector<NameAndTypeExpression>>();
482 std::string arguments_variable = "";
483 if (has_varargs) {
484 arguments_variable = child_results->NextAs<std::string>();
485 }
486 for (NameAndTypeExpression& param : explicit_params) {
487 AddParameter(&result, param);
488 }
489 result.arguments_variable = arguments_variable;
490 } else {
491 auto explicit_types = child_results->NextAs<TypeList>();
492 for (auto* explicit_type : explicit_types) {
493 result.types.push_back(explicit_type);
494 }
495 }
496 return ParseResult{std::move(result)};
497 }
498
MakeAssertStatement(ParseResultIterator * child_results)499 base::Optional<ParseResult> MakeAssertStatement(
500 ParseResultIterator* child_results) {
501 auto kind_string = child_results->NextAs<Identifier*>()->value;
502 auto expr_with_source = child_results->NextAs<ExpressionWithSource>();
503 AssertStatement::AssertKind kind;
504 if (kind_string == "assert") {
505 kind = AssertStatement::AssertKind::kAssert;
506 } else if (kind_string == "check") {
507 kind = AssertStatement::AssertKind::kCheck;
508 } else if (kind_string == "static_assert") {
509 kind = AssertStatement::AssertKind::kStaticAssert;
510 } else {
511 UNREACHABLE();
512 }
513 Statement* result = MakeNode<AssertStatement>(
514 kind, expr_with_source.expression, expr_with_source.source);
515 return ParseResult{result};
516 }
517
MakeDebugStatement(ParseResultIterator * child_results)518 base::Optional<ParseResult> MakeDebugStatement(
519 ParseResultIterator* child_results) {
520 auto kind = child_results->NextAs<Identifier*>()->value;
521 DCHECK(kind == "unreachable" || kind == "debug");
522 Statement* result = MakeNode<DebugStatement>(kind, kind == "unreachable");
523 return ParseResult{result};
524 }
525
MakeVoidType(ParseResultIterator * child_results)526 base::Optional<ParseResult> MakeVoidType(ParseResultIterator* child_results) {
527 TypeExpression* result = MakeNode<BasicTypeExpression>(
528 std::vector<std::string>{}, "void", std::vector<TypeExpression*>{});
529 return ParseResult{result};
530 }
531
MakeExternalMacro(ParseResultIterator * child_results)532 base::Optional<ParseResult> MakeExternalMacro(
533 ParseResultIterator* child_results) {
534 auto transitioning = child_results->NextAs<bool>();
535 auto operator_name = child_results->NextAs<base::Optional<std::string>>();
536 auto external_assembler_name =
537 child_results->NextAs<base::Optional<std::string>>();
538 auto name = child_results->NextAs<Identifier*>();
539 auto generic_parameters = child_results->NextAs<GenericParameters>();
540 LintGenericParameters(generic_parameters);
541
542 auto args = child_results->NextAs<ParameterList>();
543 auto return_type = child_results->NextAs<TypeExpression*>();
544 auto labels = child_results->NextAs<LabelAndTypesVector>();
545
546 Declaration* result = MakeNode<ExternalMacroDeclaration>(
547 transitioning,
548 external_assembler_name ? *external_assembler_name : "CodeStubAssembler",
549 name, operator_name, args, return_type, labels);
550 if (!generic_parameters.empty()) {
551 Error("External builtins cannot be generic.");
552 }
553 return ParseResult{result};
554 }
555
MakeIntrinsicDeclaration(ParseResultIterator * child_results)556 base::Optional<ParseResult> MakeIntrinsicDeclaration(
557 ParseResultIterator* child_results) {
558 auto name = child_results->NextAs<Identifier*>();
559 auto generic_parameters = child_results->NextAs<GenericParameters>();
560 LintGenericParameters(generic_parameters);
561
562 auto args = child_results->NextAs<ParameterList>();
563 auto return_type = child_results->NextAs<TypeExpression*>();
564 auto body = child_results->NextAs<base::Optional<Statement*>>();
565 LabelAndTypesVector labels;
566 CallableDeclaration* declaration;
567 if (body) {
568 declaration = MakeNode<TorqueMacroDeclaration>(
569 false, name, base::Optional<std::string>{}, args, return_type, labels,
570 false, body);
571 } else {
572 declaration = MakeNode<IntrinsicDeclaration>(name, args, return_type);
573 }
574 Declaration* result = declaration;
575 if (!generic_parameters.empty()) {
576 result =
577 MakeNode<GenericCallableDeclaration>(generic_parameters, declaration);
578 }
579 return ParseResult{result};
580 }
581
582 namespace {
HasAnnotation(ParseResultIterator * child_results,const char * annotation,const char * declaration)583 bool HasAnnotation(ParseResultIterator* child_results, const char* annotation,
584 const char* declaration) {
585 auto annotations = child_results->NextAs<std::vector<Annotation>>();
586 if (annotations.size()) {
587 if (annotations.size() > 1 || annotations[0].name->value != annotation) {
588 Error(declaration, " declarations only support a single ", annotation,
589 " annotation");
590 }
591 return true;
592 }
593 return false;
594 }
595
HasExportAnnotation(ParseResultIterator * child_results,const char * declaration)596 bool HasExportAnnotation(ParseResultIterator* child_results,
597 const char* declaration) {
598 return HasAnnotation(child_results, ANNOTATION_EXPORT, declaration);
599 }
600 } // namespace
601
MakeTorqueMacroDeclaration(ParseResultIterator * child_results)602 base::Optional<ParseResult> MakeTorqueMacroDeclaration(
603 ParseResultIterator* child_results) {
604 bool export_to_csa = HasExportAnnotation(child_results, "macro");
605 auto transitioning = child_results->NextAs<bool>();
606 auto operator_name = child_results->NextAs<base::Optional<std::string>>();
607 auto name = child_results->NextAs<Identifier*>();
608 if (!IsUpperCamelCase(name->value)) {
609 NamingConventionError("Macro", name, "UpperCamelCase");
610 }
611
612 auto generic_parameters = child_results->NextAs<GenericParameters>();
613 LintGenericParameters(generic_parameters);
614
615 auto args = child_results->NextAs<ParameterList>();
616 auto return_type = child_results->NextAs<TypeExpression*>();
617 auto labels = child_results->NextAs<LabelAndTypesVector>();
618 auto body = child_results->NextAs<base::Optional<Statement*>>();
619 CallableDeclaration* declaration = MakeNode<TorqueMacroDeclaration>(
620 transitioning, name, operator_name, args, return_type, labels,
621 export_to_csa, body);
622 Declaration* result = declaration;
623 if (generic_parameters.empty()) {
624 if (!body) ReportError("A non-generic declaration needs a body.");
625 } else {
626 if (export_to_csa) ReportError("Cannot export generics to CSA.");
627 result =
628 MakeNode<GenericCallableDeclaration>(generic_parameters, declaration);
629 }
630 return ParseResult{result};
631 }
632
MakeTorqueBuiltinDeclaration(ParseResultIterator * child_results)633 base::Optional<ParseResult> MakeTorqueBuiltinDeclaration(
634 ParseResultIterator* child_results) {
635 auto transitioning = child_results->NextAs<bool>();
636 auto javascript_linkage = child_results->NextAs<bool>();
637 auto name = child_results->NextAs<Identifier*>();
638 if (!IsUpperCamelCase(name->value)) {
639 NamingConventionError("Builtin", name, "UpperCamelCase");
640 }
641
642 auto generic_parameters = child_results->NextAs<GenericParameters>();
643 LintGenericParameters(generic_parameters);
644
645 auto args = child_results->NextAs<ParameterList>();
646 auto return_type = child_results->NextAs<TypeExpression*>();
647 auto body = child_results->NextAs<base::Optional<Statement*>>();
648 CallableDeclaration* declaration = MakeNode<TorqueBuiltinDeclaration>(
649 transitioning, javascript_linkage, name, args, return_type, body);
650 Declaration* result = declaration;
651 if (generic_parameters.empty()) {
652 if (!body) ReportError("A non-generic declaration needs a body.");
653 } else {
654 result =
655 MakeNode<GenericCallableDeclaration>(generic_parameters, declaration);
656 }
657 return ParseResult{result};
658 }
659
MakeConstDeclaration(ParseResultIterator * child_results)660 base::Optional<ParseResult> MakeConstDeclaration(
661 ParseResultIterator* child_results) {
662 auto name = child_results->NextAs<Identifier*>();
663 if (!IsValidNamespaceConstName(name->value)) {
664 NamingConventionError("Constant", name, "kUpperCamelCase");
665 }
666
667 auto type = child_results->NextAs<TypeExpression*>();
668 auto expression = child_results->NextAs<Expression*>();
669 Declaration* result = MakeNode<ConstDeclaration>(name, type, expression);
670 return ParseResult{result};
671 }
672
MakeExternConstDeclaration(ParseResultIterator * child_results)673 base::Optional<ParseResult> MakeExternConstDeclaration(
674 ParseResultIterator* child_results) {
675 auto name = child_results->NextAs<Identifier*>();
676 auto type = child_results->NextAs<TypeExpression*>();
677 auto literal = child_results->NextAs<std::string>();
678 Declaration* result =
679 MakeNode<ExternConstDeclaration>(name, type, std::move(literal));
680 return ParseResult{result};
681 }
682
MakeTypeAliasDeclaration(ParseResultIterator * child_results)683 base::Optional<ParseResult> MakeTypeAliasDeclaration(
684 ParseResultIterator* child_results) {
685 auto name = child_results->NextAs<Identifier*>();
686 auto type = child_results->NextAs<TypeExpression*>();
687 Declaration* result = MakeNode<TypeAliasDeclaration>(name, type);
688 return ParseResult{result};
689 }
690
MakeAbstractTypeDeclaration(ParseResultIterator * child_results)691 base::Optional<ParseResult> MakeAbstractTypeDeclaration(
692 ParseResultIterator* child_results) {
693 bool use_parent_type_checker = HasAnnotation(
694 child_results, ANNOTATION_USE_PARENT_TYPE_CHECKER, "abstract type");
695 auto transient = child_results->NextAs<bool>();
696 auto name = child_results->NextAs<Identifier*>();
697 if (!IsValidTypeName(name->value)) {
698 NamingConventionError("Type", name, "UpperCamelCase");
699 }
700 auto generic_parameters = child_results->NextAs<GenericParameters>();
701 auto extends = child_results->NextAs<base::Optional<TypeExpression*>>();
702 auto generates = child_results->NextAs<base::Optional<std::string>>();
703 AbstractTypeFlags flags(AbstractTypeFlag::kNone);
704 if (transient) flags |= AbstractTypeFlag::kTransient;
705 if (use_parent_type_checker) flags |= AbstractTypeFlag::kUseParentTypeChecker;
706 TypeDeclaration* type_decl = MakeNode<AbstractTypeDeclaration>(
707 name, flags, extends, std::move(generates));
708 Declaration* decl = type_decl;
709 if (!generic_parameters.empty()) {
710 decl = MakeNode<GenericTypeDeclaration>(generic_parameters, type_decl);
711 }
712
713 auto constexpr_generates =
714 child_results->NextAs<base::Optional<std::string>>();
715 std::vector<Declaration*> result{decl};
716
717 if (constexpr_generates) {
718 // Create a AbstractTypeDeclaration for the associated constexpr type.
719 Identifier* constexpr_name =
720 MakeNode<Identifier>(CONSTEXPR_TYPE_PREFIX + name->value);
721 constexpr_name->pos = name->pos;
722
723 base::Optional<TypeExpression*> constexpr_extends;
724 if (extends) {
725 constexpr_extends = AddConstexpr(*extends);
726 }
727 TypeDeclaration* constexpr_decl = MakeNode<AbstractTypeDeclaration>(
728 constexpr_name, flags | AbstractTypeFlag::kConstexpr, constexpr_extends,
729 constexpr_generates);
730 constexpr_decl->pos = name->pos;
731 Declaration* decl = constexpr_decl;
732 if (!generic_parameters.empty()) {
733 decl =
734 MakeNode<GenericTypeDeclaration>(generic_parameters, constexpr_decl);
735 }
736 result.push_back(decl);
737 }
738
739 return ParseResult{result};
740 }
741
MakeMethodDeclaration(ParseResultIterator * child_results)742 base::Optional<ParseResult> MakeMethodDeclaration(
743 ParseResultIterator* child_results) {
744 auto transitioning = child_results->NextAs<bool>();
745 auto operator_name = child_results->NextAs<base::Optional<std::string>>();
746 auto name = child_results->NextAs<Identifier*>();
747 if (!IsUpperCamelCase(name->value)) {
748 NamingConventionError("Method", name, "UpperCamelCase");
749 }
750
751 auto args = child_results->NextAs<ParameterList>();
752 auto return_type = child_results->NextAs<TypeExpression*>();
753 auto labels = child_results->NextAs<LabelAndTypesVector>();
754 auto body = child_results->NextAs<Statement*>();
755 Declaration* result =
756 MakeNode<TorqueMacroDeclaration>(transitioning, name, operator_name, args,
757 return_type, labels, false, body);
758 return ParseResult{result};
759 }
760
761 class AnnotationSet {
762 public:
AnnotationSet(ParseResultIterator * iter,const std::set<std::string> & allowed_without_param,const std::set<std::string> & allowed_with_param)763 AnnotationSet(ParseResultIterator* iter,
764 const std::set<std::string>& allowed_without_param,
765 const std::set<std::string>& allowed_with_param) {
766 auto list = iter->NextAs<std::vector<Annotation>>();
767 for (const Annotation& a : list) {
768 if (a.param.has_value()) {
769 if (allowed_with_param.find(a.name->value) ==
770 allowed_with_param.end()) {
771 const char* error_message =
772 allowed_without_param.find(a.name->value) ==
773 allowed_without_param.end()
774 ? " is not allowed here"
775 : " cannot have parameter here";
776 Lint("Annotation ", a.name->value, error_message)
777 .Position(a.name->pos);
778 }
779 if (!map_.insert({a.name->value, {*a.param, a.name->pos}}).second) {
780 Lint("Duplicate annotation ", a.name->value).Position(a.name->pos);
781 }
782 } else {
783 if (allowed_without_param.find(a.name->value) ==
784 allowed_without_param.end()) {
785 const char* error_message =
786 allowed_with_param.find(a.name->value) == allowed_with_param.end()
787 ? " is not allowed here"
788 : " requires a parameter here";
789 Lint("Annotation ", a.name->value, error_message)
790 .Position(a.name->pos);
791 }
792 if (!set_.insert(a.name->value).second) {
793 Lint("Duplicate annotation ", a.name->value).Position(a.name->pos);
794 }
795 }
796 }
797 }
798
Contains(const std::string & s) const799 bool Contains(const std::string& s) const {
800 return set_.find(s) != set_.end();
801 }
GetStringParam(const std::string & s) const802 base::Optional<std::string> GetStringParam(const std::string& s) const {
803 auto it = map_.find(s);
804 if (it == map_.end()) {
805 return {};
806 }
807 if (it->second.first.is_int) {
808 Error("Annotation ", s, " requires a string parameter but has an int")
809 .Position(it->second.second);
810 }
811 return it->second.first.string_value;
812 }
GetIntParam(const std::string & s) const813 base::Optional<int32_t> GetIntParam(const std::string& s) const {
814 auto it = map_.find(s);
815 if (it == map_.end()) {
816 return {};
817 }
818 if (!it->second.first.is_int) {
819 Error("Annotation ", s, " requires an int parameter but has a string")
820 .Position(it->second.second);
821 }
822 return it->second.first.int_value;
823 }
824
825 private:
826 std::set<std::string> set_;
827 std::map<std::string, std::pair<AnnotationParameter, SourcePosition>> map_;
828 };
829
MakeInt32(ParseResultIterator * child_results)830 base::Optional<ParseResult> MakeInt32(ParseResultIterator* child_results) {
831 std::string value = child_results->NextAs<std::string>();
832 size_t num_chars_converted = 0;
833 int result = 0;
834 try {
835 result = std::stoi(value, &num_chars_converted, 0);
836 } catch (const std::invalid_argument&) {
837 Error("Expected an integer");
838 return ParseResult{result};
839 } catch (const std::out_of_range&) {
840 Error("Integer out of 32-bit range");
841 return ParseResult{result};
842 }
843 // Tokenizer shouldn't have included extra trailing characters.
844 DCHECK_EQ(num_chars_converted, value.size());
845 return ParseResult{result};
846 }
847
MakeStringAnnotationParameter(ParseResultIterator * child_results)848 base::Optional<ParseResult> MakeStringAnnotationParameter(
849 ParseResultIterator* child_results) {
850 std::string value = child_results->NextAs<std::string>();
851 AnnotationParameter result{value, 0, false};
852 return ParseResult{result};
853 }
854
MakeIntAnnotationParameter(ParseResultIterator * child_results)855 base::Optional<ParseResult> MakeIntAnnotationParameter(
856 ParseResultIterator* child_results) {
857 int32_t value = child_results->NextAs<int32_t>();
858 AnnotationParameter result{"", value, true};
859 return ParseResult{result};
860 }
861
GetAnnotationValue(const AnnotationSet & annotations,const char * name,int default_value)862 int GetAnnotationValue(const AnnotationSet& annotations, const char* name,
863 int default_value) {
864 auto opt_value = annotations.GetIntParam(name);
865 return opt_value.has_value() ? *opt_value : default_value;
866 }
867
MakeInstanceTypeConstraints(const AnnotationSet & annotations)868 InstanceTypeConstraints MakeInstanceTypeConstraints(
869 const AnnotationSet& annotations) {
870 InstanceTypeConstraints result;
871 result.value =
872 GetAnnotationValue(annotations, ANNOTATION_INSTANCE_TYPE_VALUE, -1);
873 result.num_flags_bits = GetAnnotationValue(
874 annotations, ANNOTATION_RESERVE_BITS_IN_INSTANCE_TYPE, -1);
875 return result;
876 }
877
MakeClassBody(ParseResultIterator * child_results)878 base::Optional<ParseResult> MakeClassBody(ParseResultIterator* child_results) {
879 auto methods = child_results->NextAs<std::vector<Declaration*>>();
880 auto fields = child_results->NextAs<std::vector<ClassFieldExpression>>();
881 base::Optional<ClassBody*> result =
882 MakeNode<ClassBody>(std::move(methods), std::move(fields));
883 return ParseResult(result);
884 }
885
MakeClassDeclaration(ParseResultIterator * child_results)886 base::Optional<ParseResult> MakeClassDeclaration(
887 ParseResultIterator* child_results) {
888 AnnotationSet annotations(
889 child_results,
890 {ANNOTATION_GENERATE_PRINT, ANNOTATION_NO_VERIFIER, ANNOTATION_ABSTRACT,
891 ANNOTATION_HAS_SAME_INSTANCE_TYPE_AS_PARENT,
892 ANNOTATION_GENERATE_CPP_CLASS, ANNOTATION_CUSTOM_CPP_CLASS,
893 ANNOTATION_CUSTOM_MAP, ANNOTATION_GENERATE_BODY_DESCRIPTOR,
894 ANNOTATION_EXPORT, ANNOTATION_DO_NOT_GENERATE_CAST,
895 ANNOTATION_HIGHEST_INSTANCE_TYPE_WITHIN_PARENT,
896 ANNOTATION_LOWEST_INSTANCE_TYPE_WITHIN_PARENT},
897 {ANNOTATION_RESERVE_BITS_IN_INSTANCE_TYPE,
898 ANNOTATION_INSTANCE_TYPE_VALUE});
899 ClassFlags flags = ClassFlag::kNone;
900 bool generate_print = annotations.Contains(ANNOTATION_GENERATE_PRINT);
901 if (generate_print) flags |= ClassFlag::kGeneratePrint;
902 bool generate_verify = !annotations.Contains(ANNOTATION_NO_VERIFIER);
903 if (generate_verify) flags |= ClassFlag::kGenerateVerify;
904 if (annotations.Contains(ANNOTATION_ABSTRACT)) {
905 flags |= ClassFlag::kAbstract;
906 }
907 if (annotations.Contains(ANNOTATION_HAS_SAME_INSTANCE_TYPE_AS_PARENT)) {
908 flags |= ClassFlag::kHasSameInstanceTypeAsParent;
909 }
910 if (annotations.Contains(ANNOTATION_GENERATE_CPP_CLASS)) {
911 flags |= ClassFlag::kGenerateCppClassDefinitions;
912 }
913 if (annotations.Contains(ANNOTATION_CUSTOM_CPP_CLASS)) {
914 flags |= ClassFlag::kCustomCppClass;
915 }
916 if (annotations.Contains(ANNOTATION_CUSTOM_MAP)) {
917 flags |= ClassFlag::kCustomMap;
918 }
919 if (annotations.Contains(ANNOTATION_DO_NOT_GENERATE_CAST)) {
920 flags |= ClassFlag::kDoNotGenerateCast;
921 }
922 if (annotations.Contains(ANNOTATION_GENERATE_BODY_DESCRIPTOR)) {
923 flags |= ClassFlag::kGenerateBodyDescriptor;
924 }
925 if (annotations.Contains(ANNOTATION_EXPORT)) {
926 flags |= ClassFlag::kExport;
927 }
928 if (annotations.Contains(ANNOTATION_HIGHEST_INSTANCE_TYPE_WITHIN_PARENT)) {
929 flags |= ClassFlag::kHighestInstanceTypeWithinParent;
930 }
931 if (annotations.Contains(ANNOTATION_LOWEST_INSTANCE_TYPE_WITHIN_PARENT)) {
932 flags |= ClassFlag::kLowestInstanceTypeWithinParent;
933 }
934
935 auto is_extern = child_results->NextAs<bool>();
936 if (is_extern) flags |= ClassFlag::kExtern;
937 auto transient = child_results->NextAs<bool>();
938 if (transient) flags |= ClassFlag::kTransient;
939 std::string kind = child_results->NextAs<Identifier*>()->value;
940 if (kind == "shape") {
941 flags |= ClassFlag::kIsShape;
942 flags |= ClassFlag::kTransient;
943 flags |= ClassFlag::kHasSameInstanceTypeAsParent;
944 flags |= ClassFlag::kDoNotGenerateCast;
945 } else {
946 DCHECK_EQ(kind, "class");
947 }
948 auto name = child_results->NextAs<Identifier*>();
949 if (!IsValidTypeName(name->value)) {
950 NamingConventionError("Type", name, "UpperCamelCase");
951 }
952 auto extends = child_results->NextAs<TypeExpression*>();
953 if (!BasicTypeExpression::DynamicCast(extends)) {
954 ReportError("Expected type name in extends clause.");
955 }
956 auto generates = child_results->NextAs<base::Optional<std::string>>();
957 auto body = child_results->NextAs<base::Optional<ClassBody*>>();
958 std::vector<Declaration*> methods;
959 std::vector<ClassFieldExpression> fields_raw;
960 if (body.has_value()) {
961 methods = (*body)->methods;
962 fields_raw = (*body)->fields;
963 } else {
964 flags |= ClassFlag::kUndefinedLayout;
965 }
966
967 // Filter to only include fields that should be present based on decoration.
968 std::vector<ClassFieldExpression> fields;
969 std::copy_if(
970 fields_raw.begin(), fields_raw.end(), std::back_inserter(fields),
971 [](const ClassFieldExpression& exp) {
972 for (const ConditionalAnnotation& condition : exp.conditions) {
973 if (condition.type == ConditionalAnnotationType::kPositive
974 ? !BuildFlags::GetFlag(condition.condition, ANNOTATION_IF)
975 : BuildFlags::GetFlag(condition.condition,
976 ANNOTATION_IFNOT)) {
977 return false;
978 }
979 }
980 return true;
981 });
982
983 std::vector<Declaration*> result;
984
985 result.push_back(MakeNode<ClassDeclaration>(
986 name, flags, extends, std::move(generates), std::move(methods), fields,
987 MakeInstanceTypeConstraints(annotations)));
988
989 Identifier* constexpr_name =
990 MakeNode<Identifier>(CONSTEXPR_TYPE_PREFIX + name->value);
991 constexpr_name->pos = name->pos;
992 TypeExpression* constexpr_extends = AddConstexpr(extends);
993 AbstractTypeFlags abstract_type_flags(AbstractTypeFlag::kConstexpr);
994 if (transient) abstract_type_flags |= AbstractTypeFlag::kTransient;
995 TypeDeclaration* constexpr_decl = MakeNode<AbstractTypeDeclaration>(
996 constexpr_name, abstract_type_flags, constexpr_extends, name->value);
997 constexpr_decl->pos = name->pos;
998 result.push_back(constexpr_decl);
999
1000 if ((flags & ClassFlag::kDoNotGenerateCast) == 0 &&
1001 (flags & ClassFlag::kIsShape) == 0) {
1002 ParameterList parameters;
1003 parameters.names.push_back(MakeNode<Identifier>("obj"));
1004 parameters.types.push_back(
1005 MakeNode<BasicTypeExpression>(std::vector<std::string>{}, "HeapObject",
1006 std::vector<TypeExpression*>{}));
1007 LabelAndTypesVector labels;
1008 labels.push_back(LabelAndTypes{MakeNode<Identifier>("CastError"),
1009 std::vector<TypeExpression*>{}});
1010
1011 TypeExpression* class_type =
1012 MakeNode<BasicTypeExpression>(std::vector<std::string>{}, name->value,
1013 std::vector<TypeExpression*>{});
1014
1015 std::vector<std::string> namespace_qualification{
1016 TORQUE_INTERNAL_NAMESPACE_STRING};
1017
1018 IdentifierExpression* internal_downcast_target =
1019 MakeNode<IdentifierExpression>(
1020 namespace_qualification,
1021 MakeNode<Identifier>("DownCastForTorqueClass"),
1022 std::vector<TypeExpression*>{class_type});
1023 IdentifierExpression* internal_downcast_otherwise =
1024 MakeNode<IdentifierExpression>(std::vector<std::string>{},
1025 MakeNode<Identifier>("CastError"));
1026
1027 Expression* argument = MakeNode<IdentifierExpression>(
1028 std::vector<std::string>{}, MakeNode<Identifier>("obj"));
1029
1030 auto value = MakeCall(internal_downcast_target, base::nullopt,
1031 std::vector<Expression*>{argument},
1032 std::vector<Statement*>{MakeNode<ExpressionStatement>(
1033 internal_downcast_otherwise)});
1034
1035 auto cast_body = MakeNode<ReturnStatement>(value);
1036
1037 std::vector<TypeExpression*> generic_parameters;
1038 generic_parameters.push_back(
1039 MakeNode<BasicTypeExpression>(std::vector<std::string>{}, name->value,
1040 std::vector<TypeExpression*>{}));
1041
1042 Declaration* specialization = MakeNode<SpecializationDeclaration>(
1043 false, MakeNode<Identifier>("Cast"), generic_parameters,
1044 std::move(parameters), class_type, std::move(labels), cast_body);
1045 result.push_back(specialization);
1046 }
1047
1048 return ParseResult{result};
1049 }
1050
MakeNamespaceDeclaration(ParseResultIterator * child_results)1051 base::Optional<ParseResult> MakeNamespaceDeclaration(
1052 ParseResultIterator* child_results) {
1053 auto name = child_results->NextAs<std::string>();
1054 if (!IsSnakeCase(name)) {
1055 NamingConventionError("Namespace", name, "snake_case");
1056 }
1057 auto declarations = child_results->NextAs<std::vector<Declaration*>>();
1058 Declaration* result =
1059 MakeNode<NamespaceDeclaration>(std::move(name), std::move(declarations));
1060 return ParseResult{result};
1061 }
1062
MakeSpecializationDeclaration(ParseResultIterator * child_results)1063 base::Optional<ParseResult> MakeSpecializationDeclaration(
1064 ParseResultIterator* child_results) {
1065 auto transitioning = child_results->NextAs<bool>();
1066 auto name = child_results->NextAs<Identifier*>();
1067 auto generic_parameters =
1068 child_results->NextAs<std::vector<TypeExpression*>>();
1069 auto parameters = child_results->NextAs<ParameterList>();
1070 auto return_type = child_results->NextAs<TypeExpression*>();
1071 auto labels = child_results->NextAs<LabelAndTypesVector>();
1072 auto body = child_results->NextAs<Statement*>();
1073 CheckNotDeferredStatement(body);
1074 Declaration* result = MakeNode<SpecializationDeclaration>(
1075 transitioning, std::move(name), std::move(generic_parameters),
1076 std::move(parameters), return_type, std::move(labels), body);
1077 return ParseResult{result};
1078 }
1079
MakeStructDeclaration(ParseResultIterator * child_results)1080 base::Optional<ParseResult> MakeStructDeclaration(
1081 ParseResultIterator* child_results) {
1082 bool is_export = HasExportAnnotation(child_results, "Struct");
1083
1084 StructFlags flags = StructFlag::kNone;
1085 if (is_export) flags |= StructFlag::kExport;
1086
1087 auto name = child_results->NextAs<Identifier*>();
1088 if (!IsValidTypeName(name->value)) {
1089 NamingConventionError("Struct", name, "UpperCamelCase");
1090 }
1091 auto generic_parameters = child_results->NextAs<GenericParameters>();
1092 LintGenericParameters(generic_parameters);
1093 auto methods = child_results->NextAs<std::vector<Declaration*>>();
1094 auto fields = child_results->NextAs<std::vector<StructFieldExpression>>();
1095 TypeDeclaration* struct_decl = MakeNode<StructDeclaration>(
1096 flags, name, std::move(methods), std::move(fields));
1097 Declaration* result = struct_decl;
1098 if (!generic_parameters.empty()) {
1099 result = MakeNode<GenericTypeDeclaration>(generic_parameters, struct_decl);
1100 }
1101 return ParseResult{result};
1102 }
1103
MakeBitFieldStructDeclaration(ParseResultIterator * child_results)1104 base::Optional<ParseResult> MakeBitFieldStructDeclaration(
1105 ParseResultIterator* child_results) {
1106 auto name = child_results->NextAs<Identifier*>();
1107 if (!IsValidTypeName(name->value)) {
1108 NamingConventionError("Bitfield struct", name, "UpperCamelCase");
1109 }
1110 auto extends = child_results->NextAs<TypeExpression*>();
1111 auto fields = child_results->NextAs<std::vector<BitFieldDeclaration>>();
1112 Declaration* decl =
1113 MakeNode<BitFieldStructDeclaration>(name, extends, std::move(fields));
1114 return ParseResult{decl};
1115 }
1116
MakeCppIncludeDeclaration(ParseResultIterator * child_results)1117 base::Optional<ParseResult> MakeCppIncludeDeclaration(
1118 ParseResultIterator* child_results) {
1119 auto include_path = child_results->NextAs<std::string>();
1120 Declaration* result =
1121 MakeNode<CppIncludeDeclaration>(std::move(include_path));
1122 return ParseResult{result};
1123 }
1124
ProcessTorqueImportDeclaration(ParseResultIterator * child_results)1125 base::Optional<ParseResult> ProcessTorqueImportDeclaration(
1126 ParseResultIterator* child_results) {
1127 auto import_path = child_results->NextAs<std::string>();
1128 if (!SourceFileMap::FileRelativeToV8RootExists(import_path)) {
1129 Error("File '", import_path, "' not found.");
1130 }
1131
1132 auto import_id = SourceFileMap::GetSourceId(import_path);
1133 if (!import_id.IsValid()) {
1134 // TODO(szuend): Instead of reporting and error. Queue the file up
1135 // for compilation.
1136 Error("File '", import_path, "'is not part of the source set.").Throw();
1137 }
1138
1139 CurrentAst::Get().DeclareImportForCurrentFile(import_id);
1140
1141 return base::nullopt;
1142 }
1143
MakeExternalBuiltin(ParseResultIterator * child_results)1144 base::Optional<ParseResult> MakeExternalBuiltin(
1145 ParseResultIterator* child_results) {
1146 auto transitioning = child_results->NextAs<bool>();
1147 auto js_linkage = child_results->NextAs<bool>();
1148 auto name = child_results->NextAs<Identifier*>();
1149 auto generic_parameters = child_results->NextAs<GenericParameters>();
1150 LintGenericParameters(generic_parameters);
1151
1152 auto args = child_results->NextAs<ParameterList>();
1153 auto return_type = child_results->NextAs<TypeExpression*>();
1154 Declaration* result = MakeNode<ExternalBuiltinDeclaration>(
1155 transitioning, js_linkage, name, args, return_type);
1156 if (!generic_parameters.empty()) {
1157 Error("External builtins cannot be generic.");
1158 }
1159 return ParseResult{result};
1160 }
1161
MakeExternalRuntime(ParseResultIterator * child_results)1162 base::Optional<ParseResult> MakeExternalRuntime(
1163 ParseResultIterator* child_results) {
1164 auto transitioning = child_results->NextAs<bool>();
1165 auto name = child_results->NextAs<Identifier*>();
1166 auto args = child_results->NextAs<ParameterList>();
1167 auto return_type = child_results->NextAs<TypeExpression*>();
1168 Declaration* result = MakeNode<ExternalRuntimeDeclaration>(
1169 transitioning, name, args, return_type);
1170 return ParseResult{result};
1171 }
1172
StringLiteralUnquoteAction(ParseResultIterator * child_results)1173 base::Optional<ParseResult> StringLiteralUnquoteAction(
1174 ParseResultIterator* child_results) {
1175 return ParseResult{
1176 StringLiteralUnquote(child_results->NextAs<std::string>())};
1177 }
1178
MakeBasicTypeExpression(ParseResultIterator * child_results)1179 base::Optional<ParseResult> MakeBasicTypeExpression(
1180 ParseResultIterator* child_results) {
1181 auto namespace_qualification =
1182 child_results->NextAs<std::vector<std::string>>();
1183 auto is_constexpr = child_results->NextAs<bool>();
1184 auto name = child_results->NextAs<std::string>();
1185 auto generic_arguments =
1186 child_results->NextAs<std::vector<TypeExpression*>>();
1187 TypeExpression* result = MakeNode<BasicTypeExpression>(
1188 std::move(namespace_qualification),
1189 is_constexpr ? GetConstexprName(name) : std::move(name),
1190 std::move(generic_arguments));
1191 return ParseResult{result};
1192 }
1193
MakeFunctionTypeExpression(ParseResultIterator * child_results)1194 base::Optional<ParseResult> MakeFunctionTypeExpression(
1195 ParseResultIterator* child_results) {
1196 auto parameters = child_results->NextAs<std::vector<TypeExpression*>>();
1197 auto return_type = child_results->NextAs<TypeExpression*>();
1198 TypeExpression* result =
1199 MakeNode<FunctionTypeExpression>(std::move(parameters), return_type);
1200 return ParseResult{result};
1201 }
1202
MakeReferenceTypeExpression(ParseResultIterator * child_results)1203 base::Optional<ParseResult> MakeReferenceTypeExpression(
1204 ParseResultIterator* child_results) {
1205 auto is_const = child_results->NextAs<bool>();
1206 auto referenced_type = child_results->NextAs<TypeExpression*>();
1207 std::vector<std::string> namespace_qualification{
1208 TORQUE_INTERNAL_NAMESPACE_STRING};
1209 std::vector<TypeExpression*> generic_arguments{referenced_type};
1210 TypeExpression* result = MakeNode<BasicTypeExpression>(
1211 namespace_qualification,
1212 is_const ? CONST_REFERENCE_TYPE_STRING : MUTABLE_REFERENCE_TYPE_STRING,
1213 generic_arguments);
1214 return ParseResult{result};
1215 }
1216
MakeUnionTypeExpression(ParseResultIterator * child_results)1217 base::Optional<ParseResult> MakeUnionTypeExpression(
1218 ParseResultIterator* child_results) {
1219 auto a = child_results->NextAs<TypeExpression*>();
1220 auto b = child_results->NextAs<TypeExpression*>();
1221 TypeExpression* result = MakeNode<UnionTypeExpression>(a, b);
1222 return ParseResult{result};
1223 }
1224
MakeGenericParameter(ParseResultIterator * child_results)1225 base::Optional<ParseResult> MakeGenericParameter(
1226 ParseResultIterator* child_results) {
1227 auto name = child_results->NextAs<Identifier*>();
1228 auto constraint = child_results->NextAs<base::Optional<TypeExpression*>>();
1229 return ParseResult{GenericParameter{name, constraint}};
1230 }
1231
MakeExpressionStatement(ParseResultIterator * child_results)1232 base::Optional<ParseResult> MakeExpressionStatement(
1233 ParseResultIterator* child_results) {
1234 auto expression = child_results->NextAs<Expression*>();
1235 Statement* result = MakeNode<ExpressionStatement>(expression);
1236 return ParseResult{result};
1237 }
1238
MakeIfStatement(ParseResultIterator * child_results)1239 base::Optional<ParseResult> MakeIfStatement(
1240 ParseResultIterator* child_results) {
1241 auto is_constexpr = child_results->NextAs<bool>();
1242 auto condition = child_results->NextAs<Expression*>();
1243 auto if_true = child_results->NextAs<Statement*>();
1244 auto if_false = child_results->NextAs<base::Optional<Statement*>>();
1245
1246 if (if_false && !(BlockStatement::DynamicCast(if_true) &&
1247 (BlockStatement::DynamicCast(*if_false) ||
1248 IfStatement::DynamicCast(*if_false)))) {
1249 ReportError("if-else statements require curly braces");
1250 }
1251
1252 if (is_constexpr) {
1253 CheckNotDeferredStatement(if_true);
1254 if (if_false) CheckNotDeferredStatement(*if_false);
1255 }
1256
1257 Statement* result =
1258 MakeNode<IfStatement>(is_constexpr, condition, if_true, if_false);
1259 return ParseResult{result};
1260 }
1261
MakeEnumDeclaration(ParseResultIterator * child_results)1262 base::Optional<ParseResult> MakeEnumDeclaration(
1263 ParseResultIterator* child_results) {
1264 const bool is_extern = child_results->NextAs<bool>();
1265 auto name_identifier = child_results->NextAs<Identifier*>();
1266 auto name = name_identifier->value;
1267 auto base_type_expression =
1268 child_results->NextAs<base::Optional<TypeExpression*>>();
1269 auto constexpr_generates_opt =
1270 child_results->NextAs<base::Optional<std::string>>();
1271 auto entries = child_results->NextAs<std::vector<EnumEntry>>();
1272 const bool is_open = child_results->NextAs<bool>();
1273 CurrentSourcePosition::Scope current_source_position(
1274 child_results->matched_input().pos);
1275
1276 if (!is_extern) {
1277 ReportError("non-extern enums are not supported yet");
1278 }
1279
1280 if (!IsValidTypeName(name)) {
1281 NamingConventionError("Type", name, "UpperCamelCase");
1282 }
1283
1284 auto constexpr_generates =
1285 constexpr_generates_opt ? *constexpr_generates_opt : name;
1286 const bool generate_nonconstexpr = base_type_expression.has_value();
1287
1288 std::vector<Declaration*> result;
1289 // Build non-constexpr types.
1290 if (generate_nonconstexpr) {
1291 DCHECK(base_type_expression.has_value());
1292
1293 if (is_open) {
1294 // For open enumerations, we define an abstract type and inherit all
1295 // entries' types from that:
1296 // type Enum extends Base;
1297 // namespace Enum {
1298 // type kEntry0 extends Enum;
1299 // ...
1300 // type kEntryN extends Enum;
1301 // }
1302 auto type_decl = MakeNode<AbstractTypeDeclaration>(
1303 name_identifier, AbstractTypeFlag::kNone, base_type_expression,
1304 base::nullopt);
1305
1306 TypeExpression* name_type_expression =
1307 MakeNode<BasicTypeExpression>(name_identifier->value);
1308 name_type_expression->pos = name_identifier->pos;
1309
1310 std::vector<Declaration*> entry_decls;
1311 for (const auto& entry : entries) {
1312 entry_decls.push_back(MakeNode<AbstractTypeDeclaration>(
1313 entry.name, AbstractTypeFlag::kNone,
1314 entry.type.value_or(name_type_expression), base::nullopt));
1315 }
1316
1317 result.push_back(type_decl);
1318 result.push_back(
1319 MakeNode<NamespaceDeclaration>(name, std::move(entry_decls)));
1320 } else {
1321 // For closed enumerations, we define abstract types for all entries and
1322 // define the enumeration as a union of those:
1323 // namespace Enum {
1324 // type kEntry0 extends Base;
1325 // ...
1326 // type kEntryN extends Base;
1327 // }
1328 // type Enum = Enum::kEntry0 | ... | Enum::kEntryN;
1329 TypeExpression* union_type = nullptr;
1330 std::vector<Declaration*> entry_decls;
1331 for (const auto& entry : entries) {
1332 entry_decls.push_back(MakeNode<AbstractTypeDeclaration>(
1333 entry.name, AbstractTypeFlag::kNone,
1334 entry.type.value_or(*base_type_expression), base::nullopt));
1335
1336 auto entry_type = MakeNode<BasicTypeExpression>(
1337 std::vector<std::string>{name}, entry.name->value,
1338 std::vector<TypeExpression*>{});
1339 if (union_type) {
1340 union_type = MakeNode<UnionTypeExpression>(union_type, entry_type);
1341 } else {
1342 union_type = entry_type;
1343 }
1344 }
1345
1346 result.push_back(
1347 MakeNode<NamespaceDeclaration>(name, std::move(entry_decls)));
1348 result.push_back(
1349 MakeNode<TypeAliasDeclaration>(name_identifier, union_type));
1350 }
1351 }
1352
1353 // Build constexpr types.
1354 {
1355 // The constexpr entries inherit from an abstract enumeration type:
1356 // type constexpr Enum extends constexpr Base;
1357 // namespace Enum {
1358 // type constexpr kEntry0 extends constexpr Enum;
1359 // ...
1360 // type constexpr kEntry1 extends constexpr Enum;
1361 // }
1362 Identifier* constexpr_type_identifier =
1363 MakeNode<Identifier>(std::string(CONSTEXPR_TYPE_PREFIX) + name);
1364 TypeExpression* constexpr_type_expression = MakeNode<BasicTypeExpression>(
1365 std::string(CONSTEXPR_TYPE_PREFIX) + name);
1366 base::Optional<TypeExpression*> base_constexpr_type_expression =
1367 base::nullopt;
1368 if (base_type_expression) {
1369 base_constexpr_type_expression = AddConstexpr(*base_type_expression);
1370 }
1371 result.push_back(MakeNode<AbstractTypeDeclaration>(
1372 constexpr_type_identifier, AbstractTypeFlag::kConstexpr,
1373 base_constexpr_type_expression, constexpr_generates));
1374
1375 TypeExpression* type_expr = nullptr;
1376 Identifier* fromconstexpr_identifier = nullptr;
1377 Identifier* fromconstexpr_parameter_identifier = nullptr;
1378 Statement* fromconstexpr_body = nullptr;
1379 if (generate_nonconstexpr) {
1380 DCHECK(base_type_expression.has_value());
1381 type_expr = MakeNode<BasicTypeExpression>(
1382 std::vector<std::string>{}, name, std::vector<TypeExpression*>{});
1383
1384 // return %RawDownCast<Enum>(%FromConstexpr<Base>(o)))
1385 fromconstexpr_identifier = MakeNode<Identifier>("FromConstexpr");
1386 fromconstexpr_parameter_identifier = MakeNode<Identifier>("o");
1387 fromconstexpr_body =
1388 MakeNode<ReturnStatement>(MakeNode<IntrinsicCallExpression>(
1389 MakeNode<Identifier>("%RawDownCast"),
1390 std::vector<TypeExpression*>{type_expr},
1391 std::vector<Expression*>{MakeNode<IntrinsicCallExpression>(
1392 MakeNode<Identifier>("%FromConstexpr"),
1393 std::vector<TypeExpression*>{*base_type_expression},
1394 std::vector<Expression*>{MakeNode<IdentifierExpression>(
1395 std::vector<std::string>{},
1396 fromconstexpr_parameter_identifier)})}));
1397 }
1398
1399 EnumDescription enum_description{CurrentSourcePosition::Get(), name,
1400 constexpr_generates, is_open};
1401 std::vector<Declaration*> entry_decls;
1402 for (const auto& entry : entries) {
1403 const std::string entry_name = entry.name->value;
1404 const std::string entry_constexpr_type =
1405 CONSTEXPR_TYPE_PREFIX + entry_name;
1406 enum_description.entries.push_back(constexpr_generates +
1407 "::" + entry_name);
1408
1409 entry_decls.push_back(MakeNode<AbstractTypeDeclaration>(
1410 MakeNode<Identifier>(entry_constexpr_type),
1411 AbstractTypeFlag::kConstexpr, constexpr_type_expression,
1412 constexpr_generates));
1413
1414 bool generate_typed_constant = entry.type.has_value();
1415 if (generate_typed_constant) {
1416 // namespace Enum {
1417 // const constexpr_constant_kEntry0: constexpr kEntry0 constexpr
1418 // 'Enum::kEntry0'; const kEntry0 = %RawDownCast<T,
1419 // Base>(FromConstexpr<Enum>(constexpr_constant_kEntry0));
1420 // }
1421 if (!generate_nonconstexpr) {
1422 Error(
1423 "Enum constants with custom types require an enum with an "
1424 "extends clause.")
1425 .Position((*entry.type)->pos);
1426 }
1427 Identifier* constexpr_constant_name =
1428 MakeNode<Identifier>("constexpr constant " + entry_name);
1429 entry_decls.push_back(MakeNode<ExternConstDeclaration>(
1430 constexpr_constant_name,
1431 MakeNode<BasicTypeExpression>(std::vector<std::string>{},
1432 entry_constexpr_type,
1433 std::vector<TypeExpression*>{}),
1434 constexpr_generates + "::" + entry_name));
1435 entry_decls.push_back(MakeNode<ConstDeclaration>(
1436 entry.name, *entry.type,
1437 MakeNode<IntrinsicCallExpression>(
1438 MakeNode<Identifier>("%RawDownCast"),
1439 std::vector<TypeExpression*>{*entry.type,
1440 *base_type_expression},
1441 std::vector<Expression*>{MakeCall(
1442 MakeNode<Identifier>("FromConstexpr"), {type_expr},
1443 {MakeNode<IdentifierExpression>(std::vector<std::string>{},
1444 constexpr_constant_name)},
1445 {})})));
1446 } else {
1447 // namespace Enum {
1448 // const kEntry0: constexpr kEntry0 constexpr 'Enum::kEntry0';
1449 // }
1450 entry_decls.push_back(MakeNode<ExternConstDeclaration>(
1451 entry.name,
1452 MakeNode<BasicTypeExpression>(std::vector<std::string>{},
1453 entry_constexpr_type,
1454 std::vector<TypeExpression*>{}),
1455 constexpr_generates + "::" + entry_name));
1456 }
1457
1458 // FromConstexpr<Enum, Enum::constexpr kEntry0>(
1459 // : Enum::constexpr kEntry0): Enum
1460 if (generate_nonconstexpr) {
1461 TypeExpression* entry_constexpr_type_expr =
1462 MakeNode<BasicTypeExpression>(std::vector<std::string>{name},
1463 entry_constexpr_type,
1464 std::vector<TypeExpression*>{});
1465
1466 ParameterList parameters;
1467 parameters.names.push_back(fromconstexpr_parameter_identifier);
1468 parameters.types.push_back(entry_constexpr_type_expr);
1469 result.push_back(MakeNode<SpecializationDeclaration>(
1470 false, fromconstexpr_identifier,
1471 std::vector<TypeExpression*>{type_expr, entry_constexpr_type_expr},
1472 std::move(parameters), type_expr, LabelAndTypesVector{},
1473 fromconstexpr_body));
1474 }
1475 }
1476
1477 result.push_back(
1478 MakeNode<NamespaceDeclaration>(name, std::move(entry_decls)));
1479 CurrentAst::Get().AddEnumDescription(std::move(enum_description));
1480 }
1481
1482 return ParseResult{std::move(result)};
1483 }
1484
MakeTypeswitchStatement(ParseResultIterator * child_results)1485 base::Optional<ParseResult> MakeTypeswitchStatement(
1486 ParseResultIterator* child_results) {
1487 auto expression = child_results->NextAs<Expression*>();
1488 auto cases = child_results->NextAs<std::vector<TypeswitchCase>>();
1489 CurrentSourcePosition::Scope current_source_position(
1490 child_results->matched_input().pos);
1491
1492 // typeswitch (expression) case (x1 : T1) {
1493 // ...b1
1494 // } case (x2 : T2) {
1495 // ...b2
1496 // } case (x3 : T3) {
1497 // ...b3
1498 // }
1499 //
1500 // desugars to
1501 //
1502 // {
1503 // const _value = expression;
1504 // try {
1505 // const x1 : T1 = cast<T1>(_value) otherwise _NextCase;
1506 // ...b1
1507 // } label _NextCase {
1508 // try {
1509 // const x2 : T2 = cast<T2>(%assume_impossible<T1>(_value));
1510 // ...b2
1511 // } label _NextCase {
1512 // const x3 : T3 = %assume_impossible<T1|T2>(_value);
1513 // ...b3
1514 // }
1515 // }
1516 // }
1517
1518 BlockStatement* current_block = MakeNode<BlockStatement>();
1519 Statement* result = current_block;
1520 {
1521 CurrentSourcePosition::Scope current_source_position(expression->pos);
1522 current_block->statements.push_back(MakeNode<VarDeclarationStatement>(
1523 true, MakeNode<Identifier>("__value"), base::nullopt, expression));
1524 }
1525
1526 TypeExpression* accumulated_types;
1527 for (size_t i = 0; i < cases.size(); ++i) {
1528 CurrentSourcePosition::Scope current_source_position(cases[i].pos);
1529 Expression* value =
1530 MakeNode<IdentifierExpression>(MakeNode<Identifier>("__value"));
1531 if (i >= 1) {
1532 value =
1533 MakeNode<AssumeTypeImpossibleExpression>(accumulated_types, value);
1534 }
1535 BlockStatement* case_block;
1536 if (i < cases.size() - 1) {
1537 value = MakeCall(MakeNode<Identifier>("Cast"),
1538 std::vector<TypeExpression*>{cases[i].type},
1539 std::vector<Expression*>{value},
1540 std::vector<Statement*>{MakeNode<ExpressionStatement>(
1541 MakeNode<IdentifierExpression>(
1542 MakeNode<Identifier>(kNextCaseLabelName)))});
1543 case_block = MakeNode<BlockStatement>();
1544 } else {
1545 case_block = current_block;
1546 }
1547 std::string name = "__case_value";
1548 if (cases[i].name) name = *cases[i].name;
1549 case_block->statements.push_back(MakeNode<VarDeclarationStatement>(
1550 true, MakeNode<Identifier>(name), cases[i].type, value));
1551 case_block->statements.push_back(cases[i].block);
1552 if (i < cases.size() - 1) {
1553 BlockStatement* next_block = MakeNode<BlockStatement>();
1554 current_block->statements.push_back(
1555 MakeNode<ExpressionStatement>(MakeNode<TryLabelExpression>(
1556 MakeNode<StatementExpression>(case_block),
1557 MakeNode<TryHandler>(TryHandler::HandlerKind::kLabel,
1558 MakeNode<Identifier>(kNextCaseLabelName),
1559 ParameterList::Empty(), next_block))));
1560 current_block = next_block;
1561 }
1562 accumulated_types =
1563 i > 0 ? MakeNode<UnionTypeExpression>(accumulated_types, cases[i].type)
1564 : cases[i].type;
1565 }
1566 return ParseResult{result};
1567 }
1568
MakeTypeswitchCase(ParseResultIterator * child_results)1569 base::Optional<ParseResult> MakeTypeswitchCase(
1570 ParseResultIterator* child_results) {
1571 auto name = child_results->NextAs<base::Optional<std::string>>();
1572 auto type = child_results->NextAs<TypeExpression*>();
1573 auto block = child_results->NextAs<Statement*>();
1574 return ParseResult{TypeswitchCase{child_results->matched_input().pos,
1575 std::move(name), type, block}};
1576 }
1577
MakeWhileStatement(ParseResultIterator * child_results)1578 base::Optional<ParseResult> MakeWhileStatement(
1579 ParseResultIterator* child_results) {
1580 auto condition = child_results->NextAs<Expression*>();
1581 auto body = child_results->NextAs<Statement*>();
1582 Statement* result = MakeNode<WhileStatement>(condition, body);
1583 CheckNotDeferredStatement(result);
1584 return ParseResult{result};
1585 }
1586
MakeReturnStatement(ParseResultIterator * child_results)1587 base::Optional<ParseResult> MakeReturnStatement(
1588 ParseResultIterator* child_results) {
1589 auto value = child_results->NextAs<base::Optional<Expression*>>();
1590 Statement* result = MakeNode<ReturnStatement>(value);
1591 return ParseResult{result};
1592 }
1593
MakeTailCallStatement(ParseResultIterator * child_results)1594 base::Optional<ParseResult> MakeTailCallStatement(
1595 ParseResultIterator* child_results) {
1596 auto value = child_results->NextAs<Expression*>();
1597 Statement* result = MakeNode<TailCallStatement>(CallExpression::cast(value));
1598 return ParseResult{result};
1599 }
1600
MakeVarDeclarationStatement(ParseResultIterator * child_results)1601 base::Optional<ParseResult> MakeVarDeclarationStatement(
1602 ParseResultIterator* child_results) {
1603 auto kind = child_results->NextAs<Identifier*>();
1604 bool const_qualified = kind->value == "const";
1605 if (!const_qualified) DCHECK_EQ("let", kind->value);
1606 auto name = child_results->NextAs<Identifier*>();
1607 if (!IsLowerCamelCase(name->value)) {
1608 NamingConventionError("Variable", name, "lowerCamelCase");
1609 }
1610
1611 auto type = child_results->NextAs<base::Optional<TypeExpression*>>();
1612 base::Optional<Expression*> initializer;
1613 if (child_results->HasNext())
1614 initializer = child_results->NextAs<Expression*>();
1615 if (!initializer && !type) {
1616 ReportError("Declaration is missing a type.");
1617 }
1618 Statement* result = MakeNode<VarDeclarationStatement>(const_qualified, name,
1619 type, initializer);
1620 return ParseResult{result};
1621 }
1622
MakeBreakStatement(ParseResultIterator * child_results)1623 base::Optional<ParseResult> MakeBreakStatement(
1624 ParseResultIterator* child_results) {
1625 Statement* result = MakeNode<BreakStatement>();
1626 return ParseResult{result};
1627 }
1628
MakeContinueStatement(ParseResultIterator * child_results)1629 base::Optional<ParseResult> MakeContinueStatement(
1630 ParseResultIterator* child_results) {
1631 Statement* result = MakeNode<ContinueStatement>();
1632 return ParseResult{result};
1633 }
1634
MakeGotoStatement(ParseResultIterator * child_results)1635 base::Optional<ParseResult> MakeGotoStatement(
1636 ParseResultIterator* child_results) {
1637 auto label = child_results->NextAs<Identifier*>();
1638 auto arguments = child_results->NextAs<std::vector<Expression*>>();
1639 Statement* result = MakeNode<GotoStatement>(label, std::move(arguments));
1640 return ParseResult{result};
1641 }
1642
MakeBlockStatement(ParseResultIterator * child_results)1643 base::Optional<ParseResult> MakeBlockStatement(
1644 ParseResultIterator* child_results) {
1645 auto deferred = child_results->NextAs<bool>();
1646 auto statements = child_results->NextAs<std::vector<Statement*>>();
1647 for (Statement* statement : statements) {
1648 CheckNotDeferredStatement(statement);
1649 }
1650 Statement* result = MakeNode<BlockStatement>(deferred, std::move(statements));
1651 return ParseResult{result};
1652 }
1653
MakeTryLabelExpression(ParseResultIterator * child_results)1654 base::Optional<ParseResult> MakeTryLabelExpression(
1655 ParseResultIterator* child_results) {
1656 auto try_block = child_results->NextAs<Statement*>();
1657 CheckNotDeferredStatement(try_block);
1658 Statement* result = try_block;
1659 auto handlers = child_results->NextAs<std::vector<TryHandler*>>();
1660 if (handlers.empty()) {
1661 Error("Try blocks without catch or label don't make sense.");
1662 }
1663 for (size_t i = 0; i < handlers.size(); ++i) {
1664 if (i != 0 &&
1665 handlers[i]->handler_kind == TryHandler::HandlerKind::kCatch) {
1666 Error(
1667 "A catch handler always has to be first, before any label handler, "
1668 "to avoid ambiguity about whether it catches exceptions from "
1669 "preceding handlers or not.")
1670 .Position(handlers[i]->pos);
1671 }
1672 result = MakeNode<ExpressionStatement>(MakeNode<TryLabelExpression>(
1673 MakeNode<StatementExpression>(result), handlers[i]));
1674 }
1675 return ParseResult{result};
1676 }
1677
MakeForLoopStatement(ParseResultIterator * child_results)1678 base::Optional<ParseResult> MakeForLoopStatement(
1679 ParseResultIterator* child_results) {
1680 auto var_decl = child_results->NextAs<base::Optional<Statement*>>();
1681 auto test = child_results->NextAs<base::Optional<Expression*>>();
1682 auto action = child_results->NextAs<base::Optional<Expression*>>();
1683 base::Optional<Statement*> action_stmt;
1684 if (action) action_stmt = MakeNode<ExpressionStatement>(*action);
1685 auto body = child_results->NextAs<Statement*>();
1686 CheckNotDeferredStatement(body);
1687 Statement* result =
1688 MakeNode<ForLoopStatement>(var_decl, test, action_stmt, body);
1689 return ParseResult{result};
1690 }
1691
MakeLabelBlock(ParseResultIterator * child_results)1692 base::Optional<ParseResult> MakeLabelBlock(ParseResultIterator* child_results) {
1693 auto label = child_results->NextAs<Identifier*>();
1694 if (!IsUpperCamelCase(label->value)) {
1695 NamingConventionError("Label", label, "UpperCamelCase");
1696 }
1697 auto parameters = child_results->NextAs<ParameterList>();
1698 auto body = child_results->NextAs<Statement*>();
1699 TryHandler* result = MakeNode<TryHandler>(TryHandler::HandlerKind::kLabel,
1700 label, std::move(parameters), body);
1701 return ParseResult{result};
1702 }
1703
MakeCatchBlock(ParseResultIterator * child_results)1704 base::Optional<ParseResult> MakeCatchBlock(ParseResultIterator* child_results) {
1705 auto variable = child_results->NextAs<std::string>();
1706 auto body = child_results->NextAs<Statement*>();
1707 if (!IsLowerCamelCase(variable)) {
1708 NamingConventionError("Exception", variable, "lowerCamelCase");
1709 }
1710 ParameterList parameters;
1711 parameters.names.push_back(MakeNode<Identifier>(variable));
1712 parameters.types.push_back(MakeNode<BasicTypeExpression>(
1713 std::vector<std::string>{}, "JSAny", std::vector<TypeExpression*>{}));
1714 parameters.has_varargs = false;
1715 TryHandler* result = MakeNode<TryHandler>(
1716 TryHandler::HandlerKind::kCatch, MakeNode<Identifier>(kCatchLabelName),
1717 std::move(parameters), body);
1718 return ParseResult{result};
1719 }
1720
MakeExpressionWithSource(ParseResultIterator * child_results)1721 base::Optional<ParseResult> MakeExpressionWithSource(
1722 ParseResultIterator* child_results) {
1723 auto e = child_results->NextAs<Expression*>();
1724 return ParseResult{
1725 ExpressionWithSource{e, child_results->matched_input().ToString()}};
1726 }
1727
MakeIdentifier(ParseResultIterator * child_results)1728 base::Optional<ParseResult> MakeIdentifier(ParseResultIterator* child_results) {
1729 auto name = child_results->NextAs<std::string>();
1730 Identifier* result = MakeNode<Identifier>(std::move(name));
1731 return ParseResult{result};
1732 }
1733
MakeIdentifierFromMatchedInput(ParseResultIterator * child_results)1734 base::Optional<ParseResult> MakeIdentifierFromMatchedInput(
1735 ParseResultIterator* child_results) {
1736 return ParseResult{
1737 MakeNode<Identifier>(child_results->matched_input().ToString())};
1738 }
1739
MakeRightShiftIdentifier(ParseResultIterator * child_results)1740 base::Optional<ParseResult> MakeRightShiftIdentifier(
1741 ParseResultIterator* child_results) {
1742 std::string str = child_results->matched_input().ToString();
1743 for (auto character : str) {
1744 if (character != '>') {
1745 ReportError("right-shift operators may not contain any whitespace");
1746 }
1747 }
1748 return ParseResult{MakeNode<Identifier>(str)};
1749 }
1750
MakeNamespaceQualification(ParseResultIterator * child_results)1751 base::Optional<ParseResult> MakeNamespaceQualification(
1752 ParseResultIterator* child_results) {
1753 bool global_namespace = child_results->NextAs<bool>();
1754 auto namespace_qualification =
1755 child_results->NextAs<std::vector<std::string>>();
1756 if (global_namespace) {
1757 namespace_qualification.insert(namespace_qualification.begin(), "");
1758 }
1759 return ParseResult(std::move(namespace_qualification));
1760 }
1761
MakeIdentifierExpression(ParseResultIterator * child_results)1762 base::Optional<ParseResult> MakeIdentifierExpression(
1763 ParseResultIterator* child_results) {
1764 auto namespace_qualification =
1765 child_results->NextAs<std::vector<std::string>>();
1766 auto name = child_results->NextAs<Identifier*>();
1767 auto generic_arguments =
1768 child_results->NextAs<std::vector<TypeExpression*>>();
1769 Expression* result = MakeNode<IdentifierExpression>(
1770 std::move(namespace_qualification), name, std::move(generic_arguments));
1771 return ParseResult{result};
1772 }
1773
MakeFieldAccessExpression(ParseResultIterator * child_results)1774 base::Optional<ParseResult> MakeFieldAccessExpression(
1775 ParseResultIterator* child_results) {
1776 auto object = child_results->NextAs<Expression*>();
1777 auto field = child_results->NextAs<Identifier*>();
1778 Expression* result = MakeNode<FieldAccessExpression>(object, field);
1779 return ParseResult{result};
1780 }
1781
MakeReferenceFieldAccessExpression(ParseResultIterator * child_results)1782 base::Optional<ParseResult> MakeReferenceFieldAccessExpression(
1783 ParseResultIterator* child_results) {
1784 auto object = child_results->NextAs<Expression*>();
1785 auto field = child_results->NextAs<Identifier*>();
1786 // `a->b` is equivalent to `(*a).b`.
1787 Expression* deref = MakeNode<DereferenceExpression>(object);
1788 Expression* result = MakeNode<FieldAccessExpression>(deref, field);
1789 return ParseResult{result};
1790 }
1791
MakeElementAccessExpression(ParseResultIterator * child_results)1792 base::Optional<ParseResult> MakeElementAccessExpression(
1793 ParseResultIterator* child_results) {
1794 auto object = child_results->NextAs<Expression*>();
1795 auto field = child_results->NextAs<Expression*>();
1796 Expression* result = MakeNode<ElementAccessExpression>(object, field);
1797 return ParseResult{result};
1798 }
1799
MakeDereferenceExpression(ParseResultIterator * child_results)1800 base::Optional<ParseResult> MakeDereferenceExpression(
1801 ParseResultIterator* child_results) {
1802 auto reference = child_results->NextAs<Expression*>();
1803 Expression* result = MakeNode<DereferenceExpression>(reference);
1804 return ParseResult{result};
1805 }
1806
MakeStructExpression(ParseResultIterator * child_results)1807 base::Optional<ParseResult> MakeStructExpression(
1808 ParseResultIterator* child_results) {
1809 auto type = child_results->NextAs<TypeExpression*>();
1810 auto initializers = child_results->NextAs<std::vector<NameAndExpression>>();
1811 Expression* result =
1812 MakeNode<StructExpression>(type, std::move(initializers));
1813 return ParseResult{result};
1814 }
1815
MakeAssignmentExpression(ParseResultIterator * child_results)1816 base::Optional<ParseResult> MakeAssignmentExpression(
1817 ParseResultIterator* child_results) {
1818 auto location = child_results->NextAs<Expression*>();
1819 auto op = child_results->NextAs<base::Optional<std::string>>();
1820 auto value = child_results->NextAs<Expression*>();
1821 Expression* result =
1822 MakeNode<AssignmentExpression>(location, std::move(op), value);
1823 return ParseResult{result};
1824 }
1825
MakeNumberLiteralExpression(ParseResultIterator * child_results)1826 base::Optional<ParseResult> MakeNumberLiteralExpression(
1827 ParseResultIterator* child_results) {
1828 auto number = child_results->NextAs<std::string>();
1829 // TODO(tebbi): Support 64bit literals.
1830 // Meanwhile, we type it as constexpr float64 when out of int32 range.
1831 double value = 0;
1832 try {
1833 value = std::stod(number);
1834 } catch (const std::out_of_range&) {
1835 Error("double literal out-of-range").Throw();
1836 }
1837 Expression* result = MakeNode<NumberLiteralExpression>(value);
1838 return ParseResult{result};
1839 }
1840
MakeStringLiteralExpression(ParseResultIterator * child_results)1841 base::Optional<ParseResult> MakeStringLiteralExpression(
1842 ParseResultIterator* child_results) {
1843 auto literal = child_results->NextAs<std::string>();
1844 Expression* result = MakeNode<StringLiteralExpression>(std::move(literal));
1845 return ParseResult{result};
1846 }
1847
MakeIncrementDecrementExpressionPostfix(ParseResultIterator * child_results)1848 base::Optional<ParseResult> MakeIncrementDecrementExpressionPostfix(
1849 ParseResultIterator* child_results) {
1850 auto location = child_results->NextAs<Expression*>();
1851 auto op = child_results->NextAs<IncrementDecrementOperator>();
1852 Expression* result =
1853 MakeNode<IncrementDecrementExpression>(location, op, true);
1854 return ParseResult{result};
1855 }
1856
MakeIncrementDecrementExpressionPrefix(ParseResultIterator * child_results)1857 base::Optional<ParseResult> MakeIncrementDecrementExpressionPrefix(
1858 ParseResultIterator* child_results) {
1859 auto op = child_results->NextAs<IncrementDecrementOperator>();
1860 auto location = child_results->NextAs<Expression*>();
1861 Expression* result =
1862 MakeNode<IncrementDecrementExpression>(location, op, false);
1863 return ParseResult{result};
1864 }
1865
MakeLogicalOrExpression(ParseResultIterator * child_results)1866 base::Optional<ParseResult> MakeLogicalOrExpression(
1867 ParseResultIterator* child_results) {
1868 auto left = child_results->NextAs<Expression*>();
1869 auto right = child_results->NextAs<Expression*>();
1870 Expression* result = MakeNode<LogicalOrExpression>(left, right);
1871 return ParseResult{result};
1872 }
1873
MakeLogicalAndExpression(ParseResultIterator * child_results)1874 base::Optional<ParseResult> MakeLogicalAndExpression(
1875 ParseResultIterator* child_results) {
1876 auto left = child_results->NextAs<Expression*>();
1877 auto right = child_results->NextAs<Expression*>();
1878 Expression* result = MakeNode<LogicalAndExpression>(left, right);
1879 return ParseResult{result};
1880 }
1881
MakeConditionalExpression(ParseResultIterator * child_results)1882 base::Optional<ParseResult> MakeConditionalExpression(
1883 ParseResultIterator* child_results) {
1884 auto condition = child_results->NextAs<Expression*>();
1885 auto if_true = child_results->NextAs<Expression*>();
1886 auto if_false = child_results->NextAs<Expression*>();
1887 Expression* result =
1888 MakeNode<ConditionalExpression>(condition, if_true, if_false);
1889 return ParseResult{result};
1890 }
1891
MakeLabelAndTypes(ParseResultIterator * child_results)1892 base::Optional<ParseResult> MakeLabelAndTypes(
1893 ParseResultIterator* child_results) {
1894 auto name = child_results->NextAs<Identifier*>();
1895 if (!IsUpperCamelCase(name->value)) {
1896 NamingConventionError("Label", name, "UpperCamelCase");
1897 }
1898 auto types = child_results->NextAs<std::vector<TypeExpression*>>();
1899 return ParseResult{LabelAndTypes{name, std::move(types)}};
1900 }
1901
MakeNameAndType(ParseResultIterator * child_results)1902 base::Optional<ParseResult> MakeNameAndType(
1903 ParseResultIterator* child_results) {
1904 auto name = child_results->NextAs<Identifier*>();
1905 auto type = child_results->NextAs<TypeExpression*>();
1906 return ParseResult{NameAndTypeExpression{name, type}};
1907 }
1908
MakeEnumEntry(ParseResultIterator * child_results)1909 base::Optional<ParseResult> MakeEnumEntry(ParseResultIterator* child_results) {
1910 auto name = child_results->NextAs<Identifier*>();
1911 auto type = child_results->NextAs<base::Optional<TypeExpression*>>();
1912 return ParseResult{EnumEntry{name, type}};
1913 }
1914
MakeNameAndExpression(ParseResultIterator * child_results)1915 base::Optional<ParseResult> MakeNameAndExpression(
1916 ParseResultIterator* child_results) {
1917 auto name = child_results->NextAs<Identifier*>();
1918 auto expression = child_results->NextAs<Expression*>();
1919 return ParseResult{NameAndExpression{name, expression}};
1920 }
1921
MakeNameAndExpressionFromExpression(ParseResultIterator * child_results)1922 base::Optional<ParseResult> MakeNameAndExpressionFromExpression(
1923 ParseResultIterator* child_results) {
1924 auto expression = child_results->NextAs<Expression*>();
1925 if (auto* id = IdentifierExpression::DynamicCast(expression)) {
1926 if (!id->generic_arguments.empty() ||
1927 !id->namespace_qualification.empty()) {
1928 ReportError("expected a plain identifier without qualification");
1929 }
1930 return ParseResult{NameAndExpression{id->name, id}};
1931 }
1932 ReportError("Constructor parameters need to be named.");
1933 }
1934
MakeAnnotation(ParseResultIterator * child_results)1935 base::Optional<ParseResult> MakeAnnotation(ParseResultIterator* child_results) {
1936 return ParseResult{
1937 Annotation{child_results->NextAs<Identifier*>(),
1938 child_results->NextAs<base::Optional<AnnotationParameter>>()}};
1939 }
1940
MakeClassField(ParseResultIterator * child_results)1941 base::Optional<ParseResult> MakeClassField(ParseResultIterator* child_results) {
1942 AnnotationSet annotations(child_results, {ANNOTATION_NO_VERIFIER},
1943 {ANNOTATION_IF, ANNOTATION_IFNOT});
1944 bool generate_verify = !annotations.Contains(ANNOTATION_NO_VERIFIER);
1945 std::vector<ConditionalAnnotation> conditions;
1946 base::Optional<std::string> if_condition =
1947 annotations.GetStringParam(ANNOTATION_IF);
1948 base::Optional<std::string> ifnot_condition =
1949 annotations.GetStringParam(ANNOTATION_IFNOT);
1950 if (if_condition.has_value()) {
1951 conditions.push_back({*if_condition, ConditionalAnnotationType::kPositive});
1952 }
1953 if (ifnot_condition.has_value()) {
1954 conditions.push_back(
1955 {*ifnot_condition, ConditionalAnnotationType::kNegative});
1956 }
1957 auto weak = child_results->NextAs<bool>();
1958 auto const_qualified = child_results->NextAs<bool>();
1959 auto name = child_results->NextAs<Identifier*>();
1960 auto index = child_results->NextAs<base::Optional<Expression*>>();
1961 auto type = child_results->NextAs<TypeExpression*>();
1962 return ParseResult{ClassFieldExpression{{name, type},
1963 index,
1964 std::move(conditions),
1965 weak,
1966 const_qualified,
1967 generate_verify}};
1968 }
1969
MakeStructField(ParseResultIterator * child_results)1970 base::Optional<ParseResult> MakeStructField(
1971 ParseResultIterator* child_results) {
1972 auto const_qualified = child_results->NextAs<bool>();
1973 auto name = child_results->NextAs<Identifier*>();
1974 auto type = child_results->NextAs<TypeExpression*>();
1975 return ParseResult{StructFieldExpression{{name, type}, const_qualified}};
1976 }
1977
MakeBitFieldDeclaration(ParseResultIterator * child_results)1978 base::Optional<ParseResult> MakeBitFieldDeclaration(
1979 ParseResultIterator* child_results) {
1980 auto name = child_results->NextAs<Identifier*>();
1981 auto type = child_results->NextAs<TypeExpression*>();
1982 auto num_bits = child_results->NextAs<int32_t>();
1983 return ParseResult{BitFieldDeclaration{{name, type}, num_bits}};
1984 }
1985
ExtractAssignmentOperator(ParseResultIterator * child_results)1986 base::Optional<ParseResult> ExtractAssignmentOperator(
1987 ParseResultIterator* child_results) {
1988 auto op = child_results->NextAs<Identifier*>();
1989 base::Optional<std::string> result =
1990 std::string(op->value.begin(), op->value.end() - 1);
1991 return ParseResult(std::move(result));
1992 }
1993
1994 struct TorqueGrammar : Grammar {
MatchWhitespacev8::internal::torque::__anonf2940ded0111::TorqueGrammar1995 static bool MatchWhitespace(InputPosition* pos) {
1996 while (true) {
1997 if (MatchChar(std::isspace, pos)) continue;
1998 if (MatchString("//", pos)) {
1999 while (MatchChar([](char c) { return c != '\n'; }, pos)) {
2000 }
2001 continue;
2002 }
2003 if (MatchString("/*", pos)) {
2004 while (!MatchString("*/", pos)) ++*pos;
2005 continue;
2006 }
2007 return true;
2008 }
2009 }
2010
MatchIdentifierv8::internal::torque::__anonf2940ded0111::TorqueGrammar2011 static bool MatchIdentifier(InputPosition* pos) {
2012 InputPosition current = *pos;
2013 MatchString("_", ¤t);
2014 if (!MatchChar(std::isalpha, ¤t)) return false;
2015 while (MatchChar(std::isalnum, ¤t) || MatchString("_", ¤t)) {
2016 }
2017 *pos = current;
2018 return true;
2019 }
2020
MatchAnnotationv8::internal::torque::__anonf2940ded0111::TorqueGrammar2021 static bool MatchAnnotation(InputPosition* pos) {
2022 InputPosition current = *pos;
2023 if (!MatchString("@", ¤t)) return false;
2024 if (!MatchIdentifier(¤t)) return false;
2025 *pos = current;
2026 return true;
2027 }
2028
MatchIntrinsicNamev8::internal::torque::__anonf2940ded0111::TorqueGrammar2029 static bool MatchIntrinsicName(InputPosition* pos) {
2030 InputPosition current = *pos;
2031 if (!MatchString("%", ¤t)) return false;
2032 if (!MatchIdentifier(¤t)) return false;
2033 *pos = current;
2034 return true;
2035 }
2036
MatchStringLiteralv8::internal::torque::__anonf2940ded0111::TorqueGrammar2037 static bool MatchStringLiteral(InputPosition* pos) {
2038 InputPosition current = *pos;
2039 if (MatchString("\"", ¤t)) {
2040 while (
2041 (MatchString("\\", ¤t) && MatchAnyChar(¤t)) ||
2042 MatchChar([](char c) { return c != '"' && c != '\n'; }, ¤t)) {
2043 }
2044 if (MatchString("\"", ¤t)) {
2045 *pos = current;
2046 return true;
2047 }
2048 }
2049 current = *pos;
2050 if (MatchString("'", ¤t)) {
2051 while (
2052 (MatchString("\\", ¤t) && MatchAnyChar(¤t)) ||
2053 MatchChar([](char c) { return c != '\'' && c != '\n'; }, ¤t)) {
2054 }
2055 if (MatchString("'", ¤t)) {
2056 *pos = current;
2057 return true;
2058 }
2059 }
2060 return false;
2061 }
2062
MatchHexLiteralv8::internal::torque::__anonf2940ded0111::TorqueGrammar2063 static bool MatchHexLiteral(InputPosition* pos) {
2064 InputPosition current = *pos;
2065 MatchString("-", ¤t);
2066 if (MatchString("0x", ¤t) && MatchChar(std::isxdigit, ¤t)) {
2067 while (MatchChar(std::isxdigit, ¤t)) {
2068 }
2069 *pos = current;
2070 return true;
2071 }
2072 return false;
2073 }
2074
MatchDecimalLiteralv8::internal::torque::__anonf2940ded0111::TorqueGrammar2075 static bool MatchDecimalLiteral(InputPosition* pos) {
2076 InputPosition current = *pos;
2077 bool found_digit = false;
2078 MatchString("-", ¤t);
2079 while (MatchChar(std::isdigit, ¤t)) found_digit = true;
2080 MatchString(".", ¤t);
2081 while (MatchChar(std::isdigit, ¤t)) found_digit = true;
2082 if (!found_digit) return false;
2083 *pos = current;
2084 if ((MatchString("e", ¤t) || MatchString("E", ¤t)) &&
2085 (MatchString("+", ¤t) || MatchString("-", ¤t) || true) &&
2086 MatchChar(std::isdigit, ¤t)) {
2087 while (MatchChar(std::isdigit, ¤t)) {
2088 }
2089 *pos = current;
2090 return true;
2091 }
2092 return true;
2093 }
2094
TorqueGrammarv8::internal::torque::__anonf2940ded0111::TorqueGrammar2095 TorqueGrammar() : Grammar(&file) { SetWhitespace(MatchWhitespace); }
2096
2097 // Result: Expression*
2098 Symbol* expression = &assignmentExpression;
2099
2100 // Result: std::string
2101 Symbol identifier = {Rule({Pattern(MatchIdentifier)}, YieldMatchedInput),
2102 Rule({Token("runtime")}, YieldMatchedInput)};
2103
2104 // Result: Identifier*
2105 Symbol name = {Rule({&identifier}, MakeIdentifier)};
2106
2107 // Result: Identifier*
2108 Symbol annotationName = {
2109 Rule({Pattern(MatchAnnotation)}, MakeIdentifierFromMatchedInput)};
2110
2111 // Result: std::string
2112 Symbol intrinsicName = {
2113 Rule({Pattern(MatchIntrinsicName)}, MakeIdentifierFromMatchedInput)};
2114
2115 // Result: std::string
2116 Symbol stringLiteral = {
2117 Rule({Pattern(MatchStringLiteral)}, YieldMatchedInput)};
2118
2119 // Result: std::string
2120 Symbol externalString = {Rule({&stringLiteral}, StringLiteralUnquoteAction)};
2121
2122 // Result: std::string
2123 Symbol decimalLiteral = {
2124 Rule({Pattern(MatchDecimalLiteral)}, YieldMatchedInput),
2125 Rule({Pattern(MatchHexLiteral)}, YieldMatchedInput)};
2126
2127 // Result: int32_t
2128 Symbol int32Literal = {Rule({&decimalLiteral}, MakeInt32)};
2129
2130 // Result: AnnotationParameter
2131 Symbol annotationParameter = {
2132 Rule({&identifier}, MakeStringAnnotationParameter),
2133 Rule({&int32Literal}, MakeIntAnnotationParameter),
2134 Rule({&externalString}, MakeStringAnnotationParameter)};
2135
2136 // Result: AnnotationParameter
2137 Symbol annotationParameters = {
2138 Rule({Token("("), &annotationParameter, Token(")")})};
2139
2140 // Result: Annotation
2141 Symbol annotation = {Rule(
2142 {&annotationName, Optional<AnnotationParameter>(&annotationParameters)},
2143 MakeAnnotation)};
2144
2145 // Result: std::vector<Annotation>
2146 Symbol* annotations = List<Annotation>(&annotation);
2147
2148 // Result: std::vector<std::string>
2149 Symbol namespaceQualification = {
2150 Rule({CheckIf(Token("::")),
2151 List<std::string>(Sequence({&identifier, Token("::")}))},
2152 MakeNamespaceQualification)};
2153
2154 // Result: TypeList
2155 Symbol* typeList = List<TypeExpression*>(&type, Token(","));
2156
2157 // Result: TypeExpression*
2158 Symbol simpleType = {
2159 Rule({Token("("), &type, Token(")")}),
2160 Rule({&namespaceQualification, CheckIf(Token("constexpr")), &identifier,
2161 TryOrDefault<std::vector<TypeExpression*>>(
2162 &genericSpecializationTypeList)},
2163 MakeBasicTypeExpression),
2164 Rule({Token("builtin"), Token("("), typeList, Token(")"), Token("=>"),
2165 &simpleType},
2166 MakeFunctionTypeExpression),
2167 Rule({CheckIf(Token("const")), Token("&"), &simpleType},
2168 MakeReferenceTypeExpression)};
2169
2170 // Result: TypeExpression*
2171 Symbol type = {Rule({&simpleType}), Rule({&type, Token("|"), &simpleType},
2172 MakeUnionTypeExpression)};
2173
2174 // Result: GenericParameter
2175 Symbol genericParameter = {
2176 Rule({&name, Token(":"), Token("type"),
2177 Optional<TypeExpression*>(Sequence({Token("extends"), &type}))},
2178 MakeGenericParameter)};
2179
2180 // Result: GenericParameters
2181 Symbol genericParameters = {
2182 Rule({Token("<"), List<GenericParameter>(&genericParameter, Token(",")),
2183 Token(">")})};
2184
2185 // Result: TypeList
2186 Symbol genericSpecializationTypeList = {
2187 Rule({Token("<"), typeList, Token(">")})};
2188
2189 // Result: base::Optional<GenericParameters>
2190 Symbol* optionalGenericParameters = Optional<TypeList>(&genericParameters);
2191
2192 Symbol implicitParameterList{
2193 Rule({Token("("), OneOf({"implicit", "js-implicit"}),
2194 List<NameAndTypeExpression>(&nameAndType, Token(",")), Token(")")},
2195 MakeImplicitParameterList)};
2196
2197 Symbol* optionalImplicitParameterList{
2198 Optional<ImplicitParameters>(&implicitParameterList)};
2199
2200 // Result: ParameterList
2201 Symbol typeListMaybeVarArgs = {
2202 Rule({optionalImplicitParameterList, Token("("),
2203 List<TypeExpression*>(Sequence({&type, Token(",")})), Token("..."),
2204 Token(")")},
2205 MakeParameterList<true, false>),
2206 Rule({optionalImplicitParameterList, Token("("), typeList, Token(")")},
2207 MakeParameterList<false, false>)};
2208
2209 // Result: LabelAndTypes
2210 Symbol labelParameter = {Rule(
2211 {&name,
2212 TryOrDefault<TypeList>(Sequence({Token("("), typeList, Token(")")}))},
2213 MakeLabelAndTypes)};
2214
2215 // Result: TypeExpression*
2216 Symbol optionalReturnType = {Rule({Token(":"), &type}),
2217 Rule({}, MakeVoidType)};
2218
2219 // Result: LabelAndTypesVector
2220 Symbol* optionalLabelList{TryOrDefault<LabelAndTypesVector>(
2221 Sequence({Token("labels"),
2222 NonemptyList<LabelAndTypes>(&labelParameter, Token(","))}))};
2223
2224 // Result: std::vector<Statement*>
2225 Symbol* optionalOtherwise{TryOrDefault<std::vector<Statement*>>(
2226 Sequence({Token("otherwise"),
2227 NonemptyList<Statement*>(&atomarStatement, Token(","))}))};
2228
2229 // Result: NameAndTypeExpression
2230 Symbol nameAndType = {Rule({&name, Token(":"), &type}, MakeNameAndType)};
2231
2232 // Result: base::Optional<Expression*>
2233 Symbol* optionalArraySpecifier =
2234 Optional<Expression*>(Sequence({Token("["), expression, Token("]")}));
2235
2236 // Result: ClassFieldExpression
2237 Symbol classField = {
2238 Rule({annotations, CheckIf(Token("weak")), CheckIf(Token("const")), &name,
2239 optionalArraySpecifier, Token(":"), &type, Token(";")},
2240 MakeClassField)};
2241
2242 // Result: StructFieldExpression
2243 Symbol structField = {
2244 Rule({CheckIf(Token("const")), &name, Token(":"), &type, Token(";")},
2245 MakeStructField)};
2246
2247 // Result: BitFieldDeclaration
2248 Symbol bitFieldDeclaration = {Rule({&name, Token(":"), &type, Token(":"),
2249 &int32Literal, Token("bit"), Token(";")},
2250 MakeBitFieldDeclaration)};
2251
2252 // Result: ParameterList
2253 Symbol parameterListNoVararg = {
2254 Rule({optionalImplicitParameterList, Token("("),
2255 List<NameAndTypeExpression>(&nameAndType, Token(",")), Token(")")},
2256 MakeParameterList<false, true>)};
2257
2258 // Result: ParameterList
2259 Symbol parameterListAllowVararg = {
2260 Rule({¶meterListNoVararg}),
2261 Rule({optionalImplicitParameterList, Token("("),
2262 List<NameAndTypeExpression>(Sequence({&nameAndType, Token(",")})),
2263 Token("..."), &identifier, Token(")")},
2264 MakeParameterList<true, true>)};
2265
2266 // Result: Identifier*
OneOfv8::internal::torque::__anonf2940ded0111::TorqueGrammar2267 Symbol* OneOf(const std::vector<std::string>& alternatives) {
2268 Symbol* result = NewSymbol();
2269 for (const std::string& s : alternatives) {
2270 result->AddRule(Rule({Token(s)}, MakeIdentifierFromMatchedInput));
2271 }
2272 return result;
2273 }
2274
2275 // Result: Expression*
BinaryOperatorv8::internal::torque::__anonf2940ded0111::TorqueGrammar2276 Symbol* BinaryOperator(Symbol* nextLevel, Symbol* op) {
2277 Symbol* result = NewSymbol();
2278 *result = {Rule({nextLevel}),
2279 Rule({result, op, nextLevel}, MakeBinaryOperator)};
2280 return result;
2281 }
2282
2283 // Result: IncrementDecrementOperator
2284 Symbol incrementDecrementOperator = {
2285 Rule({Token("++")},
2286 YieldIntegralConstant<IncrementDecrementOperator,
2287 IncrementDecrementOperator::kIncrement>),
2288 Rule({Token("--")},
2289 YieldIntegralConstant<IncrementDecrementOperator,
2290 IncrementDecrementOperator::kDecrement>)};
2291
2292 // Result: Expression*
2293 Symbol identifierExpression = {
2294 Rule({&namespaceQualification, &name,
2295 TryOrDefault<TypeList>(&genericSpecializationTypeList)},
2296 MakeIdentifierExpression),
2297 };
2298
2299 // Result: std::vector<Expression*>
2300 Symbol argumentList = {Rule(
2301 {Token("("), List<Expression*>(expression, Token(",")), Token(")")})};
2302
2303 // Result: Expression*
2304 Symbol callExpression = {Rule(
2305 {&identifierExpression, &argumentList, optionalOtherwise}, MakeCall)};
2306
2307 // Result: Expression*
2308 Symbol callMethodExpression = {
2309 Rule({&primaryExpression, Token("."), &identifier, &argumentList,
2310 optionalOtherwise},
2311 MakeMethodCall)};
2312
2313 // Result: NameAndExpression
2314 Symbol namedExpression = {
2315 Rule({&name, Token(":"), expression}, MakeNameAndExpression),
2316 Rule({expression}, MakeNameAndExpressionFromExpression)};
2317
2318 // Result: std::vector<NameAndExpression>
2319 Symbol initializerList = {
2320 Rule({Token("{"), List<NameAndExpression>(&namedExpression, Token(",")),
2321 Token("}")})};
2322
2323 // Result: Expression*
2324 Symbol intrinsicCallExpression = {Rule(
2325 {&intrinsicName, TryOrDefault<TypeList>(&genericSpecializationTypeList),
2326 &argumentList},
2327 MakeIntrinsicCallExpression)};
2328
2329 // Result: Expression*
2330 Symbol newExpression = {
2331 Rule({Token("new"),
2332 CheckIf(Sequence({Token("("), Token("Pretenured"), Token(")")})),
2333 &simpleType, &initializerList},
2334 MakeNewExpression)};
2335
2336 // Result: Expression*
2337 Symbol primaryExpression = {
2338 Rule({&callExpression}),
2339 Rule({&callMethodExpression}),
2340 Rule({&intrinsicCallExpression}),
2341 Rule({&identifierExpression}),
2342 Rule({&primaryExpression, Token("."), &name}, MakeFieldAccessExpression),
2343 Rule({&primaryExpression, Token("->"), &name},
2344 MakeReferenceFieldAccessExpression),
2345 Rule({&primaryExpression, Token("["), expression, Token("]")},
2346 MakeElementAccessExpression),
2347 Rule({&decimalLiteral}, MakeNumberLiteralExpression),
2348 Rule({&stringLiteral}, MakeStringLiteralExpression),
2349 Rule({&simpleType, &initializerList}, MakeStructExpression),
2350 Rule({&newExpression}),
2351 Rule({Token("("), expression, Token(")")})};
2352
2353 // Result: Expression*
2354 Symbol unaryExpression = {
2355 Rule({&primaryExpression}),
2356 Rule({OneOf({"+", "-", "!", "~", "&"}), &unaryExpression},
2357 MakeUnaryOperator),
2358 Rule({Token("*"), &unaryExpression}, MakeDereferenceExpression),
2359 Rule({Token("..."), &unaryExpression}, MakeSpreadExpression),
2360 Rule({&incrementDecrementOperator, &unaryExpression},
2361 MakeIncrementDecrementExpressionPrefix),
2362 Rule({&unaryExpression, &incrementDecrementOperator},
2363 MakeIncrementDecrementExpressionPostfix)};
2364
2365 // Result: Expression*
2366 Symbol* multiplicativeExpression =
2367 BinaryOperator(&unaryExpression, OneOf({"*", "/", "%"}));
2368
2369 // Result: Expression*
2370 Symbol* additiveExpression =
2371 BinaryOperator(multiplicativeExpression, OneOf({"+", "-"}));
2372
2373 // Result: Identifier*
2374 Symbol shiftOperator = {
2375 Rule({Token("<<")}, MakeIdentifierFromMatchedInput),
2376 Rule({Token(">"), Token(">")}, MakeRightShiftIdentifier),
2377 Rule({Token(">"), Token(">"), Token(">")}, MakeRightShiftIdentifier)};
2378
2379 // Result: Expression*
2380 Symbol* shiftExpression = BinaryOperator(additiveExpression, &shiftOperator);
2381
2382 // Do not allow expressions like a < b > c because this is never
2383 // useful and ambiguous with template parameters.
2384 // Result: Expression*
2385 Symbol relationalExpression = {
2386 Rule({shiftExpression}),
2387 Rule({shiftExpression, OneOf({"<", ">", "<=", ">="}), shiftExpression},
2388 MakeBinaryOperator)};
2389
2390 // Result: Expression*
2391 Symbol* equalityExpression =
2392 BinaryOperator(&relationalExpression, OneOf({"==", "!="}));
2393
2394 // Result: Expression*
2395 Symbol* bitwiseExpression =
2396 BinaryOperator(equalityExpression, OneOf({"&", "|"}));
2397
2398 // Result: Expression*
2399 Symbol logicalAndExpression = {
2400 Rule({bitwiseExpression}),
2401 Rule({&logicalAndExpression, Token("&&"), bitwiseExpression},
2402 MakeLogicalAndExpression)};
2403
2404 // Result: Expression*
2405 Symbol logicalOrExpression = {
2406 Rule({&logicalAndExpression}),
2407 Rule({&logicalOrExpression, Token("||"), &logicalAndExpression},
2408 MakeLogicalOrExpression)};
2409
2410 // Result: Expression*
2411 Symbol conditionalExpression = {
2412 Rule({&logicalOrExpression}),
2413 Rule({&logicalOrExpression, Token("?"), expression, Token(":"),
2414 &conditionalExpression},
2415 MakeConditionalExpression)};
2416
2417 // Result: base::Optional<std::string>
2418 Symbol assignmentOperator = {
2419 Rule({Token("=")}, YieldDefaultValue<base::Optional<std::string>>),
2420 Rule({OneOf({"*=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=",
2421 "^=", "|="})},
2422 ExtractAssignmentOperator)};
2423
2424 // Result: Expression*
2425 Symbol assignmentExpression = {
2426 Rule({&conditionalExpression}),
2427 Rule({&conditionalExpression, &assignmentOperator, &assignmentExpression},
2428 MakeAssignmentExpression)};
2429
2430 // Result: Statement*
2431 Symbol block = {Rule({CheckIf(Token("deferred")), Token("{"),
2432 List<Statement*>(&statement), Token("}")},
2433 MakeBlockStatement)};
2434
2435 // Result: TryHandler*
2436 Symbol tryHandler = {
2437 Rule({Token("label"), &name,
2438 TryOrDefault<ParameterList>(¶meterListNoVararg), &block},
2439 MakeLabelBlock),
2440 Rule({Token("catch"), Token("("), &identifier, Token(")"), &block},
2441 MakeCatchBlock)};
2442
2443 // Result: ExpressionWithSource
2444 Symbol expressionWithSource = {Rule({expression}, MakeExpressionWithSource)};
2445
2446 Symbol* optionalTypeSpecifier =
2447 Optional<TypeExpression*>(Sequence({Token(":"), &type}));
2448
2449 // Result: EnumEntry
2450 Symbol enumEntry = {Rule({&name, optionalTypeSpecifier}, MakeEnumEntry)};
2451
2452 // Result: Statement*
2453 Symbol varDeclaration = {
2454 Rule({OneOf({"let", "const"}), &name, optionalTypeSpecifier},
2455 MakeVarDeclarationStatement)};
2456
2457 // Result: Statement*
2458 Symbol varDeclarationWithInitialization = {
2459 Rule({OneOf({"let", "const"}), &name, optionalTypeSpecifier, Token("="),
2460 expression},
2461 MakeVarDeclarationStatement)};
2462
2463 // Result: Statement*
2464 Symbol atomarStatement = {
2465 Rule({expression}, MakeExpressionStatement),
2466 Rule({Token("return"), Optional<Expression*>(expression)},
2467 MakeReturnStatement),
2468 Rule({Token("tail"), &callExpression}, MakeTailCallStatement),
2469 Rule({Token("break")}, MakeBreakStatement),
2470 Rule({Token("continue")}, MakeContinueStatement),
2471 Rule({Token("goto"), &name,
2472 TryOrDefault<std::vector<Expression*>>(&argumentList)},
2473 MakeGotoStatement),
2474 Rule({OneOf({"debug", "unreachable"})}, MakeDebugStatement)};
2475
2476 // Result: Statement*
2477 Symbol statement = {
2478 Rule({&block}),
2479 Rule({&atomarStatement, Token(";")}),
2480 Rule({&varDeclaration, Token(";")}),
2481 Rule({&varDeclarationWithInitialization, Token(";")}),
2482 Rule({Token("if"), CheckIf(Token("constexpr")), Token("("), expression,
2483 Token(")"), &statement,
2484 Optional<Statement*>(Sequence({Token("else"), &statement}))},
2485 MakeIfStatement),
2486 Rule(
2487 {
2488 Token("typeswitch"),
2489 Token("("),
2490 expression,
2491 Token(")"),
2492 Token("{"),
2493 NonemptyList<TypeswitchCase>(&typeswitchCase),
2494 Token("}"),
2495 },
2496 MakeTypeswitchStatement),
2497 Rule({Token("try"), &block, List<TryHandler*>(&tryHandler)},
2498 MakeTryLabelExpression),
2499 Rule({OneOf({"assert", "check", "static_assert"}), Token("("),
2500 &expressionWithSource, Token(")"), Token(";")},
2501 MakeAssertStatement),
2502 Rule({Token("while"), Token("("), expression, Token(")"), &statement},
2503 MakeWhileStatement),
2504 Rule({Token("for"), Token("("),
2505 Optional<Statement*>(&varDeclarationWithInitialization), Token(";"),
2506 Optional<Expression*>(expression), Token(";"),
2507 Optional<Expression*>(expression), Token(")"), &statement},
2508 MakeForLoopStatement)};
2509
2510 // Result: TypeswitchCase
2511 Symbol typeswitchCase = {
2512 Rule({Token("case"), Token("("),
2513 Optional<std::string>(Sequence({&identifier, Token(":")})), &type,
2514 Token(")"), Token(":"), &block},
2515 MakeTypeswitchCase)};
2516
2517 // Result: base::Optional<Statement*>
2518 Symbol optionalBody = {
2519 Rule({&block}, CastParseResult<Statement*, base::Optional<Statement*>>),
2520 Rule({Token(";")}, YieldDefaultValue<base::Optional<Statement*>>)};
2521
2522 // Result: Declaration*
2523 Symbol method = {Rule(
2524 {CheckIf(Token("transitioning")),
2525 Optional<std::string>(Sequence({Token("operator"), &externalString})),
2526 Token("macro"), &name, ¶meterListNoVararg, &optionalReturnType,
2527 optionalLabelList, &block},
2528 MakeMethodDeclaration)};
2529
2530 // Result: base::Optional<ClassBody*>
2531 Symbol optionalClassBody = {
2532 Rule({Token("{"), List<Declaration*>(&method),
2533 List<ClassFieldExpression>(&classField), Token("}")},
2534 MakeClassBody),
2535 Rule({Token(";")}, YieldDefaultValue<base::Optional<ClassBody*>>)};
2536
2537 // Result: std::vector<Declaration*>
2538 Symbol declaration = {
2539 Rule({Token("const"), &name, Token(":"), &type, Token("="), expression,
2540 Token(";")},
2541 AsSingletonVector<Declaration*, MakeConstDeclaration>()),
2542 Rule({Token("const"), &name, Token(":"), &type, Token("generates"),
2543 &externalString, Token(";")},
2544 AsSingletonVector<Declaration*, MakeExternConstDeclaration>()),
2545 Rule({annotations, CheckIf(Token("extern")), CheckIf(Token("transient")),
2546 OneOf({"class", "shape"}), &name, Token("extends"), &type,
2547 Optional<std::string>(
2548 Sequence({Token("generates"), &externalString})),
2549 &optionalClassBody},
2550 MakeClassDeclaration),
2551 Rule({annotations, Token("struct"), &name,
2552 TryOrDefault<GenericParameters>(&genericParameters), Token("{"),
2553 List<Declaration*>(&method),
2554 List<StructFieldExpression>(&structField), Token("}")},
2555 AsSingletonVector<Declaration*, MakeStructDeclaration>()),
2556 Rule({Token("bitfield"), Token("struct"), &name, Token("extends"), &type,
2557 Token("{"), List<BitFieldDeclaration>(&bitFieldDeclaration),
2558 Token("}")},
2559 AsSingletonVector<Declaration*, MakeBitFieldStructDeclaration>()),
2560 Rule({annotations, CheckIf(Token("transient")), Token("type"), &name,
2561 TryOrDefault<GenericParameters>(&genericParameters),
2562 Optional<TypeExpression*>(Sequence({Token("extends"), &type})),
2563 Optional<std::string>(
2564 Sequence({Token("generates"), &externalString})),
2565 Optional<std::string>(
2566 Sequence({Token("constexpr"), &externalString})),
2567 Token(";")},
2568 MakeAbstractTypeDeclaration),
2569 Rule({Token("type"), &name, Token("="), &type, Token(";")},
2570 AsSingletonVector<Declaration*, MakeTypeAliasDeclaration>()),
2571 Rule({Token("intrinsic"), &intrinsicName,
2572 TryOrDefault<GenericParameters>(&genericParameters),
2573 ¶meterListNoVararg, &optionalReturnType, &optionalBody},
2574 AsSingletonVector<Declaration*, MakeIntrinsicDeclaration>()),
2575 Rule({Token("extern"), CheckIf(Token("transitioning")),
2576 Optional<std::string>(
2577 Sequence({Token("operator"), &externalString})),
2578 Token("macro"),
2579 Optional<std::string>(Sequence({&identifier, Token("::")})), &name,
2580 TryOrDefault<GenericParameters>(&genericParameters),
2581 &typeListMaybeVarArgs, &optionalReturnType, optionalLabelList,
2582 Token(";")},
2583 AsSingletonVector<Declaration*, MakeExternalMacro>()),
2584 Rule({Token("extern"), CheckIf(Token("transitioning")),
2585 CheckIf(Token("javascript")), Token("builtin"), &name,
2586 TryOrDefault<GenericParameters>(&genericParameters),
2587 &typeListMaybeVarArgs, &optionalReturnType, Token(";")},
2588 AsSingletonVector<Declaration*, MakeExternalBuiltin>()),
2589 Rule({Token("extern"), CheckIf(Token("transitioning")), Token("runtime"),
2590 &name, &typeListMaybeVarArgs, &optionalReturnType, Token(";")},
2591 AsSingletonVector<Declaration*, MakeExternalRuntime>()),
2592 Rule({annotations, CheckIf(Token("transitioning")),
2593 Optional<std::string>(
2594 Sequence({Token("operator"), &externalString})),
2595 Token("macro"), &name,
2596 TryOrDefault<GenericParameters>(&genericParameters),
2597 ¶meterListNoVararg, &optionalReturnType, optionalLabelList,
2598 &optionalBody},
2599 AsSingletonVector<Declaration*, MakeTorqueMacroDeclaration>()),
2600 Rule({CheckIf(Token("transitioning")), CheckIf(Token("javascript")),
2601 Token("builtin"), &name,
2602 TryOrDefault<GenericParameters>(&genericParameters),
2603 ¶meterListAllowVararg, &optionalReturnType, &optionalBody},
2604 AsSingletonVector<Declaration*, MakeTorqueBuiltinDeclaration>()),
2605 Rule({CheckIf(Token("transitioning")), &name,
2606 &genericSpecializationTypeList, ¶meterListAllowVararg,
2607 &optionalReturnType, optionalLabelList, &block},
2608 AsSingletonVector<Declaration*, MakeSpecializationDeclaration>()),
2609 Rule({Token("#include"), &externalString},
2610 AsSingletonVector<Declaration*, MakeCppIncludeDeclaration>()),
2611 Rule({CheckIf(Token("extern")), Token("enum"), &name,
2612 Optional<TypeExpression*>(Sequence({Token("extends"), &type})),
2613 Optional<std::string>(
2614 Sequence({Token("constexpr"), &externalString})),
2615 Token("{"), NonemptyList<EnumEntry>(&enumEntry, Token(",")),
2616 CheckIf(Sequence({Token(","), Token("...")})), Token("}")},
2617 MakeEnumDeclaration),
2618 Rule({Token("namespace"), &identifier, Token("{"), &declarationList,
2619 Token("}")},
2620 AsSingletonVector<Declaration*, MakeNamespaceDeclaration>())};
2621
2622 // Result: std::vector<Declaration*>
2623 Symbol declarationList = {
2624 Rule({List<std::vector<Declaration*>>(&declaration)}, ConcatList)};
2625
2626 Symbol file = {Rule({&file, Token("import"), &externalString},
2627 ProcessTorqueImportDeclaration),
2628 Rule({&file, &declaration}, AddGlobalDeclarations), Rule({})};
2629 };
2630
2631 } // namespace
2632
ParseTorque(const std::string & input)2633 void ParseTorque(const std::string& input) {
2634 BuildFlags::Scope build_flags_scope;
2635 TorqueGrammar().Parse(input);
2636 }
2637
2638 } // namespace torque
2639 } // namespace internal
2640 } // namespace v8
2641