-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathAsmParser.cpp
813 lines (737 loc) · 23.8 KB
/
AsmParser.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Solidity inline assembly parser.
*/
#include <libyul/AST.h>
#include <libyul/AsmParser.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <liblangutil/ErrorReporter.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/Scanner.h>
#include <liblangutil/Common.h>
#include <libsolutil/Common.h>
#include <libsolutil/Visitor.h>
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <regex>
using namespace std::string_literals;
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
namespace
{
std::optional<int> toInt(std::string const& _value)
{
try
{
return stoi(_value);
}
catch (std::out_of_range const&)
{
return std::nullopt;
}
}
}
langutil::DebugData::ConstPtr Parser::createDebugData() const
{
switch (m_useSourceLocationFrom)
{
case UseSourceLocationFrom::Scanner:
return DebugData::create(ParserBase::currentLocation(), ParserBase::currentLocation());
case UseSourceLocationFrom::LocationOverride:
return DebugData::create(m_locationOverride, m_locationOverride);
case UseSourceLocationFrom::Comments:
return DebugData::create(ParserBase::currentLocation(), m_locationFromComment, m_astIDFromComment);
}
solAssert(false, "");
}
void Parser::updateLocationEndFrom(
langutil::DebugData::ConstPtr& _debugData,
SourceLocation const& _location
) const
{
solAssert(_debugData, "");
switch (m_useSourceLocationFrom)
{
case UseSourceLocationFrom::Scanner:
{
DebugData updatedDebugData = *_debugData;
updatedDebugData.nativeLocation.end = _location.end;
updatedDebugData.originLocation.end = _location.end;
_debugData = std::make_shared<DebugData const>(std::move(updatedDebugData));
break;
}
case UseSourceLocationFrom::LocationOverride:
// Ignore the update. The location we're overriding with is not supposed to change
break;
case UseSourceLocationFrom::Comments:
{
DebugData updatedDebugData = *_debugData;
updatedDebugData.nativeLocation.end = _location.end;
_debugData = std::make_shared<DebugData const>(std::move(updatedDebugData));
break;
}
}
}
std::unique_ptr<AST> Parser::parse(CharStream& _charStream)
{
m_scanner = std::make_shared<Scanner>(_charStream);
std::unique_ptr<AST> ast = parseInline(m_scanner);
expectToken(Token::EOS);
return ast;
}
std::unique_ptr<AST> Parser::parseInline(std::shared_ptr<Scanner> const& _scanner)
{
m_recursionDepth = 0;
auto previousScannerKind = _scanner->scannerKind();
_scanner->setScannerMode(ScannerKind::Yul);
ScopeGuard resetScanner([&]{ _scanner->setScannerMode(previousScannerKind); });
try
{
m_scanner = _scanner;
if (m_useSourceLocationFrom == UseSourceLocationFrom::Comments)
fetchDebugDataFromComment();
return std::make_unique<AST>(m_dialect, parseBlock());
}
catch (FatalError const&)
{
if (!m_errorReporter.hasErrors())
{
std::cerr << "Unreported fatal error:" << std::endl;
std::cerr << boost::current_exception_diagnostic_information() << std::endl;
yulAssert(false, "Unreported fatal error.");
}
}
return nullptr;
}
langutil::Token Parser::advance()
{
auto const token = ParserBase::advance();
if (m_useSourceLocationFrom == UseSourceLocationFrom::Comments)
fetchDebugDataFromComment();
return token;
}
void Parser::fetchDebugDataFromComment()
{
solAssert(m_sourceNames.has_value(), "");
std::string_view commentLiteral = m_scanner->currentCommentLiteral();
if (commentLiteral.empty())
{
m_astIDFromComment = std::nullopt;
return;
}
static std::regex const tagRegex = std::regex(
R"~~((?:^|\s+)(@[a-zA-Z0-9\-_]+)(?:\s+|$))~~", // tag, e.g: @src
std::regex_constants::ECMAScript | std::regex_constants::optimize
);
std::match_results<std::string_view::const_iterator> match;
langutil::SourceLocation originLocation = m_locationFromComment;
// Empty for each new node.
std::optional<int> astID;
while (regex_search(commentLiteral.cbegin(), commentLiteral.cend(), match, tagRegex))
{
solAssert(match.size() == 2, "");
commentLiteral = commentLiteral.substr(static_cast<size_t>(match.position() + match.length()));
if (match[1] == "@src")
{
if (auto parseResult = parseSrcComment(commentLiteral, m_scanner->currentCommentLocation()))
tie(commentLiteral, originLocation) = *parseResult;
else
break;
}
else if (match[1] == "@ast-id")
{
if (auto parseResult = parseASTIDComment(commentLiteral, m_scanner->currentCommentLocation()))
tie(commentLiteral, astID) = *parseResult;
else
break;
}
else
// Ignore unrecognized tags.
continue;
}
m_locationFromComment = originLocation;
m_astIDFromComment = astID;
}
std::optional<std::pair<std::string_view, SourceLocation>> Parser::parseSrcComment(
std::string_view const _arguments,
langutil::SourceLocation const& _commentLocation
)
{
CharStream argumentStream(std::string(_arguments), "");
Scanner scanner(argumentStream, ScannerKind::SpecialComment);
std::string_view tail{_arguments.substr(_arguments.size())};
auto const parseLocationComponent = [](Scanner& _scanner, bool expectTrailingColon) -> std::optional<std::string>
{
bool negative = false;
if (_scanner.currentToken() == Token::Sub)
{
negative = true;
_scanner.next();
}
if (_scanner.currentToken() != Token::Number)
return std::nullopt;
if (expectTrailingColon && _scanner.peekNextToken() != Token::Colon)
return std::nullopt;
if (!isValidDecimal(_scanner.currentLiteral()))
return std::nullopt;
std::string decimal = (negative ? "-" : "") + _scanner.currentLiteral();
_scanner.next();
if (expectTrailingColon)
_scanner.next();
return decimal;
};
std::optional<std::string> rawSourceIndex = parseLocationComponent(scanner, true);
std::optional<std::string> rawStart = parseLocationComponent(scanner, true);
std::optional<std::string> rawEnd = parseLocationComponent(scanner, false);
size_t const snippetStart = static_cast<size_t>(scanner.currentLocation().start);
bool const locationScannedSuccessfully = rawSourceIndex && rawStart && rawEnd;
bool const locationIsWhitespaceSeparated =
scanner.peekNextToken() == Token::EOS ||
(snippetStart > 0 && langutil::isWhiteSpace(_arguments[snippetStart - 1]));
if (!locationScannedSuccessfully || !locationIsWhitespaceSeparated)
{
m_errorReporter.syntaxError(
8387_error,
_commentLocation,
"Invalid values in source location mapping. Could not parse location specification."
);
return std::nullopt;
}
// captures error cases `"test` (illegal end quote) and `"test\` (illegal escape sequence / dangling backslash)
bool const illegalLiteral = scanner.currentToken() == Token::Illegal && (scanner.currentError() == ScannerError::IllegalStringEndQuote || scanner.currentError() == ScannerError::IllegalEscapeSequence);
if (scanner.currentToken() == Token::StringLiteral || illegalLiteral)
tail = _arguments.substr(static_cast<size_t>(scanner.currentLocation().end));
else
tail = _arguments.substr(static_cast<size_t>(scanner.currentLocation().start));
// Other scanner errors may occur if there is no string literal which follows
// (f.ex. IllegalHexDigit, IllegalCommentTerminator), but these are ignored
if (illegalLiteral)
{
m_errorReporter.syntaxError(
1544_error,
_commentLocation,
"Invalid code snippet in source location mapping. Quote is not terminated."
);
return {{tail, SourceLocation{}}};
}
std::optional<int> const sourceIndex = toInt(*rawSourceIndex);
std::optional<int> const start = toInt(*rawStart);
std::optional<int> const end = toInt(*rawEnd);
if (
!sourceIndex.has_value() || *sourceIndex < -1 ||
!start.has_value() || *start < -1 ||
!end.has_value() || *end < -1
)
m_errorReporter.syntaxError(
6367_error,
_commentLocation,
"Invalid value in source location mapping. "
"Expected non-negative integer values or -1 for source index and location."
);
else if (sourceIndex == -1)
return {{tail, SourceLocation{*start, *end, nullptr}}};
else if (!(sourceIndex >= 0 && m_sourceNames->count(static_cast<unsigned>(*sourceIndex))))
m_errorReporter.syntaxError(
2674_error,
_commentLocation,
"Invalid source mapping. Source index not defined via @use-src."
);
else
{
std::shared_ptr<std::string const> sourceName = m_sourceNames->at(static_cast<unsigned>(*sourceIndex));
solAssert(sourceName, "");
return {{tail, SourceLocation{*start, *end, std::move(sourceName)}}};
}
return {{tail, SourceLocation{}}};
}
std::optional<std::pair<std::string_view, std::optional<int>>> Parser::parseASTIDComment(
std::string_view _arguments,
langutil::SourceLocation const& _commentLocation
)
{
static std::regex const argRegex = std::regex(
R"~~(^(\d+)(?:\s|$))~~",
std::regex_constants::ECMAScript | std::regex_constants::optimize
);
std::match_results<std::string_view::const_iterator> match;
std::optional<int> astID;
bool matched = regex_search(_arguments.cbegin(), _arguments.cend(), match, argRegex);
std::string_view tail = _arguments;
if (matched)
{
solAssert(match.size() == 2, "");
tail = _arguments.substr(static_cast<size_t>(match.position() + match.length()));
astID = toInt(match[1].str());
}
if (!matched || !astID || *astID < 0 || static_cast<int64_t>(*astID) != *astID)
{
m_errorReporter.syntaxError(1749_error, _commentLocation, "Invalid argument for @ast-id.");
astID = std::nullopt;
}
if (matched)
return {{_arguments, astID}};
else
return std::nullopt;
}
Block Parser::parseBlock()
{
RecursionGuard recursionGuard(*this);
Block block = createWithDebugData<Block>();
expectToken(Token::LBrace);
while (currentToken() != Token::RBrace)
block.statements.emplace_back(parseStatement());
updateLocationEndFrom(block.debugData, currentLocation());
advance();
return block;
}
Statement Parser::parseStatement()
{
RecursionGuard recursionGuard(*this);
switch (currentToken())
{
case Token::Let:
return parseVariableDeclaration();
case Token::Function:
return parseFunctionDefinition();
case Token::LBrace:
return parseBlock();
case Token::If:
{
If _if = createWithDebugData<If>();
advance();
_if.condition = std::make_unique<Expression>(parseExpression());
_if.body = parseBlock();
updateLocationEndFrom(_if.debugData, nativeLocationOf(_if.body));
return Statement{std::move(_if)};
}
case Token::Switch:
{
Switch _switch = createWithDebugData<Switch>();
advance();
_switch.expression = std::make_unique<Expression>(parseExpression());
while (currentToken() == Token::Case)
_switch.cases.emplace_back(parseCase());
if (currentToken() == Token::Default)
_switch.cases.emplace_back(parseCase());
if (currentToken() == Token::Default)
fatalParserError(6931_error, "Only one default case allowed.");
else if (currentToken() == Token::Case)
fatalParserError(4904_error, "Case not allowed after default case.");
if (_switch.cases.empty())
fatalParserError(2418_error, "Switch statement without any cases.");
updateLocationEndFrom(_switch.debugData, nativeLocationOf(_switch.cases.back().body));
return Statement{std::move(_switch)};
}
case Token::For:
return parseForLoop();
case Token::Break:
{
Statement stmt{createWithDebugData<Break>()};
checkBreakContinuePosition("break");
advance();
return stmt;
}
case Token::Continue:
{
Statement stmt{createWithDebugData<Continue>()};
checkBreakContinuePosition("continue");
advance();
return stmt;
}
case Token::Leave:
{
Statement stmt{createWithDebugData<Leave>()};
if (!m_insideFunction)
m_errorReporter.syntaxError(8149_error, currentLocation(), "Keyword \"leave\" can only be used inside a function.");
advance();
return stmt;
}
default:
break;
}
// Options left:
// Expression/FunctionCall
// Assignment
std::variant<Literal, Identifier, BuiltinName> elementary(parseLiteralOrIdentifier());
switch (currentToken())
{
case Token::LParen:
{
Expression expr = parseCall(std::move(elementary));
return ExpressionStatement{debugDataOf(expr), std::move(expr)};
}
case Token::Comma:
case Token::AssemblyAssign:
{
Assignment assignment;
assignment.debugData = debugDataOf(elementary);
bool foundListEnd = false;
do
{
std::visit(GenericVisitor{
[&](Literal const&)
{
auto const token = currentToken() == Token::Comma ? "," : ":=";
fatalParserError(
2856_error,
std::string("Variable name must precede \"") +
token +
"\"" +
(currentToken() == Token::Comma ? " in multiple assignment." : " in assignment.")
);
},
[&](BuiltinName const& _builtin)
{
fatalParserError(
6272_error,
fmt::format(
"Cannot assign to builtin function \"{}\".",
m_dialect.builtin(_builtin.handle).name
)
);
},
[&](Identifier const& _identifier)
{
assignment.variableNames.emplace_back(_identifier);
if (currentToken() != Token::Comma)
foundListEnd = true;
else
{
expectToken(Token::Comma);
elementary = parseLiteralOrIdentifier();
}
}
}, elementary);
} while (!foundListEnd);
expectToken(Token::AssemblyAssign);
assignment.value = std::make_unique<Expression>(parseExpression());
updateLocationEndFrom(assignment.debugData, nativeLocationOf(*assignment.value));
return Statement{std::move(assignment)};
}
default:
fatalParserError(6913_error, "Call or assignment expected.");
break;
}
yulAssert(false, "");
return {};
}
Case Parser::parseCase()
{
RecursionGuard recursionGuard(*this);
Case _case = createWithDebugData<Case>();
if (currentToken() == Token::Default)
advance();
else if (currentToken() == Token::Case)
{
advance();
std::variant<Literal, Identifier, BuiltinName> literal = parseLiteralOrIdentifier();
if (!std::holds_alternative<Literal>(literal))
fatalParserError(4805_error, "Literal expected.");
_case.value = std::make_unique<Literal>(std::get<Literal>(std::move(literal)));
}
else
yulAssert(false, "Case or default case expected.");
_case.body = parseBlock();
updateLocationEndFrom(_case.debugData, nativeLocationOf(_case.body));
return _case;
}
ForLoop Parser::parseForLoop()
{
RecursionGuard recursionGuard(*this);
ForLoopComponent outerForLoopComponent = m_currentForLoopComponent;
ForLoop forLoop = createWithDebugData<ForLoop>();
expectToken(Token::For);
m_currentForLoopComponent = ForLoopComponent::ForLoopPre;
forLoop.pre = parseBlock();
m_currentForLoopComponent = ForLoopComponent::None;
forLoop.condition = std::make_unique<Expression>(parseExpression());
m_currentForLoopComponent = ForLoopComponent::ForLoopPost;
forLoop.post = parseBlock();
m_currentForLoopComponent = ForLoopComponent::ForLoopBody;
forLoop.body = parseBlock();
updateLocationEndFrom(forLoop.debugData, nativeLocationOf(forLoop.body));
m_currentForLoopComponent = outerForLoopComponent;
return forLoop;
}
Expression Parser::parseExpression(bool _unlimitedLiteralArgument)
{
RecursionGuard recursionGuard(*this);
std::variant<Literal, Identifier, BuiltinName> operation = parseLiteralOrIdentifier(_unlimitedLiteralArgument);
return visit(GenericVisitor{
[&](Identifier& _identifier) -> Expression
{
if (currentToken() == Token::LParen)
return parseCall(std::move(operation));
return std::move(_identifier);
},
[&](BuiltinName& _builtin) -> Expression
{
if (currentToken() == Token::LParen)
return parseCall(std::move(operation));
fatalParserError(
7104_error,
nativeLocationOf(_builtin),
"Builtin function \"" + m_dialect.builtin(_builtin.handle).name + "\" must be called."
);
unreachable();
},
[&](Literal& _literal) -> Expression
{
return std::move(_literal);
}
}, operation);
}
std::variant<Literal, Identifier, BuiltinName> Parser::parseLiteralOrIdentifier(bool _unlimitedLiteralArgument)
{
RecursionGuard recursionGuard(*this);
switch (currentToken())
{
case Token::Identifier:
{
std::variant<Literal, Identifier, BuiltinName> literalOrIdentifier;
if (std::optional<BuiltinHandle> const builtinHandle = m_dialect.findBuiltin(currentLiteral()))
literalOrIdentifier = BuiltinName{createDebugData(), *builtinHandle};
else
literalOrIdentifier = Identifier{createDebugData(), YulName{currentLiteral()}};
advance();
return literalOrIdentifier;
}
case Token::StringLiteral:
case Token::HexStringLiteral:
case Token::Number:
case Token::TrueLiteral:
case Token::FalseLiteral:
{
LiteralKind kind = LiteralKind::Number;
switch (currentToken())
{
case Token::StringLiteral:
case Token::HexStringLiteral:
kind = LiteralKind::String;
break;
case Token::Number:
if (!isValidNumberLiteral(currentLiteral()))
fatalParserError(4828_error, "Invalid number literal.");
kind = LiteralKind::Number;
break;
case Token::TrueLiteral:
case Token::FalseLiteral:
kind = LiteralKind::Boolean;
break;
default:
break;
}
auto const literalLocation = currentLocation();
Literal literal{
createDebugData(),
kind,
valueOfLiteral(currentLiteral(), kind, _unlimitedLiteralArgument && kind == LiteralKind::String)
};
advance();
if (currentToken() == Token::Colon)
{
expectToken(Token::Colon);
updateLocationEndFrom(literal.debugData, currentLocation());
auto const typedLiteralLocation = SourceLocation::smallestCovering(literalLocation, currentLocation());
std::ignore = expectAsmIdentifier();
raiseUnsupportedTypesError(typedLiteralLocation);
}
return literal;
}
case Token::Illegal:
fatalParserError(1465_error, "Illegal token: " + to_string(m_scanner->currentError()));
break;
default:
fatalParserError(1856_error, "Literal or identifier expected.");
}
return {};
}
VariableDeclaration Parser::parseVariableDeclaration()
{
RecursionGuard recursionGuard(*this);
VariableDeclaration varDecl = createWithDebugData<VariableDeclaration>();
expectToken(Token::Let);
while (true)
{
varDecl.variables.emplace_back(parseNameWithDebugData());
if (currentToken() == Token::Comma)
expectToken(Token::Comma);
else
break;
}
if (currentToken() == Token::AssemblyAssign)
{
expectToken(Token::AssemblyAssign);
varDecl.value = std::make_unique<Expression>(parseExpression());
updateLocationEndFrom(varDecl.debugData, nativeLocationOf(*varDecl.value));
}
else
updateLocationEndFrom(varDecl.debugData, nativeLocationOf(varDecl.variables.back()));
return varDecl;
}
FunctionDefinition Parser::parseFunctionDefinition()
{
RecursionGuard recursionGuard(*this);
if (m_currentForLoopComponent == ForLoopComponent::ForLoopPre)
m_errorReporter.syntaxError(
3441_error,
currentLocation(),
"Functions cannot be defined inside a for-loop init block."
);
ForLoopComponent outerForLoopComponent = m_currentForLoopComponent;
m_currentForLoopComponent = ForLoopComponent::None;
FunctionDefinition funDef = createWithDebugData<FunctionDefinition>();
expectToken(Token::Function);
funDef.name = expectAsmIdentifier();
expectToken(Token::LParen);
while (currentToken() != Token::RParen)
{
funDef.parameters.emplace_back(parseNameWithDebugData());
if (currentToken() == Token::RParen)
break;
expectToken(Token::Comma);
}
expectToken(Token::RParen);
if (currentToken() == Token::RightArrow)
{
expectToken(Token::RightArrow);
while (true)
{
funDef.returnVariables.emplace_back(parseNameWithDebugData());
if (currentToken() == Token::LBrace)
break;
expectToken(Token::Comma);
}
}
bool preInsideFunction = m_insideFunction;
m_insideFunction = true;
funDef.body = parseBlock();
m_insideFunction = preInsideFunction;
updateLocationEndFrom(funDef.debugData, nativeLocationOf(funDef.body));
m_currentForLoopComponent = outerForLoopComponent;
return funDef;
}
FunctionCall Parser::parseCall(std::variant<Literal, Identifier, BuiltinName>&& _initialOp)
{
RecursionGuard recursionGuard(*this);
std::function isUnlimitedLiteralArgument = [](size_t) -> bool { return false; };
FunctionCall functionCall;
std::visit(GenericVisitor{
[&](Literal const&) { fatalParserError(9980_error, "Function name expected."); },
[&](Identifier const& _identifier)
{
functionCall.debugData = _identifier.debugData;
functionCall.functionName = _identifier;
},
[&](BuiltinName const& _builtin)
{
isUnlimitedLiteralArgument = [builtinFunction=m_dialect.builtin(_builtin.handle)](size_t _index) {
if (_index < builtinFunction.literalArguments.size())
return builtinFunction.literalArgument(_index).has_value();
return false;
};
functionCall.debugData = _builtin.debugData;
functionCall.functionName = _builtin;
}
}, _initialOp);
size_t argumentIndex {0};
expectToken(Token::LParen);
if (currentToken() != Token::RParen)
{
functionCall.arguments.emplace_back(parseExpression(isUnlimitedLiteralArgument(argumentIndex++)));
while (currentToken() != Token::RParen)
{
expectToken(Token::Comma);
functionCall.arguments.emplace_back(parseExpression(isUnlimitedLiteralArgument(argumentIndex++)));
}
}
updateLocationEndFrom(functionCall.debugData, currentLocation());
expectToken(Token::RParen);
return functionCall;
}
NameWithDebugData Parser::parseNameWithDebugData()
{
RecursionGuard recursionGuard(*this);
NameWithDebugData typedName = createWithDebugData<NameWithDebugData>();
auto const nameLocation = currentLocation();
typedName.name = expectAsmIdentifier();
if (currentToken() == Token::Colon)
{
expectToken(Token::Colon);
updateLocationEndFrom(typedName.debugData, currentLocation());
auto const typedNameLocation = SourceLocation::smallestCovering(nameLocation, currentLocation());
std::ignore = expectAsmIdentifier();
raiseUnsupportedTypesError(typedNameLocation);
}
return typedName;
}
YulName Parser::expectAsmIdentifier()
{
YulName name{currentLiteral()};
if (currentToken() == Token::Identifier && m_dialect.findBuiltin(name.str()))
// Non-fatal. We'll continue and wrongly parse it as an identifier. May lead to some spurious
// errors after this point, but likely also much more useful ones.
m_errorReporter.parserError(
5568_error,
currentLocation(),
"Cannot use builtin function name \"" + name.str() + "\" as identifier name."
);
// NOTE: We keep the expectation here to ensure the correct source location for the error above.
expectToken(Token::Identifier);
return name;
}
void Parser::checkBreakContinuePosition(std::string const& _which)
{
switch (m_currentForLoopComponent)
{
case ForLoopComponent::None:
m_errorReporter.syntaxError(2592_error, currentLocation(), "Keyword \"" + _which + "\" needs to be inside a for-loop body.");
break;
case ForLoopComponent::ForLoopPre:
m_errorReporter.syntaxError(9615_error, currentLocation(), "Keyword \"" + _which + "\" in for-loop init block is not allowed.");
break;
case ForLoopComponent::ForLoopPost:
m_errorReporter.syntaxError(2461_error, currentLocation(), "Keyword \"" + _which + "\" in for-loop post block is not allowed.");
break;
case ForLoopComponent::ForLoopBody:
break;
}
}
bool Parser::isValidNumberLiteral(std::string_view const _literal)
{
try
{
// Try to convert _literal to u256.
[[maybe_unused]] auto tmp = u256(_literal);
}
catch (...)
{
return false;
}
if (boost::starts_with(_literal, "0x"))
return true;
else
return _literal.find_first_not_of("0123456789") == std::string_view::npos;
}
void Parser::raiseUnsupportedTypesError(SourceLocation const& _location) const
{
m_errorReporter.parserError(5473_error, _location, "Types are not supported in untyped Yul.");
}