-
-
Save starakaj/ffcd030070b3b9b82301b9ac86293564 to your computer and use it in GitHub Desktop.
Babel templates in our translator
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 template from "@babel/template"; | |
// ... | |
const makePaintFunction = template(` | |
function paint() { | |
%%statements%% | |
} | |
`); | |
const makeRectDrawStatements = template(` | |
mgraphics.rectangle(%%x%%, %%y%%, %%w%%, %%h%%); | |
mgraphics.fill(); | |
`); | |
/** | |
* This is where the interesting stuff happens. We'll read in the source data, build an AST, | |
* create another AST, and then use that to generate an output in a new language. | |
* @param data - Input data in SVG format | |
* @param outPath - Path to which we'd like our result to be written | |
*/ | |
function translateSource(data: string, outPath: string) { | |
let paintStatements: t.Statement[] = []; | |
const parser = new html2.Parser({ | |
onopentag(name: string, attribs: {[s: string]: string}) { | |
if (name === "rect") { | |
let x = Number.parseFloat(attribs.x || "0"); | |
let y = Number.parseFloat(attribs.y || "0"); | |
let w = Number.parseFloat(attribs.width || "0"); | |
let h = Number.parseFloat(attribs.height || "0"); | |
const rectStatements = makeRectDrawStatements({ x, y, w, h }); | |
paintStatements = paintStatements.concat(rectStatements); | |
} | |
} | |
}); | |
parser.parseComplete(data); | |
const paintFunction = ([] as t.Statement[]).concat(makePaintFunction({ statements: paintStatements })); | |
const programAST = t.program(paintFunction); | |
// Somehow turn our program AST into an outputString | |
fs.writeFile(outPath, outputString, { encoding: "utf8" }, () => { | |
console.log(`Wrote output to ${outPath}`); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment