Debian Codegraph @

core/parser.cpp

raw
1 /*
2 Copyright 2015 Google Inc. All rights reserved.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 #include <cassert>
18 #include <cmath>
19 #include <cstdlib>
20
21 #include <iomanip>
22 #include <list>
23 #include <memory>
24 #include <set>
25 #include <sstream>
26 #include <locale>
27 #include <string>
28
29 #include "ast.h"
30 #include "desugarer.h"
31 #include "lexer.h"
32 #include "parser.h"
33 #include "static_error.h"
34
35 namespace jsonnet::internal {
36
37 std::string jsonnet_unparse_number(double v)
38 {
39 std::stringstream ss;
40 // Make sure we output the same thing, even if the user
41 // of the library changed the global locale
42 ss.imbue(std::locale::classic());
43 if (v == floor(v)) {
44 ss << std::fixed << std::setprecision(0) << v;
45 } else {
46 // See "What Every Computer Scientist Should Know About Floating-Point Arithmetic"
47 // Theorem 15
48 // https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
49 ss << std::setprecision(17);
50 ss << v;
51 }
52 return ss.str();
53 }
54
55 namespace {
56
57 static const Fodder EMPTY_FODDER;
58
59 /** Maximum parsing depth to avoid stack overflow due to pathological or malicious code.
60 * This is especially important when parsing deeply nested structures that could lead to
61 * excessive recursion in the parser functions.
62 */
63 static const unsigned MAX_PARSER_DEPTH = 1000;
64
65 static bool op_is_unary(const std::string &op, UnaryOp &uop)
66 {
67 auto it = unary_map.find(op);
68 if (it == unary_map.end())
69 return false;
70 uop = it->second;
71 return true;
72 }
73
74 static bool op_is_binary(const std::string &op, BinaryOp &bop)
75 {
76 auto it = binary_map.find(op);
77 if (it == binary_map.end())
78 return false;
79 bop = it->second;
80 return true;
81 }
82
83 LocationRange span(const Token &begin)
84 {
85 return LocationRange(begin.location.file, begin.location.begin, begin.location.end);
86 }
87
88 LocationRange span(const Token &begin, const Token &end)
89 {
90 return LocationRange(begin.location.file, begin.location.begin, end.location.end);
91 }
92
93 LocationRange span(const Token &begin, AST *end)
94 {
95 return LocationRange(begin.location.file, begin.location.begin, end->location.end);
96 }
97
98 /** Holds state while parsing a given token list.
99 */
100 class Parser {
101 // The private member functions are utilities for dealing with the token stream.
102
103 StaticError unexpected(const Token &tok, const std::string &while_)
104 {
105 std::stringstream ss;
106 ss << "unexpected: " << tok.kind << " while " << while_;
107 return StaticError(tok.location, ss.str());
108 }
109
110 Token pop(void)
111 {
112 Token tok = peek();
113 tokens.pop_front();
114 return tok;
115 }
116
117 void push(Token tok)
118 {
119 tokens.push_front(tok);
120 }
121
122 const Token &peek(void)
123 {
124 return tokens.front();
125 }
126
127 /** Only call this is peek() is not an EOF token. */
128 Token doublePeek(void)
129 {
130 Tokens::iterator it = tokens.begin(); // First one.
131 it++; // Now pointing at the second one.
132 return *(it);
133 }
134
135 Token popExpect(Token::Kind k, const char *data = nullptr)
136 {
137 Token tok = pop();
138 if (tok.kind != k) {
139 std::stringstream ss;
140 ss << "expected token " << k << " but got " << tok;
141 throw StaticError(tok.location, ss.str());
142 }
143 if (data != nullptr && tok.data != data) {
144 std::stringstream ss;
145 ss << "expected operator " << data << " but got " << tok.data;
146 throw StaticError(tok.location, ss.str());
147 }
148 return tok;
149 }
150
151 std::list<Token> &tokens;
152 Allocator *alloc;
153
154 public:
155 Parser(Tokens &tokens, Allocator *alloc) : tokens(tokens), alloc(alloc) {}
156
157 /** Parse a comma-separated list of expressions.
158 *
159 * Allows an optional ending comma.
160 * \param args Expressions added here.
161 * \param element_kind Used in error messages when a comma was not found.
162 * \param got_comma Whether a trailing comma was found.
163 * \param current_depth Current recursion depth to prevent stack overflow.
164 * \returns The last token (the one that matched parameter end).
165 */
166 Token parseArgs(ArgParams &args, const std::string &element_kind, bool &got_comma, unsigned current_depth)
167 {
168 got_comma = false;
169 bool first = true;
170 do {
171 Token next = peek();
172 if (next.kind == Token::PAREN_R) {
173 // got_comma can be true or false here.
174 return pop();
175 }
176 if (!first && !got_comma) {
177 std::stringstream ss;
178 ss << "expected a comma before next " << element_kind << ".";
179 throw StaticError(next.location, ss.str());
180 }
181 // Either id=expr or id or expr, but note that expr could be id==1 so this needs
182 // look-ahead.
183 Fodder id_fodder;
184 const Identifier *id = nullptr;
185 Fodder eq_fodder;
186 if (peek().kind == Token::IDENTIFIER) {
187 Token maybe_eq = doublePeek();
188 if (maybe_eq.kind == Token::OPERATOR && maybe_eq.data == "=") {
189 id_fodder = peek().fodder;
190 id = alloc->makeIdentifier(peek().data32());
191 eq_fodder = maybe_eq.fodder;
192 pop(); // id
193 pop(); // eq
194 }
195 }
196 AST *expr = parse(MAX_PRECEDENCE, current_depth + 1);
197 got_comma = false;
198 first = false;
199 Fodder comma_fodder;
200 if (peek().kind == Token::COMMA) {
201 Token comma = pop();
202 comma_fodder = comma.fodder;
203 got_comma = true;
204 }
205 args.emplace_back(id_fodder, id, eq_fodder, expr, comma_fodder);
206 } while (true);
207 }
208
209 /** Parse function parameters.
210 *
211 * \param element_kind Used in error messages.
212 * \param got_comma Whether a trailing comma was found.
213 * \param close_fodder Fodder after the closing parenthesis.
214 * \param current_depth Current recursion depth to prevent stack overflow.
215 * \returns The parameters as ArgParams.
216 */
217 ArgParams parseParams(const std::string &element_kind, bool &got_comma, Fodder &close_fodder, unsigned current_depth)
218 {
219 ArgParams params;
220 Token paren_r = parseArgs(params, element_kind, got_comma, current_depth);
221
222 // Check they're all identifiers
223 // parseArgs returns f(x) with x as an expression. Convert it here.
224 for (auto &p : params) {
225 if (p.id == nullptr) {
226 if (p.expr->type != AST_VAR) {
227 throw StaticError(p.expr->location, "could not parse parameter here.");
228 }
229 auto *pv = static_cast<Var *>(p.expr);
230 p.id = pv->id;
231 p.idFodder = pv->openFodder;
232 p.expr = nullptr;
233 }
234 }
235
236 close_fodder = paren_r.fodder;
237
238 return params;
239 }
240
241 /** Parse a local bind statement.
242 *
243 * \param binds The bindings to be populated.
244 * \param current_depth Current recursion depth to prevent stack overflow.
245 * \returns The token after the binding (comma or semicolon).
246 */
247 Token parseBind(Local::Binds &binds, unsigned current_depth)
248 {
249 Token var_id = popExpect(Token::IDENTIFIER);
250 auto *id = alloc->makeIdentifier(var_id.data32());
251 for (const auto &bind : binds) {
252 if (bind.var == id)
253 throw StaticError(var_id.location, "duplicate local var: " + var_id.data);
254 }
255 bool is_function = false;
256 ArgParams params;
257 bool trailing_comma = false;
258 Fodder fodder_l, fodder_r;
259 if (peek().kind == Token::PAREN_L) {
260 Token paren_l = pop();
261 fodder_l = paren_l.fodder;
262 params = parseParams("function parameter", trailing_comma, fodder_r, current_depth);
263 is_function = true;
264 }
265 Token eq = popExpect(Token::OPERATOR, "=");
266 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
267 Token delim = pop();
268 binds.emplace_back(var_id.fodder,
269 id,
270 eq.fodder,
271 body,
272 is_function,
273 fodder_l,
274 params,
275 trailing_comma,
276 fodder_r,
277 delim.fodder);
278 return delim;
279 }
280
281 /** Parse the remainder of an object after the opening brace.
282 *
283 * \param obj The object AST to be populated.
284 * \param tok The opening brace token.
285 * \param current_depth Current recursion depth to prevent stack overflow.
286 * \returns The closing brace token.
287 */
288 Token parseObjectRemainder(AST *&obj, const Token &tok, unsigned current_depth)
289 {
290 if (current_depth >= MAX_PARSER_DEPTH) {
291 throw StaticError(peek().location, "Exceeded maximum parse depth limit.");
292 }
293
294 ObjectFields fields;
295 std::set<std::string> literal_fields; // For duplicate fields detection.
296 std::set<const Identifier *> binds; // For duplicate locals detection.
297
298 bool got_comma = false;
299 bool first = true;
300 Token next = pop();
301
302 do {
303 if (next.kind == Token::BRACE_R) {
304 obj = alloc->make<Object>(
305 span(tok, next), tok.fodder, fields, got_comma, next.fodder);
306 return next;
307
308 } else if (next.kind == Token::FOR) {
309 // It's a comprehension
310 unsigned num_fields = 0;
311 unsigned num_asserts = 0;
312 const ObjectField *field_ptr = nullptr;
313 for (const auto &field : fields) {
314 if (field.kind == ObjectField::LOCAL)
315 continue;
316 if (field.kind == ObjectField::ASSERT) {
317 num_asserts++;
318 continue;
319 }
320 field_ptr = &field;
321 num_fields++;
322 }
323 if (num_asserts > 0) {
324 auto msg = "object comprehension cannot have asserts.";
325 throw StaticError(next.location, msg);
326 }
327 if (num_fields != 1) {
328 auto msg = "object comprehension can only have one field.";
329 throw StaticError(next.location, msg);
330 }
331 const ObjectField &field = *field_ptr;
332
333 if (field.hide != ObjectField::INHERIT) {
334 auto msg = "object comprehensions cannot have hidden fields.";
335 throw StaticError(next.location, msg);
336 }
337
338 if (field.kind != ObjectField::FIELD_EXPR) {
339 auto msg = "object comprehensions can only have [e] fields.";
340 throw StaticError(next.location, msg);
341 }
342
343 std::vector<ComprehensionSpec> specs;
344 Token last = parseComprehensionSpecs(Token::BRACE_R, next.fodder, specs, current_depth + 1);
345 obj = alloc->make<ObjectComprehension>(
346 span(tok, last), tok.fodder, fields, got_comma, specs, last.fodder);
347
348 return last;
349 }
350
351 if (!got_comma && !first)
352 throw StaticError(next.location, "expected a comma before next field.");
353
354 first = false;
355 got_comma = false;
356
357 switch (next.kind) {
358 case Token::BRACKET_L:
359 case Token::IDENTIFIER:
360 case Token::STRING_DOUBLE:
361 case Token::STRING_SINGLE:
362 case Token::STRING_BLOCK:
363 case Token::VERBATIM_STRING_DOUBLE:
364 case Token::VERBATIM_STRING_SINGLE: {
365 ObjectField::Kind kind;
366 AST *expr1 = nullptr;
367 const Identifier *id = nullptr;
368 Fodder fodder1, fodder2;
369 LocationRange idLocation;
370 if (next.kind == Token::IDENTIFIER) {
371 fodder1 = next.fodder;
372 kind = ObjectField::FIELD_ID;
373 id = alloc->makeIdentifier(next.data32());
374 idLocation = next.location;
375 } else if (next.kind == Token::STRING_DOUBLE) {
376 kind = ObjectField::FIELD_STR;
377 expr1 = alloc->make<LiteralString>(next.location,
378 next.fodder,
379 next.data32(),
380 LiteralString::DOUBLE,
381 "",
382 "");
383 } else if (next.kind == Token::STRING_SINGLE) {
384 kind = ObjectField::FIELD_STR;
385 expr1 = alloc->make<LiteralString>(next.location,
386 next.fodder,
387 next.data32(),
388 LiteralString::SINGLE,
389 "",
390 "");
391 } else if (next.kind == Token::STRING_BLOCK) {
392 kind = ObjectField::FIELD_STR;
393 expr1 = alloc->make<LiteralString>(next.location,
394 next.fodder,
395 next.data32(),
396 LiteralString::BLOCK,
397 next.stringBlockIndent,
398 next.stringBlockTermIndent);
399 } else if (next.kind == Token::VERBATIM_STRING_SINGLE) {
400 kind = ObjectField::FIELD_STR;
401 expr1 = alloc->make<LiteralString>(next.location,
402 next.fodder,
403 next.data32(),
404 LiteralString::VERBATIM_SINGLE,
405 "",
406 "");
407 } else if (next.kind == Token::VERBATIM_STRING_DOUBLE) {
408 kind = ObjectField::FIELD_STR;
409 expr1 = alloc->make<LiteralString>(next.location,
410 next.fodder,
411 next.data32(),
412 LiteralString::VERBATIM_DOUBLE,
413 "",
414 "");
415 } else {
416 kind = ObjectField::FIELD_EXPR;
417 fodder1 = next.fodder;
418 expr1 = parse(MAX_PRECEDENCE, current_depth + 1);
419 Token bracket_r = popExpect(Token::BRACKET_R);
420 fodder2 = bracket_r.fodder;
421 }
422
423 bool is_method = false;
424 bool meth_comma = false;
425 ArgParams params;
426 Fodder fodder_l;
427 Fodder fodder_r;
428 if (peek().kind == Token::PAREN_L) {
429 Token paren_l = pop();
430 fodder_l = paren_l.fodder;
431 params = parseParams("method parameter", meth_comma, fodder_r, current_depth);
432 is_method = true;
433 }
434
435 bool plus_sugar = false;
436
437 Token op = popExpect(Token::OPERATOR);
438 const char *od = op.data.c_str();
439 if (*od == '+') {
440 plus_sugar = true;
441 od++;
442 }
443 unsigned colons = 0;
444 for (; *od != '\0'; ++od) {
445 if (*od != ':') {
446 throw StaticError(
447 next.location,
448 "expected one of :, ::, :::, +:, +::, +:::, got: " + op.data);
449 }
450 ++colons;
451 }
452 ObjectField::Hide field_hide;
453 switch (colons) {
454 case 1: field_hide = ObjectField::INHERIT; break;
455
456 case 2: field_hide = ObjectField::HIDDEN; break;
457
458 case 3: field_hide = ObjectField::VISIBLE; break;
459
460 default:
461 throw StaticError(
462 next.location,
463 "expected one of :, ::, :::, +:, +::, +:::, got: " + op.data);
464 }
465
466 // Basic checks for invalid Jsonnet code.
467 if (is_method && plus_sugar) {
468 throw StaticError(next.location,
469 "cannot use +: syntax sugar in a method: " + next.data);
470 }
471 if (kind != ObjectField::FIELD_EXPR) {
472 if (!literal_fields.insert(next.data).second) {
473 throw StaticError(next.location, "duplicate field: " + next.data);
474 }
475 }
476
477 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
478
479 Fodder comma_fodder;
480 next = pop();
481 if (next.kind == Token::COMMA) {
482 comma_fodder = next.fodder;
483 next = pop();
484 got_comma = true;
485 }
486 fields.emplace_back(kind,
487 fodder1,
488 fodder2,
489 fodder_l,
490 fodder_r,
491 field_hide,
492 plus_sugar,
493 is_method,
494 expr1,
495 id,
496 idLocation,
497 params,
498 meth_comma,
499 op.fodder,
500 body,
501 nullptr,
502 comma_fodder);
503 } break;
504
505 case Token::LOCAL: {
506 Fodder local_fodder = next.fodder;
507 Token var_id = popExpect(Token::IDENTIFIER);
508 auto *id = alloc->makeIdentifier(var_id.data32());
509
510 if (binds.find(id) != binds.end()) {
511 throw StaticError(var_id.location, "duplicate local var: " + var_id.data);
512 }
513 bool is_method = false;
514 bool func_comma = false;
515 ArgParams params;
516 Fodder paren_l_fodder;
517 Fodder paren_r_fodder;
518 if (peek().kind == Token::PAREN_L) {
519 Token paren_l = pop();
520 paren_l_fodder = paren_l.fodder;
521 is_method = true;
522 params = parseParams("function parameter", func_comma, paren_r_fodder, current_depth);
523 }
524 Token eq = popExpect(Token::OPERATOR, "=");
525 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
526 binds.insert(id);
527
528 Fodder comma_fodder;
529 next = pop();
530 if (next.kind == Token::COMMA) {
531 comma_fodder = next.fodder;
532 next = pop();
533 got_comma = true;
534 }
535 fields.push_back(ObjectField::Local(local_fodder,
536 var_id.fodder,
537 paren_l_fodder,
538 paren_r_fodder,
539 is_method,
540 id,
541 params,
542 func_comma,
543 eq.fodder,
544 body,
545 comma_fodder));
546
547 } break;
548
549 case Token::ASSERT: {
550 Fodder assert_fodder = next.fodder;
551 AST *cond = parse(MAX_PRECEDENCE, current_depth + 1);
552 AST *msg = nullptr;
553 Fodder colon_fodder;
554 if (peek().kind == Token::OPERATOR && peek().data == ":") {
555 Token colon = pop();
556 colon_fodder = colon.fodder;
557 msg = parse(MAX_PRECEDENCE, current_depth + 1);
558 }
559
560 Fodder comma_fodder;
561 next = pop();
562 if (next.kind == Token::COMMA) {
563 comma_fodder = next.fodder;
564 next = pop();
565 got_comma = true;
566 }
567 fields.push_back(
568 ObjectField::Assert(assert_fodder, cond, colon_fodder, msg, comma_fodder));
569 } break;
570
571 default: throw unexpected(next, "parsing field definition");
572 }
573
574 } while (true);
575 }
576
577 /** Parses for x in expr for y in expr if expr for z in expr ...
578 *
579 * \param end The token that ends the comprehension (e.g. ] or }).
580 * \param for_fodder Fodder before the first 'for'.
581 * \param specs The comprehension specs to be populated.
582 * \param current_depth Current recursion depth to prevent stack overflow.
583 * \returns The closing token.
584 */
585 Token parseComprehensionSpecs(Token::Kind end, Fodder for_fodder,
586 std::vector<ComprehensionSpec> &specs,
587 unsigned current_depth)
588 {
589 if (current_depth >= MAX_PARSER_DEPTH) {
590 throw StaticError(peek().location, "Exceeded maximum parse depth limit.");
591 }
592
593 while (true) {
594 LocationRange l;
595 Token id_token = popExpect(Token::IDENTIFIER);
596 const Identifier *id = alloc->makeIdentifier(id_token.data32());
597 Token in_token = popExpect(Token::IN);
598 AST *arr = parse(MAX_PRECEDENCE, current_depth + 1);
599 specs.emplace_back(
600 ComprehensionSpec::FOR, for_fodder, id_token.fodder, id, in_token.fodder, arr);
601
602 Token maybe_if = pop();
603 for (; maybe_if.kind == Token::IF; maybe_if = pop()) {
604 AST *cond = parse(MAX_PRECEDENCE, current_depth + 1);
605 specs.emplace_back(
606 ComprehensionSpec::IF, maybe_if.fodder, Fodder{}, nullptr, Fodder{}, cond);
607 }
608 if (maybe_if.kind == end) {
609 return maybe_if;
610 }
611 if (maybe_if.kind != Token::FOR) {
612 std::stringstream ss;
613 ss << "expected for, if or " << end << " after for clause, got: " << maybe_if;
614 throw StaticError(maybe_if.location, ss.str());
615 }
616 for_fodder = maybe_if.fodder;
617 }
618 }
619
620 /** Parse a terminal (literal, var, import, etc.), an object declaration, unary operator,
621 * or a parenthesized expression.
622 *
623 * \param current_depth Current recursion depth to prevent stack overflow.
624 * \returns The parsed AST.
625 */
626 AST *parseTerminalBracketsOrUnary(unsigned current_depth)
627 {
628 if (current_depth >= MAX_PARSER_DEPTH) {
629 throw StaticError(peek().location, "Exceeded maximum parse depth limit.");
630 }
631
632 Token tok = pop();
633 switch (tok.kind) {
634 case Token::ASSERT:
635 case Token::BRACE_R:
636 case Token::BRACKET_R:
637 case Token::COMMA:
638 case Token::DOT:
639 case Token::ELSE:
640 case Token::ERROR:
641 case Token::FOR:
642 case Token::FUNCTION:
643 case Token::IF:
644 case Token::IN:
645 case Token::IMPORT:
646 case Token::IMPORTSTR:
647 case Token::IMPORTBIN:
648 case Token::LOCAL:
649 case Token::PAREN_R:
650 case Token::SEMICOLON:
651 case Token::TAILSTRICT:
652 case Token::THEN: throw unexpected(tok, "parsing terminal");
653
654 case Token::END_OF_FILE: throw StaticError(tok.location, "unexpected end of file.");
655
656 case Token::OPERATOR: {
657 UnaryOp uop;
658 if (!op_is_unary(tok.data, uop)) {
659 std::stringstream ss;
660 ss << "not a unary operator: " << tok.data;
661 throw StaticError(tok.location, ss.str());
662 }
663 AST *expr = parse(UNARY_PRECEDENCE, current_depth + 1);
664 return alloc->make<Unary>(span(tok, expr), tok.fodder, uop, expr);
665 }
666 case Token::BRACE_L: {
667 AST *obj;
668 parseObjectRemainder(obj, tok, current_depth + 1);
669 return obj;
670 }
671
672 case Token::BRACKET_L: {
673 Token next = peek();
674 if (next.kind == Token::BRACKET_R) {
675 Token bracket_r = pop();
676 return alloc->make<Array>(
677 span(tok, next), tok.fodder, Array::Elements{}, false, bracket_r.fodder);
678 }
679 AST *first = parse(MAX_PRECEDENCE, current_depth + 1);
680 bool got_comma = false;
681 Fodder comma_fodder;
682 next = peek();
683 if (!got_comma && next.kind == Token::COMMA) {
684 Token comma = pop();
685 comma_fodder = comma.fodder;
686 next = peek();
687 got_comma = true;
688 }
689
690 if (next.kind == Token::FOR) {
691 // It's a comprehension
692 Token for_token = pop();
693 std::vector<ComprehensionSpec> specs;
694 Token last = parseComprehensionSpecs(Token::BRACKET_R, for_token.fodder, specs, current_depth + 1);
695 return alloc->make<ArrayComprehension>(span(tok, last),
696 tok.fodder,
697 first,
698 comma_fodder,
699 got_comma,
700 specs,
701 last.fodder);
702 }
703
704 // Not a comprehension: It can have more elements.
705 Array::Elements elements;
706 elements.emplace_back(first, comma_fodder);
707 do {
708 if (next.kind == Token::BRACKET_R) {
709 Token bracket_r = pop();
710 return alloc->make<Array>(
711 span(tok, next), tok.fodder, elements, got_comma, bracket_r.fodder);
712 }
713 if (!got_comma) {
714 std::stringstream ss;
715 ss << "expected a comma before next array element.";
716 throw StaticError(next.location, ss.str());
717 }
718 AST *expr = parse(MAX_PRECEDENCE, current_depth + 1);
719 comma_fodder.clear();
720 got_comma = false;
721 next = peek();
722 if (next.kind == Token::COMMA) {
723 Token comma = pop();
724 comma_fodder = comma.fodder;
725 next = peek();
726 got_comma = true;
727 }
728 elements.emplace_back(expr, comma_fodder);
729 } while (true);
730 }
731
732 case Token::PAREN_L: {
733 auto *inner = parse(MAX_PRECEDENCE, current_depth + 1);
734 Token close = popExpect(Token::PAREN_R);
735 return alloc->make<Parens>(span(tok, close), tok.fodder, inner, close.fodder);
736 }
737
738 // Literals
739 case Token::NUMBER: return alloc->make<LiteralNumber>(span(tok), tok.fodder, tok.data);
740
741 case Token::STRING_SINGLE:
742 return alloc->make<LiteralString>(
743 span(tok), tok.fodder, tok.data32(), LiteralString::SINGLE, "", "");
744 case Token::STRING_DOUBLE:
745 return alloc->make<LiteralString>(
746 span(tok), tok.fodder, tok.data32(), LiteralString::DOUBLE, "", "");
747 case Token::STRING_BLOCK:
748 return alloc->make<LiteralString>(span(tok),
749 tok.fodder,
750 tok.data32(),
751 LiteralString::BLOCK,
752 tok.stringBlockIndent,
753 tok.stringBlockTermIndent);
754 case Token::VERBATIM_STRING_SINGLE:
755 return alloc->make<LiteralString>(
756 span(tok), tok.fodder, tok.data32(), LiteralString::VERBATIM_SINGLE, "", "");
757 case Token::VERBATIM_STRING_DOUBLE:
758 return alloc->make<LiteralString>(
759 span(tok), tok.fodder, tok.data32(), LiteralString::VERBATIM_DOUBLE, "", "");
760
761 case Token::FALSE: return alloc->make<LiteralBoolean>(span(tok), tok.fodder, false);
762
763 case Token::TRUE: return alloc->make<LiteralBoolean>(span(tok), tok.fodder, true);
764
765 case Token::NULL_LIT: return alloc->make<LiteralNull>(span(tok), tok.fodder);
766
767 // Variables
768 case Token::DOLLAR: return alloc->make<Dollar>(span(tok), tok.fodder);
769
770 case Token::IDENTIFIER:
771 return alloc->make<Var>(span(tok), tok.fodder, alloc->makeIdentifier(tok.data32()));
772
773 case Token::SELF: return alloc->make<Self>(span(tok), tok.fodder);
774
775 case Token::SUPER: {
776 Token next = pop();
777 AST *index = nullptr;
778 const Identifier *id = nullptr;
779 Fodder id_fodder;
780 switch (next.kind) {
781 case Token::DOT: {
782 Token field_id = popExpect(Token::IDENTIFIER);
783 id_fodder = field_id.fodder;
784 id = alloc->makeIdentifier(field_id.data32());
785 } break;
786 case Token::BRACKET_L: {
787 index = parse(MAX_PRECEDENCE, current_depth + 1);
788 Token bracket_r = popExpect(Token::BRACKET_R);
789 id_fodder = bracket_r.fodder; // Not id_fodder, but use the same var.
790 } break;
791 default: throw StaticError(tok.location, "expected . or [ after super.");
792 }
793 return alloc->make<SuperIndex>(
794 span(tok), tok.fodder, next.fodder, index, id_fodder, id);
795 }
796 }
797
798 std::cerr << "INTERNAL ERROR: Unknown tok kind: " << tok.kind << std::endl;
799 std::abort();
800 return nullptr; // Quiet, compiler.
801 }
802
803 /** If the first token makes it clear that we will be parsing a greedy construct, return the AST.
804 * Otherwise, return nullptr. Greedy constructs are those that consume as many tokens as possible
805 * on the right hand side because they have no closing token.
806 *
807 * \param current_depth Current recursion depth to prevent stack overflow.
808 * \returns The parsed AST or nullptr.
809 */
810 AST *maybeParseGreedy(unsigned current_depth)
811 {
812 if (current_depth >= MAX_PARSER_DEPTH) {
813 throw StaticError(peek().location, "Exceeded maximum parse depth limit.");
814 }
815
816 // Allocate this on the heap to control stack growth.
817 std::unique_ptr<Token> begin_(new Token(peek()));
818 const Token &begin = *begin_;
819
820 switch (begin.kind) {
821 // These cases have effectively MAX_PRECEDENCE as the first
822 // call to parse will parse them.
823 case Token::ASSERT: {
824 pop();
825 AST *cond = parse(MAX_PRECEDENCE, current_depth + 1);
826 Fodder colonFodder;
827 AST *msg = nullptr;
828 if (peek().kind == Token::OPERATOR && peek().data == ":") {
829 Token colon = pop();
830 colonFodder = colon.fodder;
831 msg = parse(MAX_PRECEDENCE, current_depth + 1);
832 }
833 Token semicolon = popExpect(Token::SEMICOLON);
834 AST *rest = parse(MAX_PRECEDENCE, current_depth + 1);
835 return alloc->make<Assert>(span(begin, rest),
836 begin.fodder,
837 cond,
838 colonFodder,
839 msg,
840 semicolon.fodder,
841 rest);
842 }
843
844 case Token::ERROR: {
845 pop();
846 AST *expr = parse(MAX_PRECEDENCE, current_depth + 1);
847 return alloc->make<Error>(span(begin, expr), begin.fodder, expr);
848 }
849
850 case Token::IF: {
851 pop();
852 AST *cond = parse(MAX_PRECEDENCE, current_depth + 1);
853 Token then = popExpect(Token::THEN);
854 AST *branch_true = parse(MAX_PRECEDENCE, current_depth + 1);
855 if (peek().kind == Token::ELSE) {
856 Token else_ = pop();
857 AST *branch_false = parse(MAX_PRECEDENCE, current_depth + 1);
858 return alloc->make<Conditional>(span(begin, branch_false),
859 begin.fodder,
860 cond,
861 then.fodder,
862 branch_true,
863 else_.fodder,
864 branch_false);
865 }
866 return alloc->make<Conditional>(span(begin, branch_true),
867 begin.fodder,
868 cond,
869 then.fodder,
870 branch_true,
871 Fodder{},
872 nullptr);
873 }
874
875 case Token::FUNCTION: {
876 pop(); // Still available in 'begin'.
877 Token paren_l = pop();
878 if (paren_l.kind == Token::PAREN_L) {
879 std::vector<AST *> params_asts;
880 bool got_comma;
881 Fodder paren_r_fodder;
882 ArgParams params = parseParams("function parameter", got_comma, paren_r_fodder, current_depth);
883 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
884 return alloc->make<Function>(span(begin, body),
885 begin.fodder,
886 paren_l.fodder,
887 params,
888 got_comma,
889 paren_r_fodder,
890 body);
891 } else {
892 std::stringstream ss;
893 ss << "expected ( but got " << paren_l;
894 throw StaticError(paren_l.location, ss.str());
895 }
896 }
897
898 case Token::IMPORT: {
899 pop();
900 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
901 if (body->type == AST_LITERAL_STRING) {
902 auto *lit = static_cast<LiteralString *>(body);
903 if (lit->tokenKind == LiteralString::BLOCK) {
904 throw StaticError(lit->location,
905 "Cannot use text blocks in import statements.");
906 }
907 return alloc->make<Import>(span(begin, body), begin.fodder, lit);
908 } else {
909 std::stringstream ss;
910 ss << "computed imports are not allowed.";
911 throw StaticError(body->location, ss.str());
912 }
913 }
914
915 case Token::IMPORTSTR: {
916 pop();
917 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
918 if (body->type == AST_LITERAL_STRING) {
919 auto *lit = static_cast<LiteralString *>(body);
920 if (lit->tokenKind == LiteralString::BLOCK) {
921 throw StaticError(lit->location,
922 "Cannot use text blocks in import statements.");
923 }
924 return alloc->make<Importstr>(span(begin, body), begin.fodder, lit);
925 } else {
926 std::stringstream ss;
927 ss << "computed imports are not allowed.";
928 throw StaticError(body->location, ss.str());
929 }
930 }
931
932 case Token::IMPORTBIN: {
933 pop();
934 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
935 if (body->type == AST_LITERAL_STRING) {
936 auto *lit = static_cast<LiteralString *>(body);
937 if (lit->tokenKind == LiteralString::BLOCK) {
938 throw StaticError(lit->location,
939 "Cannot use text blocks in import statements.");
940 }
941 return alloc->make<Importbin>(span(begin, body), begin.fodder, lit);
942 } else {
943 std::stringstream ss;
944 ss << "computed imports are not allowed.";
945 throw StaticError(body->location, ss.str());
946 }
947 }
948
949 case Token::LOCAL: {
950 pop();
951 Local::Binds binds;
952 do {
953 Token delim = parseBind(binds, current_depth + 1);
954 if (delim.kind != Token::SEMICOLON && delim.kind != Token::COMMA) {
955 std::stringstream ss;
956 ss << "expected , or ; but got " << delim;
957 throw StaticError(delim.location, ss.str());
958 }
959 if (delim.kind == Token::SEMICOLON)
960 break;
961 } while (true);
962 AST *body = parse(MAX_PRECEDENCE, current_depth + 1);
963 return alloc->make<Local>(span(begin, body), begin.fodder, binds, body);
964 }
965
966 default:
967 return nullptr;
968 }
969 }
970
971
972 /** Parse a general expression.
973 *
974 * Consume infix tokens up to (but not including) max_precedence, then stop.
975 * \param max_precedence The maximum precedence to consider.
976 * \param current_depth Current recursion depth to prevent stack overflow.
977 * \returns The parsed AST.
978 */
979 AST *parse(unsigned max_precedence, unsigned current_depth)
980 {
981 if (current_depth >= MAX_PARSER_DEPTH) {
982 throw StaticError(peek().location, "Exceeded maximum parse depth limit.");
983 }
984
985 AST *ast = maybeParseGreedy(current_depth + 1);
986 // There cannot be an operator after a greedy parse.
987 if (ast != nullptr) return ast;
988
989 // If we get here, we could be parsing an infix construct.
990
991 // Allocate this on the heap to control stack growth.
992 std::unique_ptr<Token> begin_(new Token(peek()));
993 const Token &begin = *begin_;
994
995 AST *lhs = parseTerminalBracketsOrUnary(current_depth + 1);
996
997 return parseInfix(lhs, begin, max_precedence, current_depth + 1);
998 }
999
1000 /** Parse infix operators (binary operators, indexing, function calls).
1001 *
1002 * \param lhs Left-hand side of the operator.
1003 * \param begin The token representing the beginning of the expression.
1004 * \param max_precedence The maximum precedence to consider.
1005 * \param current_depth Current recursion depth to prevent stack overflow.
1006 * \returns The parsed AST.
1007 */
1008 AST *parseInfix(AST *lhs, const Token &begin, unsigned max_precedence, unsigned current_depth)
1009 {
1010 if (current_depth >= MAX_PARSER_DEPTH) {
1011 throw StaticError(peek().location, "Exceeded maximum parse depth limit.");
1012 }
1013
1014 while (true) {
1015
1016 BinaryOp bop = BOP_PLUS;
1017 unsigned op_precedence = 0;
1018
1019 switch (peek().kind) {
1020 // Logical / arithmetic binary operator.
1021 case Token::IN:
1022 case Token::OPERATOR:
1023 // These occur if the outer statement was an assert or array slice.
1024 // Either way, we terminate the parsing here.
1025 if (peek().data == ":" || peek().data == "::") {
1026 return lhs;
1027 }
1028 if (!op_is_binary(peek().data, bop)) {
1029 std::stringstream ss;
1030 ss << "not a binary operator: " << peek().data;
1031 throw StaticError(peek().location, ss.str());
1032 }
1033 op_precedence = precedence_map[bop];
1034 break;
1035
1036 // Index, Apply
1037 case Token::DOT:
1038 case Token::BRACKET_L:
1039 case Token::PAREN_L:
1040 case Token::BRACE_L:
1041 op_precedence = APPLY_PRECEDENCE;
1042 break;
1043
1044 default:
1045 // This happens when we reach EOF or the terminating token of an outer context.
1046 return lhs;
1047 }
1048
1049 // If higher precedence than the outer recursive call, let that handle it.
1050 if (op_precedence >= max_precedence)
1051 return lhs;
1052
1053 Token op = pop();
1054
1055 switch (op.kind) {
1056 case Token::BRACKET_L: {
1057 bool is_slice;
1058 AST *first = nullptr;
1059 Fodder second_fodder;
1060 AST *second = nullptr;
1061 Fodder third_fodder;
1062 AST *third = nullptr;
1063
1064 if (peek().kind == Token::BRACKET_R)
1065 throw unexpected(pop(), "parsing index");
1066
1067 if (peek().data != ":" && peek().data != "::") {
1068 first = parse(MAX_PRECEDENCE, current_depth + 1);
1069 }
1070
1071 if (peek().kind == Token::OPERATOR && peek().data == "::") {
1072 // Handle ::
1073 is_slice = true;
1074 Token joined = pop();
1075 second_fodder = joined.fodder;
1076
1077 if (peek().kind != Token::BRACKET_R)
1078 third = parse(MAX_PRECEDENCE, current_depth + 1);
1079
1080 } else if (peek().kind != Token::BRACKET_R) {
1081 is_slice = true;
1082 Token delim = pop();
1083 if (delim.data != ":")
1084 throw unexpected(delim, "parsing slice");
1085
1086 second_fodder = delim.fodder;
1087
1088 if (peek().data != ":" && peek().kind != Token::BRACKET_R)
1089 second = parse(MAX_PRECEDENCE, current_depth + 1);
1090
1091 if (peek().kind != Token::BRACKET_R) {
1092 Token delim = pop();
1093 if (delim.data != ":")
1094 throw unexpected(delim, "parsing slice");
1095
1096 third_fodder = delim.fodder;
1097
1098 if (peek().kind != Token::BRACKET_R)
1099 third = parse(MAX_PRECEDENCE, current_depth + 1);
1100 }
1101 } else {
1102 is_slice = false;
1103 }
1104 Token end = popExpect(Token::BRACKET_R);
1105 lhs = alloc->make<Index>(span(begin, end),
1106 EMPTY_FODDER,
1107 lhs,
1108 op.fodder,
1109 is_slice,
1110 first,
1111 second_fodder,
1112 second,
1113 third_fodder,
1114 third,
1115 end.fodder);
1116 break;
1117 }
1118 case Token::DOT: {
1119 Token field_id = popExpect(Token::IDENTIFIER);
1120 const Identifier *id = alloc->makeIdentifier(field_id.data32());
1121 lhs = alloc->make<Index>(span(begin, field_id),
1122 EMPTY_FODDER,
1123 lhs,
1124 op.fodder,
1125 field_id.fodder,
1126 id);
1127 break;
1128 }
1129 case Token::PAREN_L: {
1130 ArgParams args;
1131 bool got_comma;
1132 Token end = parseArgs(args, "function argument", got_comma, current_depth);
1133 bool got_named = false;
1134 for (const auto& arg : args) {
1135 if (arg.id != nullptr) {
1136 got_named = true;
1137 } else {
1138 if (got_named) {
1139 throw StaticError(arg.expr->location, "Positional argument after a named argument is not allowed");
1140 }
1141 }
1142 }
1143 bool tailstrict = false;
1144 Fodder tailstrict_fodder;
1145 if (peek().kind == Token::TAILSTRICT) {
1146 Token tailstrict_token = pop();
1147 tailstrict_fodder = tailstrict_token.fodder;
1148 tailstrict = true;
1149 }
1150 lhs = alloc->make<Apply>(span(begin, end),
1151 EMPTY_FODDER,
1152 lhs,
1153 op.fodder,
1154 args,
1155 got_comma,
1156 end.fodder,
1157 tailstrict_fodder,
1158 tailstrict);
1159 break;
1160 }
1161 case Token::BRACE_L: {
1162 AST *obj;
1163 Token end = parseObjectRemainder(obj, op, current_depth + 1);
1164 lhs = alloc->make<ApplyBrace>(span(begin, end), EMPTY_FODDER, lhs, obj);
1165 break;
1166 }
1167
1168 case Token::IN: {
1169 if (peek().kind == Token::SUPER) {
1170 Token super = pop();
1171 lhs = alloc->make<InSuper>(
1172 span(begin, super), EMPTY_FODDER, lhs, op.fodder, super.fodder);
1173 } else {
1174 AST *rhs = parse(op_precedence, current_depth + 1);
1175 lhs = alloc->make<Binary>(
1176 span(begin, rhs), EMPTY_FODDER, lhs, op.fodder, bop, rhs);
1177 }
1178 break;
1179 }
1180
1181 case Token::OPERATOR: {
1182 AST *rhs = parse(op_precedence, current_depth + 1);
1183 lhs = alloc->make<Binary>(
1184 span(begin, rhs), EMPTY_FODDER, lhs, op.fodder, bop, rhs);
1185 break;
1186 }
1187
1188 default: {
1189 std::cerr << "Should not be here." << std::endl;
1190 abort();
1191 }
1192 }
1193 }
1194
1195 // (1 & ((1 + (1 * 1)) + 1)) & 1
1196 //
1197 //
1198
1199 /*
1200 // Allocate this on the heap to control stack growth.
1201 std::unique_ptr<Token> begin_(new Token(peek()));
1202 const Token &begin = *begin_;
1203 */
1204 }
1205 };
1206
1207 } // namespace
1208
1209 AST *jsonnet_parse(Allocator *alloc, Tokens &tokens)
1210 {
1211 Parser parser(tokens, alloc);
1212 unsigned parse_depth = 0;
1213 AST *expr = parser.parse(MAX_PRECEDENCE, parse_depth);
1214 if (tokens.front().kind != Token::END_OF_FILE) {
1215 std::stringstream ss;
1216 ss << "did not expect: " << tokens.front();
1217 throw StaticError(tokens.front().location, ss.str());
1218 }
1219
1220 return expr;
1221 }
1222
1223 } // namespace jsonnet::internal