50
Compilation 2007 Compilation 2007 Scopes and Environments Scopes and Environments Michael I. Schwartzbach BRICS, University of Aarhus

Compilation 2007 Scopes and Environments Michael I. Schwartzbach BRICS, University of Aarhus

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

Compilation 2007Compilation 2007

Scopes and EnvironmentsScopes and Environments

Michael I. Schwartzbach

BRICS, University of Aarhus

2Scopes and Environments

Which Declaration Defines a Name?Which Declaration Defines a Name?

class A {

public int x;

public boolean y;

public void m(int y) {

x = y+1;

}

}

class B extends A {

String z;

public void m(boolean b) {

y = b;

{ int y = 42;

x = y;

(new B()).m(y);

}

{ String y = "foo";

y = y + z;

}

}

}

3Scopes and Environments

Bindings from Names to DeclarationsBindings from Names to Declarations

class A {

public int x;

public boolean y;

public void m(int y) {

x = y+1;

}

}

class B extends A {

String z;

public void m(boolean b) {

y = b;

{ int y = 42;

x = y;

(new B()).m(y);

}

{ String y = "foo";

y = y + z;

}

}

}this way to java.lang.String

4Scopes and Environments

Environments and ScopesEnvironments and Scopes

An environment is a map from names to declarations

A scope is the area of a program where a given declaration has effect

Scopes may be illustrated by coloring the areas of a program which use the same environment

5Scopes and Environments

An EnvironmentAn Environment

class A {

public int x;

public boolean y;

public void m(int y) {

x = y+1;

}

}

class B extends A {

String z;

public void m(boolean b) {

y = b;

{ int y = 42;

x = y;

(new B()).m(y);

}

{ String y = "foo";

y = y + z;

}

}

}

int x

int y

String z

boolean b

class A

class B

void m(boolean)

void m(int)

class String

6Scopes and Environments

class A {

public int x;

public boolean y;

public void m(int y) {

x = y+1;

}

}

class B extends A {

String z;

public void m(boolean b) {

y = b;

{ int y = 42;

x = y;

(new B()).m(y);

}

{ String y = "foo";

y = y + z;

}

}

}

A ScopeA Scope

7Scopes and Environments

class A {

public int x;

public boolean y;

public void m(int y) {

x = y+1;

}

}

class B extends A {

String z;

public void m(boolean b) {

y = b;

{ int y = 42;

x = y;

(new B()).m(y);

}

{ String y = "foo";

y = y + z;

}

}

}

A Scope Extends to SubclassesA Scope Extends to Subclasses

8Scopes and Environments

Static Nested ScopesStatic Nested Scopes

A

B

G

C

H

D

I

E

F

J

A

B

C

D

E

F

I

J

9Scopes and Environments

Most Closely NestedMost Closely Nested

A1

B

G

C

H

D

I

A2

F

A3

A3

B

C

D

F

I

10Scopes and Environments

Stack-Like BehaviorStack-Like Behavior

A

B

G

C

H

D

I

E

F

J

ABCD

ABCD | EF

ABCD | EF | G

ABCD | EF | G | H

ABCD | EF | G

ABCD | EF

ABCD | EF | IJ

ABCD | EF

ABCD

11Scopes and Environments

Implementing Static Nested ScopesImplementing Static Nested Scopes

An environment for each scope• attached to the appropriate AST node• implemented as a hash map

A search path out through the nested scopes• linking the appropriate AST nodes together

12Scopes and Environments

When Defining a NameWhen Defining a Name

If the name is already in the local environment:

identifier already declared Otherwise, insert the name in the environment

13Scopes and Environments

When Looking Up a NameWhen Looking Up a Name

Look for the name in the local environment If it is found, we are done Otherwise, repeat from the next environment on

the search path If there are no more environments:

identifier not declared

14Scopes and Environments

Distinct NamespacesDistinct Namespaces

Different kinds of identifiers may reside in separate environments:

int x = 0;

int x(int x) { return x+1; }

x = x(x);

This requires that a syntactic distinction of the different kinds is possible

15Scopes and Environments

Dynamic ScopeDynamic Scope

Look up identifiers on the call stack:

int x = 0;

int f() { return x; }

int g() { int x = 1; return f(); }

Static scope: g()==0 Dynamic scope: g()==1 Used in LaTeX, Perl, Lisp, ...

16Scopes and Environments

Uses and Definitions in JavaUses and Definitions in Java

Every name occurring in a Java program must be linked to a declaration of either:• a type (class or interface)• a local variable• a formal argument • a static or non-static field• a static or non-static method

Names in Java are of the form A.B.C.D

17Scopes and Environments

Environments and Scopes in JavaEnvironments and Scopes in Java

Quite complicated! The analysis requires several phases:

1. building a global class environment

2. resolving uses of types

3. checking well-formedness of the class hierarchy

4. disambiguating uses of names

5. resolving uses of locals, formals, and static fields

6. type checking

7. resolving uses of methods and non-static fields

18Scopes and Environments

