Skip to content

Commit

Permalink
Include combinators when stringifying (sub)trees (#76)
Browse files Browse the repository at this point in the history
* Test stringify on AST parameters

* Include combinators in stringify
  • Loading branch information
bgotink authored May 21, 2024
1 parent 4f69227 commit f4c3e3b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
21 changes: 16 additions & 5 deletions parsel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('')
}

/**
Expand Down
21 changes: 17 additions & 4 deletions test.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@
name: 'Parsing',
tests: []
},
testStringify: {
name: 'Stringifying',
testStringifyTokens: {
name: 'Stringifying tokens',
tests: []
},
testStringifyAST: {
name: 'Stringifying AST',
tests: []
},
testSpecificity: {
Expand All @@ -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);
Expand Down Expand Up @@ -93,14 +98,22 @@
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);
result.textContent = JSON.stringify(actual);
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);
Expand Down

0 comments on commit f4c3e3b

Please sign in to comment.