1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
use core:lang;
use lang:bs;
use lang:bs:macro;
Expr jsonLiteral(SrcPos pos, Block block, Expr expression) on Compiler {
Type type = named{JsonValue};
// Allow inserting JsonValues directly.
if (expression.result.type.type is type)
return expression;
var part = BSNamePart("__init", pos, Actuals(expression)).withFirst(type);
unless (found = type.find(part, Scope(type)) as Function) {
throw SyntaxError(pos, "Unable to store the type ${expression.result} in a JsonValue.");
}
CtorCall(pos, block.scope, found, Actuals(expression));
}
Expr jsonObject(SrcPos pos, Block block, ObjectElem[] elements) on Compiler {
ExprBlock child(pos, block);
Var map(child, named{Map<Str, JsonValue>}, SStr(" map"), Actuals());
child.add(map);
LocalVarAccess mapAccess(pos, map.var);
for (e in elements) {
Actuals params;
params.add(e.key);
params.add(e.value);
child.add(namedExpr(child, pos, "put", mapAccess, params));
}
child.add(mapAccess);
jsonLiteral(pos, block, child);
}
Expr jsonArray(SrcPos pos, Block block, Expr[] elements) on Compiler {
ExprBlock child(pos, block);
Var array(child, named{Array<JsonValue>}, SStr(" array"), Actuals());
child.add(array);
LocalVarAccess arrayAccess(pos, array.var);
for (e in elements) {
child.add(namedExpr(child, pos, "push", arrayAccess, Actuals(e)));
}
child.add(arrayAccess);
jsonLiteral(pos, block, child);
}
Expr jsonNull(SrcPos pos) on Compiler {
CtorCall(pos, Scope(), named{JsonValue:__init<JsonValue>}, Actuals());
}
/**
* Value storing pairs of expressions as elements to an object.
*/
package value ObjectElem {
Expr key;
Expr value;
init(Expr key, Expr value) {
init {
key = key;
value = value;
}
}
init(SStr key, Expr value) {
init {
key = StrLiteral(key.pos, key.v);
value = value;
}
}
}
|