Forked from frostburn/tagged-vector-adder.pegjs
Last active
December 3, 2023 20:08
-
-
Save hildjj/acd124e55ee1ce4cf4633e33370a1bb3 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
import peg from "peggy-tag"; | |
const PLACEHOLDER = "{{{ARG}}}"; | |
const parse = peg` | |
{{ | |
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 | |
= "${PLACEHOLDER}" { | |
const arg = options.args[offset()]; | |
return typeof arg === 'number' ? arg : new Float64Array(arg) | |
} | |
`; | |
function p(strings, ...values) { | |
let text = ""; | |
const args = {}; | |
strings.forEach((string, i) => { | |
text += string; | |
if (i < values.length) { | |
args[text.length] = values[i]; | |
text += PLACEHOLDER; | |
} | |
}); | |
return parse(text, { args }); | |
} | |
console.log(p`${6}+${[2, 3]}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment