Skip to content

Commit 9f5b4cf

Browse files
committed
1 parent 98414f9 commit 9f5b4cf

File tree

1 file changed

+33
-21
lines changed

1 file changed

+33
-21
lines changed

lib/parse.js

+33-21
Original file line numberDiff line numberDiff line change
@@ -304,30 +304,42 @@ const parse = (input, options = {}) => {
304304
push({ type: 'text', value });
305305
}
306306

307+
flattenBlocks(stack)
308+
markImbalancedBraces(ast);
309+
push({ type: 'eos' });
310+
311+
return ast;
312+
};
313+
314+
module.exports = parse;
315+
316+
function markImbalancedBraces({nodes}) {
307317
// Mark imbalanced braces and brackets as invalid
318+
for (const node of nodes) {
319+
if (node.nodes || node.invalid)
320+
continue;
321+
322+
if (node.type === 'open') node.isOpen = true;
323+
if (node.type === 'close') node.isClose = true;
324+
if (!node.nodes) node.type = 'text';
325+
326+
node.invalid = true;
327+
delete node.parent;
328+
}
329+
}
330+
331+
function flattenBlocks(stack) {
332+
let block;
308333
do {
309334
block = stack.pop();
310335

311-
if (block.type !== 'root') {
312-
block.nodes.forEach(node => {
313-
if (!node.nodes) {
314-
if (node.type === 'open') node.isOpen = true;
315-
if (node.type === 'close') node.isClose = true;
316-
if (!node.nodes) node.type = 'text';
317-
node.invalid = true;
318-
}
319-
});
336+
if (block.type === 'root')
337+
continue;
320338

321-
// get the location of the block on parent.nodes (block's siblings)
322-
let parent = stack[stack.length - 1];
323-
let index = parent.nodes.indexOf(block);
324-
// replace the (invalid) block with it's nodes
325-
parent.nodes.splice(index, 1, ...block.nodes);
326-
}
339+
// get the location of the block on parent.nodes (block's siblings)
340+
let parent = stack.at(-1);
341+
let index = parent.nodes.indexOf(block);
342+
// replace the (invalid) block with its nodes
343+
parent.nodes.splice(index, 1, ...block.nodes);
327344
} while (stack.length > 0);
328-
329-
push({ type: 'eos' });
330-
return ast;
331-
};
332-
333-
module.exports = parse;
345+
}

0 commit comments

Comments
 (0)