<<

Topics

Introduction Chapter 3 Static Attribute Semantics

Chapter 3: Semantics 2

Introduction Introduction

Language implementors Well-designed programming

n Understand how all the constructs of the n Semantics should follow directly from . language are form and their intended effect n Form of a should strongly suggest when executed. what the statement is meant to accomplish. Language users of a

n Determine how to encode a possible solution n Complete: semantics and syntax are fully of a problem (program) using the defined. manual of the programming language. A language should provides a variety of Less of how to correctly define different constructs, each one with a the semantics of a language. precise definition. Chapter 3: Semantics 3 Chapter 3: Semantics 4

Introduction Introduction

Language manuals Natural language

n Definition of semantics is given in ordinary n Ambiguous in its natural language. Different readers come away with different

n Construct interpretations of the semantics of a language construct. Syntax: a rule (or of rules) from a BNF or other formal . A method is needed for giving a Semantics: a few paragraphs and some readable, precise, and concise definition examples. of the semantics of an entire language.

Chapter 3: Semantics 5 Chapter 3: Semantics 6

1 Static Semantics Static Semantics

BNFs cannot describe all of the syntax of Some problems have nothing to do with programming . “meaning” in the sense of run-time behavior

n Some -specific parts are left out. n They are concern about the legal form of the Is there a form to generate L={anbncn} program. n Static semantics refers to type checking and resolving using a context-free grammar or a BNF? declarations.

An attempt: n Examples: ::= All variables must be declared before they are referenced ::= a | a Ada: the on the end of a procedure must match the procedure’s name ::= b | b L’={akbmcn | k=1, m=1, n=1} ::= c | c No context-free grammar generates L Both sides of an assignment must be of the same type.

Chapter 3: Semantics 7 Chapter 3: Semantics 8

Attribute Grammars: Basic Static Semantics Earliest attempts to add semantics to a A context-free grammar extended to provide programming language context-sensitivity information by appending attributes to each node of a parse tree. Add extensions to the BNF grammar Each distinct in the grammar has that defined the language. associated with it a finite, possibly empty, set of n Given a parse tree for a program, attributes. additional information could be extracted n Each attribute has a domain of possible values. from that tree. n An attribute may be assigned values from its domain during parsing.

n Attributes can be evaluated in assignments and conditions. Chapter 3: Semantics 9 Chapter 3: Semantics 10

Attribute Grammars: Generalities Attribute Grammars: Parse Tree

S Two classes of attributes:

n Synthesized attribute Gets its value from the attributes attached to its children (subtree below the node). inherited Used to pass semantic information up a parse tree.

n Inherited attribute

Gets its value from the attributes attached to the A parent (subtree above the node). Used to pass semantic information down and synthesized across a tree. t Chapter 3: Semantics 11 Chapter 3: Semantics 12

2 Attribute Grammar Definition Attribute Grammars

Associate some functions to compute the Starting with the underlying context-free value of the attributes with each grammar G= production in the grammar. For every production p in P These local associated with each production of the grammar define n Number of terminal and nonterminal the values of the attributes for all parse in string a: n(p). trees. If a is the empty string, then n(p)=0. Sometimes each symbol of a production will be Given the definitions and a parse tree, considered individually.

algorithms exist to compute the attributes n For all production pÎP : A? a or p0? p1,p2,…pn (p) of all the nodes in the three.

Chapter 3: Semantics 13 Chapter 3: Semantics 14

Attribute Grammars Attribute Grammars: attributes

Augment the context-free grammar by There is a set of attributes At(x)ÌAt to attributes and semantic rules. every grammar symbol xÎNÈT Set of attributes: At. n At(x) can be seen as additional information about the symbol x. n For each attribute aÎAt: associate a set of Set values Domain(a). n In(x) = { aÎAt(x) | aÎ In } n An attribute is just a name for a set of values n Syn(x) = { aÎAt(x) | aÎ Syn } Set of attributes: two disjoint classes: n Requirements: n Inherited attributes In and the synthesized In(S)= Æ (start symbol can inherit no information) attributes Syn (At=InÈ Syn and InÇ Syn=Æ). For all tÎT, Syn(t)= Æ (there is no structure beneath a terminal from which to synthesize information) Chapter 3: Semantics 15 Chapter 3: Semantics 16

Attribute Grammars: attribute Attribute Grammars: rules occurrences

