/** * @file parser.c * @brief Lexer and recursive-descent parser. * * The parser reads characters from the input stack (input.c) and builds a * tree (ast.h) in an arena. Words are stored as a list of typed parts; * no control bytes are embedded in strings, so the same code is correct * in ASCII and in EBCDIC. */ #include "parser.h" #include "charset.h" #include #include #include /* ---- tokens ---------------------------------------------------------- */ /** * @brief Kinds of token. */ typedef enum tok_kind { T_EOF, T_NL, T_SEMI, T_AMP, T_AND, T_OR, T_PIPE, T_LP, T_RP, T_DSEMI, T_WORD, T_REDIR } tok_kind; /** * @brief Reserved words. */ typedef enum keyword { KW_NONE, KW_IF, KW_THEN, KW_ELSE, KW_ELIF, KW_FI, KW_DO, KW_DONE, KW_CASE, KW_ESAC, KW_WHILE, KW_UNTIL, KW_FOR, KW_IN, KW_LBRACE, KW_RBRACE, KW_BANG, KW_FUNCTION, KW_TIME, KW_DLBRACKET, /**< [[ */ KW_DRBRACKET /**< ]] */ } keyword; /** * @brief The current token. */ typedef struct token { tok_kind t; keyword kw; /**< T_WORD: reserved word this could be */ redir_op op; /**< T_REDIR */ bool strip; /**< T_REDIR: <<- */ bool bare; /**< T_WORD: one unquoted literal (may be an alias) */ bool alias_ok; /**< T_WORD: follows an alias whose value ends blank */ int fd; /**< T_REDIR */ word *word; /**< T_WORD */ } token; /** * @brief A here-document whose body has not been read yet. * * The body starts on the line after the command, so its redirection is * queued when the `<<` is parsed and filled in at the next newline. */ typedef struct heredoc { struct heredoc *next; redir *redir; const char *delim; bool quoted; bool strip; } heredoc; /** * @brief Arena in which the tree being built is allocated. */ static arena *pa; /**< where the tree being built is allocated */ /** * @brief The token most recently read. */ static token tok; /** * @brief `tok` has been peeked at and not yet consumed. */ static bool tok_pushed; /** * @brief Queue of here-documents waiting for their bodies. */ static heredoc *here_head; /** * @brief Where the next pending here-document is linked. */ /** * @brief The lexer is inside `[[ ]]`, where `<` and `>` are comparison * operators, not redirections. */ static bool in_cond; static heredoc **here_tail = &here_head; /** * @brief Set by input_fill() when an alias whose value ends in a blank runs * out: the next word is then subject to alias substitution too. */ bool alias_ended_blank; static node *parse_clist(void); static node *parse_command_node(void); static node *parse_substring(const char *s, size_t len); /** * @brief Forget any half-read token and pending here-documents (after an * error). */ void parser_reset(void) { in_cond = false; tok_pushed = false; here_head = nullptr; here_tail = &here_head; } /** * @brief Report a syntax error at the current line and abort the command. */ [[noreturn]] static void syntax_error(const char *msg) { cur_lineno = input->lineno; parser_reset(); sh_error("syntax error: %s", msg); } /** * @brief Push one character back onto the input. */ static void unget(int c) { if (c != PEOF) input->p--; } /** * @brief Allocate zeroed memory in the parse arena. */ static void *pnew(size_t n) { return memset(arena_alloc(pa, n), 0, n); } /* ---- building words -------------------------------------------------- */ /** * @brief A word under construction: its parts so far and the literal text being * gathered. */ typedef struct pbuild { wpart *head; wpart **tail; strbuf lit; /**< literal text not yet turned into a part */ bool litq; /**< ... and whether it is quoted */ bool force; /**< emit the literal even if empty: '' or "" */ } pbuild; /** * @brief What surrounds the text being read, which decides what ends it and * which characters are special. */ typedef enum lex_mode { M_WORD, /**< a command word: ends at a metacharacter */ M_DQ, /**< inside "...": ends at the closing quote */ M_BRACE, /**< the word in ${x:-word}: ends at } */ M_BRACE_DQ, /**< the same, inside double quotes */ M_ARITH, /**< $(( ... )): ends at )) */ M_HERE /**< here-document body: ends at end of input */ } lex_mode; static void read_parts(pbuild *b, lex_mode mode, bool litq); /** * @brief Start building a word. */ static void pb_init(pbuild *b) { b->head = nullptr; b->tail = &b->head; sb_init(&b->lit, pa); b->litq = false; b->force = false; } /** * @brief Append a finished part to the word. */ static wpart *pb_add(pbuild *b, part_kind kind, bool q) { wpart *p = pnew(sizeof *p); p->kind = kind; p->quoted = q; *b->tail = p; b->tail = &p->next; return p; } /** * @brief Turn the literal text gathered so far into a P_LIT part. */ static void pb_flush(pbuild *b) { if (!b->lit.len && !b->force) return; size_t len = b->lit.len; const char *s = sb_cstr(&b->lit); wpart *p = pb_add(b, P_LIT, b->litq); p->u.lit.s = s; p->u.lit.len = len; sb_init(&b->lit, pa); b->force = false; } /** * @brief Add one literal character, starting a new part when the quoting * changes. */ static void pb_lit(pbuild *b, int c, bool quoted) { if ((b->lit.len || b->force) && b->litq != quoted) pb_flush(b); b->litq = quoted; sb_putc(&b->lit, (char)c); } /** * @brief Record an empty quoted string (`''` or `""`), which still makes a * field. */ static void pb_empty_quoted(pbuild *b) { if (!b->lit.len) { b->litq = true; b->force = true; } } /** * @brief Is `c` a special parameter character (`@ * # ? - $ ! 0`)? */ static bool is_special_param(int c) { return c == '@' || c == '*' || c == '#' || c == '?' || c == '-' || c == '$' || c == '!'; } /** * @brief Can `c` appear in a variable name? */ static bool is_name_char(int c) { return c != PEOF && (isalnum(c) || c == '_'); } /** * @brief Create a parameter record for a name. * * The kind of parameter (variable, positional, special) is worked out * here, once, not at every expansion. */ static param *new_param(const char *name, size_t nlen) { param *pm = pnew(sizeof *pm); pm->name = name; pm->nlen = nlen; pm->op = PS_NORMAL; if (isdigit((unsigned char)name[0])) { pm->type = PT_POS; pm->pos = atoi(name); } else if (is_special_param((unsigned char)name[0])) { pm->type = PT_SPECIAL; pm->special = name[0]; } else { pm->type = PT_VAR; } return pm; } /** * @brief Read the name that follows `$` when it is not in braces. * @return The parameter, or nullptr if `$` is not followed by a name (it * is then an ordinary character). */ static param *read_param_name(int c, bool braced) { strbuf sb; sb_init(&sb, pa); sb_putc(&sb, (char)c); if (isalpha(c) || c == '_') { while (is_name_char(c = pgetc())) sb_putc(&sb, (char)c); unget(c); } else if (braced && isdigit(c)) { while ((c = pgetc()) != PEOF && isdigit(c)) sb_putc(&sb, (char)c); unget(c); } size_t len = sb.len; return new_param(sb_cstr(&sb), len); } /** * @brief Parse `${...}`: the name, an optional operator and its word. * @param b Word being built. * @param q The expansion is quoted. * @param dq It is inside double quotes or a here-document. */ static void parse_braced_param(pbuild *b, bool q, bool dq) { bool length = false; int c = pgetc(); if (c == '#') { int c2 = pgetc(); if (c2 == '}') { /* ${#} */ pb_add(b, P_PARAM, q)->u.param = new_param("#", 1); return; } if (is_name_char(c2) || (is_special_param(c2) && c2 != '-')) { length = true; c = c2; } else { unget(c2); } } if (c == PEOF || !(is_name_char(c) || is_special_param(c))) syntax_error("bad substitution"); param *pm = read_param_name(c, true); c = pgetc(); if (length) { if (c != '}') syntax_error("bad substitution"); pm->op = PS_LENGTH; pb_add(b, P_PARAM, q)->u.param = pm; return; } if (c == '}') { pb_add(b, P_PARAM, q)->u.param = pm; return; } if (c == ':') { pm->colon = true; c = pgetc(); } bool trim = false; switch (c) { case '-': pm->op = PS_MINUS; break; case '=': pm->op = PS_EQUAL; break; case '?': pm->op = PS_QUESTION; break; case '+': pm->op = PS_PLUS; break; case '#': case '%': { if (pm->colon) syntax_error("bad substitution"); int c2 = pgetc(); bool twice = c2 == c; if (!twice) unget(c2); if (c == '#') pm->op = twice ? PS_TRIMLL : PS_TRIML; else pm->op = twice ? PS_TRIMRR : PS_TRIMR; trim = true; break; } default: syntax_error("bad substitution"); } /* * Inside double quotes the word of - = ? + is itself quoted, but a * trim pattern is not: "${x#*.}" still treats * as a wildcard. */ pbuild ab; pb_init(&ab); read_parts(&ab, dq ? M_BRACE_DQ : M_BRACE, trim ? false : q); pb_flush(&ab); pm->arg = ab.head; pb_add(b, P_PARAM, q)->u.param = pm; } /** * @brief Parse `$( ... )` by running the real parser on its contents. * * Recursing into the parser (and not scanning for the closing * parenthesis) is what makes `$(case x in x) ;; esac)` work. * @return The command, or nullptr if the substitution is empty. */ static node *parse_cmdsub(void) { token saved = tok; bool saved_pushed = tok_pushed; tok_pushed = false; node *n = parse_clist(); if (tok.t != T_RP || !tok_pushed) syntax_error("missing ')'"); tok = saved; tok_pushed = saved_pushed; return n; } /** * @brief Parse a backquoted command substitution. * * The text is collected up to the closing backquote with its backslash * escapes removed, then parsed as a string. */ static void parse_backquote(pbuild *b, bool q, bool dq) { strbuf sb; sb_init(&sb, pa); for (;;) { int c = pgetc(); if (c == PEOF) syntax_error("unterminated backquote"); if (c == '`') break; if (c == '\n') input->lineno++; if (c == '\\') { int c2 = pgetc(); if (c2 == PEOF) syntax_error("unterminated backquote"); if (c2 != '$' && c2 != '`' && c2 != '\\' && !(dq && c2 == '"')) sb_putc(&sb, '\\'); c = c2; } sb_putc(&sb, (char)c); } size_t len = sb.len; pb_add(b, P_CMDSUB, q)->u.cmd = parse_substring(sb_cstr(&sb), len); } /** * @brief Read one hexadecimal or octal digit run for a `$'...'` escape. * * @param base 8 or 16. * @param maxlen Most digits to consume. * @return The value read (0 when there were no digits). */ static int read_escape_digits(int base, int maxlen) { int v = 0; for (int i = 0; i < maxlen; i++) { int c = pgetc(); int d; if (c >= '0' && c <= '7') d = c - '0'; else if (base == 16 && (c == '8' || c == '9')) d = c - '0'; else if (base == 16 && c >= 'a' && c <= 'f') d = 10 + (c - 'a'); else if (base == 16 && c >= 'A' && c <= 'F') d = 10 + (c - 'A'); else { unget(c); break; } v = v * base + d; } return v; } /** * @brief Read the body of `$'...'` (the opening quote has been consumed). * * The text is a quoted literal in which backslash escapes are decoded at * parse time: * * @verbatim * \a \b \e \f \n \r \t \v the usual control characters * \\ \' \" the character itself * \nnn a byte, in octal (1 to 3 digits) * \xHH a byte, in hexadecimal * \cX control-X (ASCII builds only) * @endverbatim * * Numeric escapes name raw bytes of the build's character set. A NUL * produced by an escape ends the string's contribution, as in FreeBSD * sh. A backslash before any other character is kept. * * @param b Word being built. */ static void read_ansi_quoted(pbuild *b) { size_t len0 = b->lit.len; wpart **tail0 = b->tail; bool dead = false; /* an escape produced NUL: drop the rest */ for (;;) { int c = pgetc(); if (c == PEOF) syntax_error("unterminated quoted string"); if (c == '\'') break; if (c == '\n') input->lineno++; if (c == '\\') { c = pgetc(); switch (c) { case PEOF: syntax_error("unterminated quoted string"); case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 'e': c = CH_ESC; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; case 'x': c = read_escape_digits(16, 2) & 0xff; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': unget(c); c = read_escape_digits(8, 3) & 0xff; break; #if ZASH_ASCII case 'c': c = pgetc(); if (c == PEOF) syntax_error("unterminated quoted string"); c = c == '?' ? CH_DEL : c & 0x1f; break; #endif case '\n': input->lineno++; break; case '\\': case '\'': case '"': break; default: /* not an escape: the backslash stays */ unget(c); c = '\\'; break; } if (c == 0) dead = true; } if (!dead) pb_lit(b, c, true); } if (b->lit.len == len0 && b->tail == tail0) pb_empty_quoted(b); } /** * @brief Parse whatever follows a `$`: `$'...'`, `$(...)`, `$((...))`, * `${...}`, `$name`, or a lone dollar sign. */ static void parse_dollar(pbuild *b, bool q, bool dq) { int c = pgetc(); if (c == '\'' && !dq) { read_ansi_quoted(b); return; } if (c == '(') { pb_flush(b); int c2 = pgetc(); if (c2 == '(') { pbuild ab; pb_init(&ab); read_parts(&ab, M_ARITH, true); pb_flush(&ab); pb_add(b, P_ARITH, q)->u.arith = ab.head; } else { unget(c2); pb_add(b, P_CMDSUB, q)->u.cmd = parse_cmdsub(); } } else if (c == '{') { pb_flush(b); parse_braced_param(b, q, dq); } else if (c != PEOF && (is_name_char(c) || is_special_param(c))) { pb_flush(b); pb_add(b, P_PARAM, q)->u.param = read_param_name(c, false); } else { unget(c); pb_lit(b, '$', q); } } /** * @brief Does `c` end an unquoted word? */ static bool is_meta(int c) { switch (c) { case ' ': case '\t': case '\n': case ';': case '&': case '|': case '<': case '>': case '(': case ')': return true; default: return false; } } /** * @brief Read a single-quoted string up to the closing quote. */ static void read_single_quoted(pbuild *b) { size_t len0 = b->lit.len; wpart **tail0 = b->tail; int c; while ((c = pgetc()) != '\'') { if (c == PEOF) syntax_error("unterminated quoted string"); if (c == '\n') input->lineno++; pb_lit(b, c, true); } if (b->lit.len == len0 && b->tail == tail0) pb_empty_quoted(b); } /** * @brief Read a double-quoted string up to the closing quote. */ static void read_double_quoted(pbuild *b) { size_t len0 = b->lit.len; wpart **tail0 = b->tail; read_parts(b, M_DQ, true); if (b->lit.len == len0 && b->tail == tail0) pb_empty_quoted(b); } /** * @brief Read text into word parts until the construct `mode` describes ends. * * This one function serves words, double-quoted strings, the word of * `${x-word}`, arithmetic, and here-document bodies. `mode` says which * characters are special and what terminates. * * @param b Word being built. * @param mode The surrounding construct. * @param litq Whether literal text read here counts as quoted. */ static void read_parts(pbuild *b, lex_mode mode, bool litq) { /* Contexts that follow double-quote rules for backslash and quotes. */ bool dq = mode != M_WORD && mode != M_BRACE; /* A trim pattern inside double quotes: quotes still quote. */ bool pattern = mode == M_BRACE_DQ && !litq; int depth = 0; if (stack_low()) syntax_error("expansions nested too deeply"); for (;;) { int c = pgetc(); switch (c) { case PEOF: if (mode == M_WORD || mode == M_HERE) return; syntax_error(mode == M_DQ ? "unterminated quoted string" : "unterminated substitution"); case '\\': { int c2 = pgetc(); if (c2 == '\n') { input->lineno++; continue; } if (c2 == PEOF) { pb_lit(b, '\\', litq); } else if (!dq || c2 == '$' || c2 == '`' || c2 == '\\' || (c2 == '"' && mode != M_HERE) || (c2 == '}' && mode == M_BRACE_DQ)) { pb_lit(b, c2, true); } else { pb_lit(b, '\\', litq); pb_lit(b, c2, litq); } continue; } case '\'': if (dq && !pattern) break; read_single_quoted(b); continue; case '"': if (mode == M_DQ) return; if (mode == M_HERE || mode == M_ARITH) break; if (mode == M_BRACE_DQ && !pattern) continue; /* "${x:-"y"}": the inner quotes are redundant */ read_double_quoted(b); continue; case '$': parse_dollar(b, litq, dq); continue; case '`': pb_flush(b); parse_backquote(b, litq, dq); continue; case '}': if (mode == M_BRACE || mode == M_BRACE_DQ) return; break; case '(': if (mode == M_ARITH) depth++; break; case ')': if (mode == M_ARITH) { if (depth == 0) { if (pgetc() != ')') syntax_error("missing '))'"); return; } depth--; } break; case '\n': if (mode != M_WORD) input->lineno++; break; default: break; } if (mode == M_WORD && is_meta(c)) { unget(c); return; } pb_lit(b, c, litq); } } /* ---- tokens ---------------------------------------------------------- */ /** * @brief Is this word a reserved word? */ static keyword keyword_lookup(const char *s) { static const struct { const char *name; keyword kw; } table[] = { {"if", KW_IF}, {"then", KW_THEN}, {"else", KW_ELSE}, {"elif", KW_ELIF}, {"fi", KW_FI}, {"do", KW_DO}, {"done", KW_DONE}, {"case", KW_CASE}, {"esac", KW_ESAC}, {"while", KW_WHILE}, {"until", KW_UNTIL}, {"for", KW_FOR}, {"in", KW_IN}, {"{", KW_LBRACE}, {"}", KW_RBRACE}, {"!", KW_BANG}, {"function", KW_FUNCTION}, {"time", KW_TIME}, {"[[", KW_DLBRACKET}, {"]]", KW_DRBRACKET}, }; for (size_t i = 0; i < ARRAY_LEN(table); i++) { if (s[0] == table[i].name[0] && !strcmp(s, table[i].name)) return table[i].kw; } return KW_NONE; } /** * @brief Read a redirection operator. `c` is its first character. */ static void read_redir_op(int c, int fd) { tok.t = T_REDIR; tok.strip = false; int c2 = pgetc(); if (c == '<') { tok.fd = fd < 0 ? 0 : fd; if (c2 == '<') { tok.op = R_HERE; int c3 = pgetc(); if (c3 == '-') tok.strip = true; else unget(c3); } else if (c2 == '&') { tok.op = R_DUPIN; } else if (c2 == '>') { tok.op = R_RDWR; } else { tok.op = R_IN; unget(c2); } } else { tok.fd = fd < 0 ? 1 : fd; if (c2 == '>') { tok.op = R_APPEND; } else if (c2 == '&') { tok.op = R_DUPOUT; } else if (c2 == '|') { tok.op = R_CLOBBER; } else { tok.op = R_OUT; unget(c2); } } } /** * @brief Read a word token starting with `c`. * * Works out the facts the evaluator's fast paths rely on: whether the * word is a single literal (`plain`), whether it looks like an * assignment, and whether it is a reserved word. */ static void read_word(int escaped) { pbuild b; pb_init(&b); if (escaped != PEOF) pb_lit(&b, escaped, true); read_parts(&b, M_WORD, false); pb_flush(&b); wpart *p = b.head; bool single_lit = p && !p->next && p->kind == P_LIT; /* A lone digit directly before < or > is a file descriptor number. */ if (!in_cond && single_lit && !p->quoted && p->u.lit.len == 1 && isdigit((unsigned char)p->u.lit.s[0])) { int c = pgetc(); if (c == '<' || c == '>') { char digit[2] = {p->u.lit.s[0], '\0'}; read_redir_op(c, atoi(digit)); return; } unget(c); } word *w = pnew(sizeof *w); w->parts = p; tok.t = T_WORD; tok.word = w; tok.kw = KW_NONE; tok.bare = single_lit && !p->quoted; if (single_lit) { const char *s = p->u.lit.s; if (p->quoted) { w->plain = s; } else { tok.kw = keyword_lookup(s); /* "[" alone is not a pattern: keep the test command cheap. */ const char *open = strchr(s, '['); if (s[0] != '~' && !strpbrk(s, "*?") && !(open && strchr(open, ']'))) w->plain = s; } } if (p && p->kind == P_LIT && !p->quoted) { size_t n = name_len(p->u.lit.s); if (n && p->u.lit.s[n] == '=') w->assign_len = n; } } static void read_heredocs(void); /** * @brief Read the next token from the input into #tok. */ static void lex_token(void) { int c; tok.bare = false; for (;;) { c = pgetc(); if (c == ' ' || c == '\t') continue; if (c == '\\') { int c2 = pgetc(); if (c2 == '\n') { input->lineno++; continue; } if (c2 == PEOF) { unget(c2); c2 = '\\'; } read_word(c2); return; } break; } if (c == '#') { while ((c = pgetc()) != '\n' && c != PEOF) ; } tok.word = nullptr; tok.kw = KW_NONE; switch (c) { case PEOF: tok.t = T_EOF; return; case '\n': input->lineno++; tok.t = T_NL; if (here_head) read_heredocs(); return; case ';': if ((c = pgetc()) == ';') { tok.t = T_DSEMI; } else { unget(c); tok.t = T_SEMI; } return; case '&': if ((c = pgetc()) == '&') { tok.t = T_AND; } else { unget(c); tok.t = T_AMP; } return; case '|': if ((c = pgetc()) == '|') { tok.t = T_OR; } else { unget(c); tok.t = T_PIPE; } return; case '(': tok.t = T_LP; return; case ')': tok.t = T_RP; return; case '<': case '>': if (in_cond) { /* a comparison: an operator word */ static const char lt[] = "<"; static const char gt[] = ">"; wpart *p = pnew(sizeof *p); p->kind = P_LIT; p->u.lit.s = c == '<' ? lt : gt; p->u.lit.len = 1; word *w = pnew(sizeof *w); w->parts = p; w->plain = p->u.lit.s; tok.t = T_WORD; tok.word = w; tok.bare = true; return; } read_redir_op(c, -1); return; default: unget(c); read_word(PEOF); return; } } /** * @brief Advance to the next token, or re-deliver one that was pushed back. * * Also records whether the token directly follows the text of an alias * whose value ends in a blank, in which case POSIX says the token is * itself subject to alias substitution. */ static void next_token(void) { if (tok_pushed) { tok_pushed = false; return; } alias_ended_blank = false; lex_token(); tok.alias_ok = alias_ended_blank; } /** * @brief Substitute an alias for the word token that was just peeked. * * The alias text is pushed as an input source, so the caller simply reads * the next token again. An alias is not expanded inside its own text, * which is what stops `alias ls='ls -F'` from recursing. The whole * function is skipped while no aliases are defined. * * @return true if the token was replaced and must be read again. */ static bool alias_expand(void) { if (!alias_count || !tok.bare) return false; alias *a = alias_find(tok.word->parts->u.lit.s); if (!a || a->in_use) return false; tok_pushed = false; input_push_alias(a); return true; } /** * @brief Look at the next token without consuming it. */ static tok_kind peek(void) { next_token(); tok_pushed = true; return tok.t; } /** * @brief Consume the token that was peeked. */ static void consume(void) { tok_pushed = false; } /** * @brief Is the next token the reserved word `k`? */ static bool peek_kw(keyword kw) { return peek() == T_WORD && tok.kw == kw; } /** * @brief Consume the next token if it is the reserved word `k`. */ static bool accept_kw(keyword kw) { if (!peek_kw(kw)) return false; consume(); return true; } /** * @brief Describe the current token for an error message. */ static const char *token_text(void) { switch (tok.t) { case T_EOF: return "end of file"; case T_NL: return "newline"; case T_SEMI: return ";"; case T_AMP: return "&"; case T_AND: return "&&"; case T_OR: return "||"; case T_PIPE: return "|"; case T_LP: return "("; case T_RP: return ")"; case T_DSEMI: return ";;"; case T_REDIR: return "redirection"; case T_WORD: return tok.word->plain ? tok.word->plain : "word"; } return "?"; } /** * @brief Report the current token as a syntax error. */ [[noreturn]] static void unexpected(void) { strbuf sb; sb_init(&sb, &scratch); sb_puts(&sb, "unexpected '"); sb_puts(&sb, token_text()); sb_puts(&sb, "'"); syntax_error(sb_cstr(&sb)); } /** * @brief Require the reserved word `k` next. */ static void expect_kw(keyword kw) { if (!accept_kw(kw)) unexpected(); } /** * @brief Skip newline tokens, reading pending here-document bodies as they * pass. */ static void skip_newlines(void) { while (peek() == T_NL) consume(); } /* ---- here-documents -------------------------------------------------- */ /** * @brief Read the body of one here-document up to its delimiter line. */ static void read_heredoc_body(heredoc *h) { strbuf sb; sb_init(&sb, pa); size_t dlen = strlen(h->delim); for (;;) { size_t start = sb.len; int c = pgetc(); while (h->strip && c == '\t') c = pgetc(); while (c != '\n' && c != PEOF) { sb_putc(&sb, (char)c); c = pgetc(); } if (c == '\n') input->lineno++; if (sb.len - start == dlen && (!dlen || !memcmp(sb.s + start, h->delim, dlen))) { sb.len = start; break; } if (c == PEOF) break; /* unterminated: take what there is */ sb_putc(&sb, '\n'); } size_t len = sb.len; const char *body = sb_cstr(&sb); pbuild b; pb_init(&b); if (h->quoted) { wpart *p = pb_add(&b, P_LIT, true); p->u.lit.s = body; p->u.lit.len = len; } else { input_push_string(body, len); read_parts(&b, M_HERE, true); pb_flush(&b); input_pop(); } word *w = pnew(sizeof *w); w->parts = b.head; h->redir->target = w; } /** * @brief Read the bodies of all pending here-documents. */ static void read_heredocs(void) { heredoc *h = here_head; here_head = nullptr; here_tail = &here_head; for (; h; h = h->next) read_heredoc_body(h); } /** * @brief Queue a here-document whose body follows the current line. */ static void add_heredoc(redir *r, const word *delim, bool strip) { heredoc *h = pnew(sizeof *h); strbuf sb; sb_init(&sb, pa); for (const wpart *p = delim->parts; p; p = p->next) { if (p->kind != P_LIT) syntax_error("bad here-document delimiter"); if (p->quoted) h->quoted = true; sb_put(&sb, p->u.lit.s, p->u.lit.len); } h->delim = sb_cstr(&sb); h->redir = r; h->strip = strip; *here_tail = h; here_tail = &h->next; } /* ---- grammar --------------------------------------------------------- */ /** * @brief Allocate a tree node of the given kind, stamped with the current line. */ static node *new_node(node_kind kind) { node *n = pnew(sizeof *n); n->kind = kind; n->lineno = input->lineno; return n; } /** * @brief Parse one redirection. The operator token is current. */ static redir *parse_redir(void) { redir *r = pnew(sizeof *r); r->fd = tok.fd; r->op = tok.op; bool strip = tok.strip; consume(); next_token(); if (tok.t != T_WORD) unexpected(); r->target = tok.word; if (r->op == R_HERE) add_heredoc(r, tok.word, strip); return r; } /** * @brief Parse any redirections that follow a compound command. */ static void parse_redirs(node *n) { redir **tail = &n->redirs; while (*tail) tail = &(*tail)->next; while (peek() == T_REDIR) { *tail = parse_redir(); tail = &(*tail)->next; } } /** * @brief Can the token just peeked begin a command? * * This is the command-name position, so it is also where alias * substitution happens. */ static bool command_start(void) { /* This is the command-name position: the one place aliases apply. */ while (tok.t == T_WORD && tok.kw == KW_NONE && alias_expand()) peek(); switch (tok.t) { case T_LP: case T_REDIR: return true; case T_WORD: switch (tok.kw) { case KW_THEN: case KW_ELSE: case KW_ELIF: case KW_FI: case KW_DO: case KW_DONE: case KW_ESAC: case KW_RBRACE: return false; default: return true; } default: return false; } } /** * @brief Parse a simple command: assignments, words and redirections in any * order. `name()` here turns it into a function definition. */ static node *parse_simple(void) { node *n = new_node(N_SIMPLE); word **atail = &n->u.simple.assigns; word **wtail = &n->u.simple.args; redir **rtail = &n->redirs; for (;;) { tok_kind t = peek(); if (t == T_REDIR) { *rtail = parse_redir(); rtail = &(*rtail)->next; } else if (t == T_WORD) { word *w = tok.word; /* After "x=1" the command name is still to come, and a word * after a blank-ended alias is checked too ("sudo ll"). */ bool name_pos = !n->u.simple.args && n->u.simple.assigns && !w->assign_len; if ((name_pos || tok.alias_ok) && alias_expand()) continue; consume(); if (!n->u.simple.args && w->assign_len) { *atail = w; atail = &w->next; continue; } bool first = !n->u.simple.args; *wtail = w; wtail = &w->next; if (first && !n->u.simple.assigns && !n->redirs && peek() == T_LP) { /* name() compound-command */ if (!w->plain || !is_name(w->plain)) syntax_error("bad function name"); consume(); next_token(); if (tok.t != T_RP) unexpected(); skip_newlines(); node *f = new_node(N_FUNC); f->u.func.name = w->plain; f->u.func.arena = pa; if (!command_start()) unexpected(); f->u.func.body = parse_command_node(); return f; } } else { return n; } } } /** * @brief Parse `if ... then ... [elif ...] [else ...] fi`. */ static node *parse_if(void) { node *n = new_node(N_IF); n->u.if_.cond = parse_clist(); expect_kw(KW_THEN); n->u.if_.then_part = parse_clist(); if (accept_kw(KW_ELIF)) { n->u.if_.else_part = parse_if(); /* consumes the shared "fi" */ return n; } if (accept_kw(KW_ELSE)) n->u.if_.else_part = parse_clist(); expect_kw(KW_FI); return n; } /** * @brief Parse a `while` or `until` loop. */ static node *parse_loop(node_kind kind) { node *n = new_node(kind); n->u.loop.cond = parse_clist(); expect_kw(KW_DO); n->u.loop.body = parse_clist(); expect_kw(KW_DONE); return n; } /** * @brief Parse `for name [in words]; do ... done`. */ static node *parse_for(void) { node *n = new_node(N_FOR); next_token(); if (tok.t != T_WORD || !tok.word->plain || !is_name(tok.word->plain)) syntax_error("bad for loop variable"); n->u.for_.var = tok.word->plain; if (peek() == T_SEMI) consume(); skip_newlines(); if (accept_kw(KW_IN)) { n->u.for_.has_in = true; word **tail = &n->u.for_.words; while (peek() == T_WORD) { *tail = tok.word; tail = &tok.word->next; consume(); } if (tok.t != T_SEMI && tok.t != T_NL) unexpected(); consume(); skip_newlines(); } expect_kw(KW_DO); n->u.for_.body = parse_clist(); expect_kw(KW_DONE); return n; } /** * @brief Parse `case word in pattern) list ;; ... esac`. */ static node *parse_case(void) { node *n = new_node(N_CASE); next_token(); if (tok.t != T_WORD) unexpected(); n->u.case_.subject = tok.word; skip_newlines(); expect_kw(KW_IN); caseitem **itail = &n->u.case_.items; for (;;) { skip_newlines(); if (accept_kw(KW_ESAC)) break; if (peek() == T_LP) consume(); caseitem *item = pnew(sizeof *item); word **ptail = &item->patterns; for (;;) { next_token(); if (tok.t != T_WORD) unexpected(); *ptail = tok.word; ptail = &tok.word->next; if (peek() != T_PIPE) break; consume(); } if (tok.t != T_RP) unexpected(); consume(); item->body = parse_clist(); *itail = item; itail = &item->next; if (peek() == T_DSEMI) { consume(); } else if (!peek_kw(KW_ESAC)) { unexpected(); } } return n; } /* ---- [[ expression ]] ------------------------------------------------ */ /** * @brief The text of the current token if it is one unquoted literal. * * Inside `[[ ]]` only an unquoted word can be an operator: `[[ "-f" ]]` * tests the string `-f`. * * @return The text, or nullptr. */ static const char *cond_bare(void) { return tok.t == T_WORD && tok.bare ? tok.word->parts->u.lit.s : nullptr; } /** * @brief Is the current token the closing `]]`? */ static bool cond_at_end(void) { return tok.t == T_WORD && tok.kw == KW_DRBRACKET; } /** * @brief Is `s` a unary operator of `[[ ]]`? * * The file and string tests of `test`, plus `-a file` (exists), * `-o option` (shell option is on) and `-v name` (variable is set). * * @return The operator's letter, or 0. */ static char cond_unary_op(const char *s) { if (!s || s[0] != '-' || !s[1] || s[2]) return 0; return strchr("abcdefghknoprstuvwxzGLOS", s[1]) ? s[1] : 0; } /** * @brief Is `s` a binary operator of `[[ ]]`? * @param s Candidate text, or nullptr. * @param op Receives the operator. */ static bool cond_binary_op(const char *s, cond_op *op) { static const struct { const char *name; cond_op op; } ops[] = { {"=", CO_MATCH}, {"==", CO_MATCH}, {"!=", CO_NOMATCH}, {"=~", CO_REGEX}, {"<", CO_LESS}, {">", CO_GREATER}, {"-eq", CO_EQ}, {"-ne", CO_NE}, {"-lt", CO_LT}, {"-le", CO_LE}, {"-gt", CO_GT}, {"-ge", CO_GE}, {"-nt", CO_NEWER}, {"-ot", CO_OLDER}, {"-ef", CO_SAMEFILE}, }; if (!s) return false; for (size_t i = 0; i < ARRAY_LEN(ops); i++) { if (!strcmp(s, ops[i].name)) { *op = ops[i].op; return true; } } return false; } /** * @brief Allocate a `[[ ]]` expression node. */ static cond *cond_new(cond_kind kind) { cond *c = pnew(sizeof *c); c->kind = kind; return c; } /** * @brief Take the current token as an operand word. * * `]]`, `&&`, `||` and parentheses cannot be operands. */ static word *cond_operand(void) { peek(); if (tok.t != T_WORD || cond_at_end()) unexpected(); word *w = tok.word; consume(); return w; } static cond *parse_cond_or(void); /** * @brief Parse a primary: `( expr )`, a unary test, a binary test, or a * lone word. */ static cond *parse_cond_primary(void) { if (stack_low()) syntax_error("expression nested too deeply"); peek(); if (tok.t == T_LP) { consume(); cond *c = parse_cond_or(); if (peek() != T_RP) unexpected(); consume(); return c; } if (tok.t != T_WORD || cond_at_end()) unexpected(); char uop = cond_unary_op(cond_bare()); if (uop) { word *opw = tok.word; consume(); peek(); /* "-f" alone, or followed by an operator, is a string. */ cond_op dummy; if (tok.t == T_WORD && !cond_at_end() && !cond_binary_op(cond_bare(), &dummy)) { cond *c = cond_new(CN_UNARY); c->uop = uop; c->a = cond_operand(); return c; } tok_pushed = true; /* the token after it is still current */ if (tok.t == T_WORD && !cond_at_end()) { /* "-f == x": the operator word is the left operand. */ cond_binary_op(cond_bare(), &dummy); consume(); cond *c = cond_new(CN_BINARY); c->op = dummy; c->a = opw; c->b = cond_operand(); return c; } cond *c = cond_new(CN_STRING); c->a = opw; return c; } word *a = tok.word; consume(); peek(); cond_op op; if (cond_binary_op(cond_bare(), &op)) { consume(); cond *c = cond_new(CN_BINARY); c->op = op; c->a = a; c->b = cond_operand(); return c; } cond *c = cond_new(CN_STRING); c->a = a; return c; } /** * @brief Parse `! expr`. */ static cond *parse_cond_not(void) { peek(); if (tok.t == T_WORD && tok.kw == KW_BANG && tok.bare) { consume(); cond *c = cond_new(CN_NOT); c->left = parse_cond_not(); return c; } return parse_cond_primary(); } /** * @brief Parse `expr && expr`. */ static cond *parse_cond_and(void) { cond *left = parse_cond_not(); while (peek() == T_AND) { consume(); skip_newlines(); cond *c = cond_new(CN_AND); c->left = left; c->right = parse_cond_not(); left = c; } return left; } /** * @brief Parse `expr || expr`. */ static cond *parse_cond_or(void) { cond *left = parse_cond_and(); while (peek() == T_OR) { consume(); skip_newlines(); cond *c = cond_new(CN_OR); c->left = left; c->right = parse_cond_and(); left = c; } return left; } /** * @brief Parse `[[ expression ]]` (the Korn shell conditional command); * the `[[` has been peeked. * * Inside the brackets the usual command syntax is suspended: `&&`, `||`, * `!` and parentheses build the expression, `<` and `>` compare strings, * and words are neither split nor globbed. Precedence, highest first: * `!`, `&&`, `||`. * * Patterns and regular expressions are read as ordinary words, so a * regular expression that contains `(`, `)` or `|` must be quoted or * come from a variable: `re='^(a|b)$'; [[ $x =~ $re ]]`. * * @return An N_COND node. */ static node *parse_cond_command(void) { consume(); node *n = new_node(N_COND); bool saved = in_cond; in_cond = true; skip_newlines(); peek(); if (cond_at_end()) syntax_error("empty [[ ]]"); n->u.cond = parse_cond_or(); skip_newlines(); peek(); in_cond = saved; if (!cond_at_end()) unexpected(); consume(); return n; } /** * @brief Parse `function name { ...; }` (the Korn shell spelling). * * `function name() compound-command` is accepted as well. The result is * the same N_FUNC node that `name() compound-command` produces. * * @return The function-definition node. */ static node *parse_function_kw(void) { next_token(); if (tok.t != T_WORD || !tok.word->plain || !is_name(tok.word->plain)) syntax_error("bad function name"); node *f = new_node(N_FUNC); f->u.func.name = tok.word->plain; f->u.func.arena = pa; if (peek() == T_LP) { consume(); next_token(); if (tok.t != T_RP) unexpected(); } skip_newlines(); if (!command_start()) unexpected(); f->u.func.body = parse_command_node(); return f; } /** * @brief Give back text read while testing for `(( ))`, as a subshell. * @param sb What was read after the "((". * @param last The character read after that, or PEOF. * @return nullptr, for the caller to return. */ static node *arith_fallback(strbuf *sb, int last) { strbuf back; sb_init(&back, pa); sb_putc(&back, '('); sb_put(&back, sb->s, sb->len); if (last != PEOF) sb_putc(&back, (char)last); size_t len = back.len; input_push_back(sb_cstr(&back), len); return nullptr; } /** * @brief Try to parse an arithmetic command, `(( expression ))`. * * Called when "((" has just been read at the start of a command. That * spelling is ambiguous: `((a) | b)` and `((echo x))` are legal nested * subshells in POSIX `sh`. The text is read up to the parenthesis that * balances the first "(", and is taken as arithmetic only if * * - that parenthesis is immediately followed by ")", and * - the text could be an expression: it has no `;`, and no two words * separated only by blanks (`echo x`), which no expression contains. * * Otherwise everything read is pushed back as input, with the second "(" * restored, and the caller parses a subshell. POSIX advises writing * `( (` for nested subshells, which is never taken as arithmetic. * * The scan gives up early (as "not arithmetic") on a long run of opening * parentheses or a very long body, so that deeply nested subshells do not * get rescanned at every level. * * @return An N_ARITH node, or nullptr if this is not arithmetic. */ static node *parse_arith_command(void) { const size_t max_body = 4096; const int max_open_run = 8; strbuf sb; sb_init(&sb, pa); int depth = 2; int lines = 0; int open_run = 0; /* "(" seen with nothing else before them */ bool only_open = true; /* nothing but "(" so far */ bool after_word = false; /* the last non-blank ended a word */ bool gap = false; /* blanks since then */ char quote = 0; for (;;) { int c = pgetc(); if (c == PEOF) syntax_error("missing '))'"); if (quote) { sb_putc(&sb, (char)c); if (c == '\n') lines++; if (c == quote) quote = 0; continue; } bool word_char = is_name_char(c) || c == '$' || c == '"' || c == '\''; if (c == ';' || (word_char && after_word && gap) || sb.len > max_body || (only_open && open_run > max_open_run)) return arith_fallback(&sb, c); sb_putc(&sb, (char)c); if (c == '(' && only_open) open_run++; else only_open = false; if (c == ' ' || c == '\t' || c == '\n') { gap = true; } else { after_word = is_name_char(c) || c == '}'; gap = false; } if (c == '\n') lines++; if (c == '\\') { c = pgetc(); if (c != PEOF) sb_putc(&sb, (char)c); } else if (c == '\'' || c == '"') { quote = (char)c; after_word = true; } else if (c == '(') { depth++; } else if (c == ')' && --depth == 1) { c = pgetc(); if (c == ')') break; return arith_fallback(&sb, c); } } /* sb holds "expression)": hand read_parts the usual "))" ending. */ sb_putc(&sb, ')'); size_t len = sb.len; node *n = new_node(N_ARITH); pbuild ab; pb_init(&ab); input_push_string(sb_cstr(&sb), len); read_parts(&ab, M_ARITH, true); pb_flush(&ab); input_pop(); input->lineno += lines; wpart *p = pnew(sizeof *p); p->kind = P_ARITH; p->quoted = true; p->u.arith = ab.head; n->u.arith = p; return n; } /** * @brief Parse one command: simple, compound, or a function definition. */ static node *parse_command_node(void) { node *n; if (stack_low()) syntax_error("commands nested too deeply"); peek(); if (tok.t == T_LP) { consume(); int c = pgetc(); if (c == '(' && (n = parse_arith_command()) != nullptr) { parse_redirs(n); return n; } if (c != '(') unget(c); n = new_node(N_SUBSHELL); n->u.body = parse_clist(); if (peek() != T_RP) unexpected(); consume(); } else if (tok.t == T_WORD && tok.kw != KW_NONE && tok.kw != KW_IN) { keyword kw = tok.kw; consume(); switch (kw) { case KW_IF: n = parse_if(); break; case KW_WHILE: n = parse_loop(N_WHILE); break; case KW_UNTIL: n = parse_loop(N_UNTIL); break; case KW_FOR: n = parse_for(); break; case KW_CASE: n = parse_case(); break; case KW_FUNCTION: return parse_function_kw(); case KW_DLBRACKET: n = parse_cond_command(); break; case KW_LBRACE: n = new_node(N_GROUP); n->u.body = parse_clist(); expect_kw(KW_RBRACE); break; default: tok_pushed = true; unexpected(); } } else { return parse_simple(); } parse_redirs(n); return n; } /** * @brief Parse `[!] command [| command]...`. */ static node *parse_pipeline(void) { bool negate = false; while (accept_kw(KW_BANG)) negate = !negate; if (accept_kw(KW_TIME)) { /* * `time [-p] pipeline`: a keyword, as in ksh, so that it times * builtins, functions and whole pipelines without a process. */ node *t = new_node(N_TIME); if (peek() == T_WORD && tok.kw == KW_NONE && tok.bare && tok.word->plain && !strcmp(tok.word->plain, "-p")) { consume(); t->u.time.posix = true; peek(); } if (command_start() || peek_kw(KW_BANG)) t->u.time.body = parse_pipeline(); if (negate) { node *not = new_node(N_NOT); not->u.body = t; t = not; } return t; } if (!command_start()) unexpected(); node *n = parse_command_node(); if (peek() == T_PIPE) { struct item { struct item *next; node *n; } *head = pnew(sizeof *head), **tail = &head->next; head->n = n; int count = 1; while (peek() == T_PIPE) { consume(); skip_newlines(); if (!command_start()) unexpected(); struct item *it = pnew(sizeof *it); it->n = parse_command_node(); *tail = it; tail = &it->next; count++; } n = new_node(N_PIPE); n->u.pipe.n = count; n->u.pipe.cmds = pnew((size_t)count * sizeof(node *)); int i = 0; for (struct item *it = head; it; it = it->next) n->u.pipe.cmds[i++] = it->n; } if (negate) { node *not = new_node(N_NOT); not->u.body = n; n = not; } return n; } /** * @brief Parse pipelines joined by `&&` and `||`. */ static node *parse_and_or(void) { node *n = parse_pipeline(); for (;;) { tok_kind t = peek(); if (t != T_AND && t != T_OR) return n; consume(); skip_newlines(); node *b = new_node(t == T_AND ? N_AND : N_OR); b->u.bin.left = n; b->u.bin.right = parse_pipeline(); n = b; } } /** * @brief Append a command to a sequence. * * The list is built right-leaning so that the evaluator can walk a long * script in a loop rather than recursing. */ static void seq_append(node ***slot, node *n) { if (!**slot) { **slot = n; return; } node *s = new_node(N_SEQ); s->u.bin.left = **slot; s->u.bin.right = n; **slot = s; *slot = &s->u.bin.right; } /** * @brief Parse one and-or list and its terminator (`;`, `&` or newline). */ static node *parse_list_item(tok_kind *term) { node *n = parse_and_or(); tok_kind t = peek(); if (t == T_AMP) { node *bg = new_node(N_BG); bg->u.body = n; n = bg; consume(); } else if (t == T_SEMI) { consume(); } *term = t; return n; } /** * @brief Parse a compound list: the body of a loop, group, `if` branch and so * on. */ static node *parse_clist(void) { node *head = nullptr; node **slot = &head; skip_newlines(); while (command_start() || peek_kw(KW_BANG)) { tok_kind term; seq_append(&slot, parse_list_item(&term)); if (term != T_AMP && term != T_SEMI && term != T_NL) break; skip_newlines(); } return head; } /** * @brief Parse one complete command line. * * @param a Arena for the tree. * @param eof Set when the input has ended. * @return The command, or nullptr for an empty line. */ node *parse_command(arena *a, bool *eof) { pa = a; node *head = nullptr; node **slot = &head; for (;;) { tok_kind t = peek(); if (t == T_WORD) { /* an alias may expand to nothing at all */ command_start(); t = tok.t; } if (t == T_EOF) { consume(); *eof = true; break; } if (t == T_NL) { consume(); break; } if (!command_start()) unexpected(); tok_kind term; seq_append(&slot, parse_list_item(&term)); if (term != T_AMP && term != T_SEMI && term != T_NL && term != T_EOF) unexpected(); } return head; } /** * @brief Parse a string as a complete script (backquotes, `eval` of a * constant). */ static node *parse_substring(const char *s, size_t len) { token saved = tok; bool saved_pushed = tok_pushed; tok_pushed = false; input_push_string(s, len); node *n = parse_clist(); if (peek() != T_EOF) unexpected(); input_pop(); tok = saved; tok_pushed = saved_pushed; return n; } /** * @brief Parse a string the way a here-document body is parsed. * * Parameter expansions, command substitutions and arithmetic are * recognised. Quotes are ordinary characters. This is how PS1, PS2 and * PS4 are prepared for expansion. The parser's own state is saved and * restored, so this is safe to call while a command is being parsed (the * PS2 prompt is printed from inside the lexer). * * @param a Arena for the parts. * @param s Text to parse. * @param len Length of `s`. * @return The parts, ready for expand_string(). */ wpart *parse_text_parts(arena *a, const char *s, size_t len) { arena *saved_pa = pa; pbuild b; pa = a; pb_init(&b); input_push_string(s, len); read_parts(&b, M_HERE, true); pb_flush(&b); input_pop(); pa = saved_pa; return b.head; } /** * @brief Snapshot of the parser's static state. * * Taken around anything that might run the parser re-entrantly while a * command is half parsed (expanding a prompt that contains `$(...)`). */ typedef struct parser_state { arena *pa; token tok; bool tok_pushed; heredoc *here_head; heredoc **here_tail; } parser_state; static_assert(sizeof(parser_state) <= PARSER_STATE_SIZE, "PARSER_STATE_SIZE in parser.h is too small"); /** * @brief Save the parser's state and reset it. * @param state A buffer of PARSER_STATE_SIZE bytes, suitably aligned. */ void parser_save(void *state) { parser_state *ps = state; *ps = (parser_state){pa, tok, tok_pushed, here_head, here_tail}; if (here_tail == &here_head) ps->here_tail = nullptr; parser_reset(); } /** * @brief Put back the state saved by parser_save(). */ void parser_restore(const void *state) { const parser_state *ps = state; pa = ps->pa; tok = ps->tok; tok_pushed = ps->tok_pushed; here_head = ps->here_head; here_tail = ps->here_tail ? ps->here_tail : &here_head; }