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 <cctype>
6 
7 #include "src/torque/earley-parser.h"
8 #include "src/torque/torque-parser.h"
9 #include "src/torque/utils.h"
10 
11 namespace v8 {
12 namespace internal {
13 namespace torque {
14 
15 DEFINE_CONTEXTUAL_VARIABLE(CurrentAst);
16 
17 using TypeList = std::vector<TypeExpression*>;
18 using GenericParameters = std::vector<std::string>;
19 
20 struct ExpressionWithSource {
21   Expression* expression;
22   std::string source;
23 };
24 
25 struct TypeswitchCase {
26   SourcePosition pos;
27   base::Optional<std::string> name;
28   TypeExpression* type;
29   Statement* block;
30 };
31 
32 enum class ParseResultHolderBase::TypeId {
33   kStdString,
34   kBool,
35   kStdVectorOfString,
36   kExpressionPtr,
37   kLocationExpressionPtr,
38   kStatementPtr,
39   kDeclarationPtr,
40   kTypeExpressionPtr,
41   kLabelBlockPtr,
42   kNameAndTypeExpression,
43   kStdVectorOfNameAndTypeExpression,
44   kIncrementDecrementOperator,
45   kOptionalStdString,
46   kStdVectorOfStatementPtr,
47   kStdVectorOfDeclarationPtr,
48   kStdVectorOfExpressionPtr,
49   kExpressionWithSource,
50   kParameterList,
51   kRangeExpression,
52   kOptionalRangeExpression,
53   kTypeList,
54   kOptionalTypeList,
55   kLabelAndTypes,
56   kStdVectorOfLabelAndTypes,
57   kStdVectorOfLabelBlockPtr,
58   kOptionalStatementPtr,
59   kOptionalExpressionPtr,
60   kTypeswitchCase,
61   kStdVectorOfTypeswitchCase
62 };
63 
64 template <>
65 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<std::string>::id =
66     ParseResultTypeId::kStdString;
67 template <>
68 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<bool>::id =
69     ParseResultTypeId::kBool;
70 template <>
71 V8_EXPORT_PRIVATE const ParseResultTypeId
72     ParseResultHolder<std::vector<std::string>>::id =
73         ParseResultTypeId::kStdVectorOfString;
74 template <>
75 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Declaration*>::id =
76     ParseResultTypeId::kDeclarationPtr;
77 template <>
78 V8_EXPORT_PRIVATE const ParseResultTypeId
79     ParseResultHolder<TypeExpression*>::id =
80         ParseResultTypeId::kTypeExpressionPtr;
81 template <>
82 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<LabelBlock*>::id =
83     ParseResultTypeId::kLabelBlockPtr;
84 template <>
85 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Expression*>::id =
86     ParseResultTypeId::kExpressionPtr;
87 template <>
88 V8_EXPORT_PRIVATE const ParseResultTypeId
89     ParseResultHolder<LocationExpression*>::id =
90         ParseResultTypeId::kLocationExpressionPtr;
91 template <>
92 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<Statement*>::id =
93     ParseResultTypeId::kStatementPtr;
94 template <>
95 V8_EXPORT_PRIVATE const ParseResultTypeId
96     ParseResultHolder<NameAndTypeExpression>::id =
97         ParseResultTypeId::kNameAndTypeExpression;
98 template <>
99 V8_EXPORT_PRIVATE const ParseResultTypeId
100     ParseResultHolder<std::vector<NameAndTypeExpression>>::id =
101         ParseResultTypeId::kStdVectorOfNameAndTypeExpression;
102 template <>
103 V8_EXPORT_PRIVATE const ParseResultTypeId
104     ParseResultHolder<IncrementDecrementOperator>::id =
105         ParseResultTypeId::kIncrementDecrementOperator;
106 template <>
107 V8_EXPORT_PRIVATE const ParseResultTypeId
108     ParseResultHolder<base::Optional<std::string>>::id =
109         ParseResultTypeId::kOptionalStdString;
110 template <>
111 V8_EXPORT_PRIVATE const ParseResultTypeId
112     ParseResultHolder<std::vector<Statement*>>::id =
113         ParseResultTypeId::kStdVectorOfStatementPtr;
114 template <>
115 V8_EXPORT_PRIVATE const ParseResultTypeId
116     ParseResultHolder<std::vector<Declaration*>>::id =
117         ParseResultTypeId::kStdVectorOfDeclarationPtr;
118 template <>
119 V8_EXPORT_PRIVATE const ParseResultTypeId
120     ParseResultHolder<std::vector<Expression*>>::id =
121         ParseResultTypeId::kStdVectorOfExpressionPtr;
122 template <>
123 V8_EXPORT_PRIVATE const ParseResultTypeId
124     ParseResultHolder<ExpressionWithSource>::id =
125         ParseResultTypeId::kExpressionWithSource;
126 template <>
127 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<ParameterList>::id =
128     ParseResultTypeId::kParameterList;
129 template <>
130 V8_EXPORT_PRIVATE const ParseResultTypeId
131     ParseResultHolder<RangeExpression>::id =
132         ParseResultTypeId::kRangeExpression;
133 template <>
134 V8_EXPORT_PRIVATE const ParseResultTypeId
135     ParseResultHolder<base::Optional<RangeExpression>>::id =
136         ParseResultTypeId::kOptionalRangeExpression;
137 template <>
138 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<TypeList>::id =
139     ParseResultTypeId::kTypeList;
140 template <>
141 V8_EXPORT_PRIVATE const ParseResultTypeId
142     ParseResultHolder<base::Optional<TypeList>>::id =
143         ParseResultTypeId::kOptionalTypeList;
144 template <>
145 V8_EXPORT_PRIVATE const ParseResultTypeId ParseResultHolder<LabelAndTypes>::id =
146     ParseResultTypeId::kLabelAndTypes;
147 template <>
148 V8_EXPORT_PRIVATE const ParseResultTypeId
149     ParseResultHolder<std::vector<LabelAndTypes>>::id =
150         ParseResultTypeId::kStdVectorOfLabelAndTypes;
151 template <>
152 V8_EXPORT_PRIVATE const ParseResultTypeId
153     ParseResultHolder<std::vector<LabelBlock*>>::id =
154         ParseResultTypeId::kStdVectorOfLabelBlockPtr;
155 template <>
156 V8_EXPORT_PRIVATE const ParseResultTypeId
157     ParseResultHolder<base::Optional<Statement*>>::id =
158         ParseResultTypeId::kOptionalStatementPtr;
159 template <>
160 V8_EXPORT_PRIVATE const ParseResultTypeId
161     ParseResultHolder<base::Optional<Expression*>>::id =
162         ParseResultTypeId::kOptionalExpressionPtr;
163 template <>
164 V8_EXPORT_PRIVATE const ParseResultTypeId
165     ParseResultHolder<TypeswitchCase>::id = ParseResultTypeId::kTypeswitchCase;
166 template <>
167 V8_EXPORT_PRIVATE const ParseResultTypeId
168     ParseResultHolder<std::vector<TypeswitchCase>>::id =
169         ParseResultTypeId::kStdVectorOfTypeswitchCase;
170 
171 namespace {
172 
AddGlobalDeclaration(ParseResultIterator * child_results)173 base::Optional<ParseResult> AddGlobalDeclaration(
174     ParseResultIterator* child_results) {
175   auto declaration = child_results->NextAs<Declaration*>();
176   CurrentAst::Get().declarations().push_back(declaration);
177   return base::nullopt;
178 }
179 
180 template <class T, class... Args>
MakeNode(Args...args)181 T* MakeNode(Args... args) {
182   return CurrentAst::Get().AddNode(std::unique_ptr<T>(
183       new T(CurrentSourcePosition::Get(), std::move(args)...)));
184 }
185 
MakeCall(ParseResultIterator * child_results)186 base::Optional<ParseResult> MakeCall(ParseResultIterator* child_results) {
187   auto callee = child_results->NextAs<std::string>();
188   auto generic_args = child_results->NextAs<TypeList>();
189   auto args = child_results->NextAs<std::vector<Expression*>>();
190   auto labels = child_results->NextAs<std::vector<std::string>>();
191   Expression* result =
192       MakeNode<CallExpression>(callee, false, generic_args, args, labels);
193   return ParseResult{result};
194 }
195 
MakeBinaryOperator(ParseResultIterator * child_results)196 base::Optional<ParseResult> MakeBinaryOperator(
197     ParseResultIterator* child_results) {
198   auto left = child_results->NextAs<Expression*>();
199   auto op = child_results->NextAs<std::string>();
200   auto right = child_results->NextAs<Expression*>();
201   Expression* result = MakeNode<CallExpression>(
202       op, true, TypeList{}, std::vector<Expression*>{left, right},
203       std::vector<std::string>{});
204   return ParseResult{result};
205 }
206 
MakeUnaryOperator(ParseResultIterator * child_results)207 base::Optional<ParseResult> MakeUnaryOperator(
208     ParseResultIterator* child_results) {
209   auto op = child_results->NextAs<std::string>();
210   auto e = child_results->NextAs<Expression*>();
211   Expression* result = MakeNode<CallExpression>(op, true, TypeList{},
212                                                 std::vector<Expression*>{e},
213                                                 std::vector<std::string>{});
214   return ParseResult{result};
215 }
216 
217 template <bool has_varargs>
MakeParameterListFromTypes(ParseResultIterator * child_results)218 base::Optional<ParseResult> MakeParameterListFromTypes(
219     ParseResultIterator* child_results) {
220   auto types = child_results->NextAs<TypeList>();
221   ParameterList result;
222   result.types = std::move(types);
223   result.has_varargs = has_varargs;
224   return ParseResult{std::move(result)};
225 }
226 template <bool has_varargs>
MakeParameterListFromNameAndTypeList(ParseResultIterator * child_results)227 base::Optional<ParseResult> MakeParameterListFromNameAndTypeList(
228     ParseResultIterator* child_results) {
229   auto params = child_results->NextAs<std::vector<NameAndTypeExpression>>();
230   std::string arguments_variable = "";
231   if (child_results->HasNext()) {
232     arguments_variable = child_results->NextAs<std::string>();
233   }
234   ParameterList result;
235   for (NameAndTypeExpression& pair : params) {
236     result.names.push_back(std::move(pair.name));
237     result.types.push_back(pair.type);
238   }
239   result.has_varargs = has_varargs;
240   result.arguments_variable = arguments_variable;
241   return ParseResult{std::move(result)};
242 }
243 
MakeAssertStatement(ParseResultIterator * child_results)244 base::Optional<ParseResult> MakeAssertStatement(
245     ParseResultIterator* child_results) {
246   auto kind = child_results->NextAs<std::string>();
247   auto expr_with_source = child_results->NextAs<ExpressionWithSource>();
248   DCHECK(kind == "assert" || kind == "check");
249   Statement* result = MakeNode<AssertStatement>(
250       kind == "assert", expr_with_source.expression, expr_with_source.source);
251   return ParseResult{result};
252 }
253 
MakeDebugStatement(ParseResultIterator * child_results)254 base::Optional<ParseResult> MakeDebugStatement(
255     ParseResultIterator* child_results) {
256   auto kind = child_results->NextAs<std::string>();
257   DCHECK(kind == "unreachable" || kind == "debug");
258   Statement* result = MakeNode<DebugStatement>(kind, kind == "unreachable");
259   return ParseResult{result};
260 }
261 
MakeVoidType(ParseResultIterator * child_results)262 base::Optional<ParseResult> MakeVoidType(ParseResultIterator* child_results) {
263   TypeExpression* result = MakeNode<BasicTypeExpression>(false, "void");
264   return ParseResult{result};
265 }
266 
MakeExternalMacro(ParseResultIterator * child_results)267 base::Optional<ParseResult> MakeExternalMacro(
268     ParseResultIterator* child_results) {
269   auto operator_name = child_results->NextAs<base::Optional<std::string>>();
270   auto name = child_results->NextAs<std::string>();
271   auto generic_parameters = child_results->NextAs<GenericParameters>();
272   auto args = child_results->NextAs<ParameterList>();
273   auto return_type = child_results->NextAs<TypeExpression*>();
274   auto labels = child_results->NextAs<LabelAndTypesVector>();
275   MacroDeclaration* macro = MakeNode<ExternalMacroDeclaration>(
276       name, operator_name, args, return_type, labels);
277   Declaration* result;
278   if (generic_parameters.empty()) {
279     result = MakeNode<StandardDeclaration>(macro, nullptr);
280   } else {
281     result = MakeNode<GenericDeclaration>(macro, generic_parameters);
282   }
283   return ParseResult{result};
284 }
285 
MakeTorqueMacroDeclaration(ParseResultIterator * child_results)286 base::Optional<ParseResult> MakeTorqueMacroDeclaration(
287     ParseResultIterator* child_results) {
288   auto operator_name = child_results->NextAs<base::Optional<std::string>>();
289   auto name = child_results->NextAs<std::string>();
290   auto generic_parameters = child_results->NextAs<GenericParameters>();
291   auto args = child_results->NextAs<ParameterList>();
292   auto return_type = child_results->NextAs<TypeExpression*>();
293   auto labels = child_results->NextAs<LabelAndTypesVector>();
294   auto body = child_results->NextAs<base::Optional<Statement*>>();
295   MacroDeclaration* macro = MakeNode<TorqueMacroDeclaration>(
296       name, operator_name, args, return_type, labels);
297   Declaration* result;
298   if (generic_parameters.empty()) {
299     if (!body) ReportError("A non-generic declaration needs a body.");
300     result = MakeNode<StandardDeclaration>(macro, *body);
301   } else {
302     result = MakeNode<GenericDeclaration>(macro, generic_parameters, body);
303   }
304   return ParseResult{result};
305 }
306 
MakeTorqueBuiltinDeclaration(ParseResultIterator * child_results)307 base::Optional<ParseResult> MakeTorqueBuiltinDeclaration(
308     ParseResultIterator* child_results) {
309   auto javascript_linkage = child_results->NextAs<bool>();
310   auto name = child_results->NextAs<std::string>();
311   auto generic_parameters = child_results->NextAs<GenericParameters>();
312   auto args = child_results->NextAs<ParameterList>();
313   auto return_type = child_results->NextAs<TypeExpression*>();
314   auto body = child_results->NextAs<base::Optional<Statement*>>();
315   BuiltinDeclaration* builtin = MakeNode<TorqueBuiltinDeclaration>(
316       javascript_linkage, name, args, return_type);
317   Declaration* result;
318   if (generic_parameters.empty()) {
319     if (!body) ReportError("A non-generic declaration needs a body.");
320     result = MakeNode<StandardDeclaration>(builtin, *body);
321   } else {
322     result = MakeNode<GenericDeclaration>(builtin, generic_parameters, body);
323   }
324   return ParseResult{result};
325 }
326 
MakeConstDeclaration(ParseResultIterator * child_results)327 base::Optional<ParseResult> MakeConstDeclaration(
328     ParseResultIterator* child_results) {
329   auto name = child_results->NextAs<std::string>();
330   auto type = child_results->NextAs<TypeExpression*>();
331   auto expression = child_results->NextAs<Expression*>();
332   Declaration* result =
333       MakeNode<ConstDeclaration>(std::move(name), type, expression);
334   return ParseResult{result};
335 }
336 
MakeExternConstDeclaration(ParseResultIterator * child_results)337 base::Optional<ParseResult> MakeExternConstDeclaration(
338     ParseResultIterator* child_results) {
339   auto name = child_results->NextAs<std::string>();
340   auto type = child_results->NextAs<TypeExpression*>();
341   auto literal = child_results->NextAs<std::string>();
342   Declaration* result = MakeNode<ExternConstDeclaration>(std::move(name), type,
343                                                          std::move(literal));
344   return ParseResult{result};
345 }
346 
MakeTypeAliasDeclaration(ParseResultIterator * child_results)347 base::Optional<ParseResult> MakeTypeAliasDeclaration(
348     ParseResultIterator* child_results) {
349   auto name = child_results->NextAs<std::string>();
350   auto type = child_results->NextAs<TypeExpression*>();
351   Declaration* result = MakeNode<TypeAliasDeclaration>(std::move(name), type);
352   return ParseResult{result};
353 }
354 
MakeTypeDeclaration(ParseResultIterator * child_results)355 base::Optional<ParseResult> MakeTypeDeclaration(
356     ParseResultIterator* child_results) {
357   auto name = child_results->NextAs<std::string>();
358   auto extends = child_results->NextAs<base::Optional<std::string>>();
359   auto generates = child_results->NextAs<base::Optional<std::string>>();
360   auto constexpr_generates =
361       child_results->NextAs<base::Optional<std::string>>();
362   Declaration* result = MakeNode<TypeDeclaration>(
363       std::move(name), std::move(extends), std::move(generates),
364       std::move(constexpr_generates));
365   return ParseResult{result};
366 }
367 
MakeExplicitModuleDeclaration(ParseResultIterator * child_results)368 base::Optional<ParseResult> MakeExplicitModuleDeclaration(
369     ParseResultIterator* child_results) {
370   auto name = child_results->NextAs<std::string>();
371   auto declarations = child_results->NextAs<std::vector<Declaration*>>();
372   Declaration* result = MakeNode<ExplicitModuleDeclaration>(
373       std::move(name), std::move(declarations));
374   return ParseResult{result};
375 }
376 
MakeSpecializationDeclaration(ParseResultIterator * child_results)377 base::Optional<ParseResult> MakeSpecializationDeclaration(
378     ParseResultIterator* child_results) {
379   auto name = child_results->NextAs<std::string>();
380   auto generic_parameters =
381       child_results->NextAs<std::vector<TypeExpression*>>();
382   auto parameters = child_results->NextAs<ParameterList>();
383   auto return_type = child_results->NextAs<TypeExpression*>();
384   auto labels = child_results->NextAs<LabelAndTypesVector>();
385   auto body = child_results->NextAs<Statement*>();
386   Declaration* result = MakeNode<SpecializationDeclaration>(
387       std::move(name), std::move(generic_parameters), std::move(parameters),
388       return_type, std::move(labels), body);
389   return ParseResult{result};
390 }
391 
MakeStructDeclaration(ParseResultIterator * child_results)392 base::Optional<ParseResult> MakeStructDeclaration(
393     ParseResultIterator* child_results) {
394   auto name = child_results->NextAs<std::string>();
395   auto fields = child_results->NextAs<std::vector<NameAndTypeExpression>>();
396   Declaration* result =
397       MakeNode<StructDeclaration>(std::move(name), std::move(fields));
398   return ParseResult{result};
399 }
400 
MakeExternalBuiltin(ParseResultIterator * child_results)401 base::Optional<ParseResult> MakeExternalBuiltin(
402     ParseResultIterator* child_results) {
403   auto js_linkage = child_results->NextAs<bool>();
404   auto name = child_results->NextAs<std::string>();
405   auto generic_parameters = child_results->NextAs<GenericParameters>();
406   auto args = child_results->NextAs<ParameterList>();
407   auto return_type = child_results->NextAs<TypeExpression*>();
408   BuiltinDeclaration* builtin =
409       MakeNode<ExternalBuiltinDeclaration>(js_linkage, name, args, return_type);
410   Declaration* result;
411   if (generic_parameters.empty()) {
412     result = MakeNode<StandardDeclaration>(builtin, nullptr);
413   } else {
414     result = MakeNode<GenericDeclaration>(builtin, generic_parameters);
415   }
416   return ParseResult{result};
417 }
418 
MakeExternalRuntime(ParseResultIterator * child_results)419 base::Optional<ParseResult> MakeExternalRuntime(
420     ParseResultIterator* child_results) {
421   auto name = child_results->NextAs<std::string>();
422   auto args = child_results->NextAs<ParameterList>();
423   auto return_type = child_results->NextAs<TypeExpression*>();
424   ExternalRuntimeDeclaration* runtime =
425       MakeNode<ExternalRuntimeDeclaration>(name, args, return_type);
426   Declaration* result = MakeNode<StandardDeclaration>(runtime, nullptr);
427   return ParseResult{result};
428 }
429 
StringLiteralUnquoteAction(ParseResultIterator * child_results)430 base::Optional<ParseResult> StringLiteralUnquoteAction(
431     ParseResultIterator* child_results) {
432   return ParseResult{
433       StringLiteralUnquote(child_results->NextAs<std::string>())};
434 }
435 
MakeBasicTypeExpression(ParseResultIterator * child_results)436 base::Optional<ParseResult> MakeBasicTypeExpression(
437     ParseResultIterator* child_results) {
438   auto is_constexpr = child_results->NextAs<bool>();
439   auto name = child_results->NextAs<std::string>();
440   TypeExpression* result =
441       MakeNode<BasicTypeExpression>(is_constexpr, std::move(name));
442   return ParseResult{result};
443 }
444 
MakeFunctionTypeExpression(ParseResultIterator * child_results)445 base::Optional<ParseResult> MakeFunctionTypeExpression(
446     ParseResultIterator* child_results) {
447   auto parameters = child_results->NextAs<std::vector<TypeExpression*>>();
448   auto return_type = child_results->NextAs<TypeExpression*>();
449   TypeExpression* result =
450       MakeNode<FunctionTypeExpression>(std::move(parameters), return_type);
451   return ParseResult{result};
452 }
453 
MakeUnionTypeExpression(ParseResultIterator * child_results)454 base::Optional<ParseResult> MakeUnionTypeExpression(
455     ParseResultIterator* child_results) {
456   auto a = child_results->NextAs<TypeExpression*>();
457   auto b = child_results->NextAs<TypeExpression*>();
458   TypeExpression* result = MakeNode<UnionTypeExpression>(a, b);
459   return ParseResult{result};
460 }
461 
MakeExpressionStatement(ParseResultIterator * child_results)462 base::Optional<ParseResult> MakeExpressionStatement(
463     ParseResultIterator* child_results) {
464   auto expression = child_results->NextAs<Expression*>();
465   Statement* result = MakeNode<ExpressionStatement>(expression);
466   return ParseResult{result};
467 }
468 
MakeIfStatement(ParseResultIterator * child_results)469 base::Optional<ParseResult> MakeIfStatement(
470     ParseResultIterator* child_results) {
471   auto is_constexpr = child_results->NextAs<bool>();
472   auto condition = child_results->NextAs<Expression*>();
473   auto if_true = child_results->NextAs<Statement*>();
474   auto if_false = child_results->NextAs<base::Optional<Statement*>>();
475 
476   if (if_false && !(BlockStatement::DynamicCast(if_true) &&
477                     (BlockStatement::DynamicCast(*if_false) ||
478                      IfStatement::DynamicCast(*if_false)))) {
479     ReportError("if-else statements require curly braces");
480   }
481 
482   Statement* result =
483       MakeNode<IfStatement>(is_constexpr, condition, if_true, if_false);
484   return ParseResult{result};
485 }
486 
MakeTypeswitchStatement(ParseResultIterator * child_results)487 base::Optional<ParseResult> MakeTypeswitchStatement(
488     ParseResultIterator* child_results) {
489   auto expression = child_results->NextAs<Expression*>();
490   auto cases = child_results->NextAs<std::vector<TypeswitchCase>>();
491   CurrentSourcePosition::Scope current_source_position(
492       child_results->matched_input().pos);
493 
494   // typeswitch (expression) case (x1 : T1) {
495   //   ...b1
496   // } case (x2 : T2) {
497   //   ...b2
498   // } case (x3 : T3) {
499   //   ...b3
500   // }
501   //
502   // desugars to
503   //
504   // {
505   //   const _value = expression;
506   //   try {
507   //     const x1 : T1 = cast<T1>(_value) otherwise _NextCase;
508   //     ...b1
509   //   } label _NextCase {
510   //     try {
511   //       const x2 : T2 = cast<T2>(%assume_impossible<T1>(_value));
512   //       ...b2
513   //     } label _NextCase {
514   //       const x3 : T3 = %assume_impossible<T1|T2>(_value);
515   //       ...b3
516   //     }
517   //   }
518   // }
519 
520   BlockStatement* current_block = MakeNode<BlockStatement>();
521   Statement* result = current_block;
522   {
523     CurrentSourcePosition::Scope current_source_position(expression->pos);
524     current_block->statements.push_back(MakeNode<VarDeclarationStatement>(
525         true, "_value", base::nullopt, expression));
526   }
527 
528   TypeExpression* accumulated_types;
529   for (size_t i = 0; i < cases.size(); ++i) {
530     CurrentSourcePosition::Scope current_source_position(cases[i].pos);
531     Expression* value = MakeNode<IdentifierExpression>("_value");
532     if (i >= 1) {
533       value =
534           MakeNode<AssumeTypeImpossibleExpression>(accumulated_types, value);
535     }
536     BlockStatement* case_block;
537     if (i < cases.size() - 1) {
538       value = MakeNode<CallExpression>(
539           "cast", false, std::vector<TypeExpression*>{cases[i].type},
540           std::vector<Expression*>{value},
541           std::vector<std::string>{"_NextCase"});
542       case_block = MakeNode<BlockStatement>();
543     } else {
544       case_block = current_block;
545     }
546     std::string name = "_case_value";
547     if (cases[i].name) name = *cases[i].name;
548     case_block->statements.push_back(
549         MakeNode<VarDeclarationStatement>(true, name, cases[i].type, value));
550     case_block->statements.push_back(cases[i].block);
551     if (i < cases.size() - 1) {
552       BlockStatement* next_block = MakeNode<BlockStatement>();
553       current_block->statements.push_back(MakeNode<TryLabelStatement>(
554           case_block, std::vector<LabelBlock*>{MakeNode<LabelBlock>(
555                           "_NextCase", ParameterList::Empty(), next_block)}));
556       current_block = next_block;
557     }
558     accumulated_types =
559         i > 0 ? MakeNode<UnionTypeExpression>(accumulated_types, cases[i].type)
560               : cases[i].type;
561   }
562   return ParseResult{result};
563 }
564 
MakeTypeswitchCase(ParseResultIterator * child_results)565 base::Optional<ParseResult> MakeTypeswitchCase(
566     ParseResultIterator* child_results) {
567   auto name = child_results->NextAs<base::Optional<std::string>>();
568   auto type = child_results->NextAs<TypeExpression*>();
569   auto block = child_results->NextAs<Statement*>();
570   return ParseResult{TypeswitchCase{child_results->matched_input().pos,
571                                     std::move(name), type, block}};
572 }
573 
MakeWhileStatement(ParseResultIterator * child_results)574 base::Optional<ParseResult> MakeWhileStatement(
575     ParseResultIterator* child_results) {
576   auto condition = child_results->NextAs<Expression*>();
577   auto body = child_results->NextAs<Statement*>();
578   Statement* result = MakeNode<WhileStatement>(condition, body);
579   return ParseResult{result};
580 }
581 
MakeReturnStatement(ParseResultIterator * child_results)582 base::Optional<ParseResult> MakeReturnStatement(
583     ParseResultIterator* child_results) {
584   auto value = child_results->NextAs<base::Optional<Expression*>>();
585   Statement* result = MakeNode<ReturnStatement>(value);
586   return ParseResult{result};
587 }
588 
MakeTailCallStatement(ParseResultIterator * child_results)589 base::Optional<ParseResult> MakeTailCallStatement(
590     ParseResultIterator* child_results) {
591   auto value = child_results->NextAs<Expression*>();
592   Statement* result = MakeNode<TailCallStatement>(CallExpression::cast(value));
593   return ParseResult{result};
594 }
595 
MakeVarDeclarationStatement(ParseResultIterator * child_results)596 base::Optional<ParseResult> MakeVarDeclarationStatement(
597     ParseResultIterator* child_results) {
598   auto kind = child_results->NextAs<std::string>();
599   bool const_qualified = kind == "const";
600   if (!const_qualified) DCHECK_EQ("let", kind);
601   auto name = child_results->NextAs<std::string>();
602   auto type = child_results->NextAs<TypeExpression*>();
603   base::Optional<Expression*> initializer;
604   if (child_results->HasNext())
605     initializer = child_results->NextAs<Expression*>();
606   Statement* result = MakeNode<VarDeclarationStatement>(
607       const_qualified, std::move(name), type, initializer);
608   return ParseResult{result};
609 }
610 
MakeBreakStatement(ParseResultIterator * child_results)611 base::Optional<ParseResult> MakeBreakStatement(
612     ParseResultIterator* child_results) {
613   Statement* result = MakeNode<BreakStatement>();
614   return ParseResult{result};
615 }
616 
MakeContinueStatement(ParseResultIterator * child_results)617 base::Optional<ParseResult> MakeContinueStatement(
618     ParseResultIterator* child_results) {
619   Statement* result = MakeNode<ContinueStatement>();
620   return ParseResult{result};
621 }
622 
MakeGotoStatement(ParseResultIterator * child_results)623 base::Optional<ParseResult> MakeGotoStatement(
624     ParseResultIterator* child_results) {
625   auto label = child_results->NextAs<std::string>();
626   auto arguments = child_results->NextAs<std::vector<Expression*>>();
627   Statement* result =
628       MakeNode<GotoStatement>(std::move(label), std::move(arguments));
629   return ParseResult{result};
630 }
631 
MakeBlockStatement(ParseResultIterator * child_results)632 base::Optional<ParseResult> MakeBlockStatement(
633     ParseResultIterator* child_results) {
634   auto deferred = child_results->NextAs<bool>();
635   auto statements = child_results->NextAs<std::vector<Statement*>>();
636   Statement* result = MakeNode<BlockStatement>(deferred, std::move(statements));
637   return ParseResult{result};
638 }
639 
MakeTryLabelStatement(ParseResultIterator * child_results)640 base::Optional<ParseResult> MakeTryLabelStatement(
641     ParseResultIterator* child_results) {
642   auto try_block = child_results->NextAs<Statement*>();
643   auto label_blocks = child_results->NextAs<std::vector<LabelBlock*>>();
644   Statement* result =
645       MakeNode<TryLabelStatement>(try_block, std::move(label_blocks));
646   return ParseResult{result};
647 }
648 
MakeForOfLoopStatement(ParseResultIterator * child_results)649 base::Optional<ParseResult> MakeForOfLoopStatement(
650     ParseResultIterator* child_results) {
651   auto var_decl = child_results->NextAs<Statement*>();
652   auto iterable = child_results->NextAs<Expression*>();
653   auto range = child_results->NextAs<base::Optional<RangeExpression>>();
654   auto body = child_results->NextAs<Statement*>();
655   Statement* result =
656       MakeNode<ForOfLoopStatement>(var_decl, iterable, range, body);
657   return ParseResult{result};
658 }
659 
MakeForLoopStatement(ParseResultIterator * child_results)660 base::Optional<ParseResult> MakeForLoopStatement(
661     ParseResultIterator* child_results) {
662   auto var_decl = child_results->NextAs<base::Optional<Statement*>>();
663   auto test = child_results->NextAs<base::Optional<Expression*>>();
664   auto action = child_results->NextAs<base::Optional<Expression*>>();
665   auto body = child_results->NextAs<Statement*>();
666   Statement* result = MakeNode<ForLoopStatement>(var_decl, test, action, body);
667   return ParseResult{result};
668 }
669 
MakeLabelBlock(ParseResultIterator * child_results)670 base::Optional<ParseResult> MakeLabelBlock(ParseResultIterator* child_results) {
671   auto label = child_results->NextAs<std::string>();
672   auto parameters = child_results->NextAs<ParameterList>();
673   auto body = child_results->NextAs<Statement*>();
674   LabelBlock* result =
675       MakeNode<LabelBlock>(std::move(label), std::move(parameters), body);
676   return ParseResult{result};
677 }
678 
MakeRangeExpression(ParseResultIterator * child_results)679 base::Optional<ParseResult> MakeRangeExpression(
680     ParseResultIterator* child_results) {
681   auto begin = child_results->NextAs<base::Optional<Expression*>>();
682   auto end = child_results->NextAs<base::Optional<Expression*>>();
683   RangeExpression result = {begin, end};
684   return ParseResult{result};
685 }
686 
MakeExpressionWithSource(ParseResultIterator * child_results)687 base::Optional<ParseResult> MakeExpressionWithSource(
688     ParseResultIterator* child_results) {
689   auto e = child_results->NextAs<Expression*>();
690   return ParseResult{
691       ExpressionWithSource{e, child_results->matched_input().ToString()}};
692 }
693 
MakeIdentifierExpression(ParseResultIterator * child_results)694 base::Optional<ParseResult> MakeIdentifierExpression(
695     ParseResultIterator* child_results) {
696   auto name = child_results->NextAs<std::string>();
697   auto generic_arguments =
698       child_results->NextAs<std::vector<TypeExpression*>>();
699   LocationExpression* result = MakeNode<IdentifierExpression>(
700       std::move(name), std::move(generic_arguments));
701   return ParseResult{result};
702 }
703 
MakeFieldAccessExpression(ParseResultIterator * child_results)704 base::Optional<ParseResult> MakeFieldAccessExpression(
705     ParseResultIterator* child_results) {
706   auto object = child_results->NextAs<Expression*>();
707   auto field = child_results->NextAs<std::string>();
708   LocationExpression* result =
709       MakeNode<FieldAccessExpression>(object, std::move(field));
710   return ParseResult{result};
711 }
712 
MakeElementAccessExpression(ParseResultIterator * child_results)713 base::Optional<ParseResult> MakeElementAccessExpression(
714     ParseResultIterator* child_results) {
715   auto object = child_results->NextAs<Expression*>();
716   auto field = child_results->NextAs<Expression*>();
717   LocationExpression* result = MakeNode<ElementAccessExpression>(object, field);
718   return ParseResult{result};
719 }
720 
MakeStructExpression(ParseResultIterator * child_results)721 base::Optional<ParseResult> MakeStructExpression(
722     ParseResultIterator* child_results) {
723   auto name = child_results->NextAs<std::string>();
724   auto expressions = child_results->NextAs<std::vector<Expression*>>();
725   Expression* result =
726       MakeNode<StructExpression>(std::move(name), std::move(expressions));
727   return ParseResult{result};
728 }
729 
MakeAssignmentExpression(ParseResultIterator * child_results)730 base::Optional<ParseResult> MakeAssignmentExpression(
731     ParseResultIterator* child_results) {
732   auto location = child_results->NextAs<LocationExpression*>();
733   auto op = child_results->NextAs<base::Optional<std::string>>();
734   auto value = child_results->NextAs<Expression*>();
735   Expression* result =
736       MakeNode<AssignmentExpression>(location, std::move(op), value);
737   return ParseResult{result};
738 }
739 
MakeNumberLiteralExpression(ParseResultIterator * child_results)740 base::Optional<ParseResult> MakeNumberLiteralExpression(
741     ParseResultIterator* child_results) {
742   auto number = child_results->NextAs<std::string>();
743   Expression* result = MakeNode<NumberLiteralExpression>(std::move(number));
744   return ParseResult{result};
745 }
746 
MakeStringLiteralExpression(ParseResultIterator * child_results)747 base::Optional<ParseResult> MakeStringLiteralExpression(
748     ParseResultIterator* child_results) {
749   auto literal = child_results->NextAs<std::string>();
750   Expression* result = MakeNode<StringLiteralExpression>(std::move(literal));
751   return ParseResult{result};
752 }
753 
MakeIncrementDecrementExpressionPostfix(ParseResultIterator * child_results)754 base::Optional<ParseResult> MakeIncrementDecrementExpressionPostfix(
755     ParseResultIterator* child_results) {
756   auto location = child_results->NextAs<LocationExpression*>();
757   auto op = child_results->NextAs<IncrementDecrementOperator>();
758   Expression* result =
759       MakeNode<IncrementDecrementExpression>(location, op, true);
760   return ParseResult{result};
761 }
762 
MakeIncrementDecrementExpressionPrefix(ParseResultIterator * child_results)763 base::Optional<ParseResult> MakeIncrementDecrementExpressionPrefix(
764     ParseResultIterator* child_results) {
765   auto op = child_results->NextAs<IncrementDecrementOperator>();
766   auto location = child_results->NextAs<LocationExpression*>();
767   Expression* result =
768       MakeNode<IncrementDecrementExpression>(location, op, false);
769   return ParseResult{result};
770 }
771 
MakeLogicalOrExpression(ParseResultIterator * child_results)772 base::Optional<ParseResult> MakeLogicalOrExpression(
773     ParseResultIterator* child_results) {
774   auto left = child_results->NextAs<Expression*>();
775   auto right = child_results->NextAs<Expression*>();
776   Expression* result = MakeNode<LogicalOrExpression>(left, right);
777   return ParseResult{result};
778 }
779 
MakeLogicalAndExpression(ParseResultIterator * child_results)780 base::Optional<ParseResult> MakeLogicalAndExpression(
781     ParseResultIterator* child_results) {
782   auto left = child_results->NextAs<Expression*>();
783   auto right = child_results->NextAs<Expression*>();
784   Expression* result = MakeNode<LogicalAndExpression>(left, right);
785   return ParseResult{result};
786 }
787 
MakeConditionalExpression(ParseResultIterator * child_results)788 base::Optional<ParseResult> MakeConditionalExpression(
789     ParseResultIterator* child_results) {
790   auto condition = child_results->NextAs<Expression*>();
791   auto if_true = child_results->NextAs<Expression*>();
792   auto if_false = child_results->NextAs<Expression*>();
793   Expression* result =
794       MakeNode<ConditionalExpression>(condition, if_true, if_false);
795   return ParseResult{result};
796 }
797 
MakeLabelAndTypes(ParseResultIterator * child_results)798 base::Optional<ParseResult> MakeLabelAndTypes(
799     ParseResultIterator* child_results) {
800   auto name = child_results->NextAs<std::string>();
801   auto types = child_results->NextAs<std::vector<TypeExpression*>>();
802   return ParseResult{LabelAndTypes{std::move(name), std::move(types)}};
803 }
804 
MakeNameAndType(ParseResultIterator * child_results)805 base::Optional<ParseResult> MakeNameAndType(
806     ParseResultIterator* child_results) {
807   auto name = child_results->NextAs<std::string>();
808   auto type = child_results->NextAs<TypeExpression*>();
809   return ParseResult{NameAndTypeExpression{std::move(name), type}};
810 }
811 
ExtractAssignmentOperator(ParseResultIterator * child_results)812 base::Optional<ParseResult> ExtractAssignmentOperator(
813     ParseResultIterator* child_results) {
814   auto op = child_results->NextAs<std::string>();
815   base::Optional<std::string> result = std::string(op.begin(), op.end() - 1);
816   return ParseResult(std::move(result));
817 }
818 
819 struct TorqueGrammar : Grammar {
MatchWhitespacev8::internal::torque::__anon5ab2e3c20111::TorqueGrammar820   static bool MatchWhitespace(InputPosition* pos) {
821     while (true) {
822       if (MatchChar(std::isspace, pos)) continue;
823       if (MatchString("//", pos)) {
824         while (MatchChar([](char c) { return c != '\n'; }, pos)) {
825         }
826         continue;
827       }
828       return true;
829     }
830   }
831 
MatchIdentifierv8::internal::torque::__anon5ab2e3c20111::TorqueGrammar832   static bool MatchIdentifier(InputPosition* pos) {
833     if (!MatchChar(std::isalpha, pos)) return false;
834     while (MatchChar(std::isalnum, pos) || MatchString("_", pos)) {
835     }
836     return true;
837   }
838 
MatchStringLiteralv8::internal::torque::__anon5ab2e3c20111::TorqueGrammar839   static bool MatchStringLiteral(InputPosition* pos) {
840     InputPosition current = *pos;
841     if (MatchString("\"", &current)) {
842       while (
843           (MatchString("\\", &current) && MatchAnyChar(&current)) ||
844           MatchChar([](char c) { return c != '"' && c != '\n'; }, &current)) {
845       }
846       if (MatchString("\"", &current)) {
847         *pos = current;
848         return true;
849       }
850     }
851     current = *pos;
852     if (MatchString("'", &current)) {
853       while (
854           (MatchString("\\", &current) && MatchAnyChar(&current)) ||
855           MatchChar([](char c) { return c != '\'' && c != '\n'; }, &current)) {
856       }
857       if (MatchString("'", &current)) {
858         *pos = current;
859         return true;
860       }
861     }
862     return false;
863   }
864 
MatchHexLiteralv8::internal::torque::__anon5ab2e3c20111::TorqueGrammar865   static bool MatchHexLiteral(InputPosition* pos) {
866     InputPosition current = *pos;
867     MatchString("-", &current);
868     if (MatchString("0x", &current) && MatchChar(std::isxdigit, &current)) {
869       while (MatchChar(std::isxdigit, &current)) {
870       }
871       *pos = current;
872       return true;
873     }
874     return false;
875   }
876 
MatchDecimalLiteralv8::internal::torque::__anon5ab2e3c20111::TorqueGrammar877   static bool MatchDecimalLiteral(InputPosition* pos) {
878     InputPosition current = *pos;
879     bool found_digit = false;
880     MatchString("-", &current);
881     while (MatchChar(std::isdigit, &current)) found_digit = true;
882     MatchString(".", &current);
883     while (MatchChar(std::isdigit, &current)) found_digit = true;
884     if (!found_digit) return false;
885     *pos = current;
886     if ((MatchString("e", &current) || MatchString("E", &current)) &&
887         (MatchString("+", &current) || MatchString("-", &current) || true) &&
888         MatchChar(std::isdigit, &current)) {
889       while (MatchChar(std::isdigit, &current)) {
890       }
891       *pos = current;
892       return true;
893     }
894     return true;
895   }
896 
TorqueGrammarv8::internal::torque::__anon5ab2e3c20111::TorqueGrammar897   TorqueGrammar() : Grammar(&file) { SetWhitespace(MatchWhitespace); }
898 
899   // Result: std::string
900   Symbol identifier = {Rule({Pattern(MatchIdentifier)}, YieldMatchedInput)};
901 
902   // Result: std::string
903   Symbol stringLiteral = {
904       Rule({Pattern(MatchStringLiteral)}, YieldMatchedInput)};
905 
906   // Result: std::string
907   Symbol externalString = {Rule({&stringLiteral}, StringLiteralUnquoteAction)};
908 
909   // Result: std::string
910   Symbol decimalLiteral = {
911       Rule({Pattern(MatchDecimalLiteral)}, YieldMatchedInput),
912       Rule({Pattern(MatchHexLiteral)}, YieldMatchedInput)};
913 
914   // Result: TypeList
915   Symbol* typeList = List<TypeExpression*>(&type, Token(","));
916 
917   // Result: TypeExpression*
918   Symbol simpleType = {
919       Rule({Token("("), &type, Token(")")}),
920       Rule({CheckIf(Token("constexpr")), &identifier}, MakeBasicTypeExpression),
921       Rule({Token("builtin"), Token("("), typeList, Token(")"), Token("=>"),
922             &simpleType},
923            MakeFunctionTypeExpression)};
924 
925   // Result: TypeExpression*
926   Symbol type = {Rule({&simpleType}), Rule({&type, Token("|"), &simpleType},
927                                            MakeUnionTypeExpression)};
928 
929   // Result: GenericParameters
930   Symbol genericParameters = {
931       Rule({Token("<"),
932             List<std::string>(
933                 Sequence({&identifier, Token(":"), Token("type")}), Token(",")),
934             Token(">")})};
935 
936   // Result: TypeList
937   Symbol genericSpecializationTypeList = {
938       Rule({Token("<"), typeList, Token(">")})};
939 
940   // Result: base::Optional<TypeList>
941   Symbol* optionalGenericParameters = Optional<TypeList>(&genericParameters);
942 
943   // Result: ParameterList
944   Symbol typeListMaybeVarArgs = {
945       Rule({Token("("), List<TypeExpression*>(Sequence({&type, Token(",")})),
946             Token("..."), Token(")")},
947            MakeParameterListFromTypes<true>),
948       Rule({Token("("), typeList, Token(")")},
949            MakeParameterListFromTypes<false>)};
950 
951   // Result: LabelAndTypes
952   Symbol labelParameter = {Rule(
953       {&identifier,
954        TryOrDefault<TypeList>(Sequence({Token("("), typeList, Token(")")}))},
955       MakeLabelAndTypes)};
956 
957   // Result: TypeExpression*
958   Symbol optionalReturnType = {Rule({Token(":"), &type}),
959                                Rule({}, MakeVoidType)};
960 
961   // Result: LabelAndTypesVector
962   Symbol* optionalLabelList{TryOrDefault<LabelAndTypesVector>(
963       Sequence({Token("labels"),
964                 NonemptyList<LabelAndTypes>(&labelParameter, Token(","))}))};
965 
966   // Result: std::vector<std::string>
967   Symbol* optionalOtherwise{TryOrDefault<std::vector<std::string>>(
968       Sequence({Token("otherwise"),
969                 NonemptyList<std::string>(&identifier, Token(","))}))};
970 
971   // Result: NameAndTypeExpression
972   Symbol nameAndType = {
973       Rule({&identifier, Token(":"), &type}, MakeNameAndType)};
974 
975   // Result: ParameterList
976   Symbol parameterListNoVararg = {
977       Rule({Token("("), List<NameAndTypeExpression>(&nameAndType, Token(",")),
978             Token(")")},
979            MakeParameterListFromNameAndTypeList<false>)};
980 
981   // Result: ParameterList
982   Symbol parameterListAllowVararg = {
983       Rule({&parameterListNoVararg}),
984       Rule({Token("("),
985             NonemptyList<NameAndTypeExpression>(&nameAndType, Token(",")),
986             Token(","), Token("..."), &identifier, Token(")")},
987            MakeParameterListFromNameAndTypeList<true>)};
988 
989   // Result: std::string
OneOfv8::internal::torque::__anon5ab2e3c20111::TorqueGrammar990   Symbol* OneOf(std::vector<std::string> alternatives) {
991     Symbol* result = NewSymbol();
992     for (const std::string& s : alternatives) {
993       result->AddRule(Rule({Token(s)}, YieldMatchedInput));
994     }
995     return result;
996   }
997 
998   // Result: Expression*
BinaryOperatorv8::internal::torque::__anon5ab2e3c20111::TorqueGrammar999   Symbol* BinaryOperator(Symbol* nextLevel, Symbol* op) {
1000     Symbol* result = NewSymbol();
1001     *result = {Rule({nextLevel}),
1002                Rule({result, op, nextLevel}, MakeBinaryOperator)};
1003     return result;
1004   }
1005 
1006   // Result: Expression*
1007   Symbol* expression = &assignmentExpression;
1008 
1009   // Result: IncrementDecrementOperator
1010   Symbol incrementDecrementOperator = {
1011       Rule({Token("++")},
1012            YieldIntegralConstant<IncrementDecrementOperator,
1013                                  IncrementDecrementOperator::kIncrement>),
1014       Rule({Token("--")},
1015            YieldIntegralConstant<IncrementDecrementOperator,
1016                                  IncrementDecrementOperator::kDecrement>)};
1017 
1018   // Result: LocationExpression*
1019   Symbol locationExpression = {
1020       Rule(
1021           {&identifier, TryOrDefault<TypeList>(&genericSpecializationTypeList)},
1022           MakeIdentifierExpression),
1023       Rule({&primaryExpression, Token("."), &identifier},
1024            MakeFieldAccessExpression),
1025       Rule({&primaryExpression, Token("["), expression, Token("]")},
1026            MakeElementAccessExpression)};
1027 
1028   // Result: std::vector<Expression*>
1029   Symbol argumentList = {Rule(
1030       {Token("("), List<Expression*>(expression, Token(",")), Token(")")})};
1031 
1032   // Result: Expression*
1033   Symbol callExpression = {
1034       Rule({&identifier, TryOrDefault<TypeList>(&genericSpecializationTypeList),
1035             &argumentList, optionalOtherwise},
1036            MakeCall)};
1037 
1038   // Result: Expression*
1039   Symbol primaryExpression = {
1040       Rule({&callExpression}),
1041       Rule({&locationExpression},
1042            CastParseResult<LocationExpression*, Expression*>),
1043       Rule({&decimalLiteral}, MakeNumberLiteralExpression),
1044       Rule({&stringLiteral}, MakeStringLiteralExpression),
1045       Rule({&identifier, Token("{"), List<Expression*>(expression, Token(",")),
1046             Token("}")},
1047            MakeStructExpression),
1048       Rule({Token("("), expression, Token(")")})};
1049 
1050   // Result: Expression*
1051   Symbol unaryExpression = {
1052       Rule({&primaryExpression}),
1053       Rule({OneOf({"+", "-", "!", "~"}), &unaryExpression}, MakeUnaryOperator),
1054       Rule({&incrementDecrementOperator, &locationExpression},
1055            MakeIncrementDecrementExpressionPrefix),
1056       Rule({&locationExpression, &incrementDecrementOperator},
1057            MakeIncrementDecrementExpressionPostfix)};
1058 
1059   // Result: Expression*
1060   Symbol* multiplicativeExpression =
1061       BinaryOperator(&unaryExpression, OneOf({"*", "/", "%"}));
1062 
1063   // Result: Expression*
1064   Symbol* additiveExpression =
1065       BinaryOperator(multiplicativeExpression, OneOf({"+", "-"}));
1066 
1067   // Result: Expression*
1068   Symbol* shiftExpression =
1069       BinaryOperator(additiveExpression, OneOf({"<<", ">>", ">>>"}));
1070 
1071   // Do not allow expressions like a < b > c because this is never
1072   // useful and ambiguous with template parameters.
1073   // Result: Expression*
1074   Symbol relationalExpression = {
1075       Rule({shiftExpression}),
1076       Rule({shiftExpression, OneOf({"<", ">", "<=", ">="}), shiftExpression},
1077            MakeBinaryOperator)};
1078 
1079   // Result: Expression*
1080   Symbol* equalityExpression =
1081       BinaryOperator(&relationalExpression, OneOf({"==", "!="}));
1082 
1083   // Result: Expression*
1084   Symbol* bitwiseExpression =
1085       BinaryOperator(equalityExpression, OneOf({"&", "|"}));
1086 
1087   // Result: Expression*
1088   Symbol logicalAndExpression = {
1089       Rule({bitwiseExpression}),
1090       Rule({&logicalAndExpression, Token("&&"), bitwiseExpression},
1091            MakeLogicalAndExpression)};
1092 
1093   // Result: Expression*
1094   Symbol logicalOrExpression = {
1095       Rule({&logicalAndExpression}),
1096       Rule({&logicalOrExpression, Token("||"), &logicalAndExpression},
1097            MakeLogicalOrExpression)};
1098 
1099   // Result: Expression*
1100   Symbol conditionalExpression = {
1101       Rule({&logicalOrExpression}),
1102       Rule({&logicalOrExpression, Token("?"), expression, Token(":"),
1103             &conditionalExpression},
1104            MakeConditionalExpression)};
1105 
1106   // Result: base::Optional<std::string>
1107   Symbol assignmentOperator = {
1108       Rule({Token("=")}, YieldDefaultValue<base::Optional<std::string>>),
1109       Rule({OneOf({"*=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=",
1110                    "^=", "|="})},
1111            ExtractAssignmentOperator)};
1112 
1113   // Result: Expression*
1114   Symbol assignmentExpression = {
1115       Rule({&conditionalExpression}),
1116       Rule({&locationExpression, &assignmentOperator, &assignmentExpression},
1117            MakeAssignmentExpression)};
1118 
1119   // Result: Statement*
1120   Symbol block = {Rule({CheckIf(Token("deferred")), Token("{"),
1121                         List<Statement*>(&statement), Token("}")},
1122                        MakeBlockStatement)};
1123 
1124   // Result: LabelBlock*
1125   Symbol labelBlock = {
1126       Rule({Token("label"), &identifier,
1127             TryOrDefault<ParameterList>(&parameterListNoVararg), &block},
1128            MakeLabelBlock)};
1129 
1130   // Result: ExpressionWithSource
1131   Symbol expressionWithSource = {Rule({expression}, MakeExpressionWithSource)};
1132 
1133   // Result: RangeExpression
1134   Symbol rangeSpecifier = {
1135       Rule({Token("["), Optional<Expression*>(expression), Token(":"),
1136             Optional<Expression*>(expression), Token("]")},
1137            MakeRangeExpression)};
1138 
1139   // Result: Statement*
1140   Symbol varDeclaration = {
1141       Rule({OneOf({"let", "const"}), &identifier, Token(":"), &type},
1142            MakeVarDeclarationStatement)};
1143 
1144   // Result: Statement*
1145   Symbol varDeclarationWithInitialization = {
1146       Rule({OneOf({"let", "const"}), &identifier, Token(":"), &type, Token("="),
1147             expression},
1148            MakeVarDeclarationStatement)};
1149 
1150   // Disallow ambiguous dangling else by only allowing an {atomarStatement} as
1151   // a then-clause. Result: Statement*
1152   Symbol atomarStatement = {
1153       Rule({&block}),
1154       Rule({expression, Token(";")}, MakeExpressionStatement),
1155       Rule({Token("return"), Optional<Expression*>(expression), Token(";")},
1156            MakeReturnStatement),
1157       Rule({Token("tail"), &callExpression, Token(";")}, MakeTailCallStatement),
1158       Rule({Token("break"), Token(";")}, MakeBreakStatement),
1159       Rule({Token("continue"), Token(";")}, MakeContinueStatement),
1160       Rule({Token("goto"), &identifier,
1161             TryOrDefault<std::vector<Expression*>>(&argumentList), Token(";")},
1162            MakeGotoStatement),
1163       Rule({OneOf({"debug", "unreachable"}), Token(";")}, MakeDebugStatement)};
1164 
1165   // Result: Statement*
1166   Symbol statement = {
1167       Rule({&atomarStatement}),
1168       Rule({&varDeclaration, Token(";")}),
1169       Rule({&varDeclarationWithInitialization, Token(";")}),
1170       Rule({Token("if"), CheckIf(Token("constexpr")), Token("("), expression,
1171             Token(")"), &atomarStatement,
1172             Optional<Statement*>(Sequence({Token("else"), &statement}))},
1173            MakeIfStatement),
1174       Rule(
1175           {
1176               Token("typeswitch"), Token("("), expression, Token(")"),
1177               Token("{"), NonemptyList<TypeswitchCase>(&typeswitchCase),
1178               Token("}"),
1179           },
1180           MakeTypeswitchStatement),
1181       Rule({Token("try"), &block, NonemptyList<LabelBlock*>(&labelBlock)},
1182            MakeTryLabelStatement),
1183       Rule({OneOf({"assert", "check"}), Token("("), &expressionWithSource,
1184             Token(")"), Token(";")},
1185            MakeAssertStatement),
1186       Rule({Token("while"), Token("("), expression, Token(")"),
1187             &atomarStatement},
1188            MakeWhileStatement),
1189       Rule({Token("for"), Token("("), &varDeclaration, Token("of"), expression,
1190             Optional<RangeExpression>(&rangeSpecifier), Token(")"),
1191             &atomarStatement},
1192            MakeForOfLoopStatement),
1193       Rule({Token("for"), Token("("),
1194             Optional<Statement*>(&varDeclarationWithInitialization), Token(";"),
1195             Optional<Expression*>(expression), Token(";"),
1196             Optional<Expression*>(expression), Token(")"), &atomarStatement},
1197            MakeForLoopStatement)};
1198 
1199   // Result: TypeswitchCase
1200   Symbol typeswitchCase = {
1201       Rule({Token("case"), Token("("),
1202             Optional<std::string>(Sequence({&identifier, Token(":")})), &type,
1203             Token(")"), &block},
1204            MakeTypeswitchCase)};
1205 
1206   // Result: base::Optional<Statement*>
1207   Symbol optionalBody = {
1208       Rule({&block}, CastParseResult<Statement*, base::Optional<Statement*>>),
1209       Rule({Token(";")}, YieldDefaultValue<base::Optional<Statement*>>)};
1210 
1211   // Result: Declaration*
1212   Symbol declaration = {
1213       Rule({Token("const"), &identifier, Token(":"), &type, Token("="),
1214             expression, Token(";")},
1215            MakeConstDeclaration),
1216       Rule({Token("const"), &identifier, Token(":"), &type, Token("generates"),
1217             &externalString, Token(";")},
1218            MakeExternConstDeclaration),
1219       Rule({Token("type"), &identifier,
1220             Optional<std::string>(Sequence({Token("extends"), &identifier})),
1221             Optional<std::string>(
1222                 Sequence({Token("generates"), &externalString})),
1223             Optional<std::string>(
1224                 Sequence({Token("constexpr"), &externalString})),
1225             Token(";")},
1226            MakeTypeDeclaration),
1227       Rule({Token("type"), &identifier, Token("="), &type, Token(";")},
1228            MakeTypeAliasDeclaration),
1229       Rule({Token("extern"),
1230             Optional<std::string>(
1231                 Sequence({Token("operator"), &externalString})),
1232             Token("macro"), &identifier,
1233             TryOrDefault<GenericParameters>(&genericParameters),
1234             &typeListMaybeVarArgs, &optionalReturnType, optionalLabelList,
1235             Token(";")},
1236            MakeExternalMacro),
1237       Rule({Token("extern"), CheckIf(Token("javascript")), Token("builtin"),
1238             &identifier, TryOrDefault<GenericParameters>(&genericParameters),
1239             &typeListMaybeVarArgs, &optionalReturnType, Token(";")},
1240            MakeExternalBuiltin),
1241       Rule({Token("extern"), Token("runtime"), &identifier,
1242             &typeListMaybeVarArgs, &optionalReturnType, Token(";")},
1243            MakeExternalRuntime),
1244       Rule({Optional<std::string>(
1245                 Sequence({Token("operator"), &externalString})),
1246             Token("macro"), &identifier,
1247             TryOrDefault<GenericParameters>(&genericParameters),
1248             &parameterListNoVararg, &optionalReturnType, optionalLabelList,
1249             &optionalBody},
1250            MakeTorqueMacroDeclaration),
1251       Rule({CheckIf(Token("javascript")), Token("builtin"), &identifier,
1252             TryOrDefault<GenericParameters>(&genericParameters),
1253             &parameterListAllowVararg, &optionalReturnType, &optionalBody},
1254            MakeTorqueBuiltinDeclaration),
1255       Rule({&identifier, &genericSpecializationTypeList,
1256             &parameterListAllowVararg, &optionalReturnType, optionalLabelList,
1257             &block},
1258            MakeSpecializationDeclaration),
1259       Rule({Token("struct"), &identifier, Token("{"),
1260             List<NameAndTypeExpression>(Sequence({&nameAndType, Token(";")})),
1261             Token("}")},
1262            MakeStructDeclaration)};
1263 
1264   // Result: Declaration*
1265   Symbol moduleDeclaration = {
1266       Rule({Token("module"), &identifier, Token("{"),
1267             List<Declaration*>(&declaration), Token("}")},
1268            MakeExplicitModuleDeclaration)};
1269 
1270   Symbol file = {Rule({&file, &moduleDeclaration}, AddGlobalDeclaration),
1271                  Rule({&file, &declaration}, AddGlobalDeclaration), Rule({})};
1272 };
1273 
1274 }  // namespace
1275 
ParseTorque(const std::string & input)1276 void ParseTorque(const std::string& input) { TorqueGrammar().Parse(input); }
1277 
1278 }  // namespace torque
1279 }  // namespace internal
1280 }  // namespace v8
1281