Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 320: Compiling Techniques David Walker. People David Walker (Professor) 412 Computer Science Building office hours: after each.

Similar presentations


Presentation on theme: "CS 320: Compiling Techniques David Walker. People David Walker (Professor) 412 Computer Science Building office hours: after each."— Presentation transcript:

1 CS 320: Compiling Techniques David Walker

2 People David Walker (Professor) 412 Computer Science Building dpw@cs.princeton.edu office hours: after each class Limin Jia, Jay Ligatti (TAs) 418a Computer Science Building ljia,jligatti@cs.princeton.edu office hours: Mondays & Wednesdays (we’ll send email to the email list)

3 Information Web site: www.cs.princeton.edu/courses/archive/spri ng05/cos320/index.htm www.cs.princeton.edu/courses/archive/spri ng05/cos320/index.htm Mailing list: To subscribe: cos320-request@lists.cs.princeton.edu To post to this list, send your email to: cos320@lists.cs.princeton.edu

4 Books Modern Compiler Implementation in ML, Andrew Appel A reference manual for SML best choice: Online references see course web site several hardcopy books Elements of ML Programming, Jeffrey D. Ullman

5 Work Assignments: build your own compiler approximately a module/week 40% late penalty: 20%/day. Don’t be late! ask questions of me, TAs, friends on course mailing list turn in your own work In class Midterm: 25% Final during exam period: 35%

6 Assignment 0 Write your name and other information on the sheet circulating Find, skim and bookmark the course web pages Subscribe to course e-mail list Begin assignment 1 Figure out how to install, run & use SML Due next Thursday February 16 If you’ve never used a functional language like ML, this might be a difficult assignment. Start early!

7 onward!

8 What is a compiler? A compiler is program that translates a source language into an equivalent target language

9 What is a compiler? while (i > 3) { a[i] = b[i]; i ++ } mov eax, ebx add eax, 1 cmp eax, 3 jcc eax, edx C program assembly program compiler does this

10 What is a compiler? class foo { int bar;... } struct foo { int bar;... } Java program compiler does this C program

11 What is a compiler? class foo { int bar;... }......................... Java program compiler does this Java virtual machine program

12 What is a compiler? \newcommand{.... } \sfd\sf\fadg Latex program compiler does this Tex program

13 What is a compiler? \newcommand{.... } \sfd\sf\fadg Tex program compiler does this Postscript program

14 What is a compiler? Other places: Web scripts are compiled into HTML assembly language is compiled into machine language hardware description language is compiled into a hardware circuit...

15 Compilers are complex text file to abstract syntax lexing; parsing abstract syntax to intermediate form (IR) type checking; analysis; optimizations; IR to machine code code generation; data layout; register allocation; more optimization front-end middle-end back-end

16 Course project Fun Source Language simple imperative language Only 1 IR (the initial abstract syntax generated by the parser) type checking; high-level optimizations Code Generation instruction selection algorithms; register allocation via graph coloring front-end middle-end back-end

17 Standard ML Standard ML is a domain-specific language for building compilers Support for Complex data structures (abstract syntax, compiler intermediate forms) Memory management like Java Large projects with many modules Advanced type system for error detection

18 Introduction to ML You will be responsible for learning ML on your own. Today I will cover some basics Resources: Robert Harper’s Online book “an introduction to ML” is a good place to start See course webpage for pointers and info about how to get the software

19 Preliminaries start sml in Unix by typing sml at a prompt: tux% sml Standard ML of New Jersey, Version 110.0.7, September 28, 2000 [CM; autoload enabled] - (* quit SML by pressing ctrl-D; ctrl-Z some times... *) (* just so you know, comments can be (* nested *) *)

20 Preliminaries Read – Eval – Print – Loop - 3 + 2;

21 Preliminaries Read – Eval – Print – Loop - 3 + 2; > 5: int

22 Preliminaries Read – Eval – Print – Loop - 3 + 2; > 5: int - it + 7; > 12 : int

23 Preliminaries Read – Eval – Print – Loop - 3 + 2; > 5: int - it + 7; > 12 : int - it – 3; > 9 : int - 4 + true; stdIn:17.1-17.9 Error: operator and operand don't agree [literal] operator domain: int * int operand: int * bool in expression: 4 + true

24 Preliminaries Read – Eval – Print – Loop - 3 div 0; Failure : Divrun-time error

25 Basic Values - (); > () : unit=> like “void” in C (sort of) => the uninteresting value/type - true; > true : bool - false; > false : bool - if it then 3+2 else 7;“else” clause is always necessary > 7 : int - false andalso loop_Forever; > false : booland also, or else short-circuit eval

26 Basic Values Integers - 3 + 2; > 5 : int - 3 + (if not true then 5 else 7); > 10 : intNo division between expressions and statements Strings - “Dave” ^ “ “ ^ “Walker”; > “Dave Walker” : string - print “foo\n”; foo > 3 : int Reals - 3.14; > 3.14 : real

27 Using SML/NJ Interactive mode is a good way to start learning and to debug programs, but… Type in a series of declarations into a “.sml” file - use “foo.sml” [opening foo.sml] … list of declarations with their types

28 Larger Projects SML has its own built in interactive “make” Pros: It automatically does the dependency analysis for you No crazy makefile syntax to learn Cons: May be more difficult to interact with other languages or tools

