-
Notifications
You must be signed in to change notification settings - Fork 1
/
prettify_wast.js
111 lines (106 loc) · 2.55 KB
/
prettify_wast.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
function prettify(wast) {
let out = ""
let indent = true
let tokens = tokenize(wast.trim() + "\n")
//return JSON.stringify(tokens,null,2)
let stack = []
tokens = tokens[0]
while (tokens) {
let token = tokens.shift()
if (typeof token === "object") {
if (indent) {
out += "\n"
for (let i = 0; i < stack.length; i++) out += " "
}
out += "("
stack.push(tokens)
tokens = token
//out += countArrays(tokens)
indent = countArrays(tokens) > 1
} else if (token.substr(0, 2) === ";;") {
if (indent) {
out += "\n\n"
for (let i = 0; i < stack.length; i++) out += " "
}
out += token + " "
} else {
out += token + " "
}
while (tokens && !tokens.length) {
out += ") "
tokens = stack.pop()
indent = true
//indent = countArrays(tokens) > 1
}
}
return trimLineEnds(out.substr(0, out.lastIndexOf(")")))
}
function tokenize(wast) {
let stack = []
let tokens = []
let pos = 0
let char = ""
while (pos < wast.length) {
//console.log(pos)
let token = ""
while (char && !char.trim()) {
char = wast[pos++]
}
if (char === ";" && wast[pos] === ";") {
//token="\n\n"
while (char && char !== "\n") {
token += char
char = wast[pos++]
}
token += char
char = wast[pos++]
} else if (char === "(" && wast[pos] === ";") {
while (char && token.substr(-2) !== ";)") {
token += char
char = wast[pos++]
}
} else if ("(".includes(char)) {
stack.push(tokens)
tokens.push(tokens = [])
char = wast[pos++]
} else if (")".includes(char)) {
tokens = stack.pop()
char = wast[pos++]
} else if ("\"\'".includes(char)) {
while (char && char !== token[0]) {
if (char === "\\") {
token += char
char = wast[pos++]
}
token += char
char = wast[pos++]
}
token += char
char = wast[pos++]
} else {
do {
token += char
char = wast[pos++]
} while (char && char.trim() && !"(\";\')".includes(char))
}
token && tokens.push(token)
//console.log(token)
}
while (stack.length) tokens = stack.pop()
return tokens
}
function countArrays(arr) {
if (!arr) return 0
let count = 0
for (let elem of arr) {
if (typeof elem === "object") count++
}
return count
}
function trimLineEnds(txt) {
while (txt.includes(" \n")) {
txt = txt.replace(/ \n/g, "\n");
}
return txt.trim() + "\n"
}
module.exports = prettify