Programming Languages Tucker and Noonan Chapter 7 Semantics
















![Conditional • Format If. Statement if ( Expression ) Statement [ else Statement ] Conditional • Format If. Statement if ( Expression ) Statement [ else Statement ]](https://slidetodoc.com/presentation_image/d53400b58e7e6fc104c2e42fe21e0f20/image-17.jpg)



























- Slides: 44

Programming Languages Tucker and Noonan Chapter 7: Semantics 7. 1 7. 2 7. 3 7. 4 7. 5 7. 6 7. 7 Motivation Expression Semantics Program State Assignment Semantics Control Flow Semantics Input/Output Semantics Exception Handling Semantics CSC 321: Programming Languages 1

Motivation • To provide an authoritative definition of the meaning of all language constructs for: 1. Programmers 2. Compiler writers 3. Standards developers • A programming language is complete only when its syntax, type system, and semantics are well-defined. CSC 321: Programming Languages 2

Semantics • Semantics is a precise definition of the meaning of a syntactically and type-wise correct program. • Three approaches – Operational semantics • The meaning attached by compiling using compiler C and executing using machine M. Ex: Fortran on IBM 709. • Direct and straightforward program meaning – Axiomatic semantics • Axiomatize the meaning of statements -- Chapter 12 • Exploration of formal properties of programs – Denotational semantics • Statements as state transforming functions • High-level mathematical precision of program meaning • This chapter uses an informal, operational model. CSC 321: Programming Languages 3

Expression Semantics • Notation – Expression tree • Meaning – Mathematics: (a + b) - (c * d) – Polish prefix notation: • -+ab*cd • Preorder traversal – Polish postfix notation • ab+cd* • Postorder traversal – Cambridge Polish: • (- (+ a b) (* c d)) • Operator precedes operands • Parentheses CSC 321: Programming Languages 4

Infix Notation • Mathematics meaning – (a + b) - (c * d) • Uses associativity and precedence to disambiguate – Associativity of Operators Language C-like Ada Fortran +-*/ Left Unary Right non Right ** non Right == != <. . . Left non Left – Meaning of a < x < b in C-like • a < x && x < b ? • If (a < x) 1 < b else 0 < b CSC 321: Programming Languages 5

Precedence of Operators Unary ** */ +== != < <=. . . Unary not Logical and Logical or C-like 7 6 5 4 3 7 2 1 Ada 3 5 4 3 2 2 2 1 1 CSC 321: Programming Languages Fortran 3 5 4 3 2 2 2 1 1 6

Short Circuit Evaluation • a and b evaluated as: if a then b else false • a or b evaluated as: if a then true else b • Benefits – Efficiency – Shorter code – Clearer code • Example in C-like – x < Math. pow(y, 3) || b – bad? – x<1 && (y*y > 100 || y>x) – good? CSC 321: Programming Languages 7

More Example 1. Node p = head; while (p != null && p. info != key) p = p. next; 2. while (p != null && ! found) { if (p. info == key) break; else p = p. next; } // using break boolean found = false; while (p != null && ! found) { if (p. info == key) found = true; else p = p. next; } // avoiding break 3. CSC 321: Programming Languages 8

Expression Meaning • Number precision – data type size – (a+b)+c == a+(b+c) ? • Side effect – A change to any non-local variable or I/O. – What is the value of: • i = 2; b = 2; c = 5; • x = b * i++ + c * i; // 19 • y = c * i + b * i++; // 14 – Consider • y = x++; • y = x+1; CSC 321: Programming Languages 9

Program State • The state of a program is the collection of all active objects and their current values. • Two maps: 1. Active objects to specific memory locations 2. Active memory locations to specific values. • State = memory environment • The current statement (portion of an abstract syntax tree) to be executed in a program is interpreted relative to the current state. • The individual steps that occur during a program run can be viewed as a series of state transformations. • For simplicity, ignore the memory location CSC 321: Programming Languages 10

Program State Transformation Program: compute the factorial of n 1 void main ( ) { 2 int n, i, f; 3 n = 3; 4 i = 1; 5 f = 1; 6 while (i < n) { 7 i = i + 1; 8 f = f * i; 9 } 10 } State Transformation n undef 3 3 3, 3, 3 3 i undef 1 1, 2, 3 1, 2 2, 3 3 CSC 321: Programming Languages f undef 1, 2, 6 1, 2 2, 6 6 11

Assignment Semantics • Issues – Multiple assignment • Example: – a = b = c = 0; – Sets all 3 variables to zero. – Problems? ? ? – Assignment statement vs. expression – Copy vs. reference semantics CSC 321: Programming Languages 12

Assignment Statement vs. Expression • In most languages, assignment is a statement; cannot appear in an expression. • In C-like languages, assignment is an expression. – – Example: if (a = 0). . . // an error while (*p++ = *q++) ; // strcpy while (ch = getc(fp)). . . // ? ? ? while (p = p->next). . . // ? ? ? CSC 321: Programming Languages 13

Copy vs. Reference Semantics • Copy: a = b; – a, b have same value. – Changes to either have no effect on other. – Used in imperative languages. • Reference – a, b point to the same object. – A change in object state affects both – Used by many object-oriented languages. CSC 321: Programming Languages 14

Control Flow Semantics • Turing complete – a programming language is Turing Complete if its program are capable of computing any computable function • To be complete, an imperative language needs: – Statement sequencing – Conditional statement – Looping statement CSC 321: Programming Languages 15

Sequence • Format: s 1 s 2 • Semantics: in the absence of a branch: – First execute s 1 – Then execute s 2 – Output state of s 1 is the input state of s 2 CSC 321: Programming Languages 16
![Conditional Format If Statement if Expression Statement else Statement Conditional • Format If. Statement if ( Expression ) Statement [ else Statement ]](https://slidetodoc.com/presentation_image/d53400b58e7e6fc104c2e42fe21e0f20/image-17.jpg)
Conditional • Format If. Statement if ( Expression ) Statement [ else Statement ] • Semantics If the value of Expression is true, the meaning is the state resulting from evaluating Statement 1 in the current state. Otherwise the meaning is the state resulting from evaluating Statement 2 in the current state • Example: if (a > b) z = a; else z = b; CSC 321: Programming Languages 17

Various Conditional Statements • if <E> then <S> : if <E> is true then execute <S> • if <E> then <S> else <S 2>: if <E> is true then execute <S>, otherwise execute <S 2> • Dangling-else: Ambiguity. Ways to avoid ambiguity – Syntax: the else-clause associated with the closest then – e. g. C, Java if <E 1> then if <E 2> then <S 1> else <S 2> – Use compound brackets • A: • B: if <E 1> then { if <E 2> then <S 1> } else <S 2> if <E 1> then { if <E 2> then <S 1> else <S 2> } – Avoid use of nesting in then parts • A: • B: if !<E 1> then <S 2> else if <E 2> then <S 1> if <E 1> && <E 2> then <S 1> else if <E 1> then <S 2> CSC 321: Programming Languages 18

Multiple Branches • • Multiple branches – case (selection): use the value of an expression to select one of several substatements for execution Pascal, Modula-2: case x of <value 1>: <statements 1> <value 2>: <statements 2> … [else: <statements>] end Ada: case x is when <value 1> => <statements 1>; when <value 2> => <statements 2>; … [others => <statements>]; C/C++, Java : Notice: the use of break switch (x) { case <value 1>: <statements 1>; [break; ] case <value 2>: <statements 2>; [break; ] … [default: <statements>]; } CSC 321: Programming Languages 19

Multiple Branches • Points: – Cases can appear in any order, but else/others/default must be the last one – The case value of x is discrete, such as 1, 10, 6, 9 – The case values must be distinct – Some languages allow ranges of case values, such as in Modula -2, ‘ 0’. . ’ 9’ represents the value either ‘ 0’, or ‘ 1’, …, or ‘ 9’ of x • Case can be replaced with if—then—else statements if x == <value 1> then <statements 1>; else if x == <value 2> then <statements 2>; … else: <statements>; CSC 321: Programming Languages 20

Loops • Format While. Statement while ( Expression ) Statement • Semantics – The expression is evaluated. – If it is true, first the statement is executed, and then the loop is executed again. – Otherwise the loop terminates. CSC 321: Programming Languages 21

General Loop Structure • General structure: Do S 1 If C exit Otherwise Do S 2 Repeat S 1 C S 2 CSC 321: Programming Languages 22

Loop Implementation General loop While loop Ada: loop S 1 exit when C S 2 end loop Ada: S 1 while (!C) loop S 1 end loop Repeat Ada: while (!C) loop S 2 end loop C/C++, Java: while (t) { S 1 if (C) break; S 2 } C/C++, Java: do S 1 while (C) C/C++, Java: while (!C) { S 2 } Pascal: S 1; while (C) do begin S 2 S 1 end Pascal: Perl: repeat S 1 while (!C) { until C S 1 } Pascal: while (!C) do begin S 2 end CSC 321: Programming Languages Perl: unless (C) { S 2 } 23

For Loop Implementation • For statement: definite iteration – for each element do • General form: – for (<var> = <initial>; [<step>]; <termination>) do statements – <var> varies from the initial value to the termination, each loop varies with a stepwise – Step can be omitted, default value is 1 – Stepwise can be going either up from small initial to large termination, or down from large initial to small termination • Pascal: – for x : = low to high do S – for x: = high downto low do S • Fortran/Algol: – for x: = start step increment until end do S – increment may be negative to implement “going down” • Ada: – for x in low. . high loop S end loop; – for x in reverse low. . high loop S end loop • C/C++/Java: – for (e 1; e 2; e 3) S CSC 321: Programming Languages 24

For Loop Implementation • Some languages allow the stepwise to be real or other data types – Fortran/Algol: allow real steps such as 0. 1, 0. 2 – Pascal/Modula-2: allow step type of enumeration • for x in d do S; where d is a type of enumeration – Perl: allows enumeration in a list • foreach $x (@list) S; – Java: allows enumeration in a collection • Syntax foreach (Type variable : collection) statement • Example String names[]; …… foreach (String name : names) do something with name; CSC 321: Programming Languages 25

Jump Statements • Goto: jump to a specific statement (labeled by a label). Recall jmp, jp in assembly languages – makes the program difficult to trace, hard to prove – violates the structured programming style – destroy the system if goto the kernel of the OS • Break (C/C++, Java): limited use of Goto as an exit of a loop or selection – Used inside a loop: exit the loop – Used inside a selection (case): exit the case – Exit in Ada and Modula-2 • Continue(C/C++, Java, Fortran): limited use of Goto – Begin the next loop, ignore the statements after it in the body CSC 321: Programming Languages 26

7. 6 Input/Output Semantics • • • Binding: open, close Access: sequential vs. random Stream vs. fixed length records Character vs. binary Format I/O Error handling CSC 321: Programming Languages 27

Standard Files • • Unix: stdin, stdout, stderr C++: cin, cout, cerr Java: System. in, System. out, System. err CSC 321: Programming Languages 28

Input/Output Streams • Fortran integer : : i, a(8) write(8, *) “Enter 8 integers: “ read(*, *) a write(*, *) a • Java – file, pipe, memory, url – filter – reader, writer CSC 321: Programming Languages 29

Formats • C – Codes: d, e, f, c, s (decimal. float, char, string) – Specifier: % opt-width code – Ex: %s %5 d %20 s %8. 2 f • Fortran – Codes: i, f, a (integer, float, string) – Specifier: op-repeat code width – Ex: 8 i 4, f 8. 2, a 20 CSC 321: Programming Languages 30

Exception Handling Semantics • Exception – an error condition occurring from an operation that cannot be resolved by the operation itself • Purposes – Simplify programming – Make applications more robust: continue to operate under all concevable error situations CSC 321: Programming Languages 31

Exception Handling Basic Structure • Exception events: abnormal – event that the system can not deal with so that leave to the programmer, such as • division by zero, • get value from a null pointer; • read a file that doesn’t exist exception event> < Automatically jump • Exception handlers – Deal with the exception events, such as <exception handler> • output error • use default value • stop the execution CSC 321: Programming Languages 32

Exception Handling Program. Structure Ada: C++/Java: begin … exception when <exception 1> => exception 1 -handler; when <exception 2> => exception 2 -handler; …. end try { …. } catch (<exception 1>) { exception 1 handler; } catch (<exception 2>) { exception 2 handler; } CSC 321: Programming Languages … 33

Raise/Throw/Catch Exceptions • Raise/throw exception – Implicitly throw: built-in method/function throw, e. g. division, file access – Explicitly throw: • throw <exception> --- C++/Java • raise <exception> --- Ada • Catch exception – If there exists a catch clause to catch a specific exception, the exception is handled by the corresponding handler. If no handler exists, the exception is raised/thrown to the caller. To implement this, the throws must be specified in the method prototype (signature). E. g. in Java public void method_sample(…) throws <exception> { … throw <exception>; … } CSC 321: Programming Languages 34

Throwing an Exception Figure 7. 13 CSC 321: Programming Languages 35

Exception Post-process • Termination model – C++/Java, Ada: only enter the exception handler and execute the finally clause, if any. • Resumption model – Eiffel: can use the retry statement to reexecute the procedure/function in which the exception occurred CSC 321: Programming Languages 36

Exception Handling Figure 7. 9 CSC 321: Programming Languages 37

Declare Exceptions • Predefined exceptions (built-in exception) • User-defined exception: e. g. in Java Public class My. Exception extends Runtime. Exception { …… } Creating a New Exception Class CSC 321: Programming Languages 38

Java Exception Type Hierarchy Figure 7. 10 CSC 321: Programming Languages 39

Missing Argument Exception CSC 321: Programming Languages 40

Invalid Input Exception Figure 7. 12 CSC 321: Programming Languages 41

Assert. Exception Class CSC 321: Programming Languages 42

Assert Class Figure 7. 15 CSC 321: Programming Languages 43

Using Asserts CSC 321: Programming Languages 44