terms | identifier syntax | variables | binding | type binding | storage binding | type checking | strong typing | scope

CMPS 350 Lecture Notes - Names, Bindings, Type & Scope

Identifier Syntax

o how to write unmaintainable code (what not to do)

o compiler syntax (see Java identifiers) vs. coding conventions (see Java naming conventions)

o the syntax for Ada identifiers as a regular expression:

     [a-zA-Z]([a-zA-Z0-9_][a-zA-Z0-9])*{_[a-zA-Z0-9]}
meaning: An identifier must start with a letter and be followed by zero or more letters, digits or underscores. An underscore cannot be the final symbol. An underscore cannot be followed by another underscore.

Design issues for names in a language:

LENGTH : too short means poor readability: FORTRAN I: maximum 6; COBOL: maximum 30; FORTRAN 90 and ANSI C: maximum 31; Ada and Java: no limit and all are significant; C++: no limit, but implementers often impose one

CONNECTORS ( underscore and dash ) : most modern languages OK within limits but Pascal, Modula-2, and FORTRAN 77 disallow

CASE SENSITIVITY : Disadvantage is readability ( baby, Baby and BABY are all different names ) and writeability ( was that LetMeIn , letMeIn or letmeIn???? ) C++/Java predefined names are mixed case (camel notation) - IndexOutOfBoundsException; C is case-sensitive b/c Unix is; C++/Java follow C; Ada, however, is case-insensitive

SPECIAL WORDS : improve readability; used to delimit or separate statement clauses; e.g 'begin' and 'end'

Variables

A variable is an abstraction of a memory cell and is characterized by five attributes:

  1. Name - not all variables have them (examples : dynamic memory variables in the heap are referenced by pointers only ) Two variables using the same name must have different addresses (e.g. variables in different program blocks or scopes) but two variables with different names may point to the same address (aliasing).

  2. Type - determines the range of values of variables and the set of operations that are defined for values of that type; in the case of floating point, type also determines the precision

  3. Address - the memory address with which the variable is associated (the lvalue) A variable may have different addresses at different times during execution (e.g. local variables inside functions) A variable of the same name may have different addresses in the same scope; e.g. function overloading in C++ (see name mangling)

  4. Lifetime - The type of address binding determines the lifetime of a variable (the time during which it is bound to a particular memory cell); storage type determines lifetime ; scope and lifetime are related but not synonymous; - C/C++ linkage - ( static variables in C/C++ have limited scope but have program lifetime; i.e. the second time you call a function and access a static variable declared in that function you are not creating a new variable location )

  5. Value - the contents of the location by which the variable is associated.

  6. Scope - The range of statements over which a variable is visible; e.g. visibility; May be static or dynamic

Binding

Binding is the association of one thing with another thing ; e.g., a variable with its attributes or an operator and a symbol.

The binding time is the time at which a binding takes place.

Possible Binding Times:

o Language design time -- bind operator symbols to operations; e.g. '+' is bound to the addition operation

o Language implementation time-- bind floating point type to a representation (see IEEE 754 standard)

o Compile time - ex. bind a variable to a type in C or Java by the compiler - this is static binding

o Link time -- resolve external symbol references; ex. bind a variable to an address across multiple compilation units ( such as .o files ) ; external linkage (see ld manpage) by the linker is static binding ; Example file1.c and file2.c and

o Load time -- bind a FORTRAN 77 variable to a memory cell; bind shared objects libraries to an executable before runtime
(see loader manpage) - this is also static binding

o Runtime -- bind a nonstatic local variable to a memory cell ; bind a method to a class object via polymorphism in C++ - this is dynamic binding

A binding is static if it first occurs before run time and remains unchanged throughout program execution (can be performed by compiler, linker or loader).

A binding is dynamic if it first occurs during execution or can change during execution of the program

Type Binding

- the process of binding a variable with a type. Q: how is a type specified and when does the binding take place?

If static, the type may be specified by either an explicit or an implicit declaration

An explicit declaration is a program statement used for declaring the types of variables; advantage: improves reliability