Same attribute can be associated with different Attribute occurrenceof a rule p is an ordered symbols appearing in the same grammar rule. pair of attributes and natural number n Example: S? AB, all could inherit attribute int representing the attribute a at position j in associated to them: In(S)=In(A)=In(B)={int}. production p. n It is impossible to consider the set of attributes associated with all the symbols of a production n Particular rule pÎP an attribute occurrence at j will be written p.a. without losing track of which attributes appear more j than once. n Set of attribute occurrences for a production p is defined: AO(p) = { p.a | aÎAt(p), 0£ j £ n(p) } n More confusing: productions that have a nonterminal j j appearing more than once, as in S? ASA.

Chapter 3: Semantics 17 Chapter 3: Semantics 18

3 Attribute Grammars: attribute Attribute Grammars: flow of occurrences attribute occurrences

Rule: S? AB Set of attribute occurrences for a rule is subtree divided into two disjoint subsets. above S In(S) Syn (S) n Defined occurrences for a production p: S

DO(p) = { p0.s | sÎSyn(p0)} È { pj .i | iÎIn(p j), 1£ j £ n(p) } In a parse tree, the set UO(p) represents the information In(B) Syn (B) flowing into the node of the parse tree labeled p0 In(A) Syn (A) A B n Used occurrences for a production p:

UO(p) = { p0.i | iÎIn(p0)} È { pj .s | sÎSyn(p j), 1£ j £ n(p) } In a parse tree, the set DO(p) represents the information subtree subtree flowing out flowing into the node of the parse tree labeled p0 below A below B

Chapter 3: Semantics 19 Chapter 3: Semantics 20

Attribute Grammars: used attribute Attribute Grammars: defined occurrences attribute occurrences Used attribute occurrences (the Defined attribute occurrences (the information flowing in) are In(S), Syn(A), information flowing out) are Syn(S), In(A), and Syn(B). and In(B). S A B S A B

synthesized Syn(S) Syn(A) Syn(B) synthesized Syn(S) Syn(A) Syn(B)

inherited In(S) In(A) In(B) inherited In(S) In(A) In(B)

Chapter 3: Semantics 21 Chapter 3: Semantics 22

Attribute Grammars: semantic Attribute Grammar

Semantic function fp,v. n For every attribute occurrence vÎDO(p) An attribute grammar as a context-free n Defined values for attributes in DO(p) in terms of the grammar with two disjoint sets of values of the attributes in UO(p).

n Produces a value for the attribute a from values of the attributes (inherited and synthesized) attributes of UO(p). and semantic functions for all defined n There is no requirement that all the attribute attribute occurrences. occurrences of UO(p) are used by fp,v . n Dependency set (Dp,v .) of fp,v: is the set of attribute occurrences used (subset of UO(p))

n Dp,v could be empty Value of the attribute: computed without any other additional

information. The functionfp ,v is a constant. Chapter 3: Semantics 23 Chapter 3: Semantics 24

4 Attribute Grammar: binary digits Attribute Grammar: binary digits example example

Context-free grammar that generates strings Compute the defined and the used occurrences for of binary digits. each production p: B ® D The defined occurrences is the set of synthesized attributes of the LHS plus the set of inherited q: B ® D B B D attributes of all the grammar symbols of the RHS. r: D ® 0 synthesized pos, val val s: D ® 1 Defined Used inherited pow Attributes: p B.pos, B.val, D.pow D.val q B1.pos, B1.val, D.pow B2.pos, B2.val, D.val n val: accumulate the value of the binary numbers r D.val D.pow n pow and pos: keep track of the position and the s power of 2. D.val D.pow

Chapter 3: Semantics 25 Chapter 3: Semantics 26

Attribute Grammar: binary digits Attribute Grammar: binary digits

example pos val example 4 10 pos val Function definitions for the eight defined attribute occurrences. B pos val 3 2

p: B ® D 3 8 D B pos val B.pos := 1 pos val B.val := D.val 2 0 2 2 D.pow := 0 B q: B ® D B pos val 1 2 1 D pos val B1.pos := B2.pos+1 1 2 B1.val := B 2.val +D.val 1 0 B D.pow := B2.pos D r: D ® 0 D.val := 0 0 pos val s: D ® 1 D 0 0 D.val := 2 D.pow 1 Evaluation of parse tree for 1010 0 Chapter 3: Semantics 27 Chapter 3: Semantics 28

