Docsity

Semantic Analysis - Compiler Construction - Lecture Slides, Slides of Compiler Construction

Partial preview of the text

Download Semantic Analysis - Compiler Construction - Lecture Slides and more Slides Compiler Construction in PDF only on Docsity!

Semantic Analysis Typechecking in COOL

Outline

  • The role of semantic analysis in a compiler
    • A laundry list of tasks
  • Scope
  • Types

What’s Wrong?

  • • Example - let y: Int in x +
  • • Example
    • let y: String  “abc” in y +

Why a Separate Semantic Analysis?

  • Parsing cannot catch some errors
  • Some language constructs are not context- free - Example: All used variables must have been declared (i.e. scoping) - Example: A method must be invoked with arguments of proper type (i.e. typing)

Scope

  • Matching identifier declarations with uses
    • Important semantic analysis step in most languages
    • Including COOL!

Scope (Cont.)

  • The scope of an identifier is the portion of a program in which that identifier is accessible
  • The same identifier may refer to different things in different parts of the program - Different scopes for same name don’t overlap
  • An identifier may have restricted scope

Static Scoping Example

let x: Int <- 0 in

{ x; let x: Int <- 1 in x; x; }

Static Scoping Example (Cont.)

let x: Int <- 0 in

{ x; let x: Int <- 1 in x; x; }

Uses of x refer to closest enclosing definition

Scope in Cool

  • Cool identifier bindings are introduced by
    • Class declarations (introduce class names)
    • Method definitions (introduce method names)
    • Let expressions (introduce object id’s)
    • Formal parameters (introduce object id’s)
    • Attribute definitions in a class (introduce object id’s)
    • Case expressions (introduce object id’s)

Implementing the Most-Closely Nested Rule

  • Much of semantic analysis can be expressed as a recursive descent of an AST - Process an AST node n - Process the children of n - Finish processing the AST node n

Symbol Tables

  • Consider again: let x: Int  0 in e
  • Idea:
    • Before processing e, add definition of x to current definitions, overriding any other definition of x
    • After processing e, remove definition of x and restore old definition of x

• A symbol table is a data structure that tracks

the current bindings of identifiers

Scope in Cool (Cont.)

  • Not all kinds of identifiers follow the most- closely nested rule
  • For example, class definitions in Cool
    • Cannot be nested
    • Are globally visible throughout the program
  • In other words, a class name can be used before it is defined

More Scope in Cool

Attribute names are global within the class in which they are defined

Class Foo {

f(): Int { a }; a: Int  0;

}

More Scope (Cont.)

  • Method and attribute names have complex rules
  • A method need not be defined in the class in which it is used, but in some parent class
  • Methods may also be redefined (overridden)