bash-ast 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lexer.js CHANGED
@@ -52,6 +52,7 @@ var TokenType;
52
52
  TokenType["RBRACE"] = "RBRACE";
53
53
  // Special
54
54
  TokenType["IO_NUMBER"] = "IO_NUMBER";
55
+ TokenType["COMMENT"] = "COMMENT";
55
56
  TokenType["EOF"] = "EOF";
56
57
  TokenType["WHITESPACE"] = "WHITESPACE";
57
58
  })(TokenType || (exports.TokenType = TokenType = {}));
@@ -75,6 +76,17 @@ const RESERVED_WORDS = {
75
76
  function: TokenType.FUNCTION,
76
77
  '!': TokenType.BANG,
77
78
  };
79
+ /**
80
+ * Builtins whose operands are assignments (`export FOO=bar`)
81
+ */
82
+ const DECLARATION_BUILTINS = new Set([
83
+ 'export',
84
+ 'local',
85
+ 'declare',
86
+ 'readonly',
87
+ 'typeset',
88
+ ]);
89
+ const ASSIGNMENT_RE = /^[a-zA-Z_][a-zA-Z0-9_]*(\[[^\]]*\])?\+?=/;
78
90
  /**
79
91
  * Bash Lexer
80
92
  */
@@ -83,8 +95,20 @@ class Lexer {
83
95
  pos = 0;
84
96
  line = 1;
85
97
  column = 0;
86
- constructor(input) {
98
+ options;
99
+ /**
100
+ * True when the next word would be the command name, i.e. when a leading
101
+ * `NAME=value` word is an assignment rather than an ordinary argument.
102
+ */
103
+ commandPosition = true;
104
+ /**
105
+ * True while lexing the arguments of `export`/`local`/`declare`/`readonly`.
106
+ */
107
+ declarationCommand = false;
108
+ pendingHereDocs = [];
109
+ constructor(input, options = {}) {
87
110
  this.input = input;
111
+ this.options = options;
88
112
  }
89
113
  /**
90
114
  * Get current position
@@ -127,7 +151,7 @@ class Lexer {
127
151
  * Check if character is whitespace (not newline)
128
152
  */
129
153
  isWhitespace(char) {
130
- return char === ' ' || char === '\t';
154
+ return char === ' ' || char === '\t' || char === '\r';
131
155
  }
132
156
  /**
133
157
  * Check if character is a digit
@@ -136,7 +160,7 @@ class Lexer {
136
160
  return char >= '0' && char <= '9';
137
161
  }
138
162
  /**
139
- * Check if character can start a word
163
+ * Check if character can be part of a word
140
164
  */
141
165
  isWordChar(char) {
142
166
  return char !== '' &&
@@ -148,16 +172,40 @@ class Lexer {
148
172
  char !== '(' &&
149
173
  char !== ')' &&
150
174
  char !== '<' &&
151
- char !== '>' &&
152
- char !== '{' &&
153
- char !== '}';
175
+ char !== '>';
154
176
  }
155
177
  /**
156
- * Skip whitespace (not newlines)
178
+ * Check if a character terminates a token. `{` and `}` are reserved words
179
+ * only when they stand alone; elsewhere they are ordinary word characters
180
+ * (`--set jsonpath={.metadata.name}`, `{1..3}`).
181
+ */
182
+ isTokenDelimiter(char) {
183
+ return char === '' ||
184
+ this.isWhitespace(char) ||
185
+ char === '\n' ||
186
+ char === ';' ||
187
+ char === '&' ||
188
+ char === '|' ||
189
+ char === '(' ||
190
+ char === ')' ||
191
+ char === '<' ||
192
+ char === '>';
193
+ }
194
+ /**
195
+ * Skip whitespace and line continuations (not newlines)
157
196
  */
158
197
  skipWhitespace() {
159
- while (!this.isAtEnd() && this.isWhitespace(this.peek())) {
160
- this.advance();
198
+ while (!this.isAtEnd()) {
199
+ if (this.isWhitespace(this.peek())) {
200
+ this.advance();
201
+ }
202
+ else if (this.peek() === '\\' && this.peek(1) === '\n') {
203
+ this.advance();
204
+ this.advance();
205
+ }
206
+ else {
207
+ break;
208
+ }
161
209
  }
162
210
  }
163
211
  /**
@@ -208,6 +256,12 @@ class Lexer {
208
256
  result += this.readDoubleQuoted();
209
257
  }
210
258
  else if (char === '\\') {
259
+ if (this.peek(1) === '\n') {
260
+ // line continuation: removed, the word continues on the next line
261
+ this.advance();
262
+ this.advance();
263
+ continue;
264
+ }
211
265
  result += this.advance(); // backslash
212
266
  if (!this.isAtEnd()) {
213
267
  result += this.advance(); // escaped char
@@ -219,12 +273,39 @@ class Lexer {
219
273
  else if (char === '`') {
220
274
  result += this.readBacktickSubstitution();
221
275
  }
276
+ else if ((char === '{' || char === '}') && result === '' && this.isTokenDelimiter(this.peek(1))) {
277
+ break;
278
+ }
222
279
  else {
223
280
  result += this.advance();
224
281
  }
225
282
  }
226
283
  return result;
227
284
  }
285
+ /**
286
+ * Read a balanced parenthesised run, including the parens
287
+ */
288
+ readBalancedParens() {
289
+ let result = this.advance(); // (
290
+ let depth = 1;
291
+ while (!this.isAtEnd() && depth > 0) {
292
+ const char = this.peek();
293
+ if (char === "'") {
294
+ result += this.readSingleQuoted();
295
+ continue;
296
+ }
297
+ if (char === '"') {
298
+ result += this.readDoubleQuoted();
299
+ continue;
300
+ }
301
+ if (char === '(')
302
+ depth++;
303
+ if (char === ')')
304
+ depth--;
305
+ result += this.advance();
306
+ }
307
+ return result;
308
+ }
228
309
  /**
229
310
  * Read an expansion ($VAR, ${VAR}, $(cmd), $((expr)))
230
311
  */
@@ -246,15 +327,7 @@ class Lexer {
246
327
  }
247
328
  else {
248
329
  // Command substitution $(cmd)
249
- result += this.advance(); // (
250
- let depth = 1;
251
- while (!this.isAtEnd() && depth > 0) {
252
- if (this.peek() === '(')
253
- depth++;
254
- if (this.peek() === ')')
255
- depth--;
256
- result += this.advance();
257
- }
330
+ result += this.readBalancedParens();
258
331
  }
259
332
  }
260
333
  else if (this.peek() === '{') {
@@ -299,17 +372,128 @@ class Lexer {
299
372
  return result;
300
373
  }
301
374
  /**
302
- * Read a comment
375
+ * Read a comment, excluding the leading `#`
303
376
  */
304
377
  readComment() {
378
+ this.advance(); // #
379
+ let result = '';
305
380
  while (!this.isAtEnd() && this.peek() !== '\n') {
381
+ result += this.advance();
382
+ }
383
+ return result;
384
+ }
385
+ /**
386
+ * Strip one level of quoting from a here-document delimiter
387
+ */
388
+ unquoteDelimiter(word) {
389
+ if (word.length >= 2 && ((word.startsWith("'") && word.endsWith("'")) || (word.startsWith('"') && word.endsWith('"')))) {
390
+ return { delimiter: word.slice(1, -1), quoted: true };
391
+ }
392
+ if (word.includes('\\')) {
393
+ return { delimiter: word.replace(/\\(.)/g, '$1'), quoted: true };
394
+ }
395
+ return { delimiter: word, quoted: false };
396
+ }
397
+ /**
398
+ * Read one raw line, consuming its terminating newline
399
+ */
400
+ readRawLine() {
401
+ let text = '';
402
+ while (!this.isAtEnd() && this.peek() !== '\n') {
403
+ text += this.advance();
404
+ }
405
+ const terminated = this.peek() === '\n';
406
+ if (terminated) {
306
407
  this.advance();
307
408
  }
409
+ return { text, terminated };
410
+ }
411
+ /**
412
+ * Read the bodies of every here-document pending on the line just ended.
413
+ * A body is opaque text: it is never fed through the command lexer.
414
+ */
415
+ readPendingHereDocBodies() {
416
+ const pending = this.pendingHereDocs;
417
+ this.pendingHereDocs = [];
418
+ for (const entry of pending) {
419
+ if (entry.delimiter === undefined)
420
+ continue;
421
+ let content = '';
422
+ for (;;) {
423
+ if (this.isAtEnd())
424
+ break;
425
+ const startOfLine = this.pos;
426
+ const { text, terminated } = this.readRawLine();
427
+ const candidate = entry.dash ? text.replace(/^[\t]+/, '') : text;
428
+ if (candidate === entry.delimiter) {
429
+ break;
430
+ }
431
+ if (!terminated && this.isAtEnd() && startOfLine === this.pos) {
432
+ break;
433
+ }
434
+ content += text + '\n';
435
+ if (!terminated)
436
+ break;
437
+ }
438
+ entry.token.heredoc = {
439
+ type: 'HereDoc',
440
+ delimiter: entry.delimiter,
441
+ content,
442
+ quoted: entry.quoted || undefined
443
+ };
444
+ }
445
+ }
446
+ /**
447
+ * Track whether the next word sits in command (assignment) position. `)` is
448
+ * in the list because it closes a case pattern, whose body starts a command.
449
+ */
450
+ updateContext(token) {
451
+ switch (token.type) {
452
+ case TokenType.NEWLINE:
453
+ case TokenType.SEMI:
454
+ case TokenType.DSEMI:
455
+ case TokenType.AMP:
456
+ case TokenType.PIPE:
457
+ case TokenType.AND_IF:
458
+ case TokenType.OR_IF:
459
+ case TokenType.LBRACE:
460
+ case TokenType.LPAREN:
461
+ case TokenType.RPAREN:
462
+ case TokenType.BANG:
463
+ case TokenType.IF:
464
+ case TokenType.THEN:
465
+ case TokenType.ELSE:
466
+ case TokenType.ELIF:
467
+ case TokenType.WHILE:
468
+ case TokenType.UNTIL:
469
+ case TokenType.DO:
470
+ this.commandPosition = true;
471
+ this.declarationCommand = false;
472
+ break;
473
+ case TokenType.ASSIGNMENT_WORD:
474
+ case TokenType.COMMENT:
475
+ break;
476
+ case TokenType.WORD:
477
+ if (this.commandPosition && DECLARATION_BUILTINS.has(token.value)) {
478
+ this.declarationCommand = true;
479
+ }
480
+ this.commandPosition = false;
481
+ break;
482
+ default:
483
+ this.commandPosition = false;
484
+ this.declarationCommand = false;
485
+ break;
486
+ }
308
487
  }
309
488
  /**
310
489
  * Get next token
311
490
  */
312
491
  nextToken() {
492
+ const token = this.scanToken();
493
+ this.updateContext(token);
494
+ return token;
495
+ }
496
+ scanToken() {
313
497
  this.skipWhitespace();
314
498
  if (this.isAtEnd()) {
315
499
  return {
@@ -322,17 +506,28 @@ class Lexer {
322
506
  const char = this.peek();
323
507
  // Comment
324
508
  if (char === '#') {
325
- this.readComment();
326
- return this.nextToken();
509
+ const text = this.readComment();
510
+ if (this.options.keepComments) {
511
+ return {
512
+ type: TokenType.COMMENT,
513
+ value: text,
514
+ range: { start, end: this.getPosition() }
515
+ };
516
+ }
517
+ return this.scanToken();
327
518
  }
328
- // Newline
519
+ // Newline — here-document bodies start right after it
329
520
  if (char === '\n') {
330
521
  this.advance();
331
- return {
522
+ const token = {
332
523
  type: TokenType.NEWLINE,
333
524
  value: '\n',
334
525
  range: { start, end: this.getPosition() }
335
526
  };
527
+ if (this.pendingHereDocs.length > 0) {
528
+ this.readPendingHereDocBodies();
529
+ }
530
+ return token;
336
531
  }
337
532
  // Operators
338
533
  if (char === '|') {
@@ -349,6 +544,15 @@ class Lexer {
349
544
  this.advance();
350
545
  return { type: TokenType.AND_IF, value: '&&', range: { start, end: this.getPosition() } };
351
546
  }
547
+ if (this.peek() === '>') {
548
+ // `&>file` — redirect both streams; lexed as a word-carrying redirect
549
+ this.advance();
550
+ if (this.peek() === '>') {
551
+ this.advance();
552
+ return { type: TokenType.WORD, value: '&>>', range: { start, end: this.getPosition() } };
553
+ }
554
+ return { type: TokenType.WORD, value: '&>', range: { start, end: this.getPosition() } };
555
+ }
352
556
  return { type: TokenType.AMP, value: '&', range: { start, end: this.getPosition() } };
353
557
  }
354
558
  if (char === ';') {
@@ -359,6 +563,12 @@ class Lexer {
359
563
  }
360
564
  return { type: TokenType.SEMI, value: ';', range: { start, end: this.getPosition() } };
361
565
  }
566
+ // Process substitution — a word, not a redirection
567
+ if ((char === '<' || char === '>') && this.peek(1) === '(') {
568
+ const op = this.advance();
569
+ const body = this.readBalancedParens();
570
+ return { type: TokenType.WORD, value: op + body, range: { start, end: this.getPosition() } };
571
+ }
362
572
  // Redirections
363
573
  if (char === '<') {
364
574
  this.advance();
@@ -366,13 +576,17 @@ class Lexer {
366
576
  this.advance();
367
577
  if (this.peek() === '-') {
368
578
  this.advance();
369
- return { type: TokenType.DLESSDASH, value: '<<-', range: { start, end: this.getPosition() } };
579
+ const token = { type: TokenType.DLESSDASH, value: '<<-', range: { start, end: this.getPosition() } };
580
+ this.pendingHereDocs.push({ token, dash: true });
581
+ return token;
370
582
  }
371
583
  if (this.peek() === '<') {
372
584
  this.advance();
373
585
  return { type: TokenType.TLESS, value: '<<<', range: { start, end: this.getPosition() } };
374
586
  }
375
- return { type: TokenType.DLESS, value: '<<', range: { start, end: this.getPosition() } };
587
+ const token = { type: TokenType.DLESS, value: '<<', range: { start, end: this.getPosition() } };
588
+ this.pendingHereDocs.push({ token, dash: false });
589
+ return token;
376
590
  }
377
591
  if (this.peek() === '&') {
378
592
  this.advance();
@@ -400,6 +614,19 @@ class Lexer {
400
614
  }
401
615
  return { type: TokenType.GREAT, value: '>', range: { start, end: this.getPosition() } };
402
616
  }
617
+ // Arithmetic command `((expr))` — a word, not two subshells
618
+ if (char === '(' && this.peek(1) === '(') {
619
+ const text = this.readBalancedParens();
620
+ if (text.startsWith('((') && text.endsWith('))')) {
621
+ return { type: TokenType.WORD, value: text, range: { start, end: this.getPosition() } };
622
+ }
623
+ // not an arithmetic command after all: re-lex what we consumed
624
+ this.pos = start.offset;
625
+ this.line = start.line;
626
+ this.column = start.column;
627
+ this.advance();
628
+ return { type: TokenType.LPAREN, value: '(', range: { start, end: this.getPosition() } };
629
+ }
403
630
  // Grouping
404
631
  if (char === '(') {
405
632
  this.advance();
@@ -409,11 +636,11 @@ class Lexer {
409
636
  this.advance();
410
637
  return { type: TokenType.RPAREN, value: ')', range: { start, end: this.getPosition() } };
411
638
  }
412
- if (char === '{') {
639
+ if (char === '{' && this.isTokenDelimiter(this.peek(1))) {
413
640
  this.advance();
414
641
  return { type: TokenType.LBRACE, value: '{', range: { start, end: this.getPosition() } };
415
642
  }
416
- if (char === '}') {
643
+ if (char === '}' && this.isTokenDelimiter(this.peek(1))) {
417
644
  this.advance();
418
645
  return { type: TokenType.RBRACE, value: '}', range: { start, end: this.getPosition() } };
419
646
  }
@@ -423,15 +650,27 @@ class Lexer {
423
650
  return { type: TokenType.IO_NUMBER, value: num, range: { start, end: this.getPosition() } };
424
651
  }
425
652
  // Word
426
- const word = this.readWord();
427
- const end = this.getPosition();
653
+ let word = this.readWord();
428
654
  // Check for reserved words
429
655
  if (word in RESERVED_WORDS) {
430
- return { type: RESERVED_WORDS[word], value: word, range: { start, end } };
656
+ return { type: RESERVED_WORDS[word], value: word, range: { start, end: this.getPosition() } };
431
657
  }
432
- // Check for assignment word (NAME=VALUE)
433
- if (word.includes('=') && /^[a-zA-Z_][a-zA-Z0-9_]*=/.test(word)) {
434
- return { type: TokenType.ASSIGNMENT_WORD, value: word, range: { start, end } };
658
+ // Assignment words only exist in assignment position: before the command
659
+ // name, or as an operand of export/local/declare/readonly.
660
+ if ((this.commandPosition || this.declarationCommand) && ASSIGNMENT_RE.test(word)) {
661
+ if (word.endsWith('=') && this.peek() === '(') {
662
+ // array assignment: arr=(a b c)
663
+ word += this.readBalancedParens();
664
+ }
665
+ return { type: TokenType.ASSIGNMENT_WORD, value: word, range: { start, end: this.getPosition() } };
666
+ }
667
+ const end = this.getPosition();
668
+ // A here-document delimiter is the word right after the operator
669
+ const awaiting = this.pendingHereDocs.find(entry => entry.delimiter === undefined);
670
+ if (awaiting) {
671
+ const { delimiter, quoted } = this.unquoteDelimiter(word);
672
+ awaiting.delimiter = delimiter;
673
+ awaiting.quoted = quoted;
435
674
  }
436
675
  return { type: TokenType.WORD, value: word, range: { start, end } };
437
676
  }
@@ -439,9 +678,15 @@ class Lexer {
439
678
  * Tokenize entire input
440
679
  */
441
680
  tokenize() {
681
+ const deadline = this.options.timeoutMs === undefined
682
+ ? undefined
683
+ : Date.now() + this.options.timeoutMs;
442
684
  const tokens = [];
443
685
  let token;
444
686
  do {
687
+ if (deadline !== undefined && Date.now() > deadline) {
688
+ throw new Error(`bash-ast: tokenizing exceeded ${this.options.timeoutMs}ms at line ${this.line}, column ${this.column}`);
689
+ }
445
690
  token = this.nextToken();
446
691
  tokens.push(token);
447
692
  } while (token.type !== TokenType.EOF);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bash-ast",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "author": "Constructive <developers@constructive.io>",
5
5
  "description": "Bash/shell command parser and deparser",
6
6
  "main": "index.js",
@@ -38,5 +38,5 @@
38
38
  "devDependencies": {
39
39
  "makage": "0.1.10"
40
40
  },
41
- "gitHead": "cb93b66c72e3925e5f751679b5861eaaff641bf0"
41
+ "gitHead": "239f11e071f1d3891d8c9010ac6ff2d3574bbf0f"
42
42
  }
package/parser.d.ts CHANGED
@@ -3,6 +3,15 @@ import { Script } from './types';
3
3
  * Parser options
4
4
  */
5
5
  export interface ParserOptions {
6
+ /**
7
+ * Keep comments in the AST as `Comment` nodes instead of discarding them.
8
+ */
9
+ keepComments?: boolean;
10
+ /**
11
+ * Wall-clock budget for a single `parse()`, in milliseconds. Exceeding it
12
+ * throws, so a pathological input is a loud failure rather than a hang.
13
+ */
14
+ timeoutMs?: number;
6
15
  }
7
16
  /**
8
17
  * Bash Parser
@@ -11,11 +20,20 @@ export declare class Parser {
11
20
  private tokens;
12
21
  private pos;
13
22
  private options;
23
+ private deadline?;
14
24
  constructor(options?: ParserOptions);
15
25
  /**
16
26
  * Parse bash source into AST
17
27
  */
18
28
  parse(source: string): Script;
29
+ /**
30
+ * Fail if the parse budget is spent
31
+ */
32
+ private checkDeadline;
33
+ /**
34
+ * Error message for the current token
35
+ */
36
+ private unexpected;
19
37
  /**
20
38
  * Check if at end of tokens
21
39
  */
@@ -37,13 +55,21 @@ export declare class Parser {
37
55
  */
38
56
  private expect;
39
57
  /**
40
- * Skip newlines
58
+ * Skip newlines (and comments the parser was told to drop)
41
59
  */
42
60
  private skipNewlines;
43
61
  /**
44
62
  * Skip newlines and separators
45
63
  */
46
64
  private skipNewlinesAndSeparators;
65
+ /**
66
+ * Mark a command as asynchronous when it is terminated by `&`
67
+ */
68
+ private applyAsync;
69
+ /**
70
+ * Parse a comment node
71
+ */
72
+ private parseComment;
47
73
  /**
48
74
  * Parse a command (handles logical operators)
49
75
  */
@@ -64,6 +90,10 @@ export declare class Parser {
64
90
  * Parse compound command or simple command
65
91
  */
66
92
  private parseCompoundCommand;
93
+ /**
94
+ * Attach the redirections that follow a compound command (`{ … } > file`)
95
+ */
96
+ private withRedirects;
67
97
  /**
68
98
  * Parse simple command
69
99
  */
@@ -109,7 +139,8 @@ export declare class Parser {
109
139
  */
110
140
  private parseSubshell;
111
141
  /**
112
- * Parse brace group
142
+ * Parse brace group. A brace group is one compound command: it keeps its
143
+ * grouping through pipelines, `&&`/`||`, `&` and redirection.
113
144
  */
114
145
  private parseBraceGroup;
115
146
  /**