Dynamic Semantics Dynamic Semantics

Semantics of a programming language is Another way to view programming the definition of the meaning of any meaning is to start with a formal program that is syntactically valid. specification of what a program is intuitive idea of programming meaning: supposed to do, and then rigorously “whatever happens in a (real or model) prove that the program does that by computer when the program is executed. ” using a systematic series of logical steps. n A precise characterization of this idea is called operational semantics. n This approach evokes the idea of axiomatic semantics.

Chapter 3: Semantics 29 Chapter 3: Semantics 30

5 Dynamic Semantics: advantages Dynamic Semantics and disadvantages A third way to view the semantics of a Operational Semantics programming language is to define the n Advantage of representing program meaning of each type of statement that meaning directly in the code of a real (or occurs in the (abstract) syntax as a state- simulated) machine. transforming mathematical function. n Potential weakness, since the definition of n The meaning of a program can be expressed semantics is confined to a particular as a collection of functions operating on the architecture (either real or abstract). program state. Virtual machine also needs a semantic n This approach is called denotational description, which adds complexity and can semantics. lead to circular definitions.

Chapter 3: Semantics 31 Chapter 3: Semantics 32

Dynamic Semantics: advantages Operational Semantics and disadvantages Axiomatic semantics is useful in the exploration Provides a definition of program meaning of formal properties of programs. by simulating the program’s behavior on a n Programmers who must write provably correct machine model that has a very simple programs from a precise set of specification are particularly well-served by this semantic style. (through not necessarily realistic) Denotational semantics is valuable because its instruction set and memory organization. functional style brings the semantic definition of Definition of the virtual computer can be a language to a high level of mathematical described using an existing programming precision language or a virtual computer (idealized n Language designers obtain a functional definition of the meaning of each language construct that is computer). independent of any particular machine architecture.

Chapter 3: Semantics 33 Chapter 3: Semantics 34

Operational Semantics: process Operational Semantics: process Change in the state of the machine (memory, The process: registers, etc) defines the meaning of the n Identify a virtual machine (an idealized statement. computer). The operational semantics of a high-level n Build a translator (translates source code to language can be described using a virtual the machine code of an idealized computer). computer. n Build a simulator for the idealized computer. n A pure hardware is too expensive.

n A pure software interpreter has also problems: Operational semantics is sometimes called Machine-dependent transformational semantics, if an existing Difficult to understand programming language is used in place of n A better alternative: a complete computer simulation. the virtual machine.

Chapter 3: Semantics 35 Chapter 3: Semantics 36

6 Operational Semantics: automaton Operational Semantics: automaton

n A set of formally defined operations used to Automaton could be used as a virtual specify how the internal state of the automaton machine: may change, n More complex that the simple automata Corresponds to the execution of one instruction in models used in the study of syntax and parsing the program.

Automaton has n A second part of the definition specifies how a

n Internal state that corresponds to the internal program text is translated into an initial state state of the program when it its executing; for the automaton The state contains all the values of the variables, From this initial state, the rules defining the the executable program, and various system- automaton specify how the automaton moves from defined housekeeping data structures. state to state until a final state is reached.

Chapter 3: Semantics 37 Chapter 3: Semantics 38

Operational Semantics: process Operational Semantics: evaluation

Example: Advantages:

n May be simple, intuitive for small examples/ Pascal statement Operational Semantics n Good if used informally. (lower level) for i := x to y do movi, r1 n Useful for implementation. begin mov y, r2 Disadvantages: … jmpifless(r2,r1,out) end … n Very complex for large programs.

n Depends on programming languages of lower levels Operational Semantics (not mathematics)

i := x Uses: loop: if i > y goto out n Vienna Definition Language (VDL) used to define PL/I … (Wegner, 1972). i := i + 1 goto loop n Compiler work out: … Chapter 3: Semantics 39 Chapter 3: Semantics 40

Axiomatic Semantics Axiomatic Semantics

Programmers: confirm or prove that a program • Example: prove mathematically that the does what it is supposed to do under al C/C++ function Max actually computes as circumstances its result the maximum of its two Axiomatic semantics provides a vehicle for parameter: a and b. developing proofs that a program is “correct”. • Calling this function one time will obtain an answer for a particular a and b, such as 8 and 13. But the parameters a and b define a wide range of integers, so calling it several times with all the different values to prove its correctness would be an infeasible task.

