• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "stdio.h"
9 #include "src/sksl/SkSLASTNode.h"
10 #include "src/sksl/SkSLParser.h"
11 #include "src/sksl/ir/SkSLModifiers.h"
12 #include "src/sksl/ir/SkSLSymbolTable.h"
13 #include "src/sksl/ir/SkSLType.h"
14 
15 #ifndef SKSL_STANDALONE
16 #include "include/private/SkOnce.h"
17 #endif
18 
19 namespace SkSL {
20 
21 #define MAX_PARSE_DEPTH 50
22 
23 class AutoDepth {
24 public:
AutoDepth(Parser * p)25     AutoDepth(Parser* p)
26     : fParser(p)
27     , fDepth(0) {}
28 
~AutoDepth()29     ~AutoDepth() {
30         fParser->fDepth -= fDepth;
31     }
32 
increase()33     bool increase() {
34         ++fDepth;
35         ++fParser->fDepth;
36         if (fParser->fDepth > MAX_PARSE_DEPTH) {
37             fParser->error(fParser->peek(), String("exceeded max parse depth"));
38             return false;
39         }
40         return true;
41     }
42 
43 private:
44     Parser* fParser;
45     int fDepth;
46 };
47 
48 std::unordered_map<String, Parser::LayoutToken>* Parser::layoutTokens;
49 
InitLayoutMap()50 void Parser::InitLayoutMap() {
51     layoutTokens = new std::unordered_map<String, LayoutToken>;
52     #define TOKEN(name, text) (*layoutTokens)[text] = LayoutToken::name
53     TOKEN(LOCATION,                     "location");
54     TOKEN(OFFSET,                       "offset");
55     TOKEN(BINDING,                      "binding");
56     TOKEN(INDEX,                        "index");
57     TOKEN(SET,                          "set");
58     TOKEN(BUILTIN,                      "builtin");
59     TOKEN(INPUT_ATTACHMENT_INDEX,       "input_attachment_index");
60     TOKEN(ORIGIN_UPPER_LEFT,            "origin_upper_left");
61     TOKEN(OVERRIDE_COVERAGE,            "override_coverage");
62     TOKEN(BLEND_SUPPORT_ALL_EQUATIONS,  "blend_support_all_equations");
63     TOKEN(BLEND_SUPPORT_MULTIPLY,       "blend_support_multiply");
64     TOKEN(BLEND_SUPPORT_SCREEN,         "blend_support_screen");
65     TOKEN(BLEND_SUPPORT_OVERLAY,        "blend_support_overlay");
66     TOKEN(BLEND_SUPPORT_DARKEN,         "blend_support_darken");
67     TOKEN(BLEND_SUPPORT_LIGHTEN,        "blend_support_lighten");
68     TOKEN(BLEND_SUPPORT_COLORDODGE,     "blend_support_colordodge");
69     TOKEN(BLEND_SUPPORT_COLORBURN,      "blend_support_colorburn");
70     TOKEN(BLEND_SUPPORT_HARDLIGHT,      "blend_support_hardlight");
71     TOKEN(BLEND_SUPPORT_SOFTLIGHT,      "blend_support_softlight");
72     TOKEN(BLEND_SUPPORT_DIFFERENCE,     "blend_support_difference");
73     TOKEN(BLEND_SUPPORT_EXCLUSION,      "blend_support_exclusion");
74     TOKEN(BLEND_SUPPORT_HSL_HUE,        "blend_support_hsl_hue");
75     TOKEN(BLEND_SUPPORT_HSL_SATURATION, "blend_support_hsl_saturation");
76     TOKEN(BLEND_SUPPORT_HSL_COLOR,      "blend_support_hsl_color");
77     TOKEN(BLEND_SUPPORT_HSL_LUMINOSITY, "blend_support_hsl_luminosity");
78     TOKEN(PUSH_CONSTANT,                "push_constant");
79     TOKEN(POINTS,                       "points");
80     TOKEN(LINES,                        "lines");
81     TOKEN(LINE_STRIP,                   "line_strip");
82     TOKEN(LINES_ADJACENCY,              "lines_adjacency");
83     TOKEN(TRIANGLES,                    "triangles");
84     TOKEN(TRIANGLE_STRIP,               "triangle_strip");
85     TOKEN(TRIANGLES_ADJACENCY,          "triangles_adjacency");
86     TOKEN(MAX_VERTICES,                 "max_vertices");
87     TOKEN(INVOCATIONS,                  "invocations");
88     TOKEN(WHEN,                         "when");
89     TOKEN(KEY,                          "key");
90     TOKEN(TRACKED,                      "tracked");
91     TOKEN(CTYPE,                        "ctype");
92     TOKEN(SKPMCOLOR4F,                  "SkPMColor4f");
93     TOKEN(SKV4,                         "SkV4");
94     TOKEN(SKRECT,                       "SkRect");
95     TOKEN(SKIRECT,                      "SkIRect");
96     TOKEN(SKPMCOLOR,                    "SkPMColor");
97     TOKEN(SKM44,                        "SkM44");
98     TOKEN(BOOL,                         "bool");
99     TOKEN(INT,                          "int");
100     TOKEN(FLOAT,                        "float");
101     #undef TOKEN
102 }
103 
Parser(const char * text,size_t length,SymbolTable & types,ErrorReporter & errors)104 Parser::Parser(const char* text, size_t length, SymbolTable& types, ErrorReporter& errors)
105 : fText(text)
106 , fPushback(Token::INVALID, -1, -1)
107 , fTypes(types)
108 , fErrors(errors) {
109     fLexer.start(text, length);
110     static const bool layoutMapInitialized = []{ return (void)InitLayoutMap(), true; }();
111     (void) layoutMapInitialized;
112 }
113 
114 #define CREATE_NODE(result, ...)              \
115     ASTNode::ID result(fFile->fNodes.size()); \
116     fFile->fNodes.emplace_back(&fFile->fNodes, __VA_ARGS__)
117 
118 #define RETURN_NODE(...)                  \
119     do {                                  \
120         CREATE_NODE(result, __VA_ARGS__); \
121         return result;                    \
122     } while (false)
123 
124 #define CREATE_CHILD(child, target, ...)   \
125     CREATE_NODE(child, __VA_ARGS__);       \
126     fFile->fNodes[target.fValue].addChild(child)
127 
128 #define CREATE_EMPTY_CHILD(target)                    \
129     do {                                              \
130         ASTNode::ID child(fFile->fNodes.size());      \
131         fFile->fNodes.emplace_back();                 \
132         fFile->fNodes[target.fValue].addChild(child); \
133     } while (false)
134 
135 /* (directive | section | declaration)* END_OF_FILE */
file()136 std::unique_ptr<ASTFile> Parser::file() {
137     fFile.reset(new ASTFile());
138     CREATE_NODE(result, 0, ASTNode::Kind::kFile);
139     fFile->fRoot = result;
140     for (;;) {
141         switch (this->peek().fKind) {
142             case Token::END_OF_FILE:
143                 return std::move(fFile);
144             case Token::DIRECTIVE: {
145                 ASTNode::ID dir = this->directive();
146                 if (fErrors.errorCount()) {
147                     return nullptr;
148                 }
149                 if (dir) {
150                     getNode(result).addChild(dir);
151                 }
152                 break;
153             }
154             case Token::SECTION: {
155                 ASTNode::ID section = this->section();
156                 if (fErrors.errorCount()) {
157                     return nullptr;
158                 }
159                 if (section) {
160                     getNode(result).addChild(section);
161                 }
162                 break;
163             }
164             default: {
165                 ASTNode::ID decl = this->declaration();
166                 if (fErrors.errorCount()) {
167                     return nullptr;
168                 }
169                 if (decl) {
170                     getNode(result).addChild(decl);
171                 }
172             }
173         }
174     }
175     return std::move(fFile);
176 }
177 
nextRawToken()178 Token Parser::nextRawToken() {
179     if (fPushback.fKind != Token::INVALID) {
180         Token result = fPushback;
181         fPushback.fKind = Token::INVALID;
182         return result;
183     }
184     Token result = fLexer.next();
185     return result;
186 }
187 
nextToken()188 Token Parser::nextToken() {
189     Token token = this->nextRawToken();
190     while (token.fKind == Token::WHITESPACE || token.fKind == Token::LINE_COMMENT ||
191            token.fKind == Token::BLOCK_COMMENT) {
192         token = this->nextRawToken();
193     }
194     return token;
195 }
196 
pushback(Token t)197 void Parser::pushback(Token t) {
198     SkASSERT(fPushback.fKind == Token::INVALID);
199     fPushback = std::move(t);
200 }
201 
peek()202 Token Parser::peek() {
203     if (fPushback.fKind == Token::INVALID) {
204         fPushback = this->nextToken();
205     }
206     return fPushback;
207 }
208 
checkNext(Token::Kind kind,Token * result)209 bool Parser::checkNext(Token::Kind kind, Token* result) {
210     if (fPushback.fKind != Token::INVALID && fPushback.fKind != kind) {
211         return false;
212     }
213     Token next = this->nextToken();
214     if (next.fKind == kind) {
215         if (result) {
216             *result = next;
217         }
218         return true;
219     }
220     this->pushback(std::move(next));
221     return false;
222 }
223 
expect(Token::Kind kind,const char * expected,Token * result)224 bool Parser::expect(Token::Kind kind, const char* expected, Token* result) {
225     Token next = this->nextToken();
226     if (next.fKind == kind) {
227         if (result) {
228             *result = std::move(next);
229         }
230         return true;
231     } else {
232         this->error(next, "expected " + String(expected) + ", but found '" +
233                     this->text(next) + "'");
234         return false;
235     }
236 }
237 
text(Token token)238 StringFragment Parser::text(Token token) {
239     return StringFragment(fText + token.fOffset, token.fLength);
240 }
241 
error(Token token,String msg)242 void Parser::error(Token token, String msg) {
243     this->error(token.fOffset, msg);
244 }
245 
error(int offset,String msg)246 void Parser::error(int offset, String msg) {
247     fErrors.error(offset, msg);
248 }
249 
isType(StringFragment name)250 bool Parser::isType(StringFragment name) {
251     return nullptr != fTypes[name];
252 }
253 
254 /* DIRECTIVE(#version) INT_LITERAL ("es" | "compatibility")? |
255    DIRECTIVE(#extension) IDENTIFIER COLON IDENTIFIER */
directive()256 ASTNode::ID Parser::directive() {
257     Token start;
258     if (!this->expect(Token::DIRECTIVE, "a directive", &start)) {
259         return ASTNode::ID::Invalid();
260     }
261     StringFragment text = this->text(start);
262     if (text == "#extension") {
263         Token name;
264         if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
265             return ASTNode::ID::Invalid();
266         }
267         if (!this->expect(Token::COLON, "':'")) {
268             return ASTNode::ID::Invalid();
269         }
270         // FIXME: need to start paying attention to this token
271         if (!this->expect(Token::IDENTIFIER, "an identifier")) {
272             return ASTNode::ID::Invalid();
273         }
274         RETURN_NODE(start.fOffset, ASTNode::Kind::kExtension, this->text(name));
275     } else {
276         this->error(start, "unsupported directive '" + this->text(start) + "'");
277         return ASTNode::ID::Invalid();
278     }
279 }
280 
281 /* SECTION LBRACE (LPAREN IDENTIFIER RPAREN)? <any sequence of tokens with balanced braces>
282    RBRACE */
section()283 ASTNode::ID Parser::section() {
284     Token start;
285     if (!this->expect(Token::SECTION, "a section token", &start)) {
286         return ASTNode::ID::Invalid();
287     }
288     StringFragment argument;
289     if (this->peek().fKind == Token::LPAREN) {
290         this->nextToken();
291         Token argToken;
292         if (!this->expect(Token::IDENTIFIER, "an identifier", &argToken)) {
293             return ASTNode::ID::Invalid();
294         }
295         argument = this->text(argToken);
296         if (!this->expect(Token::RPAREN, "')'")) {
297             return ASTNode::ID::Invalid();
298         }
299     }
300     if (!this->expect(Token::LBRACE, "'{'")) {
301         return ASTNode::ID::Invalid();
302     }
303     StringFragment text;
304     Token codeStart = this->nextRawToken();
305     size_t startOffset = codeStart.fOffset;
306     this->pushback(codeStart);
307     text.fChars = fText + startOffset;
308     int level = 1;
309     for (;;) {
310         Token next = this->nextRawToken();
311         switch (next.fKind) {
312             case Token::LBRACE:
313                 ++level;
314                 break;
315             case Token::RBRACE:
316                 --level;
317                 break;
318             case Token::END_OF_FILE:
319                 this->error(start, "reached end of file while parsing section");
320                 return ASTNode::ID::Invalid();
321             default:
322                 break;
323         }
324         if (!level) {
325             text.fLength = next.fOffset - startOffset;
326             break;
327         }
328     }
329     StringFragment name = this->text(start);
330     ++name.fChars;
331     --name.fLength;
332     RETURN_NODE(start.fOffset, ASTNode::Kind::kSection,
333                 ASTNode::SectionData(name, argument, text));
334 }
335 
336 /* ENUM CLASS IDENTIFIER LBRACE (IDENTIFIER (EQ expression)? (COMMA IDENTIFIER (EQ expression))*)?
337    RBRACE */
enumDeclaration()338 ASTNode::ID Parser::enumDeclaration() {
339     Token start;
340     if (!this->expect(Token::ENUM, "'enum'", &start)) {
341         return ASTNode::ID::Invalid();
342     }
343     if (!this->expect(Token::CLASS, "'class'")) {
344         return ASTNode::ID::Invalid();
345     }
346     Token name;
347     if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
348         return ASTNode::ID::Invalid();
349     }
350     if (!this->expect(Token::LBRACE, "'{'")) {
351         return ASTNode::ID::Invalid();
352     }
353     fTypes.add(this->text(name), std::unique_ptr<Symbol>(new Type(this->text(name),
354                                                                   Type::kEnum_Kind)));
355     CREATE_NODE(result, name.fOffset, ASTNode::Kind::kEnum, this->text(name));
356     if (!this->checkNext(Token::RBRACE)) {
357         Token id;
358         if (!this->expect(Token::IDENTIFIER, "an identifier", &id)) {
359             return ASTNode::ID::Invalid();
360         }
361         if (this->checkNext(Token::EQ)) {
362             ASTNode::ID value = this->assignmentExpression();
363             if (!value) {
364                 return ASTNode::ID::Invalid();
365             }
366             CREATE_CHILD(child, result, id.fOffset, ASTNode::Kind::kEnumCase, this->text(id));
367             getNode(child).addChild(value);
368         } else {
369             CREATE_CHILD(child, result, id.fOffset, ASTNode::Kind::kEnumCase, this->text(id));
370         }
371         while (!this->checkNext(Token::RBRACE)) {
372             if (!this->expect(Token::COMMA, "','")) {
373                 return ASTNode::ID::Invalid();
374             }
375             if (!this->expect(Token::IDENTIFIER, "an identifier", &id)) {
376                 return ASTNode::ID::Invalid();
377             }
378             if (this->checkNext(Token::EQ)) {
379                 ASTNode::ID value = this->assignmentExpression();
380                 if (!value) {
381                     return ASTNode::ID::Invalid();
382                 }
383                 CREATE_CHILD(child, result, id.fOffset, ASTNode::Kind::kEnumCase, this->text(id));
384                 getNode(child).addChild(value);
385             } else {
386                 CREATE_CHILD(child, result, id.fOffset, ASTNode::Kind::kEnumCase, this->text(id));
387             }
388         }
389     }
390     this->expect(Token::SEMICOLON, "';'");
391     return result;
392 }
393 
394 /* enumDeclaration | modifiers (structVarDeclaration | type IDENTIFIER ((LPAREN parameter
395    (COMMA parameter)* RPAREN (block | SEMICOLON)) | SEMICOLON) | interfaceBlock) */
declaration()396 ASTNode::ID Parser::declaration() {
397     Token lookahead = this->peek();
398     if (lookahead.fKind == Token::ENUM) {
399         return this->enumDeclaration();
400     }
401     Modifiers modifiers = this->modifiers();
402     lookahead = this->peek();
403     if (lookahead.fKind == Token::IDENTIFIER && !this->isType(this->text(lookahead))) {
404         // we have an identifier that's not a type, could be the start of an interface block
405         return this->interfaceBlock(modifiers);
406     }
407     if (lookahead.fKind == Token::STRUCT) {
408         return this->structVarDeclaration(modifiers);
409     }
410     if (lookahead.fKind == Token::SEMICOLON) {
411         this->nextToken();
412         RETURN_NODE(lookahead.fOffset, ASTNode::Kind::kModifiers, modifiers);
413     }
414     ASTNode::ID type = this->type();
415     if (!type) {
416         return ASTNode::ID::Invalid();
417     }
418     if (getNode(type).getTypeData().fIsStructDeclaration && this->checkNext(Token::SEMICOLON)) {
419         return ASTNode::ID::Invalid();
420     }
421     Token name;
422     if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
423         return ASTNode::ID::Invalid();
424     }
425     if (this->checkNext(Token::LPAREN)) {
426         CREATE_NODE(result, name.fOffset, ASTNode::Kind::kFunction);
427         ASTNode::FunctionData fd(modifiers, this->text(name), 0);
428         getNode(result).addChild(type);
429         if (this->peek().fKind != Token::RPAREN) {
430             for (;;) {
431                 ASTNode::ID parameter = this->parameter();
432                 if (!parameter) {
433                     return ASTNode::ID::Invalid();
434                 }
435                 ++fd.fParameterCount;
436                 getNode(result).addChild(parameter);
437                 if (!this->checkNext(Token::COMMA)) {
438                     break;
439                 }
440             }
441         }
442         getNode(result).setFunctionData(fd);
443         if (!this->expect(Token::RPAREN, "')'")) {
444             return ASTNode::ID::Invalid();
445         }
446         ASTNode::ID body;
447         if (!this->checkNext(Token::SEMICOLON)) {
448             body = this->block();
449             if (!body) {
450                 return ASTNode::ID::Invalid();
451             }
452             getNode(result).addChild(body);
453         }
454         return result;
455     } else {
456         return this->varDeclarationEnd(modifiers, type, this->text(name));
457     }
458 }
459 
460 /* modifiers type IDENTIFIER varDeclarationEnd */
varDeclarations()461 ASTNode::ID Parser::varDeclarations() {
462     Modifiers modifiers = this->modifiers();
463     ASTNode::ID type = this->type();
464     if (!type) {
465         return ASTNode::ID::Invalid();
466     }
467     Token name;
468     if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
469         return ASTNode::ID::Invalid();
470     }
471     return this->varDeclarationEnd(modifiers, type, this->text(name));
472 }
473 
474 /* STRUCT IDENTIFIER LBRACE varDeclaration* RBRACE */
structDeclaration()475 ASTNode::ID Parser::structDeclaration() {
476     if (!this->expect(Token::STRUCT, "'struct'")) {
477         return ASTNode::ID::Invalid();
478     }
479     Token name;
480     if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
481         return ASTNode::ID::Invalid();
482     }
483     if (!this->expect(Token::LBRACE, "'{'")) {
484         return ASTNode::ID::Invalid();
485     }
486     std::vector<Type::Field> fields;
487     while (this->peek().fKind != Token::RBRACE) {
488         ASTNode::ID decls = this->varDeclarations();
489         if (!decls) {
490             return ASTNode::ID::Invalid();
491         }
492         ASTNode& declsNode = getNode(decls);
493         auto type = (const Type*) fTypes[(declsNode.begin() + 1)->getTypeData().fName];
494         for (auto iter = declsNode.begin() + 2; iter != declsNode.end(); ++iter) {
495             ASTNode& var = *iter;
496             ASTNode::VarData vd = var.getVarData();
497             for (int j = vd.fSizeCount - 1; j >= 0; j--) {
498                 const ASTNode& size = *(var.begin() + j);
499                 if (!size || size.fKind != ASTNode::Kind::kInt) {
500                     this->error(declsNode.fOffset, "array size in struct field must be a constant");
501                     return ASTNode::ID::Invalid();
502                 }
503                 uint64_t columns = size.getInt();
504                 String name = type->name() + "[" + to_string(columns) + "]";
505                 type = (Type*) fTypes.takeOwnership(std::unique_ptr<Symbol>(
506                                                                          new Type(name,
507                                                                                   Type::kArray_Kind,
508                                                                                   *type,
509                                                                                   (int) columns)));
510             }
511             fields.push_back(Type::Field(declsNode.begin()->getModifiers(), vd.fName, type));
512             if (vd.fSizeCount ? (var.begin() + (vd.fSizeCount - 1))->fNext : var.fFirstChild) {
513                 this->error(declsNode.fOffset, "initializers are not permitted on struct fields");
514             }
515         }
516     }
517     if (!this->expect(Token::RBRACE, "'}'")) {
518         return ASTNode::ID::Invalid();
519     }
520     fTypes.add(this->text(name), std::unique_ptr<Type>(new Type(name.fOffset, this->text(name),
521                                                                 fields)));
522     RETURN_NODE(name.fOffset, ASTNode::Kind::kType,
523                 ASTNode::TypeData(this->text(name), true, false));
524 }
525 
526 /* structDeclaration ((IDENTIFIER varDeclarationEnd) | SEMICOLON) */
structVarDeclaration(Modifiers modifiers)527 ASTNode::ID Parser::structVarDeclaration(Modifiers modifiers) {
528     ASTNode::ID type = this->structDeclaration();
529     if (!type) {
530         return ASTNode::ID::Invalid();
531     }
532     Token name;
533     if (this->checkNext(Token::IDENTIFIER, &name)) {
534         return this->varDeclarationEnd(modifiers, std::move(type), this->text(name));
535     }
536     this->expect(Token::SEMICOLON, "';'");
537     return ASTNode::ID::Invalid();
538 }
539 
540 /* (LBRACKET expression? RBRACKET)* (EQ assignmentExpression)? (COMMA IDENTIFER
541    (LBRACKET expression? RBRACKET)* (EQ assignmentExpression)?)* SEMICOLON */
varDeclarationEnd(Modifiers mods,ASTNode::ID type,StringFragment name)542 ASTNode::ID Parser::varDeclarationEnd(Modifiers mods, ASTNode::ID type, StringFragment name) {
543     CREATE_NODE(result, -1, ASTNode::Kind::kVarDeclarations);
544     CREATE_CHILD(modifiers, result, -1, ASTNode::Kind::kModifiers, mods);
545     getNode(result).addChild(type);
546     CREATE_NODE(currentVar, -1, ASTNode::Kind::kVarDeclaration);
547     ASTNode::VarData vd(name, 0);
548     getNode(result).addChild(currentVar);
549     while (this->checkNext(Token::LBRACKET)) {
550         if (this->checkNext(Token::RBRACKET)) {
551             CREATE_EMPTY_CHILD(currentVar);
552         } else {
553             ASTNode::ID size = this->expression();
554             if (!size) {
555                 return ASTNode::ID::Invalid();
556             }
557             getNode(currentVar).addChild(size);
558             if (!this->expect(Token::RBRACKET, "']'")) {
559                 return ASTNode::ID::Invalid();
560             }
561         }
562         ++vd.fSizeCount;
563     }
564     getNode(currentVar).setVarData(vd);
565     if (this->checkNext(Token::EQ)) {
566         ASTNode::ID value = this->assignmentExpression();
567         if (!value) {
568             return ASTNode::ID::Invalid();
569         }
570         getNode(currentVar).addChild(value);
571     }
572     while (this->checkNext(Token::COMMA)) {
573         Token name;
574         if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
575             return ASTNode::ID::Invalid();
576         }
577         currentVar = ASTNode::ID(fFile->fNodes.size());
578         vd = ASTNode::VarData(this->text(name), 0);
579         fFile->fNodes.emplace_back(&fFile->fNodes, -1, ASTNode::Kind::kVarDeclaration);
580         getNode(result).addChild(currentVar);
581         while (this->checkNext(Token::LBRACKET)) {
582             if (this->checkNext(Token::RBRACKET)) {
583                 CREATE_EMPTY_CHILD(currentVar);
584             } else {
585                 ASTNode::ID size = this->expression();
586                 if (!size) {
587                     return ASTNode::ID::Invalid();
588                 }
589                 getNode(currentVar).addChild(size);
590                 if (!this->expect(Token::RBRACKET, "']'")) {
591                     return ASTNode::ID::Invalid();
592                 }
593             }
594             ++vd.fSizeCount;
595         }
596         getNode(currentVar).setVarData(vd);
597         if (this->checkNext(Token::EQ)) {
598             ASTNode::ID value = this->assignmentExpression();
599             if (!value) {
600                 return ASTNode::ID::Invalid();
601             }
602             getNode(currentVar).addChild(value);
603         }
604     }
605     if (!this->expect(Token::SEMICOLON, "';'")) {
606         return ASTNode::ID::Invalid();
607     }
608     return result;
609 }
610 
611 /* modifiers type IDENTIFIER (LBRACKET INT_LITERAL RBRACKET)? */
parameter()612 ASTNode::ID Parser::parameter() {
613     Modifiers modifiers = this->modifiersWithDefaults(0);
614     ASTNode::ID type = this->type();
615     if (!type) {
616         return ASTNode::ID::Invalid();
617     }
618     Token name;
619     if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
620         return ASTNode::ID::Invalid();
621     }
622     CREATE_NODE(result, name.fOffset, ASTNode::Kind::kParameter);
623     ASTNode::ParameterData pd(modifiers, this->text(name), 0);
624     getNode(result).addChild(type);
625     while (this->checkNext(Token::LBRACKET)) {
626         Token sizeToken;
627         if (!this->expect(Token::INT_LITERAL, "a positive integer", &sizeToken)) {
628             return ASTNode::ID::Invalid();
629         }
630         CREATE_CHILD(child, result, sizeToken.fOffset, ASTNode::Kind::kInt,
631                      SkSL::stoi(this->text(sizeToken)));
632         if (!this->expect(Token::RBRACKET, "']'")) {
633             return ASTNode::ID::Invalid();
634         }
635         ++pd.fSizeCount;
636     }
637     getNode(result).setParameterData(pd);
638     return result;
639 }
640 
641 /** EQ INT_LITERAL */
layoutInt()642 int Parser::layoutInt() {
643     if (!this->expect(Token::EQ, "'='")) {
644         return -1;
645     }
646     Token resultToken;
647     if (this->expect(Token::INT_LITERAL, "a non-negative integer", &resultToken)) {
648         return SkSL::stoi(this->text(resultToken));
649     }
650     return -1;
651 }
652 
653 /** EQ IDENTIFIER */
layoutIdentifier()654 StringFragment Parser::layoutIdentifier() {
655     if (!this->expect(Token::EQ, "'='")) {
656         return StringFragment();
657     }
658     Token resultToken;
659     if (!this->expect(Token::IDENTIFIER, "an identifier", &resultToken)) {
660         return StringFragment();
661     }
662     return this->text(resultToken);
663 }
664 
665 
666 /** EQ <any sequence of tokens with balanced parentheses and no top-level comma> */
layoutCode()667 StringFragment Parser::layoutCode() {
668     if (!this->expect(Token::EQ, "'='")) {
669         return "";
670     }
671     Token start = this->nextRawToken();
672     this->pushback(start);
673     StringFragment code;
674     code.fChars = fText + start.fOffset;
675     int level = 1;
676     bool done = false;
677     while (!done) {
678         Token next = this->nextRawToken();
679         switch (next.fKind) {
680             case Token::LPAREN:
681                 ++level;
682                 break;
683             case Token::RPAREN:
684                 --level;
685                 break;
686             case Token::COMMA:
687                 if (level == 1) {
688                     done = true;
689                 }
690                 break;
691             case Token::END_OF_FILE:
692                 this->error(start, "reached end of file while parsing layout");
693                 return "";
694             default:
695                 break;
696         }
697         if (!level) {
698             done = true;
699         }
700         if (done) {
701             code.fLength = next.fOffset - start.fOffset;
702             this->pushback(std::move(next));
703         }
704     }
705     return code;
706 }
707 
708 /** (EQ IDENTIFIER('identity'))? */
layoutKey()709 Layout::Key Parser::layoutKey() {
710     if (this->peek().fKind == Token::EQ) {
711         this->expect(Token::EQ, "'='");
712         Token key;
713         if (this->expect(Token::IDENTIFIER, "an identifer", &key)) {
714             if (this->text(key) == "identity") {
715                 return Layout::kIdentity_Key;
716             } else {
717                 this->error(key, "unsupported layout key");
718             }
719         }
720     }
721     return Layout::kKey_Key;
722 }
723 
layoutCType()724 Layout::CType Parser::layoutCType() {
725     if (this->expect(Token::EQ, "'='")) {
726         Token t = this->nextToken();
727         String text = this->text(t);
728         auto found = layoutTokens->find(text);
729         if (found != layoutTokens->end()) {
730             switch (found->second) {
731                 case LayoutToken::SKPMCOLOR4F:
732                     return Layout::CType::kSkPMColor4f;
733                 case LayoutToken::SKV4:
734                     return Layout::CType::kSkV4;
735                 case LayoutToken::SKRECT:
736                     return Layout::CType::kSkRect;
737                 case LayoutToken::SKIRECT:
738                     return Layout::CType::kSkIRect;
739                 case LayoutToken::SKPMCOLOR:
740                     return Layout::CType::kSkPMColor;
741                 case LayoutToken::BOOL:
742                     return Layout::CType::kBool;
743                 case LayoutToken::INT:
744                     return Layout::CType::kInt32;
745                 case LayoutToken::FLOAT:
746                     return Layout::CType::kFloat;
747                 case LayoutToken::SKM44:
748                     return Layout::CType::kSkM44;
749                 default:
750                     break;
751             }
752         }
753         this->error(t, "unsupported ctype");
754     }
755     return Layout::CType::kDefault;
756 }
757 
758 /* LAYOUT LPAREN IDENTIFIER (EQ INT_LITERAL)? (COMMA IDENTIFIER (EQ INT_LITERAL)?)* RPAREN */
layout()759 Layout Parser::layout() {
760     int flags = 0;
761     int location = -1;
762     int offset = -1;
763     int binding = -1;
764     int index = -1;
765     int set = -1;
766     int builtin = -1;
767     int inputAttachmentIndex = -1;
768     Layout::Format format = Layout::Format::kUnspecified;
769     Layout::Primitive primitive = Layout::kUnspecified_Primitive;
770     int maxVertices = -1;
771     int invocations = -1;
772     StringFragment when;
773     Layout::Key key = Layout::kNo_Key;
774     Layout::CType ctype = Layout::CType::kDefault;
775     if (this->checkNext(Token::LAYOUT)) {
776         if (!this->expect(Token::LPAREN, "'('")) {
777             return Layout(flags, location, offset, binding, index, set, builtin,
778                           inputAttachmentIndex, format, primitive, maxVertices, invocations, when,
779                           key, ctype);
780         }
781         for (;;) {
782             Token t = this->nextToken();
783             String text = this->text(t);
784             auto found = layoutTokens->find(text);
785             if (found != layoutTokens->end()) {
786                 switch (found->second) {
787                     case LayoutToken::LOCATION:
788                         location = this->layoutInt();
789                         break;
790                     case LayoutToken::OFFSET:
791                         offset = this->layoutInt();
792                         break;
793                     case LayoutToken::BINDING:
794                         binding = this->layoutInt();
795                         break;
796                     case LayoutToken::INDEX:
797                         index = this->layoutInt();
798                         break;
799                     case LayoutToken::SET:
800                         set = this->layoutInt();
801                         break;
802                     case LayoutToken::BUILTIN:
803                         builtin = this->layoutInt();
804                         break;
805                     case LayoutToken::INPUT_ATTACHMENT_INDEX:
806                         inputAttachmentIndex = this->layoutInt();
807                         break;
808                     case LayoutToken::ORIGIN_UPPER_LEFT:
809                         flags |= Layout::kOriginUpperLeft_Flag;
810                         break;
811                     case LayoutToken::OVERRIDE_COVERAGE:
812                         flags |= Layout::kOverrideCoverage_Flag;
813                         break;
814                     case LayoutToken::BLEND_SUPPORT_ALL_EQUATIONS:
815                         flags |= Layout::kBlendSupportAllEquations_Flag;
816                         break;
817                     case LayoutToken::BLEND_SUPPORT_MULTIPLY:
818                         flags |= Layout::kBlendSupportMultiply_Flag;
819                         break;
820                     case LayoutToken::BLEND_SUPPORT_SCREEN:
821                         flags |= Layout::kBlendSupportScreen_Flag;
822                         break;
823                     case LayoutToken::BLEND_SUPPORT_OVERLAY:
824                         flags |= Layout::kBlendSupportOverlay_Flag;
825                         break;
826                     case LayoutToken::BLEND_SUPPORT_DARKEN:
827                         flags |= Layout::kBlendSupportDarken_Flag;
828                         break;
829                     case LayoutToken::BLEND_SUPPORT_LIGHTEN:
830                         flags |= Layout::kBlendSupportLighten_Flag;
831                         break;
832                     case LayoutToken::BLEND_SUPPORT_COLORDODGE:
833                         flags |= Layout::kBlendSupportColorDodge_Flag;
834                         break;
835                     case LayoutToken::BLEND_SUPPORT_COLORBURN:
836                         flags |= Layout::kBlendSupportColorBurn_Flag;
837                         break;
838                     case LayoutToken::BLEND_SUPPORT_HARDLIGHT:
839                         flags |= Layout::kBlendSupportHardLight_Flag;
840                         break;
841                     case LayoutToken::BLEND_SUPPORT_SOFTLIGHT:
842                         flags |= Layout::kBlendSupportSoftLight_Flag;
843                         break;
844                     case LayoutToken::BLEND_SUPPORT_DIFFERENCE:
845                         flags |= Layout::kBlendSupportDifference_Flag;
846                         break;
847                     case LayoutToken::BLEND_SUPPORT_EXCLUSION:
848                         flags |= Layout::kBlendSupportExclusion_Flag;
849                         break;
850                     case LayoutToken::BLEND_SUPPORT_HSL_HUE:
851                         flags |= Layout::kBlendSupportHSLHue_Flag;
852                         break;
853                     case LayoutToken::BLEND_SUPPORT_HSL_SATURATION:
854                         flags |= Layout::kBlendSupportHSLSaturation_Flag;
855                         break;
856                     case LayoutToken::BLEND_SUPPORT_HSL_COLOR:
857                         flags |= Layout::kBlendSupportHSLColor_Flag;
858                         break;
859                     case LayoutToken::BLEND_SUPPORT_HSL_LUMINOSITY:
860                         flags |= Layout::kBlendSupportHSLLuminosity_Flag;
861                         break;
862                     case LayoutToken::PUSH_CONSTANT:
863                         flags |= Layout::kPushConstant_Flag;
864                         break;
865                     case LayoutToken::TRACKED:
866                         flags |= Layout::kTracked_Flag;
867                         break;
868                     case LayoutToken::POINTS:
869                         primitive = Layout::kPoints_Primitive;
870                         break;
871                     case LayoutToken::LINES:
872                         primitive = Layout::kLines_Primitive;
873                         break;
874                     case LayoutToken::LINE_STRIP:
875                         primitive = Layout::kLineStrip_Primitive;
876                         break;
877                     case LayoutToken::LINES_ADJACENCY:
878                         primitive = Layout::kLinesAdjacency_Primitive;
879                         break;
880                     case LayoutToken::TRIANGLES:
881                         primitive = Layout::kTriangles_Primitive;
882                         break;
883                     case LayoutToken::TRIANGLE_STRIP:
884                         primitive = Layout::kTriangleStrip_Primitive;
885                         break;
886                     case LayoutToken::TRIANGLES_ADJACENCY:
887                         primitive = Layout::kTrianglesAdjacency_Primitive;
888                         break;
889                     case LayoutToken::MAX_VERTICES:
890                         maxVertices = this->layoutInt();
891                         break;
892                     case LayoutToken::INVOCATIONS:
893                         invocations = this->layoutInt();
894                         break;
895                     case LayoutToken::WHEN:
896                         when = this->layoutCode();
897                         break;
898                     case LayoutToken::KEY:
899                         key = this->layoutKey();
900                         break;
901                     case LayoutToken::CTYPE:
902                         ctype = this->layoutCType();
903                         break;
904                     default:
905                         this->error(t, ("'" + text + "' is not a valid layout qualifier").c_str());
906                         break;
907                 }
908             } else if (Layout::ReadFormat(text, &format)) {
909                // AST::ReadFormat stored the result in 'format'.
910             } else {
911                 this->error(t, ("'" + text + "' is not a valid layout qualifier").c_str());
912             }
913             if (this->checkNext(Token::RPAREN)) {
914                 break;
915             }
916             if (!this->expect(Token::COMMA, "','")) {
917                 break;
918             }
919         }
920     }
921     return Layout(flags, location, offset, binding, index, set, builtin, inputAttachmentIndex,
922                   format, primitive, maxVertices, invocations, when, key, ctype);
923 }
924 
925 /* layout? (UNIFORM | CONST | IN | OUT | INOUT | LOWP | MEDIUMP | HIGHP | FLAT | NOPERSPECTIVE |
926             READONLY | WRITEONLY | COHERENT | VOLATILE | RESTRICT | BUFFER | PLS | PLSIN |
927             PLSOUT)* */
modifiers()928 Modifiers Parser::modifiers() {
929     Layout layout = this->layout();
930     int flags = 0;
931     for (;;) {
932         // TODO: handle duplicate / incompatible flags
933         switch (peek().fKind) {
934             case Token::UNIFORM:
935                 this->nextToken();
936                 flags |= Modifiers::kUniform_Flag;
937                 break;
938             case Token::CONST:
939                 this->nextToken();
940                 flags |= Modifiers::kConst_Flag;
941                 break;
942             case Token::IN:
943                 this->nextToken();
944                 flags |= Modifiers::kIn_Flag;
945                 break;
946             case Token::OUT:
947                 this->nextToken();
948                 flags |= Modifiers::kOut_Flag;
949                 break;
950             case Token::INOUT:
951                 this->nextToken();
952                 flags |= Modifiers::kIn_Flag;
953                 flags |= Modifiers::kOut_Flag;
954                 break;
955             case Token::FLAT:
956                 this->nextToken();
957                 flags |= Modifiers::kFlat_Flag;
958                 break;
959             case Token::NOPERSPECTIVE:
960                 this->nextToken();
961                 flags |= Modifiers::kNoPerspective_Flag;
962                 break;
963             case Token::READONLY:
964                 this->nextToken();
965                 flags |= Modifiers::kReadOnly_Flag;
966                 break;
967             case Token::WRITEONLY:
968                 this->nextToken();
969                 flags |= Modifiers::kWriteOnly_Flag;
970                 break;
971             case Token::COHERENT:
972                 this->nextToken();
973                 flags |= Modifiers::kCoherent_Flag;
974                 break;
975             case Token::VOLATILE:
976                 this->nextToken();
977                 flags |= Modifiers::kVolatile_Flag;
978                 break;
979             case Token::RESTRICT:
980                 this->nextToken();
981                 flags |= Modifiers::kRestrict_Flag;
982                 break;
983             case Token::BUFFER:
984                 this->nextToken();
985                 flags |= Modifiers::kBuffer_Flag;
986                 break;
987             case Token::HASSIDEEFFECTS:
988                 this->nextToken();
989                 flags |= Modifiers::kHasSideEffects_Flag;
990                 break;
991             case Token::PLS:
992                 this->nextToken();
993                 flags |= Modifiers::kPLS_Flag;
994                 break;
995             case Token::PLSIN:
996                 this->nextToken();
997                 flags |= Modifiers::kPLSIn_Flag;
998                 break;
999             case Token::PLSOUT:
1000                 this->nextToken();
1001                 flags |= Modifiers::kPLSOut_Flag;
1002                 break;
1003             default:
1004                 return Modifiers(layout, flags);
1005         }
1006     }
1007 }
1008 
modifiersWithDefaults(int defaultFlags)1009 Modifiers Parser::modifiersWithDefaults(int defaultFlags) {
1010     Modifiers result = this->modifiers();
1011     if (!result.fFlags) {
1012         return Modifiers(result.fLayout, defaultFlags);
1013     }
1014     return result;
1015 }
1016 
1017 /* ifStatement | forStatement | doStatement | whileStatement | block | expression */
statement()1018 ASTNode::ID Parser::statement() {
1019     Token start = this->nextToken();
1020     AutoDepth depth(this);
1021     if (!depth.increase()) {
1022         return ASTNode::ID::Invalid();
1023     }
1024     this->pushback(start);
1025     switch (start.fKind) {
1026         case Token::IF: // fall through
1027         case Token::STATIC_IF:
1028             return this->ifStatement();
1029         case Token::FOR:
1030             return this->forStatement();
1031         case Token::DO:
1032             return this->doStatement();
1033         case Token::WHILE:
1034             return this->whileStatement();
1035         case Token::SWITCH: // fall through
1036         case Token::STATIC_SWITCH:
1037             return this->switchStatement();
1038         case Token::RETURN:
1039             return this->returnStatement();
1040         case Token::BREAK:
1041             return this->breakStatement();
1042         case Token::CONTINUE:
1043             return this->continueStatement();
1044         case Token::DISCARD:
1045             return this->discardStatement();
1046         case Token::LBRACE:
1047             return this->block();
1048         case Token::SEMICOLON:
1049             this->nextToken();
1050             RETURN_NODE(start.fOffset, ASTNode::Kind::kBlock);
1051         case Token::CONST:
1052             return this->varDeclarations();
1053         case Token::IDENTIFIER:
1054             if (this->isType(this->text(start))) {
1055                 return this->varDeclarations();
1056             }
1057             // fall through
1058         default:
1059             return this->expressionStatement();
1060     }
1061 }
1062 
1063 /* IDENTIFIER(type) (LBRACKET intLiteral? RBRACKET)* QUESTION? */
type()1064 ASTNode::ID Parser::type() {
1065     Token type;
1066     if (!this->expect(Token::IDENTIFIER, "a type", &type)) {
1067         return ASTNode::ID::Invalid();
1068     }
1069     if (!this->isType(this->text(type))) {
1070         this->error(type, ("no type named '" + this->text(type) + "'").c_str());
1071         return ASTNode::ID::Invalid();
1072     }
1073     CREATE_NODE(result, type.fOffset, ASTNode::Kind::kType);
1074     ASTNode::TypeData td(this->text(type), false, false);
1075     while (this->checkNext(Token::LBRACKET)) {
1076         if (this->peek().fKind != Token::RBRACKET) {
1077             SKSL_INT i;
1078             if (this->intLiteral(&i)) {
1079                 CREATE_CHILD(child, result, -1, ASTNode::Kind::kInt, i);
1080             } else {
1081                 return ASTNode::ID::Invalid();
1082             }
1083         } else {
1084             CREATE_EMPTY_CHILD(result);
1085         }
1086         this->expect(Token::RBRACKET, "']'");
1087     }
1088     td.fIsNullable = this->checkNext(Token::QUESTION);
1089     getNode(result).setTypeData(td);
1090     return result;
1091 }
1092 
1093 /* IDENTIFIER LBRACE varDeclaration* RBRACE (IDENTIFIER (LBRACKET expression? RBRACKET)*)? */
interfaceBlock(Modifiers mods)1094 ASTNode::ID Parser::interfaceBlock(Modifiers mods) {
1095     Token name;
1096     if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
1097         return ASTNode::ID::Invalid();
1098     }
1099     if (peek().fKind != Token::LBRACE) {
1100         // we only get into interfaceBlock if we found a top-level identifier which was not a type.
1101         // 99% of the time, the user was not actually intending to create an interface block, so
1102         // it's better to report it as an unknown type
1103         this->error(name, "no type named '" + this->text(name) + "'");
1104         return ASTNode::ID::Invalid();
1105     }
1106     CREATE_NODE(result, name.fOffset, ASTNode::Kind::kInterfaceBlock);
1107     ASTNode::InterfaceBlockData id(mods, this->text(name), 0, "", 0);
1108     this->nextToken();
1109     while (this->peek().fKind != Token::RBRACE) {
1110         ASTNode::ID decl = this->varDeclarations();
1111         if (!decl) {
1112             return ASTNode::ID::Invalid();
1113         }
1114         getNode(result).addChild(decl);
1115         ++id.fDeclarationCount;
1116     }
1117     this->nextToken();
1118     std::vector<ASTNode> sizes;
1119     StringFragment instanceName;
1120     Token instanceNameToken;
1121     if (this->checkNext(Token::IDENTIFIER, &instanceNameToken)) {
1122         id.fInstanceName = this->text(instanceNameToken);
1123         while (this->checkNext(Token::LBRACKET)) {
1124             if (this->peek().fKind != Token::RBRACKET) {
1125                 ASTNode::ID size = this->expression();
1126                 if (!size) {
1127                     return ASTNode::ID::Invalid();
1128                 }
1129                 getNode(result).addChild(size);
1130             } else {
1131                 CREATE_EMPTY_CHILD(result);
1132             }
1133             ++id.fSizeCount;
1134             this->expect(Token::RBRACKET, "']'");
1135         }
1136         instanceName = this->text(instanceNameToken);
1137     }
1138     getNode(result).setInterfaceBlockData(id);
1139     this->expect(Token::SEMICOLON, "';'");
1140     return result;
1141 }
1142 
1143 /* IF LPAREN expression RPAREN statement (ELSE statement)? */
ifStatement()1144 ASTNode::ID Parser::ifStatement() {
1145     Token start;
1146     bool isStatic = this->checkNext(Token::STATIC_IF, &start);
1147     if (!isStatic && !this->expect(Token::IF, "'if'", &start)) {
1148         return ASTNode::ID::Invalid();
1149     }
1150     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kIf, isStatic);
1151     if (!this->expect(Token::LPAREN, "'('")) {
1152         return ASTNode::ID::Invalid();
1153     }
1154     ASTNode::ID test = this->expression();
1155     if (!test) {
1156         return ASTNode::ID::Invalid();
1157     }
1158     getNode(result).addChild(test);
1159     if (!this->expect(Token::RPAREN, "')'")) {
1160         return ASTNode::ID::Invalid();
1161     }
1162     ASTNode::ID ifTrue = this->statement();
1163     if (!ifTrue) {
1164         return ASTNode::ID::Invalid();
1165     }
1166     getNode(result).addChild(ifTrue);
1167     ASTNode::ID ifFalse;
1168     if (this->checkNext(Token::ELSE)) {
1169         ifFalse = this->statement();
1170         if (!ifFalse) {
1171             return ASTNode::ID::Invalid();
1172         }
1173         getNode(result).addChild(ifFalse);
1174     }
1175     return result;
1176 }
1177 
1178 /* DO statement WHILE LPAREN expression RPAREN SEMICOLON */
doStatement()1179 ASTNode::ID Parser::doStatement() {
1180     Token start;
1181     if (!this->expect(Token::DO, "'do'", &start)) {
1182         return ASTNode::ID::Invalid();
1183     }
1184     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kDo);
1185     ASTNode::ID statement = this->statement();
1186     if (!statement) {
1187         return ASTNode::ID::Invalid();
1188     }
1189     getNode(result).addChild(statement);
1190     if (!this->expect(Token::WHILE, "'while'")) {
1191         return ASTNode::ID::Invalid();
1192     }
1193     if (!this->expect(Token::LPAREN, "'('")) {
1194         return ASTNode::ID::Invalid();
1195     }
1196     ASTNode::ID test = this->expression();
1197     if (!test) {
1198         return ASTNode::ID::Invalid();
1199     }
1200     getNode(result).addChild(test);
1201     if (!this->expect(Token::RPAREN, "')'")) {
1202         return ASTNode::ID::Invalid();
1203     }
1204     if (!this->expect(Token::SEMICOLON, "';'")) {
1205         return ASTNode::ID::Invalid();
1206     }
1207     return result;
1208 }
1209 
1210 /* WHILE LPAREN expression RPAREN STATEMENT */
whileStatement()1211 ASTNode::ID Parser::whileStatement() {
1212     Token start;
1213     if (!this->expect(Token::WHILE, "'while'", &start)) {
1214         return ASTNode::ID::Invalid();
1215     }
1216     if (!this->expect(Token::LPAREN, "'('")) {
1217         return ASTNode::ID::Invalid();
1218     }
1219     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kWhile);
1220     ASTNode::ID test = this->expression();
1221     if (!test) {
1222         return ASTNode::ID::Invalid();
1223     }
1224     getNode(result).addChild(test);
1225     if (!this->expect(Token::RPAREN, "')'")) {
1226         return ASTNode::ID::Invalid();
1227     }
1228     ASTNode::ID statement = this->statement();
1229     if (!statement) {
1230         return ASTNode::ID::Invalid();
1231     }
1232     getNode(result).addChild(statement);
1233     return result;
1234 }
1235 
1236 /* CASE expression COLON statement* */
switchCase()1237 ASTNode::ID Parser::switchCase() {
1238     Token start;
1239     if (!this->expect(Token::CASE, "'case'", &start)) {
1240         return ASTNode::ID::Invalid();
1241     }
1242     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kSwitchCase);
1243     ASTNode::ID value = this->expression();
1244     if (!value) {
1245         return ASTNode::ID::Invalid();
1246     }
1247     if (!this->expect(Token::COLON, "':'")) {
1248         return ASTNode::ID::Invalid();
1249     }
1250     getNode(result).addChild(value);
1251     while (this->peek().fKind != Token::RBRACE && this->peek().fKind != Token::CASE &&
1252            this->peek().fKind != Token::DEFAULT) {
1253         ASTNode::ID s = this->statement();
1254         if (!s) {
1255             return ASTNode::ID::Invalid();
1256         }
1257         getNode(result).addChild(s);
1258     }
1259     return result;
1260 }
1261 
1262 /* SWITCH LPAREN expression RPAREN LBRACE switchCase* (DEFAULT COLON statement*)? RBRACE */
switchStatement()1263 ASTNode::ID Parser::switchStatement() {
1264     Token start;
1265     bool isStatic = this->checkNext(Token::STATIC_SWITCH, &start);
1266     if (!isStatic && !this->expect(Token::SWITCH, "'switch'", &start)) {
1267         return ASTNode::ID::Invalid();
1268     }
1269     if (!this->expect(Token::LPAREN, "'('")) {
1270         return ASTNode::ID::Invalid();
1271     }
1272     ASTNode::ID value = this->expression();
1273     if (!value) {
1274         return ASTNode::ID::Invalid();
1275     }
1276     if (!this->expect(Token::RPAREN, "')'")) {
1277         return ASTNode::ID::Invalid();
1278     }
1279     if (!this->expect(Token::LBRACE, "'{'")) {
1280         return ASTNode::ID::Invalid();
1281     }
1282     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kSwitch, isStatic);
1283     getNode(result).addChild(value);
1284     while (this->peek().fKind == Token::CASE) {
1285         ASTNode::ID c = this->switchCase();
1286         if (!c) {
1287             return ASTNode::ID::Invalid();
1288         }
1289         getNode(result).addChild(c);
1290     }
1291     // Requiring default: to be last (in defiance of C and GLSL) was a deliberate decision. Other
1292     // parts of the compiler may rely upon this assumption.
1293     if (this->peek().fKind == Token::DEFAULT) {
1294         Token defaultStart;
1295         SkAssertResult(this->expect(Token::DEFAULT, "'default'", &defaultStart));
1296         if (!this->expect(Token::COLON, "':'")) {
1297             return ASTNode::ID::Invalid();
1298         }
1299         CREATE_CHILD(defaultCase, result, defaultStart.fOffset, ASTNode::Kind::kSwitchCase);
1300         CREATE_EMPTY_CHILD(defaultCase); // empty test to signify default case
1301         while (this->peek().fKind != Token::RBRACE) {
1302             ASTNode::ID s = this->statement();
1303             if (!s) {
1304                 return ASTNode::ID::Invalid();
1305             }
1306             getNode(defaultCase).addChild(s);
1307         }
1308     }
1309     if (!this->expect(Token::RBRACE, "'}'")) {
1310         return ASTNode::ID::Invalid();
1311     }
1312     return result;
1313 }
1314 
1315 /* FOR LPAREN (declaration | expression)? SEMICOLON expression? SEMICOLON expression? RPAREN
1316    STATEMENT */
forStatement()1317 ASTNode::ID Parser::forStatement() {
1318     Token start;
1319     if (!this->expect(Token::FOR, "'for'", &start)) {
1320         return ASTNode::ID::Invalid();
1321     }
1322     if (!this->expect(Token::LPAREN, "'('")) {
1323         return ASTNode::ID::Invalid();
1324     }
1325     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kFor);
1326     ASTNode::ID initializer;
1327     Token nextToken = this->peek();
1328     switch (nextToken.fKind) {
1329         case Token::SEMICOLON:
1330             this->nextToken();
1331             CREATE_EMPTY_CHILD(result);
1332             break;
1333         case Token::CONST: {
1334             initializer = this->varDeclarations();
1335             if (!initializer) {
1336                 return ASTNode::ID::Invalid();
1337             }
1338             getNode(result).addChild(initializer);
1339             break;
1340         }
1341         case Token::IDENTIFIER: {
1342             if (this->isType(this->text(nextToken))) {
1343                 initializer = this->varDeclarations();
1344                 if (!initializer) {
1345                     return ASTNode::ID::Invalid();
1346                 }
1347                 getNode(result).addChild(initializer);
1348                 break;
1349             }
1350         } // fall through
1351         default:
1352             initializer = this->expressionStatement();
1353             if (!initializer) {
1354                 return ASTNode::ID::Invalid();
1355             }
1356             getNode(result).addChild(initializer);
1357     }
1358     ASTNode::ID test;
1359     if (this->peek().fKind != Token::SEMICOLON) {
1360         test = this->expression();
1361         if (!test) {
1362             return ASTNode::ID::Invalid();
1363         }
1364         getNode(result).addChild(test);
1365     } else {
1366         CREATE_EMPTY_CHILD(result);
1367     }
1368     if (!this->expect(Token::SEMICOLON, "';'")) {
1369         return ASTNode::ID::Invalid();
1370     }
1371     ASTNode::ID next;
1372     if (this->peek().fKind != Token::RPAREN) {
1373         next = this->expression();
1374         if (!next) {
1375             return ASTNode::ID::Invalid();
1376         }
1377         getNode(result).addChild(next);
1378     } else {
1379         CREATE_EMPTY_CHILD(result);
1380     }
1381     if (!this->expect(Token::RPAREN, "')'")) {
1382         return ASTNode::ID::Invalid();
1383     }
1384     ASTNode::ID statement = this->statement();
1385     if (!statement) {
1386         return ASTNode::ID::Invalid();
1387     }
1388     getNode(result).addChild(statement);
1389     return result;
1390 }
1391 
1392 /* RETURN expression? SEMICOLON */
returnStatement()1393 ASTNode::ID Parser::returnStatement() {
1394     Token start;
1395     if (!this->expect(Token::RETURN, "'return'", &start)) {
1396         return ASTNode::ID::Invalid();
1397     }
1398     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kReturn);
1399     if (this->peek().fKind != Token::SEMICOLON) {
1400         ASTNode::ID expression = this->expression();
1401         if (!expression) {
1402             return ASTNode::ID::Invalid();
1403         }
1404         getNode(result).addChild(expression);
1405     }
1406     if (!this->expect(Token::SEMICOLON, "';'")) {
1407         return ASTNode::ID::Invalid();
1408     }
1409     return result;
1410 }
1411 
1412 /* BREAK SEMICOLON */
breakStatement()1413 ASTNode::ID Parser::breakStatement() {
1414     Token start;
1415     if (!this->expect(Token::BREAK, "'break'", &start)) {
1416         return ASTNode::ID::Invalid();
1417     }
1418     if (!this->expect(Token::SEMICOLON, "';'")) {
1419         return ASTNode::ID::Invalid();
1420     }
1421     RETURN_NODE(start.fOffset, ASTNode::Kind::kBreak);
1422 }
1423 
1424 /* CONTINUE SEMICOLON */
continueStatement()1425 ASTNode::ID Parser::continueStatement() {
1426     Token start;
1427     if (!this->expect(Token::CONTINUE, "'continue'", &start)) {
1428         return ASTNode::ID::Invalid();
1429     }
1430     if (!this->expect(Token::SEMICOLON, "';'")) {
1431         return ASTNode::ID::Invalid();
1432     }
1433     RETURN_NODE(start.fOffset, ASTNode::Kind::kContinue);
1434 }
1435 
1436 /* DISCARD SEMICOLON */
discardStatement()1437 ASTNode::ID Parser::discardStatement() {
1438     Token start;
1439     if (!this->expect(Token::DISCARD, "'continue'", &start)) {
1440         return ASTNode::ID::Invalid();
1441     }
1442     if (!this->expect(Token::SEMICOLON, "';'")) {
1443         return ASTNode::ID::Invalid();
1444     }
1445     RETURN_NODE(start.fOffset, ASTNode::Kind::kDiscard);
1446 }
1447 
1448 /* LBRACE statement* RBRACE */
block()1449 ASTNode::ID Parser::block() {
1450     Token start;
1451     if (!this->expect(Token::LBRACE, "'{'", &start)) {
1452         return ASTNode::ID::Invalid();
1453     }
1454     AutoDepth depth(this);
1455     if (!depth.increase()) {
1456         return ASTNode::ID::Invalid();
1457     }
1458     CREATE_NODE(result, start.fOffset, ASTNode::Kind::kBlock);
1459     for (;;) {
1460         switch (this->peek().fKind) {
1461             case Token::RBRACE:
1462                 this->nextToken();
1463                 return result;
1464             case Token::END_OF_FILE:
1465                 this->error(this->peek(), "expected '}', but found end of file");
1466                 return ASTNode::ID::Invalid();
1467             default: {
1468                 ASTNode::ID statement = this->statement();
1469                 if (!statement) {
1470                     return ASTNode::ID::Invalid();
1471                 }
1472                 getNode(result).addChild(statement);
1473             }
1474         }
1475     }
1476     return result;
1477 }
1478 
1479 /* expression SEMICOLON */
expressionStatement()1480 ASTNode::ID Parser::expressionStatement() {
1481     ASTNode::ID expr = this->expression();
1482     if (expr) {
1483         if (this->expect(Token::SEMICOLON, "';'")) {
1484             return expr;
1485         }
1486     }
1487     return ASTNode::ID::Invalid();
1488 }
1489 
1490 /* assignmentExpression (COMMA assignmentExpression)* */
expression()1491 ASTNode::ID Parser::expression() {
1492     ASTNode::ID result = this->assignmentExpression();
1493     if (!result) {
1494         return ASTNode::ID::Invalid();
1495     }
1496     Token t;
1497     while (this->checkNext(Token::COMMA, &t)) {
1498         ASTNode::ID right = this->assignmentExpression();
1499         if (!right) {
1500             return ASTNode::ID::Invalid();
1501         }
1502         CREATE_NODE(newResult, t.fOffset, ASTNode::Kind::kBinary, std::move(t));
1503         getNode(newResult).addChild(result);
1504         getNode(newResult).addChild(right);
1505         result = newResult;
1506     }
1507     return result;
1508 }
1509 
1510 /* ternaryExpression ((EQEQ | STAREQ | SLASHEQ | PERCENTEQ | PLUSEQ | MINUSEQ | SHLEQ | SHREQ |
1511    BITWISEANDEQ | BITWISEXOREQ | BITWISEOREQ | LOGICALANDEQ | LOGICALXOREQ | LOGICALOREQ)
1512    assignmentExpression)*
1513  */
assignmentExpression()1514 ASTNode::ID Parser::assignmentExpression() {
1515     AutoDepth depth(this);
1516     ASTNode::ID result = this->ternaryExpression();
1517     if (!result) {
1518         return ASTNode::ID::Invalid();
1519     }
1520     for (;;) {
1521         switch (this->peek().fKind) {
1522             case Token::EQ:           // fall through
1523             case Token::STAREQ:       // fall through
1524             case Token::SLASHEQ:      // fall through
1525             case Token::PERCENTEQ:    // fall through
1526             case Token::PLUSEQ:       // fall through
1527             case Token::MINUSEQ:      // fall through
1528             case Token::SHLEQ:        // fall through
1529             case Token::SHREQ:        // fall through
1530             case Token::BITWISEANDEQ: // fall through
1531             case Token::BITWISEXOREQ: // fall through
1532             case Token::BITWISEOREQ:  // fall through
1533             case Token::LOGICALANDEQ: // fall through
1534             case Token::LOGICALXOREQ: // fall through
1535             case Token::LOGICALOREQ: {
1536                 if (!depth.increase()) {
1537                     return ASTNode::ID::Invalid();
1538                 }
1539                 Token t = this->nextToken();
1540                 ASTNode::ID right = this->assignmentExpression();
1541                 if (!right) {
1542                     return ASTNode::ID::Invalid();
1543                 }
1544                 CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary,
1545                             std::move(t));
1546                 getNode(newResult).addChild(result);
1547                 getNode(newResult).addChild(right);
1548                 result = newResult;
1549                 break;
1550             }
1551             default:
1552                 return result;
1553         }
1554     }
1555 }
1556 
1557 /* logicalOrExpression ('?' expression ':' assignmentExpression)? */
ternaryExpression()1558 ASTNode::ID Parser::ternaryExpression() {
1559     AutoDepth depth(this);
1560     ASTNode::ID base = this->logicalOrExpression();
1561     if (!base) {
1562         return ASTNode::ID::Invalid();
1563     }
1564     if (this->checkNext(Token::QUESTION)) {
1565         if (!depth.increase()) {
1566             return ASTNode::ID::Invalid();
1567         }
1568         ASTNode::ID trueExpr = this->expression();
1569         if (!trueExpr) {
1570             return ASTNode::ID::Invalid();
1571         }
1572         if (this->expect(Token::COLON, "':'")) {
1573             ASTNode::ID falseExpr = this->assignmentExpression();
1574             if (!falseExpr) {
1575                 return ASTNode::ID::Invalid();
1576             }
1577             CREATE_NODE(ternary, getNode(base).fOffset, ASTNode::Kind::kTernary);
1578             getNode(ternary).addChild(base);
1579             getNode(ternary).addChild(trueExpr);
1580             getNode(ternary).addChild(falseExpr);
1581             return ternary;
1582         }
1583         return ASTNode::ID::Invalid();
1584     }
1585     return base;
1586 }
1587 
1588 /* logicalXorExpression (LOGICALOR logicalXorExpression)* */
logicalOrExpression()1589 ASTNode::ID Parser::logicalOrExpression() {
1590     AutoDepth depth(this);
1591     ASTNode::ID result = this->logicalXorExpression();
1592     if (!result) {
1593         return ASTNode::ID::Invalid();
1594     }
1595     Token t;
1596     while (this->checkNext(Token::LOGICALOR, &t)) {
1597         if (!depth.increase()) {
1598             return ASTNode::ID::Invalid();
1599         }
1600         ASTNode::ID right = this->logicalXorExpression();
1601         if (!right) {
1602             return ASTNode::ID::Invalid();
1603         }
1604         CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary, std::move(t));
1605         getNode(newResult).addChild(result);
1606         getNode(newResult).addChild(right);
1607         result = newResult;
1608     }
1609     return result;
1610 }
1611 
1612 /* logicalAndExpression (LOGICALXOR logicalAndExpression)* */
logicalXorExpression()1613 ASTNode::ID Parser::logicalXorExpression() {
1614     AutoDepth depth(this);
1615     ASTNode::ID result = this->logicalAndExpression();
1616     if (!result) {
1617         return ASTNode::ID::Invalid();
1618     }
1619     Token t;
1620     while (this->checkNext(Token::LOGICALXOR, &t)) {
1621         if (!depth.increase()) {
1622             return ASTNode::ID::Invalid();
1623         }
1624         ASTNode::ID right = this->logicalAndExpression();
1625         if (!right) {
1626             return ASTNode::ID::Invalid();
1627         }
1628         CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary, std::move(t));
1629         getNode(newResult).addChild(result);
1630         getNode(newResult).addChild(right);
1631         result = newResult;
1632     }
1633     return result;
1634 }
1635 
1636 /* bitwiseOrExpression (LOGICALAND bitwiseOrExpression)* */
logicalAndExpression()1637 ASTNode::ID Parser::logicalAndExpression() {
1638     AutoDepth depth(this);
1639     ASTNode::ID result = this->bitwiseOrExpression();
1640     if (!result) {
1641         return ASTNode::ID::Invalid();
1642     }
1643     Token t;
1644     while (this->checkNext(Token::LOGICALAND, &t)) {
1645         if (!depth.increase()) {
1646             return ASTNode::ID::Invalid();
1647         }
1648         ASTNode::ID right = this->bitwiseOrExpression();
1649         if (!right) {
1650             return ASTNode::ID::Invalid();
1651         }
1652         CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary, std::move(t));
1653         getNode(newResult).addChild(result);
1654         getNode(newResult).addChild(right);
1655         result = newResult;
1656     }
1657     return result;
1658 }
1659 
1660 /* bitwiseXorExpression (BITWISEOR bitwiseXorExpression)* */
bitwiseOrExpression()1661 ASTNode::ID Parser::bitwiseOrExpression() {
1662     AutoDepth depth(this);
1663     ASTNode::ID result = this->bitwiseXorExpression();
1664     if (!result) {
1665         return ASTNode::ID::Invalid();
1666     }
1667     Token t;
1668     while (this->checkNext(Token::BITWISEOR, &t)) {
1669         if (!depth.increase()) {
1670             return ASTNode::ID::Invalid();
1671         }
1672         ASTNode::ID right = this->bitwiseXorExpression();
1673         if (!right) {
1674             return ASTNode::ID::Invalid();
1675         }
1676         CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary, std::move(t));
1677         getNode(newResult).addChild(result);
1678         getNode(newResult).addChild(right);
1679         result = newResult;
1680     }
1681     return result;
1682 }
1683 
1684 /* bitwiseAndExpression (BITWISEXOR bitwiseAndExpression)* */
bitwiseXorExpression()1685 ASTNode::ID Parser::bitwiseXorExpression() {
1686     AutoDepth depth(this);
1687     ASTNode::ID result = this->bitwiseAndExpression();
1688     if (!result) {
1689         return ASTNode::ID::Invalid();
1690     }
1691     Token t;
1692     while (this->checkNext(Token::BITWISEXOR, &t)) {
1693         if (!depth.increase()) {
1694             return ASTNode::ID::Invalid();
1695         }
1696         ASTNode::ID right = this->bitwiseAndExpression();
1697         if (!right) {
1698             return ASTNode::ID::Invalid();
1699         }
1700         CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary, std::move(t));
1701         getNode(newResult).addChild(result);
1702         getNode(newResult).addChild(right);
1703         result = newResult;
1704     }
1705     return result;
1706 }
1707 
1708 /* equalityExpression (BITWISEAND equalityExpression)* */
bitwiseAndExpression()1709 ASTNode::ID Parser::bitwiseAndExpression() {
1710     AutoDepth depth(this);
1711     ASTNode::ID result = this->equalityExpression();
1712     if (!result) {
1713         return ASTNode::ID::Invalid();
1714     }
1715     Token t;
1716     while (this->checkNext(Token::BITWISEAND, &t)) {
1717         if (!depth.increase()) {
1718             return ASTNode::ID::Invalid();
1719         }
1720         ASTNode::ID right = this->equalityExpression();
1721         if (!right) {
1722             return ASTNode::ID::Invalid();
1723         }
1724         CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary, std::move(t));
1725         getNode(newResult).addChild(result);
1726         getNode(newResult).addChild(right);
1727         result = newResult;
1728     }
1729     return result;
1730 }
1731 
1732 /* relationalExpression ((EQEQ | NEQ) relationalExpression)* */
equalityExpression()1733 ASTNode::ID Parser::equalityExpression() {
1734     AutoDepth depth(this);
1735     ASTNode::ID result = this->relationalExpression();
1736     if (!result) {
1737         return ASTNode::ID::Invalid();
1738     }
1739     for (;;) {
1740         switch (this->peek().fKind) {
1741             case Token::EQEQ:   // fall through
1742             case Token::NEQ: {
1743                 if (!depth.increase()) {
1744                     return ASTNode::ID::Invalid();
1745                 }
1746                 Token t = this->nextToken();
1747                 ASTNode::ID right = this->relationalExpression();
1748                 if (!right) {
1749                     return ASTNode::ID::Invalid();
1750                 }
1751                 CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary,
1752                             std::move(t));
1753                 getNode(newResult).addChild(result);
1754                 getNode(newResult).addChild(right);
1755                 result = newResult;
1756                 break;
1757             }
1758             default:
1759                 return result;
1760         }
1761     }
1762 }
1763 
1764 /* shiftExpression ((LT | GT | LTEQ | GTEQ) shiftExpression)* */
relationalExpression()1765 ASTNode::ID Parser::relationalExpression() {
1766     AutoDepth depth(this);
1767     ASTNode::ID result = this->shiftExpression();
1768     if (!result) {
1769         return ASTNode::ID::Invalid();
1770     }
1771     for (;;) {
1772         switch (this->peek().fKind) {
1773             case Token::LT:   // fall through
1774             case Token::GT:   // fall through
1775             case Token::LTEQ: // fall through
1776             case Token::GTEQ: {
1777                 if (!depth.increase()) {
1778                     return ASTNode::ID::Invalid();
1779                 }
1780                 Token t = this->nextToken();
1781                 ASTNode::ID right = this->shiftExpression();
1782                 if (!right) {
1783                     return ASTNode::ID::Invalid();
1784                 }
1785                 CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary,
1786                             std::move(t));
1787                 getNode(newResult).addChild(result);
1788                 getNode(newResult).addChild(right);
1789                 result = newResult;
1790                 break;
1791             }
1792             default:
1793                 return result;
1794         }
1795     }
1796 }
1797 
1798 /* additiveExpression ((SHL | SHR) additiveExpression)* */
shiftExpression()1799 ASTNode::ID Parser::shiftExpression() {
1800     AutoDepth depth(this);
1801     ASTNode::ID result = this->additiveExpression();
1802     if (!result) {
1803         return ASTNode::ID::Invalid();
1804     }
1805     for (;;) {
1806         switch (this->peek().fKind) {
1807             case Token::SHL: // fall through
1808             case Token::SHR: {
1809                 if (!depth.increase()) {
1810                     return ASTNode::ID::Invalid();
1811                 }
1812                 Token t = this->nextToken();
1813                 ASTNode::ID right = this->additiveExpression();
1814                 if (!right) {
1815                     return ASTNode::ID::Invalid();
1816                 }
1817                 CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary,
1818                             std::move(t));
1819                 getNode(newResult).addChild(result);
1820                 getNode(newResult).addChild(right);
1821                 result = newResult;
1822                 break;
1823             }
1824             default:
1825                 return result;
1826         }
1827     }
1828 }
1829 
1830 /* multiplicativeExpression ((PLUS | MINUS) multiplicativeExpression)* */
additiveExpression()1831 ASTNode::ID Parser::additiveExpression() {
1832     AutoDepth depth(this);
1833     ASTNode::ID result = this->multiplicativeExpression();
1834     if (!result) {
1835         return ASTNode::ID::Invalid();
1836     }
1837     for (;;) {
1838         switch (this->peek().fKind) {
1839             case Token::PLUS: // fall through
1840             case Token::MINUS: {
1841                 if (!depth.increase()) {
1842                     return ASTNode::ID::Invalid();
1843                 }
1844                 Token t = this->nextToken();
1845                 ASTNode::ID right = this->multiplicativeExpression();
1846                 if (!right) {
1847                     return ASTNode::ID::Invalid();
1848                 }
1849                 CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary,
1850                             std::move(t));
1851                 getNode(newResult).addChild(result);
1852                 getNode(newResult).addChild(right);
1853                 result = newResult;
1854                 break;
1855             }
1856             default:
1857                 return result;
1858         }
1859     }
1860 }
1861 
1862 /* unaryExpression ((STAR | SLASH | PERCENT) unaryExpression)* */
multiplicativeExpression()1863 ASTNode::ID Parser::multiplicativeExpression() {
1864     AutoDepth depth(this);
1865     ASTNode::ID result = this->unaryExpression();
1866     if (!result) {
1867         return ASTNode::ID::Invalid();
1868     }
1869     for (;;) {
1870         switch (this->peek().fKind) {
1871             case Token::STAR: // fall through
1872             case Token::SLASH: // fall through
1873             case Token::PERCENT: {
1874                 if (!depth.increase()) {
1875                     return ASTNode::ID::Invalid();
1876                 }
1877                 Token t = this->nextToken();
1878                 ASTNode::ID right = this->unaryExpression();
1879                 if (!right) {
1880                     return ASTNode::ID::Invalid();
1881                 }
1882                 CREATE_NODE(newResult, getNode(result).fOffset, ASTNode::Kind::kBinary,
1883                             std::move(t));
1884                 getNode(newResult).addChild(result);
1885                 getNode(newResult).addChild(right);
1886                 result = newResult;
1887                 break;
1888             }
1889             default:
1890                 return result;
1891         }
1892     }
1893 }
1894 
1895 /* postfixExpression | (PLUS | MINUS | NOT | PLUSPLUS | MINUSMINUS) unaryExpression */
unaryExpression()1896 ASTNode::ID Parser::unaryExpression() {
1897     AutoDepth depth(this);
1898     switch (this->peek().fKind) {
1899         case Token::PLUS:       // fall through
1900         case Token::MINUS:      // fall through
1901         case Token::LOGICALNOT: // fall through
1902         case Token::BITWISENOT: // fall through
1903         case Token::PLUSPLUS:   // fall through
1904         case Token::MINUSMINUS: {
1905             if (!depth.increase()) {
1906                 return ASTNode::ID::Invalid();
1907             }
1908             Token t = this->nextToken();
1909             ASTNode::ID expr = this->unaryExpression();
1910             if (!expr) {
1911                 return ASTNode::ID::Invalid();
1912             }
1913             CREATE_NODE(result, t.fOffset, ASTNode::Kind::kPrefix, std::move(t));
1914             getNode(result).addChild(expr);
1915             return result;
1916         }
1917         default:
1918             return this->postfixExpression();
1919     }
1920 }
1921 
1922 /* term suffix* */
postfixExpression()1923 ASTNode::ID Parser::postfixExpression() {
1924     AutoDepth depth(this);
1925     ASTNode::ID result = this->term();
1926     if (!result) {
1927         return ASTNode::ID::Invalid();
1928     }
1929     for (;;) {
1930         Token t = this->peek();
1931         switch (t.fKind) {
1932             case Token::FLOAT_LITERAL:
1933                 if (this->text(t)[0] != '.') {
1934                     return result;
1935                 }
1936                 // fall through
1937             case Token::LBRACKET:
1938             case Token::DOT:
1939             case Token::LPAREN:
1940             case Token::PLUSPLUS:
1941             case Token::MINUSMINUS:
1942             case Token::COLONCOLON:
1943                 if (!depth.increase()) {
1944                     return ASTNode::ID::Invalid();
1945                 }
1946                 result = this->suffix(result);
1947                 if (!result) {
1948                     return ASTNode::ID::Invalid();
1949                 }
1950                 break;
1951             default:
1952                 return result;
1953         }
1954     }
1955 }
1956 
1957 /* LBRACKET expression? RBRACKET | DOT IDENTIFIER | LPAREN parameters RPAREN |
1958    PLUSPLUS | MINUSMINUS | COLONCOLON IDENTIFIER | FLOAT_LITERAL [IDENTIFIER] */
suffix(ASTNode::ID base)1959 ASTNode::ID Parser::suffix(ASTNode::ID base) {
1960     SkASSERT(base);
1961     Token next = this->nextToken();
1962     AutoDepth depth(this);
1963     if (!depth.increase()) {
1964         return ASTNode::ID::Invalid();
1965     }
1966     switch (next.fKind) {
1967         case Token::LBRACKET: {
1968             if (this->checkNext(Token::RBRACKET)) {
1969                 CREATE_NODE(result, next.fOffset, ASTNode::Kind::kIndex);
1970                 getNode(result).addChild(base);
1971                 return result;
1972             }
1973             ASTNode::ID e = this->expression();
1974             if (!e) {
1975                 return ASTNode::ID::Invalid();
1976             }
1977             this->expect(Token::RBRACKET, "']' to complete array access expression");
1978             CREATE_NODE(result, next.fOffset, ASTNode::Kind::kIndex);
1979             getNode(result).addChild(base);
1980             getNode(result).addChild(e);
1981             return result;
1982         }
1983         case Token::DOT: // fall through
1984         case Token::COLONCOLON: {
1985             int offset = this->peek().fOffset;
1986             StringFragment text;
1987             if (this->identifier(&text)) {
1988                 CREATE_NODE(result, offset, ASTNode::Kind::kField, std::move(text));
1989                 getNode(result).addChild(base);
1990                 return result;
1991             }
1992         }
1993         case Token::FLOAT_LITERAL: {
1994             // Swizzles that start with a constant number, e.g. '.000r', will be tokenized as
1995             // floating point literals, possibly followed by an identifier. Handle that here.
1996             StringFragment field = this->text(next);
1997             SkASSERT(field.fChars[0] == '.');
1998             ++field.fChars;
1999             --field.fLength;
2000             for (size_t i = 0; i < field.fLength; ++i) {
2001                 if (field.fChars[i] != '0' && field.fChars[i] != '1') {
2002                     this->error(next, "invalid swizzle");
2003                     return ASTNode::ID::Invalid();
2004                 }
2005             }
2006             // use the next *raw* token so we don't ignore whitespace - we only care about
2007             // identifiers that directly follow the float
2008             Token id = this->nextRawToken();
2009             if (id.fKind == Token::IDENTIFIER) {
2010                 field.fLength += id.fLength;
2011             } else {
2012                 this->pushback(id);
2013             }
2014             CREATE_NODE(result, next.fOffset, ASTNode::Kind::kField, field);
2015             getNode(result).addChild(base);
2016             return result;
2017         }
2018         case Token::LPAREN: {
2019             CREATE_NODE(result, next.fOffset, ASTNode::Kind::kCall);
2020             getNode(result).addChild(base);
2021             if (this->peek().fKind != Token::RPAREN) {
2022                 for (;;) {
2023                     ASTNode::ID expr = this->assignmentExpression();
2024                     if (!expr) {
2025                         return ASTNode::ID::Invalid();
2026                     }
2027                     getNode(result).addChild(expr);
2028                     if (!this->checkNext(Token::COMMA)) {
2029                         break;
2030                     }
2031                 }
2032             }
2033             this->expect(Token::RPAREN, "')' to complete function parameters");
2034             return result;
2035         }
2036         case Token::PLUSPLUS: // fall through
2037         case Token::MINUSMINUS: {
2038             CREATE_NODE(result, next.fOffset, ASTNode::Kind::kPostfix, next);
2039             getNode(result).addChild(base);
2040             return result;
2041         }
2042         default: {
2043             this->error(next,  "expected expression suffix, but found '" + this->text(next) + "'");
2044             return ASTNode::ID::Invalid();
2045         }
2046     }
2047 }
2048 
2049 /* IDENTIFIER | intLiteral | floatLiteral | boolLiteral | NULL_LITERAL | '(' expression ')' */
term()2050 ASTNode::ID Parser::term() {
2051     Token t = this->peek();
2052     switch (t.fKind) {
2053         case Token::IDENTIFIER: {
2054             StringFragment text;
2055             if (this->identifier(&text)) {
2056                 RETURN_NODE(t.fOffset, ASTNode::Kind::kIdentifier, std::move(text));
2057             }
2058         }
2059         case Token::INT_LITERAL: {
2060             SKSL_INT i;
2061             if (this->intLiteral(&i)) {
2062                 RETURN_NODE(t.fOffset, ASTNode::Kind::kInt, i);
2063             }
2064             break;
2065         }
2066         case Token::FLOAT_LITERAL: {
2067             SKSL_FLOAT f;
2068             if (this->floatLiteral(&f)) {
2069                 RETURN_NODE(t.fOffset, ASTNode::Kind::kFloat, f);
2070             }
2071             break;
2072         }
2073         case Token::TRUE_LITERAL: // fall through
2074         case Token::FALSE_LITERAL: {
2075             bool b;
2076             if (this->boolLiteral(&b)) {
2077                 RETURN_NODE(t.fOffset, ASTNode::Kind::kBool, b);
2078             }
2079             break;
2080         }
2081         case Token::NULL_LITERAL:
2082             this->nextToken();
2083             RETURN_NODE(t.fOffset, ASTNode::Kind::kNull);
2084         case Token::LPAREN: {
2085             this->nextToken();
2086             AutoDepth depth(this);
2087             if (!depth.increase()) {
2088                 return ASTNode::ID::Invalid();
2089             }
2090             ASTNode::ID result = this->expression();
2091             if (result) {
2092                 this->expect(Token::RPAREN, "')' to complete expression");
2093                 return result;
2094             }
2095             break;
2096         }
2097         default:
2098             this->nextToken();
2099             this->error(t.fOffset,  "expected expression, but found '" + this->text(t) + "'");
2100     }
2101     return ASTNode::ID::Invalid();
2102 }
2103 
2104 /* INT_LITERAL */
intLiteral(SKSL_INT * dest)2105 bool Parser::intLiteral(SKSL_INT* dest) {
2106     Token t;
2107     if (this->expect(Token::INT_LITERAL, "integer literal", &t)) {
2108         *dest = SkSL::stol(this->text(t));
2109         return true;
2110     }
2111     return false;
2112 }
2113 
2114 /* FLOAT_LITERAL */
floatLiteral(SKSL_FLOAT * dest)2115 bool Parser::floatLiteral(SKSL_FLOAT* dest) {
2116     Token t;
2117     if (this->expect(Token::FLOAT_LITERAL, "float literal", &t)) {
2118         *dest = SkSL::stod(this->text(t));
2119         return true;
2120     }
2121     return false;
2122 }
2123 
2124 /* TRUE_LITERAL | FALSE_LITERAL */
boolLiteral(bool * dest)2125 bool Parser::boolLiteral(bool* dest) {
2126     Token t = this->nextToken();
2127     switch (t.fKind) {
2128         case Token::TRUE_LITERAL:
2129             *dest = true;
2130             return true;
2131         case Token::FALSE_LITERAL:
2132             *dest = false;
2133             return true;
2134         default:
2135             this->error(t, "expected 'true' or 'false', but found '" + this->text(t) + "'");
2136             return false;
2137     }
2138 }
2139 
2140 /* IDENTIFIER */
identifier(StringFragment * dest)2141 bool Parser::identifier(StringFragment* dest) {
2142     Token t;
2143     if (this->expect(Token::IDENTIFIER, "identifier", &t)) {
2144         *dest = this->text(t);
2145         return true;
2146     }
2147     return false;
2148 }
2149 
2150 } // namespace
2151