FUNCTIONAL AND LOGIC PROGRAMS

Size: px
Start display at page:

Download "FUNCTIONAL AND LOGIC PROGRAMS"

Transcription

1 FUNCTIONAL AND LOGIC PROGRAMS

2 Contents Language Specific Compilation Context Handling Identification Scope Overloading Imported Scope Type Checking Type table Type equivalence Coercions Casts and conversions Object Oriented Language Issues Routines and Activation Code Generation and Control Flow

3 Contents Funtional Programming Introduction Basic Compilation Polymorphic type checking Compiling to register oriented architectures JavaCC

4 Language Specific Compilation Concept of compiler remains similar for any languages however its implementations differ from paradigm to paradigm(or language to language) This happens due to the syntactic and semantic differences. The main difference however in any paradigm lie in code generation : OO and structured oriented languages generate code at assembler or low level, whereas many compilers for functional, parallel and distributed languages generate code in C or C++.

5 Concerned with type checking it relates the type of a variable in a declaration to its use means in short semantic analysis. Context Handling It is also related to identification

6 Context Handling Identification Type Checking

7 Identification The process of finding the defining occurrence of a given applied occurrence of an identifier or operator Defining occurrence of the identifier is the place where it is declared. This gives us the information about the identifier : its initial value, whether it is a constant or a variable, a module or class etc. Applied occurrence of an identifier are the i.e use consumers of the information. Some languages like LISP or Prolog have no declaration of identifiers i.e no defining occurences. The identification process stores all the occurences of an identifier in the symbol table.

8 Identification int month[12];..1 month = 1; 2 do { cout<<month_name[month];.3 } while (month<=12); 4 In above code, 1 is defining occurrence 2,3,4 are applied occurrence of identifier month.

