Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
SemanticsWhat is Semantics?
Syntax is about form semantics is about meaning of the languages features
o (not just about the syntax)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
1
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 semanticso how program is compiled by compiler “C” and run on
Machine “M”o steps of computation taken during execution
Axiomatic semanticso prove that the program conforms to formal
specifications using rules and axioms Denotational semantics
o the meaning of the program is expressed as a collection of mathematical functions
But why do we care? What would you include to make people use your language?
A. B. C. D. E. F. G. H. I. Answers (within):
2
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
Overall Motivations1. To provide programmers with an authoritative definition of the meaning of all
the language constructs2. To provide compiler writers with an authoritative definition of the meaning of
all constructs, thus avoiding implementation differences3. To provide a basis for standardizing the language
3
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 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)
4
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]:
Find an example of a software issue that caused failure (and how much!)
5
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
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 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.
6
Example Operation Semanticsc statement operational semantics for(e1;e2;e3) e1;{<body>} loop: if e2=0 goto exit
<body> e3; goto loop
exit:
Requirements for Operational Semantics To use operational semantics for a high-level language, a virtual machine in
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)
7
Expression Semantics (by operation semantics) not all expressions are done or coded the SAME way
o wait until you get to Scheme!! expression tree (notation)
o while the “parse” tree” may look the same how the programming language handles it, will be different
Expression Tree
What is the tree in prefix, infix, and postfix notation?Which of these really doesn’t show precedence?What would happen if we had a negative number? What’s the issue?
o introduction “Cambridge Notation” avoids the negative (unary) issue by having the operator always
precede it’s operands and enclosing the entire expression in parentheses.
basically prefix with ( )s won’t find much on web about it used in Scheme/Lisp
( - ( + a b) ( * c d) )
associativity o using common addition, multiplication and comparison is the same
across the board left to right otherwise break mathematical foundations
o but these may not match unary
usually right to left (-5) Boolean
8
exponential (C has a function, Python has a symbol) remember, it’s reversed!!
Associativity of OperatorsLanguage + - * /
(simple math)Unary(-/+)
**(exponential)
== != < ...(comparison)
C-like L R - LAda L non non nonFortran L R R L
precedence of operatorso even this isn’t the same through the languages!!
Precedence of OperatorsOperators C-like Ada Fortran
Unary - 7 3 3** - 5 5* / 6 4 4+ - 5 3 3
== != 4 2 2< <= ... 3 2 2
not 7 2 2AND 2 1 1OR 1 1 1
What do they all agree on thought? (precedence # may not match, but overall structure)
short circuit evaluationo left to right comparison that stops as soon as the truth of the expression
can be determined saves time
o did you know at first compilers set it up that they still had to compare both!!
9
Program State mapping (table) of
o the pairing of active objects (variable names) with specific memory location
o pairing off active memory locations with their current values “side effect”
o a change to any non-local variable or I/O change can be value, datatype, etc… c = a + b (in Python)
int = int + int float = int + float etc… c can have a side affect
For each line of this program, write the values of n, i, and f respectfully. BTW, lines 6 through 9 will repeat.
// compute the factorial of n1 void main ( ) {2 int n, i, f;3 n = 3;4 i = 1;5 f = 1;6 while (i < n) {7 i = i + 1;8 f = f * i;9 }10 }
# n i f1 undef undef undef2 undef undef undef345
10
Assignment Semantics languages must cover the possibility of
o multiple assignmentso assignment statements vs. assignment expressionso copy vs. reference semantics
Other semantics you already know sequence conditionals Loops Input/Output each may be different in code, but you already understand the usage and
overall form
11
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
12
Axiomatic Semantics in Theory use this to prove the programing language is doing what it is supposed to do axiom: statement accepted without proof
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
13
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)
Usually either the Pre or POST will be missing in a problem.But we need to find the weakest of either. (Number line example, shown below)
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
14
Pre-condition Post-condition
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!!)…
15
Solve for weakest precondition:
{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
16
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:
17
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 .
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)
18
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 }
19
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
20
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
21
FYI - Sectionstuff we might get to, you need to read
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) x prime(x) y prime(y) y>x
Truth Tables
22
23
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.
24
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
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.
25
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.
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 Turing example and testing
o https://www.youtube.com/watch?v=cqTdbRukhyc JFlap tool to create a Turing machine
o https://www.youtube.com/watch?v=dNmuoF70u4I
26
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
27
Sourceshttp://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.divms.uiowa.edu/~hzhang/c123/Lecture3.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/jbbc02tat2http://www.ida.liu.se/~TDDB44/lessons/ccl2.pdfhttp://www.inf.ed.ac.uk/teaching/courses/lsi/sempl.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=rjahttp://www.computing.dcu.ie/~hamilton/teaching/CA648/notes/PartialCorrectness.pdf http://cs.au.dk/~amoeller/talks/hoare.pdf
28
Abstract Trees:http://www.phpcompiler.org/doc/latest/treetutorial1.html
FSMhttp://www.kosbie.net/cmu/fall-08/15-100/handouts/fsm.gif
29