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/lexer.js CHANGED
@@ -49,6 +49,7 @@ export var TokenType;
49
49
  TokenType["RBRACE"] = "RBRACE";
50
50
  // Special
51
51
  TokenType["IO_NUMBER"] = "IO_NUMBER";
52
+ TokenType["COMMENT"] = "COMMENT";
52
53
  TokenType["EOF"] = "EOF";
53
54
  TokenType["WHITESPACE"] = "WHITESPACE";
54
55
  })(TokenType || (TokenType = {}));
@@ -72,6 +73,17 @@ const RESERVED_WORDS = {
72
73
  function: TokenType.FUNCTION,
73
74
  '!': TokenType.BANG,
74
75
  };
76
+ /**
77
+ * Builtins whose operands are assignments (`export FOO=bar`)
78
+ */
79
+ const DECLARATION_BUILTINS = new Set([
80
+ 'export',
81
+ 'local',
82
+ 'declare',
83
+ 'readonly',
84
+ 'typeset',
85
+ ]);
86
+ const ASSIGNMENT_RE = /^[a-zA-Z_][a-zA-Z0-9_]*(\[[^\]]*\])?\+?=/;
75
87
  /**
76
88
  * Bash Lexer
77
89
  */
@@ -80,8 +92,20 @@ export class Lexer {
80
92
  pos = 0;
81
93
  line = 1;
82
94
  column = 0;
83
- constructor(input) {
95
+ options;
96
+ /**
97
+ * True when the next word would be the command name, i.e. when a leading
98
+ * `NAME=value` word is an assignment rather than an ordinary argument.
99
+ */
100
+ commandPosition = true;
101
+ /**
102
+ * True while lexing the arguments of `export`/`local`/`declare`/`readonly`.
103
+ */
104
+ declarationCommand = false;
105
+ pendingHereDocs = [];
106
+ constructor(input, options = {}) {
84
107
  this.input = input;
108
+ this.options = options;
85
109
  }
86
110
  /**
87
111
  * Get current position
@@ -124,7 +148,7 @@ export class Lexer {
124
148
  * Check if character is whitespace (not newline)
125
149
  */
126
150
  isWhitespace(char) {
127
- return char === ' ' || char === '\t';
151
+ return char === ' ' || char === '\t' || char === '\r';
128
152
  }
129
153
  /**
130
154
  * Check if character is a digit
@@ -133,7 +157,7 @@ export class Lexer {
133
157
  return char >= '0' && char <= '9';
134
158
  }
135
159
  /**
136
- * Check if character can start a word
160
+ * Check if character can be part of a word
137
161
  */
138
162
  isWordChar(char) {
139
163
  return char !== '' &&
@@ -145,16 +169,40 @@ export class Lexer {
145
169
  char !== '(' &&
146
170
  char !== ')' &&
147
171
  char !== '<' &&
148
- char !== '>' &&
149
- char !== '{' &&
150
- char !== '}';
172
+ char !== '>';
151
173
  }
152
174
  /**
153
- * Skip whitespace (not newlines)
175
+ * Check if a character terminates a token. `{` and `}` are reserved words
176
+ * only when they stand alone; elsewhere they are ordinary word characters
177
+ * (`--set jsonpath={.metadata.name}`, `{1..3}`).
178
+ */
179
+ isTokenDelimiter(char) {
180
+ return char === '' ||
181
+ this.isWhitespace(char) ||
182
+ char === '\n' ||
183
+ char === ';' ||
184
+ char === '&' ||
185
+ char === '|' ||
186
+ char === '(' ||
187
+ char === ')' ||
188
+ char === '<' ||
189
+ char === '>';
190
+ }
191
+ /**
192
+ * Skip whitespace and line continuations (not newlines)
154
193
  */
155
194
  skipWhitespace() {
156
- while (!this.isAtEnd() && this.isWhitespace(this.peek())) {
157
- this.advance();
195
+ while (!this.isAtEnd()) {
196
+ if (this.isWhitespace(this.peek())) {
197
+ this.advance();
198
+ }
199
+ else if (this.peek() === '\\' && this.peek(1) === '\n') {
200
+ this.advance();
201
+ this.advance();
202
+ }
203
+ else {
204
+ break;
205
+ }
158
206
  }
159
207
  }
160
208
  /**
@@ -205,6 +253,12 @@ export class Lexer {
205
253
  result += this.readDoubleQuoted();
206
254
  }
207
255
  else if (char === '\\') {
256
+ if (this.peek(1) === '\n') {
257
+ // line continuation: removed, the word continues on the next line
258
+ this.advance();
259
+ this.advance();
260
+ continue;
261
+ }
208
262
  result += this.advance(); // backslash
209
263
  if (!this.isAtEnd()) {
210
264
  result += this.advance(); // escaped char
@@ -216,12 +270,39 @@ export class Lexer {
216
270
  else if (char === '`') {
217
271
  result += this.readBacktickSubstitution();
218
272
  }
273
+ else if ((char === '{' || char === '}') && result === '' && this.isTokenDelimiter(this.peek(1))) {
274
+ break;
275
+ }
219
276
  else {
220
277
  result += this.advance();
221
278
  }
222
279
  }
223
280
  return result;
224
281
  }
282
+ /**
283
+ * Read a balanced parenthesised run, including the parens
284
+ */
285
+ readBalancedParens() {
286
+ let result = this.advance(); // (
287
+ let depth = 1;
288
+ while (!this.isAtEnd() && depth > 0) {
289
+ const char = this.peek();
290
+ if (char === "'") {
291
+ result += this.readSingleQuoted();
292
+ continue;
293
+ }
294
+ if (char === '"') {
295
+ result += this.readDoubleQuoted();
296
+ continue;
297
+ }
298
+ if (char === '(')
299
+ depth++;
300
+ if (char === ')')
301
+ depth--;
302
+ result += this.advance();
303
+ }
304
+ return result;
305
+ }
225
306
  /**
226
307
  * Read an expansion ($VAR, ${VAR}, $(cmd), $((expr)))
227
308
  */
@@ -243,15 +324,7 @@ export class Lexer {
243
324
  }
244
325
  else {
245
326
  // Command substitution $(cmd)
246
- result += this.advance(); // (
247
- let depth = 1;
248
- while (!this.isAtEnd() && depth > 0) {
249
- if (this.peek() === '(')
250
- depth++;
251
- if (this.peek() === ')')
252
- depth--;
253
- result += this.advance();
254
- }
327
+ result += this.readBalancedParens();
255
328
  }
256
329
  }
257
330
  else if (this.peek() === '{') {
@@ -296,17 +369,128 @@ export class Lexer {
296
369
  return result;
297
370
  }
298
371
  /**
299
- * Read a comment
372
+ * Read a comment, excluding the leading `#`
300
373
  */
301
374
  readComment() {
375
+ this.advance(); // #
376
+ let result = '';
302
377
  while (!this.isAtEnd() && this.peek() !== '\n') {
378
+ result += this.advance();
379
+ }
380
+ return result;
381
+ }
382
+ /**
383
+ * Strip one level of quoting from a here-document delimiter
384
+ */
385
+ unquoteDelimiter(word) {
386
+ if (word.length >= 2 && ((word.startsWith("'") && word.endsWith("'")) || (word.startsWith('"') && word.endsWith('"')))) {
387
+ return { delimiter: word.slice(1, -1), quoted: true };
388
+ }
389
+ if (word.includes('\\')) {
390
+ return { delimiter: word.replace(/\\(.)/g, '$1'), quoted: true };
391
+ }
392
+ return { delimiter: word, quoted: false };
393
+ }
394
+ /**
395
+ * Read one raw line, consuming its terminating newline
396
+ */
397
+ readRawLine() {
398
+ let text = '';
399
+ while (!this.isAtEnd() && this.peek() !== '\n') {
400
+ text += this.advance();
401
+ }
402
+ const terminated = this.peek() === '\n';
403
+ if (terminated) {
303
404
  this.advance();
304
405
  }
406
+ return { text, terminated };
407
+ }
408
+ /**
409
+ * Read the bodies of every here-document pending on the line just ended.
410
+ * A body is opaque text: it is never fed through the command lexer.
411
+ */
412
+ readPendingHereDocBodies() {
413
+ const pending = this.pendingHereDocs;
414
+ this.pendingHereDocs = [];
415
+ for (const entry of pending) {
416
+ if (entry.delimiter === undefined)
417
+ continue;
418
+ let content = '';
419
+ for (;;) {
420
+ if (this.isAtEnd())
421
+ break;
422
+ const startOfLine = this.pos;
423
+ const { text, terminated } = this.readRawLine();
424
+ const candidate = entry.dash ? text.replace(/^[\t]+/, '') : text;
425
+ if (candidate === entry.delimiter) {
426
+ break;
427
+ }
428
+ if (!terminated && this.isAtEnd() && startOfLine === this.pos) {
429
+ break;
430
+ }
431
+ content += text + '\n';
432
+ if (!terminated)
433
+ break;
434
+ }
435
+ entry.token.heredoc = {
436
+ type: 'HereDoc',
437
+ delimiter: entry.delimiter,
438
+ content,
439
+ quoted: entry.quoted || undefined
440
+ };
441
+ }
442
+ }
443
+ /**
444
+ * Track whether the next word sits in command (assignment) position. `)` is
445
+ * in the list because it closes a case pattern, whose body starts a command.
446
+ */
447
+ updateContext(token) {
448
+ switch (token.type) {
449
+ case TokenType.NEWLINE:
450
+ case TokenType.SEMI:
451
+ case TokenType.DSEMI:
452
+ case TokenType.AMP:
453
+ case TokenType.PIPE:
454
+ case TokenType.AND_IF:
455
+ case TokenType.OR_IF:
456
+ case TokenType.LBRACE:
457
+ case TokenType.LPAREN:
458
+ case TokenType.RPAREN:
459
+ case TokenType.BANG:
460
+ case TokenType.IF:
461
+ case TokenType.THEN:
462
+ case TokenType.ELSE:
463
+ case TokenType.ELIF:
464
+ case TokenType.WHILE:
465
+ case TokenType.UNTIL:
466
+ case TokenType.DO:
467
+ this.commandPosition = true;
468
+ this.declarationCommand = false;
469
+ break;
470
+ case TokenType.ASSIGNMENT_WORD:
471
+ case TokenType.COMMENT:
472
+ break;
473
+ case TokenType.WORD:
474
+ if (this.commandPosition && DECLARATION_BUILTINS.has(token.value)) {
475
+ this.declarationCommand = true;
476
+ }
477
+ this.commandPosition = false;
478
+ break;
479
+ default:
480
+ this.commandPosition = false;
481
+ this.declarationCommand = false;
482
+ break;
483
+ }
305
484
  }
306
485
  /**
307
486
  * Get next token
308
487
  */
309
488
  nextToken() {
489
+ const token = this.scanToken();
490
+ this.updateContext(token);
491
+ return token;
492
+ }
493
+ scanToken() {
310
494
  this.skipWhitespace();
311
495
  if (this.isAtEnd()) {
312
496
  return {
@@ -319,17 +503,28 @@ export class Lexer {
319
503
  const char = this.peek();
320
504
  // Comment
321
505
  if (char === '#') {
322
- this.readComment();
323
- return this.nextToken();
506
+ const text = this.readComment();
507
+ if (this.options.keepComments) {
508
+ return {
509
+ type: TokenType.COMMENT,
510
+ value: text,
511
+ range: { start, end: this.getPosition() }
512
+ };
513
+ }
514
+ return this.scanToken();
324
515
  }
325
- // Newline
516
+ // Newline — here-document bodies start right after it
326
517
  if (char === '\n') {
327
518
  this.advance();
328
- return {
519
+ const token = {
329
520
  type: TokenType.NEWLINE,
330
521
  value: '\n',
331
522
  range: { start, end: this.getPosition() }
332
523
  };
524
+ if (this.pendingHereDocs.length > 0) {
525
+ this.readPendingHereDocBodies();
526
+ }
527
+ return token;
333
528
  }
334
529
  // Operators
335
530
  if (char === '|') {
@@ -346,6 +541,15 @@ export class Lexer {
346
541
  this.advance();
347
542
  return { type: TokenType.AND_IF, value: '&&', range: { start, end: this.getPosition() } };
348
543
  }
544
+ if (this.peek() === '>') {
545
+ // `&>file` — redirect both streams; lexed as a word-carrying redirect
546
+ this.advance();
547
+ if (this.peek() === '>') {
548
+ this.advance();
549
+ return { type: TokenType.WORD, value: '&>>', range: { start, end: this.getPosition() } };
550
+ }
551
+ return { type: TokenType.WORD, value: '&>', range: { start, end: this.getPosition() } };
552
+ }
349
553
  return { type: TokenType.AMP, value: '&', range: { start, end: this.getPosition() } };
350
554
  }
351
555
  if (char === ';') {
@@ -356,6 +560,12 @@ export class Lexer {
356
560
  }
357
561
  return { type: TokenType.SEMI, value: ';', range: { start, end: this.getPosition() } };
358
562
  }
563
+ // Process substitution — a word, not a redirection
564
+ if ((char === '<' || char === '>') && this.peek(1) === '(') {
565
+ const op = this.advance();
566
+ const body = this.readBalancedParens();
567
+ return { type: TokenType.WORD, value: op + body, range: { start, end: this.getPosition() } };
568
+ }
359
569
  // Redirections
360
570
  if (char === '<') {
361
571
  this.advance();
@@ -363,13 +573,17 @@ export class Lexer {
363
573
  this.advance();
364
574
  if (this.peek() === '-') {
365
575
  this.advance();
366
- return { type: TokenType.DLESSDASH, value: '<<-', range: { start, end: this.getPosition() } };
576
+ const token = { type: TokenType.DLESSDASH, value: '<<-', range: { start, end: this.getPosition() } };
577
+ this.pendingHereDocs.push({ token, dash: true });
578
+ return token;
367
579
  }
368
580
  if (this.peek() === '<') {
369
581
  this.advance();
370
582
  return { type: TokenType.TLESS, value: '<<<', range: { start, end: this.getPosition() } };
371
583
  }
372
- return { type: TokenType.DLESS, value: '<<', range: { start, end: this.getPosition() } };
584
+ const token = { type: TokenType.DLESS, value: '<<', range: { start, end: this.getPosition() } };
585
+ this.pendingHereDocs.push({ token, dash: false });
586
+ return token;
373
587
  }
374
588
  if (this.peek() === '&') {
375
589
  this.advance();
@@ -397,6 +611,19 @@ export class Lexer {
397
611
  }
398
612
  return { type: TokenType.GREAT, value: '>', range: { start, end: this.getPosition() } };
399
613
  }
614
+ // Arithmetic command `((expr))` — a word, not two subshells
615
+ if (char === '(' && this.peek(1) === '(') {
616
+ const text = this.readBalancedParens();
617
+ if (text.startsWith('((') && text.endsWith('))')) {
618
+ return { type: TokenType.WORD, value: text, range: { start, end: this.getPosition() } };
619
+ }
620
+ // not an arithmetic command after all: re-lex what we consumed
621
+ this.pos = start.offset;
622
+ this.line = start.line;
623
+ this.column = start.column;
624
+ this.advance();
625
+ return { type: TokenType.LPAREN, value: '(', range: { start, end: this.getPosition() } };
626
+ }
400
627
  // Grouping
401
628
  if (char === '(') {
402
629
  this.advance();
@@ -406,11 +633,11 @@ export class Lexer {
406
633
  this.advance();
407
634
  return { type: TokenType.RPAREN, value: ')', range: { start, end: this.getPosition() } };
408
635
  }
409
- if (char === '{') {
636
+ if (char === '{' && this.isTokenDelimiter(this.peek(1))) {
410
637
  this.advance();
411
638
  return { type: TokenType.LBRACE, value: '{', range: { start, end: this.getPosition() } };
412
639
  }
413
- if (char === '}') {
640
+ if (char === '}' && this.isTokenDelimiter(this.peek(1))) {
414
641
  this.advance();
415
642
  return { type: TokenType.RBRACE, value: '}', range: { start, end: this.getPosition() } };
416
643
  }
@@ -420,15 +647,27 @@ export class Lexer {
420
647
  return { type: TokenType.IO_NUMBER, value: num, range: { start, end: this.getPosition() } };
421
648
  }
422
649
  // Word
423
- const word = this.readWord();
424
- const end = this.getPosition();
650
+ let word = this.readWord();
425
651
  // Check for reserved words
426
652
  if (word in RESERVED_WORDS) {
427
- return { type: RESERVED_WORDS[word], value: word, range: { start, end } };
653
+ return { type: RESERVED_WORDS[word], value: word, range: { start, end: this.getPosition() } };
428
654
  }
429
- // Check for assignment word (NAME=VALUE)
430
- if (word.includes('=') && /^[a-zA-Z_][a-zA-Z0-9_]*=/.test(word)) {
431
- return { type: TokenType.ASSIGNMENT_WORD, value: word, range: { start, end } };
655
+ // Assignment words only exist in assignment position: before the command
656
+ // name, or as an operand of export/local/declare/readonly.
657
+ if ((this.commandPosition || this.declarationCommand) && ASSIGNMENT_RE.test(word)) {
658
+ if (word.endsWith('=') && this.peek() === '(') {
659
+ // array assignment: arr=(a b c)
660
+ word += this.readBalancedParens();
661
+ }
662
+ return { type: TokenType.ASSIGNMENT_WORD, value: word, range: { start, end: this.getPosition() } };
663
+ }
664
+ const end = this.getPosition();
665
+ // A here-document delimiter is the word right after the operator
666
+ const awaiting = this.pendingHereDocs.find(entry => entry.delimiter === undefined);
667
+ if (awaiting) {
668
+ const { delimiter, quoted } = this.unquoteDelimiter(word);
669
+ awaiting.delimiter = delimiter;
670
+ awaiting.quoted = quoted;
432
671
  }
433
672
  return { type: TokenType.WORD, value: word, range: { start, end } };
434
673
  }
@@ -436,9 +675,15 @@ export class Lexer {
436
675
  * Tokenize entire input
437
676
  */
438
677
  tokenize() {
678
+ const deadline = this.options.timeoutMs === undefined
679
+ ? undefined
680
+ : Date.now() + this.options.timeoutMs;
439
681
  const tokens = [];
440
682
  let token;
441
683
  do {
684
+ if (deadline !== undefined && Date.now() > deadline) {
685
+ throw new Error(`bash-ast: tokenizing exceeded ${this.options.timeoutMs}ms at line ${this.line}, column ${this.column}`);
686
+ }
442
687
  token = this.nextToken();
443
688
  tokens.push(token);
444
689
  } while (token.type !== TokenType.EOF);