Skip to content
Myr

parser.y

This file

Path

src/parser.y

971 lines · 21.8 KiB

Last changed by

Parse `?//` as `?` and `//` outside destructuring patterns (#3593)A4-Tacksbefore adoptiona19efdd

History of this file

Take it

1%{2#include <assert.h>3#include <math.h>4#include <stdio.h>5#include <string.h>6#include "compile.h"7#include "jv_alloc.h"8#include "builtin.h"9#define YYMALLOC jv_mem_alloc10#define YYFREE jv_mem_free11%}12%code requires {13#include "locfile.h"14struct lexer_param;1516#define YYLTYPE location17#define YYLLOC_DEFAULT(Loc, Rhs, N)             \18  do {                                          \19    if (N) {                                    \20      (Loc).start = YYRHSLOC(Rhs, 1).start;     \21      (Loc).end = YYRHSLOC(Rhs, N).end;         \22    } else {                                    \23      (Loc).start = YYRHSLOC(Rhs, 0).end;       \24      (Loc).end = YYRHSLOC(Rhs, 0).end;         \25    }                                           \26  } while (0)27}2829%locations30%define parse.error verbose31%define api.pure32%union {33  jv literal;34  block blk;35}3637%destructor { jv_free($$); } <literal>38%destructor { block_free($$); } <blk>3940%parse-param {block* answer}41%parse-param {int* errors}42%parse-param {struct locfile* locations}43%parse-param {struct lexer_param* lexer_param_ptr}44%lex-param {block* answer}45%lex-param {int* errors}46%lex-param {struct locfile* locations}47%lex-param {struct lexer_param* lexer_param_ptr}484950%token INVALID_CHARACTER51%token <literal> IDENT52%token <literal> FIELD53%token <literal> BINDING54%token <literal> LITERAL55%token <literal> FORMAT56%token REC ".."57%token SETMOD "%="58%token EQ "=="59%token NEQ "!="60%token DEFINEDOR "//"61%token AS "as"62%token DEF "def"63%token MODULE "module"64%token IMPORT "import"65%token INCLUDE "include"66%token IF "if"67%token THEN "then"68%token ELSE "else"69%token ELSE_IF "elif"70%token REDUCE "reduce"71%token FOREACH "foreach"72%token END "end"73%token AND "and"74%token OR "or"75%token TRY "try"76%token CATCH "catch"77%token LABEL "label"78%token BREAK "break"79%token LOC "$__loc__"80%token SETPIPE "|="81%token SETPLUS "+="82%token SETMINUS "-="83%token SETMULT "*="84%token SETDIV "/="85%token SETDEFINEDOR "//="86%token LESSEQ "<="87%token GREATEREQ ">="8889%token QQSTRING_START90%token <literal> QQSTRING_TEXT91%token QQSTRING_INTERP_START92%token QQSTRING_INTERP_END93%token QQSTRING_END9495/* Instead of raising this, find a way to use precedence to resolve96 * shift-reduce conflicts. */97%expect 09899%precedence FUNCDEF100%right '|'101%left ','102%right "//"103%nonassoc '=' SETPIPE SETPLUS SETMINUS SETMULT SETDIV SETMOD SETDEFINEDOR104%left OR105%left AND106%nonassoc NEQ EQ '<' '>' LESSEQ GREATEREQ107%left '+' '-'108%left '*' '/' '%'109%precedence NONOPT /* non-optional; rules for which a specialized110                      '?' rule should be preferred over Expr '?' */111%precedence '?' '.' '[' FIELD112%precedence "try"113%precedence "catch"114115116%type <blk> Query Expr Term117%type <blk> DictPairs DictPair DictExpr118%type <blk> ElseBody119%type <blk> String QQString120%type <blk> FuncDef FuncDefs121%type <blk> Module Import Imports ImportWhat ImportFrom122%type <blk> Param Params Arg Args123%type <blk> Patterns RepPatterns Pattern ArrayPats ObjPats ObjPat124%type <literal> Keyword125%type <literal> StringStart126%{127#include "lexer.h"128struct lexer_param {129  yyscan_t lexer;130};131#define FAIL(loc, msg)                                             \132  do {                                                             \133    location l = loc;                                              \134    yyerror(&l, answer, errors, locations, lexer_param_ptr, msg);  \135    /*YYERROR*/;                                                   \136  } while (0)137138void yyerror(YYLTYPE* loc, block* answer, int* errors,139             struct locfile* locations, struct lexer_param* lexer_param_ptr, const char *s){140  (*errors)++;141  locfile_locate(locations, *loc, "jq: error: %s", s);142}143144int yylex(YYSTYPE* yylval, YYLTYPE* yylloc, block* answer, int* errors,145          struct locfile* locations, struct lexer_param* lexer_param_ptr) {146  yyscan_t lexer = lexer_param_ptr->lexer;147  int tok = jq_yylex(yylval, yylloc, lexer);148  if ((tok == LITERAL || tok == QQSTRING_TEXT) && !jv_is_valid(yylval->literal)) {149    jv msg = jv_invalid_get_msg(jv_copy(yylval->literal));150    if (jv_get_kind(msg) == JV_KIND_STRING) {151      FAIL(*yylloc, jv_string_value(msg));152    } else {153      FAIL(*yylloc, "Invalid literal");154    }155    jv_free(msg);156    jv_free(yylval->literal);157    yylval->literal = jv_null();158  }159  return tok;160}161162/* Returns string message if the block is a constant that is not valid as an163 * object key. */164static jv check_object_key(block k) {165  if (block_is_const(k) && block_const_kind(k) != JV_KIND_STRING) {166    char errbuf[30];167    return jv_string_fmt("Cannot use %s (%s) as object key",168        jv_kind_name(block_const_kind(k)),169        jv_dump_string_trunc(block_const(k), errbuf, sizeof(errbuf)));170  }171  return jv_invalid();172}173174static block gen_index(block obj, block key) {175  return BLOCK(gen_subexp(key), obj, gen_op_simple(INDEX));176}177178static block gen_index_opt(block obj, block key) {179  return BLOCK(gen_subexp(key), obj, gen_op_simple(INDEX_OPT));180}181182static block gen_slice_index(block obj, block start, block end, opcode idx_op) {183  block key = BLOCK(gen_subexp(gen_const(jv_object())),184                    gen_subexp(gen_const(jv_string("start"))),185                    gen_subexp(start),186                    gen_op_simple(INSERT),187                    gen_subexp(gen_const(jv_string("end"))),188                    gen_subexp(end),189                    gen_op_simple(INSERT));190  return BLOCK(key, obj, gen_op_simple(idx_op));191}192193static block constant_fold(block a, block b, int op) {194  if (!block_is_single(a) || !block_is_const(a) ||195      !block_is_single(b) || !block_is_const(b))196    return gen_noop();197198  jv jv_a = block_const(a);199  block_free(a);200  jv jv_b = block_const(b);201  block_free(b);202203  jv res = jv_invalid();204  switch (op) {205  case '+': res = binop_plus(jv_a, jv_b); break;206  case '-': res = binop_minus(jv_a, jv_b); break;207  case '*': res = binop_multiply(jv_a, jv_b); break;208  case '/': res = binop_divide(jv_a, jv_b); break;209  case '%': res = binop_mod(jv_a, jv_b); break;210  case EQ: res = binop_equal(jv_a, jv_b); break;211  case NEQ: res = binop_notequal(jv_a, jv_b); break;212  case '<': res = binop_less(jv_a, jv_b); break;213  case '>': res = binop_greater(jv_a, jv_b); break;214  case LESSEQ: res = binop_lesseq(jv_a, jv_b); break;215  case GREATEREQ: res = binop_greatereq(jv_a, jv_b); break;216  }217218  if (jv_is_valid(res))219    return gen_const(res);220221  return gen_error(jv_invalid_get_msg(res));222}223224static block gen_binop(block a, block b, int op) {225  block folded = constant_fold(a, b, op);226  if (!block_is_noop(folded))227    return folded;228229  const char* funcname = 0;230  switch (op) {231  case '+': funcname = "_plus"; break;232  case '-': funcname = "_minus"; break;233  case '*': funcname = "_multiply"; break;234  case '/': funcname = "_divide"; break;235  case '%': funcname = "_mod"; break;236  case EQ: funcname = "_equal"; break;237  case NEQ: funcname = "_notequal"; break;238  case '<': funcname = "_less"; break;239  case '>': funcname = "_greater"; break;240  case LESSEQ: funcname = "_lesseq"; break;241  case GREATEREQ: funcname = "_greatereq"; break;242  }243  assert(funcname);244245  return gen_call(funcname, BLOCK(gen_lambda(a), gen_lambda(b)));246}247248static block gen_format(block a, jv fmt) {249  return BLOCK(a, gen_call("format", gen_lambda(gen_const(fmt))));250}251252static block gen_definedor_assign(block object, block val) {253  block tmp = gen_op_var_fresh(STOREV, "tmp");254  return BLOCK(gen_op_simple(DUP),255               val, tmp,256               gen_call("_modify", BLOCK(gen_lambda(object),257                                         gen_lambda(gen_definedor(gen_noop(),258                                                                  gen_op_bound(LOADV, tmp))))));259}260261static block gen_update(block object, block val, int optype) {262  block tmp = gen_op_var_fresh(STOREV, "tmp");263  return BLOCK(gen_op_simple(DUP),264               val,265               tmp,266               gen_call("_modify", BLOCK(gen_lambda(object),267                                         gen_lambda(gen_binop(gen_noop(),268                                                              gen_op_bound(LOADV, tmp),269                                                              optype)))));270}271272static block gen_loc_object(location *loc, struct locfile *locations) {273  return gen_const(JV_OBJECT(jv_string("file"), jv_copy(locations->fname),274                             jv_string("line"), jv_number(locfile_get_line(locations, loc->start) + 1)));275}276277%}278279%%280TopLevel:281Module Imports Query {282  *answer = BLOCK($1, $2, gen_op_simple(TOP), $3);283} |284Module Imports FuncDefs {285  *answer = BLOCK($1, $2, $3);286}287288Module:289%empty {290  $$ = gen_noop();291} |292"module" Query ';' {293  if (!block_is_const($2)) {294    FAIL(@2, "Module metadata must be constant");295    $$ = gen_noop();296    block_free($2);297  } else if (block_const_kind($2) != JV_KIND_OBJECT) {298    FAIL(@2, "Module metadata must be an object");299    $$ = gen_noop();300    block_free($2);301  } else {302    $$ = gen_module($2);303  }304}305306Imports:307%empty {308  $$ = gen_noop();309} |310Import Imports {311  $$ = BLOCK($1, $2);312}313314FuncDefs:315%empty {316  $$ = gen_noop();317} |318FuncDef FuncDefs {319  $$ = block_join($1, $2);320}321322323Query:324FuncDef Query %prec FUNCDEF {325  $$ = block_bind_referenced($1, $2, OP_IS_CALL_PSEUDO);326} |327Expr "as" Patterns '|' Query {328  $$ = gen_destructure($1, $3, $5);329} |330"label" BINDING '|' Query {331  jv v = jv_string_fmt("*label-%s", jv_string_value($2));332  $$ = gen_location(@$, locations, gen_label(jv_string_value(v), $4));333  jv_free($2);334  jv_free(v);335} |336Query '|' Query {337  $$ = block_join($1, $3);338} |339Query ',' Query {340  $$ = gen_both($1, $3);341} |342Expr {343  $$ = $1;344}345346347Expr:348Expr "//" Expr {349  $$ = gen_definedor($1, $3);350} |351Expr '=' Expr {352  $$ = gen_call("_assign", BLOCK(gen_lambda($1), gen_lambda($3)));353} |354Expr "or" Expr {355  $$ = gen_or($1, $3);356} |357Expr "and" Expr {358  $$ = gen_and($1, $3);359} |360Expr "//=" Expr {361  $$ = gen_definedor_assign($1, $3);362} |363Expr "|=" Expr {364  $$ = gen_call("_modify", BLOCK(gen_lambda($1), gen_lambda($3)));365} |366Expr '+' Expr {367  $$ = gen_binop($1, $3, '+');368} |369Expr "+=" Expr {370  $$ = gen_update($1, $3, '+');371} |372Expr '-' Expr {373  $$ = gen_binop($1, $3, '-');374} |375Expr "-=" Expr {376  $$ = gen_update($1, $3, '-');377} |378Expr '*' Expr {379  $$ = gen_binop($1, $3, '*');380} |381Expr "*=" Expr {382  $$ = gen_update($1, $3, '*');383} |384Expr '/' Expr {385  $$ = gen_binop($1, $3, '/');386} |387Expr '%' Expr {388  $$ = gen_binop($1, $3, '%');389} |390Expr "/=" Expr {391  $$ = gen_update($1, $3, '/');392} |393Expr SETMOD Expr {394  $$ = gen_update($1, $3, '%');395} |396Expr "==" Expr {397  $$ = gen_binop($1, $3, EQ);398} |399Expr "!=" Expr {400  $$ = gen_binop($1, $3, NEQ);401} |402Expr '<' Expr {403  $$ = gen_binop($1, $3, '<');404} |405Expr '>' Expr {406  $$ = gen_binop($1, $3, '>');407} |408Expr "<=" Expr {409  $$ = gen_binop($1, $3, LESSEQ);410} |411Expr ">=" Expr {412  $$ = gen_binop($1, $3, GREATEREQ);413} |414Term %prec NONOPT {415  $$ = $1;416}417418419Import:420ImportWhat ';' {421  $$ = $1;422} |423ImportWhat Query ';' {424  if (!block_is_const($2)) {425    FAIL(@2, "Module metadata must be constant");426    $$ = gen_noop();427    block_free($1);428    block_free($2);429  } else if (block_const_kind($2) != JV_KIND_OBJECT) {430    FAIL(@2, "Module metadata must be an object");431    $$ = gen_noop();432    block_free($1);433    block_free($2);434  } else {435    $$ = gen_import_meta($1, $2);436  }437}438439ImportWhat:440"import" ImportFrom "as" BINDING {441  $$ = gen_import(block_const($2), $4, 1);442  block_free($2);443} |444"import" ImportFrom "as" IDENT {445  $$ = gen_import(block_const($2), $4, 0);446  block_free($2);447} |448"include" ImportFrom {449  $$ = gen_import(block_const($2), jv_invalid(), 0);450  block_free($2);451}452453ImportFrom:454String {455  if (!block_is_const($1)) {456    FAIL(@1, "Import path must be constant");457    $$ = gen_const(jv_string(""));458    block_free($1);459  } else {460    $$ = $1;461  }462}463464FuncDef:465"def" IDENT ':' Query ';' {466  $$ = gen_function(jv_string_value($2), gen_noop(), $4);467  jv_free($2);468} |469470"def" IDENT '(' Params ')' ':' Query ';' {471  $$ = gen_function(jv_string_value($2), $4, $7);472  jv_free($2);473}474475Params:476Param {477  $$ = $1;478} |479Params ';' Param {480  $$ = BLOCK($1, $3);481}482483Param:484BINDING {485  $$ = gen_param_regular(jv_string_value($1));486  jv_free($1);487} |488IDENT {489  $$ = gen_param(jv_string_value($1));490  jv_free($1);491}492493494StringStart:495FORMAT QQSTRING_START {496  $$ = $1;497} |498QQSTRING_START {499  $$ = jv_string("text");500}501502503String:504StringStart QQString QQSTRING_END {505  $$ = $2;506  jv_free($1);507};508509510QQString:511%empty {512  $$ = gen_const(jv_string(""));513} |514QQString QQSTRING_TEXT {515  $$ = gen_binop($1, gen_const($2), '+');516} |517QQString QQSTRING_INTERP_START Query QQSTRING_INTERP_END {518  $$ = gen_binop($1, gen_format($3, jv_copy($<literal>0)), '+');519}520521522ElseBody:523"elif" Query "then" Query ElseBody {524  $$ = gen_cond($2, $4, $5);525} |526"else" Query "end" {527  $$ = $2;528} |529"end" {530  $$ = gen_noop();531}532533534Term:535'.' {536  $$ = gen_noop();537} |538REC {539  $$ = gen_call("recurse", gen_noop());540} |541BREAK BINDING {542  jv v = jv_string_fmt("*label-%s", jv_string_value($2));     // impossible symbol543  $$ = gen_location(@$, locations,544                    BLOCK(gen_op_unbound(LOADV, jv_string_value(v)),545                    gen_call("error", gen_noop())));546  jv_free(v);547  jv_free($2);548} |549BREAK error {550  FAIL(@$, "break requires a label to break to");551  $$ = gen_noop();552} |553Term FIELD '?' {554  $$ = gen_index_opt($1, gen_const($2));555} |556FIELD '?' {557  $$ = gen_index_opt(gen_noop(), gen_const($1));558} |559Term '.' String '?' {560  $$ = gen_index_opt($1, $3);561} |562'.' String '?' {563  $$ = gen_index_opt(gen_noop(), $2);564} |565Term FIELD %prec NONOPT {566  $$ = gen_index($1, gen_const($2));567} |568FIELD %prec NONOPT {569  $$ = gen_index(gen_noop(), gen_const($1));570} |571Term '.' String %prec NONOPT {572  $$ = gen_index($1, $3);573} |574'.' String %prec NONOPT {575  $$ = gen_index(gen_noop(), $2);576} |577'.' error {578  FAIL(@$, "try .[\"field\"] instead of .field for unusually named fields");579  $$ = gen_noop();580} |581'.' IDENT error {582  jv_free($2);583  FAIL(@$, "try .[\"field\"] instead of .field for unusually named fields");584  $$ = gen_noop();585} |586/* FIXME: string literals */587Term '[' Query ']' '?' {588  $$ = gen_index_opt($1, $3);589} |590Term '[' Query ']' %prec NONOPT {591  $$ = gen_index($1, $3);592} |593Term '.' '[' Query ']' '?' {594  $$ = gen_index_opt($1, $4);595} |596Term '.' '[' Query ']' %prec NONOPT {597  $$ = gen_index($1, $4);598} |599Term '[' ']' '?' {600  $$ = block_join($1, gen_op_simple(EACH_OPT));601} |602Term '[' ']' %prec NONOPT {603  $$ = block_join($1, gen_op_simple(EACH));604} |605Term '.' '[' ']' '?' {606  $$ = block_join($1, gen_op_simple(EACH_OPT));607} |608Term '.' '[' ']' %prec NONOPT {609  $$ = block_join($1, gen_op_simple(EACH));610} |611Term '[' Query ':' Query ']' '?' {612  $$ = gen_slice_index($1, $3, $5, INDEX_OPT);613} |614Term '[' Query ':' ']' '?' {615  $$ = gen_slice_index($1, $3, gen_const(jv_null()), INDEX_OPT);616} |617Term '[' ':' Query ']' '?' {618  $$ = gen_slice_index($1, gen_const(jv_null()), $4, INDEX_OPT);619} |620Term '[' Query ':' Query ']' %prec NONOPT {621  $$ = gen_slice_index($1, $3, $5, INDEX);622} |623Term '[' Query ':' ']' %prec NONOPT {624  $$ = gen_slice_index($1, $3, gen_const(jv_null()), INDEX);625} |626Term '[' ':' Query ']' %prec NONOPT {627  $$ = gen_slice_index($1, gen_const(jv_null()), $4, INDEX);628} |629Term '?' {630  $$ = gen_try($1, gen_op_simple(BACKTRACK));631} |632LITERAL {633  $$ = gen_const($1);634} |635String {636  $$ = $1;637} |638FORMAT {639  $$ = gen_format(gen_noop(), $1);640} |641'-' Term {642  $$ = BLOCK($2, gen_call("_negate", gen_noop()));643} |644'(' Query ')' {645  $$ = $2;646} |647'[' Query ']' {648  $$ = gen_collect($2);649} |650'[' ']' {651  $$ = gen_const(jv_array());652} |653'{' DictPairs '}' {654  block o = gen_const_object($2);655  if (o.first != NULL)656    $$ = o;657  else658    $$ = BLOCK(gen_subexp(gen_const(jv_object())), $2, gen_op_simple(POP));659} |660"reduce" Expr "as" Patterns '(' Query ';' Query ')' {661  $$ = gen_reduce($2, $4, $6, $8);662} |663"foreach" Expr "as" Patterns '(' Query ';' Query ';' Query ')' {664  $$ = gen_foreach($2, $4, $6, $8, $10);665} |666"foreach" Expr "as" Patterns '(' Query ';' Query ')' {667  $$ = gen_foreach($2, $4, $6, $8, gen_noop());668} |669"if" Query "then" Query ElseBody {670  $$ = gen_cond($2, $4, $5);671} |672"if" Query "then" error {673  FAIL(@$, "Possibly unterminated 'if' statement");674  $$ = $2;675} |676"try" Expr "catch" Expr {677  $$ = gen_try($2, $4);678} |679"try" Expr "catch" error {680  FAIL(@$, "Possibly unterminated 'try' statement");681  $$ = $2;682} |683"try" Expr {684  $$ = gen_try($2, gen_op_simple(BACKTRACK));685} |686/*687 * This `$$$$varname` hack is strictly private to jq builtins.  DO NOT USE!!688 *689 * This is used in `_modify`, in src/builtin.jq, to avoid holding on to a690 * reference to `.`.691 *692 * We could just have the compiler emit bytecode for `_modify` so it can use693 * LOADVN w/o needing jq syntax for LOADVN.694 *695 * This syntax, `$$$$varname`, violates referential transparency: it has696 * side-effects that are surprising.697 *698 * DO NOT USE!!  I will break your jq code if you do use this outside699 * src/builtin.jq.700 */701'$' '$' '$' BINDING {702  $$ = gen_location(@$, locations, gen_op_unbound(LOADVN, jv_string_value($4)));703  jv_free($4);704} |705BINDING {706  $$ = gen_location(@$, locations, gen_op_unbound(LOADV, jv_string_value($1)));707  jv_free($1);708} |709"$__loc__" {710  $$ = gen_loc_object(&@$, locations);711} |712IDENT {713  const char *s = jv_string_value($1);714  if (strcmp(s, "false") == 0)715    $$ = gen_const(jv_false());716  else if (strcmp(s, "true") == 0)717    $$ = gen_const(jv_true());718  else if (strcmp(s, "null") == 0)719    $$ = gen_const(jv_null());720  else721    $$ = gen_location(@$, locations, gen_call(s, gen_noop()));722  jv_free($1);723} |724IDENT '(' Args ')' {725  $$ = gen_call(jv_string_value($1), $3);726  $$ = gen_location(@1, locations, $$);727  jv_free($1);728} |729'(' error ')' { $$ = gen_noop(); } |730'[' error ']' { $$ = gen_noop(); } |731Term '[' error ']' { $$ = $1; } |732'{' error '}' { $$ = gen_noop(); }733734Args:735Arg {736  $$ = $1;737} |738Args ';' Arg {739  $$ = BLOCK($1, $3);740}741742Arg:743Query {744  $$ = gen_lambda($1);745}746747RepPatterns:748RepPatterns '?' "//" Pattern {749  $$ = BLOCK($1, gen_destructure_alt($4));750} |751Pattern {752  $$ = gen_destructure_alt($1);753}754755Patterns:756RepPatterns '?' "//" Pattern {757  $$ = BLOCK($1, $4);758} |759Pattern {760  $$ = $1;761}762763Pattern:764BINDING {765  $$ = gen_op_unbound(STOREV, jv_string_value($1));766  jv_free($1);767} |768'[' ArrayPats ']' {769  $$ = BLOCK($2, gen_op_simple(POP));770} |771'{' ObjPats '}' {772  $$ = BLOCK($2, gen_op_simple(POP));773}774775ArrayPats:776Pattern {777  $$ = gen_array_matcher(gen_noop(), $1);778} |779ArrayPats ',' Pattern {780  $$ = gen_array_matcher($1, $3);781}782783ObjPats:784ObjPat {785  $$ = $1;786} |787ObjPats ',' ObjPat {788  $$ = BLOCK($1, $3);789}790791ObjPat:792BINDING {793  $$ = gen_object_matcher(gen_const($1), gen_op_unbound(STOREV, jv_string_value($1)));794} |795BINDING ':' Pattern {796  $$ = gen_object_matcher(gen_const($1), BLOCK(gen_op_simple(DUP), gen_op_unbound(STOREV, jv_string_value($1)), $3));797} |798IDENT ':' Pattern {799  $$ = gen_object_matcher(gen_const($1), $3);800} |801Keyword ':' Pattern {802  $$ = gen_object_matcher(gen_const($1), $3);803} |804String ':' Pattern {805  $$ = gen_object_matcher($1, $3);806} |807'(' Query ')' ':' Pattern {808  jv msg = check_object_key($2);809  if (jv_is_valid(msg)) {810    FAIL(@2, jv_string_value(msg));811  }812  jv_free(msg);813  $$ = gen_object_matcher($2, $5);814} |815error ':' Pattern {816  FAIL(@$, "May need parentheses around object key expression");817  $$ = $3;818}819820Keyword:821"as" {822  $$ = jv_string("as");823} |824"def" {825  $$ = jv_string("def");826} |827"module" {828  $$ = jv_string("module");829} |830"import" {831  $$ = jv_string("import");832} |833"include" {834  $$ = jv_string("include");835} |836"if" {837  $$ = jv_string("if");838} |839"then" {840  $$ = jv_string("then");841} |842"else" {843  $$ = jv_string("else");844} |845"elif" {846  $$ = jv_string("elif");847} |848"reduce" {849  $$ = jv_string("reduce");850} |851"foreach" {852  $$ = jv_string("foreach");853} |854"end" {855  $$ = jv_string("end");856} |857"and" {858  $$ = jv_string("and");859} |860"or" {861  $$ = jv_string("or");862} |863"try" {864  $$ = jv_string("try");865} |866"catch" {867  $$ = jv_string("catch");868} |869"label" {870  $$ = jv_string("label");871} |872"break" {873  $$ = jv_string("break");874}875876877DictPairs:878%empty {879  $$ = gen_noop();880} |881DictPair {882  $$ = $1;883} |884DictPair ',' DictPairs {885  $$ = block_join($1, $3);886}887888DictPair:889IDENT ':' DictExpr {890  $$ = gen_dictpair(gen_const($1), $3);891} |892Keyword ':' DictExpr {893  $$ = gen_dictpair(gen_const($1), $3);894} |895String ':' DictExpr {896  $$ = gen_dictpair($1, $3);897} |898String {899  $$ = gen_dictpair($1, BLOCK(gen_op_simple(POP), gen_op_simple(DUP2),900                              gen_op_simple(DUP2), gen_op_simple(INDEX)));901} |902BINDING ':' DictExpr {903  $$ = gen_dictpair(gen_location(@$, locations, gen_op_unbound(LOADV, jv_string_value($1))),904                    $3);905  jv_free($1);906} |907BINDING {908  $$ = gen_dictpair(gen_const($1),909                    gen_location(@$, locations, gen_op_unbound(LOADV, jv_string_value($1))));910} |911IDENT {912  $$ = gen_dictpair(gen_const(jv_copy($1)),913                    gen_index(gen_noop(), gen_const($1)));914} |915"$__loc__" {916  $$ = gen_dictpair(gen_const(jv_string("__loc__")),917                    gen_loc_object(&@$, locations));918} |919Keyword {920  $$ = gen_dictpair(gen_const(jv_copy($1)),921                    gen_index(gen_noop(), gen_const($1)));922} |923'(' Query ')' ':' DictExpr {924  jv msg = check_object_key($2);925  if (jv_is_valid(msg)) {926    FAIL(@2, jv_string_value(msg));927  }928  jv_free(msg);929  $$ = gen_dictpair($2, $5);930} |931error ':' DictExpr {932  FAIL(@1, "May need parentheses around object key expression");933  $$ = $3;934}935936DictExpr:937DictExpr '|' DictExpr {938  $$ = block_join($1, $3);939} |940Expr {941  $$ = $1;942}943%%944945int jq_parse(struct locfile* locations, block* answer) {946  struct lexer_param scanner;947  YY_BUFFER_STATE buf;948  jq_yylex_init_extra(0, &scanner.lexer);949  buf = jq_yy_scan_bytes(locations->data, locations->length, scanner.lexer);950  int errors = 0;951  *answer = gen_noop();952  yyparse(answer, &errors, locations, &scanner);953  jq_yy_delete_buffer(buf, scanner.lexer);954  jq_yylex_destroy(scanner.lexer);955  if (errors > 0) {956    block_free(*answer);957    *answer = gen_noop();958  }959  return errors;960}961962int jq_parse_library(struct locfile* locations, block* answer) {963  int errs = jq_parse(locations, answer);964  if (errs) return errs;965  if (block_has_main(*answer)) {966    locfile_locate(locations, UNKNOWN_LOCATION, "jq: error: library should only have function definitions, not a main expression");967    return 1;968  }969  assert(block_has_only_binders_and_imports(*answer, OP_IS_CALL_PSEUDO));970  return 0;971}