EDAN65: Compilers, Lecture 08 Reference A<ribute Grammars AG mechanisms, SemanBc analysis. Görel Hedin Revised:
|
|
- Chad Wheeler
- 5 years ago
- Views:
Transcription
1 EDAN65: Compilers, Lecture 08 Reference A<ribute Grammars AG mechanisms, SemanBc analysis Görel Hedin Revised:
2 This lecture Regular expressions Context- free grammar A<ribute grammar Lexical analyzer (scanner) SyntacBc analyzer (parser) Seman&c analyzer source code (text) tokens AST (Abstract syntax tree) Visitors StaBc aspects A.ribute grammars A<ributed AST runtime system activation records objects stack garbage collection heap Intermediate code generator Interpreter OpBmizer intermediate code Virtual machine code and data intermediate code Target code generator target code machine 2
3 A<ribute mechanisms Synthesized the equabon is in the same node as the a<ribute Inherited the equabon is in an ancestor Broadcas&ng the equabon holds for a complete subtree Reference the a<ribute can be a reference to an AST node. Parameterized the a<ribute can have parameters NTA the a<ribute is a "nonterminal" (a fresh node or subtree) Collec&on the a<ribute is defined by a set of contribubons, instead of by an equabon. Circular the a<ribute may depend on itself (solved using fixed- point iterabon) 3
4 Example computabons on an AST... Name analysis: find the declarabon of an idenbfier Mul Type analysis: compute the type of an expression IdExpr Div IdExpr IdExpr Expression evaluabon: compute the value of a constant expression Code generabon: compute an intermediate code representabon of the program Unparsing: compute a text representabon of the program 4
5 SemanBc analysis class A { int f; int m1(int x) { return x * f; class B extends A { int m2() { System.out.println(m1(3)); Name analysis: bind each use of an idenbfier to its declarabon Type analysis: compute the type of each expression Error checking: find compile- Bme errors like missing declarabons, wrong type, etc. 5
6 Reference and parameterized a<ributes Name analysis 6
7 Reference a<ribute grammars (RAGs) Can build graphs on top of the AST. Trivial example: A B myc C myb JastAdd specificabon: A ::= B C; B; C; aspect Graph { inh C B.myC(); inh B C.myB(); eq A.getB().myC() = getc(); eq A.getC().myB() = getb(); 7
8 Parameterized a<ributes A ::= B*; B; Draw some isbefore a-ributes and their values! A An a<ribute can have parameters. List inh boolean B.isBefore(int i); eq A.getB(int index).isbefore(int i) = index < i; B B B 8
9 Parameterized a<ributes A ::= B*; B; A An a<ribute can have parameters. inh boolean B.isBefore(int i); eq A.getB(int index).isbefore(int i) = index < i; List B B isbefore(0) = false isbefore(1) = false isbefore(2) = true isbefore(3) = true isbefore(...) =... B There is one a<ribute instance for each possible parameter combinabon. PotenBally infinitely many a<ribute instances. Only the accessed ones will be evaluated. 9
10 Name analysis class A { int f; int m1(int x) { return x * f; class B extends A { int m2() { System.out.println(m1(3)); Name analysis: bind each use of an idenbfier to its declarabon Name binding: a reference from a use to its declarabon Scope of a declara&on: the parts of the program where it is visible. Name binding rules: also known as scope rules or visibility rules. Typically, there are rules for blocks, nesbng, inheritance name collisions, shadowing declarabon order (insignificant or declare- before- use?) visibility restricbons (private, public,...) qualified access (a.b) overloading, namespaces... 10
11 Name binding: Blocks class A { int f; int m1(int x) { int a = 4; int f = a + 5; return x * f + b; class B extends A { int m2() { System.out.println(m1(3)); Block: a syntacbc unit containing declarabons and statements. Can be nested. Called block strucure or lexical nes<ng. DeclaraBons in inner blocks shadow declarabons in outer blocks DeclaraBon ordering can be insignificant, or declare- before- use... 11
12 Name binding: Inheritance class A { int x; class AA { int y; class B extends A { int y, z; class BB extends AA { int v; void m() { int w = x + y + z + v;... Inheritance and block nesbng can be combined. In what block order should we look for the declarabon of x? m BB AA B A globally Which declarabon of y is y bound to? AA.y since inheritance binds Bghter than lexical nesbng. 12
13 Name binding: Qualified access class A { int m() {... ; class B extends A { void m() { A a = new B(); System.out.println(a.m()); Qualified access (dot notabon) The binding of m depends on the type of a
14 Recall: RepresenBng name bindings in an AST { int a; a = 3; VarDecl Block Assign IntType IdDecl IdUse IntExp IdDecl for declared names IdUse for used names ID="a" ID="a" decl INT="3" An a<ribute decl represents the name binding. 14
15 Recall: CompuBng name bindings imperabvely { int a; a = 3; VarDecl Block Assign IntType IdDecl ID="a" Use a symbol table data structure: For each block, a map from visible names to declarabons. Use a stack of maps to handle nested blocks. IdUse ID="a" decl IntExp INT="3" Algorithm: Traverse the AST push/pop symbol table when entering/leaving a block add/lookup idenbfiers when encountering IdDecls/IdUses 15
16 Problems with the imperabve approach Need to write an algorithm that computes things in the right order. What if we have more complex name binding rules? Need a more elaborate symbol table. The algorithm may get complex. What if we extend the language? Need to change the algorithm. SoluBon: A<ribute grammars a declarabve approach 16
17 Name analysis using RAGs Think declara&vely!! What a<ributes would I like the nodes to have? Synthesized defined in the node Inherited defined in a parent Program Block eq child.lookup(string) =... VarDecl Assign IntType IdDecl IdUse IntExp ID="a" ID="a" INT="3" syn decl eq decl = lookup(id) inh lookup(string) 17
18 The Lookup pa.ern for name analysis in RAGs decl the name binding lookup(string) finds the declarabon locallookup(string) looks locally eq child.lookup(string) delegates to locallookup and lookup a<ributes, according to scope rules. Program Block eq child.lookup(string) = NoDecl eq child.lookup(string) =... syn locallookup(string) inh lookup(string) Decl Block eq child.lookup(string) =... syn locallookup(string) inh lookup(string) Decl Use ID="a" syn decl inh lookup(string) General pa<ern for name analysis. Can handle block structure, inheritance, qualified access,... 18
19 Example implementabon in JastAdd Abstract grammar: Program ::= Block; Block : Stmt ::= Decl* Stmt*; Decl ::= Type IdDecl; IdDecl ::= <ID:String>; Type; abstract Stmt; Assign : Stmt ::= To:IdUse From:IdUse; IdUse ::= <ID:String>; A<ributes and equabons: syn IdDecl IdUse.decl() = lookup(getid()); inh IdDecl IdUse.lookup(String s); eq Block.getStmt().lookup(String s) { IdDecl d = locallookup(s); if (d!= null) return d; return lookup(s); Decl Program Block Block syn locallookup(string) inh lookup(string) syn locallookup(string) inh lookup(string) syn IdDecl Block.localLookup(String s) { for (Decl d: getdecls()) { if (d.getiddecl().getid().equals(s)) return d.getiddecl(); return null; inh IdDecl Block.lookup(String s); Decl Use ID="a" eq Program.getBlock().lookup(String s) { return null; syn decl inh lookup(string) 19
20 Demand evaluabon A<ributes are not evaluated unbl demanded. Simple recursive caching algorithm: Program If not cached find the equabon compute its right- hand side cache the value fi Return the cached value List Block locallookup("a") locallookup("b") lookup("b") List Decl Assign Example program demanding a<ributes: Program p =... Assign a = p.getblock().getstmt(0); System.out.println(a.getTo().decl()); System.out.println(a.getFrom().decl()); Type IdDecl IdUse IdUse ID="a" ID="a" ID="b" decl 1 lookup("a") 2 decl lookup("b")
21 More efficient implementabon of locallookup syn IdDecl Block.localLookup(String s) { for (Decl d: getdecls()) { if (d.getiddecl().getid().equals(s)) return d.getiddecl(); return unknowndecl(); What happens if there are 1000 elements in the declarabon list? What is the complexity? Linear search for each declarabon gives quadrabc Bme complexity: O(n 2 ) More efficient: Use a local hashmap which is built on the first access. Aler that each access is done in constant Bme. ResulBng complexity: O(n) syn IdDecl Block.localLookup(String s) { IdDecl result = localmap().get(s); return (result!=null)?result:unknowndecl(); syn Map<String,IdDecl> Block.localMap() { Map<String,IdDecl> map = new HashMap<String,IdDecl>(); for (Decl d: getdecls()) { IdDecl id = d.getiddecl(); map.put(id.getid(), id); return map; 21
22 Nonterminal a<ributes The Null Pa<ern 22
23 Nonterminal a<ributes (NTAs) A ::= B; B; C ::= D; D; A nonterminal a<ribute is both an a<ribute and a nonterminal (AST node). Draw the n a-ribute and its value! A B The value must consist of fresh nodes. (If you reuse exisbng nodes, the a<ributes may get inconsistent values.) syn nta C B.n() = new C(new D()); Use for reifying informabon (making implicit informabon explicit). For example, primibve types, predefined funcbons,... 23
24 Nonterminal a<ributes (NTAs) A ::= B; B; C ::= D; D; A nonterminal a<ribute is both an a<ribute and a nonterminal (AST node). A B n The value must consist of fresh nodes. (If you reuse exisbng nodes, the a<ributes may get inconsistent values.) syn nta C B.n() = new C(new D()); Use for reifying informabon (making implicit informabon explicit). For example, primibve types, predefined funcbons,... C D Warning! If you reuse exis<ng nodes for NTAs, the AST will be inconsistent. JastAdd does not check this. 24
25 Nonterminal a<ributes (NTAs) A ::= B; B; C ::= D; D; Draw the x, y, and z a-ributes and their values! A syn nta C B.n() = new C(new D()); B n An NTA may itself have a<ributes. inh int C.x(); eq B.n().x() = 5; syn int B.y() = n().z() * 3; syn int C.z() = x() + 2; C D 25
26 Nonterminal a<ributes (NTAs) A ::= B; B; C ::= D; D; A syn nta C B.n() = new C(new D()); y=21 B n An NTA may itself have a<ributes. inh int C.x(); eq B.n().x() = 5; syn int B.y() = n().z() * 3; syn int C.z() = x() + 2; C D x=5 z=7 26
27 The Null object pa.ern Use a real object instead of null. Give the object suitable behavior. The code becomes simpler. In RAGs: use null objects for missing declarabons, unknown types, etc. But how can we implement unknowndecl()? syn IdDecl IdUse.decl() = lookup(getid()); inh IdDecl IdUse.lookup(String s); eq Block.getStmt().lookup(String s) { IdDecl d = locallookup(s); if (!d.isunknown()) return d; return lookup(s); syn IdDecl Block.localLookup(String s) { for (Decl d: getdecls()) { if (d.getiddecl().getid().equals(s)) return d.getiddecl(); return unknowndecl(); inh IdDecl Block.lookup(String s); eq Program.getBlock().lookup(String s) { return unknowndecl(); See h<p://en.wikipedia.org/wiki/null_object_pa<ern 27
28 Non- terminal a<ributes (NTAs) An NTA is both a node and an a.ribute. The right- hand side of its defining equabon must be a fresh object (not part of any AST). A eq child.a =... Useful for reifying implicit constructs (make them explicit in the AST), like: Missing declarabons Unknown types PrimiBve types and funcbons C B n N inh a an NTA syn nta N B.n() = new N(); An NTA can have a<ributes. The owning node (or its ancestors) must define the inherited a<ributes of the NTA. 28
29 Non- terminal a<ributes (NTAs) An NTA is both a node and an a.ribute. The right- hand side of its defining equabon must be a fresh object (not part of any AST). Add an UnknownDecl object to the AST using a non- terminal a<ribute Extend the abstract grammar: UnknownDecl : IdDecl; List Program unknowndecl Block UnknownDecl List Add the NTA: syn nta UnknownDecl Program.unknownDecl() = new UnknownDecl("<Unknown>"); Implement the special behavior: syn boolean IdDecl.isUnknown() = false; eq UnknownDecl.isUnknown() = true; Type Decl IdDecl IdUse Assign IdUse ID="a" ID="a" ID="b" But how can we make the UnknownDecl object known throughout the AST? 29
30 The Root A.ribute pa<ern Intent: Make an a<ribute in the root visible throughout the AST. Solu&on: Add an equabon in the root, propagabng the value to the children. Expose the a<ribute by declaring it as inherited where it is needed. Or declare it in ASTNode. Then it will be visible in all nodes. B D Root A C syn a eq child.a = a E inh a 30
31 ImplemenBng unknowndecl Program Apply the Root A<ribute pa<ern: unknowndecl eq Program.getBlock().unknownDecl() = unknowndecl(); unknowndecl Block UnknownDecl inh UnknownDecl Block.unknownDecl(); List List Decl Assign Type IdDecl IdUse IdUse ID="a" ID="a" ID="b" decl 31
32 Type analysis 32
33 Type analysis Type analysis: compute the type of each expression Add a type a<ribute to Expr syn Type Expr.type(); Implement it for IdUses eq IdUse.type() = decl().type(); Define the type a<ribute for IdDecls inh Type IdDecl.type(); eq Decl.getIdDecl().type() = gettype(); eq Program.unknownDecl().type() = unknowntype(); List Decl Program unknowndecl unknowntype Block UnknownDecl List Assign type... Define unknowntype as an NTA... Type IdDecl IdUse IdUse ID="a" ID="a" ID="b" type decl decl type type 33
34 Type checking Type checking: Check if types are used correctly First a<empt: syn boolean Assign.compatibleTypes() = getto().type().equals(getfrom().type()); Second a<empt: syn boolean Assign.compatibleTypes() = getfrom().type().isunknowntype() getto().type().isunknowntype() getto().type().equals(getfrom().type()); List Decl Program unknowndecl unknowntype Block UnknownDecl List Assign type... Type IdDecl IdUse IdUse ID="a" ID="a" ID="b" type decl decl type type Problem with first a<empt: Missing declarabon errors will give type checking errors as well. Would be nicer to view unknowntype as compabble with all other types. 34
35 CollecBon a<ributes Error checking 35
36 CollecBon a<ributes A collecbon a<ribute is defined by contribubons, instead of by a single equabon. A B Use for values combined from many small parts spread out over the tree. collection s C D Example uses: - collect compile- Bme errors in a program - collect what uses are bound to a specific declarabon - count the number of if- statements in a method E E contributes... When a collecbon a<ribute is accessed, the a<ribute evaluator will automabcally traverse the AST and find the contribubons. 36
37 CollecBon a<ributes An collec&on a<ribute has a composite value. Contribu&on rules can declare elements that should contribute to the composite value. collec<on a-ribute t B A C The a<ribute evaluator will automabcally traverse the AST starbng from a given root, and add the contribubons, using a method m which must be commuta&ve. Declare the collecbon: D E contribu<on x theb coll T B.t() [new T()] with m root B; Declare a contribubon (suppose E has an a<ribute x): E contributes x when condition to B.t() for theb(); Propagate theb (Root A<ribute pa<ern): inh B E.theB(); eq B.getChild().theB() = this; 37
38 CollecBon a<ributes, example 1... IdDecl ::= <ID:String>; IdUse ::= <ID:String>; Program ClassDecl ClassDecl IdDecl IdDecl IdUse IdUse ID="b" ID="a" ID="a" decl ID="a" decl 38
39 CollecBon a<ributes, example 1... IdDecl ::= <ID>; IdUse ::= <ID>; Program ClassDecl ClassDecl A "uses" a-ribute contains the collec<on of IdUses referring to the IdDecl IdDecl ID="b" uses= IdDecl ID="a" uses={, IdUse ID="a" decl IdUse ID="a" decl coll Set<IdUse> IdDecl.uses() [new Set<IdUse>()] with add; IdUse contributes this to IdDecl.uses() for decl(); 39
40 JastAdd Java grammar ClassDecl... MethodDecl... ConstructorDecl... CollecBon a<ributes, example 2 Program ClassDecl ClassDecl MethodDecl ConstructorDecl MethodDecl MethodDecl Private Public Public Public ContribuBons can be condibonal. Example: NPM metric- Number of Public Methods and constructors in a class 40
41 JastAdd Java grammar ClassDecl... MethodDecl... ConstructorDecl... CollecBon a<ributes, example 2 Program publicmethods=1 ClassDecl publicmethods=2 ClassDecl MethodDecl ConstructorDecl MethodDecl MethodDecl Private Public Public Public ContribuBons can be condibonal. Example: NPM metric- Number of Public Methods and constructors in a class coll Counter ClassDecl.publicMethods () [new Counter()] with add; MethodDecl contributes 1 when ispublic() to ClassDecl.publicMethods() for hosttype(); ConstructorDecl contributes 1 when ispublic() to ClassDecl.publicMethods() for hosttype(); 41
42 Error checking Error checking: collect all errors Program errors unknowndecl unknowntype We would like an a<ribute errors in the root, containing all error messages. Block UnknownDecl type... We would like an easy way to "contribute" different kinds of errors from different nodes in the AST. List Decl List Assign Type IdDecl IdUse IdUse ID="a" ID="a" ID="b" type decl decl type type contribute error 42
43 Example: CollecBng errors Error checking: collect all errors Program Declare the errors collecbon: errors unknowndecl unknowntype coll Set<String> Program.errors() [new HashSet<String>()] with add root Program; Block UnknownDecl type... Propagate a reference to the Program root: (Root A<ribute pa<ern): List List inh Program ASTNode.theProgram(); eq Program.getChild().theProgram() = this; Decl Assign Type IdDecl IdUse IdUse Contribute an error IdUse contributes "Undeclared variable" when decl().isunknown() to Program.errors() for theprogram(); ID="a" ID="a" ID="b" type decl decl type type contribute error 43
44 Circular a<ributes 44
45 Circular a<ributes syn Set<State> State.succ() =...; StateMachine State 1 State 2 State 3 State 4 reachable={2,3 reachable={2,3 reachable={2,3 reachable= What states are reachable from state k? MathemaBcal definibon: ImplementaBon using a circular a<ribute syn Set<State> State.reachable() circular [new HashSet<State>()] { HashSet<State> result = new HashSet<State>(); for (State s : succ()) { result.add(s); result.addall(s.reachable()); return result; A circular a<ribute may depend (transibvely) on itself. 45
46 Circular a<ributes - terminabon Does the computabon terminate? Yes! The values (sets of states) can be arranged in a latce. The latce is of finite height (the number of states is finite). The equabons are monotonic: they use set union. Warning! JastAdd does not check this property. If you use non- monotonic equabons or values that can grow unbounded, you might get nonterminabon. ImplementaBon using a circular a<ribute syn Set<State> State.reachable() circular [new HashSet<State>()] { HashSet<State> result = new HashSet<State>(); for (State s : succ()) { result.add(s); result.addall(s.reachable()); return result; A circular a<ribute may depend (transibvely) on itself. 46
47 Useful latce types Set laoce Start with the empty set. Use the UNION operator. Make sure there is a finite set of possible values in a set. Boolean laoces The latce is of finite height: only two possible elements TRUE FALSE FALSE TRUE Start with FALSE Use the OR operator Start with TRUE Use the AND operator 47
48 Circular a<ributes beware of externally visible side effects! It is ok to use local side effects: syn Set<State> State.reachable() circular [new HashSet<State>()] { HashSet<State> result = new HashSet<State>(); for (State s : succ()) { result.add(s); result.addall(s.reachable()); return result; Only the local object is changed. There are no externally visible side effects. This is fine! Warning! If you by mistake change the value of an a<ribute, e.g.... s.reachable().add(...)... JastAdd does not detect this error, and inconsistent a<ribubon may result. 48
49 There are many fixed- point problems in compilers and program analysis tools Cyclic class hierarchy: find out if a class inherits from itself Definite assignment: find out if every variable is guaranteed to have been assigned a value before it is used. Call graph analysis: for example, find methods that are never called (dead code) Data flow analysis: for example, find variables that are never used (dead code) Nullable, FIRST, and FOLLOW (if your "compiler" is actually a parser generator)... 49
50 Summary quesbons: reference a<ributes, name analysis What is a reference a<ribute grammar? What is a reference a<ribute? What is a parameterized a<ribute? What is name analysis? What is a name binding? What does scope mean? Give examples of some typical name binding rules. What does declare- before- use mean? What is qualified access? How does the Lookup pa<ern work? 50
51 Summary quesbons: NTAs, type checking What is a nonterminal a<ribute (NTA)? What is the Null Object pa<ern? How does the Root A<ribute pa<ern work? Why is it useful to implement missing declarabons and unknown types as AST nodes? What is type analysis and type checking? How can unnecessary error propagabon be avoided? 51
52 Summary quesbons: CollecBon a<ributes, Error checking, Circular a<ributes What is a collecbon a<ribute? How can a collecbon of error message be implemented? What is a circular a<ribute? How is a circular a<ribute evaluated? How can you know if the evaluabon of a circular a<ribute will terminate? Give examples of properbes that can be computed using circular a<ributes. 52
Visitors. Move functionality
Visitors Compiler Construction Visitor pattern, Semantic analysis Lennart Andersson How to modularize in Java (or any other OO language) if we do not have access to AOP mechanisms? Revision 2011-02-08
More informationTutorial: Generating Language Tools with JastAdd
Tutorial: Generating Language Tools with JastAdd Görel Hedin Lund University, Sweden gorel@cs.lth.se, Draft Oct 29, 2009 Abstract. JastAdd is an open-source system for generating compilers and other language-based
More informationEDA180: Compiler Construc6on. More Top- Down Parsing Abstract Syntax Trees Görel Hedin Revised:
EDA180: Compiler Construc6on More Top- Down Parsing Abstract Syntax Trees Görel Hedin Revised: 2013-02- 05 Compiler phases and program representa6ons source code Lexical analysis (scanning) Intermediate
More informationProgramming Assignment 5 Interpreter and Static Analysis
Lund University Computer Science Niklas Fors, Görel Hedin, Christoff Bürger Compilers EDAN65 2016-09-24 Programming Assignment 5 Interpreter and Static Analysis The goal of this assignment is to implement
More informationLL parsing Nullable, FIRST, and FOLLOW
EDAN65: Compilers LL parsing Nullable, FIRST, and FOLLOW Görel Hedin Revised: 2014-09- 22 Regular expressions Context- free grammar ATribute grammar Lexical analyzer (scanner) SyntacKc analyzer (parser)
More informationAn Introductory Tutorial on JastAdd Attribute Grammars
An Introductory Tutorial on JastAdd Attribute Grammars Görel Hedin Lund University, Sweden gorel@cs.lth.se Preprint, May 1, 2010. To appear in Postproceedings of GTTSE 2009. The final publication will
More informationDeclarative Intraprocedural Flow Analysis of Java Source Code
Declarative Intraprocedural Flow Analysis of Java Source Code Emma Nilsson-Nyman Torbjörn Ekman Görel Hedin Eva Magnusson Dept of Computer Science Lund University Programming Tools Group University of
More informationDrAST - An attribute debugger for JastAdd
MASTER S THESIS LUND UNIVERSITY 2016 DrAST - An attribute debugger for JastAdd Joel Lindholm, Johan Thorsberg Department of Computer Science Faculty of Engineering LTH ISSN 1650-2884 LU-CS-EX 2016-10 DrAST
More informationLL(k) Compiler Construction. Choice points in EBNF grammar. Left recursive grammar
LL(k) Compiler Construction More LL parsing Abstract syntax trees Lennart Andersson Revision 2012 01 31 2012 Related names top-down the parse tree is constructed top-down recursive descent if it is implemented
More informationLL(k) Compiler Construction. Top-down Parsing. LL(1) parsing engine. LL engine ID, $ S 0 E 1 T 2 3
LL(k) Compiler Construction More LL parsing Abstract syntax trees Lennart Andersson Revision 2011 01 31 2010 Related names top-down the parse tree is constructed top-down recursive descent if it is implemented
More information.jj file with actions
Hand-coded parser without actions Compiler Construction Computations on ASTs Lennart Andersson Revision 2011-02-07 2011 void stmt() { switch(token) { case IF: accept(if); expr(); accept(then); stmt();
More informationRewritable Reference Attributed Grammars
Rewritable Reference Attributed Grammars Torbjörn Ekman and Görel Hedin Department of Computer Science, Lund University, Sweden (torbjorn gorel)@cs.lth.se Abstract. This paper presents an object-oriented
More informationExamination in Compilers, EDAN65
Examination in Compilers, EDAN65 Department of Computer Science, Lund University 2016 10 28, 08.00-13.00 Note! Your exam will be marked only if you have completed all six programming lab assignments in
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 informationJastAdd an aspect-oriented compiler construction system
JastAdd an aspect-oriented compiler construction system Görel Hedin Eva Magnusson Department of Computer Science, Lund University, Sweden Abstract We describe JastAdd, a Java-based system for compiler
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 informationProgramming Assignment 2 LALR Parsing and Building ASTs
Lund University Computer Science Jesper Öqvist, Görel Hedin, Niklas Fors, Christoff Bürger Compilers EDAN65 2016-09-05 Programming Assignment 2 LALR Parsing and Building ASTs The goal of this assignment
More informationExtensible Compiler Architecture Examples from JModelica.org
Extensible Compiler Architecture Examples from JModelica.org Uses of the JastAdd systems Görel Hedin Computer Science, Lund University LCCC workshop, Lund, Sept 20, 2012 1 Background JastAdd: an open source
More informationA Short Summary of Javali
A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler
More informationLecture 8 CS 412/413 Spring '00 -- Andrew Myers 2. Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 4
CS412/413 Introduction to Compilers and Translators Spring 00 Outline Typechecking Symbol tables Using symbol tables for analysis Lecture 8: Semantic Analysis and Symbol Tables Lecture 8 CS 412/413 Spring
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 informationEDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:
EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 2017-09-11 This lecture Regular expressions Context-free grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)
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 informationProgramming Assignment 2 LALR Parsing and Building ASTs
Lund University Computer Science Jesper Öqvist, Görel Hedin, Niklas Fors, Christoff Bürger Compilers EDAN65 2018-09-10 Programming Assignment 2 LALR Parsing and Building ASTs The goal of this assignment
More informationTopics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited
CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation
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 informationThe Structure of a Syntax-Directed Compiler
Source Program (Character Stream) Scanner Tokens Parser Abstract Syntax Tree Type Checker (AST) Decorated AST Translator Intermediate Representation Symbol Tables Optimizer (IR) IR Code Generator Target
More informationIntro to dataflow analysis. CSE 501 Spring 15
Intro to dataflow analysis CSE 501 Spring 15 Announcements Paper commentaries Please post them 24 hours before class ApplicaBon paper presentabons Good training for conference talks! Will help go through
More informationFaculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology
Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4020 January 19, 2006 14.00-15.30 This exam (8 pages) consists of 60 True/False
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 informationEDAN65: Compilers, Lecture 04 Grammar transformations: Eliminating ambiguities, adapting to LL parsing. Görel Hedin Revised:
EDAN65: Compilers, Lecture 04 Grammar transformations: Eliminating ambiguities, adapting to LL parsing Görel Hedin Revised: 2017-09-04 This lecture Regular expressions Context-free grammar Attribute grammar
More informationEDA180: Compiler Construc6on. Top- down parsing. Görel Hedin Revised: a
EDA180: Compiler Construc6on Top- down parsing Görel Hedin Revised: 2013-01- 30a Compiler phases and program representa6ons source code Lexical analysis (scanning) Intermediate code genera6on tokens intermediate
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 informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions
More informationSemantic analysis. Compiler Construction. An expression evaluator. Examples of computations. Computations on ASTs Aspect oriented programming
Semantic analysis Compiler Construction source code scanner semantic analysis Computations on ASTs Aspect oriented programming tokens AST with attributes Lennart Andersson parser code generation Revision
More informationSemantic Analysis. Compiler Architecture
Processing Systems Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan Source Compiler Architecture Front End Scanner (lexical tokens Parser (syntax Parse tree Semantic Analysis
More informationProgramming Languages Third Edition. Chapter 7 Basic Semantics
Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol
More informationCircular Reference Attributed Grammars - their Evaluation and Applications
Circular Reference Attributed Grammars - their Evaluation and Applications Eva Magnusson 1 Dept of Computer Science Lund University Lund, Sweden Görel Hedin 2 Dept of Computer Science Lund University Lund,
More informationFaculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology
Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4303 April 9, 2010 14.00-15.30 This exam (6 pages) consists of 52 True/False
More information2. Reachability in garbage collection is just an approximation of garbage.
symbol tables were on the first exam of this particular year's exam. We did not discuss register allocation in this This exam has questions from previous CISC 471/672. particular year. Not all questions
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 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 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 informationCSC 467 Lecture 13-14: Semantic Analysis
CSC 467 Lecture 13-14: Semantic Analysis Recall Parsing is to translate token stream to parse tree Today How to build trees: syntax direction translation How to add information to trees: semantic analysis
More informationExtendJ The Extensible Java Compiler. Jesper Öqvist, PhD Student Lund University
ExtendJ The Extensible Java Compiler Jesper Öqvist, PhD Student Lund University About Me PhD student since 2013 Google Intern (2015 & 2016) ExtendJ Maintainer (668 commits of 1158 total) Current main project:
More informationIC Language Specification
CS 301 Spring 2016 IC Language Specification The IC Language For the implementation project, you will build a compiler for an object-oriented language called IC (for Irish Coffee 1 ), which is essentially
More informationQualifying Exam in Programming Languages and Compilers
Qualifying Exam in Programming Languages and Compilers University of Wisconsin Fall 1991 Instructions This exam contains nine questions, divided into two parts. All students taking the exam should answer
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 informationThe PCAT Programming Language Reference Manual
The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language
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 informationMid-Term 2 Grades
Mid-Term 2 Grades 100 46 1 HW 9 Homework 9, in untyped class interpreter: Add instanceof Restrict field access to local class Implement overloading (based on argument count) Due date is the same as for
More informationInformal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility
Informal Semantics of Data semantic specification names (identifiers) attributes binding declarations scope rules visibility 1 Ways to Specify Semantics Standards Documents (Language Definition) Language
More informationWhat about Object-Oriented Languages?
What about Object-Oriented Languages? What is an OOL? A language that supports object-oriented programming How does an OOL differ from an ALL? (ALGOL-Like Language) Data-centric name scopes for values
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 informationIntegrating Xtext and JavaRAG: Using an attribute grammar library in a language workbench
MASTER S THESIS LUND UNIVERSITY 2016 Integrating Xtext and JavaRAG: Using an attribute grammar library in a language workbench Emin Gigovic, Philip Malmros Department of Computer Science Faculty of Engineering
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 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 informationCSE 401 Midterm Exam Sample Solution 2/11/15
Question 1. (10 points) Regular expression warmup. For regular expression questions, you must restrict yourself to the basic regular expression operations covered in class and on homework assignments:
More informationIntermediate Formats. for object oriented languages
Intermediate Formats for object oriented languages Program Representation Goals Enable Program Analysis and Transformation Semantic Checks, Correctness Checks, Optimizations Structure Translation to Machine
More informationThe Decaf Language. 1 Lexical considerations
The Decaf Language In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance
More informationIntermediate Formats. for object oriented languages
Intermediate Formats for object oriented languages Program Representation Goals Enable Program Analysis and Transformation Semantic Checks, Correctness Checks, Optimizations Structure Translation to Machine
More informationWhen do We Run a Compiler?
When do We Run a Compiler? Prior to execution This is standard. We compile a program once, then use it repeatedly. At the start of each execution We can incorporate values known at the start of the run
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 informationFaculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology
Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4020 July 5, 2007 14.00-15.30 This exam (8 pages) consists of 60 True/False
More informationThe SPL Programming Language Reference Manual
The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming
More informationParsing Techniques. AST Review. AST Data Structures. LL AST Construction. AST Construction CS412/CS413. Introduction to Compilers Tim Teitelbaum
Parsing Techniques C41/C413 Introduction to Compilers Tim Teitelbaum Lecture 11: yntax-directed Definitions February 14, 005 LL parsing Computes a Leftmost derivation Determines the derivation top-down
More informationAngelaZ. Angel invests on those who awaits and prepare for the Zen of Matrix People know Matrix. We know the ZEN!
AngelaZ Angel invests on those who awaits and prepare for the Zen of Matrix People know Matrix. We know the ZEN! ZEN Yeah, sit there doing nothing! But, not really.. Our language focus on Matrix ComputaBon
More informationCS 406: Syntax Directed Translation
CS 406: Syntax Directed Translation Stefan D. Bruda Winter 2015 SYNTAX DIRECTED TRANSLATION Syntax-directed translation the source language translation is completely driven by the parser The parsing process
More information5. Semantic Analysis. Mircea Lungu Oscar Nierstrasz
5. Semantic Analysis Mircea Lungu Oscar Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes. http://www.cs.ucla.edu/~palsberg/
More informationThe Structure of a Syntax-Directed Compiler
Source Program (Character Stream) Scanner Tokens Parser Abstract Syntax Tree (AST) Type Checker Decorated AST Translator Intermediate Representation Symbol Tables Optimizer (IR) IR Code Generator Target
More informationHomework 1 Simple code genera/on. Luca Della Toffola Compiler Design HS15
Homework 1 Simple code genera/on Luca Della Toffola Compiler Design HS15 1 Administra1ve issues Has everyone found a team- mate? Mailing- list: cd1@lists.inf.ethz.ch Please subscribe if we forgot you 2
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 informationEDA180: Compiler Construc6on Context- free grammars. Görel Hedin Revised:
EDA180: Compiler Construc6on Context- free grammars Görel Hedin Revised: 2013-01- 28 Compiler phases and program representa6ons source code Lexical analysis (scanning) Intermediate code genera6on tokens
More informationAbstract Syntax Trees Synthetic and Inherited Attributes
Abstract Syntax Trees Synthetic and Inherited Attributes Lecture 22 Sections 5.1-5.2 Robb T. Koether Hampden-Sydney College Mon, Mar 16, 2015 Robb T. Koether (Hampden-Sydney College)Abstract Syntax TreesSynthetic
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 informationCSE 504: Compiler Design. Intermediate Representations Symbol Table
Intermediate Representations Symbol Table Pradipta De pradipta.de@sunykorea.ac.kr Current Topic Intermediate Representations Graphical IRs Linear IRs Symbol Table Information in a Program Compiler manages
More informationLecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.
Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.
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 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 informationCSE 431S Final Review. Washington University Spring 2013
CSE 431S Final Review Washington University Spring 2013 What You Should Know The six stages of a compiler and what each stage does. The input to and output of each compilation stage (especially the back-end).
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 informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 4a Andrew Tolmach Portland State University 1994-2017 Semantics and Erroneous Programs Important part of language specification is distinguishing valid from
More informationCS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11
CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Spring 2015 1 Handling Overloaded Declarations Two approaches are popular: 1. Create a single symbol table
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationModelica Change Proposal MCP-0019 Flattening (In Development) Proposed Changes to the Modelica Language Specification Version 3.
Modelica Change Proposal MCP-0019 Flattening (In Development) Proposed Changes to the Modelica Language Specification Version 3.3 Revision 1 Table of Contents Preface 3 Chapter 1 Introduction 3 Chapter
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level
More informationCSE 401 Final Exam. December 16, 2010
CSE 401 Final Exam December 16, 2010 Name You may have one sheet of handwritten notes plus the handwritten notes from the midterm. You may also use information about MiniJava, the compiler, and so forth
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 informationSyntax Directed Translation
Syntax Directed Translation 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 informationCS5363 Final Review. cs5363 1
CS5363 Final Review cs5363 1 Programming language implementation Programming languages Tools for describing data and algorithms Instructing machines what to do Communicate between computers and programmers
More informationReading Assignment. Scanner. Read Chapter 3 of Crafting a Compiler.
Reading Assignment Source Program (Character Stream) Scanner Tokens Parser Abstract Syntax Tree (AST) Type Checker Decorated AST Read Chapter 3 of Crafting a Compiler. Translator Intermediate Representation
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2017 Lecture 3a Andrew Tolmach Portland State University 1994-2017 Binding, Scope, Storage Part of being a high-level language is letting the programmer name things: variables
More informationAcknowledgement. CS Compiler Design. Semantic Processing. Alternatives for semantic processing. Intro to Semantic Analysis. V.
Acknowledgement CS3300 - Compiler Design Intro to Semantic Analysis V. Krishna Nandivada IIT Madras Copyright c 2000 by Antony L. Hosking. Permission to make digital or hard copies of part or all of this
More information11. a b c d e. 12. a b c d e. 13. a b c d e. 14. a b c d e. 15. a b c d e
CS-3160 Concepts of Programming Languages Spring 2015 EXAM #1 (Chapters 1-6) Name: SCORES MC: /75 PROB #1: /15 PROB #2: /10 TOTAL: /100 Multiple Choice Responses Each multiple choice question in the separate
More informationA programming language requires two major definitions A simple one pass compiler
A programming language requires two major definitions A simple one pass compiler [Syntax: what the language looks like A context-free grammar written in BNF (Backus-Naur Form) usually suffices. [Semantics:
More informationLecture 14 Sections Mon, Mar 2, 2009
Lecture 14 Sections 5.1-5.4 Hampden-Sydney College Mon, Mar 2, 2009 Outline 1 2 3 4 5 Parse A parse tree shows the grammatical structure of a statement. It includes all of the grammar symbols (terminals
More informationThe Decaf language 1
The Decaf language 1 In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance
More informationTREES Lecture 10 CS2110 Spring2014
TREES Lecture 10 CS2110 Spring2014 Readings and Homework 2 Textbook, Chapter 23, 24 Homework: A thought problem (draw pictures!) Suppose you use trees to represent student schedules. For each student there
More informationCOMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou
COMP-421 Compiler Design Presented by Dr Ioanna Dionysiou Administrative! Any questions about the syllabus?! Course Material available at www.cs.unic.ac.cy/ioanna! Next time reading assignment [ALSU07]
More information