Names and Binding - courses.cs.vt.educourses.cs.vt.edu/~cs3304/Fall00/notes/Names/Names.pdf ·...
-
Upload
hoangxuyen -
Category
Documents
-
view
218 -
download
0
Transcript of Names and Binding - courses.cs.vt.educourses.cs.vt.edu/~cs3304/Fall00/notes/Names/Names.pdf ·...
Chapter 4: Names and Binding 3
Names (User-defined Identifiers)Design issues:
Maximum length?Are connector characters allowed?Are names case sensitive?Are special words reserved words or keywords?
LengthFORTRAN I: maximum 6COBOL: maximum 30FORTRAN 90 and ANSI C: maximum 31Ada: no limit, and all are significantC++: no limit, but implementers often impose one
Connector characters (e.g., _ )Pascal, Modula-2, and FORTRAN 77 don't allowOthers do
Chapter 4: Names and Binding 4
More Design IssuesCase sensitivity
Disadvantage: readability (names that look alike aredifferent)worse in Modula-2 because predefined names are mixedcase (e.g. WriteCard)C, C++, Java, and Modula-2 names are case sensitiveNames in most other languages are not
Special wordsA keyword is a word that is special only in certain contexts
Disadvantage: poor readabilityA reserved word is a special word that cannot be used as auser-defined name
Chapter 4: Names and Binding 5
Identifiers Have 6 Attributes
A variable is an abstraction of a memory cellA (variable) identifier has 6 attributes:
NameAddressTypeRepresentation/ValueScopeLifetime
Chapter 4: Names and Binding 6
6 Attributes (cont.)
1. Name= identifiercan be one-one, many-one, or none-onemapping to memory
2. Addresspoint to a location in memorymay vary dynamicallyTwo names for same address = aliasing
3. Typerange of values + legal operationsvariable, constant, label, pointer, program, ...
Chapter 4: Names and Binding 7
6 Attributes (cont.)
4. Representation/Valueinterpreted contents of the location
l-value (address)r-value (value)
5. ScopeRange of statements over which the variable isvisibleStatic/dynamic
6. LifetimeTime during which the variable is bound to astorage location
Chapter 4: Names and Binding 8
BindingA binding is an association, such as between an attribute andan entity, or between an operation and a symbolBinding time is the time at which a binding takes placePossible binding times:1. Language design time--e.g., bind operator symbols to
operations2. Language implementation time--e.g., bind floating point
type to a representation3. Compile time--e.g., bind a variable to a type in C or Java4. Load time--e.g., bind a FORTRAN 77 variable (or a C static
variable) to a memory cell5. Runtime--e.g., bind a nonstatic local variable to a memory
cell
Chapter 4: Names and Binding 9
Static and Dynamic BindingA binding is static if it occurs before run time andremains unchanged throughout program executionA binding is dynamic if it occurs during execution orcan change during execution of the programIn many ways, binding times for various attributesdetermine the flavor of a languageAs binding time gets earlier:
efficiency goes upsafety goes upflexibility goes down
Chapter 4: Names and Binding 10
Type Bindings
Two key issues in binding a type to anidentifier:
1. How is a type specified?2. When does the binding take place?
Chapter 4: Names and Binding 11
Static Type BindingIf static, type may be specified by either anexplicit or an implicit declarationAn explicit declaration is a programstatement used for declaring the types ofvariablesAn implicit declaration is a defaultmechanism for specifying types of variables(the first appearance of the variable in theprogram)
FORTRAN, PL/I, BASIC, and Perl provide implicitdeclarations
Advantage: writabilityDisadvantage: reliability (less trouble with Perl)
Chapter 4: Names and Binding 12
Dynamic Type BindingSpecified through an assignment statement (APL,Smalltalk, etc.)
LIST <- 2 4 6 8 LIST <- 17.3
Advantage: flexibility (generic program units)Disadvantages:
Type error detection by the compiler is difficultHigh cost (dynamic type checking andinterpretation) or low safety
Type Inferencing (ML, Miranda, and Haskell)Rather than by assignment statement, types aredetermined from the context of the reference
Chapter 4: Names and Binding 13
Storage Bindings
Allocation--getting a cell from some pool ofavailable cellsDeallocation--putting a cell back into thepoolThe lifetime of a variable is the time duringwhich it is bound to a particular memory cell
Chapter 4: Names and Binding 14
Categories of Variables by Lifetimes
StaticStack-dynamicExplicit heap-dynamicImplicit heap-dynamic
Chapter 4: Names and Binding 15
Static Lifetime
Bound to memory cells before executionbegins and remains bound to the samememory cell(s) throughout executionExamples:
All FORTRAN 77 variablesC and C++ static variables
Advantages:Efficiency (direct addressing)History-sensitive subprogram support
Disadvantage:Lack of flexibility (no recursion)
Chapter 4: Names and Binding 16
Stack-Dynamic LifetimeStorage bindings are created for variables whentheir declaration statements are elaboratedIf scalar, all attributes except address are staticallyboundExamples:
Local variables in Pascal and C subprogramsLocals in C++ methods
Advantages:Allows recursionConserves storage
Disadvantages:Overhead of allocation and deallocationSubprograms cannot be history sensitiveInefficient references (indirect addressing)
Chapter 4: Names and Binding 17
Explicit Heap-Dynamic LifetimeAllocated and deallocated by explicit directives,specified by the programmer, which take effectduring executionReferenced only through pointers or referencesExamples:
Dynamic objects in C++ (via new and delete)All objects in Java
Advantage:Provides for dynamic storage managementExplicit control
Disadvantage:Potential for human error
Chapter 4: Names and Binding 18
Implicit Heap-Dynamic Lifetime
Allocation and deallocation is implicit, basedon language semantics (e.g., caused byassignment statements)Ex.: all variables in APLAdvantage:
FlexibilityDisadvantages:
Inefficient, because often all attributes aredynamicMay have delay in error detection
Chapter 4: Names and Binding 19
Type Checking
Generalize the concept of operands and operatorsto include subprograms and assignmentsType checking is the activity of ensuring that theoperands of an operator are of compatible typesA compatible type is one that is either:
Legal for the operator, orAllowed under language rules to be implicitlyconverted to a legal type by compiler-generatedcodeThis automatic conversion is called a coercion
Chapter 4: Names and Binding 20
Type Errors
A type error is the application of an operator to anoperand of an inappropriate typeIf all type bindings are static, nearly all typechecking can be staticIf type bindings are dynamic, type checking must bedynamicA programming language is strongly typed if typeerrors are always detectedIn practice, languages fall on a continuum betweenstrongly typed and untyped
Chapter 4: Names and Binding 21
Strong TypingAdvantage of strong typing: allows the detection ofthe misuses of variables that result in type errorsLanguages:
FORTRAN 77 is not: parameters, EQUIVALENCEPascal is not: variant recordsModula-2 is not: variant records, WORD typeC and C++ are not: parameter type checking can beavoided; unions are not type checkedAda is, almost (UNCHECKED CONVERSION is loophole)(Java is similar)
Coercion rules strongly affect strong typing—theycan weaken it considerably (C++ versus Ada)
Chapter 4: Names and Binding 22
Type Compatibility: Name Equiv.Type compatibility by name (“name equivalence”)means the two variables have compatible types ifthey are in either the same declaration or indeclarations that use the same type nameEasy to implement but highly restrictive:
Subranges of integer types are not compatible with integertypesFormal parameters must be the same type as theircorresponding actual parameters (Pascal)
Predefined or user-supplied coercions can easerestrictions, but also create more potential forerror
Chapter 4: Names and Binding 23
Type Compatibility: Structural Equiv.
Type compatibility by structure (“structuralequivalence”) means that two variableshave compatible types if their types haveidentical structuresMore flexible, but harder to implementMakes it more difficult to use a typechecking to detect certain types of errors(e.g., preventing inconsistent unit usage inAda)
Chapter 4: Names and Binding 24
Scope
The scope of a variable is the range ofstatements over which it is visibleThe nonlocal variables of a program unit arethose that are visible but not declared thereThe scope rules of a language determinehow references to names are associatedwith variablesScope and lifetime are sometimes closelyrelated, but are different concepts!!
Consider a static variable in a C or C++ function
Chapter 4: Names and Binding 25
Static (Lexical) Scope
Based on program textTo connect a name reference to a variable,you (or the compiler) must find thedeclarationSearch process: search declarations, firstlocally, then in increasingly larger enclosingscopes, until one is found for the given nameEnclosing static scopes (to a specific scope)are called its static ancestors; the neareststatic ancestor is called a static parent
Chapter 4: Names and Binding 26
Variable Hiding
Variables can be hidden from a unit byhaving a “closer” variable with the samename (closer == more immediate enclosingscope)C++ and Ada allow access to these “hidden”variables (using fully qualified names)Blocks are a method of creating staticscopes inside program units—from ALGOL 60
Chapter 4: Names and Binding 27
Dynamic Scope
Based on calling sequences of programunits, not their textual layout (temporalversus spatial)References to variables are connected todeclarations by searching back through thechain of subprogram calls that forcedexecution to this pointEffectively, searching “downward” throughthe call stack looking for an activationrecord possessing the declaration
Chapter 4: Names and Binding 28
Example program foo; var x: integer;
procedure f; begin print(x); end f; procedure g; var x: integer; begin x := 2; f; end g;
begin x := 1; g;
end foo.
What value isprinted?
Evaluate with staticscoping: x = 1
Evaluate withdynamic scoping: x = 2
Chapter 4: Names and Binding 29
Static vs. Dynamic Scoping
Advantages of static scoping:ReadabilityLocality of reasoningLess run-time overhead
Disadvantages:Some loss of flexibility
Advantages of dynamic scoping:Some extra convenience
Disadvantages:Loss of readabilityUnpredictable behavior (no locality of reasoning)More run-time overhead
Chapter 4: Names and Binding 30
Referencing EnvironmentsThe referencing environment of a statementis the collection of all names that are visiblein the statementIn a static scoped language, that is the localvariables plus all of the visible variables inall of the enclosing scopes (see ex., p. 184)A subprogram is active if its execution hasbegun but has not yet terminatedIn a dynamic-scoped language, thereferencing environment is the localvariables plus all visible variables in allactive subprograms (see ex., p. 185)
Chapter 4: Names and Binding 31
Variable Initialization
The binding of a variable to a value at thetime it is bound to storage is calledinitializationOften done on the declaration statementAn Ada example:
sum : Float := 0.0;
Can be static or dynamic (depending onwhen storage is bound)Typically once for static variables, once perallocation for non-static variables