An implicit declaration is a default mechanism for specifying types of variables (the first appearance of the variable in the program); Advantage: writability; Disadvantage: reduces reliability

FORTRAN, PL/I, BASIC, and Perl provide implicit declarations; (see Perl example)

Type Inferencing : Types are determined by the compiler from the context of the reference . Used by functional languages: ML, Miranda, and Haskell.

Dynamic Type Binding is typing that occurs at runtime (JavaScript and PHP)

+ A language that uses dynamic typing is not "typeless"

+ Dynamic typing is not the same as "weak typing"

+ A language is dynamically typed if type binding occurs at runtime by means of an assignment and not a type declaration

+ A dynamically-typed language that allows type to change through coercion is a weakly typed language; e.g., JavaScript

     
    list = [2, 4.33, 6, 8];
    list = 17.3;
    list = "hello";
run JavaScript example

Advantage: flexibility (generic program units) Disadvantages: High cost (dynamic type checking and interpretation) Type error detection by the compiler is difficult

Duck Typing - "If it walks like a duck, quacks like a duck, looks like a duck, it is a duck." Duck typing is the most widely used form of dynamic typing. Duck typing is used by Perl, Javascript, Python, and others..

Storage Binding

Storage binding of a variable is the binding of a variable name to a memory address

The type of storage binding determines the lifetime of a variable; the lifetime of a variable is the time during which it is bound to a particular memory cell

Storage binding begins with memory allocation - getting a cell from some pool of available cells

Storage binding ends with deallocation - putting a cell back into the pool

Categories of Variables by Storage Binding

