bash-ast.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /**
  2. * Codex-aligned bash parser.
  3. *
  4. * Hand-written TypeScript reproduction of the accept/reject set implemented by
  5. * OpenAI Codex's tree-sitter-bash parser in `shell-command/src/bash.rs`. We do
  6. * NOT pull in tree-sitter; instead we re-derive the same decision boundary with
  7. * a quote-aware scanner. The goal is behavioural parity with Codex on the set
  8. * of scripts that classify as "word-only command sequences" and on the heredoc
  9. * single-command-prefix fallback.
  10. *
  11. * Codex parity points (see bash.rs):
  12. * - A script is a "plain command sequence" iff every command is built only
  13. * from bare words / quoted strings / numbers / quote-concatenations, joined
  14. * ONLY by the side-effect-free operators `&&`, `||`, `;`, `|`.
  15. * - Any of the following make the whole script NON-plain (returns undefined):
  16. * parentheses / subshells, redirections (`>` `<` `>>` `2>` …),
  17. * background `&`, command substitution `$( … )` / backticks,
  18. * parameter expansion `$VAR` / `${VAR}` (even inside double quotes),
  19. * variable-assignment prefix (`FOO=bar cmd`), empty command positions
  20. * (leading / trailing / doubled operators), and parse errors.
  21. * - Double-quoted strings keep their literal content (Codex rejects them only
  22. * when they contain an expansion); single quotes are fully literal.
  23. *
  24. * Unlike Codex's AST walk we cannot rely on a grammar, so the scanner is
  25. * deliberately conservative: anything it is unsure about is rejected (returns
  26. * undefined), matching Codex's "if we cannot prove it word-only, it is not
  27. * auto-safe" stance.
  28. */
  29. export type ShellName = 'bash' | 'zsh' | 'sh';
  30. /** Shells whose `-lc` / `-c` script arg we are willing to parse. */
  31. const KNOWN_SHELLS = new Set<string>(['bash', 'zsh', 'sh']);
  32. /**
  33. * Extract the `(shell, script)` pair from a `bash -lc "<script>"` style argv.
  34. * Mirrors Codex `extract_bash_command`: exactly 3 tokens, flag is `-lc`/`-c`,
  35. * and the executable basename is a known shell.
  36. */
  37. export function extractBashCommand(
  38. command: readonly string[],
  39. ): { shell: string; script: string } | undefined {
  40. if (command.length !== 3) return undefined;
  41. const [shell, flag, script] = command as [string, string, string];
  42. if (flag !== '-lc' && flag !== '-c') return undefined;
  43. if (!KNOWN_SHELLS.has(basename(shell))) return undefined;
  44. return { shell, script };
  45. }
  46. /**
  47. * Codex `parse_shell_lc_plain_commands`: parse the script of a `bash -lc "…"`
  48. * invocation into a sequence of plain commands, or undefined if it is not a
  49. * word-only command sequence.
  50. */
  51. export function parseShellLcPlainCommands(command: readonly string[]): string[][] | undefined {
  52. const extracted = extractBashCommand(command);
  53. if (!extracted) return undefined;
  54. return parseScriptPlainCommands(extracted.script);
  55. }
  56. /**
  57. * Codex `try_parse_word_only_commands_sequence` operating on a raw script
  58. * string (the form used by Codex tests via `parse_seq`).
  59. */
  60. export function parseScriptPlainCommands(script: string): string[][] | undefined {
  61. // Reject any whole-script construct that the word-only grammar forbids.
  62. if (containsForbiddenConstruct(script)) return undefined;
  63. const segments = splitTopLevelSegments(script);
  64. if (segments === undefined) return undefined; // doubled / dangling operator
  65. if (segments.length === 0) return undefined;
  66. const commands: string[][] = [];
  67. for (const segment of segments) {
  68. const trimmed = segment.trim();
  69. if (trimmed.length === 0) return undefined; // empty command position
  70. const words = parsePlainCommandWords(trimmed);
  71. if (!words || words.length === 0) return undefined;
  72. if (isAssignmentPrefix(words[0]!)) return undefined; // FOO=bar cmd
  73. commands.push(words);
  74. }
  75. return commands;
  76. }
  77. /**
  78. * Codex `parse_shell_lc_single_command_prefix`: for a heredoc-style script with
  79. * exactly one command and no extra file redirect, return that command's
  80. * word prefix (argv). Used so heredoc invocations still match allow/prompt
  81. * rules by their executable prefix.
  82. */
  83. export function parseShellLcSingleCommandPrefix(command: readonly string[]): string[] | undefined {
  84. const extracted = extractBashCommand(command);
  85. if (!extracted) return undefined;
  86. const { script } = extracted;
  87. if (!hasHeredoc(script)) return undefined;
  88. // A heredoc attaches stdin; an *extra* file redirect (`> file`) may write
  89. // outside the sandbox, so Codex refuses to collapse it to the prefix.
  90. if (hasFileRedirect(script)) return undefined;
  91. // Command substitution / expansion in the header is unsafe.
  92. const withoutBodies = stripHeredocBodies(script);
  93. if (containsExpansionOrSubstitution(withoutBodies)) return undefined;
  94. // Codex requires EXACTLY one command node. After removing heredoc bodies,
  95. // any trailing command (`… PY\necho done`) leaves a second command, so the
  96. // heredoc-stripped script must collapse to a single command. Newlines, like
  97. // `;`, separate commands here.
  98. const strippedSansHeredocOp = withoutBodies.replace(
  99. /<<[-~]?\s*(['"]?)[A-Za-z_][A-Za-z0-9_]*\1/g,
  100. '',
  101. );
  102. if (countTopLevelCommands(strippedSansHeredocOp) !== 1) return undefined;
  103. const header = script.slice(0, script.indexOf('<<')).trim();
  104. if (header.length === 0) return undefined;
  105. // The header must be a single simple command: no operators joining commands.
  106. if (splitTopLevelSegments(header)?.length !== 1) return undefined;
  107. const words = parsePlainCommandWords(header);
  108. if (!words || words.length === 0) return undefined;
  109. if (isAssignmentPrefix(words[0]!)) return undefined;
  110. return words;
  111. }
  112. // ───────────────────────────────────────────────────────────────────────────
  113. // Internal scanning helpers
  114. // ───────────────────────────────────────────────────────────────────────────
  115. /**
  116. * Whole-script reject scan. Walks the source tracking quote state and rejects
  117. * any construct outside the word-only grammar. Single quotes are fully literal;
  118. * double quotes still allow `$`-expansion to be detected (Codex rejects those).
  119. */
  120. function containsForbiddenConstruct(script: string): boolean {
  121. let inSingle = false;
  122. let inDouble = false;
  123. let escaped = false;
  124. for (let i = 0; i < script.length; i++) {
  125. const ch = script[i]!;
  126. if (escaped) {
  127. escaped = false;
  128. continue;
  129. }
  130. if (ch === '\\' && !inSingle) {
  131. escaped = true;
  132. continue;
  133. }
  134. if (ch === "'" && !inDouble) {
  135. inSingle = !inSingle;
  136. continue;
  137. }
  138. if (ch === '"' && !inSingle) {
  139. inDouble = !inDouble;
  140. continue;
  141. }
  142. // Inside single quotes everything is literal data.
  143. if (inSingle) continue;
  144. // `$` introduces parameter / command / arithmetic expansion. Forbidden in
  145. // both unquoted AND double-quoted context (matches Codex rejecting
  146. // `echo "$HOME"`).
  147. if (ch === '$') return true;
  148. // Backtick command substitution.
  149. if (ch === '`') return true;
  150. // The remaining constructs are only meaningful OUTSIDE quotes.
  151. if (inDouble) continue;
  152. // Redirections.
  153. if (ch === '>' || ch === '<') return true;
  154. // Subshell / grouping / process substitution.
  155. if (ch === '(' || ch === ')' || ch === '{' || ch === '}') return true;
  156. // Background `&` is rejected; `&&` is handled by the segment splitter and
  157. // is allowed, so only a lone `&` (not part of `&&`) is forbidden here.
  158. if (ch === '&' && script[i + 1] !== '&' && script[i - 1] !== '&') return true;
  159. }
  160. // Unbalanced quotes ⇒ parse error ⇒ reject.
  161. if (inSingle || inDouble || escaped) return true;
  162. return false;
  163. }
  164. /**
  165. * Split a script into top-level command segments on the allowed operators
  166. * `&&`, `||`, `;`, `|` (quote-aware). Returns undefined if it finds a doubled
  167. * or dangling operator (empty command position), matching Codex parse errors
  168. * like `ls ;;`, `ls &&`, `ls | | wc`, `&& ls`.
  169. */
  170. function splitTopLevelSegments(script: string): string[] | undefined {
  171. const segments: string[] = [];
  172. let current = '';
  173. let inSingle = false;
  174. let inDouble = false;
  175. let escaped = false;
  176. const pushSegment = (): boolean => {
  177. // An empty segment between two operators is an empty command position.
  178. if (current.trim().length === 0) return false;
  179. segments.push(current);
  180. current = '';
  181. return true;
  182. };
  183. for (let i = 0; i < script.length; i++) {
  184. const ch = script[i]!;
  185. const next = script[i + 1];
  186. if (escaped) {
  187. current += ch;
  188. escaped = false;
  189. continue;
  190. }
  191. if (ch === '\\' && !inSingle) {
  192. current += ch;
  193. escaped = true;
  194. continue;
  195. }
  196. if (ch === "'" && !inDouble) {
  197. inSingle = !inSingle;
  198. current += ch;
  199. continue;
  200. }
  201. if (ch === '"' && !inSingle) {
  202. inDouble = !inDouble;
  203. current += ch;
  204. continue;
  205. }
  206. if (inSingle || inDouble) {
  207. current += ch;
  208. continue;
  209. }
  210. // `&&` and `||`
  211. if ((ch === '&' && next === '&') || (ch === '|' && next === '|')) {
  212. if (!pushSegment()) return undefined;
  213. i += 1;
  214. continue;
  215. }
  216. // single `|` (pipe) and `;`
  217. if (ch === '|' || ch === ';') {
  218. if (!pushSegment()) return undefined;
  219. continue;
  220. }
  221. current += ch;
  222. }
  223. // Trailing operator leaves a dangling empty segment ⇒ reject.
  224. if (current.trim().length === 0) {
  225. // If we have already collected segments, a trailing-empty means a dangling
  226. // operator (`ls &&`). An all-empty script also yields no commands.
  227. return segments.length > 0 ? undefined : [];
  228. }
  229. segments.push(current);
  230. return segments;
  231. }
  232. /**
  233. * Parse a single simple command (already free of operators) into its argv,
  234. * resolving quotes and quote-concatenation. Returns undefined if the command
  235. * is not purely word-like (caller has already reject-scanned for `$`/`` ` ``,
  236. * redirects, etc., so this only tokenises).
  237. */
  238. function parsePlainCommandWords(command: string): string[] | undefined {
  239. const words: string[] = [];
  240. let current = '';
  241. let hasToken = false;
  242. let inSingle = false;
  243. let inDouble = false;
  244. let escaped = false;
  245. const flush = (): void => {
  246. if (hasToken) {
  247. words.push(current);
  248. }
  249. current = '';
  250. hasToken = false;
  251. };
  252. for (let i = 0; i < command.length; i++) {
  253. const ch = command[i]!;
  254. if (escaped) {
  255. current += ch;
  256. hasToken = true;
  257. escaped = false;
  258. continue;
  259. }
  260. if (ch === '\\' && !inSingle) {
  261. escaped = true;
  262. hasToken = true;
  263. continue;
  264. }
  265. if (ch === "'" && !inDouble) {
  266. inSingle = !inSingle;
  267. hasToken = true; // empty quotes still produce a token
  268. continue;
  269. }
  270. if (ch === '"' && !inSingle) {
  271. inDouble = !inDouble;
  272. hasToken = true;
  273. continue;
  274. }
  275. if (!inSingle && !inDouble && isWhitespace(ch)) {
  276. flush();
  277. continue;
  278. }
  279. current += ch;
  280. hasToken = true;
  281. }
  282. if (inSingle || inDouble || escaped) return undefined;
  283. flush();
  284. return words;
  285. }
  286. // ───────────────────────────────────────────────────────────────────────────
  287. // Heredoc helpers (single-command-prefix fallback)
  288. // ───────────────────────────────────────────────────────────────────────────
  289. function hasHeredoc(script: string): boolean {
  290. return /<<[-~]?\s*['"]?[A-Za-z_][A-Za-z0-9_]*/.test(script) || script.includes('<<');
  291. }
  292. /**
  293. * Detect a file redirect (`>`, `>>`, `<`, `2>` …) that is NOT the heredoc
  294. * operator. We strip heredoc operators first, then look for any remaining
  295. * angle-bracket redirect outside quotes.
  296. */
  297. function hasFileRedirect(script: string): boolean {
  298. const withoutHeredoc = stripHeredocBodies(script).replace(/<<[-~]?/g, '');
  299. let inSingle = false;
  300. let inDouble = false;
  301. let escaped = false;
  302. for (let i = 0; i < withoutHeredoc.length; i++) {
  303. const ch = withoutHeredoc[i]!;
  304. if (escaped) {
  305. escaped = false;
  306. continue;
  307. }
  308. if (ch === '\\' && !inSingle) {
  309. escaped = true;
  310. continue;
  311. }
  312. if (ch === "'" && !inDouble) {
  313. inSingle = !inSingle;
  314. continue;
  315. }
  316. if (ch === '"' && !inSingle) {
  317. inDouble = !inDouble;
  318. continue;
  319. }
  320. if (inSingle || inDouble) continue;
  321. if (ch === '>' || ch === '<') return true;
  322. }
  323. return false;
  324. }
  325. /** Remove heredoc bodies so header scans don't trip over body content. */
  326. function stripHeredocBodies(script: string): string {
  327. const match = /<<[-~]?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(script);
  328. if (!match) return script;
  329. const delimiter = match[2]!;
  330. const headerEnd = script.indexOf('\n');
  331. if (headerEnd === -1) return script;
  332. const header = script.slice(0, headerEnd);
  333. // Drop everything from the first body line up to (and including) the closing
  334. // delimiter line; keep anything after the delimiter (e.g. `; echo done`).
  335. const lines = script.slice(headerEnd + 1).split('\n');
  336. const closingIdx = lines.findIndex((line) => line.trim() === delimiter);
  337. if (closingIdx === -1) return header;
  338. const tail = lines.slice(closingIdx + 1).join('\n');
  339. return tail.length > 0 ? `${header}\n${tail}` : header;
  340. }
  341. function containsExpansionOrSubstitution(text: string): boolean {
  342. let inSingle = false;
  343. let inDouble = false;
  344. let escaped = false;
  345. for (let i = 0; i < text.length; i++) {
  346. const ch = text[i]!;
  347. if (escaped) {
  348. escaped = false;
  349. continue;
  350. }
  351. if (ch === '\\' && !inSingle) {
  352. escaped = true;
  353. continue;
  354. }
  355. if (ch === "'" && !inDouble) {
  356. inSingle = !inSingle;
  357. continue;
  358. }
  359. if (ch === '"' && !inSingle) {
  360. inDouble = !inDouble;
  361. continue;
  362. }
  363. if (inSingle) continue;
  364. if (ch === '$' || ch === '`') return true;
  365. }
  366. return false;
  367. }
  368. // ───────────────────────────────────────────────────────────────────────────
  369. // Small utilities
  370. // ───────────────────────────────────────────────────────────────────────────
  371. function isAssignmentPrefix(word: string): boolean {
  372. // `FOO=bar` / `FOO=` at the command head is a variable assignment, not a cmd.
  373. return /^[A-Za-z_][A-Za-z0-9_]*=/.test(word);
  374. }
  375. /**
  376. * Count non-empty top-level commands, treating newlines as command separators
  377. * in addition to `;`/`&&`/`||`/`|`. Used by the heredoc fallback to enforce
  378. * Codex's "exactly one command node" rule.
  379. */
  380. function countTopLevelCommands(script: string): number {
  381. const normalized = script.replace(/\r?\n/g, ';');
  382. const segments = splitTopLevelSegments(normalized);
  383. if (segments === undefined) return -1;
  384. return segments.filter((segment) => segment.trim().length > 0).length;
  385. }
  386. function isWhitespace(ch: string): boolean {
  387. const code = ch.charCodeAt(0);
  388. return code === 32 || (code >= 9 && code <= 13);
  389. }
  390. function basename(p: string): string {
  391. const normalized = p.replaceAll('\\', '/');
  392. const idx = normalized.lastIndexOf('/');
  393. return idx === -1 ? normalized : normalized.slice(idx + 1);
  394. }