Syntax is aboutfaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Advanced... · Web viewFor most...

69
Advanced Semantics What is Semantics? Syntax is about form semantics is about meaning o how the programs behave when executed on computers o Boundary between syntax & semantics is not always clear Syntax vs. Semantics in Regular English Wrong Syntax, ‘Correct Semantics’ “I is a University Student” Correct Syntax, Wrong Semantics Sentence = Subject + verb + object “A rectangle loves chicken rice” Wrong Syntax, Wrong Semantics “House worm chair long fast twenty-two” Correct Syntax, Correct Semantics Language Semantics we want to “model” the language, see what the language can do appends semantic information onto the BNF description of a language since BNF can not handle everything about a language 1

Transcript of Syntax is aboutfaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Advanced... · Web viewFor most...

Advanced SemanticsWhat is Semantics?

Syntax is about form semantics is about meaning

o how the programs behave when executed on computerso Boundary between syntax & semantics is not always clear

Syntax vs. Semantics in Regular EnglishWrong Syntax, ‘Correct Semantics’

“I is a University Student”

Correct Syntax, Wrong SemanticsSentence = Subject + verb + object

“A rectangle loves chicken rice”

Wrong Syntax, Wrong Semantics“House worm chair long fast twenty-two”

Correct Syntax, Correct Semantics

Language Semantics we want to “model” the language, see what the language can do appends semantic information onto the BNF description of a language since

BNF can not handle everything about a language Tools on describing the semantics

o informal Manuals, Tutorials, FAQS, etc..

o formal There are three approaches to defining “deeper” semantics

Operational semantics Axiomatic semantics Denotational semantics

1

Motivation of Creating deeper Semantics Capturing what a program in some programming language means is very

difficult We can’t really do it in any practical sense