The Class EnvironmentThe Class Environment

A collection of (fully qualified) class and interface names (types)

The class environment must include the standard libraries

19Scopes and Environments

Resolving Type UsesResolving Type Uses

Fully qualified names are easy Unqualified names are handled by these rules:

1. try the enclosing class or interface

2. try any single-type-import (A.B.C.D)

3. try the same package

4. try any import-on-demand package (A.B.C.*)

Each of the above must not produce ambiguities This defines a type environment for each class

and interface

20Scopes and Environments

Prefix RequirementPrefix Requirement

For any type T in such a type environment:

if T = A1.A2.A3....An (n ≥3) then

every A1.A2....Aj (2≤j<n)

must not exist in the class environment

21Scopes and Environments

Well-Formed HierarchiesWell-Formed Hierarchies

A class environment must describe a well-formed class hierarchy

Well-formedness consists of a (long) list of surprisingly complex constraints...

22Scopes and Environments

Some Simple ConstraintsSome Simple Constraints

1) A type mentioned in extends must be a class

2) A type mentioned in implements must be an interface

3) An interface must not be mentioned twice in implements

4) A class must not extend a final class

5) Two constructors in a class must not have the same argument types

23Scopes and Environments

Descriptions of classes:

S I1 I2 ... Ik

C

C is a class that extends S and implements I j

SUPER(C) = {S, I1, I2, ..., Ik}

By default, S = Object

A Class Hierarchy Model (1/4)A Class Hierarchy Model (1/4)

24Scopes and Environments

A Class Hierarchy Model (2/4)A Class Hierarchy Model (2/4)

Descriptions of interfaces:

I1 I2 ... Ik

I

I is an interface that extends Ij

SUPER(I) = {I1, I2, ..., Ik}

Methods are public abstract, fields are static

25Scopes and Environments

A Class Hierarchy Model (3/4)A Class Hierarchy Model (3/4)

S <T means that S is a strict subtype of T:

T SUPER(S) T': S<T' T'<T

S T means S < T S = T T = Object

DECLARE(T) is the set of methods and fields that are declared in the class or interface T

26Scopes and Environments

A Class Hierarchy Model (4/4)A Class Hierarchy Model (4/4)

For a class or interface T we know:• mods(T): the set of modifiers

For a method mDECLARE(T) we know:• mods(m): the set of modifiers

• name(m): the name

• sig(m): the signature (includes the name)

• type(m): the return type

• except(m) : the set of checked exceptions

• decl(m): the declaring class or interface (T)

For a field fDECLARE(T) we know:• name(f): the name

• type(f): the type

• decl(f): the declaring class or interface (T)

{public,abstract} for interfaces

27Scopes and Environments

Derived SetsDerived Sets

Given a class hierarchy, we derive some sets:

• INHERIT(T):

the set of methods and fields that T inherits• CONTAIN(T) DECLARE(T) INHERIT(T)• REPLACE:

the set of pairs (m,m') where m replaces m'

REPLACing is often called hiding for fields and static methods, and overriding otherwise

28Scopes and Environments

Inductive Definitions (1/4)Inductive Definitions (1/4)

The sets INHERIT and REPLACE are populated through the following rules:

mDECLARE(T) SSUPER(T)

m'CONTAIN(S) sig(m)=sig(m')

(m,m')REPLACE

29Scopes and Environments

Inductive Definitions (2/4)Inductive Definitions (2/4)

SSUPER(T) mCONTAIN(S)

nodecl(T,m) abstractmods(m)

mINHERIT(T)

SSUPER(T) mCONTAIN(S)

nodecl(T,m) abstractmods(m) allabs(T,m)

mINHERIT(T)

30Scopes and Environments

Inductive Definitions (3/4)Inductive Definitions (3/4)

SSUPER(T) fCONTAIN(S)

f' DECLARE(T): name(f')name(f)

fINHERIT(T)

SSUPER(T) mCONTAIN(S)

S'SUPER(T) m'CONTAIN(S')

nodecl(T,m) sig(m)=sig(m')

abstractmods(m) abstractmods(m')

(m,m')REPLACE

31Scopes and Environments

Inductive Definitions (4/4)Inductive Definitions (4/4)

We have used the abbreviations:

nodecl(T,m) m'DECLARE(T): sig(m)sig(m')

allabs(T,m) SSUPER(T):

m'CONTAIN(S):

sig(m)=sig(m') abstractmods(m')

32Scopes and Environments

Populating InterfacesPopulating Interfaces

Interfaces without superinterfaces implicitly include abstract versions of all public methods

in the class Object

33Scopes and Environments

Well-Formedness Constraints (1/3)Well-Formedness Constraints (1/3)

1) T: T < T

2) m,m'DECLARE(T): m m' sig(m)sig(m')

3) m,m'CONTAIN(T):

sig(m)sig(m') type(m)=type(m')

4) mCONTAIN(T):

abstractmods(m) abstractmods(T)

34Scopes and Environments

Well-Formedness Constraints (2/3)Well-Formedness Constraints (2/3)

