How to be* a compiler — make a compiler with JavaScript

DNB code sample from http://dbn.media.mit.edu/introduction.html
My imaginary compiler, where code goes to be punished. If the code is bad, it’s captured in error message forever.

Let’s try to be a compiler first

Paper 0
Pen 100
Line 0 50 100 50
Compiled result

How does a compiler work ?

1. Lexical Analysis (tokenization)

lexical analysis

2. Parsing (Syntactical Analysis)

Parsing

3. Transformation

Transformation

4. Code Generation

Code Generation

Let’s make a compiler

1. Lexer function

input: "Paper 100"
output:[
{ type: "word", value: "Paper" }, { type: "number", value: 100 }
]

2. Parser function

input: [
{ type: "word", value: "Paper" }, { type: "number", value: 100 }
]
output: {
"type": "Drawing",
"body": [{
"type": "CallExpression",
"name": "Paper",
"arguments": [{ "type": "NumberLiteral", "value": "100" }]
}]
}

3. Transformer function

input: {
"type": "Drawing",
"body": [{
"type": "CallExpression",
"name": "Paper",
"arguments": [{ "type": "NumberLiteral", "value": "100" }]
}]
}
output: {
"tag": "svg",
"attr": {
"width": 100,
"height": 100,
"viewBox": "0 0 100 100",
"xmlns": "http://www.w3.org/2000/svg",
"version": "1.1"
},
"body": [{
"tag": "rect",
"attr": {
"x": 0,
"y": 0,
"width": 100,
"height": 100,
"fill": "rgb(0%, 0%, 0%)"
}
}]
}

4. Generator function

input: {
"tag": "svg",
"attr": {
"width": 100,
"height": 100,
"viewBox": "0 0 100 100",
"xmlns": "http://www.w3.org/2000/svg",
"version": "1.1"
},
"body": [{
"tag": "rect",
"attr": {
"x": 0,
"y": 0,
"width": 100,
"height": 100,
"fill": "rgb(0%, 0%, 0%)"
}
}]
}
output:
<svg width="100" height="100" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="100" height="100" fill="rgb(0%, 0%, 0%)">
</rect>
</svg>

5. Put it all together as a compiler

https://kosamari.github.io/sbn/

Shouldn’t a compiler use recursion and traversal etc ?

Writing compiler is awesome

// ES (español script)
función () {
si (verdadero) {
return «¡Hola!»
}
}

Learnings from making a compiler

How I imagine compiler after making one myself

1. It’s okay to have unfamiliar things.

2. Don’t be a jerk with bad error message.

3. Context is everything

--

--

--

Knitting some Javascript at Scripto : Co-organizer @brooklyn_js

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mariko Kosaka

Mariko Kosaka

Knitting some Javascript at Scripto : Co-organizer @brooklyn_js

More from Medium

Unit Test React Applications With Jest and Enzyme

Get the First, Last and Middle Elements of an Array using JavaScript

Two try-catch caused dive deep into JavaScript asynchronous programming

ExpressWebJs Maintenance mode