Chapter 3: Semantics 41 Chapter 3: Semantics 42

7 Axiomatic Semantics Axiomatic Semantics: assertions

• Construct a to prove the correctness • The logical expressions used in axiomatic of a program semantics are called assertions. • The meaning of a statement is defined by the • Precondition: an assertion immediately result of the logical expression that precedes preceding a statement that describes the and follows it. constraints on the program variables at that • Those logical expressions specifies constraints point. on program variables. • Postcondition: an assertion immediately • The notation used to describe constraints is following a statement that describes the calculus. new constraints on some variables after the execution of the statement.

Chapter 3: Semantics 43 Chapter 3: Semantics 44

Axiomatic Semantics: weakest Axiomatic Semantics: assertions precondition • Example • It is the least restrictive precondition that will sum = 2 * x + 1 { sum > 1 } guarantee the of the associated postcondition. • Preconditions and postconditions are enclosed in braces • Correctness proof of a program can be constructed if the weakest condition can be • Possible preconditions: computed from the given postcondition. { x > 10 } • Construct preconditions in reverse: { x > 50 } • From the postcondition of the last statement of the { x > 1000 } program generate the precondition of the previous statement. { x > 0 } • This precondition is the postcondition of the previous statement, and so on.

Chapter 3: Semantics 45 Chapter 3: Semantics 46

Axiomatic Semantics: weakest Axiomatic Semantics: assignment precondition statements

• The precondition of the first statement states the • Let x=E be a general assignment condition under which the program will compute the statement and its postconditions. desired results. Q • Correct program: If the precondition of the first • Precondition: P=Qx®E statement is implied by the input specification of the • P is computed as Q with all instance of x program. replaced by E • The computation of the weakest precondition can • Example be done using: a = b/2-1 {a<10} • Axiom: logical statement that is assumed to be true. Weakest precondition: substitute b/2-1 in the postcondition {a<10} • Inference rule: method of inferring the of one b/2-1 < 10 assertion on the basis of the values of other b < 22 assertions.

Chapter 3: Semantics 47 Chapter 3: Semantics 48

8 Axiomatic Semantics: assignment Axiomatic Semantics: assignment statements statements • General notation of a statement: {P} S {Q} • An assignment with a precondition and a • General notation of the assignment postcondition is a . • If the assignment axiom, when applied to the statement: {Qx®E}x = E {Q} postcondition and the assignment statement, produces • More examples: the given precondition, the theorem is proved. x = 2*y-3 {x>25} 2*y-3 > 25 • Example: y > 14 {x > 5} x = x-3 {x>0} Using the assignment axiom on x = x-3 {x>0} x = x+y-3 {x>10} x+y-3 > 10 {x > 3} y > 13-x {x > 5} implies {x > 3}

Chapter 3: Semantics 49 Chapter 3: Semantics 50

Axiomatic Semantics: sequences Axiomatic Semantics: sequences

• The weakest precondition cannot be • Example: described by an axiom (only with an y = 3*x+1; rule) x = y+3; • It depends on the particular kinds of statements in the sequence. {x < 10} • Inference rule: Precondition of last assignment statement • The precondition of the second statement is y < 7 computed. Used as postcondition of the first statement • This is used as the postcondition of the first 3*x+1 < 7 statement. • The precondition of the first element is the x < 2 precondition of the whole sequence.

Chapter 3: Semantics 51 Chapter 3: Semantics 52

Axiomatic Semantics: selection Axiomatic Semantics: selection • Example: • Inference rule: if (x > 0) y = y-1 • Selection statement must be proven for else y = y+1 both when the Boolean control expression {y > 0} is true and when it is . Axiom for assignment on the “then” clause y = y-1 {y > 0} • The obtained precondition should be used y-1 > 0 in the precondition of both the then and the y > 1 else clauses. Same axiom to the “else” clause y = y+1 {y > 0} y+1 > 0 y > -1 But {y > 1}Þ {y > -1} Precondition of the whole statement: {y > 1}

Chapter 3: Semantics 53 Chapter 3: Semantics 54

9 Axiomatic Semantics: evaluation Denotational Semantics

• Advantages: Most rigorous, abstract, and widely known • Can be very abstract. method. • May be useful in program correctness proofs. Based on recursive function . • Solid theoretical foundations. • Disadvantages: Originally developed by Scott and Strachery • Predicate transformers are hard to define. (1970). • Hard to give complete meaning. Key idea: define a function that maps a program • Does not suggest implementation. (a syntactic object) to its meaning (a semantic • Uses: object). • Semantics of Pascal. • Reasoning about correctness. n It is difficult to create the objects and mapping functions.

