1 | 'use strict';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | * Stringify a CST document, token, or collection item
|
---|
5 | *
|
---|
6 | * Fair warning: This applies no validation whatsoever, and
|
---|
7 | * simply concatenates the sources in their logical order.
|
---|
8 | */
|
---|
9 | const stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);
|
---|
10 | function stringifyToken(token) {
|
---|
11 | switch (token.type) {
|
---|
12 | case 'block-scalar': {
|
---|
13 | let res = '';
|
---|
14 | for (const tok of token.props)
|
---|
15 | res += stringifyToken(tok);
|
---|
16 | return res + token.source;
|
---|
17 | }
|
---|
18 | case 'block-map':
|
---|
19 | case 'block-seq': {
|
---|
20 | let res = '';
|
---|
21 | for (const item of token.items)
|
---|
22 | res += stringifyItem(item);
|
---|
23 | return res;
|
---|
24 | }
|
---|
25 | case 'flow-collection': {
|
---|
26 | let res = token.start.source;
|
---|
27 | for (const item of token.items)
|
---|
28 | res += stringifyItem(item);
|
---|
29 | for (const st of token.end)
|
---|
30 | res += st.source;
|
---|
31 | return res;
|
---|
32 | }
|
---|
33 | case 'document': {
|
---|
34 | let res = stringifyItem(token);
|
---|
35 | if (token.end)
|
---|
36 | for (const st of token.end)
|
---|
37 | res += st.source;
|
---|
38 | return res;
|
---|
39 | }
|
---|
40 | default: {
|
---|
41 | let res = token.source;
|
---|
42 | if ('end' in token && token.end)
|
---|
43 | for (const st of token.end)
|
---|
44 | res += st.source;
|
---|
45 | return res;
|
---|
46 | }
|
---|
47 | }
|
---|
48 | }
|
---|
49 | function stringifyItem({ start, key, sep, value }) {
|
---|
50 | let res = '';
|
---|
51 | for (const st of start)
|
---|
52 | res += st.source;
|
---|
53 | if (key)
|
---|
54 | res += stringifyToken(key);
|
---|
55 | if (sep)
|
---|
56 | for (const st of sep)
|
---|
57 | res += st.source;
|
---|
58 | if (value)
|
---|
59 | res += stringifyToken(value);
|
---|
60 | return res;
|
---|
61 | }
|
---|
62 |
|
---|
63 | exports.stringify = stringify;
|
---|