29 Compilation Manager % sml - OS.FileSys.chDir “ ~/courses/510/a2 ” ; - CM.make(); looks for “ sources.cm ”, analyzes dependencies [compiling … ] compiles files in group [wrote … ] saves binaries in./CM/ - CM.make ’ “ myproj/ ” (); specify directory sources.cm c.smlb.smla.sig Group is a.sig b.sml c.sml

30 What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “Dave”, ssn = 332177} Lists: 3::4::5::nil or [3,4]@[5] Datatypes Functions And more! Rather than list all the details, we will write a couple of programs

31 An interpreter Interpreters are usually implemented as a series of transformers: stream of characters (concrete syntax) abstract syntax lexing/ parsing evaluate abstract value print stream of characters

32 A little language (LL) An arithmetic expression e is a boolean value an if statement (if e1 then e2 else e3) an integer an add operation a test for zero (isZero e)

33 LL abstract syntax in ML datatype term = Bool of bool | If of term * term * term | Num of int | Add of term * term | IsZero of term vertical bar separates alternatives

34 LL abstract syntax in ML datatype term = Bool of bool | If of term * term * term | Num of int | Add of term * term | IsZero of term vertical bar separates alternatives This one declaration creates: a new type (called term) a new set of functions for creating terms (Bool, If, Num, Add, IsZero) a new set of patterns you can use case statements (like C’s “switch”) that check what sort of term object you have

35 LL abstract syntax in ML datatype term = Bool of bool | If of term * term * term | Num of int | Add of term * term | IsZero of term -- by convention, constructors are capitalized -- constructors can take a single argument of a particular type type of a tuple, in this case a triple of 3 term objects vertical bar separates alternatives

36 LL abstract syntax in ML In your program, writing: Add (Num 2, Num 3) makes an object tagged with Add containing 2 sub-objects tagged with Num represents the expression “2 + 3” Add Num 23

37 LL abstract syntax in ML If (Bool true, Num 0, Add (Num 2, Num 3)) represents “if true then 0 else 2 + 3” Add Num 2 3 true BoolNum 0 If

38 Function declarations fun isValue (t:term) : bool = case t of Num n => true | Bool b => true | _ => false

39 Function declarations fun isValue (t:term) : bool = case t of Num n => true | Bool b => true | _ => false function name function parameter t with type term default pattern matches anything function result type is bool patterns in pink

40 Function declarations fun isValue t = case t of Num n => true | Bool b => true | _ => false ML type inference can infer the types of parameters and results

41 A type error fun isValue t = case t of Num n => n | _ => false ex.sml:22.3-24.15 Error: types of rules don't agree [literal] earlier rule(s): term -> int this rule: term -> bool in rule: _ => false

42 A type error Sometimes, ML will give you several errors in a row: ex.sml:22.3-25.15 Error: types of rules don't agree [literal] earlier rule(s): term -> int this rule: term -> bool in rule: _ => true ex.sml:22.3-25.15 Error: types of rules don't agree [literal] earlier rule(s): term -> int this rule: term -> bool in rule: _ => false

43 A very subtle error fun isValue t = case t of num => true | _ => false The code above type checks. But when we test it refined the function always returns “true.” What has gone wrong?

44 A very subtle error fun isValue t = case t of num => true | _ => false The code above type checks. But when we test it refined the function always returns “true.” What has gone wrong? -- num is not capitalized (and has no argument) -- ML treats it like a variable pattern (matches anything!)

45 Exceptions exception Error of string fun debug s : unit = raise (Error s)

46 Exceptions exception Error of string fun debug s : unit = raise (Error s) - debug "hello"; uncaught exception Error raised at: ex.sml:15.28-15.35 in SML interpreter:

47 Evaluator fun isValue t =... exception NoRule fun eval t = case t of Bool _ | Num _ => t |...

48 Evaluator... fun eval t = case t of Bool _ | Num _ => t | If(t1,t2,t3) => let val v = eval t1 in case v of Bool b => if b then (eval t2) else (eval t3) | _ => raise NoRule end let statement for remembering temporary results

49 Evaluator exception NoRule fun eval1 t = case t of Bool _ | Num _ =>... |... | Add (t1,t2) => case (eval v1, eval v2) of (Num n1, Num n2) => Num (n1 + n2) | (_,_) => raise NoRule

50 Finishing the Evaluator fun eval1 t = case t of... |... | Add (t1,t2) =>... | IsZero t =>... be sure your case is exhaustive

51 Finishing the Evaluator fun eval1 t = case t of... |... | Add (t1,t2) =>... What if we forgot a case?

52 Finishing the Evaluator ex.sml:25.2-35.12 Warning: match nonexhaustive (Bool _ | Zero) =>... If (t1,t2,t3) =>... Add (t1,t2) =>... fun eval1 t = case t of... |... | Add (t1,t2) =>... What if we forgot a case?

53 Summary All ML expressions produce values that have a particular type ML doesn’t have “statements” ML can do type inference (and give you hard-to-decrypt error messages ML data types are super-cool a new type name (term) new constructors (Bool, If, Num,...) new patterns (Bool b, If (x,y,_), Num _,...) ML has a “top-level loop” to execute commands and a compilation manager type CM.Make() to load and compile a project edit sources.cm to add new files

54 Last Things Learning to program in SML can be tricky at first But once you get used to it, you will never want to go back to imperative languages Check out the reference materials listed on the course homepage


Download ppt "CS 320: Compiling Techniques David Walker. People David Walker (Professor) 412 Computer Science Building office hours: after each."

Similar presentations


Ads by Google