Chapter 3: Semantics 55 Chapter 3: Semantics 56

Denotational vs. Operational Denotational Semantics: evaluation

Advantages: Denotational semantics is similar to high- n Compact and precise, with solid mathematical level operational semantics, except: foundation.

n Machine is gone. n Provides a rigorous way to think about programs. n Can be used to prove the correctness of programs. n Language is mathematics (). n Can be an aid to language design. Differences: Disadvantages: n In operational semantics, the state changes n Requires mathematical sophistication are defined by coded algorithms for a virtual n Hard for programmers to use. machine Uses: n In denotational semantics, they are defined by n Semantics for Algol 60 rigorous mathematical functions. n Compiler generation and optimization Chapter 3: Semantics 57 Chapter 3: Semantics 58

Summary

Each form of semantic description has its place: Chapter 3 n Operational Informal Compiler work

n Axiomatic Attribute Grammars Reasoning about particular properties Proofs of correctness

n Denotational Formal definitions Probably correct implementations

Chapter 3: Semantics 59

10 Meaning Attribute Grammars

What is the semantics or meaning of the for specifying semantics based on expression: 2+3 context-free grammars (BNF). Used to solve some typical problems: n Its value: 5 n Type checking and type inference n Its type (type checker): int n Compatibility between procedure definition and call. n A string (infix-to-postfix translator): + 2 3 Associate attributes with terminals and The semantics of a construct can be any nonterminals. quantity or set of quantities associated Associate semantic functions with productions.

with the construct. n Used to compute attribute values.

Chapter 3: Semantics 61 Chapter 3: Semantics 62

Example: Evaluating arithmetic Attributes expressions A quantity associated with a construct. ::= + n X.a for attribute a of X (X is either a nonterminal or a terminal). ::= Attributes have values: ::= ::= * n Each occurrence of an attribute of an attribute in a parse tree has a value. ::= div Grammar symbols can have any number ::= of attributes. ::= ( ) ::= num

Chapter 3: Semantics 63 Chapter 3: Semantics 64

Example: 7*5 Attributes

val is the value of the digit . val = 35 At the root of the parse tree: Syntax symbols can return values (sort of output n . val has value 35 At the bottom-left: parameters) n . val has value 7 . val = 35 Attributes for terminal symbols: n Digits can return its numeric value n come with the symbol n the value of the token digit Attribute values for nonterminals: Nonterminal symbols can have also input . val = 7 * .val = 5 n Defined by semantic rules Attached to productions Decorated parse tree attributes. n Attributes attached to the nodes .val = 7 .val = 5 n Parameters that are passed from the “calling” production. number .val = 7 n base: number base (e.g. 10 or 2 or 16)

n val: returned value of the number

Chapter 3: Semantics 65 Chapter 3: Semantics 66

11 Information Flow Synthesized Attributes

inherited computed The values is computed from the values of available attributes of the children. synthesized Pass information up the parse tree (bottom-up propagation). S-attribute grammar uses only synthesized attributes ...... Example:

n Value of expressions

n Types of expressions

Chapter 3: Semantics 67 Chapter 3: Semantics 68

Inherited Attributes Example 1 Translating decimal numbers between 0 The values is computed from the values of and 99 into their English phrases. attributes of the siblings and parent. number phrase 0 zero Pass information down the parse tree (top- 10 ten 19 nineteen down propagation) or from left siblings to 20 twenty the right siblings 31 thirty one n Translations are based on each digit Example: 31: thirty, the translation of 3 on the left, and one, n Type information the translation of 1 on the right. Exceptions: n Where does a variable occur? LHS or RHS n 30 is thirty, not thirty zero

n 19: is nineteen, not ten nine

Chapter 3: Semantics 69 Chapter 3: Semantics 70

Example 1: Syntax Attribute Occurrences

::= Same attribute can be associated with different ::= symbols appearing in the same grammar rule. ::= Attribute occurrenceof a rule p is an of attributes and natural number ::= 0|1|2|3|4|5|6|7|8|9 representing the attribute a at position j in production p. Two disjoint subsets: ::= n Defined occurrences for a production: ::= The information flowing into a node of the parse tree. ::= n Used occurrences for a production The information flowing out a node of the parse tree. ::= 0|1|2|3|4|5|6|7|8|9