9 Identification In some languages like C, forward declaration is provided, which means having more than one defining occurrences. int x; int get( ) } { return x; int x = 5; main() { int x = 3;..1 cout<< Value of x = << get() ; } In above code, 1,3,4 are defining occurrence 2 is applied occurrence of identifier x. This is forward declaration.

10 Identification The identifiers can be searched in the symbol table depending upon their namespaces General namespace is the one in which identifiers like variable names, structure names, funtion names are stored Special namespace is the one for field selectors like struct members, class members etc

11 Identification struct one_int { } i;.... int i; i.i = 3;.. The first i before dot is searched in general namespace whereas second in special namespace.

12 Identification Labels, Module names can also live in special namespaces Namespaces depends upon the syntax of various languages In C there are three namespaces : One for enums, structs and unions, Second for Labels and the last containing variable names, function names, type names

13 Identification.Scope Some namespaces are scope- structured Scopes are arranged in the form of stack. For each scope there is an entry in the stack. Rules for creating stack of scopes A new Scope is pushed into the stack. Declared identifiers are entered in the top scope element For each applied occurrence, search scope elements from top to bottom Upon scope exit, remove the top scope element and all its declarations.

14 A scoped hash-based symbol table Name of identifier Pointer to declaration Other Information Level at which identifier is present Properti es of the identifie r Pointer to the next node

15 A scoped hash-based symbol table aap( int noot) { int mies, aap;... } noot decl 1 prop scope stack hash table bucket 0 bucket 1 bucket 2 aap decl 2 prop 0 prop bucket 3 mies level decl 2 prop

16 Identification.Overloading The ambiguity caused by overloading is resolved by considering the context in which the name to be identified occurs The overloaded identifiers come up with a set of definitions. These definitions are selected from the list of pointer to declaration field

17 Identification.Imported Scopes C++ scope resolution operator x:: Modula FROM module IMPORT... Solution: stack (or merge) the new scope

18 Type checking Operators and functions impose restrictions on the types of the arguments Types basic types structured types type names Some languages support forward references i.e referring to an identifier that is not yet declared Type information in a compiler must be implemented in such a way that all these checks must be performed conveniently

19 Forward Referencing Example Class A; Class B { A a; //forward reference.. } Class A {.. }

20 Type checking To resolve forward references, whenever it is met, it is added to the symbol table, marking as forward reference When type declaration for this forward reference is met, its symbol table entry is modified to represent the actual type instead of forward reference A check must be added for loose ends i.e any forward references not modified A check must also be there for circularity i.e. TYPE x = y; TYPE y = x;

21 Type checking... Type table All Type information for each type is stored in a type table The entry contains following : Its type constructor ( basic, record, array, pointer, and others); The size and alignment requirement of a variable of the type The types of components Various information is being recorded for types: For basic types : its precise type(integer, real etc.) For record type : The list of record fields, their names and types For Array : the number of dimension, index type(s) and element type For pointer : the referenced type

22 Type table Example TYPE a = b; TYPE b = Pointer to a; TYPE c = d; TYPE d = c;

23 Type table Example For, TYPE a = b; TYPE TABLE SYMBOL TABLE TYPE 0 : INTEGER integer : TYPE 0 TYPE 1 : ID_REF b a : TYPE 1 b : UNDEFINED TYPE

24 Type table Example TYPE a = b; TYPE b = Pointer to a; TYPE TABLE SYMBOL TABLE TYPE 0 : INTEGER integer : TYPE 0 TYPE 1 : ID_REF b a : TYPE 1 TYPE 2 : ID_REF a b : TYPE 3 TYPE 3 : Pointer to TYPE 2

25 Type table Example Finally we have, TYPE TABLE SYMBOL TABLE TYPE 0 : INTEGER integer : TYPE 0 TYPE 1 : ID_REF b a : TYPE 1 TYPE 2 : ID_REF a b : TYPE 3 TYPE 3 : Pointer to TYPE 2 c : TYPE4 TYPE 4 : ID_REF d d : TYPE 5 TYPE 5 : ID_REF c

26 Type table Example Finally we have, TYPE TABLE TYPE 0 : INTEGER TYPE 1 : TYPE 3 TYPE 2 : TYPE 1 TYPE 3 : Pointer to TYPE 2 TYPE 4 : TYPE 5 TYPE 5 : TYPE 4

27 Type checking... Type Equivalence Always while performing type checking of an expression or the formal and actual parameters ofa routine call check the equality of two types. When two types are equivalent value of these types are usually having same representations name equivalence [all types get a unique name] VAR a : ARRAY [Integer 1..10] OF Real; VAR b : ARRAY [Integer 1..10] OF Real;

28 Type checking... Type Equivalence structural equivalence [difficult to check] TYPE c = RECORD i : Integer; p : POINTER TO c; END RECORD; TYPE d = RECORD i : Integer; p : POINTER TO RECORD i : Integer; p : POINTER to c; END RECORD; END RECORD;

29 Type Checking : Coercions implicit data and type conversion to match operand (argument) type coercions complicate identification (ambiguity) VAR a : Real;... a := 5; two phase approach expand a type to a set by applying coercions reduce type sets based on constraints imposed by (overloaded) operators and language semantics

30 Variable: value or location?...kind checking two usages of variables rvalue: value lvalue: location VAR p : Real; VAR q : Real;... p := q; insert coercion to dereference variable checking rules: found lvalue expected rvalue lvalue - deref rvalue ERROR...lvalue required - (location of) p := deref (location of) q

31 Object Oriented Source language Issues Basic types of data Enumeration : copied,compared,incremented & decremented Pointer : Typed, Generic Structure and Union Array Object : Inheritance,, Polymorphism, Dynamic Binding, Method Overriding, Multiple Inheritance

32 Object Oriented Source language Issues : Pointer The run-time representation of pointer is an unsigned integer Operations include copy, assignment, comparison, increment, decrement, dereferencing Deferencing means obtaining the value of the data structure that the pointer refers to. : For Eg. ptr-> data or (*ptr).data. Pointers are usually of two types: Typed : Pointer to a specific data type. Eg. int *p; Generic : One that can be coerced to any other type For Eg. void *p;

33 Object Oriented Source language Issues : Pointer Issues Issue No Issue Solution 1 Pointer Never Intialized 2 NULL Pointer not assigned any value 3 Dangling Pointers : Arised when a pointer refers to a location and that location is freed Automatic initialization Dereferencing of null pointers must be done Use garbage collector

34 Object Oriented Source language Issues : Pointer Issues Scope of a pointer is that of the location into which it points. int x, *ptr, a; x = 5; ptr = &x; a= x; cout<< *ptr; cout<< a; { int y = 20; ptr = &y; a = y; cout<< *ptr; cout<< a; } cout<< *ptr; cout<< a; } o/p :

35 Object Oriented Source language Issues : Structure struct emp { int empid; //requires 4 bytes double salary; //requires 8 bytes }; We consider memory arrangement of the structure as follows : empid salary 4 bytes 8bytes 12 Bytes

36 Object Oriented Source language Issues : Structure But in real time, some gap must be inserted such that both structure members require equal amount of memory This memory is calculated as Least Common Multile(LCM) of the size of data members of the structure. Thus actually, the representation is as follows : empid salary Gap The size now is 16 bytes

37 Object Oriented Source language Issues : Arrays There s no disagreement about how plain arrays are stored in memory Any programming language that supports a plain (not associative) array type just stores the elements sequentially. Once a language supports multidimensional arrays, it needs to decide how to squeeze the 2D arrangement of data into a 1D arrangement in memory, typically as an 1D array. One classical use case for multidimensional arrays are matrices. Array copying can be done element by element or by copying block copy. Iilarly, comparison can be carried out. Arrays can be static as well as dynamic

38 Object Oriented Source language Issues : Arrays Given a Matrix, there s two canonical ways to store it in memory : i. Row-major ii. Column - major

39 Object Oriented Source language Issues : Arrays : Row Major Storage traverses the matrix by rows then within each row enumerates the columns. A would be stored in memory as a11, a12, a13, a21, a22, a23 The position of the element at row i, column j in the underlying 1D array is computed as : i*stride + j, where, stride is the number of elements stored per row, usually the width of the 2D array, but it can also be larger.

40 Object Oriented Source language Issues : Arrays : Column Major Storage traverses the matrix by columns, then enumerates the rows within each column. A would be stored in memory as a11, a21, a12, a22, a13,a23 The position of the element at row i, column j in the underlying 1D array is computed as : j*stride + i, where, stride is the number of elements stored per column, usually the width of the 2D array, but it can also be larger.

41 Routines and Activations : Activation record 41 When a function / subroutine is called, it will create an activation record. This record contains the location of local variable, return address etc.

42 Activation Record - Example foo()->bar()->baz(), determine the return address int foo() { int b; b = bar(); return b; } int bar() { int b = 0; b = baz(b); return b; } int baz(int b) { if (b < 1) return baz(b + 1); else return b; } 42

43 An example bar() 43

44 Activation Record temporaries: used in expression evaluation local data: field for local data saved machine status: holds info about machine status before procedure call access link : to access non local data control link :points to activation record of caller actual parameters: field to hold actual parameters Temporaries local data machine status Access links Control links Parameters Return value returned value: field for holding value to be returned 44

45 Routines Routines Classical Iterator Coroutines

46 Routines : Iterator Iterator is the one that can suspend itself temporarily and return to its parent without losing its activation record After suspension it can be resumed again at the point where it had left. This happens in C# with the help of keyword yield.

47 Routines : Coroutines Like Iterator it can suspend itself temporarily but control does not return to its parent but goes to another co-routine. This is called resume. This was offered by Simula C offers resume( )

48 Operations on Routines Define Call Return Pass

49 Advantages : INTRODUCTION TO FUNCTIONAL PROGRAMMING Have uniform view of programs Treat functions as data Automatic memory management Greatly flexible and has simple semantics Disadvantage : These are interpreted thus result in substantial loss in execution speed. Lecture 18

50 KEY PROPERTIES OF FUNCTIONAL PROGRAMMING LANGUAGES Lazy function evaluation First class objects All programs and procedures are functions Lack of variable and assignment Lack of loop and iteration Referential transparency Dynamic memory environment Garbage collection Side effect freedom Lecture 18

51 KEY FEATURES OF FUNCTIONAL PROGRAMMING LANGUAGE 1.Lazy function evaluation: Unnecessary function evaluation is done 2. First class objects : Functions are treated as objects 3. All programs and procedures are functions : Due to this feature the programs are considered as data and can be changed at run- time. This distinguishes 4. Lack of Variable Assignment 5. Lack of loops and iteration : replaced by recursive calls. Lecture 18

52 KEY FEATURES OF FUNCTIONAL PROGRAMMING LANGUAGE 6. Referential Transparency ( Side Effect Free) Property of function whereby its value depends upon the parameters, but not upon previous computations. 7.Dynamic Memory Management : Done automatically Maintaining free space Reclamation of storage 8.Garbage collection : Methods to collect and return unreferenced Lecture 18 storage

53 Factorial in Haskel vs. C fac 0 = 1 fac n = n * fac (n -1) int fac(int n) { int product = 1; while (n > 0) { product *= n ; n --; } return product; }

54 Offside rule Layout characters matter to parsing divide x 0 = inf divide x y = x / y Everything below and right of = in equations defines a new scope Applied recursively fac n = if (n ==0) then 1 else prod n (n-1) where prod acc n = if (n == 0) then acc else prod (acc * n) (n -1) Lexical analyzer maintains a stack

55 Lists Part of all functional programs since Lisp Empty list [] = Nil [1] [1, 2, 3, 4] [4, 3, 7, 7, 1] [ red, yellow, green ] [1.. 10] => arithmetic sequence Can be constructed using : infix operator [1, 2, 3] is equivalent to (1 : (2 : ( 3 : []))) range n m = if n > m then [ ] else ( n: range (n+1) m) Constructs arithmetic sequence [n m] dynamically

56 List Comprehension Inspired by set comprehension S = {n 2 n {1,, 100} odd n} Haskel code s = [n^2 n <- [1..100], odd n] n square such that n is an element of [1..100] and n is odd Qsort in Haskel qsort [] = [] qsort (x: xs) = qsort [y y <- xs, y < x] ++ [x] ++ qsort[y y <- xs, y >= x]

57 Pattern Matching Convenient way to define recursive functions A simple example fac 0 = 1 fac n = n * fac (n-1) Equivalent code fac n = if (n == 0) then 1 else n * fac (n -1) Another example length [ ] = 0 length (x: xs) = 1 + length xs Equivalent code length list = if (list == []) then 0 else let x = head list xs = tail list in 1 + length xs

58 Polymorphic Typing The basic types like int,char are said to be monomorphic types Polymorphic type means a variable can have many types. For eg. Empty list [ ] can have many types : list of characters, list of numbers etc. Benefits: Code reuse Guarantee consistency

59 Polymorphic Typing The compiler infers that in length [ ] = 0 length (x: xs) = 1 + length xs length has the type [a] -> int length :: [a] -> int Example expressions length [1, 2, 3] + length [ red, yellow, green ] length [1, 2, green ] // invalid list The user can optionally declare types Every expression has the most general type

60 Structure of a functional compiler High-level language Polymorphic type checking De-sugaring: 1. Pattern matching 2. List to pairs Optimizations 3. List comprehension 4. Lambda lifting Functional core Code generation C code Runtime system

61 Compiling Functional Languages Below is the compiler phase handles which aspect of Haskell: Compiler Phase Language Aspect Lexical Analyzer Parser Context Handling Run Time System Off side Rule List Notation List Comprehension Pattern Matching Polymorphic type checking Referential Transperency Higher Order Functions Lazy Evaluation

62 Polymorphic Type Checking These are rules that ML uses to infer the type correctness of polymorphic code known as : 1. All occurrences of the same identifier in a given scope must have the same type. 2. In an if/then/else expression, the condition must be of type bool, and the then and else clauses must be of the same type. 3. A programmer-defined function has type 'a -> 'b where 'a is the type of the function s parameter and 'b is the type of its result. (Functions have tuple arguments.) 4. When a function is applied, the type of the argument passed to the function must be the same as the parameter type in the function s definition and the type of the application is the same as the type of the result in the function s definition.

63 Polymorphic Type Checking The Hindley- Miler algorithm traverses a program s abstract syntax tree (AST)1, assigning type variables at each node. It then applies rules corresponding to syntactic constructs to attempt to resolve the assigned type variables against specific type information deduced from program contents and context.

64 Polymorphic Type Checking For example, consider checking the following Standard ML-ish function, which returns a string depending on the sign of its integer argument: fun sign 0 = "zero" sign n = if (> n) 0 then "positive" else "negative This function has type int -> string, i.e. it takes an integer argument and returns a string result

65 Polymorphic Type Checking Prior to type checking, it is assumed that: 0 : int i.e. 0 is an integer "negative" : string > : int -> int -> bool i.e. > compares two integers to return a boolean The rule for a function: Checks the first case: fun sign 0 = "zero" concludes 0 is int from assumptions checks the body i.e. deduces "zero" is string from assumptions concludes that the first case is int -> string

66 Polymorphic Type Checking Checks the second case: sign n = if (> n 0) then "positive" else "negative Assumes parameter n has type α checks the body i.e. checks the if expression: checks the condition i.e. checks the application of > n to 0 checks the application of > to n concludes that > is int -> int -> bool from assumptions assigns the type variable β to the result of the application concludes that n is α from assumptions unifies the anticipated type α -> β with the type of >, int -> int -> bool concludes that α is int and β is int -> bool

67 Polymorphic Type Checking assigns the type variable γ to the result of the application concludes that 0 is int from assumptions unifies the anticipated type int -> γ with the type of int -> bool concludes that γ is bool unifies the condition type bool with the required type for a condition, bool checks the then branch i.e. concludes that "positive" is string from assumptions checks the else branch i.e. concludes that "negative" is string from assumptions unifies the then and else branches, which must have the same type concludes that the if has type string concludes that the second case has type int -> string

68 Desugaring Translating high level construct into a simpler one means desugaring Translation of Pattern Matching Translation to List Translation to List Comprehension Desugaring

69 Translation to Lists List Notations has three operators in Functional Language : i), ii).. iii) : List of the form x : xs is transformed to (cons x xs) list[1,2,3] or list(1:3) is transformed to (cons 1(cons 2 ( cons 3 [ ] ) ) )