(#1) STATIC -- bound to memory before execution begins and remains bound to the same memory cell throughout execution, e.g., all FORTRAN 77 variables, C static and extern variables and C++ static members in a C++ class

Advantages: efficiency (direct addressing), history-sensitive subprogram support Disadvantage: lack of flexibility (no recursion)

(#2) STACK-DYNAMIC --Storage bindings are created for variables when their declaration statements are executed at runtime. If scalar, all attributes except address are statically bound Ex: local variables in C functions and C++/Java methods return values, arguments pass by value

Advantage: allows recursion; conserves storage

Disadvantages: Overhead of allocation and deallocation; Subprograms cannot be history sensitive; Inefficient references (indirect addressing)

(#3) EXPLICIT HEAP-DYNAMIC -- Allocated and deallocated explicitly by the programmer, occurs during execution

Referenced only through pointers or references, e.g. dynamic objects in C++ (via new and delete), all objects in Java

Advantage: provides for dynamic storage management Disadvantage: inefficient and unreliable

(#4) IMPLICIT HEAP-DYNAMIC --Allocation and deallocation caused by assignment statements

all variables in APL; all strings and arrays in Perl and JavaScript; all objects in Java; Advantage: flexibility Disadvantages -- Inefficient, because all attributes are dynamic and loss of error detection; (see Perl example)

* "Explicit stack dynamic" does not make sense

Type Checking

ensuring that the operands of an operator are of compatible types

ensuring that the arguments in a subprogram call are compatible with the parameters of the subprogram definition

ensuring that the lvalue and the rvalue of an assignment statement are compatible

A compatible type is one that is either legal for the operator, or is allowed under language rules to be implicitly converted, by compiler- generated code, to a legal type

automatic conversion is called a coercion (see C example)

C++ example of both implicit (automatic) and explicit type casting (bear example)

* A type error is the application of an operator to an operand of an inappropriate type; whether 'const' qualifier (or similar keyword) is enforced by the compiler is an issue ; C++ enforces const ; C does not

If all type bindings are static, nearly all type checking can be static

If type bindings are dynamic, type checking must be dynamic

Strong Typing

A programming language is strongly typed if type errors are always detected ( few or no implicit coercions )

most strongly typed languages are static typed but not always - ML is strongly typed but also employs dynamic typing

Advantage of strong typing: improves reliability - detects of the misuses of variables that result in type errors

Coercion weakens strong typing; Ada is more strongly typed than C - there is no implicit coercion: int i, int j; float x = i / j;

C/C++ is not strongly typed (parameter type checking can be avoided or completely ignored ( see use of void * ); ; unions are not type checked

Ada is the most strongly typed language ; C# is almost fully strongly typed ; Java is more strongly typed than C/C++ ( Java has half the assignment coercions of C++ but its strong typing is still far less than Ada ) ; no surprise- C/C++ is at the bottom

Name Type Compatibility : two variables have compatible types if they are in either the same declaration or in declarations that use the same type name

Easy to implement but highly restrictive: Subranges of integer types are not compatible with integer types Formal parameters must be the same type as their corresponding actual parameters (Pascal)

Structure Type Compatibility : two variables have compatible types if their types have identical structures; flexible, but harder to implement ; Ada supports assignment of all like structures

Design issues: Are two record types compatible if they are structurally the same but use different field names?

Are two array types compatible if they are the same except that the subscripts are different? (e.g. [1..10] and [0..9]) - yes in Ada

In C, enumeration types are compatible if spelling differs but structure is the same (see C example)

With structural type compatibility, you cannot differentiate between types of the same structure (e.g. different units of speed, both float)

Scope

The scope of a variable is the range of statements over which it is visible

Nonlocal variables are those that are visible but not declared within the unit (function, program, block, etc.)

The scope rules of a language determine how references to names are associated with variables

Scope rules are either dynamically or statically determined

Static (Lexical) Scope

Based on program text ; Ada uses static scoping rules and supports nested subroutines; (see Ada example)

The binding of a name reference to a variable address is done by compiler, linker or loader before runtime based on scoping rules; in C/C++ the compiler handles compilation unit scope (internal linkage), the linker handles program global scope (external linkage), and the loader handles references to external system libraries.

Search process: search declarations, first locally, then in increasingly larger enclosing scopes, until one is found for the given name Example file1.c and file2.c and

Enclosing static scopes (to a specific scope) are called its static ancestors; the nearest static ancestor is called a static parent

Variables can be hidden from a unit by having a "closer" variable with the same name

In addition to compilation unit scope and global scope, C++ and Ada have package (Ada) and class (C++) scope: In Ada: 'unit.name'; In C++: 'class_name::name' (see C++ example)

Blocks are a common method of creating static scopes inside program units--(see C++ example)

C/C++/Java are static scoped languages; nested functions are supported in GNU C but not ANSI C (see C example)

Evaluation of Static Scoping:

Suppose the spec is changed so that D must now access some data in B

Solutions:

Put D in B (but then C can no longer call it and D cannot access A's variables)

Move the data from B that D needs to MAIN (but then all procedures can access them)

Same problem for procedure access

Overall: static scoping often encourages or forces the use of global variables

Dynamic Scope

Based on calling sequences of program units, not their textual layout (temporal versus spatial)

Assume MAIN calls A and B, A calls C and D, D calls E, B calls E Runtime stack:

                            E
             C         D    D     D                      E 
        A    A    A    A    A     A     A          B     B     B 
   MAIN MAIN MAIN MAIN MAIN MAIN  MAIN  MAIN MAIN  MAIN  MAIN  MAIN
References to variables are connected to declarations by searching back through the chain of subprogram calls that forced execution to this point based on program text (see Ada example)

Advantage: convenience Disadvantage: poor readability

Referencing Environments

The referencing environment of a statement is the collection of all names that are visible in the statement

In a static-scoped language, it is the local variables plus all of the visible variables in all of the enclosing scopes

A subprogram is active if its execution has begun but has not yet terminated

In a dynamic-scoped language, the referencing environment is the local variables plus all visible variables in all active subprograms

Named Constants

a named constant is not a literal (a literal has no memory associated with it); a named constant is a variable bound to a value once when it is bound to storage; improves readability and modifiability; used to parameterize programs; i.e., the ability to refer to a name such as interestRate rather than hard-coding in the number 4.347 each time you need to use it

the binding of values to named constants can be either static (called manifest constants) or dynamic

the binding of a variable to a value at the time it is bound to storage is called initialization; binding can be static or dynamic: the value of a dynamic named constant is set once at runtime. Ex. where width is not known at compile time

 const static int result = 2 * width + 1;   
C# has static named variables ( keyword const ) and dynamic named constants ( keyword readonly )

Terminology

The terms name and identifier are generally interchangeable. An identifier references a user-defined entity -- a variable, a function, a label, a constant, etc. -- or a predefined entity that comes with the language -- environment variables, system calls, library functions, etc. The keywords and reserved words of a language, which name the statement constructs and basic data types, cannot be used as an identifier name.

The terms keyword and reserved word are interchangeable in most languages. In C/C++/Java, the terms 'reserved word' and 'keyword' mean the same thing. In Fortran, a keyword is a word that is special only in certain contexts. E.g.,

   Real VarName  (type followed by name makes Real is keyword)
Whereas, in Fortran and Ada a reserved word (while, do, for, break) is a special word that cannot be used as a user-defined name.

All identifiers are associated with a type. For example, a variable identifier may be a single-entity scalar type (int, float, double), a derived type (arrays, structures, unions), an object type, an enumerated type, a function type, etc. A function type has variable types associated with the return value and parameter(s). The type of the identifier determines its scope, lifetime, type checking, initialization, and type compatibility. For example, a C function type has global scope and external linkage, has a lifetime of that of the executable, and has strict type checking that is controlled by function prototypes at compilation time.

Primitive Data Types refer to the scalar and derived data types that come with the language. The implementation of those types is compiler specific. ANSI C primitive data types include int, float, double, pointer, unsigned int, array, etc. A type is also categorized as an integral or a non-integral. Integral types are scalars that have discrete values (int, unsigned int, char, enum, bool) Perl includes all the usual primitives as C and also a string as a scalar type and an associative array as a primitive data type. A language will generally include, by default, the capability to display the values of all primitive scalar datatypes. C's printf is one of the more powerful tools for displaying the value of primitive types.

A literal is the source code representation of the value of a primitive data type. A literal has a type, but does not have a memory address. This C++ code provides examples of literals:

  
    void test(char * str){
        str[0] = 'a';   // seg fault core dump
    } 
    int x = 5;  // '5' is a literal for an int data type with value 5
    test("hello"); // 'hello' is a string literal
    bool flag = false; // 'false' is a boolean literal in C++ 

Camel Notation refers to the use of mixed case in an identifier name; e.g. OutofBoundsError. Camel notation can improve readability if used consistently (getName, getPhone, getAddress, etc.) and if the notation is intuitive and easy to remember. Otherwise, camel notation degrades readability and writeability.

The term lvalue refers to the "left-hand" side of an assignment statement. The term rvalue" refers to the "right-hand" side of an assignment statement. In an extension of the original definition, rvalues and lvalues do not need to be part of an assignment statement, but reflect whether or not the expression or variable is bound to a memory address or to a value. An rvalue is bound to a value and an lvalue is is bound to a memory address. Thus, a statement that expects an lvalue requires a variable that is associated with a memory address. An rvalue does not require storage space. An rvalue is either a literal or the value of an expression. The error "unmodifiable lvalue" means that the the statement needs a variable bound to a memory address but instead has encountered a variable that either is not an lvalue or is an lvalue that cannot be modified. For example, this code will not compile

   const int y = 5; 
   int x = 5;
   if ( x > 3)    // x is an lvalue and '3' is an rvalue 
      x++;        
   y = y + 1;     // y is an unmodifiable lvalue  
 

Aliases are two or more variable names that access the same memory location. Aliases are created via pointers, reference variables, C and C++ unions. Aliases are harmful to readability (readers must remember all of them), maintainability and security.

The runtime stack (or just stack) is a portion of memory allocated to a process during execution that is used strictly for everything necessary to implement a procedure call (the code return address, the value of arguments passed in, and the value of local variables).