/
cst-stringify.ts
52 lines (49 loc) · 1.48 KB
/
cst-stringify.ts
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
import type { CollectionItem, Token } from './cst.js'
/**
* Stringify a CST document, token, or collection item
*
* Fair warning: This applies no validation whatsoever, and
* simply concatenates the sources in their logical order.
*/
export const stringify = (cst: Token | CollectionItem) =>
'type' in cst ? stringifyToken(cst) : stringifyItem(cst)
function stringifyToken(token: Token) {
switch (token.type) {
case 'block-scalar': {
let res = ''
for (const tok of token.props) res += stringifyToken(tok)
return res + token.source
}
case 'block-map':
case 'block-seq': {
let res = ''
for (const item of token.items) res += stringifyItem(item)
return res
}
case 'flow-collection': {
let res = token.start.source
for (const item of token.items) res += stringifyItem(item)
for (const st of token.end) res += st.source
return res
}
case 'document': {
let res = stringifyItem(token)
if (token.end) for (const st of token.end) res += st.source
return res
}
default: {
let res = token.source
if ('end' in token && token.end)
for (const st of token.end) res += st.source
return res
}
}
}
function stringifyItem({ start, key, sep, value }: CollectionItem) {
let res = ''
for (const st of start) res += st.source
if (key) res += stringifyToken(key)
if (sep) for (const st of sep) res += st.source
if (value) res += stringifyToken(value)
return res
}