Debian Codegraph @

core/desugarer.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
19 #include <algorithm>
20
21 #include "ast.h"
22 #include "desugarer.h"
23 #include "lexer.h"
24 #include "parser.h"
25 #include "pass.h"
26 #include "string_utils.h"
27
28 namespace jsonnet::internal {
29
30 static const Fodder EF; // Empty fodder.
31
32 static const LocationRange E; // Empty.
33
34 struct BuiltinDecl {
35 UString name;
36 std::vector<UString> params;
37 };
38
39 static unsigned long max_builtin = 41;
40 BuiltinDecl jsonnet_builtin_decl(unsigned long builtin)
41 {
42 switch (builtin) {
43 case 0: return {U"makeArray", {U"sz", U"func"}};
44 case 1: return {U"pow", {U"x", U"n"}};
45 case 2: return {U"floor", {U"x"}};
46 case 3: return {U"ceil", {U"x"}};
47 case 4: return {U"sqrt", {U"x"}};
48 case 5: return {U"sin", {U"x"}};
49 case 6: return {U"cos", {U"x"}};
50 case 7: return {U"tan", {U"x"}};
51 case 8: return {U"asin", {U"x"}};
52 case 9: return {U"acos", {U"x"}};
53 case 10: return {U"atan", {U"x"}};
54 case 11: return {U"type", {U"x"}};
55 case 12: return {U"filter", {U"func", U"arr"}};
56 case 13: return {U"objectHasEx", {U"obj", U"f", U"inc_hidden"}};
57 case 14: return {U"length", {U"x"}};
58 case 15: return {U"objectFieldsEx", {U"obj", U"inc_hidden"}};
59 case 16: return {U"codepoint", {U"str"}};
60 case 17: return {U"char", {U"n"}};
61 case 18: return {U"log", {U"n"}};
62 case 19: return {U"exp", {U"n"}};
63 case 20: return {U"mantissa", {U"n"}};
64 case 21: return {U"exponent", {U"n"}};
65 case 22: return {U"modulo", {U"a", U"b"}};
66 case 23: return {U"extVar", {U"x"}};
67 case 24: return {U"primitiveEquals", {U"a", U"b"}};
68 case 25: return {U"native", {U"name"}};
69 case 26: return {U"md5", {U"str"}};
70 case 27: return {U"trace", {U"str", U"rest"}};
71 case 28: return {U"splitLimit", {U"str", U"c", U"maxsplits"}};
72 case 29: return {U"substr", {U"str", U"from", U"len"}};
73 case 30: return {U"range", {U"from", U"to"}};
74 case 31: return {U"strReplace", {U"str", U"from", U"to"}};
75 case 32: return {U"asciiLower", {U"str"}};
76 case 33: return {U"asciiUpper", {U"str"}};
77 case 34: return {U"join", {U"sep", U"arr"}};
78 case 35: return {U"parseJson", {U"str"}};
79 case 36: return {U"parseYaml", {U"str"}};
80 case 37: return {U"encodeUTF8", {U"str"}};
81 case 38: return {U"decodeUTF8", {U"arr"}};
82 case 39: return {U"atan2", {U"y", U"x"}};
83 case 40: return {U"hypot", {U"a", U"b"}};
84 case 41: return {U"objectRemoveKey", {U"obj", U"key"}};
85 default:
86 std::cerr << "INTERNAL ERROR: Unrecognized builtin function: " << builtin << std::endl;
87 std::abort();
88 }
89 // Quiet, compiler.
90 return BuiltinDecl();
91 }
92
93 static constexpr char STD_CODE[] = {
94 #include "std.jsonnet.h"
95 };
96
97 /** Desugar Jsonnet expressions to reduce the number of constructs the rest of the implementation
98 * needs to understand.
99 *
100 * Desugaring should happen immediately after parsing, i.e. before static analysis and execution.
101 * Temporary variables introduced here should be prefixed with $ to ensure they do not clash with
102 * variables used in user code.
103 */
104 class Desugarer {
105 Allocator *alloc;
106 bool isStdlib;
107
108 template <class T, class... Args>
109 T *make(Args &&... args)
110 {
111 return alloc->make<T>(std::forward<Args>(args)...);
112 }
113
114 AST *clone(AST *ast)
115 {
116 return clone_ast(*alloc, ast);
117 }
118
119 const Identifier *id(const UString &s)
120 {
121 return alloc->makeIdentifier(s);
122 }
123
124 LiteralString *str(const UString &s)
125 {
126 return make<LiteralString>(E, EF, s, LiteralString::RAW_DESUGARED, "", "");
127 }
128
129 LiteralString *str(const LocationRange &loc, const UString &s)
130 {
131 return make<LiteralString>(loc, EF, s, LiteralString::RAW_DESUGARED, "", "");
132 }
133
134 LiteralNull *null(void)
135 {
136 return make<LiteralNull>(E, EF);
137 }
138
139 Var *var(const Identifier *ident)
140 {
141 return make<Var>(E, EF, ident);
142 }
143
144 Var *std(void)
145 {
146 // In most places, there is a "$std" variable inserted by
147 // the desugarer. On the standard library itself there isn't,
148 // so use "std" instead.
149 return var(id(isStdlib ? U"std" : U"$std"));
150 }
151
152 Local::Bind bind(const Identifier *id, AST *body)
153 {
154 return Local::Bind(EF, id, EF, body, false, EF, ArgParams{}, false, EF, EF);
155 }
156
157 Local::Binds singleBind(const Identifier *id, AST *body)
158 {
159 return {bind(id, body)};
160 }
161
162 Array *singleton(AST *body)
163 {
164 return make<Array>(
165 body->location, EF, Array::Elements{Array::Element(body, EF)}, false, EF);
166 }
167
168 Apply *stdFunc(const UString &name, AST *v)
169 {
170 return make<Apply>(
171 v->location,
172 EF,
173 make<Index>(E, EF, std(), EF, false, str(name), EF, nullptr, EF, nullptr, EF),
174 EF,
175 ArgParams{{v, EF}},
176 false, // trailingComma
177 EF,
178 EF,
179 true // tailstrict
180 );
181 }
182
183 Apply *stdFunc(const LocationRange &loc, const UString &name, AST *a, AST *b)
184 {
185 return make<Apply>(
186 loc,
187 EF,
188 make<Index>(E, EF, std(), EF, false, str(name), EF, nullptr, EF, nullptr, EF),
189 EF,
190 ArgParams{{a, EF}, {b, EF}},
191 false, // trailingComma
192 EF,
193 EF,
194 true // tailstrict
195 );
196 }
197
198 Apply *length(AST *v)
199 {
200 return stdFunc(U"length", v);
201 }
202
203 Apply *type(AST *v)
204 {
205 return stdFunc(U"type", v);
206 }
207
208 Apply *primitiveEquals(const LocationRange &loc, AST *a, AST *b)
209 {
210 return stdFunc(loc, U"primitiveEquals", a, b);
211 }
212
213 Apply *equals(const LocationRange &loc, AST *a, AST *b)
214 {
215 return stdFunc(loc, U"equals", a, b);
216 }
217
218 Error *error(AST *msg)
219 {
220 return make<Error>(msg->location, EF, msg);
221 }
222
223 Error *error(const LocationRange &loc, const UString &msg)
224 {
225 return error(str(loc, msg));
226 }
227
228 public:
229 Desugarer(Allocator *alloc, bool isStdlib = false) : alloc(alloc), isStdlib(isStdlib) {}
230
231 void desugarParams(ArgParams &params, unsigned obj_level)
232 {
233 for (auto &param : params) {
234 if (param.expr) {
235 // Default arg.
236 desugar(param.expr, obj_level);
237 }
238 }
239 }
240
241 // For all occurrences, records the identifier that will replace super[e]
242 // If self occurs, also map the self identifier to nullptr.
243 typedef std::vector<std::pair<const Identifier *, AST *>> SuperVars;
244
245 SuperVars desugarFields(AST *ast, ObjectFields &fields, unsigned obj_level)
246 {
247 // Desugar children
248 for (auto &field : fields) {
249 if (field.expr1 != nullptr)
250 desugar(field.expr1, obj_level);
251 desugar(field.expr2, obj_level + 1);
252 if (field.expr3 != nullptr)
253 desugar(field.expr3, obj_level + 1);
254 desugarParams(field.params, obj_level + 1);
255 }
256
257 // Simplify asserts
258 for (auto &field : fields) {
259 if (field.kind != ObjectField::ASSERT)
260 continue;
261 AST *msg = field.expr3;
262 field.expr3 = nullptr;
263 if (msg == nullptr) {
264 // The location is what appears in the stacktrace.
265 msg = str(field.expr2->location, U"Object assertion failed.");
266 }
267
268 // if expr2 then true else error msg
269 field.expr2 = make<Conditional>(field.expr2->location,
270 EF,
271 field.expr2,
272 EF,
273 make<LiteralBoolean>(E, EF, true),
274 EF,
275 error(msg));
276 }
277
278 // Remove methods
279 for (auto &field : fields) {
280 if (!field.methodSugar)
281 continue;
282 field.expr2 = make<Function>(field.expr2->location,
283 EF,
284 field.fodderL,
285 field.params,
286 field.trailingComma,
287 field.fodderR,
288 field.expr2);
289 field.methodSugar = false;
290 field.params.clear();
291 }
292
293 // Remove object-level locals
294 auto copy = fields;
295 fields.clear();
296 Local::Binds binds;
297 for (auto &local : copy) {
298 if (local.kind != ObjectField::LOCAL)
299 continue;
300 binds.push_back(bind(local.id, local.expr2));
301 }
302 for (auto &field : copy) {
303 if (field.kind == ObjectField::LOCAL)
304 continue;
305 if (!binds.empty())
306 field.expr2 = make<Local>(field.expr2->location, EF, binds, field.expr2);
307 fields.push_back(field);
308 }
309
310 // Change all to FIELD_EXPR
311 for (auto &field : fields) {
312 switch (field.kind) {
313 case ObjectField::ASSERT:
314 // Nothing to do.
315 break;
316
317 case ObjectField::FIELD_ID:
318 field.expr1 = str(field.idLocation, field.id->name);
319 field.kind = ObjectField::FIELD_EXPR;
320 break;
321
322 case ObjectField::FIELD_EXPR:
323 // Nothing to do.
324 break;
325
326 case ObjectField::FIELD_STR:
327 // Just set the flag.
328 field.kind = ObjectField::FIELD_EXPR;
329 break;
330
331 case ObjectField::LOCAL:
332 std::cerr << "Locals should be removed by now." << std::endl;
333 abort();
334 }
335 }
336
337 /** Replaces all occurrences of self, super[f] and e in super with variables.
338 *
339 * Returns all variables and original expressions via super_vars.
340 */
341 class SubstituteSelfSuper : public CompilerPass {
342 Desugarer *desugarer;
343 SuperVars &superVars;
344 unsigned &counter;
345 const Identifier *newSelf;
346
347 public:
348 SubstituteSelfSuper(Desugarer *desugarer, SuperVars &super_vars, unsigned &counter)
349 : CompilerPass(*desugarer->alloc),
350 desugarer(desugarer),
351 superVars(super_vars),
352 counter(counter),
353 newSelf(nullptr)
354 {
355 }
356 void visitExpr(AST *&expr)
357 {
358 if (dynamic_cast<Self *>(expr)) {
359 if (newSelf == nullptr) {
360 newSelf = desugarer->id(U"$outer_self");
361 superVars.emplace_back(newSelf, nullptr);
362 }
363 expr = alloc.make<Var>(expr->location, expr->openFodder, newSelf);
364 } else if (auto *super_index = dynamic_cast<SuperIndex *>(expr)) {
365 UStringStream ss;
366 ss << U"$outer_super_index" << (counter++);
367 const Identifier *super_var = desugarer->id(ss.str());
368 // Desugaring of expr should already have occurred.
369 assert(super_index->index != nullptr);
370 // Re-use super_index since we're replacing it here.
371 superVars.emplace_back(super_var, super_index);
372 expr = alloc.make<Var>(expr->location, expr->openFodder, super_var);
373 } else if (auto *in_super = dynamic_cast<InSuper *>(expr)) {
374 UStringStream ss;
375 ss << U"$outer_in_super" << (counter++);
376 const Identifier *in_super_var = desugarer->id(ss.str());
377 // Re-use in_super since we're replacing it here.
378 superVars.emplace_back(in_super_var, in_super);
379 expr = alloc.make<Var>(expr->location, expr->openFodder, in_super_var);
380 }
381 CompilerPass::visitExpr(expr);
382 }
383 };
384
385 SuperVars super_vars;
386 unsigned counter = 0;
387
388 // Remove +:
389 for (auto &field : fields) {
390 if (!field.superSugar)
391 continue;
392 // We have to bind self/super from expr1 outside the class, as we copy the expression
393 // into the field body.
394 // Clone it so that we maintain the AST as a tree.
395 AST *index = clone(field.expr1);
396 // This will remove self/super.
397 SubstituteSelfSuper(this, super_vars, counter).expr(index);
398 field.expr2 = make<Conditional>(
399 ast->location,
400 EF,
401 make<InSuper>(ast->location, EF, index, EF, EF),
402 EF,
403 make<Binary>(ast->location,
404 EF,
405 make<SuperIndex>(ast->location, EF, EF, clone(index), EF, nullptr),
406 EF,
407 BOP_PLUS,
408 field.expr2),
409 EF,
410 clone(field.expr2));
411 field.superSugar = false;
412 }
413
414 return super_vars;
415 }
416
417 AST* makeArrayComprehension(ArrayComprehension *ast) {
418 int n = ast->specs.size();
419 AST *zero = make<LiteralNumber>(E, EF, "0.0");
420 AST *one = make<LiteralNumber>(E, EF, "1.0");
421 auto *_r = id(U"$r");
422 auto *_l = id(U"$l");
423 std::vector<const Identifier *> _i(n);
424 for (int i = 0; i < n; ++i) {
425 UStringStream ss;
426 ss << U"$i_" << i;
427 _i[i] = id(ss.str());
428 }
429 std::vector<const Identifier *> _aux(n);
430 for (int i = 0; i < n; ++i) {
431 UStringStream ss;
432 ss << U"$aux_" << i;
433 _aux[i] = id(ss.str());
434 }
435
436 // Build it from the inside out. We keep wrapping 'in' with more ASTs.
437 assert(ast->specs[0].kind == ComprehensionSpec::FOR);
438
439 int last_for = n - 1;
440 while (ast->specs[last_for].kind != ComprehensionSpec::FOR)
441 last_for--;
442 // $aux_{last_for}($i_{last_for} + 1, $r + [body])
443 AST *in = make<Apply>(
444 ast->body->location,
445 EF,
446 var(_aux[last_for]),
447 EF,
448 ArgParams{{make<Binary>(E, EF, var(_i[last_for]), EF, BOP_PLUS, one), EF},
449 {make<Binary>(E, EF, var(_r), EF, BOP_PLUS, singleton(ast->body)), EF}},
450 false, // trailingComma
451 EF,
452 EF,
453 true // tailstrict
454 );
455 for (int i = n - 1; i >= 0; --i) {
456 const ComprehensionSpec &spec = ast->specs[i];
457 AST *out;
458 if (i > 0) {
459 int prev_for = i - 1;
460 while (ast->specs[prev_for].kind != ComprehensionSpec::FOR)
461 prev_for--;
462
463 // aux_{prev_for}($i_{prev_for} + 1, $r)
464 out = make<Apply>( // False branch.
465 E,
466 EF,
467 var(_aux[prev_for]),
468 EF,
469 ArgParams{{
470 make<Binary>(E, EF, var(_i[prev_for]), EF, BOP_PLUS, one),
471 EF,
472 },
473 {
474 var(_r),
475 EF,
476 }},
477 false, // trailingComma
478 EF,
479 EF,
480 true // tailstrict
481 );
482 } else {
483 out = var(_r);
484 }
485 switch (spec.kind) {
486 case ComprehensionSpec::IF: {
487 /*
488 if [[[...cond...]]] then
489 [[[...in...]]]
490 else
491 [[[...out...]]]
492 */
493 in = make<Conditional>(ast->location,
494 EF,
495 spec.expr,
496 EF,
497 in, // True branch.
498 EF,
499 out); // False branch.
500 } break;
501 case ComprehensionSpec::FOR: {
502 /*
503 local $l = [[[...array...]]]
504 aux_{i}(i_{i}, r) =
505 if i_{i} >= std.length($l) then
506 [[[...out...]]]
507 else
508 local [[[...var...]]] = $l[i_{i}];
509 [[[...in...]]];
510 if std.type($l) == "array" then
511 aux_{i}(0, $r) tailstrict
512 else
513 error "In comprehension, can only iterate over array..";
514 */
515 in = make<Local>(
516 ast->location,
517 EF,
518 Local::Binds{
519 bind(_l, spec.expr), // Need to check expr is an array
520 bind(_aux[i],
521 make<Function>(
522 ast->location,
523 EF,
524 EF,
525 ArgParams{{EF, _i[i], EF}, {EF, _r, EF}},
526 false, // trailingComma
527 EF,
528 make<Conditional>(ast->location,
529 EF,
530 make<Binary>(E,
531 EF,
532 var(_i[i]),
533 EF,
534 BOP_GREATER_EQ,
535 length(var(_l))),
536 EF,
537 out,
538 EF,
539 make<Local>(
540 ast->location,
541 EF,
542 singleBind(spec.var,
543 make<Index>(E,
544 EF,
545 var(_l),
546 EF,
547 false,
548 var(_i[i]),
549 EF,
550 nullptr,
551 EF,
552 nullptr,
553 EF)),
554 in))))},
555 make<Conditional>(
556 ast->location,
557 EF,
558 equals(ast->location, type(var(_l)), str(U"array")),
559 EF,
560 make<Apply>(
561 E,
562 EF,
563 var(_aux[i]),
564 EF,
565 ArgParams{{zero, EF},
566 {
567 i == 0 ? make<Array>(
568 E, EF, Array::Elements{}, false, EF)
569 : static_cast<AST *>(var(_r)),
570 EF,
571 }},
572 false, // trailingComma
573 EF,
574 EF,
575 true), // tailstrict
576 EF,
577 error(ast->location,
578 U"In comprehension, can only iterate over array.")));
579 } break;
580 }
581 }
582
583 return in;
584 }
585
586 AST* makeObject(Object *ast, unsigned obj_level) {
587 // Hidden variable to allow outer/top binding.
588 if (obj_level == 0) {
589 const Identifier *hidden_var = id(U"$");
590 auto *body = make<Self>(E, EF);
591 ast->fields.push_back(ObjectField::Local(EF, EF, hidden_var, EF, body, EF));
592 }
593
594 SuperVars svs = desugarFields(ast, ast->fields, obj_level);
595
596 DesugaredObject::Fields new_fields;
597 ASTs new_asserts;
598 for (const ObjectField &field : ast->fields) {
599 if (field.kind == ObjectField::ASSERT) {
600 new_asserts.push_back(field.expr2);
601 } else if (field.kind == ObjectField::FIELD_EXPR) {
602 new_fields.emplace_back(field.hide, field.expr1, field.expr2);
603 } else {
604 std::cerr << "INTERNAL ERROR: field should have been desugared: " << field.kind
605 << std::endl;
606 }
607 }
608
609 AST* retval = make<DesugaredObject>(ast->location, new_asserts, new_fields);
610 if (svs.size() > 0) {
611 Local::Binds binds;
612 for (const auto &pair : svs) {
613 if (pair.second == nullptr) {
614 // Self binding
615 binds.push_back(bind(pair.first, make<Self>(E, EF)));
616 } else {
617 // Super binding
618 binds.push_back(bind(pair.first, pair.second));
619 }
620 }
621 retval = make<Local>(ast->location, EF, binds, retval);
622 }
623
624 return retval;
625 }
626
627 AST* makeObjectComprehension(ObjectComprehension *ast, unsigned obj_level) {
628 // Hidden variable to allow outer/top binding.
629 if (obj_level == 0) {
630 const Identifier *hidden_var = id(U"$");
631 auto *body = make<Self>(E, EF);
632 ast->fields.push_back(ObjectField::Local(EF, EF, hidden_var, EF, body, EF));
633 }
634
635 SuperVars svs = desugarFields(ast, ast->fields, obj_level);
636
637 AST *field = ast->fields.front().expr1;
638 AST *value = ast->fields.front().expr2;
639
640 /* {
641 [arr[0]]: local x = arr[1], y = arr[2], z = arr[3]; val_expr
642 for arr in [ [key_expr, x, y, z] for ... ]
643 }
644 */
645 auto *_arr = id(U"$arr");
646 AST *zero = make<LiteralNumber>(E, EF, "0.0");
647 int counter = 1;
648 Local::Binds binds;
649 Array::Elements arr_e{Array::Element(field, EF)};
650 for (ComprehensionSpec &spec : ast->specs) {
651 if (spec.kind == ComprehensionSpec::FOR) {
652 std::stringstream num;
653 num << counter++;
654 binds.push_back(bind(spec.var,
655 make<Index>(E,
656 EF,
657 var(_arr),
658 EF,
659 false,
660 make<LiteralNumber>(E, EF, num.str()),
661 EF,
662 nullptr,
663 EF,
664 nullptr,
665 EF)));
666 arr_e.emplace_back(var(spec.var), EF);
667 }
668 }
669 AST *arr = make<ArrayComprehension>(ast->location,
670 EF,
671 make<Array>(ast->location, EF, arr_e, false, EF),
672 EF,
673 false,
674 ast->specs,
675 EF);
676 desugar(arr, obj_level);
677 return make<ObjectComprehensionSimple>(
678 ast->location,
679 make<Index>(E, EF, var(_arr), EF, false, zero, EF, nullptr, EF, nullptr, EF),
680 make<Local>(ast->location, EF, binds, value),
681 _arr,
682 arr);
683 }
684
685 void desugar(AST *&ast_, unsigned obj_level)
686 {
687 if (auto *ast = dynamic_cast<Apply *>(ast_)) {
688 desugar(ast->target, obj_level);
689 for (ArgParam &arg : ast->args)
690 desugar(arg.expr, obj_level);
691
692 } else if (auto *ast = dynamic_cast<ApplyBrace *>(ast_)) {
693 desugar(ast->left, obj_level);
694 desugar(ast->right, obj_level);
695 ast_ =
696 make<Binary>(ast->location, ast->openFodder, ast->left, EF, BOP_PLUS, ast->right);
697
698 } else if (auto *ast = dynamic_cast<Array *>(ast_)) {
699 for (auto &el : ast->elements)
700 desugar(el.expr, obj_level);
701
702 } else if (auto *ast = dynamic_cast<ArrayComprehension *>(ast_)) {
703 for (ComprehensionSpec &spec : ast->specs)
704 desugar(spec.expr, obj_level);
705 desugar(ast->body, obj_level + 1);
706
707 ast_ = makeArrayComprehension(ast);
708
709 } else if (auto *ast = dynamic_cast<Assert *>(ast_)) {
710 desugar(ast->cond, obj_level);
711 if (ast->message == nullptr) {
712 ast->message = str(U"Assertion failed.");
713 }
714 desugar(ast->message, obj_level);
715 desugar(ast->rest, obj_level);
716
717 // if cond then rest else error msg
718 AST *branch_false = make<Error>(ast->location, EF, ast->message);
719 ast_ = make<Conditional>(
720 ast->location, ast->openFodder, ast->cond, EF, ast->rest, EF, branch_false);
721
722 } else if (auto *ast = dynamic_cast<Binary *>(ast_)) {
723 desugar(ast->left, obj_level);
724 desugar(ast->right, obj_level);
725
726 bool invert = false;
727
728 switch (ast->op) {
729 case BOP_PERCENT: {
730 AST *f_mod = make<Index>(
731 E, EF, std(), EF, false, str(U"mod"), EF, nullptr, EF, nullptr, EF);
732 ArgParams args = {{ast->left, EF}, {ast->right, EF}};
733 ast_ = make<Apply>(
734 ast->location, ast->openFodder, f_mod, EF, args, false, EF, EF, false);
735 } break;
736
737 case BOP_MANIFEST_UNEQUAL: invert = true;
738 [[fallthrough]];
739 case BOP_MANIFEST_EQUAL: {
740 ast_ = equals(ast->location, ast->left, ast->right);
741 if (invert)
742 ast_ = make<Unary>(ast->location, ast->openFodder, UOP_NOT, ast_);
743 } break;
744
745 default:;
746 // Otherwise don't change it.
747 }
748
749 } else if (dynamic_cast<const BuiltinFunction *>(ast_)) {
750 // Nothing to do.
751
752 } else if (auto *ast = dynamic_cast<Conditional *>(ast_)) {
753 desugar(ast->cond, obj_level);
754 desugar(ast->branchTrue, obj_level);
755 if (ast->branchFalse == nullptr)
756 ast->branchFalse = null();
757 desugar(ast->branchFalse, obj_level);
758
759 } else if (auto *ast = dynamic_cast<Dollar *>(ast_)) {
760 if (obj_level == 0) {
761 throw StaticError(ast->location, "No top-level object found.");
762 }
763 ast_ = var(id(U"$"));
764
765 } else if (auto *ast = dynamic_cast<Error *>(ast_)) {
766 desugar(ast->expr, obj_level);
767
768 } else if (auto *ast = dynamic_cast<Function *>(ast_)) {
769 desugar(ast->body, obj_level);
770 desugarParams(ast->params, obj_level);
771
772 } else if (auto *ast = dynamic_cast<Import *>(ast_)) {
773 // TODO(dcunnin): Abstract this into a template function if it becomes more common.
774 AST *file = ast->file;
775 desugar(file, obj_level);
776 ast->file = dynamic_cast<LiteralString *>(file);
777
778 } else if (auto *ast = dynamic_cast<Importstr *>(ast_)) {
779 // TODO(dcunnin): Abstract this into a template function if it becomes more common.
780 AST *file = ast->file;
781 desugar(file, obj_level);
782 ast->file = dynamic_cast<LiteralString *>(file);
783
784 } else if (auto *ast = dynamic_cast<Importbin *>(ast_)) {
785 // TODO(dcunnin): Abstract this into a template function if it becomes more common.
786 AST *file = ast->file;
787 desugar(file, obj_level);
788 ast->file = dynamic_cast<LiteralString *>(file);
789
790 } else if (auto *ast = dynamic_cast<InSuper *>(ast_)) {
791 desugar(ast->element, obj_level);
792
793 } else if (auto *ast = dynamic_cast<Index *>(ast_)) {
794 desugar(ast->target, obj_level);
795 if (ast->isSlice) {
796 if (ast->index == nullptr)
797 ast->index = null();
798 desugar(ast->index, obj_level);
799
800 if (ast->end == nullptr)
801 ast->end = null();
802 desugar(ast->end, obj_level);
803
804 if (ast->step == nullptr)
805 ast->step = null();
806 desugar(ast->step, obj_level);
807
808 ast_ = make<Apply>(
809 ast->location,
810 EF,
811 make<Index>(
812 E, EF, std(), EF, false, str(U"slice"), EF, nullptr, EF, nullptr, EF),
813 EF,
814 ArgParams{
815 {ast->target, EF},
816 {ast->index, EF},
817 {ast->end, EF},
818 {ast->step, EF},
819 },
820 false, // trailing comma
821 EF,
822 EF,
823 false // tailstrict
824 );
825 } else {
826 if (ast->id != nullptr) {
827 assert(ast->index == nullptr);
828 ast->index = str(ast->id->name);
829 ast->id = nullptr;
830 }
831 desugar(ast->index, obj_level);
832 }
833
834 } else if (auto *ast = dynamic_cast<Local *>(ast_)) {
835 for (auto &bind : ast->binds)
836 desugar(bind.body, obj_level);
837 desugar(ast->body, obj_level);
838
839 for (auto &bind : ast->binds) {
840 if (bind.functionSugar) {
841 desugarParams(bind.params, obj_level);
842 bind.body = make<Function>(ast->location,
843 ast->openFodder,
844 bind.parenLeftFodder,
845 bind.params,
846 false,
847 bind.parenRightFodder,
848 bind.body);
849 bind.functionSugar = false;
850 bind.params.clear();
851 }
852 }
853
854 } else if (dynamic_cast<const LiteralBoolean *>(ast_)) {
855 // Nothing to do.
856
857 } else if (dynamic_cast<const LiteralNumber *>(ast_)) {
858 // Nothing to do.
859
860 } else if (auto *ast = dynamic_cast<LiteralString *>(ast_)) {
861 if ((ast->tokenKind != LiteralString::RAW_DESUGARED) &&
862 (ast->tokenKind != LiteralString::BLOCK) &&
863 (ast->tokenKind != LiteralString::VERBATIM_DOUBLE) &&
864 (ast->tokenKind != LiteralString::VERBATIM_SINGLE)) {
865 ast->value = jsonnet_string_unescape(ast->location, ast->value);
866 }
867 ast->tokenKind = LiteralString::RAW_DESUGARED;
868 ast->blockIndent.clear();
869
870 } else if (dynamic_cast<const LiteralNull *>(ast_)) {
871 // Nothing to do.
872
873 } else if (auto *ast = dynamic_cast<DesugaredObject *>(ast_)) {
874 for (auto &field : ast->fields) {
875 desugar(field.name, obj_level);
876 desugar(field.body, obj_level + 1);
877 }
878 for (AST *assert : ast->asserts) {
879 desugar(assert, obj_level + 1);
880 }
881
882 } else if (auto *ast = dynamic_cast<Object *>(ast_)) {
883 ast_ = makeObject(ast, obj_level);
884
885 } else if (auto *ast = dynamic_cast<ObjectComprehension *>(ast_)) {
886 ast_ = makeObjectComprehension(ast, obj_level);
887
888 } else if (auto *ast = dynamic_cast<ObjectComprehensionSimple *>(ast_)) {
889 desugar(ast->field, obj_level);
890 desugar(ast->value, obj_level + 1);
891 desugar(ast->array, obj_level);
892
893 } else if (auto *ast = dynamic_cast<Parens *>(ast_)) {
894 // Strip parens.
895 desugar(ast->expr, obj_level);
896 ast_ = ast->expr;
897
898 } else if (dynamic_cast<const Self *>(ast_)) {
899 // Nothing to do.
900
901 } else if (auto *ast = dynamic_cast<SuperIndex *>(ast_)) {
902 if (ast->id != nullptr) {
903 assert(ast->index == nullptr);
904 ast->index = str(ast->id->name);
905 ast->id = nullptr;
906 }
907 desugar(ast->index, obj_level);
908
909 } else if (auto *ast = dynamic_cast<Unary *>(ast_)) {
910 desugar(ast->expr, obj_level);
911
912 } else if (dynamic_cast<const Var *>(ast_)) {
913 // Nothing to do.
914
915 } else {
916 std::cerr << "INTERNAL ERROR: Unknown AST: " << ast_ << std::endl;
917 std::abort();
918 }
919 }
920
921 DesugaredObject *stdlibAST(std::string filename) {
922 // Now, implement the std library by wrapping in a local construct.
923 Tokens tokens = jsonnet_lex("std.jsonnet", STD_CODE);
924 AST *std_ast = jsonnet_parse(alloc, tokens);
925 desugar(std_ast, 0);
926 auto *std_obj = dynamic_cast<DesugaredObject *>(std_ast);
927 if (std_obj == nullptr) {
928 std::cerr << "INTERNAL ERROR: std.jsonnet not an object." << std::endl;
929 std::abort();
930 }
931
932 // Bind 'std' builtins that are implemented natively.
933 DesugaredObject::Fields &fields = std_obj->fields;
934 for (unsigned long c = 0; c <= max_builtin; ++c) {
935 const auto &decl = jsonnet_builtin_decl(c);
936 auto name = str(decl.name);
937 auto name_utf8 = "std:" + encode_utf8(decl.name);
938 auto fnbody = alloc->makeBuiltinBody(E, name_utf8, [this, &decl]()->Identifiers {
939 Identifiers params;
940 for (const auto &p : decl.params)
941 params.push_back(this->id(p));
942 return params;
943 });
944 auto field = std::find_if(fields.begin(), fields.end(),
945 [=](const DesugaredObject::Field& f) {
946 return static_cast<LiteralString*>(f.name)->value == decl.name;
947 });
948 auto fn = make<BuiltinFunction>(E, fnbody);
949 if (field != fields.end()) {
950 field->body = fn;
951 } else {
952 fields.emplace_back(ObjectField::HIDDEN, name, fn);
953 }
954 }
955 fields.emplace_back(
956 ObjectField::HIDDEN, str(U"thisFile"), str(decode_utf8(filename)));
957 return std_obj;
958 }
959
960 void desugarFile(AST *&ast, std::map<std::string, VmExt> *tlas)
961 {
962 desugar(ast, 0);
963
964 DesugaredObject *std_obj = stdlibAST(ast->location.file);
965
966 std::vector<std::string> empty;
967 auto line_end_blank = Fodder{{FodderElement::LINE_END, 1, 0, empty}};
968 auto line_end = Fodder{{FodderElement::LINE_END, 0, 0, empty}};
969
970 // local body = ast;
971 // if std.type(body) == "function") then
972 // body(tlas...)
973 // else
974 // body
975 if (tlas != nullptr) {
976 LocationRange tla_loc("Top-level function");
977 ArgParams args;
978 for (const auto &pair : *tlas) {
979 AST *expr;
980 if (pair.second.isCode) {
981 Tokens tokens = jsonnet_lex("tla:" + pair.first, pair.second.data.c_str());
982 expr = jsonnet_parse(alloc, tokens);
983 desugar(expr, 0);
984 } else {
985 expr = str(decode_utf8(pair.second.data));
986 }
987 // Add them as named arguments, so order does not matter.
988 args.emplace_back(EF, id(decode_utf8(pair.first)), EF, expr, EF);
989 }
990 const Identifier *body = id(U"top_level");
991 ast =
992 make<Local>(ast->location,
993 line_end_blank,
994 singleBind(body, ast),
995 make<Conditional>(E,
996 line_end,
997 primitiveEquals(E, type(var(body)), str(U"function")),
998 EF,
999 make<Apply>(tla_loc,
1000 EF,
1001 make<Var>(E, line_end, body),
1002 EF,
1003 args,
1004 false, // trailing comma
1005 EF,
1006 EF,
1007 false // tailstrict
1008 ),
1009 line_end,
1010 make<Var>(E, line_end, body)));
1011 }
1012
1013 // local $std = (std.jsonnet stuff); std = $std; ast
1014 // The standard library is bound to $std, which cannot be overriden,
1015 // so redefining std won't break expressions that desugar to calls
1016 // to standard library functions.
1017 ast = make<Local>(ast->location, EF, singleBind(id(U"std"), std()), ast);
1018 ast = make<Local>(ast->location, EF, singleBind(id(U"$std"), std_obj), ast);
1019 }
1020 };
1021
1022 DesugaredObject *makeStdlibAST(Allocator *alloc, std::string filename) {
1023 Desugarer desugarer(alloc, true);
1024 return desugarer.stdlibAST(filename);
1025 }
1026
1027 void jsonnet_desugar(Allocator *alloc, AST *&ast, std::map<std::string, VmExt> *tlas)
1028 {
1029 Desugarer desugarer(alloc);
1030 desugarer.desugarFile(ast, tlas);
1031 }
1032
1033 } // namespace jsonnet::internal