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/parser.js CHANGED
@@ -10,6 +10,7 @@ class Parser {
10
10
  tokens = [];
11
11
  pos = 0;
12
12
  options;
13
+ deadline;
13
14
  constructor(options = {}) {
14
15
  this.options = options;
15
16
  }
@@ -17,23 +18,57 @@ class Parser {
17
18
  * Parse bash source into AST
18
19
  */
19
20
  parse(source) {
20
- const lexer = new lexer_1.Lexer(source);
21
+ const lexer = new lexer_1.Lexer(source, {
22
+ keepComments: this.options.keepComments,
23
+ timeoutMs: this.options.timeoutMs
24
+ });
21
25
  this.tokens = lexer.tokenize();
22
26
  this.pos = 0;
27
+ this.deadline = this.options.timeoutMs === undefined
28
+ ? undefined
29
+ : Date.now() + this.options.timeoutMs;
23
30
  const commands = [];
24
31
  this.skipNewlines();
25
32
  while (!this.isAtEnd()) {
26
- const command = this.parseCommand();
27
- if (command) {
28
- commands.push(command);
33
+ this.checkDeadline();
34
+ const before = this.pos;
35
+ if (this.check(lexer_1.TokenType.COMMENT)) {
36
+ commands.push(this.parseComment());
37
+ }
38
+ else {
39
+ const command = this.parseCommand();
40
+ if (command) {
41
+ this.applyAsync(command);
42
+ commands.push(command);
43
+ }
29
44
  }
30
45
  this.skipNewlinesAndSeparators();
46
+ if (this.pos === before) {
47
+ // Nothing was consumed: the token cannot start a command. Fail loudly
48
+ // rather than spinning forever.
49
+ throw new Error(this.unexpected());
50
+ }
31
51
  }
32
52
  return {
33
53
  type: 'Script',
34
54
  commands
35
55
  };
36
56
  }
57
+ /**
58
+ * Fail if the parse budget is spent
59
+ */
60
+ checkDeadline() {
61
+ if (this.deadline !== undefined && Date.now() > this.deadline) {
62
+ throw new Error(`bash-ast: parsing exceeded ${this.options.timeoutMs}ms at ${this.unexpected()}`);
63
+ }
64
+ }
65
+ /**
66
+ * Error message for the current token
67
+ */
68
+ unexpected() {
69
+ const token = this.peek();
70
+ return `Unexpected ${token.type}${token.value ? ` (${JSON.stringify(token.value)})` : ''} at line ${token.range.start.line}, column ${token.range.start.column}`;
71
+ }
37
72
  /**
38
73
  * Check if at end of tokens
39
74
  */
@@ -72,10 +107,10 @@ class Parser {
72
107
  if (this.check(type)) {
73
108
  return this.advance();
74
109
  }
75
- throw new Error(`Expected ${type}, got ${this.peek().type} at position ${this.pos}`);
110
+ throw new Error(`Expected ${type}, got ${this.peek().type} at line ${this.peek().range.start.line}, column ${this.peek().range.start.column}`);
76
111
  }
77
112
  /**
78
- * Skip newlines
113
+ * Skip newlines (and comments the parser was told to drop)
79
114
  */
80
115
  skipNewlines() {
81
116
  while (this.check(lexer_1.TokenType.NEWLINE)) {
@@ -90,6 +125,28 @@ class Parser {
90
125
  this.advance();
91
126
  }
92
127
  }
128
+ /**
129
+ * Mark a command as asynchronous when it is terminated by `&`
130
+ */
131
+ applyAsync(command) {
132
+ if (this.check(lexer_1.TokenType.AMP)) {
133
+ this.advance();
134
+ command.async = true;
135
+ return true;
136
+ }
137
+ return false;
138
+ }
139
+ /**
140
+ * Parse a comment node
141
+ */
142
+ parseComment() {
143
+ const token = this.expect(lexer_1.TokenType.COMMENT);
144
+ return {
145
+ type: 'Comment',
146
+ text: token.value,
147
+ range: token.range
148
+ };
149
+ }
93
150
  /**
94
151
  * Parse a command (handles logical operators)
95
152
  */
@@ -180,19 +237,19 @@ class Parser {
180
237
  const token = this.peek();
181
238
  switch (token.type) {
182
239
  case lexer_1.TokenType.IF:
183
- return this.parseIf();
240
+ return this.withRedirects(this.parseIf());
184
241
  case lexer_1.TokenType.WHILE:
185
- return this.parseWhile();
242
+ return this.withRedirects(this.parseWhile());
186
243
  case lexer_1.TokenType.UNTIL:
187
- return this.parseUntil();
244
+ return this.withRedirects(this.parseUntil());
188
245
  case lexer_1.TokenType.FOR:
189
- return this.parseFor();
246
+ return this.withRedirects(this.parseFor());
190
247
  case lexer_1.TokenType.CASE:
191
- return this.parseCase();
248
+ return this.withRedirects(this.parseCase());
192
249
  case lexer_1.TokenType.LPAREN:
193
- return this.parseSubshell();
250
+ return this.withRedirects(this.parseSubshell());
194
251
  case lexer_1.TokenType.LBRACE:
195
- return this.parseBraceGroup();
252
+ return this.withRedirects(this.parseBraceGroup());
196
253
  case lexer_1.TokenType.FUNCTION:
197
254
  return this.parseFunction();
198
255
  default:
@@ -203,6 +260,22 @@ class Parser {
203
260
  return this.parseSimpleCommand();
204
261
  }
205
262
  }
263
+ /**
264
+ * Attach the redirections that follow a compound command (`{ … } > file`)
265
+ */
266
+ withRedirects(command) {
267
+ const redirects = [];
268
+ while (this.isRedirectOp()) {
269
+ const redirect = this.parseRedirect();
270
+ if (!redirect)
271
+ break;
272
+ redirects.push(redirect);
273
+ }
274
+ if (redirects.length > 0) {
275
+ command.redirects = redirects;
276
+ }
277
+ return command;
278
+ }
206
279
  /**
207
280
  * Parse simple command
208
281
  */
@@ -249,6 +322,15 @@ class Parser {
249
322
  range: token.range
250
323
  });
251
324
  }
325
+ else if (this.check(lexer_1.TokenType.ASSIGNMENT_WORD)) {
326
+ // operand of export/local/declare/readonly
327
+ const token = this.advance();
328
+ suffix.push({
329
+ type: 'AssignmentWord',
330
+ text: token.value,
331
+ range: token.range
332
+ });
333
+ }
252
334
  else {
253
335
  break;
254
336
  }
@@ -326,27 +408,27 @@ class Parser {
326
408
  return null;
327
409
  }
328
410
  this.advance();
329
- // Parse file/word
330
- if (this.check(lexer_1.TokenType.WORD)) {
331
- const fileToken = this.advance();
332
- return {
333
- type: 'Redirect',
334
- op,
335
- file: {
336
- type: 'Word',
337
- text: fileToken.value,
338
- range: fileToken.range
339
- },
340
- numberIo,
341
- range: opToken.range
342
- };
343
- }
344
- return {
411
+ const redirect = {
345
412
  type: 'Redirect',
346
413
  op,
347
414
  numberIo,
348
415
  range: opToken.range
349
416
  };
417
+ // The body of a here-document is lexed as opaque text and hangs off the
418
+ // operator token.
419
+ if (opToken.heredoc) {
420
+ redirect.heredoc = opToken.heredoc;
421
+ }
422
+ // Parse file/word (the delimiter, for a here-document)
423
+ if (this.check(lexer_1.TokenType.WORD)) {
424
+ const fileToken = this.advance();
425
+ redirect.file = {
426
+ type: 'Word',
427
+ text: fileToken.value,
428
+ range: fileToken.range
429
+ };
430
+ }
431
+ return redirect;
350
432
  }
351
433
  /**
352
434
  * Parse if clause
@@ -488,11 +570,23 @@ class Parser {
488
570
  this.skipNewlines();
489
571
  const cases = [];
490
572
  while (!this.check(lexer_1.TokenType.ESAC)) {
573
+ if (this.isAtEnd()) {
574
+ throw new Error('Expected esac, got end of input');
575
+ }
576
+ const before = this.pos;
577
+ if (this.check(lexer_1.TokenType.COMMENT)) {
578
+ // a comment between case items has nowhere to live on a CaseClause
579
+ this.advance();
580
+ continue;
581
+ }
491
582
  const caseItem = this.parseCaseItem();
492
583
  if (caseItem) {
493
584
  cases.push(caseItem);
494
585
  }
495
586
  this.skipNewlines();
587
+ if (this.pos === before) {
588
+ throw new Error(this.unexpected());
589
+ }
496
590
  }
497
591
  this.expect(lexer_1.TokenType.ESAC);
498
592
  return {
@@ -559,14 +653,19 @@ class Parser {
559
653
  };
560
654
  }
561
655
  /**
562
- * Parse brace group
656
+ * Parse brace group. A brace group is one compound command: it keeps its
657
+ * grouping through pipelines, `&&`/`||`, `&` and redirection.
563
658
  */
564
659
  parseBraceGroup() {
565
- this.expect(lexer_1.TokenType.LBRACE);
660
+ const start = this.expect(lexer_1.TokenType.LBRACE);
566
661
  this.skipNewlines();
567
662
  const list = this.parseCompoundList();
568
663
  this.expect(lexer_1.TokenType.RBRACE);
569
- return list;
664
+ return {
665
+ type: 'BraceGroup',
666
+ list,
667
+ range: start.range
668
+ };
570
669
  }
571
670
  /**
572
671
  * Parse function definition (function name { ... })
@@ -611,9 +710,9 @@ class Parser {
611
710
  */
612
711
  parseFunctionBody() {
613
712
  if (this.check(lexer_1.TokenType.LPAREN)) {
614
- return this.parseSubshell();
713
+ return this.withRedirects(this.parseSubshell());
615
714
  }
616
- return this.parseBraceGroup();
715
+ return this.withRedirects(this.parseBraceGroup());
617
716
  }
618
717
  /**
619
718
  * Parse compound list (list of commands)
@@ -621,6 +720,7 @@ class Parser {
621
720
  parseCompoundList() {
622
721
  const commands = [];
623
722
  while (true) {
723
+ this.checkDeadline();
624
724
  this.skipNewlines();
625
725
  // Check for terminators
626
726
  if (this.isAtEnd() ||
@@ -636,18 +736,21 @@ class Parser {
636
736
  this.check(lexer_1.TokenType.DSEMI)) {
637
737
  break;
638
738
  }
639
- const command = this.parseCommand();
640
- if (command) {
641
- commands.push(command);
739
+ if (this.check(lexer_1.TokenType.COMMENT)) {
740
+ commands.push(this.parseComment());
741
+ continue;
642
742
  }
643
- else {
743
+ const command = this.parseCommand();
744
+ if (!command) {
644
745
  break;
645
746
  }
646
- // Check for separator
747
+ // `cmd &` backgrounds cmd and also separates it from what follows
748
+ const separated = this.applyAsync(command);
749
+ commands.push(command);
647
750
  if (this.check(lexer_1.TokenType.SEMI) || this.check(lexer_1.TokenType.AMP) || this.check(lexer_1.TokenType.NEWLINE)) {
648
751
  this.advance();
649
752
  }
650
- else {
753
+ else if (!separated) {
651
754
  break;
652
755
  }
653
756
  }
package/types.d.ts CHANGED
@@ -19,6 +19,11 @@ export interface Range {
19
19
  export interface BaseNode {
20
20
  type: string;
21
21
  range?: Range;
22
+ /**
23
+ * Set when the command is terminated by `&` and therefore runs in the
24
+ * background. Only meaningful on command nodes.
25
+ */
26
+ async?: boolean;
22
27
  }
23
28
  /**
24
29
  * Script - root node containing a list of commands
@@ -30,7 +35,7 @@ export interface Script extends BaseNode {
30
35
  /**
31
36
  * Union type for all command types
32
37
  */
33
- export type Command = SimpleCommand | Pipeline | LogicalExpression | Subshell | CompoundList | IfClause | WhileClause | UntilClause | ForClause | CaseClause | FunctionDefinition;
38
+ export type Command = SimpleCommand | Pipeline | LogicalExpression | Subshell | BraceGroup | CompoundList | Comment | IfClause | WhileClause | UntilClause | ForClause | CaseClause | FunctionDefinition;
34
39
  /**
35
40
  * Simple command (e.g., `echo hello`)
36
41
  */
@@ -38,7 +43,14 @@ export interface SimpleCommand extends BaseNode {
38
43
  type: 'SimpleCommand';
39
44
  name?: Word;
40
45
  prefix?: AssignmentWord[];
41
- suffix?: (Word | Redirect)[];
46
+ suffix?: (Word | AssignmentWord | Redirect)[];
47
+ }
48
+ /**
49
+ * Comment (`# ...`), retained only when the parser runs with `keepComments`
50
+ */
51
+ export interface Comment extends BaseNode {
52
+ type: 'Comment';
53
+ text: string;
42
54
  }
43
55
  /**
44
56
  * Word - a token that can be expanded
@@ -131,6 +143,16 @@ export interface LogicalExpression extends BaseNode {
131
143
  export interface Subshell extends BaseNode {
132
144
  type: 'Subshell';
133
145
  list: CompoundList;
146
+ redirects?: Redirect[];
147
+ }
148
+ /**
149
+ * Brace group (e.g., `{ cmd1; cmd2; }`) — a single compound command, so it
150
+ * survives pipelines, `&&`/`||`, `&` and redirection as one unit
151
+ */
152
+ export interface BraceGroup extends BaseNode {
153
+ type: 'BraceGroup';
154
+ list: CompoundList;
155
+ redirects?: Redirect[];
134
156
  }
135
157
  /**
136
158
  * Compound list - a list of commands
@@ -147,6 +169,7 @@ export interface IfClause extends BaseNode {
147
169
  condition: CompoundList;
148
170
  then: CompoundList;
149
171
  else?: CompoundList | IfClause;
172
+ redirects?: Redirect[];
150
173
  }
151
174
  /**
152
175
  * While clause
@@ -155,6 +178,7 @@ export interface WhileClause extends BaseNode {
155
178
  type: 'WhileClause';
156
179
  condition: CompoundList;
157
180
  body: CompoundList;
181
+ redirects?: Redirect[];
158
182
  }
159
183
  /**
160
184
  * Until clause
@@ -163,6 +187,7 @@ export interface UntilClause extends BaseNode {
163
187
  type: 'UntilClause';
164
188
  condition: CompoundList;
165
189
  body: CompoundList;
190
+ redirects?: Redirect[];
166
191
  }
167
192
  /**
168
193
  * For clause
@@ -172,6 +197,7 @@ export interface ForClause extends BaseNode {
172
197
  name: string;
173
198
  wordlist?: Word[];
174
199
  body: CompoundList;
200
+ redirects?: Redirect[];
175
201
  }
176
202
  /**
177
203
  * Case clause
@@ -180,6 +206,7 @@ export interface CaseClause extends BaseNode {
180
206
  type: 'CaseClause';
181
207
  word: Word;
182
208
  cases: CaseItem[];
209
+ redirects?: Redirect[];
183
210
  }
184
211
  /**
185
212
  * Case item
@@ -195,7 +222,7 @@ export interface CaseItem extends BaseNode {
195
222
  export interface FunctionDefinition extends BaseNode {
196
223
  type: 'FunctionDefinition';
197
224
  name: string;
198
- body: CompoundList | Subshell;
225
+ body: BraceGroup | Subshell;
199
226
  }
200
227
  /**
201
228
  * Union type for all AST nodes