ice1341 programming languages spring 2005 lecture #6 lecture #6 in-young ko iko.at. icu.ac.kr...
TRANSCRIPT
ICE1341 ICE1341 Programming LanguagesProgramming Languages
Spring 2005Spring 2005
Lecture #6Lecture #6
In-Young Koiko .AT. icu.ac.kr
Information and Communications University (ICU)
Spring 2005 2 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
AnnouncementsAnnouncements
Your team information is on-lineYour team information is on-line
Spring 2005 3 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Backus-Naur Form (BNF)Backus-Naur Form (BNF) DerivationsDerivations Parse TreesParse Trees
Ambiguity in GrammarsAmbiguity in Grammars Operator PrecedenceOperator Precedence Associativity of OperatorsAssociativity of Operators
Extended BNF (EBNF)Extended BNF (EBNF)
Last LectureLast Lecture
Spring 2005 4 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
This LectureThis Lecture
Attribute GrammarsAttribute Grammars Dynamic SemanticsDynamic Semantics
Spring 2005 5 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Language Survey ResultLanguage Survey Result
34%
15%
36%
6%2% 7%
C C++ Java VB VC Etc
72%
3%
25%0%0%0%
C C++ Java VB VC Etc
Languages that most Languages that most students can usestudents can use
Most favored languagesMost favored languages
Spring 2005 6 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Attribute Grammars – Attribute Grammars – Problem DescriptionProblem Description
Example Problem: Example Problem: Type Compatibility RuleType Compatibility Rule<assign> <assign> <var> = <expr> <var> = <expr>
<expr> <expr> <var> + <var> | <var> <var> + <var> | <var>
<var> <var> A | B | C A | B | C
1.1. The type of an expression The type of an expression when the operand types are not the when the operand types are not the samesame is always is always realreal (e.g., C = 10 + 12.5) (e.g., C = 10 + 12.5)
2.2. When they are the sameWhen they are the same, the expression type is that of the , the expression type is that of the operands (e.g., C = 12.5 + 0.23)operands (e.g., C = 12.5 + 0.23)
3.3. The type of the left side of the assignment must The type of the left side of the assignment must match the match the typetype of the right side of the right side
This rule represents the This rule represents the static semanticsstatic semantics that needs to that needs to be checked at compile time (c.f., dynamic semantics)be checked at compile time (c.f., dynamic semantics)
This rule cannot be represented in BNFThis rule cannot be represented in BNF
e.g., C = 10 + 12.5 + 0.23e.g., C = 10 + 12.5 + 0.23
Spring 2005 7 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Attribute Grammars –Attribute Grammars –DefinitionDefinition
Designed by Designed by Donald E.Donald E. KnuthKnuth, 1968, 1968 A formal approach to both A formal approach to both describing and checking the describing and checking the
correctness of the static semanticscorrectness of the static semantics of a program of a program Main elementsMain elements
AttributesAttributes: associated with grammar symbols: associated with grammar symbols Synthesized AttributesSynthesized Attributes: computed based on the attributes in a : computed based on the attributes in a
parse treeparse tree Inherited AttributesInherited Attributes: inherited from parents in a parse tree: inherited from parents in a parse tree Intrinsic AttributesIntrinsic Attributes: synthesized attributes of leaf nodes: synthesized attributes of leaf nodes
Attribute computation functionsAttribute computation functions ( (semantic rulessemantic rules): specify ): specify how attribute values are computedhow attribute values are computed
Predicate functionsPredicate functions: syntactic and semantic rules of a : syntactic and semantic rules of a language, associated with grammar ruleslanguage, associated with grammar rules
Spring 2005 8 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Attribute Grammars –Attribute Grammars –An ExampleAn Example
Attributes: Attributes: actual_typeactual_type (synthesized attr.), (synthesized attr.), expected_typeexpected_type (inherited attr.) (inherited attr.)
1.1. Syntax rule:Syntax rule: <assign> <assign> <var> = <expr> <var> = <expr>Semantic rule:Semantic rule: <expr>. <expr>.expected_typeexpected_type <var>. <var>.actual_typeactual_type
2.2. Syntax rule:Syntax rule: <expr> <expr> <var>[2] + <var>[3] <var>[2] + <var>[3]Semantic rule:Semantic rule: <expr>. <expr>.actual_typeactual_type
if (<var>[2].if (<var>[2].actual_typeactual_type = int) and = int) and (<var>[3].(<var>[3].actual_typeactual_type = int) then int = int) then intelse realelse realendifendif
Predicate:Predicate: <expr>. <expr>.actual_typeactual_type = <expr>. = <expr>.expected_typeexpected_type
3.3. Syntax rule:Syntax rule: <expr> <expr> <var> <var>Semantic rule:Semantic rule: <expr>. <expr>.actual_typeactual_type <var>. <var>.actual_typeactual_typePredicate:Predicate: <expr>. <expr>.actual_typeactual_type = <expr>. = <expr>.expected_typeexpected_type
4.4. Syntax rule:Syntax rule: <var> <var> A | B | C A | B | CSemantic rule:Semantic rule: <var>. <var>.actual_typeactual_type look-up(<var>. look-up(<var>.stringstring))
<assign> <assign> <var> = <expr> <var> = <expr><expr> <expr> <var> + <var> | <var> <var> + <var> | <var><var> <var> A | B | C A | B | C
Spring 2005 9 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Computing Attribute Values – Computing Attribute Values – Evaluating AttributesEvaluating Attributes
Sentence: Sentence: A = A + BA = A + B
1. <var>.1. <var>.actual_typeactual_type look-up(A) look-up(A) (Rule 4)(Rule 4)
2. <expr>.2. <expr>.expected_typeexpected_type <var>. <var>.actual_typeactual_type (Rule 1)(Rule 1)
3. <var>[2].3. <var>[2].actual_typeactual_type look-up(A)look-up(A) (Rule 4)(Rule 4)
<var>[3].<var>[3].actual_typeactual_type look-up(B)look-up(B) (Rule 4)(Rule 4)
4. <expr>.4. <expr>.actual_typeactual_type either int or realeither int or real (Rule 2)(Rule 2)
5. <expr>.5. <expr>.expected_typeexpected_type = =
<expr>.<expr>.actual_typeactual_type is is
either TRUE or FALSEeither TRUE or FALSE (Rule 2)(Rule 2)
Grammar:Grammar:<assign> <assign> <var> = <expr> <var> = <expr><expr> <expr> <var> + <var> | <var> <var> + <var> | <var><var> <var> A | B | C A | B | C
* Sebesta Figure 3.6
Spring 2005 10
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Computing Attribute Values – Computing Attribute Values – Flow of AttributesFlow of Attributes in a Parse Tree in a Parse Tree
An Inherited An Inherited AttributeAttribute
A Synthesized A Synthesized AttributeAttribute
An Intrinsic An Intrinsic AttributeAttribute
* Sebesta Figure 3.7
Spring 2005 11
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Computing Attribute Values – Computing Attribute Values – Fully Attributed Parse TreeFully Attributed Parse Tree
* Sebesta Figure 3.8
Spring 2005 12
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics (Semantics)Dynamic Semantics (Semantics)
Definition: Definition: Meaning of expressions, statements, Meaning of expressions, statements, and program unitsand program units
Why do we need semantic information?Why do we need semantic information? ProgrammersProgrammers need to know precisely what statements need to know precisely what statements
of a language doof a language do Compiler writersCompiler writers need to know how to interpret and need to know how to interpret and
process the meaning embedded in program statementsprocess the meaning embedded in program statements What do we need to utilize semantic information?What do we need to utilize semantic information?
Formal ways to describe dynamic semanticsFormal ways to describe dynamic semantics No single widely acceptable notation or formalismNo single widely acceptable notation or formalism
Spring 2005 13
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics –Dynamic Semantics –Operational SemanticsOperational Semantics
Operational SemanticsOperational Semantics: The meaning of a program : The meaning of a program described by described by execution of its statementsexecution of its statements on a machine on a machine
The meaning of a statement is defined by the The meaning of a statement is defined by the change in change in the state of the machinethe state of the machine (memory, registers, etc.) (memory, registers, etc.)
Components needed to Components needed to describe operational describe operational semanticssemantics TranslatorTranslator: converts : converts
statements in a high-level statements in a high-level language to a low-level language to a low-level languagelanguage
Virtual MachineVirtual Machine: interprets : interprets the low-level language and the low-level language and reports state changesreports state changes
Java StatementJava Statementforfor (expr1; expr2; expr3) { (expr1; expr2; expr3) {
……
}}
Operational SemanticsOperational Semantics expr1;expr1;
loop: loop: ifif expr2 = 0 expr2 = 0 gotogoto out out
… …
expr3;expr3;
gotogoto loop loop
out: …out: …
TranslatorTranslator
Virtual Virtual MachineMachine
State State ChangesChanges
Meaning of the Meaning of the statementstatement
Spring 2005 14
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics –Dynamic Semantics –Axiomatic SemanticsAxiomatic Semantics
Method to prove the Method to prove the correctness of programscorrectness of programs Described by Described by logical expressionslogical expressions ( (predicate calculuspredicate calculus) )
rather than the entire state of a virtual machinerather than the entire state of a virtual machine PreconditionPrecondition: constraints on the program variables : constraints on the program variables
immediately preceding a statementimmediately preceding a statement PostconditionPostcondition: new constraints on the variables after : new constraints on the variables after
execution of the statementexecution of the statement
Notation (Notation (Hoare TripleHoare Triple)) { P } S { Q }{ P } S { Q }, P: Precondition, Q: Postcondition, S: Statement, P: Precondition, Q: Postcondition, S: Statement e.g., e.g., { x > 10 }{ x > 10 } sum = 2 * x + 1sum = 2 * x + 1 { sum > 1 } { sum > 1 }
Weakest PreconditionsWeakest Preconditions:: the the least restrictive preconditionsleast restrictive preconditions that that will guarantee the validity of the associated postconditionswill guarantee the validity of the associated postconditions
e.g.,e.g., { x > 0 } { x > 0 } at the above exampleat the above example
Spring 2005 15
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics – Dynamic Semantics – Axiomatic Semantics –Axiomatic Semantics –Predicate CalculusPredicate Calculus
SentencesSentences ((assertionsassertions) are represented by a ) are represented by a subjectsubject and a and a predicatepredicate: : P(x)P(x) e.g., e.g., P: “is red”, P(x): “x is red.”P: “is red”, P(x): “x is red.”
Sentences can be combined by using logical Sentences can be combined by using logical connectives such as connectives such as , , , , ~~, , e.g., Q: “is round”, P(x) e.g., Q: “is round”, P(x) Q(x) : “x is red and round.” Q(x) : “x is red and round.”
A sentence can be structured using the A sentence can be structured using the universal universal quantifierquantifier ( ( ) or the ) or the existential quantifierexistential quantifier ( ( ) )
e.g.,e.g., All men are mortal: All men are mortal: x: P(x) x: P(x) Q(x) Q(x) Socrates is a man: Socrates is a man: P(Socrates) P(Socrates) Socrates is mortal: Socrates is mortal: Q(Socrates)Q(Socrates)
Spring 2005 16
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics – Dynamic Semantics – Axiomatic Semantics –Axiomatic Semantics –Inference Rules (Hoare Logic)Inference Rules (Hoare Logic)
Inference RuleInference Rule: Method of inferring the truth of : Method of inferring the truth of one assertion on the basis of the values of one assertion on the basis of the values of other assertionsother assertions
Axiom of AssignmentAxiom of Assignment: : { Q{ QxxEE } x = E { Q } } x = E { Q } An assignment statement: An assignment statement: x = Ex = E The precondition is computed as the postcondition, The precondition is computed as the postcondition,
Q with all instances of x replaced by EQ with all instances of x replaced by E e.g., e.g., a = b / 2 – 1 { a < 10 }a = b / 2 – 1 { a < 10 }
The weakest precondition:The weakest precondition:b / 2 – 1 < 10b / 2 – 1 < 10
b < 22b < 22
Spring 2005 17
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Inference RulesInference Rules (Hoare Logic)(Hoare Logic) ––Rules of ConsequenceRules of Consequence
Rules to Rules to deduce new theoremsdeduce new theorems from one or more from one or more axioms or theorems already provedaxioms or theorems already proved
If S1, S2, …, Sn are true,If S1, S2, …, Sn are true,
then the truth of S can be inferredthen the truth of S can be inferred Formal representation:Formal representation:
A postcondition can A postcondition can always be always be
weakened and a weakened and a precondition precondition
can always be can always be strengthenedstrengthened
e.g., e.g.,
}}{Q'{Q' SS }}{P'{P'
Q'Q' QQ P,P, P'P' {Q},{Q}, SS {P}{P}
SSS1, S2, …, SnS1, S2, …, Sn
{x>5} x = x – 3 {x>0}{x>5} x = x – 3 {x>0}
{x>3} x = x – 3 {x>0}, (x>5)=>(x>3), (x>0)=>(x>0){x>3} x = x – 3 {x>0}, (x>5)=>(x>3), (x>0)=>(x>0)
Spring 2005 18
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Inference RulesInference Rules (Hoare Logic)(Hoare Logic) ––Rules of Composition (Sequencing)Rules of Composition (Sequencing)
Rules to prove the correctness of a sequence of Rules to prove the correctness of a sequence of statementsstatements S1 and S2 are adjacent program statementsS1 and S2 are adjacent program statements Inference rule:Inference rule:
e.g.,e.g.,y = 3 * x + 1; x = y + 3; { x < 10 }y = 3 * x + 1; x = y + 3; { x < 10 }
The precondition of the 2The precondition of the 2ndnd statement: statement: y < 7y < 7
The precondition of the 1The precondition of the 1stst statement: statement: x < 2x < 2
{ P1 } S1; S2 { P3 }{ P1 } S1; S2 { P3 }
{ P1 } S1 { P2 }, { P2 } S2 { P3 }{ P1 } S1 { P2 }, { P2 } S2 { P3 }
Spring 2005 19
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Inference RulesInference Rules (Hoare Logic)(Hoare Logic) ––Rules of SelectionRules of Selection
Rules to prove the correctness of conditional Rules to prove the correctness of conditional statementsstatements Inference rule:Inference rule:
e.g.,e.g.,ifif (x > 0) y = y – 1 (x > 0) y = y – 1 elseelse y = y + 1 { y > 0 } y = y + 1 { y > 0 }
{ y > 1 } y = y – 1 { y > 0}{ y > 1 } y = y – 1 { y > 0}{ y > -1 } y = y + 1 { y > 0 }{ y > -1 } y = y + 1 { y > 0 }precondition: { y > 1 }precondition: { y > 1 }
{P} {P} ifif B B thenthen S1 S1 elseelse S2 {Q} S2 {Q}
{B P} S1 {Q}, {~B P} S2 {Q}{B P} S1 {Q}, {~B P} S2 {Q}
V V
Spring 2005 20
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Inference RulesInference Rules (Hoare Logic)(Hoare Logic) ––Rules of IterationRules of Iteration
Rules to prove the correctness of Rules to prove the correctness of whilewhile loops loops Inference rule:Inference rule:
Loop InvariantLoop Invariant ( (II): an assertion that is unaffected by the loop-): an assertion that is unaffected by the loop-controlling Boolean expression (controlling Boolean expression (BB) and the loop body ) and the loop body statements (statements (SS))
wp(statement, postcondition) = preconditionwp(statement, postcondition) = precondition e.g., e.g., whilewhile y <> xy <> x dodo y = y + 1y = y + 1 endend { y = x }{ y = x }
Zero iterations:Zero iterations: wp( wp( εε, { y = x } ) = , { y = x } ) = { y = x }{ y = x } One iteration:One iteration: wp( y = y + 1, { y = x } ) = wp( y = y + 1, { y = x } ) = { y = x – 1 }{ y = x – 1 } Two iterations:Two iterations: wp( y = y + 1, { y = x – 1 } ) = wp( y = y + 1, { y = x – 1 } ) = { y = x – 2 }{ y = x – 2 } … … Loop Invariant (precondition):Loop Invariant (precondition): { y <= x } { y <= x } Proof: see Text pp.145-146Proof: see Text pp.145-146
{I} {I} whilewhile B B dodo S S endend {I ~B} {I ~B}
{I B} S {I}{I B} S {I}
V
V
Spring 2005 21
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics –Dynamic Semantics –Denotational SemanticsDenotational Semantics
Based on Based on recursive function theoryrecursive function theory The most abstract semantics description methodThe most abstract semantics description method Originally developed by Scott and Strachey (1970)Originally developed by Scott and Strachey (1970) Define a Define a functionfunction that maps instances of the that maps instances of the language entitieslanguage entities onto onto
instances of the corresponding instances of the corresponding mathematical objectsmathematical objects e.g., e.g., <bin_num> <bin_num> 0 | 1 | <bin_num> 0 | <bin_num> 1 0 | 1 | <bin_num> 0 | <bin_num> 1
Mapping Function:Mapping Function:
MMbinbin(‘0’) = 0(‘0’) = 0
MMbinbin(‘1’) = 1(‘1’) = 1
MMbinbin(<bin_num> ‘0’) = 2 * M(<bin_num> ‘0’) = 2 * Mbinbin(<bin_num>)(<bin_num>)
MMbinbin(<bin_num> ‘1’) = 2 * M(<bin_num> ‘1’) = 2 * Mbinbin(<bin_num>) + 1(<bin_num>) + 1
Parse Tree for ‘110’ with Denoted Objects Parse Tree for ‘110’ with Denoted Objects
* Sebesta Figure 3.10
Spring 2005 22
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics – Denotational Semantics –Dynamic Semantics – Denotational Semantics –
State of a ProgramState of a Program
The state of a program is the values of all its The state of a program is the values of all its current variablescurrent variables
s = {<is = {<i11, v, v11>, <i>, <i22, v, v22>, …, <i>, …, <inn, v, vnn>}>}
Let Let VARMAPVARMAP be a function that, when given a be a function that, when given a variable name and a state, returns the current variable name and a state, returns the current value of the variablevalue of the variable
VARMAP(iVARMAP(ijj, s) = v, s) = vjj,,
vvjj can be can be undefundef
* AW Lecture Notes
Spring 2005 23
ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University
Dynamic Semantics – Denotational Semantics –Dynamic Semantics – Denotational Semantics –
Assignment StatementsAssignment Statements
Ma(x := E, s) Ma(x := E, s) ==
if Me(E, s) == errorif Me(E, s) == error
then errorthen error
else else s’ = {<is’ = {<i11’,v’,v11’>,<i’>,<i22’,v’,v22’>,...,<i’>,...,<inn’,v’,vnn’>}’>}, where, where
for j = 1, 2, ..., n,for j = 1, 2, ..., n,
vvjj’ = VARMAP(i’ = VARMAP(ijj, s) if i, s) if ijj <> x; <> x;
Me(E, s) if iMe(E, s) if ijj == x == x