@bablr/agast-helpers 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Conrad Buck
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @bablr/agast-helpers
2
+
3
+ Helper functions for working with agAST trees
@@ -0,0 +1,229 @@
1
+ const { freeze } = Object;
2
+
3
+ export const buildReference = (name, isArray) => {
4
+ return freeze({ type: 'Reference', value: freeze({ name, isArray }) });
5
+ };
6
+
7
+ export const buildNull = () => {
8
+ return freeze({ type: 'Null', value: undefined });
9
+ };
10
+
11
+ export const buildGap = () => {
12
+ return freeze({ type: 'Gap', value: undefined });
13
+ };
14
+
15
+ export const buildEmbedded = (node) => {
16
+ return freeze({ type: 'Embedded', value: node });
17
+ };
18
+
19
+ export const buildDoctypeTag = (attributes) => {
20
+ return freeze({
21
+ type: 'DoctypeTag',
22
+ value: { doctype: 'cstml', version: 0, attributes: freeze(attributes) },
23
+ });
24
+ };
25
+
26
+ export const buildNodeOpenTag = (flags, language, type, intrinsicValue, attributes = {}) => {
27
+ let { token, trivia, escape, expression } = flags;
28
+
29
+ if (!type) throw new Error();
30
+
31
+ token = !!token;
32
+ trivia = !!trivia;
33
+ escape = !!escape;
34
+ expression = !!expression;
35
+ let intrinsic = !!intrinsicValue;
36
+
37
+ return freeze({
38
+ type: 'OpenNodeTag',
39
+ value: freeze({
40
+ flags: freeze({ token, trivia, escape, intrinsic, expression }),
41
+ language,
42
+ type,
43
+ intrinsicValue,
44
+ attributes,
45
+ }),
46
+ });
47
+ };
48
+
49
+ export const buildFragmentOpenTag = (flags = nodeFlags, language) => {
50
+ let { token, trivia, escape } = flags;
51
+
52
+ token = !!token;
53
+ trivia = !!trivia;
54
+ escape = !!escape;
55
+
56
+ return freeze({
57
+ type: 'OpenFragmentTag',
58
+ value: freeze({ flags: freeze({ token, trivia, escape }) }),
59
+ });
60
+ };
61
+
62
+ export const buildNodeCloseTag = (type = null, language = null) => {
63
+ return freeze({ type: 'CloseNodeTag', value: freeze({ language, type }) });
64
+ };
65
+
66
+ export const buildFragmentCloseTag = () => {
67
+ return freeze({ type: 'CloseFragmentTag', value: freeze({}) });
68
+ };
69
+
70
+ const isString = (val) => typeof val === 'string';
71
+
72
+ export const buildLiteral = (value) => {
73
+ if (!isString(value)) throw new Error('invalid literal');
74
+ return freeze({ type: 'Literal', value });
75
+ };
76
+
77
+ export const buildNodeWithFlags = (
78
+ flags,
79
+ language,
80
+ type,
81
+ children = [],
82
+ properties = {},
83
+ attributes = {},
84
+ ) =>
85
+ freeze({
86
+ flags,
87
+ language,
88
+ type,
89
+ children: freeze(children),
90
+ properties: freeze(properties),
91
+ attributes: freeze(attributes),
92
+ });
93
+
94
+ export const nodeFlags = freeze({
95
+ token: false,
96
+ escape: false,
97
+ trivia: false,
98
+ intrinsic: false,
99
+ expression: false,
100
+ });
101
+
102
+ export const buildNode = (language, type, children = [], properties = {}, attributes = {}) =>
103
+ freeze({
104
+ flags: nodeFlags,
105
+ language,
106
+ type,
107
+ children: freeze(children),
108
+ properties: freeze(properties),
109
+ attributes: freeze(attributes),
110
+ });
111
+
112
+ export const syntacticFlags = freeze({
113
+ token: true,
114
+ escape: false,
115
+ trivia: false,
116
+ intrinsic: false,
117
+ expression: false,
118
+ });
119
+
120
+ export const buildSyntacticNode = (language, type, value, attributes = {}) =>
121
+ freeze({
122
+ flags: syntacticFlags,
123
+ language,
124
+ type,
125
+ children: [buildLiteral(value)],
126
+ properties: freeze({}),
127
+ attributes: freeze(attributes),
128
+ });
129
+
130
+ export const syntacticIntrinsicFlags = freeze({
131
+ token: true,
132
+ escape: false,
133
+ trivia: false,
134
+ intrinsic: true,
135
+ expression: false,
136
+ });
137
+ export const buildSyntacticIntrinsicNode = (language, type, value, attributes = {}) =>
138
+ freeze({
139
+ flags: syntacticIntrinsicFlags,
140
+ language,
141
+ type,
142
+ children: [buildLiteral(value)],
143
+ properties: freeze({}),
144
+ attributes: freeze(attributes),
145
+ });
146
+
147
+ export const escapeFlags = freeze({
148
+ token: false,
149
+ escape: true,
150
+ trivia: false,
151
+ intrinsic: false,
152
+ expression: false,
153
+ });
154
+
155
+ export const buildEscapeNode = (language, type, children = [], properties = {}, attributes = {}) =>
156
+ freeze({
157
+ flags: escapeFlags,
158
+ language,
159
+ type,
160
+ children: freeze(children),
161
+ properties: freeze(properties),
162
+ attributes: freeze(attributes),
163
+ });
164
+
165
+ export const syntacticEscapeFlags = freeze({
166
+ token: true,
167
+ escape: true,
168
+ trivia: false,
169
+ intrinsic: false,
170
+ expression: false,
171
+ });
172
+
173
+ export const buildSyntacticEscapeNode = (
174
+ language,
175
+ type,
176
+ children = [],
177
+ properties = {},
178
+ attributes = {},
179
+ ) =>
180
+ freeze({
181
+ flags: syntacticEscapeFlags,
182
+ language,
183
+ type,
184
+ children: freeze(children),
185
+ properties: freeze(properties),
186
+ attributes: freeze(attributes),
187
+ });
188
+
189
+ export const syntacticTriviaFlags = freeze({
190
+ token: true,
191
+ escape: false,
192
+ trivia: true,
193
+ intrinsic: false,
194
+ expression: false,
195
+ });
196
+
197
+ export const buildSyntacticTriviaNode = (
198
+ language,
199
+ type,
200
+ children = [],
201
+ properties = {},
202
+ attributes = {},
203
+ ) =>
204
+ freeze({
205
+ flags: syntacticTriviaFlags,
206
+ language,
207
+ type,
208
+ children: freeze(children),
209
+ properties: freeze(properties),
210
+ attributes: freeze(attributes),
211
+ });
212
+
213
+ export const triviaFlags = freeze({
214
+ token: false,
215
+ escape: false,
216
+ trivia: true,
217
+ intrinsic: false,
218
+ expression: false,
219
+ });
220
+
221
+ export const buildTriviaNode = (language, type, children = [], properties = {}, attributes = {}) =>
222
+ freeze({
223
+ flags: triviaFlags,
224
+ language,
225
+ type,
226
+ children: freeze(children),
227
+ properties: freeze(properties),
228
+ attributes: freeze(attributes),
229
+ });
package/lib/path.js ADDED
@@ -0,0 +1,16 @@
1
+ export const parsePath = (str) => {
2
+ const isArray = str.endsWith('[]');
3
+ const name = isArray ? str.slice(0, -2) : str;
4
+
5
+ if (!/^\w+$/.test(name)) throw new Error();
6
+
7
+ return { isArray, name };
8
+ };
9
+
10
+ export const printPath = (path) => {
11
+ if (!path) return null;
12
+
13
+ const { isArray, name } = path;
14
+
15
+ return `${name}${isArray ? '[]' : ''}`;
16
+ };
package/lib/print.js ADDED
@@ -0,0 +1,198 @@
1
+ const { isInteger, isFinite } = Number;
2
+ const { isArray } = Array;
3
+ const isString = (val) => typeof val === 'string';
4
+ const isNumber = (val) => typeof val === 'number';
5
+
6
+ export const printExpression = (expr) => {
7
+ if (isString(expr)) {
8
+ return printString(expr);
9
+ } else if (expr == null || typeof expr === 'boolean') {
10
+ return String(expr);
11
+ } else if (isNumber(expr)) {
12
+ if (!isFinite(expr)) {
13
+ return expr === -Infinity ? '-Infinity' : '+Infinity';
14
+ } else if (isInteger(expr)) {
15
+ return String(expr);
16
+ } else {
17
+ throw new Error();
18
+ }
19
+ } else if (isArray(expr)) {
20
+ return `[${expr.map((v) => printExpression(v)).join(', ')}]`;
21
+ } else if (typeof expr === 'object') {
22
+ return `{${Object.entries(expr).map(([k, v]) => `${k}: ${printExpression(v)}`)}}`;
23
+ } else {
24
+ throw new Error();
25
+ }
26
+ };
27
+
28
+ export const printAttributes = (attributes) => {
29
+ return Object.entries(attributes)
30
+ .map(([k, v]) => (v === true ? k : v === false ? `!${k}` : `${k}=${printExpression(v)}`))
31
+ .join(' ');
32
+ };
33
+
34
+ export const printLanguage = (language) => {
35
+ if (isString(language)) {
36
+ return printSingleString(language);
37
+ } else {
38
+ return language.join('.');
39
+ }
40
+ };
41
+
42
+ export const printTagPath = (language, type) => {
43
+ return language?.length ? `${printLanguage(language)}:${type}` : type;
44
+ };
45
+
46
+ const escapeReplacer = (esc) => {
47
+ if (esc === '\r') {
48
+ return '\\r';
49
+ } else if (esc === '\n') {
50
+ return '\\n';
51
+ } else if (esc === '\t') {
52
+ return '\\t';
53
+ } else if (esc === '\0') {
54
+ return '\\0';
55
+ } else {
56
+ return `\\${esc}`;
57
+ }
58
+ };
59
+
60
+ export const printSingleString = (str) => {
61
+ return `'${str.replace(/['\\\0\r\n\t]/g, escapeReplacer)}'`;
62
+ };
63
+
64
+ export const printDoubleString = (str) => {
65
+ return `"${str.replace(/["\\\0\r\n\t]/g, escapeReplacer)}"`;
66
+ };
67
+
68
+ export const printString = (str) => {
69
+ return str === "'" ? printDoubleString(str) : printSingleString(str);
70
+ };
71
+
72
+ export const printGap = (terminal) => {
73
+ if (terminal?.type !== 'Gap') throw new Error();
74
+
75
+ return `<//>`;
76
+ };
77
+
78
+ export const printReference = (terminal) => {
79
+ if (terminal?.type !== 'Reference') throw new Error();
80
+
81
+ const { name, isArray } = terminal.value;
82
+ const pathBraces = isArray ? '[]' : '';
83
+
84
+ return `${name}${pathBraces}:`;
85
+ };
86
+
87
+ export const printNull = (terminal) => {
88
+ if (terminal?.type !== 'Null') throw new Error();
89
+
90
+ return 'null';
91
+ };
92
+
93
+ export const printType = (type) => {
94
+ return typeof type === 'string'
95
+ ? type
96
+ : typeof type === 'symbol'
97
+ ? `$${type.description.replace('@bablr/', '')}`
98
+ : String(type);
99
+ };
100
+
101
+ export const printDoctypeTag = (terminal) => {
102
+ if (terminal?.type !== 'DoctypeTag') throw new Error();
103
+
104
+ let { doctype, version, attributes } = terminal.value;
105
+
106
+ attributes = attributes ? ` ${printAttributes(attributes)}` : '';
107
+
108
+ return `<!${version}:${doctype}${attributes}>`;
109
+ };
110
+
111
+ export const printLiteral = (terminal) => {
112
+ if (terminal?.type !== 'Literal') throw new Error();
113
+
114
+ return printString(terminal.value);
115
+ };
116
+
117
+ export const printFlags = (flags) => {
118
+ const hash = flags.trivia ? '#' : '';
119
+ const star = flags.token ? '*' : '';
120
+ const at = flags.escape ? '@' : '';
121
+ const plus = flags.expression ? '+' : '';
122
+
123
+ if (flags.escape && flags.trivia) throw new Error('Node cannot be escape and trivia');
124
+
125
+ return `${hash}${star}${at}${plus}`;
126
+ };
127
+
128
+ export const printOpenNodeTag = (terminal) => {
129
+ if (terminal?.type !== 'OpenNodeTag') throw new Error();
130
+
131
+ const { flags, language: tagLanguage, type, intrinsicValue, attributes } = terminal.value;
132
+
133
+ if (intrinsicValue && !flags.intrinsic) throw new Error();
134
+
135
+ const printedAttributes = attributes && printAttributes(attributes);
136
+ const attributesFrag = printedAttributes ? ` ${printedAttributes}` : '';
137
+ const intrinsicFrag = flags.intrinsic ? ` ${printString(intrinsicValue)}` : '';
138
+ const selfCloser = flags.intrinsic ? ' /' : '';
139
+
140
+ return `<${printFlags(flags)}${printTagPath(
141
+ tagLanguage,
142
+ type,
143
+ )}${intrinsicFrag}${attributesFrag}${selfCloser}>`;
144
+ };
145
+
146
+ export const printOpenFragmentTag = (terminal) => {
147
+ if (terminal?.type !== 'OpenFragmentTag') throw new Error();
148
+
149
+ let { flags } = terminal.value;
150
+
151
+ return `<${printFlags(flags)}>`;
152
+ };
153
+
154
+ export const printCloseNodeTag = (terminal) => {
155
+ if (terminal?.type !== 'CloseNodeTag') throw new Error();
156
+
157
+ return `</>`;
158
+ };
159
+
160
+ export const printCloseFragmentTag = (terminal) => {
161
+ if (terminal?.type !== 'CloseFragmentTag') throw new Error();
162
+
163
+ return `</>`;
164
+ };
165
+
166
+ export const printTerminal = (terminal) => {
167
+ switch (terminal?.type || 'Null') {
168
+ case 'Null':
169
+ return printNull(terminal);
170
+
171
+ case 'Gap':
172
+ return printGap(terminal);
173
+
174
+ case 'Literal':
175
+ return printLiteral(terminal);
176
+
177
+ case 'DoctypeTag':
178
+ return printDoctypeTag(terminal);
179
+
180
+ case 'Reference':
181
+ return printReference(terminal);
182
+
183
+ case 'OpenNodeTag':
184
+ return printOpenNodeTag(terminal);
185
+
186
+ case 'OpenFragmentTag':
187
+ return printOpenFragmentTag(terminal);
188
+
189
+ case 'CloseNodeTag':
190
+ return printCloseNodeTag(terminal);
191
+
192
+ case 'CloseFragmentTag':
193
+ return printCloseFragmentTag(terminal);
194
+
195
+ default:
196
+ throw new Error();
197
+ }
198
+ };
@@ -0,0 +1,59 @@
1
+ import {
2
+ buildReference,
3
+ buildGap,
4
+ buildEmbedded,
5
+ buildNodeOpenTag,
6
+ buildFragmentOpenTag,
7
+ buildNodeCloseTag,
8
+ buildFragmentCloseTag,
9
+ buildLiteral,
10
+ buildNode,
11
+ buildSyntacticNode,
12
+ buildSyntacticIntrinsicNode,
13
+ buildEscapeNode,
14
+ buildSyntacticEscapeNode,
15
+ buildSyntacticTriviaNode,
16
+ buildTriviaNode,
17
+ } from './builders.js';
18
+
19
+ export * from './builders.js';
20
+
21
+ const { isArray } = Array;
22
+
23
+ const stripArray = (val) => {
24
+ if (isArray(val)) {
25
+ if (val.length > 1) {
26
+ throw new Error();
27
+ }
28
+ return val[0];
29
+ } else {
30
+ return val;
31
+ }
32
+ };
33
+
34
+ export const ref = (path) => {
35
+ if (isArray(path)) {
36
+ const pathIsArray = path[0].endsWith('[]');
37
+ const name = pathIsArray ? path[0].slice(0, -2) : path[0];
38
+ return buildReference(name, pathIsArray);
39
+ } else {
40
+ const { name, isArray: pathIsArray } = path;
41
+ return buildReference(name, pathIsArray);
42
+ }
43
+ };
44
+
45
+ export const lit = (str) => buildLiteral(stripArray(str));
46
+
47
+ export const gap = buildGap;
48
+ export const embedded = buildEmbedded;
49
+ export const nodeOpen = buildNodeOpenTag;
50
+ export const fragOpen = buildFragmentOpenTag;
51
+ export const nodeClose = buildNodeCloseTag;
52
+ export const fragClose = buildFragmentCloseTag;
53
+ export const node = buildNode;
54
+ export const s_node = buildSyntacticNode;
55
+ export const s_i_node = buildSyntacticIntrinsicNode;
56
+ export const e_node = buildEscapeNode;
57
+ export const s_e_node = buildSyntacticEscapeNode;
58
+ export const s_t_node = buildSyntacticTriviaNode;
59
+ export const t_node = buildTriviaNode;
package/lib/stream.js ADDED
@@ -0,0 +1,276 @@
1
+ import { printTerminal } from './print.js';
2
+ export * from './print.js';
3
+
4
+ export const getStreamIterator = (obj) => {
5
+ return obj[Symbol.for('@@streamIterator')]?.() || obj[Symbol.iterator]?.();
6
+ };
7
+
8
+ export class SyncGenerator {
9
+ constructor(embeddedGenerator) {
10
+ if (!embeddedGenerator.next) throw new Error();
11
+
12
+ this.generator = embeddedGenerator;
13
+ }
14
+
15
+ next(value) {
16
+ const step = this.generator.next(value);
17
+
18
+ if (step instanceof Promise) {
19
+ throw new Error('invalid embedded generator');
20
+ }
21
+
22
+ if (step.done) {
23
+ return { value: undefined, done: true };
24
+ } else if (step.value instanceof Promise) {
25
+ throw new Error('sync generators cannot resolve promises');
26
+ } else {
27
+ const { value } = step;
28
+ return { value, done: false };
29
+ }
30
+ }
31
+
32
+ return(value) {
33
+ const step = this.generator.return(value);
34
+ if (step instanceof Promise) {
35
+ throw new Error('invalid embedded generator');
36
+ }
37
+
38
+ if (step.value instanceof Promise) {
39
+ throw new Error('sync generators cannot resolve promises');
40
+ }
41
+ return step;
42
+ }
43
+
44
+ [Symbol.iterator]() {
45
+ return this;
46
+ }
47
+ }
48
+
49
+ export class AsyncGenerator {
50
+ constructor(embeddedGenerator) {
51
+ this.generator = embeddedGenerator;
52
+ }
53
+
54
+ next(value) {
55
+ const step = this.generator.next(value);
56
+
57
+ if (step instanceof Promise) {
58
+ throw new Error('invalid embedded generator');
59
+ }
60
+
61
+ if (step.done) {
62
+ return Promise.resolve({ value: undefined, done: true });
63
+ } else if (step.value instanceof Promise) {
64
+ return step.value.then((value) => {
65
+ return this.next(value);
66
+ });
67
+ } else {
68
+ const { value } = step;
69
+ return Promise.resolve({ value, done: false });
70
+ }
71
+ }
72
+
73
+ return(value) {
74
+ const result = this.generator.return(value);
75
+ if (result instanceof Promise) {
76
+ throw new Error('sync generators cannot resolve promises');
77
+ }
78
+ return result;
79
+ }
80
+
81
+ [Symbol.asyncIterator]() {
82
+ return this;
83
+ }
84
+ }
85
+
86
+ export class StreamGenerator {
87
+ constructor(embeddedGenerator) {
88
+ this.generator = embeddedGenerator;
89
+ }
90
+
91
+ next(value) {
92
+ const step = this.generator.next(value);
93
+
94
+ if (step.done) {
95
+ return { value: undefined, done: true };
96
+ } else if (step.value instanceof Promise) {
97
+ return step.value.then((value) => {
98
+ return this.next(value);
99
+ });
100
+ } else {
101
+ const { value } = step;
102
+ return { value, done: false };
103
+ }
104
+ }
105
+
106
+ return(value) {
107
+ return this.generator.return(value);
108
+ }
109
+
110
+ [Symbol.for('@@streamIterator')]() {
111
+ return this;
112
+ }
113
+ }
114
+
115
+ export class StreamIterable {
116
+ constructor(embeddedStreamIterable) {
117
+ this.iterable = embeddedStreamIterable;
118
+ }
119
+
120
+ [Symbol.iterator]() {
121
+ return new SyncGenerator(this.iterable);
122
+ }
123
+
124
+ [Symbol.asyncIterator]() {
125
+ return new AsyncGenerator(this.iterable);
126
+ }
127
+
128
+ [Symbol.for('@@streamIterator')]() {
129
+ return new StreamGenerator(this.iterable);
130
+ }
131
+ }
132
+
133
+ export const maybeWait = (maybePromise, callback) => {
134
+ if (maybePromise instanceof Promise) {
135
+ return maybePromise.then(callback);
136
+ } else {
137
+ return callback(maybePromise);
138
+ }
139
+ };
140
+
141
+ export const printCSTML = (terminals) => {
142
+ if (!terminals) {
143
+ return '<//>';
144
+ }
145
+
146
+ let printed = '';
147
+
148
+ for (const terminal of terminals) {
149
+ printed += printTerminal(terminal);
150
+ }
151
+
152
+ return printed;
153
+ };
154
+
155
+ export const printPrettyCSTML = (terminals, indent = ' ') => {
156
+ if (!terminals) {
157
+ return '<//>';
158
+ }
159
+
160
+ let printed = '';
161
+ let indentLevel = 0;
162
+ let first = true;
163
+
164
+ for (const terminal of terminals) {
165
+ const inline =
166
+ terminal.type === 'Null' ||
167
+ terminal.type === 'Gap' ||
168
+ (terminal.type === 'OpenNodeTag' && terminal.value.flags.intrinsic);
169
+
170
+ if (!first && !inline) {
171
+ printed += '\n';
172
+ }
173
+
174
+ if (['CloseNodeTag', 'CloseFragmentTag'].includes(terminal.type)) {
175
+ indentLevel--;
176
+ }
177
+
178
+ if (!inline) {
179
+ printed += indent.repeat(indentLevel);
180
+ } else {
181
+ printed += ' ';
182
+ }
183
+ printed += printTerminal(terminal);
184
+
185
+ if (
186
+ terminal.type === 'OpenFragmentTag' ||
187
+ (terminal.type === 'OpenNodeTag' && !terminal.value.flags.intrinsic)
188
+ ) {
189
+ indentLevel++;
190
+ }
191
+
192
+ first = false;
193
+ }
194
+
195
+ return printed;
196
+ };
197
+
198
+ export const getCooked = (terminals) => {
199
+ let cooked = '';
200
+
201
+ for (const terminal of terminals) {
202
+ switch (terminal.type) {
203
+ case 'Reference': {
204
+ throw new Error('cookable nodes must not contain other nodes');
205
+ }
206
+
207
+ case 'OpenNodeTag': {
208
+ const { flags, attributes } = terminal.value;
209
+
210
+ if (!(flags.trivia || (flags.escape && attributes.cooked))) {
211
+ throw new Error('cookable nodes must not contain other nodes');
212
+ }
213
+
214
+ if (flags.escape) {
215
+ const { cooked: cookedValue } = terminal.value.attributes;
216
+
217
+ if (!cookedValue) throw new Error('cannot cook string: it contains uncooked escapes');
218
+
219
+ cooked += cookedValue;
220
+ }
221
+
222
+ break;
223
+ }
224
+
225
+ case 'Literal': {
226
+ cooked += terminal.value;
227
+ break;
228
+ }
229
+
230
+ default: {
231
+ throw new Error();
232
+ }
233
+ }
234
+ }
235
+
236
+ return cooked;
237
+ };
238
+
239
+ export const printSource = (terminals) => {
240
+ let printed = '';
241
+
242
+ for (const terminal of terminals) {
243
+ if (terminal.type === 'Literal') {
244
+ printed += terminal.value;
245
+ } else if (terminal.type === 'OpenNodeTag' && terminal.value.flags.intrinsic) {
246
+ printed += terminal.value.intrinsicValue;
247
+ }
248
+ }
249
+
250
+ return printed;
251
+ };
252
+
253
+ export function* generateSourceTextFor(terminals) {
254
+ for (const terminal of terminals) {
255
+ if (terminal.type === 'Literal') {
256
+ yield* terminal.value;
257
+ } else if (terminal.type === 'OpenNodeTag' && terminal.value.flags.intrinsic) {
258
+ yield* terminal.value.intrinsicValue;
259
+ }
260
+ }
261
+ }
262
+
263
+ export function sourceTextFor(terminals) {
264
+ return [...generateSourceTextFor(terminals)].join('');
265
+ }
266
+
267
+ export const startsDocument = (terminal) => {
268
+ const { type } = terminal;
269
+ if (type === 'OpenFragmentTag' || type === 'DoctypeTag') {
270
+ return true;
271
+ } else if (type === 'OpenNodeTag') {
272
+ const { flags } = terminal.value;
273
+
274
+ return flags.trivia || flags.escape;
275
+ }
276
+ };
@@ -0,0 +1,54 @@
1
+ import * as t from './builders.js';
2
+
3
+ const { isArray } = Array;
4
+ const { freeze } = Object;
5
+
6
+ export const interpolateArray = (value) => {
7
+ if (isArray(value)) {
8
+ return value;
9
+ } else {
10
+ return [value];
11
+ }
12
+ };
13
+
14
+ export const interpolateArrayChildren = (value, ref, sep) => {
15
+ if (isArray(value)) {
16
+ const values = value;
17
+ const children = [];
18
+ let first = true;
19
+ for (const _ of values) {
20
+ if (!first) children.push(freeze({ ...sep }));
21
+ children.push(freeze({ ...ref }));
22
+ first = false;
23
+ }
24
+ return children;
25
+ } else {
26
+ return [freeze({ ...ref })];
27
+ }
28
+ };
29
+
30
+ const validateTerminal = (term) => {
31
+ if (!term || (term.type !== 'Literal' && term.type !== 'Embedded')) {
32
+ throw new Error('Invalid terminal');
33
+ }
34
+ if (term.type === 'Embedded' && !term.value.flags.escape) {
35
+ throw new Error();
36
+ }
37
+ };
38
+
39
+ export const interpolateString = (value) => {
40
+ const terminals = [];
41
+ if (isArray(value)) {
42
+ for (const element of value) {
43
+ validateTerminal(element);
44
+
45
+ terminals.push(element);
46
+ }
47
+ } else {
48
+ // we can't safely interpolate strings here, though I wish we could
49
+ validateTerminal(value);
50
+ terminals.push(value);
51
+ }
52
+
53
+ return t.buildNode('String', 'Content', terminals);
54
+ };
package/lib/tree.js ADDED
@@ -0,0 +1,373 @@
1
+ import emptyStack from '@iter-tools/imm-stack';
2
+ import {
3
+ buildNodeCloseTag,
4
+ buildNodeOpenTag,
5
+ buildNull,
6
+ buildEmbedded,
7
+ nodeFlags,
8
+ buildDoctypeTag,
9
+ buildFragmentOpenTag,
10
+ buildFragmentCloseTag,
11
+ buildReference,
12
+ } from './builders.js';
13
+ import {
14
+ printPrettyCSTML as printPrettyCSTMLFromStream,
15
+ printCSTML as printCSTMLFromStream,
16
+ } from './stream.js';
17
+ export * from './builders.js';
18
+ export * from './print.js';
19
+
20
+ const arrayLast = (arr) => arr[arr.length - 1];
21
+
22
+ const buildFrame = (node) => {
23
+ if (!node) throw new Error();
24
+ return { node, childrenIdx: -1, resolver: new Resolver(node) };
25
+ };
26
+
27
+ const { hasOwn, freeze } = Object;
28
+
29
+ const get = (node, path) => {
30
+ const { 1: name, 2: index } = /^([^\.]+)(?:\.(\d+))?/.exec(path) || [];
31
+
32
+ if (index != null) {
33
+ return node.properties[name]?.[parseInt(index, 10)];
34
+ } else {
35
+ return node.properties[name];
36
+ }
37
+ };
38
+
39
+ const reduceTokenToNodes = (nodes, token) => {
40
+ switch (token.type) {
41
+ case 'OpenFragmentTag':
42
+ case 'Null': {
43
+ return nodes;
44
+ }
45
+
46
+ case 'DoctypeTag': {
47
+ const { attributes } = token.value;
48
+
49
+ return nodes.push(
50
+ freeze({
51
+ flags: nodeFlags,
52
+ type: Symbol.for('@bablr/fragment'),
53
+ children: [],
54
+ properties: {},
55
+ attributes: freeze(attributes),
56
+ }),
57
+ );
58
+ }
59
+
60
+ case 'CloseFragmentTag': {
61
+ freeze(nodes.value.properties);
62
+ freeze(nodes.value.children);
63
+
64
+ return nodes.pop();
65
+ }
66
+
67
+ case 'Literal':
68
+ case 'Gap':
69
+ case 'Reference': {
70
+ nodes.value.children.push(token);
71
+ return nodes;
72
+ }
73
+
74
+ case 'OpenNodeTag': {
75
+ const buildStringTerminals = (str) => {
76
+ // do better
77
+ return [{ type: 'Literal', value: str }];
78
+ };
79
+
80
+ const { flags, language, type, intrinsicValue, attributes } = token.value;
81
+ const node = nodes.value;
82
+ const newNode = freeze({
83
+ flags,
84
+ language,
85
+ type,
86
+ children: flags.intrinsic ? buildStringTerminals(intrinsicValue) : [],
87
+ properties: {},
88
+ attributes: freeze(attributes),
89
+ });
90
+
91
+ if (node && !(flags.escape || flags.trivia)) {
92
+ if (nodes.size === 1) {
93
+ node.children.push(buildReference('root', false));
94
+ }
95
+
96
+ if (!node.children.length) {
97
+ throw new Error('Nodes must follow references');
98
+ }
99
+
100
+ const { name, isArray } = arrayLast(node.children).value;
101
+
102
+ if (isArray) {
103
+ if (!hasOwn(node.properties, name)) {
104
+ node.properties[name] = [];
105
+ }
106
+ const array = node.properties[name];
107
+
108
+ array.push(newNode);
109
+ } else {
110
+ node.properties[name] = newNode;
111
+ }
112
+ }
113
+
114
+ if (flags.intrinsic) {
115
+ freeze(newNode.children);
116
+ freeze(newNode.properties);
117
+ return nodes;
118
+ }
119
+
120
+ return nodes.push(newNode);
121
+ }
122
+
123
+ case 'CloseNodeTag': {
124
+ const completedNode = nodes.value;
125
+ const { flags } = completedNode;
126
+
127
+ if (flags.escape || flags.trivia) {
128
+ const parentChildren = nodes.prev.value.children;
129
+
130
+ parentChildren.push(buildEmbedded(completedNode));
131
+ }
132
+
133
+ freeze(completedNode.properties);
134
+ freeze(completedNode.children);
135
+
136
+ return nodes.pop();
137
+ }
138
+
139
+ default: {
140
+ throw new Error();
141
+ }
142
+ }
143
+ };
144
+
145
+ export const treeFromStreamSync = (tokens) => {
146
+ let nodes = emptyStack;
147
+ let rootNode;
148
+
149
+ for (const token of tokens) {
150
+ nodes = reduceTokenToNodes(nodes, token);
151
+ rootNode = nodes.value || rootNode;
152
+ }
153
+
154
+ return rootNode;
155
+ };
156
+
157
+ export const treeFromStreamAsync = async (tokens) => {
158
+ let nodes = emptyStack;
159
+ let rootNode;
160
+
161
+ for await (const token of tokens) {
162
+ nodes = reduceTokenToNodes(nodes, token);
163
+ rootNode = nodes.value || rootNode;
164
+ }
165
+
166
+ return rootNode;
167
+ };
168
+
169
+ export function* streamFromTree(rootNode) {
170
+ if (!rootNode || rootNode.type === 'Gap') {
171
+ return rootNode;
172
+ }
173
+
174
+ yield buildDoctypeTag(rootNode.attributes);
175
+ yield buildFragmentOpenTag();
176
+
177
+ let stack = emptyStack.push(buildFrame(rootNode));
178
+
179
+ stack: while (stack.size) {
180
+ const frame = stack.value;
181
+ const { node, resolver } = frame;
182
+ const { flags, language, type, children, attributes } = node;
183
+
184
+ const intrinsicValue = flags.intrinsic ? children[0].value : null;
185
+
186
+ if (frame.childrenIdx === -1 && stack.size > 1) {
187
+ yield buildNodeOpenTag(flags, language, type, intrinsicValue, attributes);
188
+ }
189
+
190
+ if (!flags.intrinsic) {
191
+ while (++frame.childrenIdx < node.children.length) {
192
+ const terminal = node.children[frame.childrenIdx];
193
+
194
+ switch (terminal.type) {
195
+ case 'Literal':
196
+ case 'Gap':
197
+ case 'Null': {
198
+ yield terminal;
199
+ break;
200
+ }
201
+
202
+ case 'Embedded': {
203
+ stack = stack.push(buildFrame(terminal.value));
204
+ continue stack;
205
+ }
206
+
207
+ case 'Reference': {
208
+ if (stack.size > 1) {
209
+ yield terminal;
210
+ }
211
+
212
+ const resolved = resolver.consume(terminal).get(terminal);
213
+ if (resolved) {
214
+ stack = stack.push(buildFrame(resolved));
215
+ continue stack;
216
+ } else {
217
+ yield buildNull();
218
+ break;
219
+ }
220
+ }
221
+
222
+ default: {
223
+ throw new Error();
224
+ }
225
+ }
226
+ }
227
+
228
+ if (stack.size > 1) {
229
+ yield buildNodeCloseTag(type, language);
230
+ }
231
+ }
232
+
233
+ stack = stack.pop();
234
+ }
235
+ yield buildFragmentCloseTag();
236
+ }
237
+
238
+ export const getCooked = (cookable) => {
239
+ if (!cookable || cookable.type === 'Gap') {
240
+ return '';
241
+ }
242
+
243
+ const children = cookable.children || cookable;
244
+
245
+ let cooked = '';
246
+
247
+ for (const terminal of children) {
248
+ switch (terminal.type) {
249
+ case 'Reference': {
250
+ throw new Error('cookable nodes must not contain other nodes');
251
+ }
252
+
253
+ case 'Embedded': {
254
+ const { flags, attributes } = terminal.value;
255
+
256
+ if (!(flags.trivia || (flags.escape && attributes.cooked))) {
257
+ throw new Error('cookable nodes must not contain other nodes');
258
+ }
259
+
260
+ if (flags.escape) {
261
+ const { cooked: cookedValue } = attributes;
262
+
263
+ if (!cookedValue) throw new Error('cannot cook string: it contains uncooked escapes');
264
+
265
+ cooked += cookedValue;
266
+ }
267
+
268
+ break;
269
+ }
270
+
271
+ case 'Literal': {
272
+ cooked += terminal.value;
273
+ break;
274
+ }
275
+
276
+ default: {
277
+ throw new Error();
278
+ }
279
+ }
280
+ }
281
+
282
+ return cooked;
283
+ };
284
+
285
+ export const printCSTML = (rootNode) => {
286
+ return printCSTMLFromStream(streamFromTree(rootNode));
287
+ };
288
+
289
+ export const printPrettyCSTML = (rootNode, indent = ' ') => {
290
+ return printPrettyCSTMLFromStream(streamFromTree(rootNode), indent);
291
+ };
292
+
293
+ export const printSource = (node) => {
294
+ const resolver = new Resolver(node);
295
+ let printed = '';
296
+
297
+ if (node instanceof Promise) {
298
+ printed += '$Promise';
299
+ } else {
300
+ for (const child of node.children) {
301
+ if (child.type === 'Literal') {
302
+ printed += child.value;
303
+ } else if (child.type === 'Embedded') {
304
+ printed += printSource(child.value);
305
+ } else if (child.type === 'Reference') {
306
+ const node_ = resolver.consume(child).get(child);
307
+
308
+ if (node_ || !child.value.isArray) {
309
+ printed += printSource(node_);
310
+ }
311
+ }
312
+ }
313
+ }
314
+
315
+ return printed;
316
+ };
317
+
318
+ export class Resolver {
319
+ constructor(node, counters = new Map()) {
320
+ this.node = node;
321
+ this.counters = counters;
322
+ }
323
+
324
+ consume(reference) {
325
+ const { name, isArray } = reference.value;
326
+ const { counters } = this;
327
+
328
+ if (isArray) {
329
+ const count = counters.get(name) + 1 || 0;
330
+
331
+ counters.set(name, count);
332
+ } else {
333
+ if (counters.has(name))
334
+ throw new Error(`attempted to consume property {name: ${name}} twice`);
335
+
336
+ counters.set(name, 1);
337
+ }
338
+
339
+ return this;
340
+ }
341
+
342
+ resolve(reference) {
343
+ let { name, isArray } = reference.value;
344
+ const { counters } = this;
345
+ let path = name;
346
+
347
+ if (isArray) {
348
+ const count = counters.get(name) || 0;
349
+
350
+ path += '.' + count;
351
+ }
352
+
353
+ return path;
354
+ }
355
+
356
+ get(reference) {
357
+ if (!this.node) throw new Error('Cannot get from a resolver with no node');
358
+
359
+ return get(this.node, this.resolve(reference));
360
+ }
361
+
362
+ branch() {
363
+ return new Resolver(this.node, new Map(this.counters));
364
+ }
365
+
366
+ accept(resolver) {
367
+ this.counters = resolver.counters;
368
+
369
+ return this;
370
+ }
371
+ }
372
+
373
+ freeze(Resolver.prototype);
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@bablr/agast-helpers",
3
+ "description": "Helper functions for working with agAST trees",
4
+ "version": "0.1.0",
5
+ "author": "Conrad Buck<conartist6@gmail.com>",
6
+ "type": "module",
7
+ "files": [
8
+ "lib"
9
+ ],
10
+ "exports": {
11
+ "./builders": "./lib/builders.js",
12
+ "./path": "./lib/path.js",
13
+ "./print": "./lib/print.js",
14
+ "./shorthand": "./lib/shorthand.js",
15
+ "./stream": "./lib/stream.js",
16
+ "./template": "./lib/template.js",
17
+ "./tree": "./lib/tree.js"
18
+ },
19
+ "sideEffects": false,
20
+ "dependencies": {
21
+ "@iter-tools/imm-stack": "1.1.0"
22
+ },
23
+ "devDependencies": {
24
+ "@bablr/eslint-config-base": "github:bablr-lang/eslint-config-base#d834ccc52795d6c3b96ecc6c419960fceed221a6",
25
+ "enhanced-resolve": "^5.12.0",
26
+ "eslint": "^8.32.0",
27
+ "eslint-import-resolver-enhanced-resolve": "^1.0.5",
28
+ "eslint-plugin-import": "^2.27.5",
29
+ "prettier": "^2.6.2"
30
+ },
31
+ "repository": "github:bablr-lang/agast-helpers",
32
+ "homepage": "https://github.com/bablr-lang/agast-helpers",
33
+ "license": "MIT"
34
+ }