Add alternation destructuring operator `?//`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This is a first pass to show the implementation. It needs tests and evaluation, but doesn't break any existing tests. NOT READY FOR MERGING
authored by William Langford · committed by Nicolas Williams · parent b142d48 · Browse files · 7 files·+206 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+206 added−27 removed
- other:+206 added−27 removed
Provenance
- Commit
3a8c8f4- Tree
a9a6270- Author
William Langford <wlangfor@gmail.com>- Committer
Nicolas Williams <nico@cryptonector.com>- Parent
b142d48
7 files changed+206 added−27 removed
modified:src/compile.c+146 added-17 removed
157 unmodified lines158 i->symbol = strdup(name);159 return inst_block(i);160 }161 162+block gen_op_pushk_under(jv constant) {163+ assert(opcode_describe(PUSHK_UNDER)->flags & OP_HAS_CONSTANT);164+ inst* i = inst_new(PUSHK_UNDER);165+ i->imm.constant = constant;166+ return inst_block(i);167+}168+169 int block_is_const(block b) {163- return (block_is_single(b) && b.first->op == LOADK);170+ return (block_is_single(b) && (b.first->op == LOADK || b.first->op == PUSHK_UNDER));171 }172 173 int block_is_const_inf(block b) {174 return (block_is_single(b) && b.first->op == LOADK &&51 unmodified lines226 b.first->bound_by = binder.first;227 return b;228 }229 230+block gen_dictpair(block k, block v) {231+ return BLOCK(gen_subexp(k), gen_subexp(v), gen_op_simple(INSERT));232+}233 234+235 static void inst_join(inst* a, inst* b) {236 assert(a && b);237 assert(!a->next);238 assert(!b->prev);334 unmodified lines573 b.first->arglist = args;574 return b;575 }576 566-567-577 block gen_subexp(block a) {578+ if (block_is_noop(a)) {579+ return gen_op_simple(DUP);580+ }581+ if (block_is_single(a) && a.first->op == LOADK) {582+ jv c = block_const(a);583+ block_free(a);584+ return gen_op_pushk_under(c);585+ }586 return BLOCK(gen_op_simple(SUBEXP_BEGIN), a, gen_op_simple(SUBEXP_END));587 }588 589 block gen_both(block a, block b) {9 unmodified lines599 jv o = jv_object();600 jv k = jv_null();601 jv v = jv_null();602 for (inst *i = expr.first; i; i = i->next) {586- if (i->op != SUBEXP_BEGIN ||603+ if (i->op == PUSHK_UNDER) {604+ k = jv_copy(i->imm.constant);605+ i = i->next;606+ } else if (i->op != SUBEXP_BEGIN ||607 i->next == NULL ||608 i->next->op != LOADK ||609 i->next->next == NULL ||610 i->next->next->op != SUBEXP_END) {611 is_const = 0;612 break;613+ } else {614+ k = jv_copy(i->next->imm.constant);615+ i = i->next->next->next;616 }617+ if (i != NULL && i->op == PUSHK_UNDER) {594- k = jv_copy(i->next->imm.constant);595- i = i->next->next->next;596- if (i == NULL ||618+ v = jv_copy(i->imm.constant);619+ i = i->next;620+ } else if (i == NULL ||621 i->op != SUBEXP_BEGIN ||622 i->next == NULL ||623 i->next->op != LOADK ||624 i->next->next == NULL ||625 i->next->next->op != SUBEXP_END) {626 is_const = 0;627 break;628+ } else {629+ v = jv_copy(i->next->imm.constant);630+ i = i->next->next->next;631 }605- v = jv_copy(i->next->imm.constant);606- i = i->next->next->next;632 if (i == NULL || i->op != INSERT) {633 is_const = 0;634 break;635 }97 unmodified lines733 // cannot call block_bind(matcher, body) because that requires734 // block_has_only_binders(matcher), which is not true here as matchers735 // may also contain code to extract the correct elements736 for (inst* i = matcher.first; i; i = i->next) {712- if (i->op == STOREV && !i->bound_by)737+ if ((i->op == STOREV || i->op == STOREVN) && !i->bound_by)738 block_bind_subblock(inst_block(i), body, OP_HAS_VARIABLE, 0);739 }740 return BLOCK(matcher, body);741 }742 743+744+// Extract destructuring var names from the block745+// *vars should be a jv_object (for set semantics)746+static void block_get_unbound_vars(block b, jv *vars) {747+ assert(vars != NULL);748+ assert(jv_get_kind(*vars) == JV_KIND_OBJECT);749+ for (inst* i = b.first; i; i = i->next) {750+ if (i->subfn.first) {751+ block_get_unbound_vars(i->subfn, vars);752+ continue;753+ }754+ if ((i->op == STOREV || i->op == STOREVN) && i->bound_by == NULL) {755+ *vars = jv_object_set(*vars, jv_string(i->symbol), jv_true());756+ }757+ }758+}759+760+/* Build wrappers around destructuring matchers so that we can chain them761+ * when we have errors. The approach is as follows:762+ * FORK_OPT NEXT_MATCHER (unless last matcher)763+ * existing_matcher_block764+ * JUMP BODY765+ */766+static block bind_alternation_matchers(block matchers, block body) {767+ block preamble = {0};768+ block altmatchers = {0};769+ block mb = {0};770+771+ // Pass through the matchers to find all destructured names.772+ while (matchers.first && matchers.first->op == DESTRUCTURE_ALT) {773+ block_append(&altmatchers, inst_block(block_take(&matchers)));774+ }775+776+ // We don't have any alternations here, so we can use the simplest case.777+ if (altmatchers.first == NULL) {778+ return bind_matcher(matchers, body);779+ }780+781+ // The final matcher needs to strip the error from the previous FORK_OPT782+ block final_matcher = BLOCK(gen_op_simple(POP), gen_op_simple(DUP), matchers);783+784+ // Collect var names785+ jv all_vars = jv_object();786+ block_get_unbound_vars(altmatchers, &all_vars);787+ block_get_unbound_vars(final_matcher, &all_vars);788+789+ // We need a preamble of STOREVs to which to bind the matchers and the body.790+ jv_object_keys_foreach(all_vars, key) {791+ preamble = BLOCK(preamble,792+ gen_op_simple(DUP),793+ gen_const(jv_null()),794+ gen_op_unbound(STOREV, jv_string_value(key)));795+ jv_free(key);796+ }797+ jv_free(all_vars);798+799+ // Now we build each matcher in turn800+ for (inst *i = altmatchers.first; i; i = i->next) {801+ block submatcher = i->subfn;802+803+ // Get rid of the error from the previous matcher804+ if (mb.first != NULL) {805+ submatcher = BLOCK(gen_op_simple(POP), gen_op_simple(DUP), submatcher);806+ }807+808+ // If we're successful, jump to the end of the matchers809+ submatcher = BLOCK(submatcher, gen_op_target(JUMP, final_matcher));810+811+ // FORK_OPT to the end of this submatcher so we can skip to the next one on error812+ mb = BLOCK(mb, gen_op_target(FORK_OPT, submatcher), submatcher);813+814+ // We're done with this inst and we don't want it anymore815+ // But we can't let it free the submatcher block.816+ i->subfn.first = i->subfn.last = NULL;817+ }818+ // We're done with these insts now.819+ block_free(altmatchers);820+821+ return bind_matcher(preamble, BLOCK(mb, final_matcher, body));822+}823+824 block gen_reduce(block source, block matcher, block init, block body) {825 block res_var = gen_op_var_fresh(STOREV, "reduce");826 block update_var = gen_op_bound(STOREV, res_var);827 block jmp = gen_op_target(JUMP, body);828 block loop = BLOCK(gen_op_simple(DUPN),829 source,724- bind_matcher(matcher,830+ bind_alternation_matchers(matcher,831 BLOCK(gen_op_bound(LOADVN, res_var),832 /*833 * We fork to the body, jump to834 * the STOREV. This means that25 unmodified lines860 // get a value from the source expression:861 source,862 // destructure the value into variable(s) for all the code863 // in the body to see758- bind_matcher(matcher,864+ bind_alternation_matchers(matcher,865 // load the loop state variable866 BLOCK(gen_op_bound(LOADVN, state_var),867 // generate updated state868 update,97 unmodified lines966 gen_condbranch(gen_const(jv_true()),967 gen_const(jv_false())))));968 }969 970+block gen_destructure_alt(block matcher) {971+ for (inst *i = matcher.first; i; i = i->next) {972+ if (i->op == STOREV) {973+ i->op = STOREVN;974+ }975+ }976+ inst* i = inst_new(DESTRUCTURE_ALT);977+ i->subfn = matcher;978+ return inst_block(i);979+}980+981 block gen_var_binding(block var, const char* name, block body) {982 return gen_destructure(var, gen_op_unbound(STOREV, name), body);983 }984 4 unmodified lines989 else {990 // `left` was returned by this function, so the third inst is the991 // constant containing the previously used index992 assert(left.first->op == DUP);876- assert(left.first->next->op == SUBEXP_BEGIN);877- assert(left.first->next->next->op == LOADK);878- index = 1 + (int) jv_number_value(left.first->next->next->imm.constant);993+ assert(left.first->next != NULL);994+ inst *i = NULL;995+ if (left.first->next->op == PUSHK_UNDER) {996+ i = left.first->next;997+ } else {998+ assert(left.first->next->op == SUBEXP_BEGIN);999+ assert(left.first->next->next->op == LOADK);1000+ i = left.first->next->next;1001+ }1002+ index = 1 + (int) jv_number_value(i->imm.constant);1003 }1004 1005 // `left` goes at the end so that the const index is in a predictable place1006 return BLOCK(gen_op_simple(DUP), gen_subexp(gen_const(jv_number(index))),4 unmodified lines1011 return BLOCK(gen_op_simple(DUP), gen_subexp(name), gen_op_simple(INDEX),1012 curr);1013 }1014 891-block gen_destructure(block var, block matcher, block body) {1015+block gen_destructure(block var, block matchers, block body) {1016 // var bindings can be added after coding the program; leave the TOP first.1017 block top = gen_noop();1018 if (body.first && body.first->op == TOP)1019 top = inst_block(block_take(&body));1020 1021+ if (matchers.first && matchers.first->op == DESTRUCTURE_ALT && !block_is_noop(var)) {1022+ block_append(&var, gen_op_simple(DUP));1023+ block_append(&matchers, gen_op_simple(POP));1024+ }1025+897- return BLOCK(top, gen_op_simple(DUP), gen_subexp(var), gen_op_simple(POP), bind_matcher(matcher, body));1026+ return BLOCK(top, gen_op_simple(DUP), gen_subexp(var), gen_op_simple(POP), bind_alternation_matchers(matchers, body));1027 }1028 1029 // Like gen_var_binding(), but bind `break`'s wildcard unbound variable1030 static block gen_wildvar_binding(block var, const char* name, block body) {377 unmodified linesmodified:src/compile.h+3 added
27 unmodified lines28 block gen_op_target(opcode op, block target);29 block gen_op_unbound(opcode op, const char* name);30 block gen_op_bound(opcode op, block binder);31 block gen_op_var_fresh(opcode op, const char* name);32+block gen_op_pushk_under(jv constant);33 34 block gen_module(block metadata);35 jv block_module_meta(block b);36 block gen_import(const char* name, const char *as, int is_data);12 unmodified lines49 block gen_definedor(block a, block b);50 block gen_condbranch(block iftrue, block iffalse);51 block gen_and(block a, block b);52 block gen_or(block a, block b);53+block gen_dictpair(block k, block v);54 55 block gen_var_binding(block var, const char* name, block body);56 block gen_array_matcher(block left, block curr);57 block gen_object_matcher(block name, block curr);58 block gen_destructure(block var, block matcher, block body);59+block gen_destructure_alt(block matcher);60 61 block gen_cond(block cond, block iftrue, block iffalse);62 block gen_try_handler(block handler);63 block gen_try(block exp, block handler);43 unmodified linesmodified:src/execute.c+21 added
449 unmodified lines450 stack_push(jq, b);451 break;452 }453 454+ case PUSHK_UNDER: {455+ jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);456+ assert(jv_is_valid(v));457+ jv v2 = stack_pop(jq);458+ stack_push(jq, v);459+ stack_push(jq, v2);460+ break;461+ }462+463 case POP: {464 jv_free(stack_pop(jq));465 break;466 }89 unmodified lines556 *var = jv_null();557 break;558 }559 560+ case STOREVN:561+ stack_save(jq, pc - 1, stack_get_pos(jq));562 case STOREV: {563 uint16_t level = *pc++;564 uint16_t v = *pc++;565 jv* var = frame_local_var(jq, v, level);7 unmodified lines573 *var = val;574 break;575 }576 577+ case ON_BACKTRACK(STOREVN): {578+ uint16_t level = *pc++;579+ uint16_t v = *pc++;580+ jv* var = frame_local_var(jq, v, level);581+ jv_free(*var);582+ *var = jv_null();583+ goto do_backtrack;584+ break;585+ }586+587 case STORE_GLOBAL: {588 // Get the constant589 jv val = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);590 assert(jv_is_valid(val));659 unmodified linesmodified:src/jv.h+9 added
143 unmodified lines144 1) \145 : 0; \146 jv_i__ = jv_object_iter_next(t, jv_i__)) \147 148+#define jv_object_keys_foreach(t, k) \149+ for (int jv_i__ = jv_object_iter(t), jv_j__ = 1; jv_j__; jv_j__ = 0) \150+ for (jv k; \151+ jv_object_iter_valid((t), jv_i__) ? \152+ (k = jv_object_iter_key(t, jv_i__), \153+ 1) \154+ : 0; \155+ jv_i__ = jv_object_iter_next(t, jv_i__))156+157 #define JV_OBJECT_1(k1) (jv_object_set(jv_object(),(k1),jv_null()))158 #define JV_OBJECT_2(k1,v1) (jv_object_set(jv_object(),(k1),(v1)))159 #define JV_OBJECT_3(k1,v1,k2) (jv_object_set(JV_OBJECT_2((k1),(v1)),(k2),jv_null()))160 #define JV_OBJECT_4(k1,v1,k2,v2) (jv_object_set(JV_OBJECT_2((k1),(v1)),(k2),(v2)))115 unmodified linesmodified:src/lexer.l+1 added
69 unmodified lines70 "//=" { return SETDEFINEDOR; }71 "<=" { return LESSEQ; }72 ">=" { return GREATEREQ; }73 ".." { return REC; }74+"?//" { return ALTERNATION; }75 "."|"?"|"="|";"|","|":"|"|"|"+"|"-"|"*"|"/"|"%"|"\$"|"<"|">" { return yytext[0];}76 77 "["|"{"|"(" {78 return enter(yytext[0], YY_START, yyscanner);107 unmodified linesmodified:src/opcode_list.h+4 added
1 OP(LOADK, CONSTANT, 1, 1)2 OP(DUP, NONE, 1, 2)3 OP(DUPN, NONE, 1, 2)4 OP(DUP2, NONE, 2, 3)5+OP(PUSHK_UNDER, CONSTANT, 1, 2)6 OP(POP, NONE, 1, 0)7 OP(LOADV, VARIABLE, 1, 1)8 OP(LOADVN, VARIABLE, 1, 1)9 OP(STOREV, VARIABLE, 1, 0)32 unmodified lines42 OP(CLOSURE_PARAM_REGULAR, DEFINITION, 0, 0)43 OP(DEPS, CONSTANT, 0, 0)44 OP(MODULEMETA, CONSTANT, 0, 0)45 OP(GENLABEL, NONE, 0, 1)46+47+OP(DESTRUCTURE_ALT, NONE, 0, 0)48+OP(STOREVN, VARIABLE, 1, 0)modified:src/parser.y+22 added-10 removed
81 unmodified lines82 %token SETDIV "/="83 %token SETDEFINEDOR "//="84 %token LESSEQ "<="85 %token GREATEREQ ">="86+%token ALTERNATION "?//"87 88 %token QQSTRING_START89 %token <literal> QQSTRING_TEXT90 %token QQSTRING_INTERP_START27 unmodified lines118 %type <blk> String QQString119 %type <blk> FuncDef FuncDefs120 %type <blk> Module Import Imports ImportWhat ImportFrom121 %type <blk> Param Params Arg Args121-%type <blk> Pattern ArrayPats ObjPats ObjPat122+%type <blk> Patterns RepPatterns Pattern ArrayPats ObjPats ObjPat123 %type <literal> Keyword124 %{125 #include "lexer.h"126 struct lexer_param {49 unmodified lines176 }177 return jv_invalid();178 }179 179-static block gen_dictpair(block k, block v) {180- return BLOCK(gen_subexp(k), gen_subexp(v), gen_op_simple(INSERT));181-}182-180 static block gen_index(block obj, block key) {181 return BLOCK(gen_subexp(key), obj, gen_op_simple(INDEX));182 }183 154 unmodified lines338 FuncDef Exp %prec FUNCDEF {339 $$ = block_bind_referenced($1, $2, OP_IS_CALL_PSEUDO);340 } |341 345-Term "as" Pattern '|' Exp {342+Term "as" Patterns '|' Exp {343 $$ = gen_destructure($1, $3, $5);344 } |348-349-"reduce" Term "as" Pattern '(' Exp ';' Exp ')' {345+"reduce" Term "as" Patterns '(' Exp ';' Exp ')' {346 $$ = gen_reduce($2, $4, $6, $8);347 } |348 353-"foreach" Term "as" Pattern '(' Exp ';' Exp ';' Exp ')' {349+"foreach" Term "as" Patterns '(' Exp ';' Exp ';' Exp ')' {350 $$ = gen_foreach($2, $4, $6, $8, $10);351 } |352 357-"foreach" Term "as" Pattern '(' Exp ';' Exp ')' {353+"foreach" Term "as" Patterns '(' Exp ';' Exp ')' {354 $$ = gen_foreach($2, $4, $6, $8, gen_noop());355 } |356 357 "if" Exp "then" Exp ElseBody {415 unmodified lines773 Exp {774 $$ = gen_lambda($1);775 }776 777+RepPatterns:778+RepPatterns "?//" Pattern {779+ $$ = BLOCK($1, gen_destructure_alt($3));780+} |781+Pattern {782+ $$ = gen_destructure_alt($1);783+}784+785+Patterns:786+RepPatterns "?//" Pattern {787+ $$ = BLOCK($1, $3);788+} |789+Pattern {790+ $$ = $1;791+}792+793 Pattern:794 '$' IDENT {795 $$ = gen_op_unbound(STOREV, jv_string_value($2));796 jv_free($2);180 unmodified lines