Chapter 3: Semantics 71 Chapter 3: Semantics 72

12 Used Attribute Occurrences Defined Attribute Occurrences

Rule: S?AB Rule: S?AB S A B S A B

synthesized Syn(S) Syn(A) Syn(B) synthesized Syn(S) Syn(A) Syn(B)

inherited In(S) In(A) In(B) inherited In(S) In(A) In(B)

• Set of inherited attributes of all the grammar symbols on • Set of synthesized attributes of all the grammar symbols the LHS plus the set of synthesized attributes of the RHS. on the LHS plus the set of inherited attributes of the RHS.

Chapter 3: Semantics 73 Chapter 3: Semantics 74

Semantic Function Example 1: Semantics

::= N.trans := spell(D.val) Define a semantic function for every ::= S.in ::= D.val defined occurrence in terms of the values N.trans ::= S.trans of used occurrences. ::= S.val:= if D.val = 0 then decade(S.in) Defined Used else if S.in £ 1 then spell(10*S.in +D.val) else decade(P.in) || spell(D.val) Rule 1 … … ::= 0 .val:= 0 … ::= 9 .val:= 9 Rule 2 … … Functions spell and decade: spell(1) = one, spell(2) = two, …, spell(19) = nineteen decade(0) = zero, decade(1) = ten, …, decade(9) = ninety Function definitions Chapter 3: Semantics 75 Chapter 3: Semantics 76

Example 2: Syntax Example 2: Semantics Decimal value of a binary number

::= ::= B.pos := 1 ::= B.val := D. val ::= 0 D.pow := 0 ::= 1 ::= B1.pos := B 2.pos + 1 B1.val := B2.val + D.val D.pow := B2.pos ::= ::= 0 D.val := 0 ::= ::= 1 D.val := 2D.pow ::= 0 ::= 1

Chapter 3: Semantics 77 Chapter 3: Semantics 78

13 Example 2: Sample Parse Tree Example 3: Syntax pos val Simple Assignment Statements 4 10 pos val B pos val 3 2 ::= = 3 8 ::= + D B pos val pos val ::= 2 2 2 0 ::= X | Y | Z pos val B 1 D pos val 1 2 1 0 ::= = B D ::= + 0 pos val ::= D 0 0 1 ::= X | Y | Z Evaluation of parse tree for 1010 0 Chapter 3: Semantics 79 Chapter 3: Semantics 80

Example 3: Semantics Attribute Grammars: Summary

::= = E.exp := V.act

::= + E.act = if (V1.act = int) and An attribute grammar is a context-free V2.act := int) then int grammar with two disjoint sets of else real attributes (inherited and synthesized) ::= E.act := E.exp and semantic functions for all defined ::= X | Y | Z V.act = … attribute occurrences.

Variables can be either real or integer. Both sides of an assignment different: type = real Same type on both sides of an assignment

Chapter 3: Semantics 81 Chapter 3: Semantics 82

Attribute Grammar: Process

1. EBNF 2. Attributes Chapter 3 • Identify the parameters of the syntax symbols. § Output attributes (synthesized) yield results. Operational Semantics § Input attributes (inherited) provide context. 3. Semantic functions

Chapter 3: Semantics 83

14 Operational Semantics: Dynamic Semantics advantages and disadvantages Semantics of a programming language is Operational Semantics

the definition of the meaning of any n Advantage of representing program program that is syntactically valid. meaning directly in the code of a real (or Intuitive idea of programming meaning: simulated) machine. “whatever happens in a (real or model) n Potential weakness, since the definition of computer when the program is executed. ” semantics is confined to a particular architecture (either real or abstract). n A precise characterization of this idea is Virtual machine also needs a semantic called operational semantics. description, which adds complexity and can lead to circular definitions.

Chapter 3: Semantics 85 Chapter 3: Semantics 86

Operational Semantics Process

Provides a definition of program meaning by The process: simulating the program’s behavior on a n Identify a virtual machine (an idealized machine model that has a very simple (through computer). not necessarily realistic) instruction set and n Build a translator (translates source code to memory organization. the machine code of an idealized computer). Definition of the virtual computer can be described using an existing programming n Build a simulator for the idealized computer. language or a virtual computer (idealized Operational semantics is sometimes called computer). transformational semantics, if an existing Change in the state of the machine (memory, programming language is used in place of registers, etc) defines the meaning of the statement. the virtual machine. Chapter 3: Semantics 87 Chapter 3: Semantics 88

