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/esm/deparser.js CHANGED
@@ -3,7 +3,11 @@
3
3
  */
4
4
  export class Deparser {
5
5
  options;
6
- indentLevel = 0;
6
+ /**
7
+ * Here-document bodies owed by the statement currently being deparsed. They
8
+ * are emitted after the line that opened them.
9
+ */
10
+ heredocs = [];
7
11
  constructor(options = {}) {
8
12
  this.options = {
9
13
  newline: '\n',
@@ -19,54 +23,49 @@ export class Deparser {
19
23
  switch (node.type) {
20
24
  case 'Script':
21
25
  return this.deparseScript(node);
22
- case 'SimpleCommand':
23
- return this.deparseSimpleCommand(node);
24
- case 'Pipeline':
25
- return this.deparsePipeline(node);
26
- case 'LogicalExpression':
27
- return this.deparseLogicalExpression(node);
28
- case 'Subshell':
29
- return this.deparseSubshell(node);
30
- case 'CompoundList':
31
- return this.deparseCompoundList(node);
32
- case 'IfClause':
33
- return this.deparseIf(node);
34
- case 'WhileClause':
35
- return this.deparseWhile(node);
36
- case 'UntilClause':
37
- return this.deparseUntil(node);
38
- case 'ForClause':
39
- return this.deparseFor(node);
40
- case 'CaseClause':
41
- return this.deparseCase(node);
42
- case 'FunctionDefinition':
43
- return this.deparseFunction(node);
44
26
  case 'Word':
45
27
  return this.deparseWord(node);
46
28
  case 'AssignmentWord':
47
29
  return node.text;
48
30
  case 'Redirect':
49
31
  return this.deparseRedirect(node);
32
+ case 'CaseItem':
33
+ return this.deparseCaseItem(node);
34
+ case 'HereDoc': {
35
+ const heredoc = node;
36
+ return heredoc.content + heredoc.delimiter;
37
+ }
50
38
  default:
51
- throw new Error(`Unknown node type: ${node.type}`);
39
+ return this.emitStatement(node);
52
40
  }
53
41
  }
54
42
  throw new Error('Invalid node');
55
43
  }
56
- /**
57
- * Get current indentation
58
- */
59
- getIndent() {
60
- return this.options.indent.repeat(this.indentLevel);
61
- }
62
44
  /**
63
45
  * Deparse script
64
46
  */
65
47
  deparseScript(script) {
66
48
  return script.commands
67
- .map(cmd => this.deparseCommand(cmd))
49
+ .map(cmd => this.emitStatement(cmd))
68
50
  .join(this.options.newline);
69
51
  }
52
+ /**
53
+ * Deparse one statement: the command itself, its `&`, and the bodies of any
54
+ * here-documents it opened.
55
+ */
56
+ emitStatement(command) {
57
+ const owed = this.heredocs;
58
+ this.heredocs = [];
59
+ let text = this.deparseCommand(command);
60
+ if (command.async) {
61
+ text += ' &';
62
+ }
63
+ if (this.heredocs.length > 0) {
64
+ text += '\n' + this.heredocs.join('\n');
65
+ }
66
+ this.heredocs = owed;
67
+ return text;
68
+ }
70
69
  /**
71
70
  * Deparse any command
72
71
  */
@@ -80,8 +79,12 @@ export class Deparser {
80
79
  return this.deparseLogicalExpression(command);
81
80
  case 'Subshell':
82
81
  return this.deparseSubshell(command);
82
+ case 'BraceGroup':
83
+ return this.deparseBraceGroup(command);
83
84
  case 'CompoundList':
84
- return this.deparseCompoundList(command);
85
+ return this.deparseList(command).text;
86
+ case 'Comment':
87
+ return this.deparseComment(command);
85
88
  case 'IfClause':
86
89
  return this.deparseIf(command);
87
90
  case 'WhileClause':
@@ -98,6 +101,18 @@ export class Deparser {
98
101
  throw new Error(`Unknown command type: ${command.type}`);
99
102
  }
100
103
  }
104
+ /**
105
+ * Deparse a list of commands, keeping it on one line when that is safe
106
+ */
107
+ deparseList(list) {
108
+ const parts = list.commands.map(cmd => this.emitStatement(cmd));
109
+ const multiline = parts.some(part => part.includes('\n') || part.endsWith('&')) ||
110
+ list.commands.some(cmd => cmd.type === 'Comment');
111
+ return {
112
+ text: parts.join(multiline ? '\n' : '; '),
113
+ multiline
114
+ };
115
+ }
101
116
  /**
102
117
  * Deparse simple command
103
118
  */
@@ -116,8 +131,8 @@ export class Deparser {
116
131
  // Suffix (arguments and redirections)
117
132
  if (cmd.suffix) {
118
133
  for (const item of cmd.suffix) {
119
- if (item.type === 'Word') {
120
- parts.push(this.deparseWord(item));
134
+ if (item.type === 'Word' || item.type === 'AssignmentWord') {
135
+ parts.push(item.text);
121
136
  }
122
137
  else if (item.type === 'Redirect') {
123
138
  parts.push(this.deparseRedirect(item));
@@ -133,7 +148,14 @@ export class Deparser {
133
148
  return word.text;
134
149
  }
135
150
  /**
136
- * Deparse redirect
151
+ * Deparse comment
152
+ */
153
+ deparseComment(comment) {
154
+ return `#${comment.text}`;
155
+ }
156
+ /**
157
+ * Deparse redirect. A here-document's body is owed to the end of the
158
+ * statement, so it is buffered rather than returned.
137
159
  */
138
160
  deparseRedirect(redirect) {
139
161
  let result = '';
@@ -144,8 +166,25 @@ export class Deparser {
144
166
  if (redirect.file) {
145
167
  result += this.deparseWord(redirect.file);
146
168
  }
169
+ else if (redirect.heredoc) {
170
+ result += redirect.heredoc.quoted
171
+ ? `'${redirect.heredoc.delimiter}'`
172
+ : redirect.heredoc.delimiter;
173
+ }
174
+ if (redirect.heredoc) {
175
+ this.heredocs.push(redirect.heredoc.content + redirect.heredoc.delimiter);
176
+ }
147
177
  return result;
148
178
  }
179
+ /**
180
+ * Deparse the redirections attached to a compound command
181
+ */
182
+ deparseRedirects(redirects) {
183
+ if (!redirects || redirects.length === 0) {
184
+ return '';
185
+ }
186
+ return ' ' + redirects.map(redirect => this.deparseRedirect(redirect)).join(' ');
187
+ }
149
188
  /**
150
189
  * Deparse pipeline
151
190
  */
@@ -171,104 +210,130 @@ export class Deparser {
171
210
  * Deparse subshell
172
211
  */
173
212
  deparseSubshell(subshell) {
174
- const list = this.deparseCompoundListInline(subshell.list);
175
- return `(${list})`;
213
+ const list = this.deparseList(subshell.list);
214
+ const body = list.multiline ? `(\n${list.text}\n)` : `(${list.text})`;
215
+ return body + this.deparseRedirects(subshell.redirects);
176
216
  }
177
217
  /**
178
- * Deparse compound list
218
+ * Deparse brace group. The braces are always emitted: they are what keeps
219
+ * the group a single command inside a pipeline or after `&&`/`||`.
179
220
  */
180
- deparseCompoundList(list) {
181
- return list.commands
182
- .map(cmd => this.deparseCommand(cmd))
183
- .join('; ');
221
+ deparseBraceGroup(group) {
222
+ const list = this.deparseList(group.list);
223
+ const body = list.multiline ? `{\n${list.text}\n}` : `{ ${list.text}; }`;
224
+ return body + this.deparseRedirects(group.redirects);
184
225
  }
185
226
  /**
186
- * Deparse compound list inline (for subshells, etc.)
227
+ * Render `<keyword> <list><separator><terminator>`, breaking the line when
228
+ * the list cannot be inlined
187
229
  */
188
- deparseCompoundListInline(list) {
189
- return list.commands
190
- .map(cmd => this.deparseCommand(cmd))
191
- .join('; ');
230
+ clause(keyword, list, terminator) {
231
+ if (list.multiline) {
232
+ return `${keyword} ${list.text}\n${terminator}`;
233
+ }
234
+ return `${keyword} ${list.text}; ${terminator}`;
192
235
  }
193
236
  /**
194
237
  * Deparse if clause
195
238
  */
196
- deparseIf(ifClause) {
197
- const parts = [];
198
- parts.push('if');
199
- parts.push(this.deparseCompoundListInline(ifClause.condition));
200
- parts.push('; then');
201
- parts.push(this.deparseCompoundListInline(ifClause.then));
239
+ deparseIf(ifClause, keyword = 'if') {
240
+ const condition = this.deparseList(ifClause.condition);
241
+ const then = this.deparseList(ifClause.then);
242
+ let elseText;
243
+ let elseMultiline = false;
202
244
  if (ifClause.else) {
203
245
  if (ifClause.else.type === 'IfClause') {
204
- // elif
205
- parts.push('; el' + this.deparseIf(ifClause.else).substring(0));
206
- return parts.join(' ').replace('; elif', '; elif').replace('; fi; fi', '; fi');
246
+ elseText = this.deparseIf(ifClause.else, 'elif');
247
+ elseMultiline = elseText.includes('\n');
207
248
  }
208
249
  else {
209
- parts.push('; else');
210
- parts.push(this.deparseCompoundListInline(ifClause.else));
250
+ const elseList = this.deparseList(ifClause.else);
251
+ elseText = elseList.text;
252
+ elseMultiline = elseList.multiline;
211
253
  }
212
254
  }
213
- parts.push('; fi');
214
- return parts.join(' ');
255
+ const multiline = condition.multiline || then.multiline || elseMultiline;
256
+ const isElif = keyword === 'elif';
257
+ if (!multiline) {
258
+ const parts = [`${this.clause(keyword, condition, 'then')} ${then.text}`];
259
+ if (elseText !== undefined) {
260
+ parts.push(ifClause.else.type === 'IfClause' ? elseText : `else ${elseText}`);
261
+ }
262
+ const body = parts.join('; ');
263
+ return isElif ? body : `${body}; fi`;
264
+ }
265
+ const parts = [`${this.clause(keyword, condition, 'then')}\n${then.text}`];
266
+ if (elseText !== undefined) {
267
+ parts.push(ifClause.else.type === 'IfClause' ? elseText : `else\n${elseText}`);
268
+ }
269
+ const body = parts.join('\n');
270
+ return isElif ? body : `${body}\nfi`;
215
271
  }
216
272
  /**
217
273
  * Deparse while clause
218
274
  */
219
275
  deparseWhile(whileClause) {
220
- const condition = this.deparseCompoundListInline(whileClause.condition);
221
- const body = this.deparseCompoundListInline(whileClause.body);
222
- return `while ${condition}; do ${body}; done`;
276
+ return this.deparseLoop('while', whileClause.condition, whileClause.body) +
277
+ this.deparseRedirects(whileClause.redirects);
223
278
  }
224
279
  /**
225
280
  * Deparse until clause
226
281
  */
227
282
  deparseUntil(untilClause) {
228
- const condition = this.deparseCompoundListInline(untilClause.condition);
229
- const body = this.deparseCompoundListInline(untilClause.body);
230
- return `until ${condition}; do ${body}; done`;
283
+ return this.deparseLoop('until', untilClause.condition, untilClause.body) +
284
+ this.deparseRedirects(untilClause.redirects);
285
+ }
286
+ /**
287
+ * Deparse `while`/`until`
288
+ */
289
+ deparseLoop(keyword, conditionList, bodyList) {
290
+ const condition = this.deparseList(conditionList);
291
+ const body = this.deparseList(bodyList);
292
+ if (!condition.multiline && !body.multiline) {
293
+ return `${keyword} ${condition.text}; do ${body.text}; done`;
294
+ }
295
+ return `${this.clause(keyword, condition, 'do')}\n${body.text}\ndone`;
231
296
  }
232
297
  /**
233
298
  * Deparse for clause
234
299
  */
235
300
  deparseFor(forClause) {
236
- const parts = ['for', forClause.name];
301
+ let head = `for ${forClause.name}`;
237
302
  if (forClause.wordlist && forClause.wordlist.length > 0) {
238
- parts.push('in');
239
- parts.push(forClause.wordlist.map(w => this.deparseWord(w)).join(' '));
303
+ head += ` in ${forClause.wordlist.map(word => this.deparseWord(word)).join(' ')}`;
240
304
  }
241
- parts.push(';');
242
- parts.push('do');
243
- parts.push(this.deparseCompoundListInline(forClause.body));
244
- parts.push(';');
245
- parts.push('done');
246
- return parts.join(' ');
305
+ const body = this.deparseList(forClause.body);
306
+ const text = body.multiline
307
+ ? `${head}; do\n${body.text}\ndone`
308
+ : `${head}; do ${body.text}; done`;
309
+ return text + this.deparseRedirects(forClause.redirects);
247
310
  }
248
311
  /**
249
312
  * Deparse case clause
250
313
  */
251
314
  deparseCase(caseClause) {
252
- const parts = [];
253
- parts.push('case');
254
- parts.push(this.deparseWord(caseClause.word));
255
- parts.push('in');
256
- for (const caseItem of caseClause.cases) {
257
- parts.push(this.deparseCaseItem(caseItem));
258
- }
259
- parts.push('esac');
260
- return parts.join(' ');
315
+ const items = caseClause.cases.map(item => this.deparseCaseItem(item));
316
+ const multiline = items.some(item => item.includes('\n'));
317
+ const head = `case ${this.deparseWord(caseClause.word)} in`;
318
+ const text = multiline
319
+ ? `${head}\n${items.join('\n')}\nesac`
320
+ : [head, ...items, 'esac'].join(' ');
321
+ return text + this.deparseRedirects(caseClause.redirects);
261
322
  }
262
323
  /**
263
324
  * Deparse case item
264
325
  */
265
326
  deparseCaseItem(caseItem) {
266
- const pattern = caseItem.pattern.map(w => this.deparseWord(w)).join('|');
327
+ const pattern = caseItem.pattern.map(word => this.deparseWord(word)).join('|');
267
328
  let result = `${pattern})`;
268
329
  if (caseItem.body) {
269
- result += ' ' + this.deparseCompoundListInline(caseItem.body);
330
+ const body = this.deparseList(caseItem.body);
331
+ result += body.multiline ? `\n${body.text}\n` : ` ${body.text} `;
332
+ }
333
+ else {
334
+ result += ' ';
270
335
  }
271
- result += ' ;;';
336
+ result += ';;';
272
337
  return result;
273
338
  }
274
339
  /**
@@ -277,7 +342,7 @@ export class Deparser {
277
342
  deparseFunction(func) {
278
343
  const body = func.body.type === 'Subshell'
279
344
  ? this.deparseSubshell(func.body)
280
- : `{ ${this.deparseCompoundListInline(func.body)}; }`;
345
+ : this.deparseBraceGroup(func.body);
281
346
  return `${func.name}() ${body}`;
282
347
  }
283
348
  }