Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics

Similar documents
Full file at Chapter 2 - Inheritance and Exception Handling

Programming Languages Third Edition

CMSC 330: Organization of Programming Languages

COSC252: Programming Languages: Semantic Specification. Jeremy Bolton, PhD Adjunct Professor

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Formal Semantics of Programming Languages

Formal Semantics of Programming Languages

Chapter 3 (part 3) Describing Syntax and Semantics

Input from Files. Buffered Reader

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Fundamentals of Object Oriented Programming

CS 3 Introduction to Software Engineering. 3: Exceptions

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

Chapter 14. Exception Handling and Event Handling ISBN

Exceptions Handling Errors using Exceptions

CSCE 314 Programming Languages. Type System

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Syntax and Grammars 1 / 21

The role of semantic analysis in a compiler

The Substitution Model

The Decaf Language. 1 Lexical considerations

CMSC 330: Organization of Programming Languages. Operational Semantics

CMSC 331 Second Midterm Exam

More on Exception Handling

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Programming II (CS300)

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

Intro to semantics; Small-step semantics Lecture 1 Tuesday, January 29, 2013

Chapter 3. Describing Syntax and Semantics

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

BBM 102 Introduction to Programming II Spring Exceptions

Program Syntax; Operational Semantics

Defining syntax using CFGs

Lexical Considerations

Exception-Handling Overview

Introduction Unit 4: Input, output and exceptions

Semantic Analysis. Lecture 9. February 7, 2018

6.Introducing Classes 9. Exceptions

Semantic Analysis and Type Checking

Denotational Semantics. Domain Theory

7. Introduction to Denotational Semantics. Oscar Nierstrasz

Input-Output and Exception Handling

ECE 122. Engineering Problem Solving with Java

Syntax. A. Bellaachia Page: 1

More on Exception Handling

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

Lexical Considerations

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

Formal Semantics. Prof. Clarkson Fall Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Pace University. Fundamental Concepts of CS121 1

CS4215 Programming Language Implementation. Martin Henz

1 Introduction. 3 Syntax

Lecture 12: Conditional Expressions and Local Binding

Application: Programming Language Semantics

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far

Operational Semantics. One-Slide Summary. Lecture Outline

Exceptions. Examples of code which shows the syntax and all that

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

1 Lexical Considerations

Lecture 19 Programming Exceptions CSE11 Fall 2013

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

This book is licensed under a Creative Commons Attribution 3.0 License

Java Loose Ends. 11 December 2017 OSU CSE 1

CS558 Programming Languages

Chapter 7 Control I Expressions and Statements

axiomatic semantics involving logical rules for deriving relations between preconditions and postconditions.

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

14. Exception Handling

Object Oriented Programming

Pierce Ch. 3, 8, 11, 15. Type Systems

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

3.7 Denotational Semantics

The Substitution Model. Nate Foster Spring 2018

CS 61B Discussion 5: Inheritance II Fall 2014

CA Compiler Construction

Compilers and computer architecture: Semantic analysis

Lecture 15 CIS 341: COMPILERS

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

I/O in Haskell. To output a character: putchar :: Char -> IO () e.g., putchar c. To output a string: putstr :: String -> IO () e.g.

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Intermediate Code Generation

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Notation. The rules. Evaluation Rules So Far.

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

CS 6110 S11 Lecture 25 Typed λ-calculus 6 April 2011

Defining Languages GMU

Introduction to Programming Using Java (98-388)

Operational Semantics of Cool

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

THE CONCEPT OF OBJECT

CS 11 Ocaml track: lecture 7

COSC Exception Handling. Yves Lespérance. Lecture Notes Week 10 Exception Handling

Transcription:

SE3E03, 2006 1.59 61 Syntax and Semantics Syntax Shape of PL constructs What are the tokens of the language? Lexical syntax, word level How are programs built from tokens? Mostly use Context-Free Grammars (CFG) or Backus-Naur-Form (BNF) to describe syntax at the sentence level Static semantics : aspects of program structure that are checked at compile time, but cannot be captured by CFGs ( context-sensitive syntax ): Scopes of names Typing Semantics Meaning of PL constructs Three major approaches: Axiomatic semantics: {p Prog{q Denotational semantics: Prog denotes a mathematical function [[Prog]] Operational semantics: state transitions of an abstract machine SE3E03, 2006 1.66 68 Given Q, R :A B. Relation Overriding The relation Q R relates everything in the domain of R to the same objects as R does, and everything else in the domain of Q to the same objects as Q does. is not commutative Q R {(x, y) : Q x / dom R R Textbook: overriding union operator U Haskell: addlisttomap :: Ord key Map k v [ ( k, v ) ] Map k v addlisttomap = foldr ( uncurry Map. insert ) If Q and R are both partial functions, then Q R is a partial function, too. is used to model writing into memory or store locations insertion into environments (shadowing previous bindings) SE3E03, 2006 1.60 62 From the textbook: Simple Semantic Domains A semantic domain is any set whose properties and operations are independently well-understood and upon which the functions that define the semantics of a language are ultimately based. Primitive domains: IB {True, False, IN, Z, Char, seq Char, Ident Domains for Program States: Locations are usually natural numbers: Loc IN Values are, in a simple context, integers: Val 0 Z Memory states can be considered as partial functions: Mem 0 IN Val 0 Simple environments are partial functions, too: Env 0 Ident Loc A simple state is pair: State 0 Env 0 Mem 0 SE3E03, 2006 1.73 75 Two kinds of assertions: Operational Semantics Evaluating expression e starting in store σ produces value v σ(e) v Execution of statement s starting in store results in storeσ 2 Execution axioms: σ(c) c σ(v) σv if v domσ Execution rules: premise conclusion Example rule addition: σ(e 1 ) v 1 σ(e 2 ) v 2 σ(e 1 + e 2 ) v 1 + v 2 or premise 1 premise n conclusion (The left + is syntax, the right + is a mathematical operation on numbers.) A simple store directly maps identifiers to values: Store 0 Ident Val 0

SE3E03, 2006 1.79 81 Mechanized Operational Semantics: Interpreter SE3E03, 2006 1.90 92 Interpreter: Expression Evaluation (Maybe Monad) Two kinds of assertions: Evaluating expression e starting in store σ produces value v σ(e) v Execution of statement s starting in store results in storeσ 2 This notation stands for two ternary relations, which are partial functions for deterministic programming languages: expression evaluation: eval : State 1 Expr Val 1 statement execution: exec : State 1 Stmt State 1 Note: one syntactic and one semantic argument. Two interpreter functions (assuming deterministic semantics): interpstmt :: Statement State1 Maybe State1 data Value1 = ValInt Int ValBool Bool type State1 = Map Variable Value1 even simpler than State 0 data Value1 = ValInt Int ValBool Bool type State1 = Map Variable Value1 evalexpr ( Var v ) s = Map. lookup v s evalexpr ( Value ( LitInt i ) ) s = Just ( ValInt i ) better: function littoval evalexpr ( Value ( LitBool b ) ) s = Just ( ValBool b ) evalexpr ( Binary ( MkArithOp Plus ) e1 e2 ) s = do ValInt v1 evalexpr e1 s ValInt v2 evalexpr e2 s Just ( ValInt ( v1 + v2 ) ) SE3E03, 2006 1.89 91 Interpreter: Expression Evaluation data Value1 = ValInt Int ValBool Bool type State1 = Map Variable Value1 evalexpr ( Var v ) s = Map. lookup v s evalexpr ( Value ( LitInt i ) ) s = Just ( ValInt i ) better: function littoval evalexpr ( Value ( LitBool b ) ) s = Just ( ValBool b ) evalexpr ( Binary ( MkArithOp Plus ) e1 e2 ) s = case ( evalexpr e1 s, evalexpr e2 s ) of ( Just ( ValInt v1), Just ( ValInt v2 ) ) Just ( ValInt ( v1 + v2 ) ) _ Nothing SE3E03, 2006 1.98 100 For example: Assume {x 39, y 7 Then: Assignment σ(e) v σ(x : e) σ {x v (x) 39 (3) 3 (x + 3) 42 (x : x + 3) {x 42, y 7 since {x 42 {x 42, y 7

SE3E03, 2006 1.101 103 Interpreter: Assignment SE3E03, 2006 1.123 125 Loop Example interpstmt :: Statement State1 Maybe State1 P while x< 50 do x : 2 x od data Value1 = ValInt Int ValBool Bool type State1 = Map Variable Value1 σ(e) v σ(x : e) σ {x v interpstmt ( Assignment var e ) s = case evalexpr e s of Just val Just ( Map. insert var val s ) {x 28 (x< 50) True {x 28 (x : 2 x) {x 56 {x 14 (x< 50) True {x 14 (x : 2 x) {x 28 {x 7 (x< 50) True {x 7 (x : 2 x) {x 14 {x 7(P) {x 56 I {x 56 (x< 50) False {x 56(P) {x 56 I {x 28(P) {x 56 I {x 14(P) {x 56 I (Using the Maybe monad:) interpstmt ( Assignment var e ) s = do val evalexpr e s of Just ( Map. insert var val s ) σ(b) True σ(s) (while b do s od) σ 2 σ(while b do s od) σ 2 σ(b) False σ(while b do s od) σ SE3E03, 2006 1.102 104 Sequencing, Conditionals, Loops SE3E03, 2006 1.140 142 Interpreter: Sequencing (s 1 ) σ 2 σ 2 (s 2 ) σ 3 (s 1 ; s 2 ) σ 3 (s 1 ) σ 2 σ 2 (s 2 ) σ 3 (s 1 ; s 2 ) σ 3 This corresponds to a special case of our Jay ASTs: σ(b) True σ(s 1 ) σ(if b then s 1 else s 2 fi) σ(b) False σ(s 2 ) σ 2 σ(if b then s 1 else s 2 fi) σ 2 σ(b) True σ(s) (while b do s od) σ 2 σ(while b do s od) σ 2 σ(b) False σ(while b do s od) σ interpstmt ( MkBlock [ stmt1, stmt2 ] ) = λ s case ( interpstmt stmt1) s of Just s1 ( interpstmt stmt2 ) s1 General case: interpstmt ( MkBlock stmts ) = λ s interpblock stmts s interpblock :: [ Statement ] ( State1 Maybe State1) interpblock [ ] = Just interpblock ( stmt : stmts ) = λ s case interpstmt stmt s of Just s1 interpblock stmts s1

SE3E03, 2006 1.153 155 Interpreter: Loops σ(b) True σ(s) (while b do s od) σ 2 σ(while b do s od) σ 2 σ(b) False σ(while b do s od) σ interpstmt ( Loop cond body ) = λ s case ( evalexpr cond ) s of Just ( ValBool False) Just s Just ( ValBool True) case ( interpstmt body ) s of Just s1 ( interpstmt ( Loop cond body ) ) s1 Just ( ValInt i ) Nothing This is not compositional, but recursive: interpstmt ( Loop cond body ) occurs also on the right-hand side. SE3E03, 2006 1.167 169 Output: print (e) Input: read (e) Additional Language Features Nested Scopes (declarations in inner blocks) Function and procedure calls Side-effecting expressions Main tasks: Define an appropriate state space Adapt assertion schemas if necessary e.g., expression evaluation with side-effects: σ(e) (σ, v) Port all existing feature definitions to the new states Appropriately define the new features Prove conservative extension : mapping from old states to new is injective and preserves transitions. SE3E03, 2006 1.158 160 Additional Control Structures do {... while (... ) repeat {... until (... ) for (...,...,...) {... for i = beg to end do {... Options: Direct definition using new operational semantics rules SE3E03, 2006 31 180 New Language Feature Example: Output Assume a new statement print (e) that prints the integer expression e to the screen. New typing rule: the argument of PRINT has to be of type integer. New abstract syntax constructor: Print :: Expression Statement New state space: State 2 State 1 [ Z] New statement assertion schema: (, out 1 )(s) (σ 2, out 2 ) σ 2 (b) False σ 2 (b) True σ 2 ( do s while (b)) σ 3 ( do s while (b)) σ 2 ( do s while (b)) σ 3 Adapted rules, e.g.: σ(e) v (σ, out)(x : e) (σ {x v, out) Translation into core language derived features (s ; while b do s od) σ 2 ( do s while (c)) σ 2 Rules for new feature: Check determinism, add to interpreter. σ(e) i (σ, out)( print (e)) (σ, out ++ [i])

SE3E03, 2006 40 189 Exceptions SE3E03, 2006 58 207 Exception Handling in Java An exception is an event that needs to be handled in a special way Examples: system errors, program errors, user errors, undefined operations Most importantly: events that cannot be conveniently handled where generated Exception Handling: A generated exception is thrown to a higher part of the code A thrown exception is caught by an appropriate exception handler that processes the exception Benefits of an exception handling mechanism: Exception-handling code can be separated from regular code Exceptions can be handled at the most appropriate place in the code, not necessarily where they are generated Any Java code can construct an exception and then throw it Exceptions are caught and handled with a try catch finally statement Raising an exception terminates the current block Exceptions propagate up through the code until they are caught by a catch substatement Every checked exception that can be thrown in a method must be either caught in the method or declared in the method with a throws clause Benefits of Java s exception handling mechanism: A class of exceptions can be subclassed There is an enforced discipline for checked exceptions SE3E03, 2006 49 198 Exceptions in Java In Java, exceptions are represented by objects in the java.lang.throwable class. Throwable has two subclasses: Exception: Exceptions which can be thrown and caught Error: Nonrecoverable errors thrown by the system Two kinds of Exceptions: Checked Exceptions which must be declared with a throws clause in a method declaration: All user-defined exceptions, IOExc., ClassNotFoundExc., RuntimeException: Abnormal runtime events which need not be declared with a throws clause: ArithmeticExc., ClassCastExc., IllegalArgumentExc., IndexOutOfBoundsExc., NullPointerExc., SE3E03, 2006 59 208 try { try body catch ( Exception 1 var 1 ) { catch 1 body catch ( Exception 2 var 2 ) { catch 2 body catch ( Exception n var n ) { catch n body finally { finally body Try-Catch-Finally Statement

SE3E03, 2006 60 209 Try-Catch-Finally Example SE3E03, 2006 69 218 Exceptions Example import java.io.*; class Read1 { public static void main(string[] args) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("How old are you?"); String inputline = in.readline(); int age = Integer.parseInt(inputLine); age++; System.out.println("Next year, you ll be " + age); catch (IOException exception) { System.out.println("Input/output error " + exception); catch (NumberFormatException exception) { System.out.println("Input was not a number"); finally { if (in null) { try { in.close(); catch (IOException exception) { class Simulate4 { private static void println(string s) {System.out.println(s); public static int _q = 0; public static void main(string[] a) { int s = g (2); println("* "+s+" "+_q); public static int f (int k, int m) { println("f("+k+","+m+")"); _q += m; int r = g(k) + _q; println("f("+k+","+m+")="+r); return r; public static int g(int n) { println("g(" + n + ")"); int t = 3 * n; if ( t < 10 ) { try { t = (f (n + 1, _q)); catch (Exception e) { println("g: caught exception!"); _q += n; t = t / _q; println("g( " + n + " )= " + t); return t; SE3E03, 2006 68 217 Ways of Handling Exceptions SE3E03, 2006 75 224 Operational Semantics of Exceptions Capture it and execute some code to deal with it Capture it, execute some code, and then rethrow the exception Capture it, execute some code, and then throw a new exception Capture it and execute no code (ignore the exception) bad idea! Do not capture it (let it propagate up) may need to declare! Originally: Two kinds of assertions: σ(e) v evaluating expression e starting in stateσcan produce value v execution of statement s starting in state can successfully terminate in stateσ 2 Now an additional possibility: (s)! (σ 2, x) execution of statement s starting in state can terminate in stateσ 2 rasing exception x Two additional sequencing rules: (s 1 )! (σ 2, z) (s 1 ; s 2 )! (σ 2, z) (s 1 ) σ 2 σ 2 (s 2 )! (σ 3, z) (s 1 ; s 2 )! (σ 3, z) Two additional if rules (no exceptions in expression evaluation yet): σ(b) True σ(s 1 )! (, x) σ(if b then s 1 else s 2 fi)! (, x) σ(b) False σ(s 2 )! (σ 2, x) σ(if b then s 1 else s 2 fi)! (σ 2, x)

SE3E03, 2006 82 231 Original statement interpretation: Exceptions Interpreter interpstmt :: Statement State1 Maybe State1 meaning: iff interpstmt s = Justσ 2 σ 2 iff interpstmt s {, Nothing Statement interpretation with exceptions: interpstmtexc :: Statement State1 Maybe ( Either State1 ( State1, Exc ) ) meaning: iff interpstmt s = Just ( Leftσ 2 ) (s)! (σ 2, x) iff interpstmt s = Just ( Right (σ 2, x ) ) σ 2, x (s)! (σ 2, x) iff interpstmt s {, Nothing SE3E03, 2006 83 232 Exceptions in Expression Evaluation Exercise