CSC321: Programming Languages7-1 Programming Languages Tucker and Noonan Chapter 7: Semantics 7.1 Motivation 7.2 Expression Semantics 7.3 Program State.

Slides:



Advertisements
Similar presentations
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 7 Semantics Surely all this is not without.
Advertisements

ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Programming Languages and Paradigms
Adapted from Scott, Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
CSCI 330: Programming Language Concepts Instructor: Pranava K. Jha Control Flow-II: Execution Order.
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
COP4020 Programming Languages Expression and assignment Prof. Xin Yuan.
Introduction to Programming Languages Nai-Wei Lin Department of Computer Science and Information Engineering National Chung Cheng University.
Gary MarsdenSlide 1University of Cape Town Statements & Expressions Gary Marsden Semester 2 – 2000.
1 Chapter 7: Expressions Expressions are the fundamental means of specifying computations in a programming language To understand expression evaluation,
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering CSCE 330 Programming Language Structures Chapter 7: Semantics Fall 2009 Marco.
Control Structures. Hierarchical Statement Structure Standard in imperative languages since Algol60. Exceptions: Early FORTRAN, COBOL, early BASIC, APL.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 7 Semantics Surely all this is not without.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 8 . Sequence Control
CSE 452: Programming Languages Expressions and Control Flow.
ISBN Chapter 7 Expressions and Assignment Statements.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 7 Semantics Surely all this is not without.
Imperative Programming
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
High-Level Programming Languages: C++
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 7 Expressions and Assignment Statements. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Arithmetic Expressions Arithmetic evaluation.
C H A P T E R S E V E N Expressions and Assignment Statements.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
PLLab, NTHU,Cs2403 Programming Languages Expression and control structure Kun-Yuan Hsieh Programming Language Lab., NTHU.
1 Control Flow: Expressions, Sequencing & Selection (Section ) A compilation of material developed by Felix Hernandez-Campos and Michael Scott.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 4: Control Structures I (Selection)
ISBN Chapter 8 Statement-Level Control Structures.
1 CS Programming Languages Class 11 September 26, 2000.
Expressions and Statements. Expressions Literals and identifiers are expressions More complex expressions are built from simple expressions by the application.
Semantics. Semantics is a precise definition of the meaning of a syntactically and type-wise correct program. Ideas of meaning: –Operational Semantics.
Arithmetic Expressions
Expressions and Assignment Statements
ISBN Chapter 7 Expressions and Assignment Statements.
Copyright © 1998 by Addison Wesley Longman, Inc. 1 Chapter 7 Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
Semantics (1).
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
LECTURE 18 Control Flow. CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
Semantics(1). 2 Symantec(1)  To provide an authoritative definition of the meaning of all language constructs for: 1.Programmers 2.Compiler writers 3.Standards.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Expressions and Assignment Statements
Definition of the Programming Language CPRL
Chapter 4: Control Structures I (Selection)
Chapter 7: Expressions and Assignment Statements
Def: A control structure is a control statement and
Expressions and Assignment
Chapter 7: Expressions and Assignment Statements
Chapter 8: Control Structures
Imperative languages Most familiar: computation modifies store
Java Programming: From Problem Analysis to Program Design, 4e
Control Structures – Selection
Chapter 4: Control Structures I (Selection)
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
Languages and Compilers (SProg og Oversættere)
Chapter 7 Expressions and Assignment Statements.
Chapter 8: Statement Level Control Structures
Presentation transcript:

CSC321: Programming Languages7-1 Programming Languages Tucker and Noonan Chapter 7: Semantics 7.1 Motivation 7.2 Expression Semantics 7.3 Program State 7.4 Assignment Semantics 7.5 Control Flow Semantics 7.6 Input/Output Semantics 7.7 Exception Handling Semantics

CSC321: Programming Languages7-2 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.

CSC321: Programming Languages7-3 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. Semantics

CSC321: Programming Languages7-4 Expression Semantics Notation – Expression tree Meaning –Mathematics: (a + b) - (c * d) –Polish prefix notation: - + a b * c d Preorder traversal –Polish postfix notation a b + c d * - Postorder traversal –Cambridge Polish: (- (+ a b) (* c d)) Operator precedes operands Parentheses

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

CSC321: Programming Languages7-6 Precedence of Operators Operators C-likeAdaFortran Unary -733 **55 * / == !=422 < <= Unary not722 Logical and211 Logical or111

CSC321: Programming Languages7-7 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 100 || y>x) – good?

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

CSC321: Programming Languages7-9 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;