Example Notation

State of a program s:

n A set of pairs that represent all active variables Pascal statement Operational Semantics and their current assigned values at some stage during (lower level) the program’s execution. for i := x to y do movi, r1 s= { , , } begin mov y, r2 … jmpifless(r2,r1,out) After y = 2 * z + 3 s= { , , } end … After w = 4 s= { , , , } State transformation of these type of assignments Operational Semantics can be represented by a function called overriding

i := x union U loop: if i > y goto out n s1 = { , , } … i := i + 1 n s2 = { , } goto loop n s1 U s2 = { , , , } out: … Chapter 3: Semantics 89 Chapter 3: Semantics 90

15 Notation Examples

Addition of two expressions s Þ s Þ Execution rule: (e1) v1 (e1) v1 s(e1 + e2) Þ v1 + v2 Assignment statement (s.target = s.source) conclusion s(s.source) Þ v s(s.target = s.source) Þ s U { }

n “If the premise is true, then the conclusion is n Suppose: assignment x = x +1, current state x=5 true” s(x) Þ 5 s(1) Þ 1 s(x+1) Þ 6 s(x = x+1) Þ {…, , …} U { }

Chapter 3: Semantics 91 Chapter 3: Semantics 92

Examples Examples

Conditionals (s = if (s.text) s.then else s.else) Loops (s = while (s.test) s.body )

s(s.test) Þ true s (s.body) Þ s1 s1(while(s.test)s.body) Þ s1 s(s.test) Þ true s(s.then) Þ s1 s(while (s.text) s.body) Þ s1 s(if(s.test)s.then else s.else) Þ s1 s(s.test) Þ false s( while (s.text) s.body) Þ s s(s.test) Þ false s(s.else) Þ s1

s(if(s.test)s.then else s.else) Þ s1

Chapter 3: Semantics 93 Chapter 3: Semantics 94

Evaluation

Advantages: n May be simple, intuitive for small examples/ Chapter 3 n Good if used informally.

n Useful for implementation. Disadvantages: n Very complex for large programs. Axiomatic Semantics n Depends on programming languages of lower levels (not mathematics) Uses:

n Vienna Definition Language (VDL) used to define PL/I (Wegner, 1972).

n Compiler work

Chapter 3: Semantics 95

16 Dynamic Semantics Axiomatic Semantics

Another way to view programming Programmers: confirm or prove that a meaning is to start with a formal program does what it is supposed to specification of what a program is do under al circumstances supposed to do, and then rigorously Axiomatic semantics provides a prove that the program does that by vehicle for developing proofs that a using a systematic series of logical program is “correct”. steps.

n This approach evokes the idea of axiomatic semantics.

Chapter 3: Semantics 97 Chapter 3: Semantics 98

Axiomatic Semantics Assertions

• Example: prove mathematically that the • The logical expressions used in axiomatic C/C++ function Max actually computes as semantics are called assertions. its result the maximum of its two • Precondition: an assertion immediately parameter: a and b. preceding a statement that describes the constraints on the program variables at that • Calling this function one time will obtain an point. answer for a particular a and b, such as 8 • Postcondition: an assertion immediately and 13. But the parameters a and b define a wide range of integers, so calling it several following a statement that describes the times with all the different values to prove its new constraints on some variables after the correctness would be an infeasible task. execution of the statement.

Chapter 3: Semantics 99 Chapter 3: Semantics 100

Assertions Weakest Precondition

• Example • It is the least restrictive precondition that will sum = 2 * x + 1 { sum > 1 } guarantee the validity of the associated postcondition. • Preconditions and postconditions are enclosed in braces • Correctness proof of a program can be constructed if the weakest condition can be • Possible preconditions: computed from the given postcondition. { x > 10 } • Construct preconditions in reverse: { x > 50 } • From the postcondition of the last statement of the { x > 1000 } program generate the precondition of the previous statement. { x > 0 } • This precondition is the postcondition of the previous statement, and so on.

Chapter 3: Semantics 101 Chapter 3: Semantics 102

17 Weakest Precondition Assignment Statements

