Presidency University, Bengaluru. Programming Language Design
|
|
- Bridget Ball
- 6 years ago
- Views:
Transcription
1 Programming Language Design
2 Goal * To design the Programming Language. * To Implement the compiler (start now and continue learning till end of next semester) * Not to worry much about Cousins of Compiler Preprocessors Assemblers Linkers Loaders 2
3 Developing Programming Language Similar to developing any software. Should have knowledge Data used and Environment where program runs. Follows all phases of Software Development Life Cycle (SDLC) SDLC (PL-DLC) Phase Requirements analysis Design Implementation Output Programming Language Requirements Specification (PLRS) Design Document, Design rules Grammar / Syntax Semantic Back end Writing compiler. Maintenance Modification/ Version Management 3
4 Why Design is so Important? 4
5 Jargons Language Statement Alphabets Grammar Derivation Language Recognition / Acceptor
6 Language / Statements /Alphabets Hindi: आम, ब ट, कत ब, बच, घर Kannada: ಅಮ, ಮಗ, ವ, ಗಳರ Tamil: அம, ஆ ச, த, த ச Telugu:, к,, English: Apple, Ball, Cat, Doll, Egg, Fish, Girl, Him, In, Jump, Kick. C: int main() printf( hello world ); return (0);
7 Programming Language Example 1) <Program> <funcons>comma<functionbody>comma 2) <funcons> <funcon><funcons>/ ε 3) <funcon> <funsignature><functionbody> 4) <Funsignature> <type> id ( <params)> 5) <type> int/ float/string 6) <params> <type> id comma <params> / ε 7) <functionbody> <declaraons> <statements> *<E>; 8) <declaraons> <type>id ; <declarations >/ ε 9) <statements> id = <E>; 10) <E> <E>+<E >/ <E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral> 11) <more> (<args>) 12)<args> id comma <args> / ε 13) <id> [a-z] + [A-Z] [0-9]*[a-z]*[A-Z]* string fun1(int x, string y,) int a; string b; b = b + y; *y; float fun2(int I, float j,) int k; k = I *j+k; *k;, float z; string s= bits ; int p; Z=10.5; p=5; z = fun1(p,s,); p = fun2(p,z,); *z;,
8 Programming Language Example 1) <Program> <funcons>comma<functionbody>comma 2) <funcons> <funcon><funcons>/ ε 3) <funcon> <funsignature><functionbody> 4) <Funsignature> <type> id ( <params)> 5) <type> int/ float/string 6) <params> <type> id comma <params> / ε 7) <functionbody> <declaraons> <statements> *<E>; 8) <declaraons> <type>id ; <declarations >/ ε 9) <statements> id =<E>;<statements>/ ε 10)<E> <E>+<E >/ <E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral> 11) <more> (<args>) 12)<args> id comma <args> / ε 13) <id> [a-z] + [A-Z] [0-9]*[a-z]*[A-Z]* string fun1(int x, string y,) int a; string b; b = b + y; *y; float fun2(int I, float j,) int k; k = I *j+k; *k;, float z; string s= bits ; int p; Z=10.5; p=5; z = fun1(p,s,); p = fun2(p,z,); *z;,
9 Programming Language Example 1) <Program> <funcons>comma<functionbody>comma 2) <funcons> <funcon><funcons>/ ε 3) <funcon> <funsignature><functionbody> 4) <Funsignature> <type> id ( <params)> 5) <type> int/ float/string 6) <params> <type> id comma <params> / ε 7) <functionbody> <declaraons> <statements> *<E>; 8) <declaraons> <type>id ; <declarations >/ ε 9) <statements> id = <E>; <statements>/ id = id <more>;<statements>/ε 10)<E> <E>+<E >/ <E*E>/id/<intigerliteral>/<floatliteral>/<stringliteral> 11) <more> (<args>) 12)<args> id comma <args> / ε 13) <id> [a-z] + [A-Z] [0-9]*[a-z]*[A-Z]* string fun1(int x, string y,) int a; string b; b = b + y; *y; float fun2(int I, float j,) int k; k = I *j+k; *k;, float z; string s= bits ; int p; Z=10.5; p=5; z = fun1(p,s,); p = fun2(p,z,); *z;,
10
11 Language Recognition / Acceptor start < = return(relop, LE) > 3 return(relop, NE) = other 4 * Pushback(LA) return(relop, LT) > 5 return(relop, EQ) = 6 7 return(relop, GE) other 8 * return(relop, GT) Pushback(LA)
12 Revisiting Jargons Language Statement Alphabets Grammar Derivation Language Recognition / Acceptor
13 Definitions Alphabet: Is a finite, non empty set of symbols. Usually denoted by symbol. Example: Binary = 0,1. all lower case letters = a, b, z DNA molecule letters = a, c, g, t Sentence : Strings of symbols. Usually denoted by w symbol. Example: ε, 0, 1, 00, 11, 010,101, , 0011,.. Note:εdenote empty string Language: A language is a collection of sentences of finite length all constructed from alphabets and follow some grammar rules. Denoted by *. Example: 10001, , , , , , 11 Note: * (Kleene Closure) denote zero or more Grammar : Finite set of rules defining a language. Denoted by symbol G. A grammar can be regarded as a device that enumerates the sentences of a language - nothing more, nothing less
14 Language Generators Grammar is 4 tuple N. T. P S A mechanism (or set of rules) by which a language is generated Defined by : Note: A set of non-terminal symbols, N Do not actually appear in strings A set of terminal symbols, T or Appear in strings A set of productions, P Rules used in string generation A starting symbol, S 1) Non-terminals are generally denoted by capital letters A, B,.Z 2) Terminals are generally denoted by a, b,.z, 0-9, operators, symbols.etc. 3) Productions must be of the form <N> α / β / δ Where α, β, δ are strings containing terminals and non-terminals including ε.
15 Grammar Example Example 1: Grammar to generate sets of balanced parentheses N = A T = (,) S = A P = A AA (A) () Example 2: Expression Grammar N = E, T, ID, F T = +, *, (, ), a, b, c,..z S = E P = E E+T / T T T * F / F F ID / ( E) ID a / b / c / / z
16 Derivation
17 Derivation Example: Leftmost derivation of nested parens: (()(())) A (A) (AA) (()A) (()(A)) (()(())) We can view this derivation as a tree, called a parse tree for the string
18 Parse Tree Parse tree for (()(())) A ( A ) A A ( ) ( A ) ( )
19 Grammar Example 3
20 Example 4 : The grammar G(L) to generate a language L, strings of 0 s and 1 s having a substring 000 SA000A Grammar Example A 0A / 1A / A1 / A0 / ε Example 5: Regular grammar to generate a binary string containing an odd number of 1s A 0A 1B 1 B 0B 1A 0 Example 6: Grammar to generate set of all strings with at least one a when =a,b SbS / aa A aa / ba / ε Example 7: Grammar to generate set of all strings with exactly one a when =a,b SbS /ab B bb / ε
21 Example Grammar 8
22 Ambiguous Grammars Two distinct parse trees for the same sentence, A = B + C * A
23 A unique parse tree for A = B + C * A
24 Ambiguous
25 Ambiguous We can easily make this grammar unambiguous: Remove production: A 0A1 Note that nonterminal B can generate an arbitrary number of 0s and nonterminal C can generate an arbitrary number of 1s Now only one parse tree
26 Left Recursion A grammar is left recursive if for a nonterminal A, there is a derivation A + Aα There are three types of left recursion: direct (A A x) indirect (A B C, B A ) hidden (A B A, B ε)
27 Left Recursion To eliminate direct left recursion replace A Aα 1 Aα 2... Aα m β 1 β 2... β n with A β 1 B β 2 B... β n B B α 1 B α 2 B... α m B ε
28 Left Recursion
29 Left recursion Example 3: Expression Grammar: S E E E+T E T T E-T T F F E*F F id
30 Eliminating indirect left recursion S E E E+T /T T E-T / F F E*F /id S E E TE' E' +TE' ε T E-T T F F E*F F id S E E TE' E' +TE' ε T TE'-T T F F E*F F id S E E TE' E' +TE' ε T FT' T' E'-TT' ε F E*F F id S E E TE' E' +TE' ε T FT' T' E'-TT' ε F TE'*F F id S E E TE' E' +TE' ε T FT' T' E'-TT' ε F FT'E'*F F id S E E TE' E' +TE' ε T FT' T' E'-TT' ε F idf' F' T'E'*FF' ε
31 Look ahead during Parsing or Syntax Analysis To derive the string : aacdmnb SaAb / acb A abc / aca B cd C mn / pq a S A b a B C c d m n
32 aaaaaaaaa aaaaaa
33
34 Left-Factoring
35 Left-Factoring
36 Dangling if_else Statement int a=0; if (0==0) if (0==1) a=1; else a=2; What is the value of a after this fragment executes? Some languages define if-then-else in a way that forces the programmer to be more clear Algol does not allow the then part to be another if statement though it can be a block containing an if statement Ada requires each if statement to be terminated with an end if Python requires nested if statement to be indented int a=0; if (0==0) if (0==1) a=1; else a=2; Use of a block reinforces the structure int a=0; if (0==0) if (0==1) a=1; else a=2; Correct indentation
37 Dangling if_else Statement Stmt if <Logic_Expr> then <Stmt> else <Stmt> if <Logic_Expr> then <Stmt> Consider the string: If <logic-expr>then if <logic_expr> then <stmt> else <stmt> Yields two distinct parse trees and is therefore ambiguous
38 Dangling if_else Statement
39 Dangling if_else Statement Stmt if <Logic_Expr> then <Stmt> else <Stmt> if <Logic_Expr> then <Stmt> Becomes: Stmt if <Logic_Expr> then <Stmt>B B else <Stmt> ε
40 Dangling if_else Statement Stmt if <Logic_Expr> then <Stmt> else <Stmt> if <Logic_Expr> then <Stmt> Becomes: <Stmt> E withelse E noelse E withelse if <Logic_Expr> then E withelse else E withelse other E noelse if <Logic_Expr> then <Stmt> if <Logic_Expr> then E withelse else E noelse
41 Check List for Design Constructs Identifiers Data Types Expressions & Assignment Statements Iterative Statements Selection Statements Issues (Naming, Binding, Scope, Lifetime) ( Primitive and User Defined) (Precedence, Associativity and Evaluation) Condition vs Range Two Way vs Multiple Selection
42 Identifiers
43 Topics Introduction Variables (Name, Address, type, value) The Concept of Binding Scope (Static vs Dynamic) Type Checking Type Equivalence Referencing Environments Named Constants 43
44 Introduction Imperative languages are abstractions of von Neumann architecture Memory Processor A variable is an abstraction of a memory cell Variables can be characterized as a six tuple of attributes: Name Address Value Type Lifetime Scope To design a type, must consider scope, lifetime, type checking, initialization, and type compatibility 44
45 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Case sensitivity ROSE, rose, Rose are different in C-based languages Disadvantage: readability (names that look alike are different) Names in the C-based languages are case sensitive Names in C++, Java, and C# have predefined names with mixed case parseint : to convert form char to int, Parseint: are not recognized in java 45
46 Length If too short, they cannot be connective Language examples: FORTRAN I: maximum 6 COBOL: maximum 30 FORTRAN 90 and C89: maximum 31 C99: maximum 63 C#, Ada, and Java: no limit, and all are significant C++: no limit, but implementers often impose one
47 Special words Special words -- reserved words or keywords? An aid to readability; used to delimit or separate statement clauses A keyword is a word that is special only in certain contexts, e.g., in Fortran» Real VarName (Real is a data type followed with a name, therefore Real is a keyword)» Real = 3.4 (Real is a variable) A reserved word is a special word that cannot be used as a user-defined name Potential problem with reserved words: If there are too many, many collisions occur (e.g., COBOL has 300 reserved words!)
48 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Address - the memory address with which it is associated A variable may have different addresses at different times during execution A variable may have different addresses at different places in a program If two variable names can be used to access the same memory location, they are called aliases Aliases are created via pointers, reference variables, Using Typedef in C and C++ Aliases can be harmful to readability (program readers must remember all of them) 48
49 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Value - the contents of the location with which the variable is associated Abstract memory cell - the physical cell or collection of cells associated with a variable - The l-value of a variable is its address - The r-value of a variable is its value To access r-value, the l value must be determined first. Scoping rules can greatly complicate matters. 49
50 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) 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 Type Binding How is a type specified? When does the binding take place? 50
51 First -- The Concept of Binding A binding is an association, such as between an attribute and an entity, or between an operation and a symbol Binding time is the time at which a binding takes place. Static Binding A binding is static if it first occurs before run time and remains unchanged throughout program execution. Dynamic Binding A binding is dynamic if it first occurs during execution or can change during execution of the program A Complete Understanding of the binding times of the attributes of program entities is a prerequisite for understanding the semantics of the programming language. 51
52 Possible Binding Times Language design time Binding of an operator symbol to its operation Language implementation time Binding of the floating point data type to a specific representation Compile time Load time Runtime Binding of a variable to a type as in C or Java Binding of a variable to a memory cell as with C or C++ static variables Binding of a non static local variable to a memory cell 52
53 Static int m, n; float x, y; scanf( %d %d,&m,&n); scanf( %f %f,&x,&y); Binding Times Static vs Run time printf("%d %f %f %d", m + n, x + y, m+y, n+x); Dynamic void function(m,n,x,y) OP1= m+n; OP2 = x*y; OP3 = x*m; Static void function(int m, int n, float x, float y) OP1= m+n; OP2 = x*y; OP3= x*m;
54 The following code declares three distinct functions in C++. int max (int x, int y); int max (int x, int y, int z); float max (float x, float y);
55 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Static Type Binding -- Explicit/Implicit Declaration An explicit declaration is a program statement used for declaring the types of variables int count; An implicit declaration is a default mechanism for specifying types of variables (the first appearance of the variable in the program) Pre 1960s - FORTRAN, PL/I, BASIC Post 1960s JavaScript, Ruby, and ML Perl uses special characters to denote type ($ scalar for array ) Advantage: writability Disadvantage: reliability Forgotten declarations in Python and Fortran. 55
56 Explicit int m, n; float x, y; scanf( %d %d,&m,&n); scanf( %f %f,&x,&y); printf("%d %f %f %d", m + n, x + y, m+y, n+x); Implicit: read<<m; //if m=5 read<<n; //if n=4 read<<x // if x=3.5 read<<y; //if y=6.3 print<< m + n print x + y Print<< m+y print, n+x);
57 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Dynamic Type Binding When the assignment statement is executed, the name on the lhs is bound to the type of the value of the rhs JavaScript list = [2, 4.33, 6, 8]; list = 17.3; Advantage: flexibility (generic program units) Disadvantages: High cost (dynamic type checking and interpretation) Type error detection by the compiler is difficult 57
58 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Who is in the memory?
59 Lifetime and Scope Lifetime Period of time when location is allocated to program Scope Region of program text where declaration is visible Inner declaration of x hides outer: hole in scope
60 Run-time Environments The compiler creates and manages a run-time environment in which it assumes the target program will be executed Includes Layout and allocation of storage locations for named program objects Mechanism for the target program to access variables Linkages between procedures Mechanisms for passing parameters Interfaces to the operating system for I/O and other programs 60
61 Memory Manager The memory manager has one large chunk of memory from the operating system that it can manage for the application program Allocation when a program requests memory for a variable or an object (anything requiring space), the memory manager gives it the address of a chunk of contiguous heap memory if there is no space big enough, can request the operating system for virtual space if out of space, inform the program De-allocation returns de-allocated space to the pool of free space doesn t reduce the size of space and return to the operating system 61
62 Storage Organization Assumes a logical address space Operating system will later map it to physical addresses, decide how to use cache memory, etc. Memory typically divided into areas for Program code Other static data storage, including global constants and compiler generated data Stack to support call/return policy for procedures Heap to store data that can outlive a call to a procedure Code Static Heap Free Memory Stack 62
63 Heap Management Store used for data that lives indefinitely, or until the program explicitly deletes it Memory manager allocates and de-allocates memory in the heap calls to free and delete can be generated by the compiler, or in some languages, explicitly by the programmer Garbage Collection is an important subsystem of the memory manager that finds spaces within the heap that are no longer used and can be returned to free storage the language Java uses the garbage collector as the deallocation operation 63
64 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) The lifetime of a variable is the time during which it is bound to a particular memory cell Static Stack-dynamic Explicit heap-dynamic Implicit heap-dynamic 64
65 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Static Bound to memory cells before program execution begins and remains bound to the same memory cell throughout execution. C and C++ static variables Advantages: efficiency static constants in Java efficiency - (direct addressing) and no run-time allocate/deallocate history-sensitive support Disadvantage: lack of flexibility (no recursion) 65
66 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Stack-dynamic Storage bindings are created for variables when their declaration statements are elaborated. A declaration is elaborated when the executable code associated with it is executed. Local variables of a method in Java Advantages allows recursion conserves storage Disadvantages Overhead of allocation and de-allocation Subprograms cannot be history sensitive Inefficient references (indirect addressing) 66
67 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Explicit heap-dynamic allocated and de-allocated by explicit directives, specified by the programmer, which take effect during execution Referenced only through pointers or references dynamic objects in C++ (via new and delete) int *intnode; intnode = new int; Delete intnode; Objects in Java Advantage: provides for dynamic storage management Disadvantages: inefficient and can be unreliable due to the complexities of storage management 67
68 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) Implicit heap-dynamic Bound to heap storage only when assigned a value allocation and de-allocation caused by assignment statements all variables in APL; all strings and arrays in Perl, JavaScript, and PHP» Highs = [74, 80, 85, 90] Advantage: flexibility (generic code) Disadvantages: Inefficient, because all attributes are dynamic Loss of error detection 68
69 Classify the variables in the program according to their Lifetime static int x; int m; int fun(double a) static int z = 0; int y[100] ; int *ptr = new (int); static char *p= "B","I","T","S";... Variable 1. x Static 2 m Static 3. a Stack 4. z Static 5. y Stack 6. ptr Stack 7 the anonymous Heap object to which ptr points. 8 p Static 9 the string BITS Heap which p is pointing to. Category
70 Run-time stack Each time a procedure is called (or a block entered), space for local variables is pushed onto the stack. When the procedure is terminated, the space is popped off the stack. If procedure p calls procedure q, then even in cases of exceptions and errors, q will always terminate before p. Activations of procedures during the running of a program can be represented by an activation tree Each procedure activation has an activation record (aka frame) on the run-time stack. The run-time stack consists of the activation records at any point in time during the running of the program for all procedures which have been called but not yet returned. 70
71 Activation Tree main() ; g(x); return(0); void g(int m) f(y); g(y); void f(int n) g(n); f(1) g(1) main g(2) g(1) 71 Global area activation record for main activation record for g(2) activation record for f(1) g(1) activation record for g(1)
72 Finding the factorial of 3 fact(3) main() fact(2) fact(3) main() fact(1) fact(2) fact(3) main() fact(2) fact(3) main() 1 fact(3) main() 2 main() 6 Time 2: Time 3: Time 4: Time 5: Time 6: Time 7: Push: fact(3) Push: fact(2) Push: fact(1) Pop: fact(1) Pop: fact(2) Pop: fact(3) returns 1. returns 2. returns 6. Inside findfactorial(3): if (number <= 1) return 1; else return (3 * factorial (2)); Inside findfactorial(2): if (number <= 1) return 1; else return (2 * factorial (1)); Inside findfactorial(1): if (number <= 1) return 1; else return (1 * factorial (0));
73 Storage Allocation Heap High address Parameter & Return value Control link & Saved status Activation Record Stack ptr Local temps Frame pointer (fp) Stack Parameter & Return value Static data Control link & Saved status Code Local temps Low address
74 Activation Record Format or Layout of the non code part of sub-program Temporaries Returned value Local data parameter Optional access link / static link Optional control link / dynamic link Return Address temporaries Return a value to the calling procedure Local data To supply parameters to the called procedure To refer to nonlocal data held in the other activation records Points to the activation record of the caller Info about the state of the machine just before the proc is called
75 An Example: C Function void sub(float total, int part) int list[4]; float sum; [4] [3] [2] [1] [0] 75
76 void main() int a,b,c; c=sum(a,b); print(c); ARI: Activation Record Instance int sum(int m, int n) int res; res = m+f(n); return(res); int f(int p) int i; for(i=0;i<5;i++) p= p+i; return(p): fp NIL 1008 return value 1007 c 1006 b 1005 a 1004 NIL 1003 NIL 1002 NIL 1001 return global env 1000 sp ARI of function main
77 Call Sequence in Stack-based Environments Calling sequence Store return address Push fp as control link Copy sp to fp Push arguments Reserve space for local variables Return sequence Copy fp to sp Load control link into fp Jump to return address Change sp 77
78 void main() int a,b,c; c=sum(a,b); print(c); int sum(int m, int n) int res; res = m+f(n); return(res); int f(int p) int i; for(i=0;i<5;i++) p= p+i; return(p): fp NIL 1016 return value 1015 res 1014 n 1013 m 1012 NIL return main 1009 NIL 1008 return value 1007 c 1006 b 1005 a 1004 NIL 1003 NIL 1002 NIL 1001 return global env 1000 sp ARI of function sum ARI of function main
79 void main() int a,b,c; c=sum(a,b); print(c); int sum(int m, int n) int res; res = m+f(n); return(res); fp temp 1023 return value 1022 i 1021 p 1020 NIL return sum 1017 NIL 1016 return value 1015 res 1014 n 1013 m 1012 NIL sp ARI of function f ARI of function sum int f(int p) int i; for(i=0;i<5;i++) p= p+i; return(p): return main 1009 NIL 1008 return value 1007 c 1006 b 1005 a 1004 NIL 1003 NIL 1002 NIL 1001 return global env 1000 ARI of function main
80 Variables Attributes (Name, Address, Value, Type, Lifetime, Scope) The scope of a variable is the range of statements over which it is visible The non local variables (free variables) of a program unit are those that are visible but not declared there The scope rules of a language determine how references to names are associated with variables. Disallowing them altogether (except keywords and special forms) Lexical Scoping: Compile Time -- Only two scoping Levels- Global and Local. -- Nested scoping Dynamic Scoping: At run time. 80
81 Static Scope Also called Lexical Scope Lexical scope rules specify the association of variables with declarations based on just the examination of the source code The binding of variables to declarations is done at compile time It is based on their spatial relationship Pascal and C use Static Scoping rules
82 program MAIN_2; var X : integer; procedure BIGSUB; var A, B, C : integer; procedure SUB1; var A, D : integer; begin SUB1 A := B + C; < end; SUB1 procedure SUB2(X : integer); var B, E : integer; procedure SUB3; var C, E : integer; begin SUB3 SUB1; E := B + A: < end; SUB3 begin SUB2 SUB3; A := D + E; < end; SUB2 begin BIGSUB SUB2(7); end; BIGSUB begin BIGSUB; end; MAIN_2
83 void main() int x,y,z; while( ) int a,b,c; while( ) int d,e; while( ) int f,g;
84 Dynamic Scope The binding of variables to declarations is done at run time It is based on the calling sequence of subprograms. Pure Lisp and original Common Lisp, as well as Snobol and APL use Dynamic Scoping Rules void sub3() int x, z; x = u + v; void sub2() int w, x;... void sub1() int v, w;... int main() int v, u;... Call Sequence main calls sub1 sub1 calls sub1 sub1 calls sub2 sub2 calls sub3 Run time Stack Sub3 :x,z Sub2 :w,x Sub1: v,w Sub1: v,w Main: v,u In sub3: reference to x is local reference to u searches all activation records on stack until main reference to v is in most recent activation record of sub1 84
85 Implementing Dynamic Scoping Deep Access: non-local references are found by searching the activation record instances on the dynamic chain. Example in previous slide Shallow Access: put locals in a central place One stack for each variable name Central table with an entry for each variable name 85
86 For Dynamic Scoping check the visibility of Non-local variable void main() int a,b,c,d,e,f; fun1() fun2 fun1 main a b c d e f int fun1( ) int res, a,b,g,h,i,j; Fun2() int fun2( ) int a,b,g,l,m,n; Draw run time stack
87 For Dynamic Scoping check the visibility of Non-local variable void main() int a,b,c,d,e,f; fun1() fun2 fun1 a b g h i j c d e f main a b c d e f int fun1( ) int res, a,b,g,h,i,j; Fun2() int fun2( ) int a,b,g,l,m,n;
88 For Dynamic Scoping check the visibility of Non-local variable void main() int a,b,c,d,e,f; fun1() fun2 a b g l m n c d e f h i j fun1 a b g h i j c d e f main a b c d e f int fun1( ) int res, a,b,g,h,i,j; Fun2() int fun2( ) int a,b,g,l,m,n;
89 Exercise: void main() int a,b,c,d,e,f; fun1() fun2() fun2 fun1 main int fun1( ) int res, a,b,g,h,i,j; int fun2( ) int a,b,g,l,m,n; Draw run time stack Fill the visible variables Calculate the address of non local variable
90 Exercise: void main() int a,b,c,d,e,f; fun1() fun2() fun2 a b g l m n c d e f fun1 a b g h i j c d e f main a b c d e f int fun1( ) int res, a,b,g,h,i,j; int fun2( ) int a,b,g,l,m,n; Draw run time stack Fill the visible variables Calculate the address of non local variable
91 Example 1 :Static vs Dynamic int i = 10; void fun1() printf( Inside fun1 %d\n, i); void fun2() int i = 20; fun1(); int main() fun1(); fun2(); fun1(); Static Scope Inside fun1 10 Inside fun1 10 Inside fun1 10 Dynamic Scope Inside fun1 10 Inside fun1 20 Inside fun1 10
92 Example 2: Static vs. Dynamic Scope var a : integer; procedure first a := 1; procedure second var a : integer; first(); begin a := 2; second(); write_integer(a); end; 92
93 Example 2: Static Scope var a : integer; procedure first a := 1; procedure second var a : integer; first(); begin a := 2; second(); write_integer(a); end; 93 var a : integer; main() a := 2; second() var a : integer; first() a := 1; write_integer(a); The program prints 1
94 Example 2: Dynamic Scope var a : integer; procedure first a := 1; procedure second var a : integer; first(); begin a := 2; second(); write_integer(a); end; 94 var a : integer; main() a := 2; second() var a : integer; first() a := 1; write_integer(a); The program prints 2
95 Example 3: Static vs. Dynamic Scope int n = 1; print_plus_n(int x) Print( x + n); increment_n() n = n + 2; print_plus_n(n); main() int n; n = 200; print_plus_n(7); n = 50; increment_n(); Print( n); Static Scoping Dynamic Scoping
96 Example 4: Static vs. Dynamic Scope void P() write x; void Q() x = x + 1; if (x < 23) Q(); else P(); void R() int x = 20; Q(); P(): Dynamic Scoping void main() int x = 10; R(); P();
97 Dynamic scope - Shallow Access Alternative implementation, not a different semantics Variables are not stored in activation records of subprograms Have separate stack for each variable. When subprogram begins, values are pushed onto stack. When it exits, values are popped off all stacks. Allows fast references, but costly exits and entrances to subprograms 97
98 Using Shallow Access to Implement Dynamic Scoping void subc() int x, z; x = u + v; void subb() int w, x;... void suba() int v, w;... int main() int v, u;... main calls suba suba calls suba suba calls subb subb calls subc Stacks Variables A B A C A Main Main B C A u v x z w Names in the stack cells indicate the program units of the variable declaration 98
99 What is the output when Static Scoping is followed? What is the output when Dynamic Scoping is followed? Give the run time stack when fun3() is executing (Shallow Access) void fun3( ) min=(min<c)?min:c; void fun2( ) declare int b=15; declare int c=3; min= (a<b)?a :b; fun3( ); void fun1( ) declare int b; a=6; b=1; c=5; fun2( ); Global declare int min=0,a=9,c=8; driver( ) declare int a=15,b=13,c=22; fun1( ); Write( min );
100 Scope Statically visible variables BLOCK 4 Y =13 X=3 BLOCK 3 Y =11 X=2 BLOCK 2 Y=11 X=3 BLOCK1 X=3 Y=7 Z Dynamically visible variables BLOCK 4 Y =13 X=3 BLOCK 3 Y =13 X=2 BLOCK 2 Y=13 X=2 BLOCK1 X=3 Y=7 Z Solution a. 33 b. 26
101 Blocks Blocks are user-specified local scopes for variables An example in C int temp; temp = list [upper]; list [upper] = list [lower]; list [lower] = temp The lifetime of temp in the above example begins when control enters the block An advantage of using a local variable like temp is that it cannot interfere with any other variable with the same name 101
102 Implementing Blocks Two Methods: 1. Treat blocks as parameter-less subprograms that are always called from the same location Every block has its own activation record; an instance is created every time the block is executed 2. Since the maximum storage required for a block can be statically determined, this amount of space can be allocated after the local variables in the activation record. Blocks that are not active at the same time can reuse space. 102
103 Static Link void main() int x,y,z,m; while( ) ---1 int a,b,c,m; while( )-2 int d,e,m; d = b + x + m; f, g d, e, m a,b, c, m x, y, z, m while 3 while 2 while 1 main while( )-3 int f,g; f=b + x + m; Statically visible variables While 3 F G X Y Z M While 2 D E M A B C X Y Z While 1 A B C M X Y Z Main X Y Z M
104 Static Chain- for Nested Scoping A static chain is a chain of static links that connects certain activation record instances The static link in an activation record instance for subprogram A points to one of the activation record instances of A's static parent (for access to variables) The static chain from an activation record instance connects it to all of its static ancestors 104
105 void main() int x,y,z; while( ) int a,b,c; while( ) int d,e; while( ) int f,g; Block Variables Local Variables e d c b and g a and f z y x
106 Nested Subprograms Some non-c-based static-scoped languages (e.g., Fortran 95, Ada, Python, JavaScript) use stack-dynamic local variables and allow subprograms to be nested. procedure A is procedure B is procedure C is... end; -- of C procedure D is... end; -- of D end; -- of B end; -- of A 106
107 Example Pascal Program program MAIN_2; var X : integer; procedure BIGSUB; var A, B, C : integer; procedure SUB1; var A, D : integer; begin SUB1 A := B + C; end; SUB1 procedure SUB2(X : integer); var B, E : integer; procedure SUB3; var C, E : integer; begin SUB3 SUB1; E := B + A: end; SUB3 begin SUB2 SUB3; A := D + E; end; SUB2 begin BIGSUB SUB2(7); end; BIGSUB begin BIGSUB; end; MAIN_2 Static Structure of the program VS Call sequence for MAIN_2 MAIN_2 calls BIGSUB BIGSUB calls SUB2 SUB2 calls SUB3 SUB3 calls SUB1 107
108 Example Pascal Program program MAIN_2; var X : integer; procedure BIGSUB; var A, B, C : integer; procedure SUB1; var A, D : integer; begin SUB1 A := B + C; end; SUB1 procedure SUB2(X : integer); var B, E : integer; procedure SUB3; var C, E : integer; begin SUB3 SUB1; E := B + A: end; SUB3 begin SUB2 SUB3; A := D + E; end; SUB2 begin BIGSUB SUB2(7); end; BIGSUB begin BIGSUB; end; MAIN_2 Statically visible variables SUB 3 C E B A X SUB2 B E A C X SUB1 A D B C X BIGSUB A B C X Main_2 X Call sequence for MAIN_2 MAIN_2 calls BIGSUB BIGSUB calls SUB2 SUB2 calls SUB3 SUB3 calls SUB1 108
109 Example Pascal Program program MAIN_2; var X : integer; procedure BIGSUB; var A, B, C : integer; procedure SUB1; var A, D : integer; begin SUB1 A := B + C; end; SUB1 procedure SUB2(X : integer); var B, E : integer; procedure SUB3; var C, E : integer; begin SUB3 SUB1; E := B + A: end; SUB3 begin SUB2 SUB3; A := D + E; end; SUB2 begin BIGSUB SUB2(7); end; BIGSUB begin BIGSUB; end; MAIN_2 Dynamically visible variables SUB 1 A D C E X B SUB3 C E B A X SUB2 B E A C X BIGSUB Main_2 A B C X X Call sequence for MAIN_2 MAIN_2 calls BIGSUB BIGSUB calls SUB2 SUB2 calls SUB3 SUB3 calls SUB1 109
110 Example Pascal Program program MAIN_2; var X : integer; procedure BIGSUB; var A, B, C : integer; procedure SUB1; var A, D : integer; begin SUB1 A := B + C; end; SUB1 procedure SUB2(X : integer); var B, E : integer; procedure SUB3; var C, E : integer; begin SUB3 SUB1; E := B + A: end; SUB3 begin SUB2 SUB3; A := D + E; end; SUB2 begin BIGSUB SUB2(7); end; BIGSUB begin BIGSUB; end; MAIN_2 D A Static Link Dynamic link Return SUB 3 E C Static Link Dynamic link Return SUB 2 E B X Static Link Dynamic link return BIGSUB C B A Static Link Dynamic link SUB1 SUB3 SUB 2 BIGSUB Local offect Static Links At Position 1 A (0, 3) B (1, 4) C (1, 5) Chain_offect X return to main return global env
111 Nested Scoping The actual reference can be represented by an ordered pair of integers(chain_offect, Local offect). To compute Chain_offset it is required to understand the Static Depth of a variable. Static Depth: An integer associated with a static scope that indicates how deeply it is nested in the outermost scope. procedure A is procedure B is procedure C is... end; -- of C procedure D is... end; -- of D end; -- of B end; -- of A Let static depth of main procedure is 0. A s static depth is 0 B s static depth is 1 C s static depth is 2 D s static depth is 2 111
112 Chain_offect/ nesting_depth Needed to reach the correct activation record instance for a non local references to a variable x Difference between the static depth of the procedure containing the reference to x and the static depth of the procedure containing the declaration for x. procedure A is procedure B is procedure C is... end; -- of C procedure D is... end; -- of D end; -- of B end; -- of A If procedure C reference a variable declared in A, The chain_offcect of the reference would be 2. If Procedure C references a variable declared in B, The chain_offect of that reference would be 1. Reference to local is 0
113 Example Pascal Program program MAIN_2; var X : integer; procedure BIGSUB; var A, B, C : integer; procedure SUB1; var A, D : integer; begin SUB1 A := B + C; end; SUB1 procedure SUB2(X : integer); var B, E : integer; procedure SUB3; var C, E : integer; begin SUB3 SUB1; E := B + A: end; SUB3 begin SUB2 SUB3; A := D + E; end; SUB2 begin BIGSUB SUB2(7); end; BIGSUB begin BIGSUB; end; MAIN_2 Call sequence for MAIN_2 MAIN_2 calls BIGSUB BIGSUB calls SUB2 SUB2 calls SUB3 SUB3 calls SUB1 Statically visible variable and their Chain offset SUB 3 C ( 0) E (0) B (1) A (2) X (1) SUB2 B (0) E (0) A (1) C (1) X (0) SUB1 A (0) D (0) B (1) C (1) X (2) BIGSUB A ( 0) B (0) C (0) X (1) Main_2 X (0) 113
114 Example Pascal Program program MAIN_2; var X : integer; procedure BIGSUB; var A, B, C : integer; procedure SUB1; var A, D : integer; begin SUB1 A := B + C; end; SUB1 procedure SUB2(X : integer); var B, E : integer; procedure SUB3; var C, E : integer; begin SUB3 SUB1; E := B + A: end; SUB3 begin SUB2 SUB3; A := D + E; end; SUB2 begin BIGSUB SUB2(7); end; BIGSUB begin BIGSUB; end; MAIN_2 D A Static Link Dynamic link Return SUB 3 E C Static Link Dynamic link Return SUB 2 E B X Static Link Dynamic link return BIGSUB C B A Static Link Dynamic link SUB1 SUB3 SUB 2 BIGSUB Static Links At Position 1 A (0,3) B (1,4) C (1,5) At Position 2 E (0,4) B (1,4) A (2,3) At Position 3 A (1,3) D static error (not visible) E (0,5) X return to main return global env
115 void main() int x,y,z,m; while( ) ---1 int a,b,c,m; while( )-2 int d,e,m; d = b + x + m; Static Link f, g d, e, m a,b, c, m x, y, z, m while 3 while 2 while 1 main while( )-3 int f,g; f=b + x + m; Statically visible variables While 3 F G X Y Z M While 2 D E M A B C X Y Z While 1 A B C M X Y Z Main X Y Z M
116 void main() int x,y,z,m; while( ) ---1 int a,b,c,m; while( )-2 int d,e,m; d = b + x + m; Static Link f, g, m d, e, m a,b, c, m x, y, z, m while 3 while 2 while 1 main while( )-3 int f,g; f=b + x + m; Static Chain While 3 F(0,1) B Static error X(1,1) M(1,4) While 2 D(0,1) B(1,2) X (2,1) M (0,3)
117 If the same program is nested as shown, What is the Static link of the variables in Position 1,2,3? Global declare int min=0,a=9,c=8; driver( ) declare int a=15,b=13,c=22; void fun1( ) declare int b; a=6; b=1; c=5; > Position 1 void fun2( ) declare int b=15,c=3; min= (a<b)? a : b; > Position 2 void fun3( ) min=(min<c)? min : c; > Position 3 //endfun3 fun3( ); //end fun2 fun2( ); //end fun1 fun1( ); Write( min ); Position 1: a = (1,3) b = (0,3) c = (1,5) Position 2: a = (2,3) b = (0,3) min = (3, ) Position 3: c = (1,4) min = (4, )
118 Thank You...
Chapter 5. Names, Bindings, and Scopes
Chapter 5 Names, Bindings, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative
More informationChapter 10. Implementing Subprograms
Chapter 10 Implementing Subprograms Chapter 10 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms
More informationChapter 5 Names, Binding, Type Checking and Scopes
Chapter 5 Names, Binding, Type Checking and Scopes Names - We discuss all user-defined names here - Design issues for names: -Maximum length? - Are connector characters allowed? - Are names case sensitive?
More informationChapter 5 Names, Bindings, Type Checking, and Scopes
Chapter 5 Names, Bindings, Type Checking, and Scopes 長庚大學資訊工程學系 陳仁暉 助理教授 Tel: (03) 211-8800 Ext: 5990 E-mail: jhchen@mail.cgu.edu.tw URL: http://www.csie.cgu.edu.tw/jhchen All rights reserved. No part
More informationImplementing Subprograms
1 Implementing Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages Pinar Duygulu The General Semantics of Calls and Returns 2 The subprogram call and return
More informationSubprograms. Copyright 2015 Pearson. All rights reserved. 1-1
Subprograms Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling Subprograms Indirectly
More information12/4/18. Outline. Implementing Subprograms. Semantics of a subroutine call. Storage of Information. Semantics of a subroutine return
Outline Implementing Subprograms In Text: Chapter 10 General semantics of calls and returns Implementing simple subroutines Call Stack Implementing subroutines with stackdynamic local variables Nested
More informationChapter 10. Implementing Subprograms ISBN
Chapter 10 Implementing Subprograms ISBN 0-321-33025-0 Chapter 10 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables
More informationProgramming Languages, Summary CSC419; Odelia Schwartz
Programming Languages, Summary CSC419; Odelia Schwartz Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design
More informationSE352b: Roadmap. SE352b Software Engineering Design Tools. W3: Programming Paradigms
SE352b Software Engineering Design Tools W3: Programming Paradigms Feb. 3, 2005 SE352b, ECE,UWO, Hamada Ghenniwa SE352b: Roadmap CASE Tools: Introduction System Programming Tools Programming Paradigms
More informationImplementing Subprograms
Implementing Subprograms 1 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms Blocks Implementing
More informationProgramming Languages: Lecture 12
1 Programming Languages: Lecture 12 Chapter 10: Implementing Subprograms Jinwoo Kim jwkim@jjay.cuny.edu Chapter 10 Topics 2 The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing
More informationNames, Bindings, Scopes
Names, Bindings, Scopes Variables In imperative l Language: abstractions of von Neumann machine Variables: abstraction of memory cell or cells Sometimes close to machine (e.g., integers), sometimes not
More informationChapter 10 Implementing Subprograms
Chapter 10 Implementing Subprograms The General Semantics of Calls and Returns - Definition: The subprogram call and return operations of a language are together called its subprogram linkage Implementing
More information9/7/17. Outline. Name, Scope and Binding. Names. Introduction. Names (continued) Names (continued) In Text: Chapter 5
Outline Name, Scope and Binding In Text: Chapter 5 Names Variable Binding Type bindings, type conversion Storage bindings and lifetime Scope Lifetime vs. Scope Referencing Environments N. Meng, S. Arthur
More informationImperative Programming
Naming, scoping, binding, etc. Instructor: Dr. B. Cheng Fall 2004 1 Imperative Programming The central feature of imperative languages are variables Variables are abstractions for memory cells in a Von
More informationChapter 9. Def: The subprogram call and return operations of a language are together called its subprogram linkage
Def: The subprogram call and return operations of a language are together called its subprogram linkage Implementing FORTRAN 77 Subprograms Call Semantics: 1. Save the execution status of the caller 2.
More information! Those values must be stored somewhere! Therefore, variables must somehow be bound. ! How?
A Binding Question! Variables are bound (dynamically) to values Subprogram Activation! Those values must be stored somewhere! Therefore, variables must somehow be bound to memory locations! How? Function
More informationNOTE: Answer ANY FOUR of the following 6 sections:
A-PDF MERGER DEMO Philadelphia University Lecturer: Dr. Nadia Y. Yousif Coordinator: Dr. Nadia Y. Yousif Internal Examiner: Dr. Raad Fadhel Examination Paper... Programming Languages Paradigms (750321)
More informationCS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline
CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can
More informationCSC 533: Organization of Programming Languages. Spring 2005
CSC 533: Organization of Programming Languages Spring 2005 Language features and issues variables & bindings data types primitive complex/structured expressions & assignments control structures subprograms
More informationPrinciples of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004
Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?
More informationConcepts Introduced in Chapter 7
Concepts Introduced in Chapter 7 Storage Allocation Strategies Static Stack Heap Activation Records Access to Nonlocal Names Access links followed by Fig. 7.1 EECS 665 Compiler Construction 1 Activation
More informationProgramming Languages Third Edition. Chapter 7 Basic Semantics
Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol
More informationExample. program sort; var a : array[0..10] of integer; procedure readarray; : function partition (y, z :integer) :integer; var i, j,x, v :integer; :
Runtime Environment Relationship between names and data objects (of target machine) Allocation & de-allocation is managed by run time support package Each execution of a procedure is an activation of the
More informationLECTURE 14. Names, Scopes, and Bindings: Scopes
LECTURE 14 Names, Scopes, and Bindings: Scopes SCOPE The scope of a binding is the textual region of a program in which a name-to-object binding is active. Nonspecifically, scope is a program region of
More informationLecture 7: Type Systems and Symbol Tables. CS 540 George Mason University
Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing
More informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction
More informationRun-time Environments
Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction
More informationConcepts of Programming Languages
Concepts of Programming Languages COMP322 Fall 2012/2013 1-1 Textbook ISBN 0-321-49362-1 Chapter 1 Preliminaries ISBN 0-321-49362-1 Chapter 1 Topics Reasons for Studying Concepts of Programming Languages
More informationChapter 5. Variables. Topics. Imperative Paradigm. Von Neumann Architecture
Topics Chapter 5 Variables Imperative Paradigm Variables Names Address Types Assignment Binding Lifetime Scope Constants 2 Imperative Paradigm The most widely used and well-developed programming paradigm.
More informationScope, Functions, and Storage Management
Scope, Functions, and Storage Management Implementing Functions and Blocks cs3723 1 Simplified Machine Model (Compare To List Abstract Machine) Registers Code Data Program Counter (current instruction)
More informationInformatica 3 Syntax and Semantics
Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines
More informationProgramming Languages Third Edition. Chapter 10 Control II Procedures and Environments
Programming Languages Third Edition Chapter 10 Control II Procedures and Environments Objectives Understand the nature of procedure definition and activation Understand procedure semantics Learn parameter-passing
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions
More informationAnswer: Early binding generally leads to greater efficiency (compilation approach) Late binding general leads to greater flexibility
Quiz Review Q1. What is the advantage of binding things as early as possible? Is there any advantage to delaying binding? Answer: Early binding generally leads to greater efficiency (compilation approach)
More informationProgrammiersprachen (Programming Languages)
2016-05-13 Preface Programmiersprachen (Programming Languages) coordinates: lecturer: web: usable for: requirements: No. 185.208, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/ps.html
More informationAttributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,
Chapter 5 Basic Semantics Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes, and the Environment Variables
More informationCSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:
Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd
More informationTopics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited
CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter
More informationWeeks 6&7: Procedures and Parameter Passing
CS320 Principles of Programming Languages Weeks 6&7: Procedures and Parameter Passing Jingke Li Portland State University Fall 2017 PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 1 / 45
More information6. Names, Scopes, and Bindings
Copyright (C) R.A. van Engelen, FSU Department of Computer Science, 2000-2004 6. Names, Scopes, and Bindings Overview Names Binding time Object lifetime Object storage management Static allocation Stack
More informationLecture 16: Static Semantics Overview 1
Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis
More informationLecture 11: Subprograms & their implementation. Subprograms. Parameters
Lecture 11: Subprograms & their implementation Subprograms Parameter passing Activation records The run-time stack Implementation of static and dynamic scope rules Subprograms A subprogram is a piece of
More informationName, Scope, and Binding. Outline [1]
Name, Scope, and Binding In Text: Chapter 3 Outline [1] Variable Binding Storage bindings and lifetime Type bindings Type Checking Scope Lifetime vs. Scope Referencing Environments N. Meng, S. Arthur 2
More informationData Types. Outline. In Text: Chapter 6. What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 5-1. Chapter 6: Data Types 2
Data Types In Text: Chapter 6 1 Outline What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers Chapter 6: Data Types 2 5-1 Data Types Two components: Set of objects in the type (domain
More informationNames, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University
Names, Scopes, and Bindings CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Names, Scopes, and Bindings Names are identifiers (mnemonic character
More informationInformal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility
Informal Semantics of Data semantic specification names (identifiers) attributes binding declarations scope rules visibility 1 Ways to Specify Semantics Standards Documents (Language Definition) Language
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level
More informationLecture 4 Memory Management
Lecture 4 Memory Management Dr. Wilson Rivera ICOM 4036: Programming Languages Electrical and Computer Engineering Department University of Puerto Rico Some slides adapted from Sebesta s textbook Lecture
More informationIntroduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types
Chapter 6 Topics WEEK E FOUR Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference
More informationAn Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables
Activation Records The storage (for formals, local variables, function results etc.) needed for execution of a subprogram is organized as an activation record. An Activation Record for Simple Subprograms.
More informationTail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)
CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)
More informationQuestion No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given
MUHAMMAD FAISAL MIT 4 th Semester Al-Barq Campus (VGJW01) Gujranwala faisalgrw123@gmail.com MEGA File Solved MCQ s For Final TERM EXAMS CS508- Modern Programming Languages Question No: 1 ( Marks: 1 ) -
More informationCOP4020 Programming Languages. Syntax Prof. Robert van Engelen
COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview Tokens and regular expressions Syntax and context-free grammars Grammar derivations More about parse trees Top-down and bottom-up
More informationCOP4020 Programming Languages. Names, Scopes, and Bindings Prof. Robert van Engelen
COP4020 Programming Languages Names, Scopes, and Bindings Prof. Robert van Engelen Overview Abstractions and names Binding time Object lifetime Object storage management Static allocation Stack allocation
More informationNames, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University
Names, Scopes, and Bindings CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Names, Scopes, and Bindings Names are identifiers (mnemonic character
More informationData Types In Text: Ch C apter 6 1
Data Types In Text: Chapter 6 1 Outline What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 2 Data Types Two components: Set of objects in the type (domain of values) Set of applicable
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing
More informationChapter 5 Names, Bindings, Type Checking, and Scopes
Chapter 5 Names, Bindings, Type Checking, and Scopes Names Variables The Concept of Binding Scope and Lifetime Type Checking Referencing Environments Named Constants Names Used for variables, subprograms
More informationCSE 307: Principles of Programming Languages
1 / 57 CSE 307: Principles of Programming Languages Course Review R. Sekar Course Topics Introduction and History Syntax Values and types Names, Scopes and Bindings Variables and Constants Expressions
More informationCS558 Programming Languages. Winter 2013 Lecture 3
CS558 Programming Languages Winter 2013 Lecture 3 1 NAMES AND BINDING One essential part of being a high-level language is having convenient names for things: variables constants types functions etc. classes
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationCS 3360 Design and Implementation of Programming Languages. Exam 1
1 Spring 2016 (Monday, March 21) Name: CS 3360 Design and Implementation of Programming Languages Exam 1 This test has 18 questions and pages numbered 1 through 6. Reminders This test is closed-notes and
More informationLECTURE 18. Control Flow
LECTURE 18 Control Flow CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear in a program text. Selection (or alternation): a
More informationCOP4020 Programming Languages. Syntax Prof. Robert van Engelen
COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview n Tokens and regular expressions n Syntax and context-free grammars n Grammar derivations n More about parse trees n Top-down and
More informationINSTITUTE OF AERONAUTICAL ENGINEERING
INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad -500 043 INFORMATION TECHNOLOGY TUTORIAL QUESTION BANK Name : PRINCIPLES OF PROGRAMMING LANGUAGES Code : A40511 Class : II B. Tech
More informationAnnouncements. Scope, Function Calls and Storage Management. Block Structured Languages. Topics. Examples. Simplified Machine Model.
CS 242 2007 Scope, Function Calls and Storage Management John Mitchell Announcements Homework Returned in class Wed; afterwards in 4 th Floor Gates Cabinet SCPD students: attach routing slip, will be returned
More informationSt. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad
St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad-00 014 Subject: PPL Class : CSE III 1 P a g e DEPARTMENT COMPUTER SCIENCE AND ENGINEERING S No QUESTION Blooms Course taxonomy level Outcomes UNIT-I
More informationMIDTERM EXAMINATION - CS130 - Spring 2003
MIDTERM EXAMINATION - CS130 - Spring 2003 Your full name: Your UCSD ID number: This exam is closed book and closed notes Total number of points in this exam: 120 + 10 extra credit This exam counts for
More informationProgramming Languages
Programming Languages Tevfik Koşar Lecture - VIII February 9 th, 2006 1 Roadmap Allocation techniques Static Allocation Stack-based Allocation Heap-based Allocation Scope Rules Static Scopes Dynamic Scopes
More informationReferences and pointers
References and pointers Pointers are variables whose value is a reference, i.e. an address of a store location. Early languages (Fortran, COBOL, Algol 60) had no pointers; added to Fortran 90. In Pascal,
More informationChapter 9 Subprograms
Chapter 9 Subprograms We now explore the design of subprograms, including parameter-passing methods, local referencing environment, overloaded subprograms, generic subprograms, and the aliasing and problematic
More informationR13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA.
R13 SET - 1 III B. Tech I Semester Regular Examinations, November - 2015 1 a) What constitutes a programming environment? [3M] b) What mixed-mode assignments are allowed in C and Java? [4M] c) What is
More informationThe PCAT Programming Language Reference Manual
The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language
More informationRun-time Environments - 3
Run-time Environments - 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time
More informationType Bindings. Static Type Binding
Type Bindings Two key issues in binding (or associating) a type to an identifier: How is type binding specified? When does the type binding take place? N. Meng, S. Arthur 1 Static Type Binding An explicit
More informationCPSC 3740 Programming Languages University of Lethbridge. Data Types
Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type
More informationThe role of semantic analysis in a compiler
Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationRun Time Environments
Run Time Environments ALSU Textbook Chapter 7.1 7.3 Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 Preliminaries During the execution of a program, the same name in the source
More informationExpressions and Assignment
Expressions and Assignment COS 301: Programming Languages Outline Other assignment mechanisms Introduction Expressions: fundamental means of specifying computations Imperative languages: usually RHS of
More informationImplementing Subroutines. Outline [1]
Implementing Subroutines In Text: Chapter 9 Outline [1] General semantics of calls and returns Implementing simple subroutines Call Stack Implementing subroutines with stackdynamic local variables Nested
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationStatic Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1
Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing
More informationNames and Abstractions: What s in a Name?
Copyright R.A. van Engelen, FSU Department of Computer Science, 2000 Names, Scopes, and Bindings Binding time Object lifetime Object storage management Static allocation Stack allocation Heap allocation
More informationThe SPL Programming Language Reference Manual
The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming
More informationMemory Management and Run-Time Systems
TDDD55 Compilers and Interpreters TDDB44 Compiler Construction Memory Management and Run-Time Systems Part of the Attribute Grammar Material Presented at the Beginning of this Lecture Peter Fritzson IDA,
More informationSyntax Errors; Static Semantics
Dealing with Syntax Errors Syntax Errors; Static Semantics Lecture 14 (from notes by R. Bodik) One purpose of the parser is to filter out errors that show up in parsing Later stages should not have to
More informationMIT Specifying Languages with Regular Expressions and Context-Free Grammars
MIT 6.035 Specifying Languages with Regular essions and Context-Free Grammars Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Language Definition Problem How to precisely
More informationCSCI312 Principles of Programming Languages!
CSCI312 Principles of Programming Languages! Scope Xu Liu ! 4.1 Syntactic Issues! 4.2 Variables! 4.3 Scope! 4.4 Symbol Table! 4.5 Resolving References! 4.6 Dynamic Scoping! 4.7 Visibility! 4.8 Overloading!
More informationChapter 7. Expressions and Assignment Statements
Chapter 7 Expressions and Assignment Statements Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment
More informationDesign Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8
Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns
More informationChapter 9. Subprograms
Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling
More informationCMSC 331 Final Exam Section 0201 December 18, 2000
CMSC 331 Final Exam Section 0201 December 18, 2000 Name: Student ID#: You will have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for
More informationQualifying Exam in Programming Languages and Compilers
Qualifying Exam in Programming Languages and Compilers University of Wisconsin Fall 1991 Instructions This exam contains nine questions, divided into two parts. All students taking the exam should answer
More informationSoftware II: Principles of Programming Languages. Why Expressions?
Software II: Principles of Programming Languages Lecture 7 Expressions and Assignment Statements Why Expressions? Expressions are the fundamental means of specifying computations in a programming language
More informationSubprograms. Bilkent University. CS315 Programming Languages Pinar Duygulu
1 Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University Introduction 2 Two fundamental abstraction facilities Process abstraction Emphasized from early days Data abstraction Emphasized
More informationRun-Time Environments
CS308 Run-Time Environments Li Jiang Department of Computer Science and Engineering Shanghai Jiao Tong University Current Progress Source Language Lexical Analyzer Syntax Analyzer Semantic Analyzer Intermediate
More informationStorage. Outline. Variables and updating. Copy vs. Ref semantics Lifetime. Dangling References Garbage collection
Storage 1 Variables and updating Outline Copy vs. Ref semantics Lifetime Local and global variables Heap variables Persistent variables Dangling References Garbage collection 2 Variables and Updating Variable:
More information