SlideShare a Scribd company logo
1 of 65
Build your own
WebAssembly Compiler
Colin Eberhardt, Scott Logic
InfoQ.com: News & Community Site
• Over 1,000,000 software developers, architects and CTOs read the site world-
wide every month
• 250,000 senior developers subscribe to our weekly newsletter
• Published in 4 languages (English, Chinese, Japanese and Brazilian
Portuguese)
• Post content from our QCon conferences
• 2 dedicated podcast channels: The InfoQ Podcast, with a focus on
Architecture and The Engineering Culture Podcast, with a focus on building
• 96 deep dives on innovative topics packed as downloadable emags and
minibooks
• Over 40 new content items per week
Watch the video with slide
synchronization on InfoQ.com!
https://www.infoq.com/presentations/
webassembly-compiler/
Purpose of QCon
- to empower software development by facilitating the spread of
knowledge and innovation
Strategy
- practitioner-driven conference designed for YOU: influencers of
change and innovation in your teams
- speakers and topics driving the evolution and innovation
- connecting and catalyzing the influencers and innovators
Highlights
- attended by more than 12,000 delegates since 2007
- held in 9 cities worldwide
Presented at QCon San Francisco
www.qconsf.com
https://wasmweekly.news/
Why do we need
WebAssembly?
JavaScript is a compilation target
> WebAssembly or wasm is a new portable,
size- and load-time-efficient format
suitable for compilation to the web.
executedecode
compile + optimise
parse
compile + optimise
re-optimise
execute
garbage collection
Why create a
WebAssembly compiler?
https://insights.stackoverflow.com/survey/2019
Create an open source project
Meet Brendan Eich
Write an emulator
Create my own language and a compiler
Bucket List
var y = 0
while (y < 100)
y = (y + 1)
var x = 0
while (x < 100)
x = (x + 1)
var e = ((y / 50) - 1.5)
var f = ((x / 50) - 1)
var a = 0
var b = 0
var i = 0
var j = 0
var c = 0
while ((((i * i) + (j * j)) < 4) && (c < 255))
i = (((a * a) - (b * b)) + e)
j = (((2 * a) * b) + f)
a = i
b = j
c = (c + 1)
endwhile
A simple wasm module
const magicModuleHeader = [0x00, 0x61, 0x73, 0x6d];
const moduleVersion = [0x01, 0x00, 0x00, 0x00];
export const emitter: Emitter = () =>
Uint8Array.from([
...magicModuleHeader,
...moduleVersion
]);
● wasm modules are binary
● Typically delivered to the browser as a .wasm file
const wasm = emitter();
const instance = await WebAssembly.instantiate(wasm);
● Instantiated asynchronously via the JS API
● Runs alongside the JavaScript virtual machine
● This compiles the wasm module, returning the executable
○ … which currently does nothing!
An ‘add’ function
(module
(func (param f32) (param f32) (result f32)
get_local 0
get_local 1
f32.add)
(export "add" (func 0))
)
● wasm has a relatively simple instruction set
● Four numeric types
○ More complex types can be constructed in memory (more on this later ...)
● Stack machine
● WebAssembly has no built in I/O
+---------------------------------------------------------------------------+
| header: 0x00 0x61 0x73 0x6d version: 0x01 0x00 0x00 0x00 |
+---------------------------------------------------------------------------+
| type (0x01): (i32, i32) => (i32), (i64, i64) => () |
+---------------------------------------------------------------------------+
| import (0x02): “print”, “sin” |
+---------------------------------------------------------------------------+
| function (0x03): type 0, type 2, type 1 |
+---------------------------------------------------------------------------+
| etc ... |
+---------------------------------------------------------------------------+
| code (0x0a): code for fn 1, code for fn 2, code for fn 3 |
+---------------------------------------------------------------------------+
| etc ... |
const code = [
Opcodes.get_local /** 0x20 */,
...unsignedLEB128(0),
Opcodes.get_local /** 0x20 */,
...unsignedLEB128(1),
Opcodes.f32_add /** 0x92 */
];
const functionBody = encodeVector([
...encodeVector([]) /** locals */,
...code,
Opcodes.end /** 0x0b */
]);
const codeSection = createSection(Section.code, encodeVector([functionBody]));
get_local 0
get_local 1
f32.add
function encoding
$ xxd out.wasm
00000000: 0061 736d 0100 0000 0107 0160 027d 7d01 .asm.......`.}}.
00000010: 7d03 0201 0007 0701 0372 756e 0000 0a09 }........add....
00000020: 0107 0020 0020 0192 0b ... . ...
const { instance } = await WebAssembly.instantiate(wasm);
console.log(instance.exports.add(5, 6));
// 11
Building a compiler
var a = 0
var b = 0
var i = 0
e = ((y / 50) - 1.5)
f = ((x / 50) - 1)
while ((((i * i) + (j * j)) < 4) && (c < 255))
i = (((a * a) - (b * b)) + e)
j = (((2 * a) * b) + f)
a = i
b = j
c = (c + 1)
endwhile
variable
declaration
statement
variable
assignment
statement
while
statement
simple expression
(numeric literal)
expression tree
Tokeniser Parser Emitter
tokens ASTcode
chasm v0.1
print 12
print 46.1
Tokenizer
" print 23.1"
patterns
input
output
[]
"^[.0-9]+"
"^(print|var)"
"^s+"
" print 23.1"
patterns
input
output
[]
"^[.0-9]+"
"^(print|var)"
"^s+"
" print 23.1"
[
{
"type": "keyword",
"value": "print",
"index": 1
}
]
patterns
input
output
"^[.0-9]+"
"^(print|var)"
"^s+"
" print 23.1"
[
{
"type": "keyword",
"value": "print",
"index": 1
}
]
patterns
input
output
"^[.0-9]+"
"^(print|var)"
"^s+"
" print 23.1"
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
patterns
input
output
"^[.0-9]+"
"^(print|var)"
"^s+"
" print 23.1"
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
patterns
input
output
"^[.0-9]+"
"^(print|var)"
"^s+"
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
● Removes whitespace
● Basic validation of syntax
Parser
export const parse: Parser = tokens => {
const iterator = tokens[Symbol.iterator]();
let currentToken = iterator.next().value;
const eatToken = () =>
(currentToken = iterator.next().value);
[...]
const nodes: StatementNode[] = [];
while (index < tokens.length) {
nodes.push(parseStatement());
}
return nodes;
};
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
parser tokens
export const parse: Parser = tokens => {
const iterator = tokens[Symbol.iterator]();
let currentToken = iterator.next().value;
const eatToken = () =>
(currentToken = iterator.next().value);
[...]
const nodes: StatementNode[] = [];
while (currentToken) {
nodes.push(parseStatement());
}
return nodes;
};
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
parser tokens
const parseStatement = () => {
if (currentToken.type === "keyword") {
switch (currentToken.value) {
case "print":
eatToken();
return {
type: "printStatement",
expression: parseExpression()
};
}
}
};
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
parser tokens
const parseExpression = () => {
let node: ExpressionNode;
switch (currentToken.type) {
case "number":
node = {
type: "numberLiteral",
value: Number(currentToken.value)
};
eatToken();
return node;
}
};
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
parser tokens
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
tokens
[
{
"type": "printStatement",
"expression": {
"type": "numberLiteral",
"value": 23.1
}
}
]
AST
Emitter
const codeFromAst = ast => {
const code = [];
const emitExpression = node => {
switch (node.type) {
case "numberLiteral":
code.push(Opcodes.f32_const);
code.push(...ieee754(node.value));
break;
}
};
ast.forEach(statement => {
switch (statement.type) {
case "printStatement":
emitExpression(statement.expression);
code.push(Opcodes.call);
code.push(...unsignedLEB128(0));
break;
}
});
return code;
};
[
{
"type": "printStatement",
"expression": {
"type": "numberLiteral",
"value": 23.1
}
}
]
Demo Time!
[
{
"type": "keyword",
"value": "print",
"index": 1
},
{
"type": "number",
"value": "23.1",
"index": 7
}
]
tokens
[
{
"type": "printStatement",
"expression": {
"type": "numberLiteral",
"value": 42
}
}
]
AST wasm
0x43 f3.const
0xcd 42 (IEE754)
0xcc
0xb8
0x41
0x10 call
0x00 0 (LEB 128)
" print 42"
Program
Memory
Execution
Stack
push / pop
JavaScript
Host
import / export
chasm v0.2 - expressions
print ((42 + 10) / 2)
[
{ "type": "keyword", "value": "print" },
{ "type": "parens", "value": "(" },
{ "type": "parens", "value": "(" },
{ "type": "number", "value": "42" },
{ "type": "operator", "value": "+" },
{ "type": "number", "value": "10" },
{ "type": "parens", "value": ")" },
{ "type": "operator", "value": "/" },
{ "type": "number", "value": "2" },
{ "type": "parens", "value": ")" }
]
print ((42 + 10) / 2)
const parseExpression = () => {
let node: ExpressionNode;
switch (currentToken.type) {
case "number":
[...]
case "parens":
eatToken();
const left = parseExpression();
const operator = currentToken.value;
eatToken();
const right = parseExpression();
eatToken();
return {
type: "binaryExpression",
left, right, operator
};
}
};
[{
type: "printStatement",
expression: {
type: "binaryExpression",
left: {
type: "binaryExpression",
left: {
type: "numberLiteral",
value: 42
},
right: {
type: "numberLiteral",
value: 10
},
operator: "+"
},
right: {
type: "numberLiteral",
value: 2
},
operator: "/"
}
}];
print ((42 + 10) / 2)
const codeFromAst = ast => {
const code: number[] = [];
const emitExpression = (node) =>
traverse(node, (node) => {
switch (node.type) {
case "numberLiteral":
code.push(Opcodes.f32_const);
code.push(...ieee754(node.value));
break;
case "binaryExpression":
code.push(binaryOpcode[node.operator]);
break;
}
});
ast.forEach(statement => [...]);
return code;
};
depth-first
post-order traversal
(left, right, root)
const binaryOpcode = {
"+": Opcodes.f32_add,
"-": Opcodes.f32_sub,
"*": Opcodes.f32_mul,
"/": Opcodes.f32_div,
"==": Opcodes.f32_eq,
">": Opcodes.f32_gt,
"<": Opcodes.f32_lt,
"&&": Opcodes.i32_and
};
Demo Time!
chasm v0.3 - variables and
while loops
var f = 23
print f
(func (local f32)
f32.const 23
set_local 0
get_local 0
call 0)
while (f < 10)
...
endwhile
(block
(loop
[loop condition]
i32.eqz
br_if 1
[nested statements]
br 0)
)
Demo Time!
chasm v1.0 - setpixel
Program
Memory
Execution
Stack
push / pop
JavaScript
Host
import / export
Program
Memory
Execution
Stack
Linear
Memory
push / pop
ArrayBuffer
JavaScript
Host
i32.store
i32.load
...
import / export
Demo Time!
● WebAssembly is a relatively simple virtual machine
● It’s a fun playground
● <aside> TypeScript is great! </aside>
● Creating a (simple) compiler isn’t that hard
● A good way to ‘exercise’ your programming skills
● There is a _lot_ of creative energy being poured
into WebAssembly
● Hopefully _you_ have been inspired?
Recap
Create an open source project
Meet Brendan Eich
Write an emulator
Create my own language and a compiler
Bucket List
Bucket List
Create an open source project
Meet Brendan Eich
Write an emulator
Create my own language and a compiler
... that supports strings, arrays, functions,
lambdas, objects, ...
Build your own
WebAssembly Compiler
Colin Eberhardt, Scott Logic
https://github.com/ColinEberhardt/chasm
Watch the video with slide
synchronization on InfoQ.com!
https://www.infoq.com/presentations/
webassembly-compiler/

More Related Content

What's hot

Design Patterns in Go Code
Design Patterns in Go CodeDesign Patterns in Go Code
Design Patterns in Go CodeKamil Mówiński
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 
Easy undo.key
Easy undo.keyEasy undo.key
Easy undo.keyzachwaugh
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using RoomNelson Glauber Leal
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talksjeresig
 
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the AirAvitoTech
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessorAlessandro Nadalin
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveEugene Zharkov
 
Scalaで実装してみる簡易ブロックチェーン
Scalaで実装してみる簡易ブロックチェーンScalaで実装してみる簡易ブロックチェーン
Scalaで実装してみる簡易ブロックチェーンHiroshi Ito
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensionserwanl
 
The Ring programming language version 1.5.4 book - Part 42 of 185
The Ring programming language version 1.5.4 book - Part 42 of 185The Ring programming language version 1.5.4 book - Part 42 of 185
The Ring programming language version 1.5.4 book - Part 42 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30Mahmoud Samir Fayed
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 
CS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBCS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBjorgeortiz85
 

What's hot (20)

Design Patterns in Go Code
Design Patterns in Go CodeDesign Patterns in Go Code
Design Patterns in Go Code
 
XQuery Rocks
XQuery RocksXQuery Rocks
XQuery Rocks
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Easy undo.key
Easy undo.keyEasy undo.key
Easy undo.key
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talks
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessor
 
Bookstore-Project
Bookstore-ProjectBookstore-Project
Bookstore-Project
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Scalaで実装してみる簡易ブロックチェーン
Scalaで実装してみる簡易ブロックチェーンScalaで実装してみる簡易ブロックチェーン
Scalaで実装してみる簡易ブロックチェーン
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 
The Ring programming language version 1.5.4 book - Part 42 of 185
The Ring programming language version 1.5.4 book - Part 42 of 185The Ring programming language version 1.5.4 book - Part 42 of 185
The Ring programming language version 1.5.4 book - Part 42 of 185
 
The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
BingoConsoleApp
BingoConsoleAppBingoConsoleApp
BingoConsoleApp
 
CS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBCS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDB
 

Similar to Build Your Own WebAssembly Compiler

JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesWSO2
 
Score (smart contract for icon)
Score (smart contract for icon) Score (smart contract for icon)
Score (smart contract for icon) Doyun Hwang
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wyciekówKonrad Kokosa
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important PartsSergey Bolshchikov
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8tdc-globalcode
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Windows Developer
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Windows Developer
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom componentsJeremy Grancher
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builderMaurizio Vitale
 
CP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKCP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKMifeng
 
Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features WSO2
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35Bilal Ahmed
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXLLinaro
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation PrimitivesSynack
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Mikhail Sosonkin
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Alessandro Molina
 

Similar to Build Your Own WebAssembly Compiler (20)

JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web Services
 
Score (smart contract for icon)
Score (smart contract for icon) Score (smart contract for icon)
Score (smart contract for icon)
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wycieków
 
Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 
CP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKCP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDK
 
Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features Complex Event Processor 3.0.0 - An overview of upcoming features
Complex Event Processor 3.0.0 - An overview of upcoming features
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXL
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation Primitives
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2
 

More from C4Media

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoC4Media
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileC4Media
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020C4Media
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsC4Media
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No KeeperC4Media
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like OwnersC4Media
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaC4Media
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideC4Media
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDC4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine LearningC4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at SpeedC4Media
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsC4Media
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsC4Media
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleC4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeC4Media
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereC4Media
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing ForC4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data EngineeringC4Media
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 
Navigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsNavigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsC4Media
 

More from C4Media (20)

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live Video
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy Mobile
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 
Navigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsNavigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery Teams
 

Recently uploaded

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Build Your Own WebAssembly Compiler

  • 1. Build your own WebAssembly Compiler Colin Eberhardt, Scott Logic
  • 2. InfoQ.com: News & Community Site • Over 1,000,000 software developers, architects and CTOs read the site world- wide every month • 250,000 senior developers subscribe to our weekly newsletter • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • 2 dedicated podcast channels: The InfoQ Podcast, with a focus on Architecture and The Engineering Culture Podcast, with a focus on building • 96 deep dives on innovative topics packed as downloadable emags and minibooks • Over 40 new content items per week Watch the video with slide synchronization on InfoQ.com! https://www.infoq.com/presentations/ webassembly-compiler/
  • 3. Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide Presented at QCon San Francisco www.qconsf.com
  • 5.
  • 6. Why do we need WebAssembly?
  • 7. JavaScript is a compilation target
  • 8.
  • 9.
  • 10. > WebAssembly or wasm is a new portable, size- and load-time-efficient format suitable for compilation to the web.
  • 11. executedecode compile + optimise parse compile + optimise re-optimise execute garbage collection
  • 14. Create an open source project Meet Brendan Eich Write an emulator Create my own language and a compiler Bucket List
  • 15. var y = 0 while (y < 100) y = (y + 1) var x = 0 while (x < 100) x = (x + 1) var e = ((y / 50) - 1.5) var f = ((x / 50) - 1) var a = 0 var b = 0 var i = 0 var j = 0 var c = 0 while ((((i * i) + (j * j)) < 4) && (c < 255)) i = (((a * a) - (b * b)) + e) j = (((2 * a) * b) + f) a = i b = j c = (c + 1) endwhile
  • 16. A simple wasm module
  • 17. const magicModuleHeader = [0x00, 0x61, 0x73, 0x6d]; const moduleVersion = [0x01, 0x00, 0x00, 0x00]; export const emitter: Emitter = () => Uint8Array.from([ ...magicModuleHeader, ...moduleVersion ]); ● wasm modules are binary ● Typically delivered to the browser as a .wasm file
  • 18. const wasm = emitter(); const instance = await WebAssembly.instantiate(wasm); ● Instantiated asynchronously via the JS API ● Runs alongside the JavaScript virtual machine ● This compiles the wasm module, returning the executable ○ … which currently does nothing!
  • 20. (module (func (param f32) (param f32) (result f32) get_local 0 get_local 1 f32.add) (export "add" (func 0)) ) ● wasm has a relatively simple instruction set ● Four numeric types ○ More complex types can be constructed in memory (more on this later ...) ● Stack machine ● WebAssembly has no built in I/O
  • 21. +---------------------------------------------------------------------------+ | header: 0x00 0x61 0x73 0x6d version: 0x01 0x00 0x00 0x00 | +---------------------------------------------------------------------------+ | type (0x01): (i32, i32) => (i32), (i64, i64) => () | +---------------------------------------------------------------------------+ | import (0x02): “print”, “sin” | +---------------------------------------------------------------------------+ | function (0x03): type 0, type 2, type 1 | +---------------------------------------------------------------------------+ | etc ... | +---------------------------------------------------------------------------+ | code (0x0a): code for fn 1, code for fn 2, code for fn 3 | +---------------------------------------------------------------------------+ | etc ... |
  • 22. const code = [ Opcodes.get_local /** 0x20 */, ...unsignedLEB128(0), Opcodes.get_local /** 0x20 */, ...unsignedLEB128(1), Opcodes.f32_add /** 0x92 */ ]; const functionBody = encodeVector([ ...encodeVector([]) /** locals */, ...code, Opcodes.end /** 0x0b */ ]); const codeSection = createSection(Section.code, encodeVector([functionBody])); get_local 0 get_local 1 f32.add function encoding
  • 23. $ xxd out.wasm 00000000: 0061 736d 0100 0000 0107 0160 027d 7d01 .asm.......`.}}. 00000010: 7d03 0201 0007 0701 0372 756e 0000 0a09 }........add.... 00000020: 0107 0020 0020 0192 0b ... . ... const { instance } = await WebAssembly.instantiate(wasm); console.log(instance.exports.add(5, 6)); // 11
  • 25. var a = 0 var b = 0 var i = 0 e = ((y / 50) - 1.5) f = ((x / 50) - 1) while ((((i * i) + (j * j)) < 4) && (c < 255)) i = (((a * a) - (b * b)) + e) j = (((2 * a) * b) + f) a = i b = j c = (c + 1) endwhile variable declaration statement variable assignment statement while statement simple expression (numeric literal) expression tree
  • 31. " print 23.1" [ { "type": "keyword", "value": "print", "index": 1 } ] patterns input output "^[.0-9]+" "^(print|var)" "^s+"
  • 32. " print 23.1" [ { "type": "keyword", "value": "print", "index": 1 } ] patterns input output "^[.0-9]+" "^(print|var)" "^s+"
  • 33. " print 23.1" [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] patterns input output "^[.0-9]+" "^(print|var)" "^s+"
  • 34. " print 23.1" [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] patterns input output "^[.0-9]+" "^(print|var)" "^s+"
  • 35. [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] ● Removes whitespace ● Basic validation of syntax
  • 37. export const parse: Parser = tokens => { const iterator = tokens[Symbol.iterator](); let currentToken = iterator.next().value; const eatToken = () => (currentToken = iterator.next().value); [...] const nodes: StatementNode[] = []; while (index < tokens.length) { nodes.push(parseStatement()); } return nodes; }; [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] parser tokens
  • 38. export const parse: Parser = tokens => { const iterator = tokens[Symbol.iterator](); let currentToken = iterator.next().value; const eatToken = () => (currentToken = iterator.next().value); [...] const nodes: StatementNode[] = []; while (currentToken) { nodes.push(parseStatement()); } return nodes; }; [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] parser tokens
  • 39. const parseStatement = () => { if (currentToken.type === "keyword") { switch (currentToken.value) { case "print": eatToken(); return { type: "printStatement", expression: parseExpression() }; } } }; [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] parser tokens
  • 40. const parseExpression = () => { let node: ExpressionNode; switch (currentToken.type) { case "number": node = { type: "numberLiteral", value: Number(currentToken.value) }; eatToken(); return node; } }; [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] parser tokens
  • 41. [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] tokens [ { "type": "printStatement", "expression": { "type": "numberLiteral", "value": 23.1 } } ] AST
  • 43. const codeFromAst = ast => { const code = []; const emitExpression = node => { switch (node.type) { case "numberLiteral": code.push(Opcodes.f32_const); code.push(...ieee754(node.value)); break; } }; ast.forEach(statement => { switch (statement.type) { case "printStatement": emitExpression(statement.expression); code.push(Opcodes.call); code.push(...unsignedLEB128(0)); break; } }); return code; }; [ { "type": "printStatement", "expression": { "type": "numberLiteral", "value": 23.1 } } ]
  • 45. [ { "type": "keyword", "value": "print", "index": 1 }, { "type": "number", "value": "23.1", "index": 7 } ] tokens [ { "type": "printStatement", "expression": { "type": "numberLiteral", "value": 42 } } ] AST wasm 0x43 f3.const 0xcd 42 (IEE754) 0xcc 0xb8 0x41 0x10 call 0x00 0 (LEB 128) " print 42"
  • 47. chasm v0.2 - expressions print ((42 + 10) / 2)
  • 48. [ { "type": "keyword", "value": "print" }, { "type": "parens", "value": "(" }, { "type": "parens", "value": "(" }, { "type": "number", "value": "42" }, { "type": "operator", "value": "+" }, { "type": "number", "value": "10" }, { "type": "parens", "value": ")" }, { "type": "operator", "value": "/" }, { "type": "number", "value": "2" }, { "type": "parens", "value": ")" } ] print ((42 + 10) / 2)
  • 49. const parseExpression = () => { let node: ExpressionNode; switch (currentToken.type) { case "number": [...] case "parens": eatToken(); const left = parseExpression(); const operator = currentToken.value; eatToken(); const right = parseExpression(); eatToken(); return { type: "binaryExpression", left, right, operator }; } };
  • 50. [{ type: "printStatement", expression: { type: "binaryExpression", left: { type: "binaryExpression", left: { type: "numberLiteral", value: 42 }, right: { type: "numberLiteral", value: 10 }, operator: "+" }, right: { type: "numberLiteral", value: 2 }, operator: "/" } }]; print ((42 + 10) / 2)
  • 51. const codeFromAst = ast => { const code: number[] = []; const emitExpression = (node) => traverse(node, (node) => { switch (node.type) { case "numberLiteral": code.push(Opcodes.f32_const); code.push(...ieee754(node.value)); break; case "binaryExpression": code.push(binaryOpcode[node.operator]); break; } }); ast.forEach(statement => [...]); return code; }; depth-first post-order traversal (left, right, root) const binaryOpcode = { "+": Opcodes.f32_add, "-": Opcodes.f32_sub, "*": Opcodes.f32_mul, "/": Opcodes.f32_div, "==": Opcodes.f32_eq, ">": Opcodes.f32_gt, "<": Opcodes.f32_lt, "&&": Opcodes.i32_and };
  • 53. chasm v0.3 - variables and while loops
  • 54. var f = 23 print f (func (local f32) f32.const 23 set_local 0 get_local 0 call 0)
  • 55. while (f < 10) ... endwhile (block (loop [loop condition] i32.eqz br_if 1 [nested statements] br 0) )
  • 57. chasm v1.0 - setpixel
  • 61. ● WebAssembly is a relatively simple virtual machine ● It’s a fun playground ● <aside> TypeScript is great! </aside> ● Creating a (simple) compiler isn’t that hard ● A good way to ‘exercise’ your programming skills ● There is a _lot_ of creative energy being poured into WebAssembly ● Hopefully _you_ have been inspired? Recap
  • 62. Create an open source project Meet Brendan Eich Write an emulator Create my own language and a compiler Bucket List
  • 63. Bucket List Create an open source project Meet Brendan Eich Write an emulator Create my own language and a compiler ... that supports strings, arrays, functions, lambdas, objects, ...
  • 64. Build your own WebAssembly Compiler Colin Eberhardt, Scott Logic https://github.com/ColinEberhardt/chasm
  • 65. Watch the video with slide synchronization on InfoQ.com! https://www.infoq.com/presentations/ webassembly-compiler/