5) (m,m')REPLACE:

staticmods(m) staticmods(m')

6) (m,m')REPLACE: type(m)=type(m')

7) (m,m')REPLACE:

publicmods(m') publicmods(m)

35Scopes and Environments

Well-Formedness Constraints (3/3)Well-Formedness Constraints (3/3)

8) (m,m')REPLACE:

eexcept(m): e'except(m'): ee'

9) (m,m')REPLACE: finalmods(m')

10) f,f' DECLARE(T):

f f' name(f) name(f')

11) S,S' SUPER(T):

fCONTAIN(S), f'CONTAIN(S'):

name(f) name(f') decl(f) decl(f')

Special Joos restriction, Java is more complicated

36Scopes and Environments

Field and Method EnvironmentField and Method Environment

The methods that are available in an object of type T are exactly those in CONTAIN(T)

The fields that are available in an object of type T are exactly those in CONTAIN(T)

37Scopes and Environments

Block EnvironmentsBlock Environments

Blocks and formals use static nested scope rules Except that overlapping scopes are not allowed:

{ int x;

x = 42;

{ int y

y = 12;

}

{ boolean y;

y = true;

}

{ String x;

x = "foo";

}

}

identifier already declared

38Scopes and Environments

Arbitrary Local DeclarationsArbitrary Local Declarations

Can be understood through a transformation:

int x;x = 42;int y = x+1;y = x+12;int z;z = x+y;

{ int x; x = 42; { int y = x+1; y = x+12; { int z; z = x+y; } }}

39Scopes and Environments

Static Scope RulesStatic Scope Rules

Java has this search path of environments:

1. the local block environments (including formals)

2. the field and method environments of the enclosing class

3. the type environment of the enclosing class

This defines a function lookupName(...)

40Scopes and Environments

Resolving The Lvalue AResolving The Lvalue A

Check that lookupName(A) returns one of:• a local• a static field• a non-static field

41Scopes and Environments

Resolving The Method Invocation A(...)Resolving The Method Invocation A(...)

Check that the method environment of the enclosing class declares A as one of:• a static method• a non-static method

42Scopes and Environments

Ambiguous NamesAmbiguous Names

Names occurring as:• lvalues: A.B.C.D• method invocations: A.B.C.D(...)

are syntactically ambiguous

We must now resolve their meanings...

43Scopes and Environments

Disambiguating ADisambiguating A11.A.A22....A....Ann

If lookupName(A1) is a local, then A2,...,An are all non-static fields

If lookupName(A1) is a field, then A2,...,An are all non-static fields

If lookupName(A1) is an unqualified type, then A2 is a static field and A3,...,An are all non-static fields

If lookupName(A1....Ak) is a qualified type and 1<k<n then Ak+1 is a static field and Ak+2,...,An are all non-static fields

44Scopes and Environments

Disambiguating ADisambiguating A11.A.A22....A....Ann(...) (1/2)(...) (1/2)

If lookupName(A1) is a local, then A2,...,An-1 are all non-static fields and An is a non-static method

If lookupName(A1) is a field, then A2,...,An-1 are all non-static fields and An is a non-static method

If lookupName(A1) is an unqualified type and n=2, then A2 is a static method

If lookupName(A1) is an unqualified type and n>2, then A2 is a static field, A3,...,An-1 are non-static fields and An is a non-static method

45Scopes and Environments

Disambiguating ADisambiguating A11.A.A22....A....Ann(...) (2/2)(...) (2/2)

If lookupName(A1...Ak) is a qualified type and 1<k=n-1, then An is a static method

If lookupName(A1...Ak) is a qualified type and 1<k<n-1, then Ak+1 is a static field, Ak+1,...,An-1 are non-static fields, and An is a non-static method

46Scopes and Environments

Resolving Local and Static Field UsesResolving Local and Static Field Uses

Every use of a local variable or a static field is now linked to its declaration

Other uses of fields and methods look like:• exp.foo• exp.foo(...)

which can only be resolved using knowledge about the type of exp

47Scopes and Environments

Type CheckingType Checking

Type checking will for every expression determine a static type (class, interface, or primitive type)

The run-time type of the result will be a subclass of the static type

We will later see how to do this...

48Scopes and Environments

Resolving Field and Method UsesResolving Field and Method Uses

For a non-static field:

get the declaration from the field environment of the static type of its object

For a method:

get the declaration from the field and method environment of the static type of its object, using the static types of the arguments to resolve overloading

49Scopes and Environments

Distinct Namespaces (1/2)Distinct Namespaces (1/2)

Fields and methods reside in different namespaces

public class Foo {

public static int x;

public static int x(int x) { return x+1; }

public static void main(String[] args) {

x = x(x);

}

}

50Scopes and Environments

Distinct Namespaces (2/2)Distinct Namespaces (2/2)

Locals and types reside in distinct namespaces

(provided they syntactically distinguishable)

public class Foo {

public void m(int a) {

String String = "bar";

String = String;

String s = "baz";

String = s;

}

}