/** * Shell parser. * * Consumes the token stream produced by tokenizer.ts and emits a * CommandList (AST) that the executor can walk. Handles: * - pipelines (|) * - and-or lists (&&, ||) * - sequences (;, newline) * - compound: for, while, until, if, case, subshell (…), group {…} * - redirections (including fd numbers and heredocs) * * Also collects heredoc bodies: after the tokenizer finishes, any `<out ls`). while (this.peekIsRedirStart()) { cmd.redirections.push(this.parseRedirection()); } // Inline variable assignments before the command name. while (this.peekIsAssignment() && cmd.words.length === 0) { const tok = this.advance(); const eq = tok.value.indexOf('='); const name = tok.value.slice(0, eq); const valueText = tok.value.slice(eq + 1); // Build a Word from the post-= part of the token's segments. cmd.assignments.push({ name, value: segmentsAfterChar(tok, eq + 1, valueText) }); } // Command name + arguments, interleaved with redirections. while (!this.atEnd()) { const startPos = this.pos; if (this.peekIsRedirStart()) { cmd.redirections.push(this.parseRedirection()); continue; } const t = this.peek(); if (t.type !== 'WORD') break; // A bare reserved word is only a terminator if we're currently // parsing inside a compound body that's expecting it. Otherwise // it's just an argument (e.g. `echo done` at top level). if (this.isActiveTerminator(t.value)) break; // `;;` is a case-item separator, handled as an OPERATOR. `}` is // an operator too. These don't reach here as WORDs. cmd.words.push(this.consumeWord()); // Safety: if we failed to advance, bail rather than hang. if (this.pos === startPos) { throw new ParseError(`unexpected token: ${this.peek().value}`, this.peek().offset); } } if (cmd.words.length === 0 && cmd.redirections.length === 0 && cmd.assignments.length === 0) { // Didn't parse anything — make sure the caller sees progress or an // explicit error rather than looping. throw new ParseError(`expected command, got "${this.peek().value}"`, this.peek().offset); } return cmd; } private peekIsRedirStart(): boolean { const t = this.peek(); if (t.type === 'IO_NUMBER') return true; if (t.type === 'OPERATOR' && ['<', '>', '>>', '<<', '<<-', '>&', '<&', '&>', '&>>'].includes(t.value)) return true; return false; } private peekIsAssignment(): boolean { const t = this.peek(); if (t.type !== 'WORD' || !t.segments || t.segments.length === 0) return false; const first = t.segments[0]; if (first.type !== 'literal') return false; const m = first.value.match(/^([A-Za-z_][A-Za-z0-9_]*)=/); return !!m; } private parseRedirection(): Redirection { let fd: number | undefined; const first = this.peek(); if (first.type === 'IO_NUMBER') { fd = parseInt(first.value, 10); this.advance(); } const op = this.expect('OPERATOR', 'redirection operator'); const opStr = op.value as RedirOp | string; // Map the operator string into our RedirOp set. let realOp: RedirOp; switch (opStr) { case '>': realOp = fd === 2 ? '2>' : '>'; break; case '>>': realOp = fd === 2 ? '2>>' : '>>'; break; case '<': realOp = '<'; break; case '<<': case '<<-': realOp = '<<'; break; case '>&': realOp = '>&'; break; case '<&': realOp = '<&'; break; case '&>': realOp = '&>'; break; case '&>>': realOp = '&>'; break; // treat like &> (rare) default: throw new ParseError(`unexpected redirection operator: ${opStr}`, op.offset); } // For >&/<& the target may be a number (fd dup). if (realOp === '>&' || realOp === '<&') { const t = this.expect('WORD', 'target for fd duplication'); if (/^[0-9]+$/.test(t.value)) { return { op: realOp, fd: fd ?? (realOp === '>&' ? 1 : 0), target: { fd: parseInt(t.value, 10) } }; } // Could also be a filename (e.g. bash's >&file). Treat as file. return { op: realOp === '>&' ? '>' : '<', fd: fd ?? (realOp === '>&' ? 1 : 0), target: tokenToWord(t) }; } // Heredoc: gather body by scanning the source for the delimiter line. if (realOp === '<<') { const tagTok = this.expect('WORD', 'heredoc delimiter'); const { tag, expand } = parseHeredocTag(tagTok); const body = this.readHeredocBody(tag, opStr === '<<-'); return { op: '<<', fd: fd ?? 0, target: tokenToWord(tagTok), heredocBody: body, heredocExpand: expand }; } const target = this.expect('WORD', 'redirection target'); return { op: realOp, fd, target: tokenToWord(target) }; } /** * Heredoc body reader: finds the line matching the delimiter AFTER the * current position in the input, extracts everything between, and * advances the tokenizer's effective "where we are". Since heredocs * are rare in the shell-tool use case, we implement a minimal version * that works for single-line command input (no heredoc) and multi-line * input (the body begins on the next newline). */ private readHeredocBody(tag: string, stripTabs: boolean): string { // Find the next NEWLINE token after the current position; the body // starts after its offset + 1 and ends at the first line equal to `tag`. let nlIdx = this.pos; while (nlIdx < this.tokens.length && this.tokens[nlIdx].type !== 'NEWLINE' && this.tokens[nlIdx].type !== 'EOF') { nlIdx++; } if (nlIdx >= this.tokens.length || this.tokens[nlIdx].type === 'EOF') { // No newline — no heredoc body available. Return empty. return ''; } const bodyStart = this.tokens[nlIdx].offset + 1; // Scan the source for the delimiter line. let i = bodyStart; const lines: string[] = []; while (i < this.source.length) { const nl = this.source.indexOf('\n', i); const line = nl === -1 ? this.source.slice(i) : this.source.slice(i, nl); const trimmed = stripTabs ? line.replace(/^\t+/, '') : line; if (trimmed === tag) { // Advance parser past all tokens up to and including this line. const endOffset = nl === -1 ? this.source.length : nl + 1; while (this.pos < this.tokens.length && this.tokens[this.pos].offset < endOffset) { this.pos++; } return lines.map((l) => (stripTabs ? l.replace(/^\t+/, '') : l) + '\n').join(''); } lines.push(line); if (nl === -1) break; i = nl + 1; } // Delimiter not found — consume to EOF and return whatever we have. while (this.pos < this.tokens.length && this.tokens[this.pos].type !== 'EOF') this.pos++; return lines.map((l) => (stripTabs ? l.replace(/^\t+/, '') : l) + '\n').join(''); } /** Parse trailing redirections after a compound command. */ private parseRedirections(): Redirection[] { const out: Redirection[] = []; while (this.peekIsRedirStart()) { out.push(this.parseRedirection()); } return out; } // ----------------------------------------------------------------- // Token utility methods // ----------------------------------------------------------------- private peek(): Token { return this.tokens[this.pos]; } private advance(): Token { return this.tokens[this.pos++]; } private atEnd(): boolean { return this.peek().type === 'EOF'; } private skipNewlines(): void { while (this.peek().type === 'NEWLINE') this.advance(); } private isOp(value: string): boolean { const t = this.peek(); return t.type === 'OPERATOR' && t.value === value; } private peekWordIs(value: string): boolean { const t = this.peek(); return t.type === 'WORD' && t.value === value; } private expect(type: Token['type'], description: string): Token { const t = this.peek(); if (t.type !== type) { throw new ParseError(`expected ${description}, got ${t.type} "${t.value}"`, t.offset); } return this.advance(); } private expectWord(value: string): Token { const t = this.peek(); if (t.type !== 'WORD' || t.value !== value) { throw new ParseError(`expected "${value}", got ${t.type} "${t.value}"`, t.offset); } return this.advance(); } private isTerminator(): boolean { const t = this.peek(); return t.type === 'NEWLINE' || t.type === 'EOF' || (t.type === 'OPERATOR' && (t.value === ';' || t.value === '&')); } private consumeTerminators(): void { while (this.isTerminator()) this.advance(); } private consumeWord(): Word { const t = this.peek(); if (t.type !== 'WORD') { throw new ParseError(`expected word, got ${t.type} "${t.value}"`, t.offset); } this.advance(); return tokenToWord(t); } } /** Export: parse a token stream into a CommandList AST. */ export function parse(tokens: Token[], source: string): CommandList { const parser = new Parser(tokens, source); return parser.parseScript(); } // --------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------- function tokenToWord(tok: Token): Word { if (!tok.segments) { return { segments: [{ type: 'literal', value: tok.value }] }; } return { segments: tok.segments.map(tokenSegmentToWordSegment) }; } function tokenSegmentToWordSegment(seg: TokenSegment): WordSegment { if (seg.type === 'literal') return { type: 'literal', value: seg.value }; if (seg.type === 'single_quoted') return { type: 'single_quoted', value: seg.value }; if (seg.type === 'double_quoted') { return { type: 'double_quoted', segments: splitDoubleQuotedBody(seg.value) }; } // dollar-prefixed expression return classifyDollar(seg.value); } /** * Inside a double-quoted segment, further split into text vs $-exprs. * We do a lightweight re-scan here (not a full tokenize) since we already * have a clean string. */ function splitDoubleQuotedBody(body: string): WordSegment[] { const out: WordSegment[] = []; let i = 0; let lit = ''; const flushLit = () => { if (lit) { out.push({ type: 'literal', value: lit }); lit = ''; } }; while (i < body.length) { const c = body[i]; if (c === '$') { // Replicate the dollar-reader logic (simpler: support $NAME, ${...}, $(...), $?, $@, $#) const { expr, end } = readDollarInString(body, i); flushLit(); out.push(classifyDollar(expr)); i = end; continue; } if (c === '`') { // Backticks inside double quotes. const end = body.indexOf('`', i + 1); if (end === -1) { lit += c; i++; continue; } flushLit(); out.push({ type: 'command_substitution', script: body.slice(i + 1, end) }); i = end + 1; continue; } lit += c; i++; } flushLit(); return out; } function readDollarInString(s: string, i: number): { expr: string; end: number } { const start = i; i++; if (i >= s.length) return { expr: '$', end: i }; const c = s[i]; if (c === '{') { i++; let depth = 1; while (i < s.length && depth > 0) { if (s[i] === '{') depth++; else if (s[i] === '}') { depth--; if (depth === 0) break; } i++; } if (i < s.length) i++; return { expr: s.slice(start, i), end: i }; } if (c === '(') { if (s[i + 1] === '(') { i += 2; let depth = 2; while (i < s.length && depth > 0) { if (s[i] === '(') depth++; else if (s[i] === ')') { depth--; if (depth === 0) { i++; if (s[i] === ')') i++; break; } } i++; } return { expr: s.slice(start, i), end: i }; } i++; let depth = 1; while (i < s.length && depth > 0) { if (s[i] === '(') depth++; else if (s[i] === ')') { depth--; if (depth === 0) break; } i++; } if (i < s.length) i++; return { expr: s.slice(start, i), end: i }; } if (/[A-Za-z_]/.test(c)) { while (i < s.length && /[A-Za-z0-9_]/.test(s[i])) i++; return { expr: s.slice(start, i), end: i }; } if (c === '?' || c === '$' || c === '!' || c === '#' || c === '*' || c === '@' || c === '-' || /[0-9]/.test(c)) { i++; return { expr: s.slice(start, i), end: i }; } return { expr: '$', end: i }; } /** Classify a $-prefixed expression string into a WordSegment. */ function classifyDollar(expr: string): WordSegment { if (expr === '$') return { type: 'literal', value: '$' }; if (expr.startsWith('$((') && expr.endsWith('))')) { return { type: 'arithmetic', expression: expr.slice(3, -2) }; } if (expr.startsWith('$(') && expr.endsWith(')')) { return { type: 'command_substitution', script: expr.slice(2, -1) }; } if (expr.startsWith('${') && expr.endsWith('}')) { return { type: 'param', name: expr.slice(2, -1) }; } // $NAME or $? return { type: 'param', name: expr.slice(1) }; } /** Build a Word from the suffix of a token's segments after an `=`. */ function segmentsAfterChar(_tok: Token, _charIndex: number, valueText: string): Word { // Rough: for simple cases (no quoting across the `=`), build a literal // word from the post-= text. Full fidelity would walk the original // segments, but inline assignments with quotes are edge cases. return { segments: [{ type: 'literal', value: valueText }] }; } /** Decide whether a heredoc delimiter is quoted (disables expansion). */ function parseHeredocTag(tok: Token): { tag: string; expand: boolean } { if (!tok.segments) return { tag: tok.value, expand: true }; let tag = ''; let expand = true; for (const seg of tok.segments) { if (seg.type === 'literal') tag += seg.value; else if (seg.type === 'single_quoted') { tag += seg.value; expand = false; } else if (seg.type === 'double_quoted') { tag += seg.value; expand = false; } else tag += seg.value; // ignore dollar inside a heredoc tag } return { tag, expand }; }