From f4c3e3b17329aee5ce9141b2f47e98c65887f2fd Mon Sep 17 00:00:00 2001 From: Bram Gotink Date: Tue, 21 May 2024 06:13:19 +0200 Subject: [PATCH] Include combinators when stringifying (sub)trees (#76) * Test stringify on AST parameters * Include combinators in stringify --- parsel.ts | 21 ++++++++++++++++----- test.html | 21 +++++++++++++++++---- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/parsel.ts b/parsel.ts index 28bc529..f6aeef0 100644 --- a/parsel.ts +++ b/parsel.ts @@ -393,13 +393,24 @@ export function parse( * Converts the given list or (sub)tree to a string. */ export function stringify(listOrNode: Token[] | AST): string { - let tokens: Token[]; if (Array.isArray(listOrNode)) { - tokens = listOrNode; - } else { - tokens = [...flatten(listOrNode)].map(([token]) => token); + return listOrNode.map((token) => token.content).join(""); + } + + switch (listOrNode.type) { + case "list": + return listOrNode.list.map(stringify).join(","); + case "complex": + return ( + stringify(listOrNode.left) + + listOrNode.combinator + + stringify(listOrNode.right) + ); + case "compound": + return listOrNode.list.map(stringify).join(""); + default: + return listOrNode.content; } - return tokens.map(token => token.content).join('') } /** diff --git a/test.html b/test.html index d3e83ce..eb0e54f 100644 --- a/test.html +++ b/test.html @@ -27,8 +27,12 @@ name: 'Parsing', tests: [] }, - testStringify: { - name: 'Stringifying', + testStringifyTokens: { + name: 'Stringifying tokens', + tests: [] + }, + testStringifyAST: { + name: 'Stringifying AST', tests: [] }, testSpecificity: { @@ -45,7 +49,8 @@ tests.testParse.tests.push(testCase); break; case 'stringify': - tests.testStringify.tests.push(testCase); + tests.testStringifyTokens.tests.push(testCase); + tests.testStringifyAST.tests.push(testCase); break; case 'specificity': tests.testSpecificity.tests.push(testCase); @@ -93,7 +98,7 @@ return Test.equals(JSON.stringify(JSON.parse(expected.textContent), null, "\t"), actual); } -window.testStringify = function(test, result, expected) { +window.testStringifyTokens = function(test, result, expected) { console.log(arguments) const tokens = parsel.tokenize(test.textContent); const actual = parsel.stringify(tokens); @@ -101,6 +106,14 @@ return Test.equals(JSON.parse(expected.textContent), actual); } +window.testStringifyAST = function(test, result, expected) { + console.log(arguments) + const tokens = parsel.parse(test.textContent); + const actual = parsel.stringify(tokens); + result.textContent = JSON.stringify(actual); + return Test.equals(JSON.parse(expected.textContent), actual); +} + window.testSpecificity = function(test, result, expected) { console.log(arguments) const specificity = parsel.specificity(test.textContent);