CSC321: Programming Languages7-10 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

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

CSC321: Programming Languages7-12 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

CSC321: Programming Languages7-13 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)... // ???

CSC321: Programming Languages7-14 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.

CSC321: Programming Languages7-15 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

CSC321: Programming Languages7-16 Sequence Format: s1 s2 Semantics: in the absence of a branch: –First execute s1 –Then execute s2 –Output state of s1 is the input state of s2

CSC321: Programming Languages7-17 Conditional Format IfStatement  if ( Expression ) Statement [ else Statement ] Semantics If the value of Expression is true, the meaning is the state resulting from evaluating Statement1 in the current state. Otherwise the meaning is the state resulting from evaluating Statement2 in the current state Example: if (a > b) z = a; else z = b;

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

CSC321: Programming Languages7-19 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 : … [else: ] end Ada: case x is when => ; … [others => ]; C/C++, Java : Notice: the use of break switch (x) { case : ; [break;] case : ; [break;] … [default: ]; }

CSC321: Programming Languages7-20 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 == then ; else if x == then ; … else: ;

CSC321: Programming Languages7-21 Loops Format WhileStatement  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.

CSC321: Programming Languages7-22 General Loop Structure General structure: Do S1 If C exit Otherwise Do S2 Repeat S1 C S2

CSC321: Programming Languages7-23 Loop Implementation Ada: while (!C) loop S2 end loop C/C++, Java: while (!C) { S2 } Pascal: while (!C) do begin S2 end Perl: unless (C) { S2 } Ada: S1 while (!C) loop S1 end loop C/C++, Java: do S1 while (C) Pascal: repeat S1 until C Perl: S1 while (!C) { S1 } Ada: loop S1 exit when C S2 end loop C/C++, Java: while (t) { S1 if (C) break; S2 } Pascal: S1; while (C) do begin S2 S1 end General loop While loop Repeat loop

CSC321: Programming Languages7-24 For Loop Implementation For statement: definite iteration – for each element do General form: –for ( = ; [ ]; ) do statements – 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 (e1; e2; e3) S

CSC321: Programming Languages7-25 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 S ; –Java: allows enumeration in a collection Syntax foreach (Type variable : collection) statement Example String names[]; …… foreach (String name : names) do something with name;

CSC321: Programming Languages7-26 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

CSC321: Programming Languages Input/Output Semantics Binding: open, close Access: sequential vs. random Stream vs. fixed length records Character vs. binary Format I/O Error handling

CSC321: Programming Languages7-28 Standard Files Unix: stdin, stdout, stderr C: stdin, stdout, stderr C++: cin, cout, cerr Java: System.in, System.out, System.err

CSC321: Programming Languages7-29 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

CSC321: Programming Languages7-30 Formats C –Codes: d, e, f, c, s (decimal. float, float, char, string) –Specifier: % opt-width code –Ex: %s %5d %20s %8.2f Fortran –Codes: i, f, a (integer, float, string) –Specifier: op-repeat code width –Ex: 8i4, f8.2, a20

CSC321: Programming Languages7-31 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

CSC321: Programming Languages7-32 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 handlers –Deal with the exception events, such as output error use default value stop the execution Automatically jump

CSC321: Programming Languages7-33 Exception Handling ProgramStructure Ada: begin … exception when => exception1-handler; when => exception2-handler; …. end C++/Java: try { …. } catch ( ) { exception1- handler; } catch ( ) { exception2- handler; } … [finally { …. }]

CSC321: Programming Languages7-34 Raise/Throw/Catch Exceptions Raise/throw exception –Implicitly throw: built-in method/function throw, e.g. division, file access –Explicitly throw: throw --- C++/Java raise --- 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 { … throw ; … }

CSC321: Programming Languages7-35 Throwing an Exception Figure 7.13

CSC321: Programming Languages7-36 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 re- execute the procedure/function in which the exception occurred

CSC321: Programming Languages7-37 Exception Handling Figure 7.9

CSC321: Programming Languages7-38 Creating a New Exception Class Declare Exceptions Predefined exceptions (built-in exception) User-defined exception: e.g. in Java Public class MyException extends RuntimeException { …… }

CSC321: Programming Languages7-39 Java Exception Type Hierarchy Figure 7.10

CSC321: Programming Languages7-40 Missing Argument Exception

CSC321: Programming Languages7-41 Invalid Input Exception Figure 7.12

CSC321: Programming Languages7-42 AssertException Class

CSC321: Programming Languages7-43 Assert Class Figure 7.15

CSC321: Programming Languages7-44 Using Asserts