SlideShare a Scribd company logo
Static Checking and Type Systems Chapter 6 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2007-2009
The Structure of our Compiler Revisited Lexical analyzer Syntax-directed static checker Character stream Token stream Java bytecode Yacc specification JVM specification Lex specification Syntax-directed translator Type checking Code generation
Static versus Dynamic Checking ,[object Object],[object Object],[object Object],[object Object]
Static Checking ,[object Object],[object Object],[object Object],[object Object],[object Object]
Type Checks, Overloading, Coercion, and Polymorphism int op(int), op(float); int f(float); int a, c[10], d; d = c+d; // FAIL *d = a; // FAIL a = op(d); // OK: overloading (C++) a = f(d); // OK: coersion of d to float vector<int> v; // OK: template instantiation
Flow-of-Control Checks myfunc() { … break; // ERROR } myfunc() { … switch (a)   { case 0: …   break; // OK case 1: … } } myfunc() { … while (n) { … if (i>10) break; // OK } }
Uniqueness Checks myfunc() { int i, j, i; // ERROR    … } cnufym(int a, int a) // ERROR {  … } struct myrec { int name; }; struct myrec // ERROR { int id; };
Name-Related Checks LoopA: for (int I = 0; I < n; I++) { …   if (a[I] == 0)   break LoopB; // Java labeled loop   … }
One-Pass versus Multi-Pass Static Checking ,[object Object],[object Object],[object Object]
Type Expressions ,[object Object],[object Object],[object Object],[object Object]
Graph Representations for Type Expressions int *f(char*,char*) fun args pointer char int pointer char pointer Tree forms fun args pointer char int pointer DAGs
Cyclic Graph Representations struct Node { int val;   struct Node *next; }; struct val pointer int Internal compiler representation of the  Node  type: cyclic graph next Source program
Name Equivalence ,[object Object],[object Object],[object Object],type link = ^node; var next : link;   last : link;   p : ^node;   q, r : ^node; With name equivalence in Pascal: p  ≠  next p  ≠  last p  =  q  =  r next  =  last
Structural Equivalence of Type Expressions ,[object Object],[object Object],struct val next int pointer struct val int pointer = pointer next
Structural Equivalence of Type Expressions (cont’d) ,[object Object],struct val int pointer s p struct Node { int val;   struct Node *next; }; struct Node s, *p; …  p = &s; // OK … *p = s; // OK next &s *p
Constructing Type Graphs in Yacc Type *mkint() construct int node if not already   constructed Type *mkarr(Type*,int) construct array-of-type node   if not already constructed   Type *mkptr(Type*) construct pointer-of-type node   if not already constructed
Syntax-Directed Definitions for Constructing Type Graphs in Yacc %union { Symbol *sym;   int num;   Type *typ; } %token INT %token <sym> ID %token <int> NUM %type <typ> type %% decl : type ID  { addtype($2, $1); }   | type ID ‘[’ NUM ‘]’ { addtype($2, mkarr($1, $4)); }   ; type : INT  { $$ = mkint(); }   | type ‘*’  { $$ = mkptr($1); }   | /* empty */  { $$ = mkint(); }   ;
Type Systems ,[object Object],[object Object],[object Object]
Type Rules in Post System Notation     e 1  :  integer     e 2  :  integer     e 1   +   e 2  :  integer Type judgments e  :   where  e  is an expression and    is a type Environment     maps objects  v  to types   :  ( v ) =    ( v ) =         v  :       e  :       v  :=  e  :  void  ( v ) =  
Type System Example     y + 2  :  integer     x := y + 2  :  void Environment    is a set of   name ,  type   pairs, for example:    = {   x , integer  ,   y , integer  ,   z , char  ,   1, integer  ,   2, integer   } From    and rules we can check types: type checking = theorem proving The proof that  x := y + 2  is typed correctly:  ( y ) =  integer       y  :  integer  ( x ) =  integer    ( 2 ) =  integer       2  :  integer
A Simple Language Example P      D   ;   S D      D   ;   D      id :  T T      boolean      char      integer      array   [ num ] of   T      ^   T S      id :=   E      if   E   then   S      while   E   do   S      S   ;   S E      true      false        literal        num        id      E   and   E      E   +   E      E   [   E   ]      E   ^ Pascal-like pointer dereference operator Pointer to  T
Simple Language Example: Declarations D      id :  T {  addtype ( id .entry,  T .type) } T      boolean {  T .type :=  boolean  } T      char {  T .type :=  char  } T      integer {  T .type :=  integer  } T      array   [ num ] of   T 1 {  T .type :=  array (1.. num .val,  T 1 .type) } T      ^   T 1 {  T .type :=  pointer ( T 1 ) Parametric types: type constructor
Simple Language Example: Checking Statements S      id :=   E  {  S .type :=  if   id .type =  E .type  then   void   else   type_error  }     e  :       v  :=  e  :  void  ( v ) =     Note: the type of  id  is determined by scope’s environment: id .type =  lookup ( id .entry)
Simple Language Example: Checking Statements (cont’d) S      if   E   then   S 1 {  S .type :=  if   E .type =  boolean   then   S 1 .type   else   type_error  }      s  :       if  e  then  s  :      e  :  boolean    
Simple Language Example: Statements (cont’d) S      while   E   do   S 1 {  S .type :=  if   E .type =  boolean   then   S 1 .type   else   type_error  }      s  :       while  e  do  s  :      e  :  boolean    
Simple Language Example: Checking Statements (cont’d) S      S 1   ;   S 2 {  S .type :=  if   S 1 .type =  void  and  S 2 .type =  void  then  void   else   type_error  }      s 2  :  void     s 1   ;  s 2   :  void    s 1  :  void    
Simple Language Example: Checking Expressions E      true {  E .type =  boolean  } E      false   {  E .type =  boolean  } E      literal   {  E .type =  char  } E      num {  E .type =  integer  }  E      id {  E .type =  lookup ( id .entry) } …  ( v ) =         v  :  
Simple Language Example: Checking Expressions (cont’d) E      E 1   +   E 2 {  E .type :=  if   E 1 .type =  integer   and   E 2 .type =  integer     then   integer   else   type_error  }       e 1  :  integer     e 2  :  integer     e 1   +   e 2  :  integer
Simple Language Example: Checking Expressions (cont’d) E      E 1   and   E 2   {  E .type :=  if   E 1 .type =  boolean   and   E 2 .type =  boolean     then   boolean   else   type_error  }       e 1  :  boolean     e 2  :  boolean     e 1   and   e 2  :  boolean
Simple Language Example: Checking Expressions (cont’d) E      E 1   [   E 2   ]  {  E .type :=  if   E 1 .type =  array ( s ,  t )  and   E 2 .type =  integer     then   t   else   type_error  }       e 1  :  array ( s ,   )     e 2  :  integer     e 1 [ e 2 ]  :  
Simple Language Example: Checking Expressions (cont’d) E      E 1   ^ {  E .type :=  if   E 1 .type =  pointer ( t )  then   t   else   type_error  }       e  :  pointer (  )     e   ^  :  
A Simple Language Example: Functions T      T   ->   T E      E   (   E   ) Example: v : integer; odd : integer -> boolean; if odd(3) then   v := 1; Function type declaration Function call
Simple Language Example: Function Declarations T      T 1   ->  T 2 {  T .type :=  function ( T 1 .type,  T 2 .type) } Parametric type: type constructor
Simple Language Example: Checking Function Invocations E      E 1   (   E 2   )  {  E .type :=  if   E 1 .type =  function ( s ,  t )  and   E 2 .type =  s     then   t   else   type_error  }       e 1  :  function (  ,   )     e 2  :       e 1 ( e 2 )  :  
Type Conversion and Coercion ,[object Object],[object Object],[object Object]
Syntax-Directed Definitions for Type Checking in Yacc %{ enum Types {Tint, Tfloat, Tpointer, Tarray, … }; typedef struct Type { enum Types type;   struct Type *child; // at most one type parameter } Type; %} %union { Type *typ; } %type <typ> expr %% …
Syntax-Directed Definitions for Type Checking in Yacc (cont’d) … %% expr : expr ‘+’ expr { if ($1->type != Tint   || $3->type != Tint)   semerror(“non-int operands in +”);   $$ = mkint();   emit(iadd);   }
Syntax-Directed Definitions for Type Coercion in Yacc … %% expr : expr ‘+’ expr   { if ($1->type == Tint && $3->type == Tint)   { $$ = mkint(); emit(iadd);   } else if ($1->type == Tfloat && $3->type == Tfloat)   { $$ = mkfloat(); emit(fadd);   }   else if ($1->type == Tfloat && $3->type == Tint)   { $$ = mkfloat(); emit(i2f); emit(fadd);   }   else if ($1->type == Tint && $3->type == Tfloat)   { $$ = mkfloat(); emit(swap); emit(i2f); emit(fadd);   }   else semerror(“type error in +”);   $$ = mkint(); }
Checking L-Values and R-Values in Yacc %{ typedef struct Node { Type *typ;  // type structure   int islval; // 1 if L-value } Node; %} %union { Node *rec; } %type <rec> expr %% …
Checking L-Values and R-Values in Yacc expr : expr ‘+’ expr   { if ($1->typ->type != Tint || $3->typ->type != Tint)   semerror(“non-int operands in +”);   $$->typ = mkint();   $$->islval = FALSE;   emit(…);   }    | expr ‘=’ expr   { if (!$1->islval || $1->typ != $3->typ)   semerror(“invalid assignment”);   $$->typ = $1->typ;   $$->islval = FALSE;   emit(…);   }   | ID   { $$->typ = lookup($1);   $$->islval = TRUE;   emit(…);   }
Type Inference and Polymorphic Functions ,[object Object],[object Object],[object Object],[object Object],[object Object]
Type Inference and Polymorphic Functions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Type Inference and Polymorphic Functions ,[object Object],[object Object],    e 1  : α   -> β     e 2  : α     e 1 ( e 2 )  : β     length  : ∀α.list(α) -> integer     [“a”, “b”] : list(string)     length ( [“a”, “b”] )  : integer …
Example Type Inference Append  concatenates two lists recursively: fun   append ( x, y ) = if   null ( x )  then   y else   cons ( hd ( x ) , append ( tl ( x ),  y ))  where null  : ∀α.list(α) -> bool hd  : ∀α.list(α) -> α tl  : ∀α.list(α) -> list(α) cons  : ∀α.(α  ×  list(α)) -> list(α)
Example Type Inference fun   append ( x, y ) = if   null ( x )  then   y else   cons ( hd ( x ) , append ( tl ( x ),  y ))  The type of  append  :   ∀ σ ,τ, φ . ( σ  × τ) ->  φ  is: type of  x  :   σ  =  list(α 1 ) from  null ( x ) type of  y  :   τ =  φ  from  append ’s return type return type of  append  : list(α 2 ) from return type of  cons and   α 1  = α 2  because     cons ( hd(x), append ( tl ( x ),  y )) : list(α 2 )     hd ( x ) : α 1     x  : list(α 1 )     append ( tl ( x ) , y ) : list(α 1 )     tl ( x ) : list(α 1 )     y  : list(α 1 )  x  : list(α 1 ) 
Example Type Inference fun   append ( x, y ) = if   null ( x )  then   y else   cons ( hd ( x ) , append ( tl ( x ),  y ))  The type of  append  :   ∀ σ ,τ, φ . ( σ  × τ) ->  φ  is: σ  =  list(α) τ =  φ  = list(α) Hence, append  : ∀α.(list(α)  ×  list(α)) -> list(α)
Example Type Inference     append ([1, 2], [3]) :  τ     append ([1, 2], [3]) : list( α )     ([1, 2],[3]) : list( α ) ×  list( α ) τ  = list( α ) α  = integer     append ([1], [“a”]) :  τ     append ([1], [“a”]) : list( α )     ([1],[“a”]) : list( α ) ×  list( α ) Type error
Type Inference: Substitutions, Instances, and Unification ,[object Object],[object Object],[object Object]
Unification An AST representation of  append ([], [1, 2])  apply append  : ∀α.(list(α)  ×  list(α)) -> list(α) [] : list( φ )  1 : integer (  ×  ) : ( σ ,  τ ) [  ,  ] : list( ψ ) 2 : integer
Unification An AST representation of  append ([], [1, 2])  apply append  : ∀α.(list(α)  ×  list(α)) -> list(α) (  ×  ) : ( σ ,  τ ) [] : list( φ )  [  ,  ] : list( ψ ) 1 : integer 2 : integer τ  =  list( ψ ) = list(integer) ⇒  φ  =  ψ  = integer σ  =  list( φ ) = list( ψ ) ⇒  φ  =  ψ Unify by the following substitutions: σ  =  τ  =  list( α ) ⇒  α  = integer

More Related Content

What's hot

Code Optimization
Code OptimizationCode Optimization
Code Optimization
Akhil Kaushik
 
Intermediate code generator
Intermediate code generatorIntermediate code generator
Intermediate code generator
sanchi29
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Dharita Chokshi
 
Lecture 4 principles of parallel algorithm design updated
Lecture 4   principles of parallel algorithm design updatedLecture 4   principles of parallel algorithm design updated
Lecture 4 principles of parallel algorithm design updated
Vajira Thambawita
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
ASHOK KUMAR REDDY
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
vikram mahendra
 
Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
Dattatray Gandhmal
 
Classification in data mining
Classification in data mining Classification in data mining
Classification in data mining
Sulman Ahmed
 
Assembly and Machine Code
Assembly and Machine CodeAssembly and Machine Code
Assembly and Machine Code
Project Student
 
Address in the target code in Compiler Construction
Address in the target code in Compiler ConstructionAddress in the target code in Compiler Construction
Address in the target code in Compiler Construction
Muhammad Haroon
 
Regular Expression in Compiler design
Regular Expression in Compiler designRegular Expression in Compiler design
Regular Expression in Compiler design
Riazul Islam
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
AD3251-Data Structures Design-Notes-Searching-Hashing.pdf
AD3251-Data Structures  Design-Notes-Searching-Hashing.pdfAD3251-Data Structures  Design-Notes-Searching-Hashing.pdf
AD3251-Data Structures Design-Notes-Searching-Hashing.pdf
Ramco Institute of Technology, Rajapalayam, Tamilnadu, India
 
Array in c++
Array in c++Array in c++
Array in c++
Mahesha Mano
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
swapnac12
 
COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
Code generator
Code generatorCode generator
Code generatorTech_MX
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler Design
Kuppusamy P
 
Compiler Design
Compiler DesignCompiler Design
Compiler DesignMir Majid
 

What's hot (20)

Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Intermediate code generator
Intermediate code generatorIntermediate code generator
Intermediate code generator
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
3. mining frequent patterns
3. mining frequent patterns3. mining frequent patterns
3. mining frequent patterns
 
Lecture 4 principles of parallel algorithm design updated
Lecture 4   principles of parallel algorithm design updatedLecture 4   principles of parallel algorithm design updated
Lecture 4 principles of parallel algorithm design updated
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
 
Classification in data mining
Classification in data mining Classification in data mining
Classification in data mining
 
Assembly and Machine Code
Assembly and Machine CodeAssembly and Machine Code
Assembly and Machine Code
 
Address in the target code in Compiler Construction
Address in the target code in Compiler ConstructionAddress in the target code in Compiler Construction
Address in the target code in Compiler Construction
 
Regular Expression in Compiler design
Regular Expression in Compiler designRegular Expression in Compiler design
Regular Expression in Compiler design
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
AD3251-Data Structures Design-Notes-Searching-Hashing.pdf
AD3251-Data Structures  Design-Notes-Searching-Hashing.pdfAD3251-Data Structures  Design-Notes-Searching-Hashing.pdf
AD3251-Data Structures Design-Notes-Searching-Hashing.pdf
 
Array in c++
Array in c++Array in c++
Array in c++
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time Environments
 
Code generator
Code generatorCode generator
Code generator
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler Design
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 

Viewers also liked

Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
Mozaic Works
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 
Type checking
Type checkingType checking
Type checkingrawan_z
 
Type checking in compiler design
Type checking in compiler designType checking in compiler design
Type checking in compiler design
Sudip Singh
 
Compiler construction
Compiler constructionCompiler construction
Compiler construction
Muhammed Afsal Villan
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
Huawei Technologies
 
Type conversions
Type conversionsType conversions
Type conversions
sanya6900
 

Viewers also liked (8)

Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Type checking
Type checkingType checking
Type checking
 
Type checking in compiler design
Type checking in compiler designType checking in compiler design
Type checking in compiler design
 
Compiler construction
Compiler constructionCompiler construction
Compiler construction
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
 
Type conversions
Type conversionsType conversions
Type conversions
 

Similar to Ch6

Ch6.ppt
Ch6.pptCh6.ppt
Ch6.ppt
daniloalbay1
 
12TypeSystem.pdf
12TypeSystem.pdf12TypeSystem.pdf
12TypeSystem.pdf
MdAshik35
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysisraosir123
 
IMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptxIMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptx
lemonchoos
 
ANSI C REFERENCE CARD
ANSI C REFERENCE CARDANSI C REFERENCE CARD
ANSI C REFERENCE CARD
Tia Ricci
 
Lecture 1 - Lexical Analysis.ppt
Lecture 1 - Lexical Analysis.pptLecture 1 - Lexical Analysis.ppt
Lecture 1 - Lexical Analysis.ppt
NderituGichuki1
 
Chapter Two(1)
Chapter Two(1)Chapter Two(1)
Chapter Two(1)bolovv
 
Declarative Semantics Definition - Static Analysis and Error Checking
Declarative Semantics Definition - Static Analysis and Error CheckingDeclarative Semantics Definition - Static Analysis and Error Checking
Declarative Semantics Definition - Static Analysis and Error Checking
Guido Wachsmuth
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
Eelco Visser
 
12IRGeneration.pdf
12IRGeneration.pdf12IRGeneration.pdf
12IRGeneration.pdf
SHUJEHASSAN
 
Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafios
Brian Cardiff
 
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution
Eelco Visser
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdf
king931283
 
Types and perl language
Types and perl languageTypes and perl language
Types and perl language
Masahiro Honma
 
C Tutorial
C TutorialC Tutorial
C Tutorial
Dr.Subha Krishna
 
compiler Design course material chapter 2
compiler Design course material chapter 2compiler Design course material chapter 2
compiler Design course material chapter 2
gadisaAdamu
 
C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 

Similar to Ch6 (20)

Ch6.ppt
Ch6.pptCh6.ppt
Ch6.ppt
 
12TypeSystem.pdf
12TypeSystem.pdf12TypeSystem.pdf
12TypeSystem.pdf
 
Ch3
Ch3Ch3
Ch3
 
Ch5a
Ch5aCh5a
Ch5a
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysis
 
IMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptxIMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptx
 
ANSI C REFERENCE CARD
ANSI C REFERENCE CARDANSI C REFERENCE CARD
ANSI C REFERENCE CARD
 
Lecture 1 - Lexical Analysis.ppt
Lecture 1 - Lexical Analysis.pptLecture 1 - Lexical Analysis.ppt
Lecture 1 - Lexical Analysis.ppt
 
Chapter Two(1)
Chapter Two(1)Chapter Two(1)
Chapter Two(1)
 
Declarative Semantics Definition - Static Analysis and Error Checking
Declarative Semantics Definition - Static Analysis and Error CheckingDeclarative Semantics Definition - Static Analysis and Error Checking
Declarative Semantics Definition - Static Analysis and Error Checking
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
 
12IRGeneration.pdf
12IRGeneration.pdf12IRGeneration.pdf
12IRGeneration.pdf
 
Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafios
 
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdf
 
Types and perl language
Types and perl languageTypes and perl language
Types and perl language
 
C Tutorial
C TutorialC Tutorial
C Tutorial
 
compiler Design course material chapter 2
compiler Design course material chapter 2compiler Design course material chapter 2
compiler Design course material chapter 2
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
C tutorial
C tutorialC tutorial
C tutorial
 

More from kinnarshah8888 (15)

Yuva Msp All
Yuva Msp AllYuva Msp All
Yuva Msp All
 
Yuva Msp Intro
Yuva Msp IntroYuva Msp Intro
Yuva Msp Intro
 
Ch9c
Ch9cCh9c
Ch9c
 
Ch8a
Ch8aCh8a
Ch8a
 
Ch9b
Ch9bCh9b
Ch9b
 
Ch9a
Ch9aCh9a
Ch9a
 
Ch10
Ch10Ch10
Ch10
 
Ch7
Ch7Ch7
Ch7
 
Ch2
Ch2Ch2
Ch2
 
Ch4b
Ch4bCh4b
Ch4b
 
Ch4a
Ch4aCh4a
Ch4a
 
Ch8b
Ch8bCh8b
Ch8b
 
Ch5b
Ch5bCh5b
Ch5b
 
Ch4c
Ch4cCh4c
Ch4c
 
Ch1
Ch1Ch1
Ch1
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 

Ch6

  • 1. Static Checking and Type Systems Chapter 6 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2007-2009
  • 2. The Structure of our Compiler Revisited Lexical analyzer Syntax-directed static checker Character stream Token stream Java bytecode Yacc specification JVM specification Lex specification Syntax-directed translator Type checking Code generation
  • 3.
  • 4.
  • 5. Type Checks, Overloading, Coercion, and Polymorphism int op(int), op(float); int f(float); int a, c[10], d; d = c+d; // FAIL *d = a; // FAIL a = op(d); // OK: overloading (C++) a = f(d); // OK: coersion of d to float vector<int> v; // OK: template instantiation
  • 6. Flow-of-Control Checks myfunc() { … break; // ERROR } myfunc() { … switch (a) { case 0: … break; // OK case 1: … } } myfunc() { … while (n) { … if (i>10) break; // OK } }
  • 7. Uniqueness Checks myfunc() { int i, j, i; // ERROR … } cnufym(int a, int a) // ERROR { … } struct myrec { int name; }; struct myrec // ERROR { int id; };
  • 8. Name-Related Checks LoopA: for (int I = 0; I < n; I++) { … if (a[I] == 0) break LoopB; // Java labeled loop … }
  • 9.
  • 10.
  • 11. Graph Representations for Type Expressions int *f(char*,char*) fun args pointer char int pointer char pointer Tree forms fun args pointer char int pointer DAGs
  • 12. Cyclic Graph Representations struct Node { int val; struct Node *next; }; struct val pointer int Internal compiler representation of the Node type: cyclic graph next Source program
  • 13.
  • 14.
  • 15.
  • 16. Constructing Type Graphs in Yacc Type *mkint() construct int node if not already constructed Type *mkarr(Type*,int) construct array-of-type node if not already constructed Type *mkptr(Type*) construct pointer-of-type node if not already constructed
  • 17. Syntax-Directed Definitions for Constructing Type Graphs in Yacc %union { Symbol *sym; int num; Type *typ; } %token INT %token <sym> ID %token <int> NUM %type <typ> type %% decl : type ID { addtype($2, $1); } | type ID ‘[’ NUM ‘]’ { addtype($2, mkarr($1, $4)); } ; type : INT { $$ = mkint(); } | type ‘*’ { $$ = mkptr($1); } | /* empty */ { $$ = mkint(); } ;
  • 18.
  • 19. Type Rules in Post System Notation   e 1 : integer   e 2 : integer   e 1 + e 2 : integer Type judgments e :  where e is an expression and  is a type Environment  maps objects v to types  :  ( v ) =   ( v ) =    v :    e :    v := e : void  ( v ) = 
  • 20. Type System Example   y + 2 : integer   x := y + 2 : void Environment  is a set of  name , type  pairs, for example:  = {  x , integer  ,  y , integer  ,  z , char  ,  1, integer  ,  2, integer  } From  and rules we can check types: type checking = theorem proving The proof that x := y + 2 is typed correctly:  ( y ) = integer   y : integer  ( x ) = integer  ( 2 ) = integer   2 : integer
  • 21. A Simple Language Example P  D ; S D  D ; D  id : T T  boolean  char  integer  array [ num ] of T  ^ T S  id := E  if E then S  while E do S  S ; S E  true  false  literal  num  id  E and E  E + E  E [ E ]  E ^ Pascal-like pointer dereference operator Pointer to T
  • 22. Simple Language Example: Declarations D  id : T { addtype ( id .entry, T .type) } T  boolean { T .type := boolean } T  char { T .type := char } T  integer { T .type := integer } T  array [ num ] of T 1 { T .type := array (1.. num .val, T 1 .type) } T  ^ T 1 { T .type := pointer ( T 1 ) Parametric types: type constructor
  • 23. Simple Language Example: Checking Statements S  id := E { S .type := if id .type = E .type then void else type_error }   e :    v := e : void  ( v ) =  Note: the type of id is determined by scope’s environment: id .type = lookup ( id .entry)
  • 24. Simple Language Example: Checking Statements (cont’d) S  if E then S 1 { S .type := if E .type = boolean then S 1 .type else type_error }  s :    if e then s :   e : boolean  
  • 25. Simple Language Example: Statements (cont’d) S  while E do S 1 { S .type := if E .type = boolean then S 1 .type else type_error }  s :    while e do s :   e : boolean  
  • 26. Simple Language Example: Checking Statements (cont’d) S  S 1 ; S 2 { S .type := if S 1 .type = void and S 2 .type = void then void else type_error }  s 2 : void   s 1 ; s 2 : void  s 1 : void  
  • 27. Simple Language Example: Checking Expressions E  true { E .type = boolean } E  false { E .type = boolean } E  literal { E .type = char } E  num { E .type = integer } E  id { E .type = lookup ( id .entry) } …  ( v ) =    v : 
  • 28. Simple Language Example: Checking Expressions (cont’d) E  E 1 + E 2 { E .type := if E 1 .type = integer and E 2 .type = integer then integer else type_error }   e 1 : integer   e 2 : integer   e 1 + e 2 : integer
  • 29. Simple Language Example: Checking Expressions (cont’d) E  E 1 and E 2 { E .type := if E 1 .type = boolean and E 2 .type = boolean then boolean else type_error }   e 1 : boolean   e 2 : boolean   e 1 and e 2 : boolean
  • 30. Simple Language Example: Checking Expressions (cont’d) E  E 1 [ E 2 ] { E .type := if E 1 .type = array ( s , t ) and E 2 .type = integer then t else type_error }   e 1 : array ( s ,  )   e 2 : integer   e 1 [ e 2 ] : 
  • 31. Simple Language Example: Checking Expressions (cont’d) E  E 1 ^ { E .type := if E 1 .type = pointer ( t ) then t else type_error }   e : pointer (  )   e ^ : 
  • 32. A Simple Language Example: Functions T  T -> T E  E ( E ) Example: v : integer; odd : integer -> boolean; if odd(3) then v := 1; Function type declaration Function call
  • 33. Simple Language Example: Function Declarations T  T 1 -> T 2 { T .type := function ( T 1 .type, T 2 .type) } Parametric type: type constructor
  • 34. Simple Language Example: Checking Function Invocations E  E 1 ( E 2 ) { E .type := if E 1 .type = function ( s , t ) and E 2 .type = s then t else type_error }   e 1 : function (  ,  )   e 2 :    e 1 ( e 2 ) : 
  • 35.
  • 36. Syntax-Directed Definitions for Type Checking in Yacc %{ enum Types {Tint, Tfloat, Tpointer, Tarray, … }; typedef struct Type { enum Types type; struct Type *child; // at most one type parameter } Type; %} %union { Type *typ; } %type <typ> expr %% …
  • 37. Syntax-Directed Definitions for Type Checking in Yacc (cont’d) … %% expr : expr ‘+’ expr { if ($1->type != Tint || $3->type != Tint) semerror(“non-int operands in +”); $$ = mkint(); emit(iadd); }
  • 38. Syntax-Directed Definitions for Type Coercion in Yacc … %% expr : expr ‘+’ expr { if ($1->type == Tint && $3->type == Tint) { $$ = mkint(); emit(iadd); } else if ($1->type == Tfloat && $3->type == Tfloat) { $$ = mkfloat(); emit(fadd); } else if ($1->type == Tfloat && $3->type == Tint) { $$ = mkfloat(); emit(i2f); emit(fadd); } else if ($1->type == Tint && $3->type == Tfloat) { $$ = mkfloat(); emit(swap); emit(i2f); emit(fadd); } else semerror(“type error in +”); $$ = mkint(); }
  • 39. Checking L-Values and R-Values in Yacc %{ typedef struct Node { Type *typ; // type structure int islval; // 1 if L-value } Node; %} %union { Node *rec; } %type <rec> expr %% …
  • 40. Checking L-Values and R-Values in Yacc expr : expr ‘+’ expr { if ($1->typ->type != Tint || $3->typ->type != Tint) semerror(“non-int operands in +”); $$->typ = mkint(); $$->islval = FALSE; emit(…); } | expr ‘=’ expr { if (!$1->islval || $1->typ != $3->typ) semerror(“invalid assignment”); $$->typ = $1->typ; $$->islval = FALSE; emit(…); } | ID { $$->typ = lookup($1); $$->islval = TRUE; emit(…); }
  • 41.
  • 42.
  • 43.
  • 44. Example Type Inference Append concatenates two lists recursively: fun append ( x, y ) = if null ( x ) then y else cons ( hd ( x ) , append ( tl ( x ), y )) where null : ∀α.list(α) -> bool hd : ∀α.list(α) -> α tl : ∀α.list(α) -> list(α) cons : ∀α.(α × list(α)) -> list(α)
  • 45. Example Type Inference fun append ( x, y ) = if null ( x ) then y else cons ( hd ( x ) , append ( tl ( x ), y )) The type of append : ∀ σ ,τ, φ . ( σ × τ) -> φ is: type of x : σ = list(α 1 ) from null ( x ) type of y : τ = φ from append ’s return type return type of append : list(α 2 ) from return type of cons and α 1 = α 2 because   cons ( hd(x), append ( tl ( x ), y )) : list(α 2 )   hd ( x ) : α 1   x : list(α 1 )   append ( tl ( x ) , y ) : list(α 1 )   tl ( x ) : list(α 1 )   y : list(α 1 )  x : list(α 1 ) 
  • 46. Example Type Inference fun append ( x, y ) = if null ( x ) then y else cons ( hd ( x ) , append ( tl ( x ), y )) The type of append : ∀ σ ,τ, φ . ( σ × τ) -> φ is: σ = list(α) τ = φ = list(α) Hence, append : ∀α.(list(α) × list(α)) -> list(α)
  • 47. Example Type Inference   append ([1, 2], [3]) : τ   append ([1, 2], [3]) : list( α )   ([1, 2],[3]) : list( α ) × list( α ) τ = list( α ) α = integer   append ([1], [“a”]) : τ   append ([1], [“a”]) : list( α )   ([1],[“a”]) : list( α ) × list( α ) Type error
  • 48.
  • 49. Unification An AST representation of append ([], [1, 2]) apply append : ∀α.(list(α) × list(α)) -> list(α) [] : list( φ ) 1 : integer ( × ) : ( σ , τ ) [ , ] : list( ψ ) 2 : integer
  • 50. Unification An AST representation of append ([], [1, 2]) apply append : ∀α.(list(α) × list(α)) -> list(α) ( × ) : ( σ , τ ) [] : list( φ ) [ , ] : list( ψ ) 1 : integer 2 : integer τ = list( ψ ) = list(integer) ⇒ φ = ψ = integer σ = list( φ ) = list( ψ ) ⇒ φ = ψ Unify by the following substitutions: σ = τ = list( α ) ⇒ α = integer