o For most work-a-day programming languages (e.g., C, C++, Java, Perl, C#, Python)

o For large programs

Why even do this stuff??1. How to convey to the programming language compiler/interpreter writer what

it should do?a. Natural language may be too ambiguous

2. How to know that the compiler/interpreter did the right thing when it executed our code?

a. We can’t answer this w/o a very solid idea of what the right thing is3. How to be sure that the program satisfies its specification?

a. Maybe we can do this automatically if we know what the program means

Describing a Language #1 - Program Verification

another way of describing a language think of it as debugging, that the program does indeed behaves the way it is

required while testing hardware too!!! is the process of formally proving that the computer program does exactly

what is stated in the program’s specification can be done for simple programming languages and small or moderately sized

programs requires a formal specification for what the program should do

o its inputs and the actions to take or output to generate given the inputso That’s a hard task in itself!

There are applications where it is worth ito use a simplified programming languageo work out formal specs for a programo capture the semantics of the simplified PL ando do the hard work of putting it all together and proving program

2

correctness. Like…

o Security and encryptiono Financial transactionso Applications on which lives depend (e.g., healthcare, aviation)o Expensive, one-shot, un-repairable applications (e.g., Martian rover)o Hardware design (e.g. Pentium chip)

Applications that needed better verification Double Int kills the Ariane 5

o European Space Agency project in 1996o 10 years and $7B to produceo Ariane 5, a giant rocket capable of hurling a pair of three-ton satellites

into orbit with each launch and intended to give Europe supremacy in the commercial space business

o the rocket exploded in less than a minute into its maiden voyageo computer program trying to stuff a 64-bit number into a 16-bit space.

Patriot Missileo Clock inside hardware malfunction

Intel Pentium Bugo In the mid 90’s a bug was found in the floating point hardware in Intel’s

latest Pentium microprocessoro Unfortunately, the bug was only found after many had been made and

soldo The bug was subtle, effecting only the ninth decimal place of some

computationso But users caredo Intel had to recall the chips, taking a $500M write-off

The correct value is

However, the value returned by the flawed Pentium would be incorrect beyond four significant digits[9]:

3

4

Overall goals of Program Verification While automatic program verification is a long range goal …

o Which might be restricted to applications where the extra cost is justified should try to

o design programming languages that help, rather than hinder, our ability to make progress in this area.

o continue research on the semantics of programming languages o continue research the ability to prove program correctness

Describing a Language #2 - Static Semantics Static semantics covers some language features difficult or impossible to

handle in a BNF/CFG It’s also a mechanism for building a parser that produces an abstract syntax

tree of its input Attribute grammars are just one common technique Categories attribute grammars can handle

o Context-free but cumbersome (e.g., type checking)o Non-context-free (e.g., variables must be declared before they are used)

5

Parse tree vs. abstract syntax tree Parse trees follow a grammar and usually have many nodes that are artifacts

of how the grammar was written An abstract syntax tree (AST) eliminates useless structural nodes It uses nodes corresponding to constructs in the programming language and is

easier to interpret or generate code from it

Parse tree vs. abstract syntax tree(1 + 2 + 3)

Abstract Tree for PHP code

6

Attributes of a Grammar much like an attribute of an HTML tag, it describes a property of this < >

symbol two types of attributes

o synthesized pass semantic information up the parse tree

o inherited pass semantic information down the parse tree

called “AG” in notes for short

7

AGs Motivation

o CFGs can’t describe all of the syntax of programming languageso Additions to CFGs to annotate the parse tree with some “semantic” info

Example that needs an Attribute additiono L = { anbncn | n>=1 }

we want the same number of a’s b’s and c’so we can get that, BUT, was can also get what we don’t want!!

Grammar Attempt for anbncn (Example 1)<letter sequence> ::= <a_Sequence> <b_Sequence> <c_Sequence><a_Sequence> ::= a | <a_Sequence> a<b_Sequence> ::= b | <b_Sequence> b<c_Sequence > ::= c | <c_Sequence> c

CFG just isn’t enough!! Parse Tree Proofaaabbbccc aaabbbbcc

the grammar itself has no control over how many of each character, we need more control!!

we get the CFG Languageo a+b+c+ = { akbmcn | k>=1, m>=1, n>=1 }

Will show how we fix this later!! Primary value of AGs

o Static semantics specificationo Compiler design (static semantics checking)

8

AG Example #2 - Matching Strings Example Ada Procedure

procedure A_Test (A, B: in Integer; C: out Integer) isbegin C := A + B;end A_Test;

Semantics Rules for Ada Procedure(Matching Strings)

Syntax rule: <proc_def> procedure <proc_name>[1]<proc_body>

end <proc_name>[2];

Predicate: <proc_name>[1].string == <proc_name>[2].string

Descriptions: Syntax Rule

o same as the EBNF/BNF we are used too bolded items are reserved words

[ ]o more than one occurrence

so the proc_name is the same twice or should be the same twice

o check predicate Predicate

o syntax will only work if the predicate case is trueo think of it as a fail safe

9

AG Grammar setup “” part of grammar “” is assigned in order:

o syntax must match parse tree nodes start bottom up

o predicate must be true in order to do rest of steps below

o semantics some attribute is usually assigned a value

AG Completion Steps (Suggested)1. Create parse tree for syntax2. Make sure syntax is correct first!!3. Start from root:

a. if any inherited attributes, pass downb. otherwise start from bottom left of tree to right

AG Example #3 – Type Checking variable names can only be A, B and C respectfully RHS of the assignment can either be:

o a variableo or an expression of the form of a variable added to another variable

variables can be of two types: real or int if two variables on right side, they do not need to be of the same type

o if they do not match, then the overall result is a real number the type on the LHS of the assignment must match the type on the RHS

o so the operands on the RHS can be mixed, but the assignment is valid only if the target AND the value resulting from evaluating the RHS have the same type

10

Syntax Portion of Grammar

<assign> -> <var> = <expr><expr> -> <var> + <var> | <var><var> A | B | C

AG for Simple Assignment

Syntax rule #1: <assign> <var> = <expr>Semantic rules: <expr>.expected_type (inherited) <var>.actual_type (synthesized)

Syntax rule #2: <expr> <var>[2] + <var>[3] // remember <var>[1] is the resultSemantic rules: // waits for if/else answer below

if ( <var>[2].actual_type == int) && ( <var>[3].actual_type == int))<expr>.actual_type then int

else then real

Predicate: <expr>.actual_type (synthesized) == <expr>.expected_type (inherited)

Syntax rule #3: <expr> <var>Semantic rules: <expr>.actual_type <var>.actual_typePredicate: <expr>.actual_type (synthesized) == <expr>.expected_type (inherited)

Syntax rule #4: <var> A | B | CSemantic rule: <var>.actual_type (synthesized) lookup (<var>.string)

11

Actual Type vs. Expected Type and Lookup actual_type

o synthesized attributeo used by <expr> and <var> in this exampleo used to store actual data type (int or real) of the variable or expression

if variable, then instrinsic if expression, it is determined from the child node or children

nodes expected_type

o inherited attributeo used by <expr>o used to store the type (int or real) that is expected for the expression

as determined by the type of the variable on the LHS of assignment lookup( )

o Compilers usually maintain a “symbol table” where they record the names of procedures and variables along with type information.

o Looking up this information in the symbol table is a common operation.

AG Example #3 – At work uses procedure and grammar (with rules) above

Parse Tree for A (real) = A (real) + B (int)

Label Attributes for A (real) = A (real) + B (int)12

attributes are located in original Grammar’s Semantic rules

13

Check Semantics (data type check) for A (real) = A (real) + B (int)

This is OK!! real (left side) can be assigned to real (right)

AG for Simple AssignmentSyntax rule #1: <assign> <var> = <expr>Semantic rules: <expr>.expected_type (inherited) <var>.actual_type (synthesized)

Syntax rule #2: <expr> <var>[2] + <var>[3] // remember <var>[1] is the resultSemantic rules: // waits for if/else answer below

if ( <var>[2].actual_type == int) && ( <var>[3].actual_type == int))<expr>.actual_type then int

else then real

Predicate: <expr>.actual_type (synthesized) == <expr>.expected_type (inherited)

Syntax rule #3: <expr> <var>Semantic rules: <expr>.actual_type <var>.actual_typePredicate: <expr>.actual_type (synthesized) == <expr>.expected_type (inherited)

Syntax rule #4: <var> A | B | CSemantic rule: <var>.actual_type (synthesized) lookup (<var>.string)

Now try A(int) = A(int) + B (real)

14

Parse Tree for A (int) = A (int) + B (real)

Label Attributes for A (int) = A (int) + B (real)

attributes are located in original Grammar’s Semantic rules

15

Check Semantics (data type check) forA (int) = A (int) + B (real)

so int (left side) cannot be assigned to a “real” number

16

Fixing AG Ex #1 (part 1 – Using Synthesis) using what we know to fix it Synthesis in a nutshell

o https://youtu.be/vnJ22buRy3s

Create a similar grammar with semantic rules that would enable the calculation from binary to decimal. Use the tree below as a hint:

Creating a Grammar with Semantic RulesIn General for value 1101

Answerb:

17

Grammar Attempt for anbncn (Example 1)<letter sequence> ::= <aSequence> <bSequence> <cSequence><aSequence> ::= a | <aSequence> a<bSequence> ::= b | <bSequence> b<cSequence > ::= c | <cSequence> c

Solution for Grammar aboveo synthesized attribute Size that is associated with the non-terminals

<asequence>, <bsequence>, and <csequence>. o add the condition that, at the root of the tree, the Size attribute for each

of the letter sequences has the same value. o If a character sequence consists of a single character, Size is set to 1; if it

consists of a character sequence followed by a single character, Size for the parent character sequence is the Size of the child character sequence plus one.

o We have added the necessary attribute assignments and conditions to the grammar shown below. Notice that we differentiate a parent sequence from a child sequence by adding subscripts to the nonterminal symbols.

18

AG Ex #1 Solution Using SynthesisDomain of Size = Positive Integers

Syntax rule #1: <lettersequence> ::= <asequence> <bsequence> <csequence>Predicate: Size (<asequence>) == Size (<bsequence>) == Size (<csequence>)

Syntax rule #2: <asequence> ::= aSize (<asequence>) 1| <asequence>[2] aSize (<asequence>) Size (<asequence>[2]) + 1

Syntax rule #3: <bsequence> ::= bSize (<bsequence>) 1| <bsequence>[2] bSize (<bsequence>) Size (<bsequence>[2]) + 1

Syntax rule #4: <csequence> ::= cSize (<csequence>) 1| <csequence>[2] cSize (<csequence>) Size (<csequence>[2]) + 1

** Notice the grouping!!! (Watch for the |)

19

AG Exercise #1aaabbcc

What was size for a,b,c respectfully?Did the sentence work with the AG? (True/False, but why too)

20

AG Exercise #2aaaabbbbcccc

Did the sentence work with the AG? (True/False, but why too)Where in the Grammar are we able to pull the “Size” from the previous child node?

21

Answer to AG Exercise #2(just aaabbbccc instead)

22

Fixing AG #1 – Inheritance and Synthesis remember, data (and how it is solved) is passed down Inherited

o https://youtu.be/hS0KWxxwmFQ In this scenario we:

o attach a synthesized attribute Size to <a seq>o attach an inherited attributes InSize to <b seq> and <c seq>.

AG Ex #1 Solution both Inherited & Synthesis

Syntax rule #1: <string> ::= <a seq> <b seq> <c seq>InSize(<b seq>) Size(<a seq>)InSize(<c seq>) Size(<a seq>)

Syntax rule #2: <a seq> ::= aSize(<a seq>) 1| <a seq>[2] aSize(<a seq>) Size(<a seq>[2])+1

Here the value of the child is incremented by one and passed to the parent.

Syntax rule #3: <b seq> ::= bpredicate:InSize(<b seq>) = 1 // first b is set to 1!!!| <b seq>[2] bInSize(<b seq>[2]) InSize(<b seq>)-1

