Created
December 3, 2023 18:49
-
-
Save frostburn/f8477fb4ce6bf912475ef5c8dd1ef932 to your computer and use it in GitHub Desktop.
Peggy proposition: Tagged template parser with auto-vectorization of template arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{ | |
function add(left, right) { | |
if (typeof left === 'number') { | |
if (typeof right === 'number') { | |
return left + right; | |
} else { | |
return right.map(r => left + r); | |
} | |
} else { | |
if (typeof right === 'number') { | |
return left.map(l => l + right); | |
} else { | |
return left.map((l, i) => l + right[i]); | |
} | |
} | |
} | |
}} | |
Start | |
= Expression | |
Expression | |
= left: Value '+' right: Value { return add(left, right); } | |
Value | |
= Int | |
/ FormattedTemplateArgument | |
Int | |
= [0-9]+ { return parseInt(text(), 10); } | |
FormattedTemplateArgument | |
= arg: €TemplateArgument { return typeof arg === 'number' ? arg : new Float64Array(arg) } | |
/** | |
Above €TemplateArgument is a new magic pattern that accepts the "hole" left by ${arg} inside backquotes and passes in the value as is. | |
Examples: | |
parse`1+2` | |
// Evaluates to 3. | |
parse`5+${3}` | |
// Evaluates to 8. | |
parse`5+${[1, 2, 3]}` | |
// Evaluates to Float64Array(3) [ 6, 7, 8 ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment