1
0
mirror of https://github.com/stedolan/jq.git synced 2024-05-11 05:55:39 +00:00

Constant fold objects

This commit is contained in:
Nicolas Williams
2014-08-09 20:47:03 -05:00
parent f87521183f
commit c321c3b86b
3 changed files with 51 additions and 2 deletions

View File

@@ -499,7 +499,51 @@ block gen_both(block a, block b) {
return c; return c;
} }
block gen_const_array(block expr) { block gen_const_object(block expr) {
int is_const = 1;
jv o = jv_object();
jv k = jv_null();
jv v = jv_null();
for (inst *i = expr.first; i; i = i->next) {
if (i->op != SUBEXP_BEGIN ||
i->next == NULL ||
i->next->op != LOADK ||
i->next->next == NULL ||
i->next->next->op != SUBEXP_END) {
is_const = 0;
break;
}
k = jv_copy(i->next->imm.constant);
i = i->next->next->next;
if (i == NULL ||
i->op != SUBEXP_BEGIN ||
i->next == NULL ||
i->next->op != LOADK ||
i->next->next == NULL ||
i->next->next->op != SUBEXP_END) {
is_const = 0;
break;
}
v = jv_copy(i->next->imm.constant);
i = i->next->next->next;
if (i == NULL || i->op != INSERT) {
is_const = 0;
break;
}
o = jv_object_set(o, k, v);
}
if (!is_const) {
jv_free(o);
jv_free(k);
jv_free(v);
block b = {0,0};
return b;
}
block_free(expr);
return gen_const(o);
}
static block gen_const_array(block expr) {
/* /*
* An expr of all constant elements looks like this: * An expr of all constant elements looks like this:
* *

View File

@@ -36,6 +36,7 @@ block gen_lambda(block body);
block gen_call(const char* name, block body); block gen_call(const char* name, block body);
block gen_subexp(block a); block gen_subexp(block a);
block gen_both(block a, block b); block gen_both(block a, block b);
block gen_const_object(block expr);
block gen_collect(block expr); block gen_collect(block expr);
block gen_reduce(const char* varname, block source, block init, block body); block gen_reduce(const char* varname, block source, block init, block body);
block gen_foreach(const char* varname, block source, block init, block update, block extract); block gen_foreach(const char* varname, block source, block init, block update, block extract);

View File

@@ -631,7 +631,11 @@ FORMAT {
$$ = gen_const(jv_array()); $$ = gen_const(jv_array());
} | } |
'{' MkDict '}' { '{' MkDict '}' {
$$ = BLOCK(gen_subexp(gen_const(jv_object())), $2, gen_op_simple(POP)); block o = gen_const_object($2);
if (o.first != NULL)
$$ = o;
else
$$ = BLOCK(gen_subexp(gen_const(jv_object())), $2, gen_op_simple(POP));
} | } |
'$' IDENT { '$' IDENT {
$$ = gen_location(@$, locations, gen_op_unbound(LOADV, jv_string_value($2))); $$ = gen_location(@$, locations, gen_op_unbound(LOADV, jv_string_value($2)));