2.3 context-dependent analysis - - tu kaiserslautern · context-dependent analysis problem and...
TRANSCRIPT
Compilers and Language Processing ToolsSummer Term 2011
Prof. Dr. Arnd Poetzsch-Heffter
Software Technology GroupTU Kaiserslautern
c© Prof. Dr. Arnd Poetzsch-Heffter 1
Content of Lecture
1. Introduction2. Syntax and Type Analysis
2.1 Lexical Analysis2.2 Context-Free Syntax Analysis2.3 Context-Dependent Analysis
3. Translation to Target Language3.1 Translation of Imperative Language Constructs3.2 Translation of Object-Oriented Language Constructs
4. Selected Aspects of Compilers4.1 Intermediate Languages4.2 Optimization4.3 Data Flow Analysis4.4 Register Allocation4.5 Code Generation
5. Garbage Collection6. XML Processing (DOM, SAX, XSLT)
c© Prof. Dr. Arnd Poetzsch-Heffter 2
Context-Dependent Analysis
2.3 Context-Dependent Analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 3
Context-Dependent Analysis
Section outline
1. Problem and specification techniques2. Name analysis
2.1 Specification of name analysis2.2 Realizations based on symboltables2.3 Implementation of attributions
3. Type analysis3.1 Specification of type analysis3.2 Type safety3.3 Implementation aspects
4. Interplay of name and type analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 4
Context-Dependent Analysis
Terminology
• Most authors talk about semantic analysis or analysis of the staticsemantics.
• We use the term context-dependent analysis, because
I the phase (as the other phases) aims at checking whether theprogram is a program at all. If it is not a program, it has nosemantics.
I the term semantic analysis applies better to the analysis of theprogram semantics (e.g. for optimizing, avoiding runtime errors ...)
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 5
Context-Dependent Analysis
Learning objectives
• Tasks of context-dependent analysis• Typical context conditions of programing languages• Name analysis and relation to binding• Type analysis and relation to verification• Techniques for specification and implementation of
context-dependent analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 6
Context-Dependent Analysis
Task of context-dependent analysis
Check if syntax tree complies to context conditions of language:• In error case: error handling• If correct: Provide attributed/decorated syntax tree
Context Checking/Attribute Evaluation
Syntax Tree
Decorated Syntax Tree
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 7
Context-Dependent Analysis Problem and Specification Techniques
2.3.1 Problem and Specification Techniques
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 8
Context-Dependent Analysis Problem and Specification Techniques
Problem of context-dependent analysis
The context-dependent analysis• creates connection between declaration and applied occurrence
of a program element• checks the correct usage of program elements• checks further context conditions, e.g. initialization of variables
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 9
Context-Dependent Analysis Problem and Specification Techniques
Examples
Connection to declaration/inheritance:
1 class A {2 void m() { x = B.x; }3 static B x;4 }56 class B extends A { }
Questions:• Where is declaration position of x in line 2?• Where is B in line 2 and 3 declared?• Where is the declaration of A in line 6?• Is the static field x inherited,
i.e. is the program context correct?
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 10
Context-Dependent Analysis Problem and Specification Techniques
Examples (2)
Connection between declaration and access control rules:
class MyClassIsMyCastle {private static int streetno = 169;private static class FirstFloor {private static class DiningRoom {private static int size = 36;
}}private static class SecondFloor {private static class BathRoom {private static int size = 16;private static void mymess(){System.out.print("Can access the ");System.out.print("dining room size");System.out.println(": "+FirstFloor.DiningRoom.size);
}}
}public static void main( String[] argv ){SecondFloor.BathRoom.mymess();
}}
Questions:• Which qualified names are
permitted?• May the inner classBathroom access a field ofthe inner classDiningRoom?
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 11
Context-Dependent Analysis Problem and Specification Techniques
Examples (3)
Usage of declaration and type information: Information computedby the context-dependent analysis is a prerequisite for the translation.
class A {void m( Object x ) {System.out.println( x.toString() );
}}class B extends A {void m( A x ) {System.out.println("Na so was");
}}class Overloading {public static void main(String[] argv){Object xact = new A();new B(). m( xact );
}}
Type of xact required to select correct method.c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 12
Context-Dependent Analysis Problem and Specification Techniques
Specification and implementation techniques
• Informal specification techniques for name and type rules arediverse.
• Formal specification techniques are based on attribute grammarsand inference rules.
• Attributes are a concept to incrementally decorate tree structures(not only for compiler construction). We consider
I attribute grammarsI attributatio of abstract syntax
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 13
Context-Dependent Analysis Problem and Specification Techniques
Attribute grammars
• Declare for each non-terminal and each terminal attributes (nameand type).
• Declare for each production of the CFG, (semantic) rules how thevalues of the attributes are computed.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 14
Context-Dependent Analysis Problem and Specification Techniques
Attribute grammars (2)
Example: Consider the grammar• Prog → AnwSeq,• AnwSeq → ε |Anw AnwSeq,• Anw → Ident |AnwSeq
Attribute grammar to compute number of occurrences of an identifier ina program:• non-terminals AnwSeq and Anw get attributes
I id of type IdentI anz of type int
• The semantic rules are as follows:
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 15
Context-Dependent Analysis Problem and Specification Techniques
Attribute grammars (3)
Beispiel: (Einführung Attributierung)
Betrachte die Grammatik
Prog ! AnwSeq ,
AnwSeq ! e | Anw AnwSeq ,
Anw ! Ident | AnwSeq
Att ib t tik B h d A hl dAttributgrammatik zur Berechnung der Anzahl der
Vorkommen eines geg. Bezeichners im Programm:
- die Nichtterminale AnwSeq u. Anw erhalten die
Attribute id vom Typ Ident und anz vom Typ intAttribute id vom Typ Ident und anz vom Typ int
- die Attributierungsregeln sehen wie folgt aus,
wobei id und anz bedeutet.
Prog A S
Bezeichner-
eingabe
Prog AnwSeq
drucken +
AnwSeq
AnwSeq
Anw AnwSeq
AnwAnwSeqAnw
Anw
if = then 1 else 00
128© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
IdentAnwSeq
Beispiel: (Einführung Attributierung)
Betrachte die Grammatik
Prog ! AnwSeq ,
AnwSeq ! e | Anw AnwSeq ,
Anw ! Ident | AnwSeq
Att ib t tik B h d A hl dAttributgrammatik zur Berechnung der Anzahl der
Vorkommen eines geg. Bezeichners im Programm:
- die Nichtterminale AnwSeq u. Anw erhalten die
Attribute id vom Typ Ident und anz vom Typ intAttribute id vom Typ Ident und anz vom Typ int
- die Attributierungsregeln sehen wie folgt aus,
wobei id und anz bedeutet.
Prog A S
Bezeichner-
eingabe
Prog AnwSeq
drucken +
AnwSeq
AnwSeq
Anw AnwSeq
AnwAnwSeqAnw
Anw
if = then 1 else 00
128© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
IdentAnwSeq
Beispiel: (Einführung Attributierung)
Betrachte die Grammatik
Prog ! AnwSeq ,
AnwSeq ! e | Anw AnwSeq ,
Anw ! Ident | AnwSeq
Att ib t tik B h d A hl dAttributgrammatik zur Berechnung der Anzahl der
Vorkommen eines geg. Bezeichners im Programm:
- die Nichtterminale AnwSeq u. Anw erhalten die
Attribute id vom Typ Ident und anz vom Typ intAttribute id vom Typ Ident und anz vom Typ int
- die Attributierungsregeln sehen wie folgt aus,
wobei id und anz bedeutet.
Prog A S
Bezeichner-
eingabe
Prog AnwSeq
drucken +
AnwSeq
AnwSeq
Anw AnwSeq
AnwAnwSeqAnw
Anw
if = then 1 else 00
128© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
IdentAnwSeq
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 16
Context-Dependent Analysis Problem and Specification Techniques
Attribute grammars (4)
DefinitionLet Γ be a CFG. An attribute grammar over Γ consists of• two disjoint set of attributes, Inh(X) the set of inherited attributes
and Syn(X) the set of synthesized attributes• an association of attributes to symbols X ∈ T ∪ N of Γ.• the types/domains of the attributes• semantic rules for each inherited attribute a ∈ Inh(Xi) on the right
side of a production and for each synthesized attributea ∈ Syn(X0) on the left side of a production
Xi .a = f (Yj , . . .)
• potentially further semantic actions, e.g. for output
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 17
Context-Dependent Analysis Problem and Specification Techniques
Attribute grammars (5)
Remarks:• Synthesized attributes are, for example, the type of an expression
or the target code.• Inherited attributes are, for example, declaration information or
symbol tables.• Different classes of attribute grammars are distinguished by the
permitted dependencies between attributes.• Attribute grammars are generalizations of recursion schemes.• We use attribute grammars to describe processes.• Attribute grammars are the specification technique for many
compiler generators.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 18
Context-Dependent Analysis Problem and Specification Techniques
Example: Combining productions
• Attributgrammatiken stellen eine Verallgemeinerung von Rekursionsschemata dar.
• Wir benutzen AGen zur Beschreibung von Abläufen.g
• AGen bilden die Spezifikationstechnik für viele
Übersetzer-Generatoren.
Bezeichner-
Prog
dr cken
Beispiel: (Zusammensetzen von attributierten Produktionen)
Bezeichnereingabe
AnwSeq
Anw AnwSeq
+
Anw AnwSeq
AnwSeq
+
AnwSeq
if = then 1 else 0 0
Anw AnwSeq
0
130© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Ident
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 19
Context-Dependent Analysis Problem and Specification Techniques
Attribution of abstract syntax
• Analogue to attribute grammars• Attributes are associated to types of abstract syntax• Attributes of variant types are used for all occurrences of this type,
i.e. if a is an attribute of the variant type V , then each variant Vihas an attribute a.
• Tuple types (and list types) are also attributed.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 20
Context-Dependent Analysis Problem and Specification Techniques
Example: Attribution of abstract syntax
• Prog(AnwSeq)
• AnwSeq = Empty() | Elem(Anw ,AnwSeq)
• Anw = IdAnw(Ident) | SeqAnw(AnwSeq)
Some semantic rules:
Attributierung abstrakter Syntax:
• analog zu Attributgrammatiken
• Die Attribute werden den Typen der abstrakten
Syntax zugeordnet.
• Attribute der Variantentypen werden an alle
Varianten „vererbt“, d.h. wenn a ein Attribut eines
Variantentyps mit Variante Vi ist, dann hat auch
Vi ein Attribut a.
• attributiert werden Tupeltypdeklarationenattributiert werden Tupeltypdeklarationen
(und Listentypproduktionen; hier nicht behandelt)
Beispiel: (Attributierung abstrakter Syntax)Beispiel: (Attributierung abstrakter Syntax)
Prog ( AnwSeq )
AnwSeq = Leer( ) | Elem( Anw, AnwSeq )
Anw = IdAnw( Ident ) | SeqAnw( AnwSeq )
Wir benutzen die gleiche graphische Notation wie
bei AGen, verwenden allerdings den Tupeltypen als
linke Seite der Produktion:
SeqAnwIdAnw
if = then 1 else 0
131© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
IdentAnwSeq
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 21
Context-Dependent Analysis Problem and Specification Techniques
Inference rules - concept
Inference rules are used for specification of static and dynamiclanguage and program properties, in particular for specification of typerules and operational semantics (e.g. structural operationalsemantics), and is also a basis for language implementation tools.
Principle:• Considered property is formalized with a fixed number of
parameters. Each parameter is a program part.• With inference rules, the property (judgment) is defined inductively
over the program structure.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 22
Context-Dependent Analysis Problem and Specification Techniques
Inference rules - concept (2)
Example: Language as in the previous examples
Property: Identifier Y occurs N times in program part P (Y ` P : N)
Rules:
Y ` AS : NY ` Prog(AS) : N
Y ` A : M Y ` AS : NY ` Elem(A,AS) : M + N
Y ` Empty() : 0Y ` AS : N
Y ` SeqAnw(AS) : N
Y 6= XY ` IdAnw(X ) : 0
Y = XY ` IdAnw(X ) : 1
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 23
Context-Dependent Analysis Problem and Specification Techniques
Literature
Recommended reading:
Wilhelm, Maurer: Section 9.2, pp. 424-429
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 24
Context-Dependent Analysis Name Analysis
2.3.2 Name Analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 25
Context-Dependent Analysis Name Analysis
Name Analysis
• Name analysis determines that each used identifier is alsodeclared.
• Checks context conditions• Has to make declaration information available at applied
occurrence of identifierI by connecting declaration and applied occurrenceI by transferring declaration information to applied occurrence
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 26
Context-Dependent Analysis Name Analysis
Name Analysis (2)
Name analysis is the prerequisite for binding of names to programelements, thus this phase is often called identification.
Program elements are for instance:• packages, modules, classes, types• procedures, functions• variables, fields, records, parameters• labels
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 27
Context-Dependent Analysis Name Analysis
2.3.2.1 Specification of name analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 28
Context-Dependent Analysis Name Analysis
Specification of name analysis
Informal specification technique
• Specify different kinds of named program elements• Specify defining and applied occurrences of identifiers• Specify for each declaration which program element is declared
and which identifier it binds (binding pair)• Specify the scope for each programming construct changing
scope and which binding pairs are additionally valid and which arehidden
• A program element (PE) with an identifier ID is visible at aprogram point if the binding pair (ID, PE) is valid and not hidden.
Remark: Specification techniques for name analysis are not asadvanced as for context-free analysis(Gap between formal and informal specification techniques).
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 29
Context-Dependent Analysis Name Analysis
Example: Specification of name analysis
Abstract Syntax of C Sub-Language:
Beispiele: (zur Erläuterung der Begriffe)
Siehe VorlesungSiehe Vorlesung
Beispiel: (Zusammenwirken der Begriffe)
Abstrakte Syntax einer C-Teilsprache:
Program ( GlobDeclList )
GlobDeclList * GlobDecl
GlobDecl = Var | ProcGlobDecl = Var | Proc
Var ( Ident id )
Proc ( Ident id, LocVarList, Block )
LocVarList * LocVar
LocVar ( Ident id )
Block ( LocVarList, Stat )
Stat = Assign | Call | SeqStat | Block
Assign ( Ident id, Exp )
Call ( Ident id ExpList )Call ( Ident id, ExpList )
SeqStat ( Stat , Stat )
Exp ( Ident id )
ExpList * Exp
In der Attributierung gehen wir davon aus, dass die
Listentypen in Sequenzen aufgelöst sind; z.B.:
GlobDeclList =
136© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
GlobalDeclEmpty
| GlobDeclElem( GlobDecl, GlobDeclList )
For attribution, we consider list types as sequences
Beispiele: (zur Erläuterung der Begriffe)
Siehe VorlesungSiehe Vorlesung
Beispiel: (Zusammenwirken der Begriffe)
Abstrakte Syntax einer C-Teilsprache:
Program ( GlobDeclList )
GlobDeclList * GlobDecl
GlobDecl = Var | ProcGlobDecl = Var | Proc
Var ( Ident id )
Proc ( Ident id, LocVarList, Block )
LocVarList * LocVar
LocVar ( Ident id )
Block ( LocVarList, Stat )
Stat = Assign | Call | SeqStat | Block
Assign ( Ident id, Exp )
Call ( Ident id ExpList )Call ( Ident id, ExpList )
SeqStat ( Stat , Stat )
Exp ( Ident id )
ExpList * Exp
In der Attributierung gehen wir davon aus, dass die
Listentypen in Sequenzen aufgelöst sind; z.B.:
GlobDeclList =
136© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
GlobalDeclEmpty
| GlobDeclElem( GlobDecl, GlobDeclList )
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 30
Context-Dependent Analysis Name Analysis
Example: Specification of name analysis (2)
• Program elements: global variables, procedures, formalparameters, local variables, ...
• Occurrences of Ident in Var, Proc, Loc Var are defining, all otheroccurrences are applied.
• Var defines a global variable, Proc a procedure, LocVar defineseither a formal parameter or a local variable, a binding pairconsists of a declared identifier and a program element.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 31
Context-Dependent Analysis Name Analysis
Example: Specification of name analysis (3)
• The scopes are defined as:I for a global variable, from declaration to end of programI for a procedure, from the beginning of the parameter list to the end
of the programI for a formal parameter, from the end of the parameter list to the end
of the enclosing procedureI for a local variable, from the beginning of the block statement to the
end of the block. The binding pair (ID,PE) of a non-local programelement hides all binding pairs in enclosing scopes with the sameidentifier
• Visibility is defined as usual.• For each identifier at most one binding pair may be visible at each
program point.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 32
Context-Dependent Analysis Name Analysis
2.3.2.2 Realizations based on symboltables
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 33
Context-Dependent Analysis Name Analysis
Name analysis with functional attribution
Idea: Compute for each applied occurrence of an identifier, the list ofvisible binding pairs (or a table that maps each identifier to itsdeclaration)
Simplest solution: Functional language
Data types and functions for environments and symbol table:
Spezifikation mit funktionaler Attributierung:
Idee:Idee:
Berechne für jede Anwendungsstelle eines Bezeichners
die Liste der dort sichtbaren Bindungspaare (bzw. eine
Tabelle, die jedem Bezeichner seine Deklaration
d ) Ei f h V i B f k i lzuordnet). Einfachste Variante: Benutze funktionale
Sprache für die Spezifikation/Realisierung.
D t t F kti B h ib dDatentypen u. Funktionen zur Beschreibung des
Environments bzw. der Symboltabelle:
Decl = GlobDecl | LocVar
Env * Decl
FCT enter(Decl d, Env e) Env: appfront(d,e)
FCT concat( Env e1, Env e2 ) Env:
IF e2=Env() THEN e1
ELSE concat( appback(e1,first(e2)),
rest(e2) )
FCT lookup( Ident i, Env e ) Decl:
IF e=Env() THEN nil
ELSF i=id(first(e)) THEN first(e)
138© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
ELSE lookup(i,rest(e))
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 34
Context-Dependent Analysis Name Analysis
Attribution for name analysis
• GlobDeclList, GlobDecl, LocVarList, LocVar, Stat, Exp, ExpList getinherited attribute envin of type Env
• GlobDecl gets synthesized attribute envout
Attributierung für die Namensanalyse:
Die folgenden Typen der abstrakten Syntax erhalten
ein ererbtes Attribut envin vom Typ Envein ererbtes Attribut envin vom Typ Env
(dargestellt als ) : GlobDeclList, GlobDecl,
LocVarList, LocVar, Stat, Exp, ExpList
GlobDecl erhält außerdem ein abgeleitetes
A ib (d ll l )
ProgramGlobDeclElem
Attribut envout (dargestellt als )
Env( )
GlobDeclList
GlobDeclEmpty GlobDecl GlobDeclListGlobDeclEmpty GlobDecl GlobDeclList
Var
lookup( ) = nil ?
Ident
enter(_,_)lookup(_,_) = nil ?
Proc
concat( )
enter(_,_)lookup(_,_) = nil ?
Env( )
139© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Ident LocVarList Block
concat(_,_)Env( )
envin
envout
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 35
Context-Dependent Analysis Name Analysis
Attribution for name analysis (2)
Attributierung für die Namensanalyse:
Die folgenden Typen der abstrakten Syntax erhalten
ein ererbtes Attribut envin vom Typ Envein ererbtes Attribut envin vom Typ Env
(dargestellt als ) : GlobDeclList, GlobDecl,
LocVarList, LocVar, Stat, Exp, ExpList
GlobDecl erhält außerdem ein abgeleitetes
A ib (d ll l )
ProgramGlobDeclElem
Attribut envout (dargestellt als )
Env( )
GlobDeclList
GlobDeclEmpty GlobDecl GlobDeclListGlobDeclEmpty GlobDecl GlobDeclList
Var
lookup( ) = nil ?
Ident
enter(_,_)lookup(_,_) = nil ?
Proc
concat( )
enter(_,_)lookup(_,_) = nil ?
Env( )
139© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Ident LocVarList Block
concat(_,_)Env( )
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 36
Context-Dependent Analysis Name Analysis
Attribution for name analysis (3)
LocVarEmpty LocVarElem
LocVar LocVarList
enter(_,_)
LocVar
lookup(_,_) = nil ?
Block Assign
Ident
p(_ _)
g
Env( ) concat(_,_)
isVar( lookup(_,_))?
LocVarList Stat Ident Exp
CallSeqStat CallSeqStat
isProc( lookup(_,_))?
140© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
ExpListStat Stat Ident
(Prüfe Parameteranzahl)
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 37
Context-Dependent Analysis Name Analysis
Attribution for name analysis (4)
LocVarEmpty LocVarElem
LocVar LocVarList
enter(_,_)
LocVar
lookup(_,_) = nil ?
Block Assign
Ident
p(_ _)
g
Env( ) concat(_,_)
isVar( lookup(_,_))?
LocVarList Stat Ident Exp
CallSeqStat CallSeqStat
isProc( lookup(_,_))?
140© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
ExpListStat Stat Ident
(Prüfe Parameteranzahl)check number of parameters
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 38
Context-Dependent Analysis Name Analysis
Attribution for name analysis (5)
Exp ExpElem
Exp ExpListIdent
isVar( lookup(_,_))?
ExpEmpty
ExpList
Bemerkungen:
• Das Beispiel demonstriert eine grundlegendep g g
Technik für die Namensanalyse.
• Transport von Deklarationsinformation zur
Anwendungsstelle wird allerdings nur ansatzweise
verdeutlichtverdeutlicht.
• Der einfache Datentyp zur Repräsentation des
Environments und dessen funktionale Behandlung
bieten aus Spezifikationssicht Vorteile (relativ leicht
zu verstehen, für Verifikationszwecke besser
geeignet).
• Spezifikation lässt sich direkt im MAX-System
oder ähnlichen Systemen implementieren
141© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
oder ähnlichen Systemen implementieren.
Remarks:
• Example shows basic technique for name analysis.• Transport of declaration information to applied occurrence is only
sketched.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 39
Context-Dependent Analysis Name Analysis
Attribution for name analysis (6)
• The data type for representing environments and its functionaltreatment have advantages for specification(easy to understand, more appropriate for verification)
• Specification can be directly implemented, e.g. in functionallanguages.
• For real compilers, a more efficient technique should be used;problems:
I Linear search for identifiers is too expensiveI If hashing is used, values of data type environment cannot be easily
represented by sharing, copying of symbol tables would benecessary.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 40
Context-Dependent Analysis Name Analysis
Name analysis with symbol table
Compilation units can contain a large number of identifiers. Thus,insertion and lookup of identifiers should have constant complexity.
Solution:• Hashing of identifiers in compilation unit (e.g. during scanning);
each compilation unit has finite number of identifiers:→ use array with constant access
• Enforce sequential access to symbol table such that it can beimplemented as global data structure with destructive updates:→ avoids copying
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 41
Context-Dependent Analysis Name Analysis
Name analysis with symbol table (2)
Steps for sequential access to symbol table1. Operations for entering and exiting scope G:
I Entering of scope G marks declarations of GI Exiting G deletes all declarations of G
1. Operationen zum Öffnen und Schließen eines
A. Schritte zum Erreichen des sequentiellen Flusses:
pGültigkeitsbereichs G:
- Das Öffnen markiert quasi die Deklarationen von G.
- Beim Schließen werden alle Deklarationen von G
a s der Tabelle gelöschtaus der Tabelle gelöscht.
Block
L V Li t St t
close_scp(_)open_scp(_)
2. Schreibende und lesende Zugriff auf die Symbol-tabelle werden sequentialisiert; um das in der
LocVarList Stat
q ;Attributierung zu erzwingen, betrachtet man dieSymboltabelle formal auch als Ergebnis einerlesenden Operation wie lookup.
Assign
isVar( lookup(_,_))?
143© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Ident Exp
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 42
Context-Dependent Analysis Name Analysis
Name analysis with symbol table (3)
2. Write and read accesses to symbol table are sequentialized.For attribution, symbol table is formally considered as the result ofa read operation, such as a lookup.
1. Operationen zum Öffnen und Schließen eines
A. Schritte zum Erreichen des sequentiellen Flusses:
pGültigkeitsbereichs G:
- Das Öffnen markiert quasi die Deklarationen von G.
- Beim Schließen werden alle Deklarationen von G
a s der Tabelle gelöschtaus der Tabelle gelöscht.
Block
L V Li t St t
close_scp(_)open_scp(_)
2. Schreibende und lesende Zugriff auf die Symbol-tabelle werden sequentialisiert; um das in der
LocVarList Stat
q ;Attributierung zu erzwingen, betrachtet man dieSymboltabelle formal auch als Ergebnis einerlesenden Operation wie lookup.
Assign
isVar( lookup(_,_))?
143© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Ident Exp
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 43
Context-Dependent Analysis Name Analysis
Name analysis with symbol table (4)
Steps for development of data structure1. Since scopes in the considered language (and in most other
languages) are nested, entering and exiting scopes can beorganized with a stack.
I For each nesting level nl , store a mapping of identifiers todeclaration information.
I The symbol table is a stack of these mappings.I When entering a scope, push an empty mapping onto the stack.I When exiting a scope, pop the top-most mapping from the stack.I Lookup starts with the top-most mapping, if identifier is not in the
domain, consider next mapping on stack (Complexity: max. nl)
Symbol table is stack of finite mappingsstackof (Ident → DeclInf)
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 44
Context-Dependent Analysis Name Analysis
Name analysis with symbol table (5)
2. Transformation to a finite mapping of identifiers to stacks ofdeclaration information, i.e.
stackof (Ident → DeclInf)
is transformed to
Ident → stackof(DeclInf)
This can be efficiently implemented by a matrix-linked datastructure.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 45
Context-Dependent Analysis Name Analysis
Symbol table for languages with nested scopes
Snapshot at nesting level 2
Symboltabelle für Sprachen mit
geschachtelten Gültigkeitsbereichen:
Momentaufnahme der Datenstruktur bei aktueller
Schachtelungstiefe 2:.
curr nl max nlnl: 2 1 0
IdNo:
curr_nl max_nlnl:
1
2
2 1 0
2 . . .
DE
• • •••• • •2
k
. . .
DE
DE
DE
•
•
• •
• •••
m
. . .
DE DE
DE DE• ••• •
max_id
. . .
•
Dabei sind die Deklarationseinträge für einen
Bezeichner zeilenweise angeordnet. Sie bilden einen
Keller, der von rechts nach links wächst. Die Spalten
enthalten die Einträge zu einer Schachtelungstiefe
145© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
enthalten die Einträge zu einer Schachtelungstiefe.
DE bezeichnet den Deklarationseintrag (umfasst IdNo).
Declarations for each identifier are stored in rows forming a stack that growsfrom right to left. The columns contain the nesting levels. DE is thedeclaration entry (includes IdNo of entry).
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 46
Context-Dependent Analysis Name Analysis
Operations on symbol table
• create(): initializes empty symbol table• open_scp(st): increments curr_nl• close_scp(st): deletes all entries for curr_nl, restores identifier
links, decrements curr_nl• enter(id,de,st): adds entry for curr_nl, the entry contains
I declaration entry (de)I pointer for nl linksI pointer to other entries for the identifier id
• lookup(id,st): access to declaration information of visible bindingpair for id
For sequential access in attribution, each operation returns pointer tosymbol table. The specified data type is called SymTab.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 47
Context-Dependent Analysis Name Analysis
Advantages of SymTab data type
• Complexity of lookup and enter is constant.• Complexity of exiting scope is linear in the number of declarations
of this scope.• Efficient memory management possible.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 48
Context-Dependent Analysis Name Analysis
Example: Usage of SymTab data type
1. Declaration information:
Anwendung der Symboltabelle anhand der
Beispielsprache:
1. Bestimmung der Deklarationsinformation:
DeclInf = VInf | PInf
VInf ()
PInf ( Int parcount )PInf ( Int parcount )
Zur Sequentialisierung der Symboltabellenzugriffe
h lt f t ll T d b t kt S t
2. Attributierung:
erhalten fast alle Typen der abstrakten Syntax
ein ererbtes Attribut symin vom Typ SymTab
(dargestellt als ) und ein abgeleitetes
Attribut symout (dargestellt als ). Darüberhinaus
b k L V Li t d E Li t i b l it t
Program GlobDeclElem
bekommen LocVarList und ExpList ein abgeleitetes
Attribut length vom Typ Int (dargestellt als ).
create
open_scp(_)
GlobDeclList
GlobDeclEmpty
GlobDecl GlobDeclList
147© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
close_scp(_)
2. Attribution:For sequential access to the symbol table, almost all types of theabstract syntax get an inherited attribute symin of type SymTaband a synthesized attribute symout.Additionally, LocVarList and ExpList get an synthesized attributelength of type Int.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 49
Context-Dependent Analysis Name Analysis
Example: Semantic rules
Anwendung der Symboltabelle anhand der
Beispielsprache:
1. Bestimmung der Deklarationsinformation:
DeclInf = VInf | PInf
VInf ()
PInf ( Int parcount )PInf ( Int parcount )
Zur Sequentialisierung der Symboltabellenzugriffe
h lt f t ll T d b t kt S t
2. Attributierung:
erhalten fast alle Typen der abstrakten Syntax
ein ererbtes Attribut symin vom Typ SymTab
(dargestellt als ) und ein abgeleitetes
Attribut symout (dargestellt als ). Darüberhinaus
b k L V Li t d E Li t i b l it t
Program GlobDeclElem
bekommen LocVarList und ExpList ein abgeleitetes
Attribut length vom Typ Int (dargestellt als ).
create
open_scp(_)
GlobDeclList
GlobDeclEmpty
GlobDecl GlobDeclList
147© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
close_scp(_)
Var
lookup( ) = nil ? enter( Vinf() )lookup(_,_) = nil ? enter(_,Vinf(),_)
Proc
Ident
lookup(_,_) = nil ?
close_scp(_)
Ident LocVarList Block
enter(_,Pinf(_),_)
open_scp(_)
Ident LocVarList Block
LocVarEmpty LocVarElem
0 +1
148© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
LocVar LocVarList
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 50
Context-Dependent Analysis Name Analysis
Example: Semantic rules (2)
Var
lookup( ) = nil ? enter( Vinf() )lookup(_,_) = nil ? enter(_,Vinf(),_)
Proc
Ident
lookup(_,_) = nil ?
close_scp(_)
Ident LocVarList Block
enter(_,Pinf(_),_)
open_scp(_)
Ident LocVarList Block
LocVarEmpty LocVarElem
0 +1
148© A . P o e t z s c h - H e f f t e r , T U K a i s e r s l a u t e r n10.05.2007
LocVar LocVarList
length
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 51
Context-Dependent Analysis Name Analysis
Example: Semantic rules (3)
LocVar
lookup( ) = nil ? enter( Vinf() )lookup(_,_) = nil ? enter(_,Vinf(),_)
Ident
BlockBlock
open_scp(_) close_scp(_)
LocVarList Stat
Assign SeqStat
Ident Exp Stat Stat
isVar( lookup(_,_))?
149© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 52
Context-Dependent Analysis Name Analysis
Example: Semantic rules (4)
LocVar
lookup( ) = nil ? enter( Vinf() )lookup(_,_) = nil ? enter(_,Vinf(),_)
Ident
BlockBlock
open_scp(_) close_scp(_)
LocVarList Stat
Assign SeqStat
Ident Exp Stat Stat
isVar( lookup(_,_))?
149© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
ExpEmpty ExpElem
0 +1
E
Exp ExpList
Exp
isVar( lookup(_,_))?
Ident
Call
isProc( lookup(_,_))? parcount(lookup(_,_)) = _?
ExpListIdent
150© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 53
Context-Dependent Analysis Name Analysis
Example: Semantic rules (5)
ExpEmpty ExpElem
0 +1
E
Exp ExpList
Exp
isVar( lookup(_,_))?
Ident
Call
isProc( lookup(_,_))? parcount(lookup(_,_)) = _?
ExpListIdent
150© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 54
Context-Dependent Analysis Name Analysis
Declaration information
Declaration information has to be sufficient• to check the correct application of an identifier
I Is a variable allowed at the applied occurrence?I Is there a procedure, type, label ... allowed?I Is the number of parameters correct?I Are the types correct?
• to handle named scopesI Is a selector admissible?I Which methods and fields are contained in a class?
• to check additional context conditions(e.g. case statement in Pascal)
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 55
Context-Dependent Analysis Name Analysis
Declaration information (2)
• How to determine declaration information?I Which declaration and program elements exist?I Which information is necessary for each program element?
• Implementation of declaration informationI Reference to declaration position (simple)I Using special data structures (designed for the particular task,
e.g. table for class elements)
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 56
Context-Dependent Analysis Name Analysis
Declaration information (3)
Remarks:
• Name analysis and its implementation depend on the rules of theprograming language, e.g. name spaces, application ofdeclarations, overloading
• For separate translation, a symbol table for each translation unitshould be created that contains the declaration information of theprogram elements used by other translation units.
• The symbol table is also used for distributing other information inlater phases, e.g. address information of variables
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 57
Context-Dependent Analysis Name Analysis
Literature
Recommended Reading:• Wilhelm, Maurer: Sections 9.1.1 and 9.1.2, pp. 408 – 416• Appel: Section 5.1, pp. 108 – 119
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 58
Context-Dependent Analysis Name Analysis
2.3.2.3 Implementation of attributions
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 59
Context-Dependent Analysis Name Analysis
Implementation of attribution
Learning objectives:• Different interpretations of attributions• Introduction into the semantics of attributions• Classes of attribute grammars• Implementation techniques
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 60
Context-Dependent Analysis Name Analysis
Interpretations of attribute grammars
1. Specification and equation interpretationAn attribute grammar (AG) assigns attribute values to nodes ofgrammar trees. The specification is given by an equation systemthat is generated for each tree.
Question: Has the system a (unique) solution?
2. Functional or computational interpretationAn AG determines how attribute values in a tree are computed.
I w/o storage: goal is computation of attribute values at root nodeonly
I with storage: goal is computation of all attribute values for furtherprocessing phases
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 61
Context-Dependent Analysis Name Analysis
Interpretations of attribute grammars (2)
3. Control of action executionsAn AG describes in which order semantic actions are executed
I “copy” actions (if two attributes are equated)I semantic actions
An attribute value v is stored as long as all actions have beenexecuted that use v as parameter.
Remarks:• Use semantic actions with side effects carefully• For classification of attribute grammars, only attribute
dependencies are considered.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 62
Context-Dependent Analysis Name Analysis
Classes of attribute grammars
Definition (Non-circular attribute grammar)Let AG be an attribute grammar over CFG Γ. For syntax trees S of Γ,let Dt(S) denote the directed attribute dependency graph. The AG isnon-circular if Dt(S) is cycle free for all S.
Remarks:• For non-circular attribute grammars, the equation system for each
syntax tree has a unique solution.• Testing non-circularity is exponential in general. Thus and for
generating efficient attribute evaluators, restricted classes ofattribute grammars are considered.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 63
Context-Dependent Analysis Name Analysis
Classes of attribute grammars (2)
An attribute grammar AG over Γ is• S-attributed if AG only has synthesized attributes• L-attributed if the attributes for each syntax tree for Γ can be
evaluated with a left-right depth-first traversal.
Other important classes of attribute grammars:• absolute non-circular (Kennedy & Warren)• ordered (Karstens)
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 64
Context-Dependent Analysis Name Analysis
Implementation of attribute grammars
1. Computational interpretation w/o storage
For L-attributed grammars and other simple classes of attributegrammars, attribute evaluation can be performed by recursivefunctions:• inherited attributes become parameters• synthesized attributes become results
For each production, a function is defined that calls the semanticactions and the functions for the children (sometimes one function canhandle several productions).
Remark:For other attribute grammar classes, several functions per productionmight be used.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 65
Context-Dependent Analysis Name Analysis
Example: L-AG implemnted by recursive functionsConsider simple L-AG (cf. lecture): The environment parameter representsthe inherited attribute, the result represents the synthesized attribute:
Beispiel: (Impl. v. L-AG mit rekursiver Funktion)
Implementierung einer einfachen L-AG (s. Vorlesung)
datatype exp =
durch eine rekursive Funktion. Der Environment-
Parameter entspricht dem ererbten Attribut, das
Ergebnis dem abgeleiteten Attribut:
datatype exp =
Int of int
| Add of exp * exp
| Var of string
| Let of string * exp * exp
;
val mp = Let ("x",Add (Int 1, Int 2),
Let ("y",Int 5,
Let ("z",Int 8, Add (Add
(Var "x",Var "y"), Var "z"))));
type env = (string * int) list;
fun lkup s [] = raise notDeclared
| lkup s ((s1,i)::es) =
if s=s1 then i else lkup s es
;
fun eval E (Int i) = ifun eval E (Int i) i
| eval E (Add (le,re)) =
(eval E le) + (eval E re)
| eval E (Var s) = lkup s E
| eval E (Let (s,e1,e2)) =
157© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
eval ((s,eval E e1)::E) e2
;
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 66
Context-Dependent Analysis Name Analysis
Implementation of attribute grammars (2)
2. Computational interpretation with storage
If attribute values in the syntax tree should be memorized, attributescan be stored in components of the tree nodes and can be evaluatedby visiting the trees in an appropriate order:
→ Attribute evaluators
Attribute evaluators can be implemented manually or generatedautomatically.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 67
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator
Task: Name analysis for Java subset
2. Berechnungsinterpretation mit Speicherung:
Sollen die Attributwerte in Baum gespeichert
werden, kann man die Attribute als Komponenten
der Baumknoten vorsehen und durch Besuche
der Bäume in geeigneter Reihenfolge die
Attributwerte berechnen:
! Attributauswerter
Attributauswerter können von Hand realisiert oder
i AG t ti h i t dzu einer AG automatisch generiert werden.
Beispiel: (Attributauswerter)
Class ( DeclList )
D lLi t D lE t | D lEl
Wir betrachten die Namensanalyse für folgende
einfache Java-Teilsprache:
DeclList = DeclEmpty | DeclElem
DeclEmpty ()
DeclElem ( Decl DeclList )
Decl = FieldDecl | MethDecl
FieldDecl ( Ident )
MethDecl ( Ident Ident Ident )
Erläuterung: siehe Vorlesung
158© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Signature of symbol tableSignatur der Symboltabelle:
emptyST : ! SymTab
lookup : Ident x SymTab ! FieldMethUndef
enter : Ident x FieldMeth x SymTab ! SymTab
Attributierung:
Class
DeclEmptyemptyST
DeclList
DeclElem
Decl DeclList
159© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 68
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator (2)
Attribution of abstract syntax
Signatur der Symboltabelle:
emptyST : ! SymTab
lookup : Ident x SymTab ! FieldMethUndef
enter : Ident x FieldMeth x SymTab ! SymTab
Attributierung:
Class
DeclEmptyemptyST
DeclList
DeclElem
Decl DeclList
159© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 69
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator (3)
FieldDecl
lookup(_,_) = UNDEF ? enter(_,FIELD,_)
Ident
MethDecll
enter(_,METH,_)lookup(_,_) = UNDEF ?
Ident Ident IdentIdent Ident Ident
lookup(_,_) = METH ? lookup(_,_) = FIELD ?
160© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 70
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator (4)
Interface of symbol table
class SymTab {
Schnittstelle der Symboltabelle:
y {
static int FIELD = 1;
static int METH = 2;
static int UNDEF = 3;
t ti S T b t ST() {static SymTab emptyST() {
return new SymTab();
}
int lookup( String id ) {p( g ) {
// liefert SymTab.FIELD oder ... }
SymTab enter( String id, boolean isField ) {
// ... }
}}
class JClass {
Attributdeklaration und 2-Passauswertung:
class JClass {
DeclList dl;
// keine Attribute
void evalAttr() {
dl.stIn = SymTab.emptyST();
dl.evalAttr0();
dl.st = dl.stOut;
dl.evalAttr1();
}
161© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
}
}
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 71
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator (5)
Attribute declaration and 2-pass evaluation
class SymTab {
Schnittstelle der Symboltabelle:
y {
static int FIELD = 1;
static int METH = 2;
static int UNDEF = 3;
t ti S T b t ST() {static SymTab emptyST() {
return new SymTab();
}
int lookup( String id ) {p( g ) {
// liefert SymTab.FIELD oder ... }
SymTab enter( String id, boolean isField ) {
// ... }
}}
class JClass {
Attributdeklaration und 2-Passauswertung:
class JClass {
DeclList dl;
// keine Attribute
void evalAttr() {
dl.stIn = SymTab.emptyST();
dl.evalAttr0();
dl.st = dl.stOut;
dl.evalAttr1();
}
161© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
}
}
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 72
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator (6)
abstract class DeclList {
SymTab stIn;
SymTab stOut;
SymTab st;
abstract void evalAttr0();
abstract void evalAttr1();
}
class DeclEmpty extends DeclList {
void evalAttr0() { stOut = stIn; }
void evalAttr1() { }
}
class DeclElem extends DeclList {
Decl dc;
DeclList dl;
void evalAttr0() {
dc.stIn = this.stIn;
dc.evalAttr0();
dl.stIn = dc.stOut;
dl.evalAttr0();
this.stOut = dl.stOut;
}
void evalAttr1() {void evalAttr1() {
dc.st = this.stIn;
dl.st = this.stOut;
dc.evalAttr1();
dl.evalAttr1();
162© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
}
}
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 73
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator (7)
abstract class Decl {
SymTab stIn;
SymTab stOut;
SymTab st;
abstract void evalAttr0();
abstract void evalAttr1();
}}
class MethDecl extends Decl {
String dmid;
String umid;
String uaid;
void evalAttr0() {
if( this.stIn.lookup(dmid)!=SymTab.UNDEF ){
so println("Identifier already declared!");so.println( Identifier already declared! );
}
this.stOut = this.stIn.enter(dmid,false);
}
void evalAttr1() {
if( this.st.lookup(umid)!= SymTab.METH ){
so.println("Method not declared!");
}
if( this st lookup(uaid)!= SymTab FIELD ){if( this.st.lookup(uaid)! SymTab.FIELD ){
so.println("Attribute not declared!");
}
}
}
163© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 74
Context-Dependent Analysis Name Analysis
Example: Attribute evaluator (8)
class FieldDecl extends Decl {
String id;
void evalAttr0() {
if( this.stIn.lookup(id)!= SymTab.UNDEF ){
so.println("Identifier already declared!");
}
thi tO t thi tI t (id t )this.stOut = this.stIn.enter(id,true);
}
void evalAttr1() { }
}}
Die im obigen Beispiel demonstrierten Auswertungs-
methoden evalAttr, evalAttr0, evalAttr1 lassen sich
Bemerkung:
von Attributauswertergeneratoren automatisch
erzeugen.
Attributierung und Attributauswertung sind allg.
Verfahren zur Anreicherung von Baumstrukturen.
Ihre Anwendung ist nicht auf die kontextabhängige
Bemerkung:
Analyse von Sprachen beschränkt.
Lesen Sie zu Abschnitten 2.3.2.3:
164© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Wilhelm, Maurer:
• die Abschnitte 9.2 und 9.3 (S. 424-436)
The evaluator methods evalAttr, evalAttr0, evalAttr1 can begenerated automatically by attribute evaluator generators.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 75
Context-Dependent Analysis Name Analysis
Remark and literature
Remark:Attribution and attribute evaluation are techniques to decorate treestructures and are not limited to context-dependent analyses oflanguages.
Recommended ReadingWilhelm, Maurer: Sections 9.2 and 9.3, pp. 424–436
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 76
Context-Dependent Analysis Type Analysis
2.3.3 Type Analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 77
Context-Dependent Analysis Type Analysis
Type analysis
Relevance of Typing
• improves readability of programs• improves possibilities for static checks• allows more efficient implementations, because runtime checks
can be avoided and memory can be allocated more specifically• prerequisite for high-level programming techniques
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 78
Context-Dependent Analysis Type Analysis
Tasks of Type Analysis
• Computation and inference of explicit type informationI for declared program elements often from declaration informationI for expressions from sub-expressionsI potentially complex algorithm (because of overloading, generic
types, missing type declarations)
• Type correctness: check of typing rules
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 79
Context-Dependent Analysis Type Analysis
2.3.3.1 Specification of type analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 80
Context-Dependent Analysis Type Analysis
Specification of type analysis
The type system of a programing language determines• which types/type schemes exists in the language• how types and type instances relate• which rules a typed program has to satisfy to be type correct
For a formal specification of a type system, types are described by anabstract syntax and type rules by inference rules.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 81
Context-Dependent Analysis Type Analysis
Example: Type System
Java (w/o generics) has the following types:
2.3.3.1 Spezifikation der Typanalyse
D T i P i h ibDas Typsystem einer Programmiersprache gibt an:
• welche Typen/Typschemata es in der Sprache gibt;
• wie die Typen/Typinstanzen in Beziehung stehen;
• welche Regeln ein typisiertes Programm erfüllen
muss, um typkorrekt zu sein.
Bei einer formalen Spezifikation eines Typsystemsp yp y
werden Typen mit einer abstrakten Syntax,
die Typregeln mittels Inferenzregeln beschrieben.
Beispiel: (Typsystem)Beispiel: (Typsystem)
Java kennt die folgenden Typen:
JavaType = PrimitiveType | ReferenceType
PrimitiveType = byte | short | int | long
| char | boolean | float | double
ReferenceType = ClassType( Ident )
| InterfaceType( Ident )
| ArrayType( JavaType )| ArrayType( JavaType )
Die Basisdatentypen (primitive types) sind vordefiniert.
Klassen- und Schnittstellentypen sind benutzerdefiniert.
F ldt i d i li it d fi i t
166© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Feldtypen sind implizit definiert.
Beachte: Ein Programm hat unendl. viele Typen.
The primitive types are pre-defined. Class and interface types are userdefined. Field types are defined implicitly.
Note: A program has infinitely many types.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 82
Context-Dependent Analysis Type Analysis
Subtyping
Definition of subtyping relation in Java:
S is a subtype of T, S ≤ T, iff• S = T or• S and T are reference types and
I S extends or implements the type of T orI T = Object orI S = ArrayType(SE) and T = ArrayType(TE) and SE ≤ TE orI or there exists type U with S ≤ U and U ≤ T
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 83
Context-Dependent Analysis Type Analysis
Type rules
Consider the following subset of Java:
Definition der Subtypbeziehung in Java:
S ist Subtyp von T, in Zeichen S ! T, gdw.
S = T oder
S und T Referenztypen sind und
S den Typ T erweitert oder implementiertS den Typ T erweitert oder implementiert
oder T = Object
oder S = ArrayType(SE) und T=ArrayType(TE)
und SE ! TE
oder es gibt einen Typ U mit S ! U und U ! T.oder es gibt einen Typ U mit S ! U und U ! T.
Betrachte folgende Teilsprache von Java:
Stat = IfStat | Invoc | Assign
IfStat ( Exp cond, Stat then, Stat else )
Invoc ( Exp target, Ident name, Exp par )
A i ( Id t lh E h )Assign ( Ident lhs, Exp rhs )
Exp = Assign | Invoc | Arithm | Relation
| Cast | Const | Var | Null
Arithm ( Exp le, ArithmOp op, Exp re )
Relation ( Exp le, RelOp op, Exp re )p , p p, p
Cast ( JavaType t, Exp e )
Const = IntConst | LongConst
| FloatConst |...
Var ( Ident id )
N ll ()
167© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Null ()
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 84
Context-Dependent Analysis Type Analysis
Type rules (2)Type rules (similar to Java):• Let Σ |= e : S denote the property that in the environment Σ the
expression e is of type S• Let Σ |= s. the property that the statement s is type correct in the
environment Σ
where Σ captures bindings of variables to types and the subtyperelation.
In the following, we use the following variables• S,T, ... : JavaType• a,b,m: Ident• i: IntConst, l:LongConst, f:FloatConst• aop: ArithOp, rop: RelOp• e,e1,e2: Exp, s,s1,s2:Stat
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 85
Context-Dependent Analysis Type Analysis
Type rules (3)
Ausgewälte Typregeln von Java:
Bezeichne ! "#$e : S die Eigenschaft, dass in der
SUmgebung ! der Ausdruck e vom Typ S ist.
Bezeichne ! "#$s . die Eigenschaft, dass in der
Umgebung ! die Anweisung s typkorrekt ist.
Die logischen Variablen sind wie folgt sortiert:
S, T, ... : JavaType, a,b,m: Ident, i: IntConst,
l: LongConst, f: FloatConst, aop: ArithOp,
rop: RelOp, e, e1, e2: Exp, s, s1,s2 : Statp p, , , p, , ,
! "#$null : S
S ReferenceType in !
! "#$$Var(a) : T
[ a!T] %!
" $ u S " ( )
! "#$i : int ! "#$l : long ! "#$f : float
! "#$ e : long ! "#$ e : float
! "#$$e : int ! "#$$e : long
! "#$e : T
! "#$e : S, S & T in !
! "# Cast(T,e) : T
! "#$e : S , S,T % { int, long, float }
! "#$e : S S & '$in ! ! "#$e : S T & S in !
168© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
! "# Cast(T,e) : T
! "#$e : S , S & '$in !
! "# Cast(T,e) : T
! "#$e : S , T & S in !
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 86
Context-Dependent Analysis Type Analysis
Type rules (4)
! "#$$Relation(e1,rop,e2) : boolean
! "#$e1 : T, ! "#$e2 : T
! "#$$Arithm(e1,aop,e2) : T
! "#$e1 : T, ! "#$e2 : T
[ !T] !$$ ! " $ T
! "#$e1 : S , [ (S,m)!(TP,TR) ] %!$ , ! "#$e2 : TP
! "#$$Assign(a,e) : T
[ a!T] %!$$, ! "#$e : T
! "#$$Invoc(e1,m,e2) : TR
! "#$$Assign(a,e) : T
! "#$$Invoc(e1,m,e2) .
! "#$$Assign(a,e) .
! "#$$Invoc(e1,m,e2) : TR
" ( , , )
! "#$$IfStat(e,s1,s2) .
! "#$$e: boolean , ! "#$$s1. , ! "#$$s2.
Zeige: !$$"#$$$Assign( a, Assign( b, Null() ) ) :
InterfaceType(EinTyp) mit
!$= { [ a! InterfaceType(EinTyp) ],
[ b! Cl T (M i T ) ]
169© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
[ b! ClassType(MeinTyp) ],
ClassType(MeinTyp) & InterfaceType(EinTyp),
... }
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 87
Context-Dependent Analysis Type Analysis
Type rules (5)
! "#$$Relation(e1,rop,e2) : boolean
! "#$e1 : T, ! "#$e2 : T
! "#$$Arithm(e1,aop,e2) : T
! "#$e1 : T, ! "#$e2 : T
[ !T] !$$ ! " $ T
! "#$e1 : S , [ (S,m)!(TP,TR) ] %!$ , ! "#$e2 : TP
! "#$$Assign(a,e) : T
[ a!T] %!$$, ! "#$e : T
! "#$$Invoc(e1,m,e2) : TR
! "#$$Assign(a,e) : T
! "#$$Invoc(e1,m,e2) .
! "#$$Assign(a,e) .
! "#$$Invoc(e1,m,e2) : TR
" ( , , )
! "#$$IfStat(e,s1,s2) .
! "#$$e: boolean , ! "#$$s1. , ! "#$$s2.
Zeige: !$$"#$$$Assign( a, Assign( b, Null() ) ) :
InterfaceType(EinTyp) mit
!$= { [ a! InterfaceType(EinTyp) ],
[ b! Cl T (M i T ) ]
169© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
[ b! ClassType(MeinTyp) ],
ClassType(MeinTyp) & InterfaceType(EinTyp),
... }c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 88
Context-Dependent Analysis Type Analysis
Type rules (6)
Task:
! "#$$Relation(e1,rop,e2) : boolean
! "#$e1 : T, ! "#$e2 : T
! "#$$Arithm(e1,aop,e2) : T
! "#$e1 : T, ! "#$e2 : T
[ !T] !$$ ! " $ T
! "#$e1 : S , [ (S,m)!(TP,TR) ] %!$ , ! "#$e2 : TP
! "#$$Assign(a,e) : T
[ a!T] %!$$, ! "#$e : T
! "#$$Invoc(e1,m,e2) : TR
! "#$$Assign(a,e) : T
! "#$$Invoc(e1,m,e2) .
! "#$$Assign(a,e) .
! "#$$Invoc(e1,m,e2) : TR
" ( , , )
! "#$$IfStat(e,s1,s2) .
! "#$$e: boolean , ! "#$$s1. , ! "#$$s2.
Zeige: !$$"#$$$Assign( a, Assign( b, Null() ) ) :
InterfaceType(EinTyp) mit
!$= { [ a! InterfaceType(EinTyp) ],
[ b! Cl T (M i T ) ]
169© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
[ b! ClassType(MeinTyp) ],
ClassType(MeinTyp) & InterfaceType(EinTyp),
... }
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 89
Context-Dependent Analysis Type Analysis
Example: Featherweight Java
Specification of name and type analysis in Featherweight Java
A. Igarashi, B.C. Pierce, P. Wadler: Featherweight Java: A MinimalCore Calculus for Java and GJ, ACM Transactions on ProgrammingLanguages and Systems, 23(3), May 2001
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 90
Context-Dependent Analysis Type Analysis
2.3.3.2 Type safety
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 91
Context-Dependent Analysis Type Analysis
Type Safety
A type characterizes specific properties of program elements andconstructs, e.g.• a variable of type T is only for storing values of type T• an expression of type T only provides values of type T
Types can also carry semantic information.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 92
Context-Dependent Analysis Type Analysis
Terminology
• A program is type correct if it satisfies the type rules.• A type error occurs if
I a value of an incorrect type is assigned to a variableI an operation is called with an inadmissible parameter
• A program is type safe if its execution does not lead to type errors.• A programing language is strongly typed if type correctness
implies type safety. (This is a proof of a semantic programproperty. → semantic analysis)
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 93
Context-Dependent Analysis Type Analysis
Example: Guaranteed Program Properties
• A variable of type A contains only values of type A.• Evaluation of an expression of type A only yields values of type A.• If a method m is called, its existence in the target object is
ensured.
Remarks:
• Type safety can also be obtained by runtime checks and errorhandling.
• Type safety ensures the safe application of operations and is theprerequisite of further safety checks.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 94
Context-Dependent Analysis Type Analysis
Typed Languages - Example
• C is a typed language, but permits non-type safe conversions,thus C is not strongly typed.
Bemerkungen:
• Typsicherheit kann auch durch Laufzeitprüfungen
und entsprechende Fehlerbehandlung erreichtund entsprechende Fehlerbehandlung erreicht
werden.
• Typsicherheit gewährleistet sinnvolle Anwendung
von Operationen und ist Voraussetzung für weiter-
Beispiel: (Typisierte Sprachen)
gehende Sicherheitsaspekte.
• C ist eine typisierte Sprache, erlaubt aber
typunsichere Konvertierungen; demzufolge ist
C nicht stark typisiert.
h t 1 1short s1 = 1;
short s2 = 2;
short *sp = &s2;
*((long*) sp) = 89;
t( 1 1 )assert( s1 == 1 );
• Java ist eine stark typisierte Sprache, die die
Schwächen des Typsystems zur Laufzeit auffängt.yp y g
String[] strfeld = { “0“, “1“, “2“ };
Object[] objfeld = strfeld;
objfeld[0] = new Object();
// ArrayStoreException
172© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
// ArrayStoreException
strfeld[0].length();
• Java is a strongly typed language that needs some type checks atruntime.
Bemerkungen:
• Typsicherheit kann auch durch Laufzeitprüfungen
und entsprechende Fehlerbehandlung erreichtund entsprechende Fehlerbehandlung erreicht
werden.
• Typsicherheit gewährleistet sinnvolle Anwendung
von Operationen und ist Voraussetzung für weiter-
Beispiel: (Typisierte Sprachen)
gehende Sicherheitsaspekte.
• C ist eine typisierte Sprache, erlaubt aber
typunsichere Konvertierungen; demzufolge ist
C nicht stark typisiert.
h t 1 1short s1 = 1;
short s2 = 2;
short *sp = &s2;
*((long*) sp) = 89;
t( 1 1 )assert( s1 == 1 );
• Java ist eine stark typisierte Sprache, die die
Schwächen des Typsystems zur Laufzeit auffängt.yp y g
String[] strfeld = { “0“, “1“, “2“ };
Object[] objfeld = strfeld;
objfeld[0] = new Object();
// ArrayStoreException
172© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
// ArrayStoreException
strfeld[0].length();
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 95
Context-Dependent Analysis Type Analysis
2.3.3.3 Implementation aspects
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 96
Context-Dependent Analysis Type Analysis
Implementation Aspects
Techniques and algorithms for type analysis strongly depend on theconcrete language:
• For many languages, type inference can be implemented byS-attribution.
• For languages with polymorphism, type analysis can be arbitrarilycomplex or even undecidable.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 97
Context-Dependent Analysis Type Analysis
Implementation Aspects (2)
Procedure:
1. For each program construct to be typed, determine exactly onetype (type inference)
2. Check context conditions (type checking)I Type of conditions in a conditional statement or loop has to be
boolean.I Type of current parameter expressions has to be compatible with
formal parameter types.I Implicit type conversions have to be possible.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 98
Context-Dependent Analysis Type Analysis
Type Analysis - Example
Consider previously defined Java subset.
1. Data Types for AttributionFor representing type information:
JType = JavaType | NullType
NullType()
where NullType() is used to type the constant null and is asubtype of all reference types.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 99
Context-Dependent Analysis Type Analysis
Type Analysis - Example (2)
For representing environment information, we use symbol tablesof type SymTab with the following operations:
Demonstration anhand ausgewählter Produktionen
der obigen Java-Teilsprache
Beispiel: (Typanalyse)
der obigen Java Teilsprache.
1. Datentypen für die Attributierung:
Zur Repräsentation der Typinformation:
JType = JavaType | NullType
NullType ( )
NullType dient der Typisierung der Konstanten null
und ist Subtyp von allen Referenztypenund ist Subtyp von allen Referenztypen.
Zur Repräsentation der Umgebungsinformation
betrachten wir funktionale Symboltabellen vom Typ
SymTab mit den Operationen:SymTab mit den Operationen:
lookupVar: Ident x SymTab ! JType
lookupMth: Ident x Ident x SymTab ! (Signatur | undef)
Signature ( JType partyp, JType restyp )g ( yp p yp yp yp )
isCompatible: JType x JType ! boolean
max: JType x JType x SymTab ! ( Jtype | undef )
T, wenn S ! T
S wenn T ! SS, wenn T ! S
wobei max (S,T) = T, wenn S ist zu T konvertierbar
S, wenn T ist zu S konvertierbar
undef, sonst
174© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
und isCompatible(S,T) gdw. S ! T
oder S ist zu T konvertierbar
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 100
Context-Dependent Analysis Type Analysis
Type Analysis - Example (3)
where
max(S,T ) =
T if S ≤ TS if T ≤ ST if S is convertible to TS if T is convertible to Sundef else
and isCompatible(S,T ) iff S ≤ T or S is convertible to T .
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 101
Context-Dependent Analysis Type Analysis
Type Analysis - Example (4)
2. Attribution:Statements and expressions get the inherited attribute SymTab.
Expressions get the synthesized attribute JType which aredenoted by:
2. Attributierung:
Anweisungen Ausdrücke: SymTab stabAnweisungen, Ausdrücke: SymTab stab
Ausdrücke: JType typ
In der folgenden Attributierung gehen wir davon aus,
dass die Namensanalyse bereits abgeschlossen ist
IfStat
dass die Namensanalyse bereits abgeschlossen ist.
_ = boolean ?
Invoc
Exp Stat Stat
Invoc
restyp(_)_ ! undef ?
Exp Ident Exp
lookupMth(_,_,_) isCompatible(_,_) ?partyp(_)
175© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Note: For the attribution, we assume that name analysis has alreadybeen completed.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 102
Context-Dependent Analysis Type Analysis
Type Analysis - Example (5)
2. Attributierung:
Anweisungen Ausdrücke: SymTab stabAnweisungen, Ausdrücke: SymTab stab
Ausdrücke: JType typ
In der folgenden Attributierung gehen wir davon aus,
dass die Namensanalyse bereits abgeschlossen ist
IfStat
dass die Namensanalyse bereits abgeschlossen ist.
_ = boolean ?
Invoc
Exp Stat Stat
Invoc
restyp(_)_ ! undef ?
Exp Ident Exp
lookupMth(_,_,_) isCompatible(_,_) ?partyp(_)
175© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 103
Context-Dependent Analysis Type Analysis
Type Analysis - Example (6)
Assign
ExpIdent
isCompatible(_,_) ?lookupVar(_,_)
Arithm
!"# undef ?
max(_,_)
ExpExp ...
Relation
!"# undef ?
EE
boolean
max(_,_)
176© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
ExpExp ...
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 104
Context-Dependent Analysis Type Analysis
Type Analysis - Example (7)
Assign
ExpIdent
isCompatible(_,_) ?lookupVar(_,_)
Arithm
!"# undef ?
max(_,_)
ExpExp ...
Relation
!"# undef ?
EE
boolean
max(_,_)
176© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
ExpExp ...
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 105
Context-Dependent Analysis Type Analysis
Type Analysis - Example (8)
Cast !"# undef ?
max( )
ExpJavaType
max(_,_)
NullType()
Null Var
lookupVar(_,_)
Ident
Bemerkungen:Bemerkungen:
• Spezifikation und Implementierung der Typregeln
sind so unterschiedlich, dass man die Korrektheit
der Implementierung beweisen sollte.
• Für die nachfolgenden Phasen ist der bestimmte
Typ eines Ausdrucks wichtig. Er entscheidet z.B.
über die auszuführende arithmetische Operation.
Man beachte dass die Attributierung im Unter• Man beachte, dass die Attributierung im Unter-
schied zur Spezifikation deterministisch ist.
Lesen Sie zu Abschnitt 2.3.3:
177© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Appel:
• Section 5.2, 5.3, S. 116-127
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 106
Context-Dependent Analysis Type Analysis
Type Analysis - Example (9)
Remarks:
• For the subsequent compiler phases, the type of an expression isneeded; for instance, it determines the arithmetic operations to beexecuted.
• The attribution is deterministic in contrast to the specification.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 107
Context-Dependent Analysis Type Analysis
Literature
Recommended Reading:• Appel, Sections 5.2, 5.3, pp. 116 – 127
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 108
Context-Dependent Analysis Interplay of name and type analysis
2.3.4 Interplay of name and type analysis
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 109
Context-Dependent Analysis Interplay of name and type analysis
Connections between Context-Dependent Analyses
Name and type analysis are in general mutually dependent.
For instance:• For expressions of the form e.a, the type of e is required or name
analysis of a (analog for method calls).• For overload resolution of procedure or method names, the types
of the current parameters are required.
In particular, rules and algorithms for overload resolution are stronglylanguage dependent.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 110
Context-Dependent Analysis Interplay of name and type analysis
Overload Resolution in Java
Goals:
• Example of language report, i.e. basis of language implementation
• Connections between context-dependent analysis
• Learn overloading rules of a commonly used language
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 111
Context-Dependent Analysis Interplay of name and type analysis
Overload Resolution in Java (2)
Part of Java Language Report: Before, it was defined what it means that amethod declaration is accessible and applicable to a method invocation.
Beispiel: (Überladungsauflösung)
Auszug aus dem Java-Sprachbericht:
In vorangehenden Abschnitten wurde definiert, was
es heißt, dass „a method declaration is accessible and
15.12.2.2 Choose the Most Specific Method
If more than one method declaration is both accessible
applicable to a method invocation“.
and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
The precise definition is as follows. ...
A method is said to be maximally specific for a method invocation if it is applicable and accessible and there is noinvocation if it is applicable and accessible and there is noother applicable and accessible method that is more specific. If there is exactly one maximally specific method, then it is in fact the most specific method; ...
179© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 112
Context-Dependent Analysis Interplay of name and type analysis
Overload Resolution in Java (3)class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {
static void test(ColoredPoint p, Point q)
{
out.println("(ColoredPoint, Point)");
}}
static void test(Point p, ColoredPoint q)
{
out.println("(Point, ColoredPoint)");
}
static void test(ColoredPoint p,ColoredPoint q)
{
out.println("(ColoredPoint, ColoredPoint)");
}
public static void main(String[] args)public static void main(String[] args)
{
ColoredPoint cp = new ColoredPoint();
test(cp, cp); // ***** Aufrufstelle
}
}
Die dritte Deklaration ist most specific an der markiertenAufrufstelle. Wenn sie fehlen würde, wäre der Aufruf fehlerhaft und ein Übersetzungsfehler wäre die Folge
Lesen Sie zu Abschnitt 2.3.4:
Wilh l M
fehlerhaft und ein Übersetzungsfehler wäre die Folge.
180© A. Poetzsch-Heffter, TU Kaiserslautern10.05.2007
Wilhelm, Maurer: • Unterabschnitt 9.1.3 (S. 416-419)
The third declaration is most specific at the marked applied occurrence. If itwas missing, the call would be erroneous and cause a translation error.
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 113
Context-Dependent Analysis Interplay of name and type analysis
Literature
Recommended Reading:• Wilhelm, Maurer: Section 9.1.3, pp. 416 –419
c© Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 114