inherited attribute that is passed from parent to child shows that the value is decremented by one each time it is passed from the parent sequence to the child sequence. When the sequence is a single character, we check that

the inherited size attribute value is one.

Syntax rule #4: <c seq> ::= cpredicate:InSize(<c seq>) = 1 // first c is set to 1!!!| <c seq>[2] cInSize(<c seq>[2]) InSize(<c seq>)-1

23

Inherited AG Parse Tree for aaabbbccc

Please note, the “A” side is completed first to get the count or Size using Synthesis!

24

Inherited AG Parse Tree for aaabbbbcc

How are attribute values computed? If all attributes were inherited, the tree could be decorated in top-down order If all attributes were synthesized, the tree could be decorated in bottom-up

order In many cases, both kinds of attributes are used, and it is some combination of

top-down and bottom-up that must be used

AG in a nutshell AGs are a practical extension to CFGs that allow us to annotate the parse tree

with information needed for semantic processingo e.g., interpretation or compilation

We call the annotated tree an abstract syntax treeo It no longer just reflects the derivation

AGs can move information from anywhere in abstract syntax tree to anywhere else in a controlled wayo Needed for no-local syntactic dependencies (e.g., Ada example) and for

semantics

25

Static vs. Dynamic Semantics Attribute grammar is an example of static semantics (e.g., type checking) that

don’t reason about how things change when a program is executed Understanding what a program means often requires reasoning about how, for

example, a variable’s value changes Dynamic semantics tries to capture this

o proving that an array index will never be out of its intended range

26

Dynamic Semantics in General No single widely acceptable notation or formalism for describing dynamic

semantics Here are three approaches we’ll briefly examine:

o Operational semanticso Axiomatic semanticso Denotational semantics

How might we define what expression in a language mean?o One approach is to give a general mechanism to translate a sentence in

L into a set of sentences in another language or system that is well defined

For example:o Define the meaning of computer science terms by translating them in

ordinary Englisho Define the meaning of English by showing how to translate into Frencho Define the meaning of French expression by translating into

mathematical logic

Operational SemanticsOperational Semantics Overview

definitionso describe the meaning of a program in language L by specifying how

statements effect the state of a machine (simulated or actual) when 27

executed.o the purpose of operational semantics is to describe how a computation is

performed. The change in the state of the machine (memory, registers, stack, heap, etc.)

defines the meaning of the statemento operations on hypothetical machine (simulation) or “Virtual machine”

Similar in spirit to the notion of a Turing Machine and also used informally to explain higher-level constructs in terms of simpler ones.

Example Operation Semanticsc statement operational semantics for(e1;e2;e3) e1;{<body>} loop: if e2=0 goto exit

<body> e3; goto loop

exit:

Alan Turing and his Machine The Turing machine is an abstract machine introduced in 1936 by Alan

Turingo Alan Turing (1912 –54) was a British mathematician, logician,

cryptographer, considered a father of modern computer science It can be used to give a mathematically precise definition of algorithm or

'mechanical procedure’ Concept widely used in theoretical computer science, especially in complexity

theory and the theory of computation

28

First Real Example of an DFSM Diagram

The machine has 4 states (0, 1, 2, and 3, written as q0, q1, q2, q3).Its start state is q0. The double-circled state is the accept state, which in this case also happens to be q0

input string is "01", machine accepts the stringinput string is "110".  ends in a non-accept state, machine does not accept

29

Requirements for Operational Semantics To use operational semantics for a high-level language, a virtual machine is

needed A hardware pure interpreter is too expensive A software pure interpreter also has problems

o The detailed characteristics of the particular computer makes actions hard to understand

o Such a semantic definition would be machine-dependent A better alternative: a complete computer simulation

o Build a translator (translates source code to the machine code of an idealized computer)

o Build a simulator for the idealized computer Evaluation of operational semantics:

o Good if used informallyo Extremely complex if used formally (e.g. VDL)

The basic idea is to define a language’s semantics in terms of a reference language, system or machine

It’s use ranges from the theoretical (e.g., lambda calculus) to the practical (e.g., Java Virtual Machine)

The Lambda Calculus The first use of operational semantics was in the lambda calculus

o A formal system designed to investigate function definition, function application and recursion

o Introduced by Alonzo Church and Stephen Kleene in the 1930s The lambda calculus can be called the smallest universal programming

language It’s widely used today as a target for defining the semantics of a programming

language The lambda calculus consists of a single transformation rule (variable

substitution) and a single function definition scheme The lambda calculus is universal in the sense that any computable function

can be expressed and evaluated using this formalism We’ll revisit the lambda calculus later in the course The Lisp language is close to the lambda calculus model The lambda calculus

