Writing Evaluators MIF08. Laure Gonnord
|
|
- Christian Murphy
- 6 years ago
- Views:
Transcription
1 Writing Evaluators MIF08 Laure Gonnord
2 Evaluators, what for? Outline 1 Evaluators, what for? 2 Implementation Laure Gonnord (Lyon1/FST) Writing Evaluators 2 / 21
3 Evaluators, what for? Analysis Phases source code lexical analysis sequence of lexems (tokens) syntactic analysis (Parsing) abstract syntax tree (AST ) semantic analysis abstract syntax (+ symbol table) Laure Gonnord (Lyon1/FST) Writing Evaluators 3 / 21
4 Evaluators, what for? Until now We have parsed, and evaluate in semantic actions. But we want: more structure. an easier way to perform actions (not in the.g4 file). Laure Gonnord (Lyon1/FST) Writing Evaluators 4 / 21
5 Evaluators, what for? Notion of Abstract Syntax Tree = int y + 12 * 4 x int AST: memory representation of a program; Node: a language construct; Sub-nodes: parameters of the construct; Leaves: usually constants or variables. Laure Gonnord (Lyon1/FST) Writing Evaluators 5 / 21
6 Evaluators, what for? Separation of concerns The semantics of the program could be defined in the semantic actions (of the grammar). Usually though: Syntax analyzer only produces the AST; The rest of the compiler directly works with this AST. Why? Manipulating a tree (AST) is easy (recursive style); Separate language syntax from language semantics; During later compiler phases, we can assume that the AST is syntactically correct simplifies the rest of the compilation. Laure Gonnord (Lyon1/FST) Writing Evaluators 6 / 21
7 Evaluators, what for? Running example : Numerical expressions This is an abstract syntax (no more parenthesis,... ): Let us construct an AST to: e ::= c constant x variable e + e add e e mult... Evaluate this expression (by tree traversal) Later: generate code for these expressions (by tree traversal) Laure Gonnord (Lyon1/FST) Writing Evaluators 7 / 21
8 Implementation Outline 1 Evaluators, what for? 2 Implementation Old-school way Evaluators with visitors Laure Gonnord (Lyon1/FST) Writing Evaluators 8 / 21
9 Implementation Old-school way Outline 1 Evaluators, what for? 2 Implementation Old-school way Evaluators with visitors Laure Gonnord (Lyon1/FST) Writing Evaluators 9 / 21
10 Implementation Old-school way Explicit construction of the AST Declare a type for the abstract syntax. Construct instances of these types during parsing (trees). Evaluate with tree traversal. Laure Gonnord (Lyon1/FST) Writing Evaluators 10 / 21
11 Implementation Old-school way Example in Java 1/3 AST definition in Java: one class per language construct. public class APlus extends AExpr { AExpr e1, e2 ; public APlus ( AExpr e1, AExpr e2 ) { this. e1=e1 ; this. e2=e2 ; } } public class AMinus extends AExpr {... Laure Gonnord (Lyon1/FST) Writing Evaluators 11 / 21
12 Implementation Old-school way Example in Java 2/3 The parser builds an AST instance using AST classes defined previously. ArithExprASTParser.g4 parser grammar A r i t h E x p r A S T P a r s e r ; options { tokenvocab = ArithExprASTLexer; } prog returns [ AExpr e ] : expr EOF { $e= $expr. e; } ; // We create an AExpr instead of computing a value expr returns [ AExpr e ] : LPAR x= expr RPAR { $e=$x. e; } INT { $e = new AInt ( $INT. int ) ; } e1 = expr PLUS e2 = expr { $e = new APlus ( $e1. e,$e2. e ) ; } e1 = expr MINUS e2 = expr { $e = new AMinus ( $e1. e,$e2. e ) ; } ; Laure Gonnord (Lyon1/FST) Writing Evaluators 12 / 21
13 Implementation Old-school way Example in Java 3/3 Evaluation is an eval function per class: AExpr.java p u b l i c a b s t r a c t class AExpr { a b s t r a c t i n t eval ( ) ; / / need to provide semantics } APlus.java public class APlus extends AExpr { AExpr e1, e2 ; public APlus ( AExpr e1, AExpr e2 ) { this. e1=e1 ; this. e2=e2 ; } / / semantics below i n t eval ( ) { return ( e1. eval ( ) + e2. eval ( ) ) ; } } Laure Gonnord (Lyon1/FST) Writing Evaluators 13 / 21
14 Implementation Evaluators with visitors Outline 1 Evaluators, what for? 2 Implementation Old-school way Evaluators with visitors Laure Gonnord (Lyon1/FST) Writing Evaluators 14 / 21
15 Implementation Evaluators with visitors Principle - OO programming The visitor design pattern is a way of separating an algorithm from an object structure on which it operates.[...] In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. Laure Gonnord (Lyon1/FST) Writing Evaluators 15 / 21
16 Implementation Evaluators with visitors Application Designing evaluators / tree traversal in ANTLR-Python The ANTLR compiler generates a Visitor class. We override this class to traverse the parsed instance. Laure Gonnord (Lyon1/FST) Writing Evaluators 16 / 21
17 Implementation Evaluators with visitors Example with ANTLR/Python 1/3 AritParser.g4 expr: expr mdop expr # m u l t i p l i c a t i o n E x p r expr pmop expr # a d d i t i v e E x p r atom # atomexpr ; atom : INT # int ID # id '( ' expr ') ' # parens compilation with -Dlanguage=Python3 -visitor Laure Gonnord (Lyon1/FST) Writing Evaluators 17 / 21
18 Implementation Evaluators with visitors Example with ANTLR/Python 2/3 -generated file class A r i t V i s i t o r ( P a r s e T r e e V i s i t o r ) :... # V i s i t a parse t r e e produced by A r i t P a r s e r # m u l t i p l i c a t i o n E x p r. def v i s i t M u l t i p l i c a t i o n E x p r ( s e l f, c t x ) : r e t u r n s e l f. v i s i t C h i l d r e n ( c t x ).. # V i s i t a parse t r e e produced by A r i t P a r s e r #atomexpr. def visitatomexpr ( s e l f, c t x ) : r e t u r n s e l f. v i s i t C h i l d r e n ( c t x ) Laure Gonnord (Lyon1/FST) Writing Evaluators 18 / 21
19 Implementation Evaluators with visitors Example with ANTLR/Python 3/3 Visitor class overriding to write the evaluator: MyAritVisitor.py class M y A r i t V i s i t o r ( A r i t V i s i t o r ) : # V i s i t a parse t r e e produced by A r i t P a r s e r # i n t. def v i s i t I n t ( s e l f, c t x ) : value = i n t ( c t x. gettext ( ) ) ; r e t u r n value ; def v i s i t M u l t i p l i c a t i o n E x p r ( s e l f, c t x ) : l e f t v a l = s e l f. v i s i t ( c t x. expr ( 0 ) ) r i g h t v a l = s e l f. v i s i t ( c t x. expr ( 1 ) ) myop = s e l f. v i s i t ( c t x. mdop ( ) ) i f ( myop == ) : r e t u r n l e f t v a l r i g h t v a l else : r e t u r n l e f t v a l / r i g h t v a l Laure Gonnord (Lyon1/FST) Writing Evaluators 19 / 21
20 Implementation Evaluators with visitors Nice Picture (Lab#3) Arit.g4 Tree.py antlr -visitor inherits from AritParser.py AritVisitor.py inherits from MyAritVisitor.py Laure Gonnord (Lyon1/FST) Writing Evaluators 20 / 21
21 Implementation Evaluators with visitors From grammars to evaluators - summary The meaning of each operation/grammar rule is now given by the implementation of the associated function in the visitor. The visitor performs a tree traversal on the structure of the parse tree. Laure Gonnord (Lyon1/FST) Writing Evaluators 21 / 21
22 Types, Typing MIF08 Laure Gonnord
23 Typing + Laure Gonnord (Lyon1/FST) Typing (simple) programs 2 / 18
24 Typing / Laure Gonnord (Lyon1/FST) Typing (simple) programs 3 / 18
25 Typing If you write: "5" + 37 what do you want to obtain a compilation error? (OCaml) an exec error? (Python) the int 42? (Visual Basic, PHP) the string "537"? (Java) anything else? and what about 37 / "5"? Typing: an analysis that gives a type to each subexpression, and reject incoherent programs. Laure Gonnord (Lyon1/FST) Typing (simple) programs 4 / 18
26 When Dynamic typing (during exec): Lisp, PHP, Python Static typing (at compile time): C, Java, OCaml Here: the second one. Laure Gonnord (Lyon1/FST) Typing (simple) programs 5 / 18
27 Typing objectives well typed programs do not go wrong Should be decidable. It should reject programs like (1 2) in OCaml, or 1+"toto" in C before an actual arror in the evaluation of the expression: this is safety. The type system should be expressive enough and not reject too many programs. (expressivity) Laure Gonnord (Lyon1/FST) Typing (simple) programs 6 / 18
28 Several solutions All sub-expressions are anotated by a type fun (x : int) let (y : int) = (+ :)(((x : int), (1 : int)) : int int) in easy to verify, but tedious for the programmer Annotate only variable declarations (Pascal, C, Java,... ) fun (x : int) let (y : int) = +(x, 1) in y Only annotate function parameters fun (x : int) let y = +(x, 1) in y Do nothing : complete inference : Ocaml, Haskell,... Laure Gonnord (Lyon1/FST) Typing (simple) programs 7 / 18
29 Simple Type Checking for mini-while, theory Outline 1 Simple Type Checking for mini-while, theory 2 A bit of implementation (for expr) Laure Gonnord (Lyon1/FST) Typing (simple) programs 8 / 18
30 Simple Type Checking for mini-while, theory Mini-While Syntax Expressions: Mini-while: e ::= c constant x variable e + e addition e e multiplication... S(Smt) ::= x := expr assign skip do nothing S 1 ; S 2 sequence if b then S 1 else S 2 test while b do S done loop Laure Gonnord (Lyon1/FST) Typing (simple) programs 9 / 18
31 Simple Type Checking for mini-while, theory Typing judgement We will define how to compute typing judgements denoted by: Γ e : τ and means in environment Γ, expression e has type τ Γ associates a type Γ(x) to all free variables x in e (in this course, computed from the variable declarations). Here types are basic types: Int String Bool Laure Gonnord (Lyon1/FST) Typing (simple) programs 10 / 18
32 Simple Type Checking for mini-while, theory Typing rules for expr (or bool,... ) Γ x : Γ(x) Γ n : int Γ e 1 : int Γ e 2 : int Γ e 1 + e 2 : int An expression is well typed if there is a proof tree for it with regular applications of the rules, and whose leaves are axioms. Laure Gonnord (Lyon1/FST) Typing (simple) programs 11 / 18
33 Simple Type Checking for mini-while, theory Hybrid expressions What if we have ? reject? compute a float! This is type coercion. Laure Gonnord (Lyon1/FST) Typing (simple) programs 12 / 18
34 Simple Type Checking for mini-while, theory More complex expressions What if we have types pointer of bool or array of int? We might want to check equivalence (for addition... ). This is called structural equivalence (see Dragon Book, type equivalence ). This is solved by a basic graph traversal. Laure Gonnord (Lyon1/FST) Typing (simple) programs 13 / 18
35 Simple Type Checking for mini-while, theory Typing rules for statements - See TD2 Idea: the type is void otherwise typing error Γ e : t Γ(x) : t t {int, bool} Γ x := e : void Γ b : bool Γ S : void Γ while b do S done : void A program is well typed if there is a proof tree with regular applications of the rules whose leaves are axioms. Laure Gonnord (Lyon1/FST) Typing (simple) programs 14 / 18
36 A bit of implementation (for expr) Outline 1 Simple Type Checking for mini-while, theory 2 A bit of implementation (for expr) Laure Gonnord (Lyon1/FST) Typing (simple) programs 15 / 18
37 A bit of implementation (for expr) Principle of type checking Gamma is constructed with lexing information or parsing (variable declaration with types). Rules are semantic actions. The semantic actions are responsible for the evaluation order, as well as typing errors. Laure Gonnord (Lyon1/FST) Typing (simple) programs 16 / 18
38 A bit of implementation (for expr) Type Checking (here): visitor (Lab3) MyMuTypingVisitor.py def v i s i t A d d i t i v e E x p r ( s e l f, c t x ) : l v a l t y p e = s e l f. v i s i t ( c t x. expr ( 0 ) ) r v a l t y p e = s e l f. v i s i t ( c t x. expr ( 1 ) ) op = s e l f. v i s i t ( c t x. oplus ( ) ) i f l v a l t y p e == r v a l t y p e : r e t u r n l v a l t y p e e l i f { l v a l t y p e, r v a l t y p e } == { BaseType. Integer, BaseType. F l o a t } : r e t u r n BaseType. F l o a t e l i f op == u + and any ( v t == BaseType. S t r i n g f o r v t i n ( r v a l t y p e, l v a l t y p e ) ) : r e t u r n BaseType. S t r i n g else : r a i s e SyntaxError ( " I n v a l i d type f o r a d d i t i v e operand " ) Laure Gonnord (Lyon1/FST) Typing (simple) programs 17 / 18
39 A bit of implementation (for expr) Typing is more than type checking. Sometimes we want this information during code generation AST decorated with types (but not in this course) And we want informative errors: Type error at line 42 is not sufficient! Laure Gonnord (Lyon1/FST) Typing (simple) programs 18 / 18
40 Code Generation MIF08 Laure Gonnord oct 2017
41 Big picture source code lexical+syntactic analysis + typing decorated AST code production (numerous phases) assembly language Laure Gonnord (Lyon1/FST) Code Generation / 21
42 Rules of the Game here For this code generation: Still no functions and no non-basic types. (mini-while) Syntax-directed: one grammar rule a set of instructions. Code redundancy. No register reuse: everything will be stored on the stack. The Target Machine : LEIA (course #1) Laure Gonnord (Lyon1/FST) Code Generation / 21
43 3-address syntax-directed Code Generation Outline 1 3-address syntax-directed Code Generation Rules 2 Memory allocation 3 Toward a more efficient Code Generation Laure Gonnord (Lyon1/FST) Code Generation / 21
44 3-address syntax-directed Code Generation A first example (1/4) How do we translate: var x;y:int; x=4; y=12+x; Variable decl s visitor gives a place to each variable: x place0, y place1. Compute 4, store somewhere, then copy in x s place. Compute 12 + x : 12 in place1, copy the value of x in place2, then add, store in place3, then copy into y s place. the code generator will use a place generator called newtmp() Laure Gonnord (Lyon1/FST) Code Generation / 21
45 3-address syntax-directed Code Generation A first example: 3@code (2/4) Compute 4 and store in x (temp0) :.let temp2 4 copy temp0 temp2 Laure Gonnord (Lyon1/FST) Code Generation / 21
46 3-address syntax-directed Code Generation Objective 3-address LEIA Code Generation for the Mini-While language: All variables are int/bool. All variables are global. No functions with syntax-directed translation. Implementation in Lab. This is called three-adress code generation Laure Gonnord (Lyon1/FST) Code Generation / 21
47 3-address syntax-directed Code Generation Rules Outline 1 3-address syntax-directed Code Generation Rules 2 Memory allocation 3 Toward a more efficient Code Generation Laure Gonnord (Lyon1/FST) Code Generation / 21
48 3-address syntax-directed Code Generation Rules Code generation utility functions We will use: A new (fresh) temporary can be created with a newtemp() function. A new fresh label can be created with a newlabel() function. The generated instructions are closed to the LEIA ones (except for snif) Laure Gonnord (Lyon1/FST) Code Generation / 21
49 3-address syntax-directed Code Generation Rules Abstract Syntax Expressions: and statements: e ::= c constant x variable e + e addition e or e boolean or e < e less than... S(Smt) ::= x := expr assign skip do nothing S 1 ; S 2 sequence if b then S 1 else S 2 test while b do S done loop Laure Gonnord (Lyon1/FST) Code Generation / 21
50 3-address syntax-directed Code Generation Rules Code generation for expressions, example e ::= c (cte expr) dr <-newtemp() code.add(instructionlet(dr, c)) return dr this rule gives a way to generate code for any constant. Laure Gonnord (Lyon1/FST) Code Generation / 21
51 3-address syntax-directed Code Generation Rules Code generation for a boolean expression, example e ::= e 1 < e 2 dr <-newtemp() t1 <- GenCodeExpr(e1) t2 <- GenCodeExpr(e2) dr <- newtemp() endrel <- newlabel() code.add(instructionlet(dr, 0)) #if t1>=t2 jump to endrel code.add(instructioncondjump(endrel, t1, ">=", t2) code.add(instructionlet(dr, 1)) code.addlabel(endrel) return dr integer value 0 or 1. Laure Gonnord (Lyon1/FST) Code Generation / 21
52 3-address syntax-directed Code Generation Rules Code generation for commands, example if b then S1 else S2 lelse,lendif <-newlabels() t1 <- GenCodeExpr(b) #if the condition is false, jump to else code.add(instructioncondjump(lelse, t1, "=", 0)) GenCodeSmt(S1) #then code.add(instructionjump(lendif)) code.addlabel(lelse) GenCodeSmt(S2) #else code.addlabel(lendif) Laure Gonnord (Lyon1/FST) Code Generation / 21
53 Memory allocation Outline 1 3-address syntax-directed Code Generation 2 Memory allocation 3 Toward a more efficient Code Generation Laure Gonnord (Lyon1/FST) Code Generation / 21
54 Memory allocation A first example: from 3@ code to valid LC-3 (3/5) 3@code is not valid LEIA code! 3 kinds of allocation : All in registers (but?) place i register All in memory (here!) place i memory Something in the middle (later!) Laure Gonnord (Lyon1/FST) Code Generation / 21
55 Memory allocation A stack, why? Store constants, strings,... Provide an easy way to communicate arguments values (see later) Give place to store intermediate values (here) Laure Gonnord (Lyon1/FST) Code Generation / 21
56 Memory allocation LEIA stack emulation - from the archi course r 6 is initialised to the stack address. addresses will be computed from this base. The stack grows in the dir. of decreasing addresses!. R0 R1 ins1 ins2 x0000 R7 R8 x30fe x3000 x3001 x30ff stackend: x xffff Nice picture by N. Louvet Laure Gonnord (Lyon1/FST) Code Generation / 21
57 Memory allocation A first example: prelude/postlude 4/5 Here store r 1 on the stack! [init r6].let r1 4 sub r0 r6 1 ; first dec from r6 (and store some info!) wmem r1 [r0] ; now r1 can be recycled Laure Gonnord (Lyon1/FST) Code Generation / 21
58 Memory allocation A first example: prelude/postlude 5/5 The rest of the code generation:.set r6 stack [...] jump 0.align16 stackend:.reserve 42 stack: This is valid LEIA code that can be assembled and executed Laure Gonnord (Lyon1/FST) Code Generation / 21
59 Toward a more efficient Code Generation Outline 1 3-address syntax-directed Code Generation 2 Memory allocation 3 Toward a more efficient Code Generation Laure Gonnord (Lyon1/FST) Code Generation / 21
60 Toward a more efficient Code Generation Drawbacks of the former translation Drawbacks: redundancies (constants recomputations,... ) memory intensive loads and stores. we need a more efficient data structure to reason on: the control flow graph (CFG). (see next course) Laure Gonnord (Lyon1/FST) Code Generation / 21
Compilation: a bit about the target architecture
Compilation: a bit about the target architecture MIF08 Laure Gonnord Laure.Gonnord@univ-lyon1.fr Plan 1 The LEIA architecture in a nutshell 2 One example Laure Gonnord (Lyon1/FST) Compilation: a bit about
More informationSyntax Analysis MIF08. Laure Gonnord
Syntax Analysis MIF08 Laure Gonnord Laure.Gonnord@univ-lyon1.fr Goal of this chapter Understand the syntaxic structure of a language; Separate the different steps of syntax analysis; Be able to write a
More informationLexing, Parsing. Laure Gonnord sept Master 1, ENS de Lyon
Lexing, Parsing Laure Gonnord http://laure.gonnord.org/pro/teaching/capm1.html Laure.Gonnord@ens-lyon.fr Master 1, ENS de Lyon sept 2017 Analysis Phase source code lexical analysis sequence of lexems (tokens)
More informationStatic Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1
Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing
More informationPartial Exam Compilation and Program Analysis (CAP) October, 24th, 2016 Duration: 2 Hours
http://laure.gonnord.org/pro/ CAP, ENSL, 2016/2017 Partial Exam Compilation and Program Analysis (CAP) October, 24th, 2016 Duration: 2 Hours Only one a4 sheet (10pt, recto/verso) is autorized. Instructions
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationTime : 1 Hour Max Marks : 30
Total No. of Questions : 6 P4890 B.E/ Insem.- 74 B.E ( Computer Engg) PRINCIPLES OF MODERN COMPILER DESIGN (2012 Pattern) (Semester I) Time : 1 Hour Max Marks : 30 Q.1 a) Explain need of symbol table with
More informationToday. Assignments. Lecture Notes CPSC 326 (Spring 2019) Quiz 5. Exam 1 overview. Type checking basics. HW4 due. HW5 out, due in 2 Tuesdays
Today Quiz 5 Exam 1 overview Type checking basics Assignments HW4 due HW5 out, due in 2 Tuesdays S. Bowers 1 of 11 Exam Overview Basics closed notes, book, etc. 4 multi-part questions worth 15% of final
More informationCompilers. Intermediate representations and code generation. Yannis Smaragdakis, U. Athens (original slides by Sam
Compilers Intermediate representations and code generation Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Today Intermediate representations and code generation Scanner Parser Semantic
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationThe role of semantic analysis in a compiler
Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationCompilers. Compiler Construction Tutorial The Front-end
Compilers Compiler Construction Tutorial The Front-end Salahaddin University College of Engineering Software Engineering Department 2011-2012 Amanj Sherwany http://www.amanj.me/wiki/doku.php?id=teaching:su:compilers
More informationType Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules.
Outline Type Checking General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time
More informationOutline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference
Type Checking Outline General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time
More information6.035 Project 3: Unoptimized Code Generation. Jason Ansel MIT - CSAIL
6.035 Project 3: Unoptimized Code Generation Jason Ansel MIT - CSAIL Quiz Monday 50 minute quiz Monday Covers everything up to yesterdays lecture Lexical Analysis (REs, DFAs, NFAs) Syntax Analysis (CFGs,
More informationCompilers and computer architecture: Semantic analysis
1 / 1 Compilers and computer architecture: Semantic analysis Martin Berger Alex Jeffery October 2018 Recall the function of compilers 2 / 1 3 / 1 Recall the structure of compilers Source program Lexical
More informationLECTURE 3. Compiler Phases
LECTURE 3 Compiler Phases COMPILER PHASES Compilation of a program proceeds through a fixed series of phases. Each phase uses an (intermediate) form of the program produced by an earlier phase. Subsequent
More informationIntermediate Code Generation
Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target
More informationCompiler construction
Compiler construction Martin Steffen March 13, 2017 Contents 1 Abstract 1 1.1 Symbol tables. 1 1.1.1 Introduction 1 1.1.2 Symbol table design and interface.. 2 1.1.3 Implementing symbol tables 3 1.1.4
More informationTail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)
CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)
More informationSemantic Analysis. Lecture 9. February 7, 2018
Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average
More informationSEMANTIC ANALYSIS TYPES AND DECLARATIONS
SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether
More informationCOS 320. Compiling Techniques
Topic 5: Types COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Types: potential benefits (I) 2 For programmers: help to eliminate common programming mistakes, particularly
More informationCSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1
CSE P 501 Compilers Static Semantics Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Attribute grammars Representing types Symbol tables Note: this covers
More informationUNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2009 P. N. Hilfinger CS 164: Final Examination (corrected) Name: Login: You have
More informationSemantic analysis and intermediate representations. Which methods / formalisms are used in the various phases during the analysis?
Semantic analysis and intermediate representations Which methods / formalisms are used in the various phases during the analysis? The task of this phase is to check the "static semantics" and generate
More informationThe Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.
The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages
More informationTopic 6: Types COS 320. Compiling Techniques. Princeton University Spring Prof. David August. Adapted from slides by Aarne Ranta
Topic 6: Types COS 320 Compiling Techniques Princeton University Spring 2015 Prof. David August 1 Adapted from slides by Aarne Ranta Types What is a type? Type Checking: Helps find language-level errors:
More informationIntroduction - CAP Course
Introduction - CAP Course Laure Gonnord http://laure.gonnord.org/pro/teaching/ Laure.Gonnord@ens-lyon.fr Master 1, ENS de Lyon sept 2016 Credits A large part of the compilation part of this course is inspired
More informationCMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics
Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End
More informationSyntax and Grammars 1 / 21
Syntax and Grammars 1 / 21 Outline What is a language? Abstract syntax and grammars Abstract syntax vs. concrete syntax Encoding grammars as Haskell data types What is a language? 2 / 21 What is a language?
More informationA Simple Syntax-Directed Translator
Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and
More informationFall Compiler Principles Lecture 6: Intermediate Representation. Roman Manevich Ben-Gurion University of the Negev
Fall 2015-2016 Compiler Principles Lecture 6: Intermediate Representation Roman Manevich Ben-Gurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation
More informationLab 5. Syntax-Directed Code Generation
Lab 5 Syntax-Directed Code Generation Objective Generate 3-address code for the Mu language. Generate executable dummy LEIA from programs in Mu via 2 simple allocation algorithms. Student files are in
More informationOperational Semantics of Cool
Operational Semantics of Cool Key Concepts semantics: the meaning of a program, what does program do? how the code is executed? operational semantics: high level code generation steps of calculating values
More informationCrafting a Compiler with C (II) Compiler V. S. Interpreter
Crafting a Compiler with C (II) 資科系 林偉川 Compiler V S Interpreter Compilation - Translate high-level program to machine code Lexical Analyzer, Syntax Analyzer, Intermediate code generator(semantics Analyzer),
More informationCSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking
CSE450 Translation of Programming Languages Lecture 11: Semantic Analysis: Types & Type Checking Structure Project 1 - of a Project 2 - Compiler Today! Project 3 - Source Language Lexical Analyzer Syntax
More informationCOMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking
Agenda COMP 181 Type checking October 21, 2009 Next week OOPSLA: Object-oriented Programming Systems Languages and Applications One of the top PL conferences Monday (Oct 26 th ) In-class midterm Review
More information5. Syntax-Directed Definitions & Type Analysis
5. Syntax-Directed Definitions & Type Analysis Eva Rose Kristoffer Rose NYU Courant Institute Compiler Construction (CSCI-GA.2130-001) http://cs.nyu.edu/courses/spring15/csci-ga.2130-001/lecture-5.pdf
More informationCSCE 314 Programming Languages. Type System
CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be
More informationSimply-Typed Lambda Calculus
#1 Simply-Typed Lambda Calculus #2 Back to School What is operational semantics? When would you use contextual (small-step) semantics? What is denotational semantics? What is axiomatic semantics? What
More informationCS 406/534 Compiler Construction Putting It All Together
CS 406/534 Compiler Construction Putting It All Together Prof. Li Xu Dept. of Computer Science UMass Lowell Fall 2004 Part of the course lecture notes are based on Prof. Keith Cooper, Prof. Ken Kennedy
More informationStructure of a compiler. More detailed overview of compiler front end. Today we ll take a quick look at typical parts of a compiler.
More detailed overview of compiler front end Structure of a compiler Today we ll take a quick look at typical parts of a compiler. This is to give a feeling for the overall structure. source program lexical
More informationCS 360 Programming Languages Interpreters
CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like
More informationCompilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam
Compilers Type checking Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Summary of parsing Parsing A solid foundation: context-free grammars A simple parser: LL(1) A more powerful parser:
More informationChapter 3 (part 3) Describing Syntax and Semantics
Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings
More informationThe Substitution Model
The Substitution Model Prof. Clarkson Fall 2017 Today s music: Substitute by The Who Review Previously in 3110: simple interpreter for expression language abstract syntax tree (AST) evaluation based on
More informationIntermediate Code Generation
Intermediate Code Generation Rupesh Nasre. CS3300 Compiler Design IIT Madras July 2018 Character stream Lexical Analyzer Machine-Independent Code Code Optimizer F r o n t e n d Token stream Syntax Analyzer
More informationOutline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context
Types 1 / 15 Outline Introduction Concepts and terminology The case for static typing Implementing a static type system Basic typing relations Adding context 2 / 15 Types and type errors Type: a set of
More informationStatic Semantics. Winter /3/ Hal Perkins & UW CSE I-1
CSE 401 Compilers Static Semantics Hal Perkins Winter 2009 2/3/2009 2002-09 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Symbol tables General ideas for now; details later for MiniJava project
More informationCompiler Theory. (Semantic Analysis and Run-Time Environments)
Compiler Theory (Semantic Analysis and Run-Time Environments) 005 Semantic Actions A compiler must do more than recognise whether a sentence belongs to the language of a grammar it must do something useful
More informationSECOND PUBLIC EXAMINATION. Compilers
A10401W1 SECOND PUBLIC EXAMINATION Honour School of Computer Science Honour School of Mathematics and Computer Science Honour School of Computer Science and Philosophy Compilers TRINITY TERM 2016 Thursday
More informationProf. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan
Language Processing Systems Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan Semantic Analysis Compiler Architecture Front End Back End Source language Scanner (lexical analysis)
More informationCompiler Design (40-414)
Compiler Design (40-414) Main Text Book: Compilers: Principles, Techniques & Tools, 2 nd ed., Aho, Lam, Sethi, and Ullman, 2007 Evaluation: Midterm Exam 35% Final Exam 35% Assignments and Quizzes 10% Project
More informationCompiler Code Generation COMP360
Compiler Code Generation COMP360 Students who acquire large debts putting themselves through school are unlikely to think about changing society. When you trap people in a system of debt, they can t afford
More informationSyntactic Analysis. The Big Picture Again. Grammar. ICS312 Machine-Level and Systems Programming
The Big Picture Again Syntactic Analysis source code Scanner Parser Opt1 Opt2... Optn Instruction Selection Register Allocation Instruction Scheduling machine code ICS312 Machine-Level and Systems Programming
More informationCS152 Programming Language Paradigms Prof. Tom Austin, Fall Syntax & Semantics, and Language Design Criteria
CS152 Programming Language Paradigms Prof. Tom Austin, Fall 2014 Syntax & Semantics, and Language Design Criteria Lab 1 solution (in class) Formally defining a language When we define a language, we need
More informationSyntax Errors; Static Semantics
Dealing with Syntax Errors Syntax Errors; Static Semantics Lecture 14 (from notes by R. Bodik) One purpose of the parser is to filter out errors that show up in parsing Later stages should not have to
More informationIntermediate Code Generation
Intermediate Code Generation Rupesh Nasre. CS3300 Compiler Design IIT Madras Aug 2015 Character stream Lexical Analyzer Machine-Independent Code Optimizer F r o n t e n d Token stream Syntax Analyzer Syntax
More informationLecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far
Lecture Outline Operational Semantics of Cool Lecture 13 COOL operational semantics Motivation Notation The rules Prof. Aiken CS 143 Lecture 13 1 Prof. Aiken CS 143 Lecture 13 2 Motivation We must specify
More informationIntermediate Representations
Intermediate Representations A variety of intermediate representations are used in compilers Most common intermediate representations are: Abstract Syntax Tree Directed Acyclic Graph (DAG) Three-Address
More informationComputer Science Department Carlos III University of Madrid Leganés (Spain) David Griol Barres
Computer Science Department Carlos III University of Madrid Leganés (Spain) David Griol Barres dgriol@inf.uc3m.es Introduction He am a driver might be syntactically correct but semantically wrong. Semantic
More informationWhat is a compiler? var a var b mov 3 a mov 4 r1 cmpi a r1 jge l_e mov 2 b jmp l_d l_e: mov 3 b l_d: ;done
What is a compiler? What is a compiler? Traditionally: Program that analyzes and translates from a high level language (e.g., C++) to low-level assembly language that can be executed by hardware int a,
More informationProject Compiler. CS031 TA Help Session November 28, 2011
Project Compiler CS031 TA Help Session November 28, 2011 Motivation Generally, it s easier to program in higher-level languages than in assembly. Our goal is to automate the conversion from a higher-level
More informationLab 2. Lexing and Parsing with ANTLR4
Lab 2 Lexing and Parsing with ANTLR4 Objective Understand the software architecture of ANTLR4. Be able to write simple grammars and correct grammar issues in ANTLR4. Todo in this lab: Install and play
More informationModule 27 Switch-case statements and Run-time storage management
Module 27 Switch-case statements and Run-time storage management In this module we will discuss the pending constructs in generating three-address code namely switch-case statements. We will also discuss
More informationCompiler Optimisation
Compiler Optimisation 1 Introductory Lecture Hugh Leather IF 1.18a hleather@inf.ed.ac.uk Institute for Computing Systems Architecture School of Informatics University of Edinburgh 2018 Textbooks Engineering
More informationCIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL
CIS 194: Homework 3 Due Wednesday, February 11, 2015 Interpreters An interpreter is a program that takes another program as an input and evaluates it. Many modern languages such as Java 1, Javascript,
More information9/5/17. The Design and Implementation of Programming Languages. Compilation. Interpretation. Compilation vs. Interpretation. Hybrid Implementation
Language Implementation Methods The Design and Implementation of Programming Languages Compilation Interpretation Hybrid In Text: Chapter 1 2 Compilation Interpretation Translate high-level programs to
More informationCA Compiler Construction
CA4003 - Compiler Construction Semantic Analysis David Sinclair Semantic Actions A compiler has to do more than just recognise if a sequence of characters forms a valid sentence in the language. It must
More informationOperational Semantics. One-Slide Summary. Lecture Outline
Operational Semantics #1 One-Slide Summary Operational semantics are a precise way of specifying how to evaluate a program. A formal semantics tells you what each expression means. Meaning depends on context:
More informationSemantic Analysis computes additional information related to the meaning of the program once the syntactic structure is known.
SEMANTIC ANALYSIS: Semantic Analysis computes additional information related to the meaning of the program once the syntactic structure is known. Parsing only verifies that the program consists of tokens
More informationType Checking. Chapter 6, Section 6.3, 6.5
Type Checking Chapter 6, Section 6.3, 6.5 Inside the Compiler: Front End Lexical analyzer (aka scanner) Converts ASCII or Unicode to a stream of tokens Syntax analyzer (aka parser) Creates a parse tree
More informationTypes and Static Type Checking (Introducing Micro-Haskell)
Types and Static (Introducing Micro-Haskell) Informatics 2A: Lecture 13 Alex Simpson School of Informatics University of Edinburgh als@inf.ed.ac.uk 16 October, 2012 1 / 21 1 Types 2 3 4 2 / 21 Thus far
More informationLecture 16: Static Semantics Overview 1
Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis
More informationSemantic Analysis. Role of Semantic Analysis
Semantic Analysis Chapter 4 Role of Semantic Analysis Following parsing, the next two phases of the "typical" compiler are semantic analysis (intermediate) code generation The principal job of the semantic
More informationLecture 7: Type Systems and Symbol Tables. CS 540 George Mason University
Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing
More informationInterpreters. Prof. Clarkson Fall Today s music: Step by Step by New Kids on the Block
Interpreters Prof. Clarkson Fall 2017 Today s music: Step by Step by New Kids on the Block Review Previously in 3110: functional programming modular programming data structures Today: new unit of course:
More informationFormal Languages and Compilers Lecture X Intermediate Code Generation
Formal Languages and Compilers Lecture X Intermediate Code Generation Free University of Bozen-Bolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationStatic Checking and Intermediate Code Generation Pat Morin COMP 3002
Static Checking and Intermediate Code Generation Pat Morin COMP 3002 Static Checking and Intermediate Code Generation Parser Static Checker Intermediate Code Generator Intermediate Code Generator Parse
More informationCS415 Compilers. Intermediate Represeation & Code Generation
CS415 Compilers Intermediate Represeation & Code Generation These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University Review - Types of Intermediate Representations
More informationSemantic Analysis and Type Checking
Semantic Analysis and Type Checking The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on
More informationRecap: Functions as first-class values
Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse
More informationCompiler Theory Introduction and Course Outline Sandro Spina Department of Computer Science
Compiler Theory 001 - Introduction and Course Outline Sandro Spina Department of Computer Science ( course Books (needed during this My slides are based on the three books: Compilers: Principles, techniques
More informationFront End. Hwansoo Han
Front nd Hwansoo Han Traditional Two-pass Compiler Source code Front nd IR Back nd Machine code rrors High level functions Recognize legal program, generate correct code (OS & linker can accept) Manage
More informationCS 432 Fall Mike Lam, Professor. Code Generation
CS 432 Fall 2015 Mike Lam, Professor Code Generation Compilers "Back end" Source code Tokens Syntax tree Machine code char data[20]; int main() { float x = 42.0; return 7; } 7f 45 4c 46 01 01 01 00 00
More informationTopics Covered Thus Far CMSC 330: Organization of Programming Languages
Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free
More informationBegin at the beginning
Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of
More informationCS 415 Midterm Exam Spring 2002
CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming
More informationRYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 INSTRUCTIONS
RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 STUDENT ID: INSTRUCTIONS Please write your student ID on this page. Do not write it or your name
More informationSemantics of programming languages
Semantics of programming languages Informatics 2A: Lecture 27 Alex Simpson School of Informatics University of Edinburgh als@inf.ed.ac.uk 18 November, 2014 1 / 18 Two parallel pipelines A large proportion
More informationCS 242. Fundamentals. Reading: See last slide
CS 242 Fundamentals Reading: See last slide Syntax and Semantics of Programs Syntax The symbols used to write a program Semantics The actions that occur when a program is executed Programming language
More informationCompil M1 : Front-End
Compil M1 : Front-End TD1 : Introduction à Flex/Bison Laure Gonnord (groupe B) http://laure.gonnord.org/pro/teaching/ Laure.Gonnord@univ-lyon1.fr Master 1 - Université Lyon 1 - FST Plan 1 Lexical Analysis
More informationUNIT IV INTERMEDIATE CODE GENERATION
UNIT IV INTERMEDIATE CODE GENERATION 2 Marks 1. Draw syntax tree for the expression a=b*-c+b*-c 2. Explain postfix notation. It is the linearized representation of syntax tree.it is a list of nodes of
More informationAnatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?
Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator
More informationProgrammiersprachen (Programming Languages)
2016-05-13 Preface Programmiersprachen (Programming Languages) coordinates: lecturer: web: usable for: requirements: No. 185.208, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/ps.html
More informationIR Optimization. May 15th, Tuesday, May 14, 13
IR Optimization May 15th, 2013 Tuesday, May 14, 13 But before we talk about IR optimization... Wrapping up IR generation Tuesday, May 14, 13 Three-Address Code Or TAC The IR that you will be using for
More informationLecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Notation. The rules. Evaluation Rules So Far.
Lecture Outline Operational Semantics of Cool COOL operational semantics Motivation Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Notation The rules CS781(Prasad) L24CG 1 CS781(Prasad)
More information