write your own compiler in 24 hours

16
24 HOURS LATER Phillip Trelford, @ptrelford #DDDNorth, Leeds, 2014

Upload: phillip-trelford

Post on 01-Dec-2014

340 views

Category:

Technology


1 download

DESCRIPTION

Compiler talk at DDD North in Leeds

TRANSCRIPT

Page 1: Write Your Own Compiler in 24 Hours

24 HOURS LATER Phillip Trelford, @ptrelford#DDDNorth, Leeds, 2014

Page 2: Write Your Own Compiler in 24 Hours

THIS TALK IS *NOT*

About how to write a compiler the hard way

All theory

For the faint of heart

Page 3: Write Your Own Compiler in 24 Hours

THIS TALK *IS* ABOUT

Abstract Syntax Trees

Parsing

Domain Specific Languages

Interpreters

Code Generation

Page 4: Write Your Own Compiler in 24 Hours

LANGUAGE FAMILIES

Lisp

C

ML

BASIC

Page 5: Write Your Own Compiler in 24 Hours

LANGUAGE DESIGN (CONSIDERED OPTIONAL)

Adhoc• PHP• JavaScript• Scala

Copy&Delete• Java• J• Go

Copy&Add• C#• F#• Haskell

Page 6: Write Your Own Compiler in 24 Hours

TO THE TURTLES CODE

Phillip Trelford, @ptrelford#DDDNorth, Leeds, 2014

Page 7: Write Your Own Compiler in 24 Hours

TURTLE LANGUAGE

repeat 10

[right 36 repeat 5

[forward 54 right 72]]

Page 8: Write Your Own Compiler in 24 Hours

TURTLE AST

module AST

type arg = int

type command =

| Forward of arg

| Turn of arg

| Repeat of arg * command list

Page 9: Write Your Own Compiler in 24 Hours

TWO GIRLS (5 & 7YRS) + TURTLE

Page 10: Write Your Own Compiler in 24 Hours

SMALL BASIC SAMPLE

Sub Init

gw = 598

gh = 428

GraphicsWindow.BackgroundColor = "DodgerBlue"

GraphicsWindow.Width = gw

GraphicsWindow.Height = gh

color = "1=Orange;2=Cyan;3=Lime;"

size = "1=20;2=16;3=12;"

passed = 0

cd = "False" ' collision detected

EndSub

Page 11: Write Your Own Compiler in 24 Hours

SMALL BASIC AST

/// Small Basic expressiontype expr = | Literal of value | Identifier of identifier | GetAt of location | Func of invoke | Neg of expr | Arithmetic of expr * arithmetic * expr | Comparison of expr * comparison * expr | Logical of expr * logical * expr

/// Small Basic instruction type instruction = | Assign of assign | SetAt of location * expr | PropertySet of string * string * expr

| Action of invoke | For of assign * expr * expr | EndFor | If of expr | ElseIf of expr | Else | EndIf | While of expr | EndWhile | Sub of identifier * string list | EndSub | Label of label | Goto of label

Page 12: Write Your Own Compiler in 24 Hours

RESOURCES

Page 13: Write Your Own Compiler in 24 Hours

F# KOANS

[<Koan>]let SquareEvenNumbersWithPipelineOperator() =(* In F#, you can use the pipeline operator to get the benefit of the parens style with the readability of the statement style. *)

let result = [0..5] |> List.filter isEven |> List.map square AssertEquality result __

Page 14: Write Your Own Compiler in 24 Hours

TRYFSHARP.ORG

Page 15: Write Your Own Compiler in 24 Hours

F# BOOKS