CSE 5317/4305 L6: Semantic Analysis1 Semantic Analysis Leonidas Fegaras.

Slides:



Advertisements
Similar presentations
CPSC 388 – Compiler Design and Construction
Advertisements

Semantic Analysis and Symbol Tables
Symbol Table.
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Peter Fritzson 1 MetaModelica for Meta-Modeling and Model Transformations Peter Fritzson, Adrian Pop, Peter Aronsson OpenModelica Course at INRIA, 2006.
Semantic Analysis Chapter 6. Two Flavors  Static (done during compile time) –C –Ada  Dynamic (done during run time) –LISP –Smalltalk  Optimization.
CS7100 (Prasad)L16-7AG1 Attribute Grammars Attribute Grammar is a Framework for specifying semantics and enables Modular specification.
1 Compiler Construction Intermediate Code Generation.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Elaboration or: Semantic Analysis Compiler Baojian Hua
CSE 5317/4305 L5: Abstract Syntax1 Abstract Syntax Leonidas Fegaras.
Tutorial 6 & 7 Symbol Table
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
Elaboration or: Semantic Analysis Compiler Baojian Hua
Cse321, Programming Languages and Compilers 1 6/19/2015 Lecture #18, March 14, 2007 Syntax directed translations, Meanings of programs, Rules for writing.
Cse321, Programming Languages and Compilers 1 6/23/2015 Lecture #15, March. 5, 2007 Judgments for mini-Java Multiple type environments Class Hierarchy.
Environments and Evaluation
Yu-Chen Kuo1 Chapter 2 A Simple One-Pass Compiler.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Chapter 2 A Simple Compiler
SchemeCOP Introduction to Scheme. SchemeCOP Scheme Meta-language for coding interpreters –“ clean ” semantics Scheme = LISP + ALGOL –simple.
Building An Interpreter After having done all of the analysis, it’s possible to run the program directly rather than compile it … and it may be worth it.
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
CSC 8310 Programming Languages Meeting 2 September 2/3, 2014.
CS784 (Prasad)L167AG1 Attribute Grammars Attribute Grammar is a Framework for specifying semantics and enables Modular specification.
Symbol Table (  ) Contents Map identifiers to the symbol with relevant information about the identifier All information is derived from syntax tree -
Syntax & Semantic Introduction Organization of Language Description Abstract Syntax Formal Syntax The Way of Writing Grammars Formal Semantic.
Semantic Analysis CS 671 February 5, CS 671 – Spring The Compiler So Far Lexical analysis Detects inputs with illegal tokens –e.g.: main$
5. Semantic Analysis Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture.
Semantic Analysis (Generating An AST) CS 471 September 26, 2007.
COMPILERS Semantic Analysis hussein suleman uct csc3005h 2006.
1 Semantic Analysis Aaron Bloomfield CS 415 Fall 2005.
7-1 7 Contextual analysis  Aspects of contextual analysis  Scope checking  Type checking  Case study: Fun contextual analyser  Representing types.
Chapter Twenty-ThreeModern Programming Languages1 Formal Semantics.
COMPILERS Symbol Tables hussein suleman uct csc3003s 2007.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
Unit-1 Introduction Prepared by: Prof. Harish I Rathod
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
Prof. Fateman CS 164 Lecture 111 Syntax  Simple Semantics Lecture 11.
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
Review: Syntax directed translation. –Translation is done according to the parse tree. Each production (when used in the parsing) is a sub- structure of.
CSE 5317/4305 L6: Semantic Analysis1 Semantic Analysis Leonidas Fegaras.
CS1101 Group1 Discussion 10 Lek Hsiang Hui comp.nus.edu.sg
Compiler (scalac, gcc) Compiler (scalac, gcc) I = 0 while (i < 10) { i = i + 1 } I = 0 while (i < 10) { i = i + 1 } source code i d 3 = 0 LF w i d 3 =
1 Compiler & its Phases Krishan Kumar Asstt. Prof. (CSE) BPRCE, Gohana.
Bernd Fischer RW713: Compiler and Software Language Engineering.
1 A Simple Syntax-Directed Translator CS308 Compiler Theory.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
CSE 130 : Spring 2011 Programming Languages Ranjit Jhala UC San Diego Lecture 5: Functions and Closures.
CPSC 388 – Compiler Design and Construction Parsers – Syntax Directed Translation.
CSE 5317/4305 L5: Abstract Syntax1 Abstract Syntax Leonidas Fegaras.
CS412/413 Introduction to Compilers Radu Rugina Lecture 11: Symbol Tables 13 Feb 02.
Overview of Compilation Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Programming Language Principles Lecture 2.
1 Vectors, binary search, and sorting. 2 We know about lists O(n) time to get the n-th item. Consecutive cons cell are not necessarily consecutive in.
COMPILERS Semantic Analysis hussein suleman uct csc3003s 2009.
Lecture 9 Symbol Table and Attributed Grammars
Chapter 3 – Describing Syntax
Constructing Precedence Table
Semantic Analysis with Emphasis on Name Analysis
CS 536 / Fall 2017 Introduction to programming languages and compilers
Basic Program Analysis: AST
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Semantic Analysis Semantic analysis includes
6.001 SICP Interpretation Parts of an interpreter
COMPILERS Semantic Analysis
Presentation transcript:

CSE 5317/4305 L6: Semantic Analysis1 Semantic Analysis Leonidas Fegaras

CSE 5317/4305 L6: Semantic Analysis2 Type Checking Checking whether the use of names is consistent with their declaration in the program int x; x := x+1; correct use of x x.A := 1; x[0] := 0; type errors Statically typed languages: done at compile time, not at run time Need to remember declarations –Symbol Table scanner parser get token token source file get next character AST type checking AST symbol table type errors

CSE 5317/4305 L6: Semantic Analysis3 Symbol Table A compile-time data structure used to map names into declarations It stores: –for each type name, its type definition eg. for the C type declaration typedef int* mytype, it maps the name mytype to a data structure that represents the type int* –for each variable name, its type if the variable is an array, it also stores dimension information it may also store storage class, offset in activation record, etc –for each constant name, its type and value –for each function and procedure, its formal parameter list and its output type each formal parameter must have –name –type –type of passing (by-reference, by-value, etc)‏

CSE 5317/4305 L6: Semantic Analysis4 Symbol Table (cont.)‏ Need to capture nested scopes, if necessary { int a; { int a; a = 1; }; a = 2; }; Interface: insert ( key: String, binding: Declaration )‏ lookup ( key: String ): Option[Declaration]‏ begin_scope ()‏ end_scope ()‏

CSE 5317/4305 L6: Semantic Analysis5 The Gen Symbol Table class SymbolTable { var symbol_table: List[List[(String,Declaration)]] = Nil def lookup ( key: String ): Option[Declaration] = { val ds = for ( s <- symbol_table; (n,d) <- s if n.equals(key) ) yield d ds match { case c::cs => Some(c) case _ => None } def insert ( key: String, declaration: Declaration ) { symbol_table match { case c::cs => symbol_table = ((key,declaration)::c)::cs case _ => throw new Error("Empty scope") }

CSE 5317/4305 L6: Semantic Analysis6 The Gen Symbol Table (cont.)‏ def begin_scope () { symbol_table = List()::symbol_table } def end_scope () { symbol_table match { case c::cs => symbol_table = cs case _ => throw new Error("Empty scope") }

CSE 5317/4305 L6: Semantic Analysis7 Example { int a; { int a; a = 1; }; a = 2; };

CSE 5317/4305 L6: Semantic Analysis8 Type ASTs A typechecker is a function that maps an AST that represents an expression into its type Need to define the data structures for types: sealed abstract class Type case class IntegerType () extends Type case class BooleanType () extends Type case class NamedType ( typename: String ) extends Type case class ArrayType ( elements: Type ) extends Type case class RecordType ( components: List[(String,Type)] ) extends Type

CSE 5317/4305 L6: Semantic Analysis9 Declarations The symbol table must contain type declarations (ie. typedefs),variable declarations, constant declarations, and function signatures: var symbol_table: List[List[(String,Declaration)]] = Nil sealed abstract class Declaration case class TypeDeclaration ( declaration: Type ) extends Declaration case class VarDeclaration ( declaration: Type ) extends Declaration case class ConstantDeclaration ( declaration: Type, value: Exp ) extends Declaration case class FunctionDeclaration ( result: Type, parameters: List[Type] ) extends Declaration

CSE 5317/4305 L6: Semantic Analysis10 Typechecking A tree traversals that checks each node of the AST tree recursively: def typecheck ( e: Expr ): Type = e match { case IntegerExp => IntegerType case TrueExp => BooleanType case FalseExp => BooleanType case VariableExp(name) => st.lookup(name) match { case Some(VarDeclaration(type) => type case Some(_) => throw new Error(name+" is not a variable") case None => throw new Error("Undefined variable: "+name) }

CSE 5317/4305 L6: Semantic Analysis11 Typechecking: BinaryExp case BinOpExp(op,left,right) => { val left_type = typecheck(left) val right_type = typecheck(right) op match { case "+": if (left_type == right_type && left_type == IntegerType()) left_type else throw new Error("expected integers in addition") … }

CSE 5317/4305 L6: Semantic Analysis12 Typechecking: CallExp case CallExp(f,args) => st.lookup(f) match { case Some(FunctionDeclaration(otp,params)) => { if (params.length != args.length) throw new Error("Number of parameters doesn't match number of arguments") else (args.map(typecheck(_)) zip params).map({ case (atp,(_,ptp)) => if (!equal_types(atp,ptp)) throw new Error("The type of call argument ("+atp +") does not match the type of the formal parameter: "+ptp) }) otp } case _ => throw new Error("Undefined function: "+f) } equal_types(x,y) checks the types x and y for equality Two types of type equality: type equality based on type name equivalence, or based on structural equivalence

CSE 5317/4305 L6: Semantic Analysis13 The Calculator Interpreter Evaluate an expression e using a symbol table st: def eval ( e: Expr ): Double = { e match { case RealConst(v) => v case IntConst(v) => v case StringConst(v) => throw new Error("Strings are not permitted: "+e) case Var(v) => st.lookup(v) match { case Some(VarDec(v)) => v case Some(_) => throw new Error(v+" is not a variable") case None => throw new Error("Undefined variable: "+v) } case IfExp(e1,e2,e3) => if (eval(e1) > 0.0) eval(e2) else eval(e3)

CSE 5317/4305 L6: Semantic Analysis14 The Calculator Interpreter (cont.)‏ case CallExp(fnc,args) => st.lookup(fnc) match { case Some(FunDec(body,params)) => if (params.length != args.length) throw new Error("Number of parameters does not much number of arguments") else { st.begin_scope() (args.map(eval(_)) zip params).map({ case (a,p) => st.insert(p,new VarDec(a)) }) val res = eval(body) st.end_scope() res } case Some(_) => throw new Error(fnc+" has not been defined as a function"); case None => throw new Error("Undefined function: "+fnc) }

CSE 5317/4305 L6: Semantic Analysis15 The Calculator Interpreter (cont.)‏ case BinOpExp(op,e1,e2) => { val left = eval(e1) val right = eval(e2) op match { case "plus" => left + right case "minus" => left - right case "times" => left * right case "div" => left / right case "and" => if ((left > 0.0) && (right > 0.)) 1.0 else 0.0 case "or" => if ((left > 0.0) || (right > 0.0)) 1.0 else 0.0 case "eq" => if (left == right) 1.0 else 0.0 case "ne" => if (left != right) 1.0 else 0.0 case "gt" => if (left > right) 1.0 else 0.0 case "lt" => if (left < right) 1.0 else 0.0 case "ge" => if (left >= right) 1.0 else 0.0 case "le" => if (left <= right) 1.0 else 0.0 case _ => throw new Error("Unrecognized binary operation: "+e) } case _ => throw new Error("Unrecognized expression: "+e)