70 Translation OF Pattern Matching Pattern matching on constructors desugars to case statements

71 Translation OF Pattern Matching Pattern matching on numeric or string literals desugars to equality tests:

72 Translation OF List Comprehension List comprehensions are equivalent to do notation:

73 JAVA CC JAVA COMPILER COMPILER Parser and Lexical Analyzer Generator i.e it Produces Lexical Analyzers And Parsers in Java It generates Top Down Parser hence cannot parse left recursive grammar Lecture 18

74 JAVA CC JAVA COMPILER COMPILER Regular Expression Translation Grammar JAVA CC Java Code.jj file Lecture 18

75 Steps for Execution > JavaCC eg.jj //Generates eg. java > Javac eg.java //Generates eg. Class > Java eg Lecture 18

76 Java CC Specification : ClassName.jj Options { // Java CC Options } PARSER-BEGIN(Class-Name) // Code PARSER-END (Class-Name) SKIP : { } SKIP : { \n \r \r\n } TOKEN : { < PLUS : + > } TOKEN : { < NUMBER : ([ 0-9 ])+ > } void Start() : {} { <NUMBER> ( <PLUS> <NUMBER> )* <EOF> Parser Lexical Analyzer

77 JavaCC Compilation : javacc ClassName.jj Compiling this file generates Seven Files TokenMgrError is a simple error class; it is used for errors detected by the lexical analyser and is a subclass of Throwable. ParseException is another error class; it is used for errors detected by the parser and is a subclass of Exception and hence of Throwable. Token is a class representing tokens. SimpleCharStream is an adapter class that delivers characters to the lexical analyser. ClassNameConstants is an interface that defines a number of classes used in both the lexical analyser and the parser. ClassNameTokenManager is the lexical analyser ClassName is the Parser Lecture 18

78 Java CC Example PARSER_BEGIN(Calc0) // must define parser class public class Calc0 { public static void main (String args []) { Calc0 parser = new Calc0(System.in); for (;;) try { if (parser.expr() == -1) System.exit(0); } catch (Exception e) { e.printstacktrace(); System.exit(1); } } } PARSER_END(Calc0)

79 Java CC Example SKIP: { " " "\r" "\t" } // defines input to be ignored TOKEN: // defines token names { < EOL: "\n" > < CONSTANT: ( <DIGIT> )+ > // re: 1 or more < #DIGIT: ["0" - "9"] > // private re } int expr() : // expr: sum \n { } // -1 at eof, 0 at eol { sum() <EOL> { return 1; } <EOL> { return 0; } <EOF> { return -1; } }

80 Java CC Example // sum: product { + - product } void sum(): { } { product() ( ( "+" "-" ) product() )* } // product: term { *%/ term } void product():{} { term() (( "*" "%" "/" ) term() )* } // term: +term -term (sum) number void term(): {} { "+" term() "-" term() "(" sum() ")" <CONSTANT> }

Compiler construction in4020 lecture 5

Compiler construction in4020 lecture 5 Compiler construction in4020 lecture 5 Semantic analysis Assignment #1 Chapter 6.1 Overview semantic analysis identification symbol tables type checking CS assignment yacc LLgen language grammar parser

More information

Compiler construction 2002 week 5

Compiler construction 2002 week 5 Compiler construction in400 lecture 5 Koen Langendoen Delft University of Technology The Netherlands Overview semantic analysis identification symbol tables type checking assignment yacc LLgen language

More information

The PCAT Programming Language Reference Manual

The 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 information

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

Faculty 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 information

The SPL Programming Language Reference Manual

The 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 information

Compiler construction 2005 lecture 5

Compiler construction 2005 lecture 5 Compiler construction in400 lecture 5 Semantic analysis Assignment #1 Chapter 6.1 Overview semantic analysis identification symbol tables type checking CS assignment yacc LLgen language parser generator

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming 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 information

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Lecture 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 information

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

SEMANTIC 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 information

Introduction to Programming Using Java (98-388)

Introduction 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 information

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

The 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 information

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

Faculty 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 information

Type Checking and Type Inference

Type Checking and Type Inference Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

More information

Compiler Theory. (Semantic Analysis and Run-Time Environments)

Compiler 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 information

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

Faculty 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 information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. 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 information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Semantic Analysis and Type Checking

Semantic 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 information

Lecture #23: Conversion and Type Inference

Lecture #23: Conversion and Type Inference Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:

More information

R13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA.

R13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA. R13 SET - 1 III B. Tech I Semester Regular Examinations, November - 2015 1 a) What constitutes a programming environment? [3M] b) What mixed-mode assignments are allowed in C and Java? [4M] c) What is

