SlideShare a Scribd company logo
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 Code
Kamil Mówiński
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
jeresig
 
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 196
Mahmoud Samir Fayed
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
Nelson Glauber Leal
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talks
jeresig
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
“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
AvitoTech
 
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
Alessandro Nadalin
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
Eugene Zharkov
 
Scalaで実装してみる簡易ブロックチェーン
Scalaで実装してみる簡易ブロックチェーンScalaで実装してみる簡易ブロックチェーン
Scalaで実装してみる簡易ブロックチェーン
Hiroshi Ito
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
erwanl
 
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
Mahmoud 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 30
Mahmoud Samir Fayed
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
Kenneth Geisshirt
 
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
RORLAB
 
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
jorgeortiz85
 

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 code
Laurence 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 Services
WSO2
 
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ów
Konrad Kokosa
 
Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
Giovanni Bassi
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
Sergey 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 8
tdc-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 Win32
Windows 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 2015
Windows Developer
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
Jeremy Grancher
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
Maurizio 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 SDK
Mifeng
 
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 35
Bilal Ahmed
 
SFO15-500: VIXL
SFO15-500: VIXLSFO15-500: VIXL
SFO15-500: VIXL
Linaro
 
iOS Automation Primitives
iOS Automation PrimitivesiOS Automation Primitives
iOS Automation Primitives
Synack
 
Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016Owasp orlando, april 13, 2016
Owasp orlando, april 13, 2016
Mikhail 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 Video
C4Media
 
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
C4Media
 
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
C4Media
 
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
C4Media
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
C4Media
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
C4Media
 
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
C4Media
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
C4Media
 
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
C4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
C4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
C4Media
 
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
C4Media
 
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
C4Media
 
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
C4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
C4Media
 
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
C4Media
 
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
C4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
C4Media
 
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
C4Media
 
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
C4Media
 

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

20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 

Recently uploaded (20)

20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 

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/