-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
415 lines (379 loc) · 14.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
"use strict"
const lustils = require("lustils")
const { parse, defaultOptions } = require("luaparse")
const { read, writer, writeBeautifiedText } = require("luon")
const commentWriter = writer({
string_format: "long_newline"
})
const writeLongText = content => commentWriter.write(content).text
defaultOptions.ranges = true
const _precedency = [["^"], ["unary"], ["*", "/", "%"], ["+", "-"], [".."], ["<", ">", "<=", ">=", "~=", "=="], ["and"], ["or"]]
const precedency = {}
for (let i = 0; i < _precedency.length; i++) {
for (let operator of _precedency[i]) precedency[operator] = _precedency.length - i
}
const commentParents = {
Chunk: "body",
DoStatement: "body",
FunctionDeclaration: "body",
IfClause: "body",
ElseifClause: "body",
ElseClause: "body",
WhileStatement: "body",
RepeatStatement: "body",
ForNumericStatement: "body",
ForGenericStatement: "body",
TableConstructorExpression: "fields"
}
// HACK to make luaparse ranges be from "if" to "end" and not from "if" to "then" for IfClauses
// TODO ensure luaparse behaves strangely only for IfClauses
const fixRanges = node => {
if (node.range) {
if (node.type === "IfStatement") {
for (let i = 0; i < node.clauses.length - 1; i++) {
node.clauses[i].range[1] = node.clauses[i + 1].range[0] - 1
}
node.clauses[node.clauses.length - 1].range[1] = node.range[1]
}
}
for (let key in node) {
let children = node[key]
if (Array.isArray(children)) children.forEach(fixRanges)
else if (children !== null && typeof children === "object" && children.type) fixRanges(children)
}
}
const insertComment = (node, comment) => {
for (let key in node) {
let children = node[key]
if (Array.isArray(children)) {
// TODO binary search, ensure AST is properly sorted for this to work
let comment_parent_index = children.findIndex(
node => node.range && node.range[0] <= comment.range[0] && node.range[1] >= comment.range[1]
)
const comment_parent = comment_parent_index !== -1 && children[comment_parent_index]
if (comment_parent && insertComment(comment_parent, comment)) return true
if (commentParents[node.type] === key) {
if (children.length) {
comment_parent_index = comment_parent
? comment_parent_index
: children.findIndex(node => node.range[0] > comment.range[1])
if (comment_parent_index === -1) comment_parent_index = children.length + 1
// insert comment as own child
node[key].splice(comment_parent_index, 0, comment)
} else {
node[key] = [comment]
}
return true
}
} else if (children !== null && typeof children === "object" && children.type) {
if (insertComment(children, comment)) {
return true
}
}
}
}
const insertComments = chunk => chunk.comments.forEach(comment => insertComment(chunk, comment))
const isBinaryExpression = node => node.type === "LogicalExpression" || node.type === "BinaryExpression"
const indexNoParens = {
Identifier: true,
MemberExpression: true,
IndexExpression: true,
CallStatement: true,
CallExpression: true,
TableCallExpression: true,
StringCallExpression: true
}
const default_conf = {
indent: "\t",
newline: "\n",
extra_newlines: true,
inline: {
block: {
max_exp_length: 60
},
table: {
max_field_count: 3,
max_field_length: 60
}
}
}
Object.freeze(default_conf)
const assertType = (value, type) => {
if (typeof value !== type) throw new TypeError("invalid type")
}
const formatter = conf => {
assertType((conf = conf === undefined ? {} : conf), "object")
conf = lustils.object.complete(conf, default_conf)
let { indent, newline, extra_newlines, inline } = conf
if (!/^\s*$/.test(indent)) throw new Error('"indent" needs to be a string of spacing characters')
const indentationText = number => indent.repeat(number)
if (!{ "\n": true, "\r": true, "\r\n": true }[newline])
throw new Error('"newline" needs to be CR ("\\r"), LF ("\\n"), or CRLF ("\\r\\n")')
const indentationNewline = number => newline + indentationText(number)
assertType(extra_newlines, "boolean")
assertType(inline, "object")
inline = lustils.object.complete(inline, default_conf.inline)
let inline_block = inline.block
let inline_table = inline.table
if (inline_block !== false) {
assertType(inline_block, "object")
inline_block = lustils.object.complete(inline_block, default_conf.inline.block)
assertType(inline_block.max_exp_length, "number")
}
if (inline_table !== false) {
assertType(inline_table, "object")
inline_table = lustils.object.complete(inline_table, default_conf.inline.table)
assertType(inline_table.max_field_count, "number")
assertType(inline_table.max_field_length, "number")
}
const block = (fnc, formatted_body_consumer, trailing_spaces) => {
trailing_spaces = trailing_spaces || !formatted_body_consumer
return (node, indent) => {
const { body } = node
const body_length = body.length
const body_pp = prettyPrint(body, indent + 1)
let body_formatted
if (body_length === 0) body_formatted = " "
else if (
body_length === 1 &&
inline_block &&
body[0].type !== "Comment" &&
body_pp.length <= inline_block.max_exp_length &&
!body_pp.includes(newline)
)
body_formatted = " " + body_pp + (trailing_spaces ? " " : "")
else body_formatted = indentationNewline(indent + 1) + body_pp + (trailing_spaces ? indentationNewline(indent) : "")
return !formatted_body_consumer ? fnc(node, indent) + body_formatted + "end" : fnc(node, indent, body_formatted)
}
}
const mapPrettyPrint = (array, indent) => array.map(node => prettyPrint(node, indent))
const mapPrettyPrintJoin = (array, indent) => mapPrettyPrint(array, indent).join(", ")
const indexPrettyPrint = (node, indent) => {
const { base } = node
const base_formatted = prettyPrint(base, indent)
return indexNoParens[base.type] ? base_formatted : "(" + base_formatted + ")"
}
const AssignmentStatement = (node, indent) =>
mapPrettyPrintJoin(node.variables, indent) + (node.init.length ? " = " + mapPrettyPrintJoin(node.init, indent) : "")
const generateClauseFormatters = trailing_spaces => {
const IfClause = block(
(node, indent, body_formatted) => "if " + prettyPrint(node.condition, indent) + " then" + body_formatted,
true,
trailing_spaces
)
const ElseifClause = (node, indent) => "else" + IfClause(node, indent)
const ElseClause = block((_node, _indent, body_formatted) => "else" + body_formatted, true, true)
return {
IfClause,
ElseifClause,
ElseClause
}
}
const clauseFormatters = generateClauseFormatters()
const clauseFormattersTrailingSpaces = generateClauseFormatters(true)
const BinaryExpression = (node, indent) => {
const { left, right, operator } = node
const op_precedency = precedency[operator]
let left_pp = prettyPrint(left, indent)
let right_pp = prettyPrint(right, indent)
if (isBinaryExpression(left) && precedency[left.operator] < op_precedency) left_pp = "(" + left_pp + ")"
if (
(isBinaryExpression(right) && precedency[right.operator] < op_precedency) ||
(right.operator !== ".." && precedency[right.operator] == op_precedency)
)
right_pp = "(" + right_pp + ")"
return left_pp + " " + operator + " " + right_pp
}
let formatters = {
// comments
Comment: (node, indent) => {
let content = node.value.trim()
if (!node.raw.startsWith("--[") || !content.includes(newline)) return "-- " + content.trim()
return (
"--" +
writeLongText(
indentationText(indent + 1) +
content.replace(/\s*(\r?\n|\r)\s*/g, indentationNewline(indent + 1)) +
indentationNewline(indent)
)
)
},
// various trivial stuff; identifiers, simple statements
Identifier: node => node.name,
Chunk: (node, indent) => prettyPrint(node.body, indent),
LabelStatement: node => "::" + node.label + "::",
GotoStatement: node => "goto " + node.label,
BreakStatement: _ => "break",
ReturnStatement: (node, indent) =>
node.arguments.length === 0 ? "return" : "return " + mapPrettyPrintJoin(node.arguments, indent),
DoStatement: block(() => "do"),
// assignments
AssignmentStatement,
LocalStatement: (node, indent) => "local " + AssignmentStatement(node, indent),
FunctionDeclaration: block(
node =>
(node.isLocal ? "local " : "") +
"function" +
(node.identifier ? " " + prettyPrint(node.identifier) : "") +
"(" +
mapPrettyPrintJoin(node.parameters) +
")"
),
// if-[elseif]-[else] chains
IfStatement: (node, indent) => {
const clauses = node.clauses
let out = ""
const prev_ind = indentationNewline(indent)
for (let i = 0; i < clauses.length; i++) {
const clause = clauses[i]
if (i !== 0) out += prev_ind
out += (i === clauses.length - 1 ? clauseFormattersTrailingSpaces : clauseFormatters)[clause.type](clause, indent)
}
return out + "end"
},
// loops
WhileStatement: block((node, indent) => "while " + prettyPrint(node.condition, indent) + " do"),
RepeatStatement: block(
(node, indent, body_formatted) => "repeat" + body_formatted + "until " + prettyPrint(node.condition, indent),
true,
true
),
ForNumericStatement: block(
node =>
"for " + prettyPrint(node.variable) + " = " + mapPrettyPrintJoin([node.start, node.end, node.step].filter(x => x)) + " do"
),
ForGenericStatement: block(
(node, indent) => "for " + mapPrettyPrintJoin(node.variables) + " in " + mapPrettyPrintJoin(node.iterators, indent) + " do"
),
// operators / expressions / calls
UnaryExpression: (node, indent) => {
const { operator, argument } = node
let argument_pp = prettyPrint(argument, indent)
if (isBinaryExpression(argument) && precedency[argument.operator] < precedency.unary) argument_pp = "(" + argument_pp + ")"
else if (operator === "not" || argument.type === "UnaryExpression") argument_pp = " " + argument_pp
return operator + argument_pp
},
BinaryExpression,
LogicalExpression: BinaryExpression,
CallStatement: (node, indent) => prettyPrint(node.expression, indent),
CallExpression: (node, indent) => {
if (node.arguments.length === 1) {
const argument = node.arguments[0]
if (argument.type === "StringLiteral")
return formatters.StringCallExpression(
{
base: node.base,
argument: argument
},
indent
)
if (argument.type === "TableConstructorExpression")
return formatters.TableCallExpression(
{
base: node.base,
arguments: argument
},
indent
)
}
return prettyPrint(node.base, indent) + "(" + mapPrettyPrintJoin(node.arguments, indent) + ")"
},
StringCallExpression: (node, indent) => prettyPrint(node.base, indent) + prettyPrint(node.argument),
TableCallExpression: (node, indent) => prettyPrint(node.base, indent) + prettyPrint(node.arguments, indent),
TableKey: (node, indent) => "[" + prettyPrint(node.key, indent) + "] = " + prettyPrint(node.value, indent),
TableKeyString: (node, indent) => prettyPrint(node.key, indent) + " = " + prettyPrint(node.value, indent),
TableValue: (node, indent) => prettyPrint(node.value, indent),
TableConstructorExpression: (node, indent) => {
const length = node.fields.length
if (length === 0) return "{}"
indent++
const fields_pp = mapPrettyPrint(node.fields, indent)
const inline =
inline_table &&
length <= inline_table.max_field_count &&
!node.fields.find(field => field.type === "Comment") &&
!fields_pp.find(formatted => formatted.length > inline_table.max_field_length || formatted.includes(newline))
const spacing = inline ? " " : indentationNewline(indent)
const end_spacing = inline ? " " : indentationNewline(indent - 1)
let table = [end_spacing + "}"]
let beforeField = false
for (let i = length - 1; i > -1; i--) {
const field = node.fields[i]
const isField = field.type !== "Comment"
if (beforeField && isField) {
table.push(",")
beforeField = false
}
table.push(spacing + prettyPrint(field, indent))
beforeField = beforeField || isField
}
table.push("{")
return table.reverse().join("")
},
MemberExpression: (node, indent) => indexPrettyPrint(node, indent) + node.indexer + prettyPrint(node.identifier, indent),
IndexExpression: (node, indent) => indexPrettyPrint(node, indent) + "[" + prettyPrint(node.index, indent) + "]",
NilLiteral: node => node.raw,
VarargLiteral: node => node.raw,
BooleanLiteral: node => node.raw,
StringLiteral: node => writeBeautifiedText(read(node.value || node.raw)),
NumericLiteral: node => {
node.value = node.value || read(node.raw)
const rawUpper = node.raw.toUpperCase()
if (rawUpper.startsWith("0X")) return "0x" + rawUpper.substring(2)
return writeBeautifiedText(node.value)
}
}
const extraNewlines = {
FunctionDeclaration: true
}
const prettyPrint = (node, indent) => {
if (Array.isArray(node)) {
const indentNewline = indentationNewline(indent)
if (!extra_newlines) return mapPrettyPrint(node, indent).join(indentNewline)
let formatted = ""
let extraNewline
let i = 0
for (; i < node.length; i++) {
const notFirst = i > 0
let comments = []
let j = i
for (; j < node.length && node[j].type === "Comment"; j++) comments.push(prettyPrint(node[j], indent))
if (i + comments.length === node.length) {
if (notFirst) formatted += indentNewline
formatted += comments.join(indentNewline)
break
}
i = j
const child = node[i]
const prevExtraNewline = extraNewline
extraNewline = extraNewlines[child.type]
if (notFirst) formatted += (prevExtraNewline || extraNewline ? newline : "") + indentNewline
if (comments.length > 0) {
formatted += comments.join(indentNewline)
formatted += indentNewline
}
formatted += prettyPrint(child, indent)
}
return formatted
}
const nodeFormatter = formatters[node.type]
if (!nodeFormatter) throw new Error("Formatter for " + node.type + " not implemented yet")
return nodeFormatter(node, indent)
}
return prettyPrint
}
const astFormatter = conf => (ast, indent) => formatter(conf)(ast, indent === undefined ? 0 : indent)
const textFormatter = conf => {
const formatter = astFormatter(conf)
return text => {
const ast = parse(text)
fixRanges(ast)
insertComments(ast)
return formatter(ast)
}
}
module.exports = {
ast: { fixRanges, insertComments, formatter: astFormatter },
formatChunk: textFormatter(),
formatter: textFormatter
}