• The precondition of the first statement states the • Let x=E be a general assignment condition under which the program will compute the statement and its postconditions. desired results. Q • Correct program: If the precondition of the first • Precondition: P=Qx®E statement is implied by the input specification of the • P is computed as Q with all instance of x program. replaced by E • The computation of the weakest precondition can • Example be done using: a = b/2-1 {a<10} • Axiom: logical statement that is assumed to be true. Weakest precondition: substitute b/2-1 in the postcondition {a<10} • Inference rule: method of inferring the truth of one b/2-1 < 10 assertion on the basis of the values of other b < 22 assertions.

Chapter 3: Semantics 103 Chapter 3: Semantics 104

Assignment Statements: examples Assignment Statements

• General notation of a statement: {P} S {Q} • An assignment with a precondition and a postcondition is a theorem.

• If the assignment axiom, when applied to the • More examples: postcondition and the assignment statement, produces the given precondition, the theorem is proved. • x = 4*y+5 { x>13 } • Example: {x > 5} x = x-3 {x>0} • X = y-3*6 { x>-5 } Using the assignment axiom on x = x-3 {x>0} {x > 3} • X = 2*y+3*x { x>10} {x > 5} implies {x > 3}

Chapter 3: Semantics 105 Chapter 3: Semantics 106

Sequences Sequences: examples

• The weakest precondition for a sequence • Example: cannot be described by an axiom (only with y = 3*x+1; an inference rule) x = y+3; {x < 10} • It depends on the particular kinds of statements in Precondition of last assignment statement the sequence. y < 7 • Inference rule: Used as postcondition of the first statement • The precondition of the second statement is 3*x+1 < 7 computed. x < 2 • This is used as the postcondition of the first • Other example: statement. a = 3*(2*b+a); • The precondition of the first element is the b = 2*a -1 precondition of the whole sequence. { b > 5 }

Chapter 3: Semantics 107 Chapter 3: Semantics 108

18 Selection Selection: example • Example: • Inference rule: if (x > 0) y = y-1 • Selection statement must be proven for else y = y+1 both when the Boolean control expression {y > 0} is true and when it is false. Axiom for assignment on the “then” clause y = y-1 {y > 0} • The obtained precondition should be used y-1 > 0 in the precondition of both the then and the y > 1 else clauses. Same axiom to the “else” clause y = y+1 {y > 0} y+1 > 0 y > -1 But {y > 1}Þ {y > -1} Precondition of the whole statement: {y > 1}

Chapter 3: Semantics 109 Chapter 3: Semantics 110

Evaluation

• Advantages: • Can be very abstract. Chapter 3 • May be useful in program correctness proofs. • Solid theoretical foundations. • Disadvantages: • Predicate transformers are hard to define. Denotational Semantics • Hard to give complete meaning. • Does not suggest implementation. • Uses:

• Semantics of Pascal. • Reasoning about correctness.

Chapter 3: Semantics 111

Dynamic Semantics Denotational Semantics

A third way to view the semantics of a Most rigorous, abstract, and widely known programming language is to define the method. meaning of each type of statement that Based on recursive function theory. occurs in the (abstract) syntax as a state- Originally developed by Scott and Strachery transforming mathematical function. (1970). n The meaning of a program can be expressed Key idea: define a function that maps a program as a collection of functions operating on the program state. (a syntactic object) to its meaning (a semantic object). n This approach is called denotational semantics. n It is difficult to create the objects and mapping functions.

Chapter 3: Semantics 113 Chapter 3: Semantics 114

19 Denotational vs. Operational Denotational Semantics: evaluation

Advantages: Denotational semantics is similar to high- n Compact and precise, with solid mathematical level operational semantics, except: foundation.

n Machine is gone. n Provides a rigorous way to think about programs. n Can be used to prove the correctness of programs. n Language is mathematics (lambda calculus). n Can be an aid to language design. Differences: Disadvantages: n In operational semantics, the state changes n Requires mathematical sophistication are defined by coded algorithms for a virtual n Hard for programmers to use. machine Uses: n In denotational semantics, they are defined by n Semantics for Algol 60 rigorous mathematical functions. n Compiler generation and optimization Chapter 3: Semantics 115 Chapter 3: Semantics 116

Summary

Each form of semantic description has its place:

n Operational Informal descriptions Compiler work

n Axiomatic Reasoning about particular properties Proofs of correctness

n Denotational Formal definitions Probably correct implementations

Chapter 3: Semantics 117

20