bash-ast 0.1.2 → 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/esm/parser.js CHANGED
@@ -6,6 +6,7 @@ export class Parser {
6
6
  tokens = [];
7
7
  pos = 0;
8
8
  options;
9
+ deadline;
9
10
  constructor(options = {}) {
10
11
  this.options = options;
11
12
  }
@@ -13,23 +14,57 @@ export class Parser {
13
14
  * Parse bash source into AST
14
15
  */
15
16
  parse(source) {
16
- const lexer = new Lexer(source);
17
+ const lexer = new Lexer(source, {
18
+ keepComments: this.options.keepComments,
19
+ timeoutMs: this.options.timeoutMs
20
+ });
17
21
  this.tokens = lexer.tokenize();
18
22
  this.pos = 0;
23
+ this.deadline = this.options.timeoutMs === undefined
24
+ ? undefined
25
+ : Date.now() + this.options.timeoutMs;
19
26
  const commands = [];
20
27
  this.skipNewlines();
21
28
  while (!this.isAtEnd()) {
22
- const command = this.parseCommand();
23
- if (command) {
24
- commands.push(command);
29
+ this.checkDeadline();
30
+ const before = this.pos;
31
+ if (this.check(TokenType.COMMENT)) {
32
+ commands.push(this.parseComment());
33
+ }
34
+ else {
35
+ const command = this.parseCommand();
36
+ if (command) {
37
+ this.applyAsync(command);
38
+ commands.push(command);
39
+ }
25
40
  }
26
41
  this.skipNewlinesAndSeparators();
42
+ if (this.pos === before) {
43
+ // Nothing was consumed: the token cannot start a command. Fail loudly
44
+ // rather than spinning forever.
45
+ throw new Error(this.unexpected());
46
+ }
27
47
  }
28
48
  return {
29
49
  type: 'Script',
30
50
  commands
31
51
  };
32
52
  }
53
+ /**
54
+ * Fail if the parse budget is spent
55
+ */
56
+ checkDeadline() {
57
+ if (this.deadline !== undefined && Date.now() > this.deadline) {
58
+ throw new Error(`bash-ast: parsing exceeded ${this.options.timeoutMs}ms at ${this.unexpected()}`);
59
+ }
60
+ }
61
+ /**
62
+ * Error message for the current token
63
+ */
64
+ unexpected() {
65
+ const token = this.peek();
66
+ return `Unexpected ${token.type}${token.value ? ` (${JSON.stringify(token.value)})` : ''} at line ${token.range.start.line}, column ${token.range.start.column}`;
67
+ }
33
68
  /**
34
69
  * Check if at end of tokens
35
70
  */
@@ -68,10 +103,10 @@ export class Parser {
68
103
  if (this.check(type)) {
69
104
  return this.advance();
70
105
  }
71
- throw new Error(`Expected ${type}, got ${this.peek().type} at position ${this.pos}`);
106
+ throw new Error(`Expected ${type}, got ${this.peek().type} at line ${this.peek().range.start.line}, column ${this.peek().range.start.column}`);
72
107
  }
73
108
  /**
74
- * Skip newlines
109
+ * Skip newlines (and comments the parser was told to drop)
75
110
  */
76
111
  skipNewlines() {
77
112
  while (this.check(TokenType.NEWLINE)) {
@@ -86,6 +121,28 @@ export class Parser {
86
121
  this.advance();
87
122
  }
88
123
  }
124
+ /**
125
+ * Mark a command as asynchronous when it is terminated by `&`
126
+ */
127
+ applyAsync(command) {
128
+ if (this.check(TokenType.AMP)) {
129
+ this.advance();
130
+ command.async = true;
131
+ return true;
132
+ }
133
+ return false;
134
+ }
135
+ /**
136
+ * Parse a comment node
137
+ */
138
+ parseComment() {
139
+ const token = this.expect(TokenType.COMMENT);
140
+ return {
141
+ type: 'Comment',
142
+ text: token.value,
143
+ range: token.range
144
+ };
145
+ }
89
146
  /**
90
147
  * Parse a command (handles logical operators)
91
148
  */
@@ -176,19 +233,19 @@ export class Parser {
176
233
  const token = this.peek();
177
234
  switch (token.type) {
178
235
  case TokenType.IF:
179
- return this.parseIf();
236
+ return this.withRedirects(this.parseIf());
180
237
  case TokenType.WHILE:
181
- return this.parseWhile();
238
+ return this.withRedirects(this.parseWhile());
182
239
  case TokenType.UNTIL:
183
- return this.parseUntil();
240
+ return this.withRedirects(this.parseUntil());
184
241
  case TokenType.FOR:
185
- return this.parseFor();
242
+ return this.withRedirects(this.parseFor());
186
243
  case TokenType.CASE:
187
- return this.parseCase();
244
+ return this.withRedirects(this.parseCase());
188
245
  case TokenType.LPAREN:
189
- return this.parseSubshell();
246
+ return this.withRedirects(this.parseSubshell());
190
247
  case TokenType.LBRACE:
191
- return this.parseBraceGroup();
248
+ return this.withRedirects(this.parseBraceGroup());
192
249
  case TokenType.FUNCTION:
193
250
  return this.parseFunction();
194
251
  default:
@@ -199,6 +256,22 @@ export class Parser {
199
256
  return this.parseSimpleCommand();
200
257
  }
201
258
  }
259
+ /**
260
+ * Attach the redirections that follow a compound command (`{ … } > file`)
261
+ */
262
+ withRedirects(command) {
263
+ const redirects = [];
264
+ while (this.isRedirectOp()) {
265
+ const redirect = this.parseRedirect();
266
+ if (!redirect)
267
+ break;
268
+ redirects.push(redirect);
269
+ }
270
+ if (redirects.length > 0) {
271
+ command.redirects = redirects;
272
+ }
273
+ return command;
274
+ }
202
275
  /**
203
276
  * Parse simple command
204
277
  */
@@ -245,6 +318,15 @@ export class Parser {
245
318
  range: token.range
246
319
  });
247
320
  }
321
+ else if (this.check(TokenType.ASSIGNMENT_WORD)) {
322
+ // operand of export/local/declare/readonly
323
+ const token = this.advance();
324
+ suffix.push({
325
+ type: 'AssignmentWord',
326
+ text: token.value,
327
+ range: token.range
328
+ });
329
+ }
248
330
  else {
249
331
  break;
250
332
  }
@@ -322,27 +404,27 @@ export class Parser {
322
404
  return null;
323
405
  }
324
406
  this.advance();
325
- // Parse file/word
326
- if (this.check(TokenType.WORD)) {
327
- const fileToken = this.advance();
328
- return {
329
- type: 'Redirect',
330
- op,
331
- file: {
332
- type: 'Word',
333
- text: fileToken.value,
334
- range: fileToken.range
335
- },
336
- numberIo,
337
- range: opToken.range
338
- };
339
- }
340
- return {
407
+ const redirect = {
341
408
  type: 'Redirect',
342
409
  op,
343
410
  numberIo,
344
411
  range: opToken.range
345
412
  };
413
+ // The body of a here-document is lexed as opaque text and hangs off the
414
+ // operator token.
415
+ if (opToken.heredoc) {
416
+ redirect.heredoc = opToken.heredoc;
417
+ }
418
+ // Parse file/word (the delimiter, for a here-document)
419
+ if (this.check(TokenType.WORD)) {
420
+ const fileToken = this.advance();
421
+ redirect.file = {
422
+ type: 'Word',
423
+ text: fileToken.value,
424
+ range: fileToken.range
425
+ };
426
+ }
427
+ return redirect;
346
428
  }
347
429
  /**
348
430
  * Parse if clause
@@ -484,11 +566,23 @@ export class Parser {
484
566
  this.skipNewlines();
485
567
  const cases = [];
486
568
  while (!this.check(TokenType.ESAC)) {
569
+ if (this.isAtEnd()) {
570
+ throw new Error('Expected esac, got end of input');
571
+ }
572
+ const before = this.pos;
573
+ if (this.check(TokenType.COMMENT)) {
574
+ // a comment between case items has nowhere to live on a CaseClause
575
+ this.advance();
576
+ continue;
577
+ }
487
578
  const caseItem = this.parseCaseItem();
488
579
  if (caseItem) {
489
580
  cases.push(caseItem);
490
581
  }
491
582
  this.skipNewlines();
583
+ if (this.pos === before) {
584
+ throw new Error(this.unexpected());
585
+ }
492
586
  }
493
587
  this.expect(TokenType.ESAC);
494
588
  return {
@@ -555,14 +649,19 @@ export class Parser {
555
649
  };
556
650
  }
557
651
  /**
558
- * Parse brace group
652
+ * Parse brace group. A brace group is one compound command: it keeps its
653
+ * grouping through pipelines, `&&`/`||`, `&` and redirection.
559
654
  */
560
655
  parseBraceGroup() {
561
- this.expect(TokenType.LBRACE);
656
+ const start = this.expect(TokenType.LBRACE);
562
657
  this.skipNewlines();
563
658
  const list = this.parseCompoundList();
564
659
  this.expect(TokenType.RBRACE);
565
- return list;
660
+ return {
661
+ type: 'BraceGroup',
662
+ list,
663
+ range: start.range
664
+ };
566
665
  }
567
666
  /**
568
667
  * Parse function definition (function name { ... })
@@ -607,9 +706,9 @@ export class Parser {
607
706
  */
608
707
  parseFunctionBody() {
609
708
  if (this.check(TokenType.LPAREN)) {
610
- return this.parseSubshell();
709
+ return this.withRedirects(this.parseSubshell());
611
710
  }
612
- return this.parseBraceGroup();
711
+ return this.withRedirects(this.parseBraceGroup());
613
712
  }
614
713
  /**
615
714
  * Parse compound list (list of commands)
@@ -617,6 +716,7 @@ export class Parser {
617
716
  parseCompoundList() {
618
717
  const commands = [];
619
718
  while (true) {
719
+ this.checkDeadline();
620
720
  this.skipNewlines();
621
721
  // Check for terminators
622
722
  if (this.isAtEnd() ||
@@ -632,18 +732,21 @@ export class Parser {
632
732
  this.check(TokenType.DSEMI)) {
633
733
  break;
634
734
  }
635
- const command = this.parseCommand();
636
- if (command) {
637
- commands.push(command);
735
+ if (this.check(TokenType.COMMENT)) {
736
+ commands.push(this.parseComment());
737
+ continue;
638
738
  }
639
- else {
739
+ const command = this.parseCommand();
740
+ if (!command) {
640
741
  break;
641
742
  }
642
- // Check for separator
743
+ // `cmd &` backgrounds cmd and also separates it from what follows
744
+ const separated = this.applyAsync(command);
745
+ commands.push(command);
643
746
  if (this.check(TokenType.SEMI) || this.check(TokenType.AMP) || this.check(TokenType.NEWLINE)) {
644
747
  this.advance();
645
748
  }
646
- else {
749
+ else if (!separated) {
647
750
  break;
648
751
  }
649
752
  }
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from './types';
2
- export { Lexer, Token, TokenType } from './lexer';
2
+ export { Lexer, LexerOptions, Token, TokenType } from './lexer';
3
3
  export { parse, Parser, ParserOptions } from './parser';
4
4
  export { deparse, Deparser, DeparserOptions, deparseSync } from './deparser';
5
5
  export { cleanTree, compareAst, noop } from './clean';
package/lexer.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Range } from './types';
1
+ import { HereDoc, Range } from './types';
2
2
  /**
3
3
  * Token types for bash lexer
4
4
  */
@@ -43,6 +43,7 @@ export declare enum TokenType {
43
43
  LBRACE = "LBRACE",
44
44
  RBRACE = "RBRACE",
45
45
  IO_NUMBER = "IO_NUMBER",
46
+ COMMENT = "COMMENT",
46
47
  EOF = "EOF",
47
48
  WHITESPACE = "WHITESPACE"
48
49
  }
@@ -53,6 +54,25 @@ export interface Token {
53
54
  type: TokenType;
54
55
  value: string;
55
56
  range: Range;
57
+ /**
58
+ * Body of the here-document introduced by this token. Only ever set on
59
+ * `<<` / `<<-` tokens, and only once the delimiter line has been read.
60
+ */
61
+ heredoc?: HereDoc;
62
+ }
63
+ /**
64
+ * Lexer options
65
+ */
66
+ export interface LexerOptions {
67
+ /**
68
+ * Emit COMMENT tokens instead of discarding comments.
69
+ */
70
+ keepComments?: boolean;
71
+ /**
72
+ * Wall-clock budget for tokenizing, in milliseconds. Exceeding it throws
73
+ * instead of letting a pathological input run unbounded.
74
+ */
75
+ timeoutMs?: number;
56
76
  }
57
77
  /**
58
78
  * Bash Lexer
@@ -62,7 +82,18 @@ export declare class Lexer {
62
82
  private pos;
63
83
  private line;
64
84
  private column;
65
- constructor(input: string);
85
+ private options;
86
+ /**
87
+ * True when the next word would be the command name, i.e. when a leading
88
+ * `NAME=value` word is an assignment rather than an ordinary argument.
89
+ */
90
+ private commandPosition;
91
+ /**
92
+ * True while lexing the arguments of `export`/`local`/`declare`/`readonly`.
93
+ */
94
+ private declarationCommand;
95
+ private pendingHereDocs;
96
+ constructor(input: string, options?: LexerOptions);
66
97
  /**
67
98
  * Get current position
68
99
  */
@@ -88,11 +119,17 @@ export declare class Lexer {
88
119
  */
89
120
  private isDigit;
90
121
  /**
91
- * Check if character can start a word
122
+ * Check if character can be part of a word
92
123
  */
93
124
  private isWordChar;
94
125
  /**
95
- * Skip whitespace (not newlines)
126
+ * Check if a character terminates a token. `{` and `}` are reserved words
127
+ * only when they stand alone; elsewhere they are ordinary word characters
128
+ * (`--set jsonpath={.metadata.name}`, `{1..3}`).
129
+ */
130
+ private isTokenDelimiter;
131
+ /**
132
+ * Skip whitespace and line continuations (not newlines)
96
133
  */
97
134
  private skipWhitespace;
98
135
  /**
@@ -107,6 +144,10 @@ export declare class Lexer {
107
144
  * Read a word token
108
145
  */
109
146
  private readWord;
147
+ /**
148
+ * Read a balanced parenthesised run, including the parens
149
+ */
150
+ private readBalancedParens;
110
151
  /**
111
152
  * Read an expansion ($VAR, ${VAR}, $(cmd), $((expr)))
112
153
  */
@@ -116,13 +157,32 @@ export declare class Lexer {
116
157
  */
117
158
  private readBacktickSubstitution;
118
159
  /**
119
- * Read a comment
160
+ * Read a comment, excluding the leading `#`
120
161
  */
121
162
  private readComment;
163
+ /**
164
+ * Strip one level of quoting from a here-document delimiter
165
+ */
166
+ private unquoteDelimiter;
167
+ /**
168
+ * Read one raw line, consuming its terminating newline
169
+ */
170
+ private readRawLine;
171
+ /**
172
+ * Read the bodies of every here-document pending on the line just ended.
173
+ * A body is opaque text: it is never fed through the command lexer.
174
+ */
175
+ private readPendingHereDocBodies;
176
+ /**
177
+ * Track whether the next word sits in command (assignment) position. `)` is
178
+ * in the list because it closes a case pattern, whose body starts a command.
179
+ */
180
+ private updateContext;
122
181
  /**
123
182
  * Get next token
124
183
  */
125
184
  nextToken(): Token;
185
+ private scanToken;
126
186
  /**
127
187
  * Tokenize entire input
128
188
  */