30

o introduces variables ranging over valueso defines functions by (lambda) abstracting over variableso applies functions to valueso The Visual C++ compiler binds a lambda expression to its captured

variables when the expression is declared instead of when the expression is called.

o basically you create a function “on the fly” without creating a separate procedure, it is local!!!

Lambda Calculus Example in C++// declaring_lambda_expressions2.cpp// compile with: /EHsc#include <iostream>#include <functional>

int main(){ using namespace std;

int i = 3; int j = 5;

// The following lambda expression captures i by value and // j by reference. function<int (void)> f = [i, &j] { return i + j; };

// Change the values of i and j. i = 22; j = 44;

// Call f and print its result. cout << f() << endl;}

The lambda expression that captures the local variable i by value and the local variable j by reference.Because the lambda expression captures i by value, the reassignment of i later in the program does not affect the result of the expression.However, because the lambda expression captures j by reference, the reassignment of j does affect the result of the expression.

31

Axiomatic Semantics Based on formal logic (first order predicate calculus) Original purpose: formal program verification Approach: Define axioms and inference rules in logic for each statement type

in the language (to allow transformations of expressions to other expressions) The expressions are called assertions and are either

o Preconditions: An assertion before a statement states the relationships and constraints among variables that are true at that point in execution

o Postconditions: An assertion following a statement It is a good tool for correctness proofs, and an excellent framework for

reasoning about programs It is much less useful for language users and compiler writers

Meaning of Logic Symbols⇒ implies (if … then …)⇔ if and only if, is necessary and sufficient for, is equivalent to∧ conjunction between propositions, means “and”∨ disjunction between propositions, means “or”∀ universal quantifier, means "for every", "for each", "for all"∃ existential quantifier, means “there exists”∴ therefore∈ is an element of∉ is not an element of not

32

Axiomatic Semantics using Floyd Hoare Logic Axiomatic semantics is based on Hoare Logic

o named after computer scientist Sir Tony Hoare Based on triples that describe how execution of a statement changes the state

of the computation

Hoare Logic Setup

P is a logical statement of what’s true before executing S (Pre-Condition)Q is a logical expression describing what’s true after (Post-Condition)

Since all depend on one another, we could solve for o Q

Given P and S determine Qo P

Given S and Q determine Po We will need this property to solve some conditions

33

Weakest Precondition (WP) A weakest precondition is the least restrictive precondition that will guarantee

the post-conditiono The overall goal is to determine the preconditions {P?} that satisfies the

post condition {Q} using the statement {S} in between.

Symbol Definitions (Syntactic Conventions)Symbol Meaning ExampleV ; V1; ... ; Vn arbitrary variables X, R, Q etc…E;E1; ...;En arbitrary expressions (or terms) X + 1; which denote values

(usually numbers)S; S1; ...; Sn arbitrary statements X < Y ;X2 = 1 (T or F)C;C1; ...;Cn arbitrary commands of our programming languageB Condition (x < y)P Pre-Condition {x< 3}Q Post-Condition { y < 12 }

Complete Weakest Condition Examples (Assignment)

{x>0} x = x+1 {x>1}

(note, since x is the ONLY variable, and is the one “assigned”, we solve for x)

DO A NUMBER LINE EXERCISE HERE!!! (Will cover restrictions)

Different problems in solving for wpo by axiom

assignmento by inference

sequence selection (Conditions) loops

axiomo a logical statement that is assumed to be true

inferenceo inferring the truth of one assertion on the basis of values of other

assertions

34

WPs for Assignments one line assignment operators, form x := e in a programming language.

o {Qx->E} x := E {Q} Where Qx->E means the result of replacing all occurrences of x with

E in QHints for Solving

{P???} A = B {Q????}

A is the PostCondition of the equationB is the Pre-condition of the equation

Solving for the WP #1 (Assignment)

{P?} x = x+1 {x>1}-- OR --

{P?} x(total) = x(i)+1 {x>1}

(which you know the answer already)

Solve for variable in pre-condition portion of equation (x):

{P?} x = x + 1; { x > 1}x + 1 > 1{ x > 0 }

Solve for weakest condition:{ x > 0 } (since 1 is >, 1 is ok!!)

Identify other possible preconditions:{ x > 1 }{ x > 2 }{ x > 3 } // all preconditions, but not the weakest!! (infinite # of precons!!)…

Solve for weakest precondition:

35

{P?} sum = 2 * x + 1 { sum > 1} Answer: {P?} a = b / 2 – 1 { a < 10 } Answer: {P?} x = 2 * y – 3 { x > 25 } Answer:

WP for Sequences several line sequences for a sequence S1 ; S2; … Sn:

WP for SequencesSetup Example

{P1} S1 {P2}{P2} S2 {P3}

{x < 2}y = 3 * x + 1;x = y + 3;{x < 10}

the inference rule is:

{P1} S1 {P2}, {P2} S2 {P3} {P1} S1; S2 {P3}

in a nutshell, to get the ENTIRE sequence’s precondition, the precondition of the second statement {S2} is computed.o this is then used as the postcondition for the first statement {S1} and the

whole sequence

36

Solving for the WP #1 (Sequence)

{P? }y = 3 * x + 1;x = y + 3;{x < 10}

(again, you know the answer already)

1. Solve for {P?} for last statement {Sn}. (using assignment model of solving)

{P?} x = y + 3; {x < 10}y + 3 < 10;{ y < 7 }

2. Use newly acquired and use for POST condition of previous statement {Sn-1}

{P??} y = 3 * x + 1 { y < 7 }3 * x + 1 < 7x < 2

Solve the wp for the following:{P?}a = 2 * b + 1;b = a – 3{b < 0} Answer:

37

WP for Conditions Here’s a rule for a conditional statement

WP for ConditionsSetup Example

{ B P} S1 {Q}, { B P} S2 {Q} {P} if B then S1 else S2 {Q}

// remember B is for condition

{y>1}If x>0 then y=y-1else y=y+1{y>0}

And an example of its use for the statemento {P} if x>0 then y=y-1 else y=y+1 {y>0}

So the weakest precondition P can be deduced as follows:o The postcondition of S1 and S2 is Q.o The weakest precondition of S1 is x>0 y>1 and for S2 is x<=0 y>-1o The rule of consequence and the fact that y>1 y>-1 supports the

conclusiono That the weakest precondition for the entire conditional is y>1 .

38

Solving for the WP #1 (Conditions)

{p?}If x>0 then y=y-1else y=y+1{y>0}

(again, you know the answer already)

1. Solve for {P?} for first statement in then clause {Sn} and the Q. (using assignment model of solving)

{P?} y = y - 1 {y > 0}y - 1 > 0;{ y > 1 }

2. Solve for each else in the structure using the same Q

{P?} y = y + 1 {y > 0}y + 1 > 0;{ y > -1 }

3. When all conditions are completed, pick:a. highest value needed if x > ?? form as your Pb. pick lowest value needed if x < ?? form as your Pc. pick the stronger (more restrictive) of the two pre-conditions.

{P?} = { y > 1 }

39

Compute the weakest precondition for the following if statement:{ P???}if (a == b) then b = 2 * a + 1;else b = 2 * a;{b > 1}

Answer:

WP for (while) Loops number of iterations cannot always be determined if it is know, you can “unroll” it like a sequence the first goal to find the weakest condition is to find an assertion called a

“loop invariant”

For the loop construct {P} while B do S end {Q}

the inference rule is:

{I B} S {I} _ {I} while B do S {I B}

where I is the loop invariant, a proposition necessarily true throughout the loop’s executiono I is true before the loop executes and also after the loop executeso B is false after the loop executes

40

Loop Invariants in While Loops A loop invariant I must meet the following conditions:

1. P => I (the loop invariant must be true initially, in order to run the loop) 2. {I} B {I} (evaluation of the Boolean must not change the validity of I)3. {I and B} S {I} (I is not changed by executing the body of the loop)4. (I and (not B)) => Q (if I is true and B is false, Q is implied)5. The loop terminates (this can be difficult to prove)6. The loop invariant I is a weakened version of the loop postcondition, and

it is also a precondition. I must be weak enough to be satisfied prior to the beginning of the loop, but

when combined with the loop exit condition, it must be strong enough to force the truth of the postcondition

Finding WP for Single Assignment While Loops Homework!!!

FYI - Sectionstuff we might get to, you need to read

AG by Definition Def: An attribute grammar is a CFG

o G=(S,N,T,P) A Grammar is formally defined by specifying four components. S is the start symbol N is a set of non-terminal symbols T is a set of terminal symbols P is a set of productions or rules

with the following additions:o For each grammar symbol x there is a set A(x) of attribute valueso Each rule has a set of functions that define certain attributes of the non-

terminals in the ruleo Each rule has a (possibly empty) set of predicates to check for attribute

consistency Let X0 => X1 ... Xn be a grammar rule Functions of the form S(X0) = f(A(X1),...A(Xn) define synthesized attributes

o i.e., attribute defined by a nodes children

41

Functions of the form I(Xj) = f(A(X0),…A(Xn)) for i <= j <= n define inherited attributeso i.e., attribute defined by parent and siblings

Initially, there are intrinsic attributes on the leaveso i.e., attribute predefined

Denotational Semantics Book just gives you an intro. Why I’m not elaborating A technique for describing the meaning of programs in terms of mathematical

functions on programs and program components. Programs are translated into functions about which properties can be proved

using the standard mathematical theory of functions, and especially domain theory.

Originally developed by Scott and Strachey (1970) and based on recursive function theory

The process of building a denotational specification for a language:o Define a mathematical object for each language entityo Define a function that maps instances of the language entities onto

instances of the corresponding mathematical objects The meaning of language constructs are defined by only the values of the

program's variables The difference between denotational and operational semantics:

o operational semantics, the state changes are defined by coded algorithms;

o denotational semantics, they are defined by rigorous mathematical functions

The state of a program is the values of all its current variables s = {<i1, v1>, <i2, v2>, …, <in, vn>}

Let VARMAP be a function that, when given a variable name and a state, returns the current value of the variable

VARMAP(ij, s) = vj

Example: Decimal Numbers<dec_num> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | <dec_num> (0|1|2|3|4|5|6|7|8|9)

42

Mdec('0') = 0, Mdec ('1') = 1, …, Mdec ('9') = 9Mdec (<dec_num> '0') = 10 * Mdec (<dec_num>)Mdec (<dec_num> '1’) = 10 * Mdec (<dec_num>) + 1 …Mdec (<dec_num> '9') = 10 * Mdec (<dec_num>) + 9

Expressions Me(<expr>, s) = case <expr> of <dec_num> => Mdec(<dec_num>, s) <var> => if VARMAP(<var>, s) = undef then error else VARMAP(<var>, s) <binary_expr> => if (Me(<binary_expr>.<left_expr>, s) = undef OR Me(<binary_expr>.<right_expr>, s) = undef) then errorelse if (<binary_expr>.<operator> = ‘+’ then Me(<binary_expr>.<left_expr>, s) + Me(<binary_expr>.<right_expr>, s) else Me(<binary_expr>.<left_expr>, s) * Me(<binary_expr>.<right_expr>, s)

Assignment Statements

43

Ma(x := E, s) = if Me(E, s) = error then error else s’ = {<i1’,v1’>,<i2’,v2’>,...,<in’,vn’>}, where for j = 1, 2, ..., n, vj’ = VARMAP(ij, s) if ij <> x = Me(E, s) if ij = x

Logical Pretest Loopso The meaning of the loop is the value of the program variables after the

statements in the loop have been executed the prescribed number of times, assuming there have been no errors

o In essence, the loop has been converted from iteration to recursion, where the recursive control is mathematically defined by other recursive state mapping functions

o Recursion, when compared to iteration, is easier to describe with mathematical rigor

Logical Pretest Loops Ml(while B do L, s) =

if Mb(B, s) = undef then error else if Mb(B, s) = false then s else if Msl(L, s) = error then error else Ml(while B do L, Msl(L, s))

A Word about Symbol Tables A Symbol table contains all the information that must be passed between

different phases of a compiler/interpreter A symbol (or token) has at least the following attributes:

o Symbol Nameo Symbol Type (int, real, char, ....)!o Symbol Class (static, automatic, cons...)

44

In a compiler we also needo Address (where it is the info stored?)o Other info due to used data structures

Symbol tables are typically implemented using hashing schemes because good efficiency for the lookup is needed

We classify for symbol tables as:o Simple

only one scope only “global” variables may be found in BASIC and FORTRAN compilers

o Scoped Complication in simple tables involves languages that permit

multiple scopes C permits at the simplest level two scopes: global and local (it is

also possible to have nested scopes in C)!

The importance of considering the scopesint a=10; //global variable

void main(){

changeA();printf(”Value of a=%d\n”,a);

}

void changeA(){

int a; //local variablea=5;

}

int a=10; //global variable

void main(){

changeA();printf(”Value of a=%d\n”,a);

}

void changeA(){ a=5; }

Operations that must be supported by the symbol table in order to handle scopingo Lookup in any scope – search the most recently created scope firsto Enter a new symbol in the symbol tableo Modify information about a symbol in a “visible” scopeo Create a new scopeo Delete the most recently scope

45

Symbol Table

Vienna Definition Language - FYI VDL was a language developed at IBM Vienna Labs as a language

for formal, algebraic definition via operational semantics. It was used to specify the semantics of PL/I See: The Vienna Definition Language, P. Wegner, ACM Comp Surveys

4(1):5-63 (Mar 1972) The VDL specification of PL/I was very large, very complicated, a

remarkable technical accomplishment, and of little practical use.

Logic 101 Propositional logic:

o Logical constants: true, falseo Propositional symbols: P, Q, S, ... that are either true or falseo Logical connectives: (and) , (or), (implies), (is equivalent),

(not) which are defined by the truth tables below.o Sentences are formed by combining propositional symbols, connectives

and parentheses and are either true or false. e.g.: PQ (P Q) First order logic adds

o Variables which can range over objects in the domain of discourseo Quantifiers including: (forall) and (there exists)o Predicates to capture domain classes and relations

(p) (q) pq (p q)

46

x prime(x) y prime(y) y>x

Truth Tables

47

Implies & Equivalence ( => and <=> ) Implies > “(p-> q)” can be used to translate to the

followingo If p then q.o p only if q.o q if p.o Whenever p, q.o q provided that p.o p is sufficient for q.o q is necessary for p.

The statement: 

Your teacher tells you that "if you participate in class, then you will get extra points." 

fact 1:   "you participate in class."fact 2:   "you get participation points."

When is the teacher's statement true?

1.  If you participate in class (fact 1 true) and you get extra points (fact 2 true) then the teacher's statement is true.

2.  If you participate in class (fact 1 true) and you do not get extra points (fact 2 false), then the teacher did not tell the truth and the statement is false.

3.  If you do not participate in class (fact 1 false), EITHER WAY we cannot judge the truth of the teacher's statement.  The teacher did not tell you what would happen if you did NOT participate in class.  Since we cannot accuse the teacher of making a false statement, we assign "true" to the statement.

48

Solutions

AG with Semantics Rules

syntax rule #1: <bval> <bval><bit> | <bit>

49

semantics rule: <bval>[1].val = <bval>[2].val * 2 + <bit>.val

syntax rule #2: <bit> 0 | 1semantics rule: <bval>.val = <bit>.val

50

Resources:

http://www.divms.uiowa.edu/~hzhang/c123/Lecture3.pdfhttp://www.divms.uiowa.edu/~slonnegr/plf/Book/Chapter3.pdfhttp://www.cs.vassar.edu/~cs331/lectures/attribute-grammars.pdfhttp://www.cs.vassar.edu/~cs331/lectures/attribute-grammars.pdfhttp://www.divms.uiowa.edu/~hzhang/c123/Lecture3.pdfhttp://www.cs.vassar.edu/~cs331/lectures/attribute-grammars.pdfwww.cs.wright.edu/~tkprasad/courses/cs784/L167AG.ppt http://www.divms.uiowa.edu/~slonnegr/plf/Book/Chapter8.pdfhttp://www.doc.ic.ac.uk/~pg/Computation/lecture2.pdfhttp://www.divms.uiowa.edu/~slonnegr/plf/Book/Chapter8.pdfhttp://julieburke.hubpages.com/hub/logicfundamentalshttp://en.wikipedia.org/wiki/Pentium_FDIV_bughttp://www.divms.uiowa.edu/~slonnegr/plf/Book/Chapter3.pdfhttp://www.ceng.metu.edu.tr/courses/ceng444/lect/notes4a.pdfhttp://www.box.net/shared/jbbc02tat2

http://www.ida.liu.se/~TDDB44/lessons/ccl2.pdf

Preconditions:

http://www.cs.umd.edu/~mvz/handouts/weakest-precondition.pdfhttp://www.cse.scu.edu/~rdaniels/html/courses/Coen171/HW1Soln.htmhttp://gauss.ececs.uc.edu/Courses/c626/lectures/ACL2/wp.pdf

Truth Tables:http://www.cs.colorado.edu/~frohardt/SepLogic.pdfhttp://regentsprep.org/Regents/math/geometry/GP1/ifthen.htmhttp://gauss.ececs.uc.edu/Courses/c626/lectures/ACL2/wp.pdfhttp://www.google.com/url?sa=t&rct=j&q=floyd-hoare%20logic%20examples&source=web&cd=3&ved=0CDIQFjAC&url=http%3A%2F%2Fwww.bcl.hamilton.ie%2F~barak%2Fteach%2FF2008%2FNUIM%2FCS424%2Fnotes%2FAxiomatic_Semantics%2FHoare_Logic_1.ppt&ei=VlM2T7KyL6LI0QGy9rm9Ag&usg=AFQjCNFsmDrBykIGdvfTLrEsgTxZxTi5bw&cad=rja

51

http://www.computing.dcu.ie/~hamilton/teaching/CA648/notes/PartialCorrectness.pdf http://cs.au.dk/~amoeller/talks/hoare.pdf

Abreact Trees:http://www.phpcompiler.org/doc/latest/treetutorial1.html

FSMhttp://www.kosbie.net/cmu/fall-08/15-100/handouts/fsm.gif

52