More information

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = Hello; Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 6 Robert Grimm, New York University 1 Review Last week Function Languages Lambda Calculus SCHEME review 2 Outline Promises, promises, promises Types,

More information

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6] 1 Lecture Overview Types 1. Type systems 2. How to think about types 3. The classification of types 4. Type equivalence structural equivalence name equivalence 5. Type compatibility 6. Type inference [Scott,

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages 1 / 57 CSE 307: Principles of Programming Languages Course Review R. Sekar Course Topics Introduction and History Syntax Values and types Names, Scopes and Bindings Variables and Constants Expressions

More information

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Topics 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 information

St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad

St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad-00 014 Subject: PPL Class : CSE III 1 P a g e DEPARTMENT COMPUTER SCIENCE AND ENGINEERING S No QUESTION Blooms Course taxonomy level Outcomes UNIT-I

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Project Compiler. CS031 TA Help Session November 28, 2011

Project 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 information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

Informal 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 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 information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

Semantic 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 information

CSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1

CSE 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 information

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered

More information

CMSC 330: Organization of Programming Languages

CMSC 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 information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 15: Review and Functional Programming Zheng (Eddy) Zhang Rutgers University March 19, 2018 Class Information Midterm exam forum open in Sakai. HW4 and

More information

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

The role of semantic analysis in a compiler

The 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 information

Semantic Processing. Semantic Errors. Semantics - Part 1. Semantics - Part 1

Semantic Processing. Semantic Errors. Semantics - Part 1. Semantics - Part 1 Semantic Processing The Lexer and Parser Found lexical and syntax errors Built Abstract Syntax Tree Now!Find semantic errors.!build information about the program. Later!Generate IR Code!Optimize IR Code!Generate

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CPSC 3740 Programming Languages University of Lethbridge. Data Types Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type

More information

Data Types The ML Type System

Data Types The ML Type System 7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let

More information

Example. program sort; var a : array[0..10] of integer; procedure readarray; : function partition (y, z :integer) :integer; var i, j,x, v :integer; :

Example. program sort; var a : array[0..10] of integer; procedure readarray; : function partition (y, z :integer) :integer; var i, j,x, v :integer; : Runtime Environment Relationship between names and data objects (of target machine) Allocation & de-allocation is managed by run time support package Each execution of a procedure is an activation of the

More information

A Short Summary of Javali

A 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 information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

CS558 Programming Languages

CS558 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 information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic 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 information

Semantic Processing (Part 2)

Semantic Processing (Part 2) Semantic Processing (Part 2) All Projects Due: Fray 12-2-05, Noon Final: Monday, December 5, 2005, 10:15-12:05 Comprehensive 1 Recursive Type Definitions type MyRec is record f1: integer; f2: array of

More information

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking CS 430 Spring 2015 Mike Lam, Professor Data Types and Type Checking Type Systems Type system Rules about valid types, type compatibility, and how data values can be used Benefits of a robust type system

More information

TYPES, VALUES AND DECLARATIONS

TYPES, VALUES AND DECLARATIONS COSC 2P90 TYPES, VALUES AND DECLARATIONS (c) S. Thompson, M. Winters 1 Names, References, Values & Types data items have a value and a type type determines set of operations variables Have an identifier

More information

Expressions and Assignment

Expressions and Assignment Expressions and Assignment COS 301: Programming Languages Outline Other assignment mechanisms Introduction Expressions: fundamental means of specifying computations Imperative languages: usually RHS of

More information

5. Semantic Analysis!

5. Semantic Analysis! 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 notes.! http://www.cs.ucla.edu/~palsberg/! http://www.cs.purdue.edu/homes/hosking/!

More information

Pierce Ch. 3, 8, 11, 15. Type Systems

Pierce Ch. 3, 8, 11, 15. Type Systems Pierce Ch. 3, 8, 11, 15 Type Systems Goals Define the simple language of expressions A small subset of Lisp, with minor modifications Define the type system of this language Mathematical definition using

More information

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University Note 3 Types Yunheung Paek Associate Professor Software Optimizations and Restructuring Lab. Seoul National University Topics Definition of a type Kinds of types Issues on types Type checking Type conversion

More information

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

More information

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

CSCE 314 Programming Languages. Type System

CSCE 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 information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

5. Semantic Analysis. Mircea Lungu Oscar Nierstrasz

5. 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 information

Context Analysis. Mooly Sagiv. html://www.cs.tau.ac.il/~msagiv/courses/wcc11-12.html

Context Analysis. Mooly Sagiv. html://www.cs.tau.ac.il/~msagiv/courses/wcc11-12.html Context Analysis Mooly Sagiv html://www.cs.tau.ac.il/~msagiv/courses/wcc11-12.html 1 Short Decaf Program Interface not declared class MyClass implements MyInterface { string myinteger; void dosomething()

More information

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) Review Final exam Final exam will be 12 problems, drop any 2 Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) 2 hours exam time, so 12 min per problem (midterm 2 had

More information

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics 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 information

HANDLING NONLOCAL REFERENCES

HANDLING NONLOCAL REFERENCES SYMBOL TABLE A symbol table is a data structure kept by a translator that allows it to keep track of each declared name and its binding. Assume for now that each name is unique within its local scope.

More information

NOTE: Answer ANY FOUR of the following 6 sections:

NOTE: Answer ANY FOUR of the following 6 sections: A-PDF MERGER DEMO Philadelphia University Lecturer: Dr. Nadia Y. Yousif Coordinator: Dr. Nadia Y. Yousif Internal Examiner: Dr. Raad Fadhel Examination Paper... Programming Languages Paradigms (750321)

More information

Lecture 12: Data Types (and Some Leftover ML)

Lecture 12: Data Types (and Some Leftover ML) Lecture 12: Data Types (and Some Leftover ML) COMP 524 Programming Language Concepts Stephen Olivier March 3, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goals

More information

Data Types. (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011

Data Types. (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011 Data Types (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011 Based in part on slides and notes by Bjoern 1 Brandenburg, S. Olivier and A. Block. 1 Data Types Hardware-level:

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

CS:3820 Programming Language Concepts

CS:3820 Programming Language Concepts CS:3820 Programming Language Concepts Imperative languages, environment and store, micro-c Copyright 2013-18, Peter Sestoft and Cesare Tinelli. Created by Cesare Tinelli at the University of Iowa from

More information

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8 Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

More information

Semantic actions for declarations and expressions

Semantic actions for declarations and expressions Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Anatomy 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 information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1

Static 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 information

CS 415 Midterm Exam Spring 2002

CS 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 information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Semantic actions for declarations and expressions. Monday, September 28, 15

Semantic actions for declarations and expressions. Monday, September 28, 15 Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

G Programming Languages - Fall 2012

G 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 information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

COMP-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

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false Test 1 Multiple Choice. Write your answer to the LEFT of each problem. 4 points each 1. Which celebrity has not received an ACM Turing Award? A. Alan Kay B. John McCarthy C. Dennis Ritchie D. Bjarne Stroustrup

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

UNIVERSITY 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. P. N. Hilfinger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2010 P. N. Hilfinger CS 164: Final Examination (revised) Name: Login: You have

More information

Programs as Data 6 Imperative languages, environment and store, micro-c

Programs as Data 6 Imperative languages, environment and store, micro-c Programs as Data 6 Imperative languages, environment and store, micro-c Peter Sestoft Monday 2012-10-01* www.itu.dk 1 Course overview Today A naïve imperative language C concepts Pointers and pointer arithmetics,

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

Semantic actions for declarations and expressions

Semantic actions for declarations and expressions Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan

Prof. 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 information

CA Compiler Construction

CA 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 information

Semantic Analysis. Compiler Architecture

Semantic 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 information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Type Checking Binary Operators

Type Checking Binary Operators Type Checking Binary Operators binaryopnode expr tree expr tree Type checking steps: 1. Type check left and right operands. 2. Check that left and right operands are both scalars. 3. binaryopnode.kind

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information