Chapter 3 Describing Syntax and Semantics Chapter 3
Chapter 3 Describing Syntax and Semantics
Chapter 3 Topics w Introduction w The General Problem of Describing Syntax w Formal Methods of Describing Syntax w Static Semantics: Attribute Grammars w Describing the Meanings of Programs: Dynamic Semantics 2
Introduction w Who must use language definitions? n n n Other language designers Implementors Programmers (the users of the language) w Syntax - the form or structure of the expressions, statements, and program units w Semantics - the meaning of the expressions, statements, and program units 3
Describing Syntax w A sentence is a string of characters over some alphabet w A language is a set of sentences w A lexeme is the lowest level syntactic unit of a language (e. g. , *, sum, begin) w A token is a category of lexemes (e. g. , identifier) I Subject like Verb apples. Object Lexeme Token 4
Describing Syntax Lexeme: n, main, void, = … Token: identifier, literal, keyword , …. 5
Describing Syntax w Formal approaches to describing syntax: n n Recognizers - used in compilers (we will look at in Chapter 4) Generators – generate the sentences of a language (what we'll study in this chapter) 6
Formal Methods of Describing Syntax w Context-Free Grammars n n n Developed by Noam Chomsky in the mid 1950 s Language generators, meant to describe the syntax of natural languages Define a class of languages called context-free languages 7
Formal Methods of Describing Syntax w Backus-Naur Form (1959) n n Invented by John Backus to describe Algol 58 BNF is equivalent to context-free grammars A metalanguage is a language used to describe another language. In BNF, abstractions are used to represent classes of syntactic structures--they act like syntactic variables (also called nonterminal symbols) 8
Formal Methods of Describing Syntax w A rule has a left-hand side (LHS) and a right -hand side (RHS), and consists of terminal and nonterminal symbols w A grammar is a finite nonempty set of rules w A nonterminal symbol can have more than one RHS <stmt> <single_stmt> | begin <stmt_list> end 9
Backus-Naur Form (1959) Non terminal Terminal Non terminal <while_stmt> while ( <logic_expr> ) <stmt> Terminal w This is a rule; it describes the structure of a while statement CFG is composed of (S, N, T, P) where …. 10
Formal Methods of Describing Syntax w Syntactic lists are described using recursion <ident_list> ident | ident, <ident_list> w A derivation is a repeated application of rules, starting with the start symbol and ending with a sentence (all terminal symbols) 11
Formal Methods of Describing Syntax w An example grammar: <program> <stmts> <stmt> | <stmt> ; <stmts> <stmt> <var> = <expr> <var> a | b | c | d <expr> <term> + <term> | <term> <var> | const 12
Formal Methods of Describing Syntax w An example derivation: <program> <stmts> <stmt> <var> = <expr> a = <expr> To derive a = <term> + <term> a=b+2 a = <var> + <term> a = b + const 13
Derivation w Every string of symbols in the derivation is a sentential form w A sentence is a sentential form that has only terminal symbols w A leftmost derivation is one in which the leftmost nonterminal in each sentential form is the one that is expanded w A derivation may be neither leftmost nor rightmost 14
Parse Tree w A hierarchical representation of a derivation <program> <stmts> <stmt> <var> = <expr> a <term>+ <term> <var> b const 15
Parse Tree What is the CFG grammar? Integer -> Integer Digit | Digit 16
Parse Tree Example Parse tree for x+2*y Assume: Start Symbol is Expression 17
Formal Methods of Describing Syntax w A grammar is ambiguous iff it generates a sentential form that has two or more distinct parse trees 18
An Ambiguous Expression Grammar <expr> <op> <expr> | const <expr> <op> / | - <expr> <op> <expr><op><expr> const - const / <expr><op><expr> const - const / const If we want to derive const – const / const (eg. 2 – 9 /3) 19
An Unambiguous Expression Grammar w If we use the parse tree to indicate precedence levels of the operators, we cannot have ambiguity <expr> - <term> | <term> <expr> <term> / const | const Derivation: <expr> => <expr> - <term> => <term> - <term> => const - <term> / const => const - const / const <expr> - <term> / const 20
An Ambiguous Grammar Another example Create a parse tree for: if (x <0) if (y <0) y = y-1 else y=0 21
An Ambiguous Grammar if (x <0) if (y <0) y = y-1 else y=0 22
Formal Methods of Describing (A+B) + C Syntax =A + (B +C) w Operator associativity can also be indicated by a grammar <expr> -> <expr> + <expr> | const (ambiguous) <expr> -> <expr> + const | const (unambiguous) <expr> + Left Association Recursion goes on the left side. const <expr> + const 23
Formal Methods of Describing (A+B) + C Syntax =A + (B +C) <expr> -> const + <expr> | const (unambiguous) <expr> const + Right Association Recursion goes on the right side. <expr> const + <expr> const 24
Formal Methods of Describing Syntax w Extended BNF (just abbreviations): n Optional parts are placed in brackets ([ ]) <proc_call> -> ident [ ( <expr_list>)] n Put alternative parts of RHSs in parentheses and separate them with vertical bars <term> -> <term> (+ | -) const n Put repetitions (0 or more) in braces ({ }) <ident> -> letter {letter | digit} 25
BNF and EBNF w BNF: <expr> + <term> | <expr> - <term> | <term> * <factor> | <term> / <factor> | <factor> w EBNF: <expr> <term> {(+ | -) <term>} <term> <factor> {(* | /) <factor>} 26
Attribute Grammars (AGs) (Knuth, 1968) w Cfgs cannot describe all of the syntax of programming languages w Additions to cfgs to carry some semantic info along through parse trees w Primary value of AGs: n n Static semantics specification Compiler design (static semantics checking) 27
Attribute Grammars w Def: An attribute grammar is a cfg G = (S, N, T, P) with the following additions: n n n For each grammar symbol x there is a set A(x) of attribute values Each rule has a set of functions that define certain attributes of the nonterminals in the rule Each rule has a (possibly empty) set of predicates to check for attribute consistency 28
Attribute Grammars w Let X 0 X 1. . . Xn be a rule w Functions of the form S(X 0) = f(A(X 1), . . . , A(Xn)) define synthesized attributes w Functions of the form I(Xj) = f(A(X 0), . . . , A(Xn)), for i <= j <= n, define inherited attributes w Initially, there are intrinsic attributes on the leaves (terminals) 29
Attribute Grammars w Example: expressions of the form id + id n n n id's can be either int_type or real_types of the two id's must be the same type of the expression must match it's expected type w BNF: <expr> <var> + <var> id 30
Attribute Grammars w BNF: <expr> <var> + <var> id w Attributes: n actual_type - synthesized for <var> and <expr> for <var> - actual type is intrinsic, for <expr> actual type is decided by child node. n expected_type - inherited for <expr> 31
The Attribute Grammar w Syntax rule: <expr> <var>[1] + <var>[2] Semantic rules: <expr>. actual_type <var>[1]. actual_type Predicate: <var>[1]. actual_type == <var>[2]. actual_type <expr>. expected_type == <expr>. actual_type w Syntax rule: <var> id Semantic rule: <var>. actual_type lookup (<var>. string) 32
Attribute Grammars w How are attribute values computed? n n n 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. 33
Attribute Grammars <expr>. expected_type inherited from parent <var>[1]. actual_type lookup (A) <var>[2]. actual_type lookup (B) <var>[1]. actual_type =? <var>[2]. actual_type <expr>. actual_type <var>[1]. actual_type <expr>. actual_type =? <expr>. expected_type 34
Attribute Grammars w BNF: <assign> <var> : = <expr> <var> + <var> id w Attributes: n actual_type - synthesized for <var> and <expr> for <var> - actual type is intrinsic, for <expr> actual type is decided by child node. n expected_type - inherited for <expr> is from the left handside of : = ( from <var>) 35
Attribute Grammars Exp <expr>. actual_type <var>[1]. actual_type =? <var>[2]. actual_type Var + Var <var>[1]. actual_type lookup (A) <var>[2]. actual_type lookup (B) Synthesized id id A B 36
Attribute Grammars <expr>. actual_type =? <expr>. expected_type Assign <expr>. expected <var>. actual_type Exp Var <expr>. actual_type <var>[1]. actual_type = Var id Inherited + Var id id A B C What if int A, B, C ? What if float A; int B, C; ? What if float A, B; int C; ? 37
Attribute Grammars Exp <expr>. actual_type <var>[1]. actual_type =? <var>[2]. actual_type Var + Var <var>[1]. actual_type lookup (A) id id A B <var>[2]. actual_type lookup (B) Synthesized What if int A, B, C ? What if float A; int B, C; ? What if float A, B; int C; ? 38
The Attribute Grammar w Syntax rule: <assign> <var> : = <expr> Semantic rules: <expr>. expected <var>. actual_type 39
Semantics w There is no single widely acceptable notation or formalism for describing semantics w Operational Semantics n Describe the meaning of a program by executing its statements on a machine, either simulated or actual. The change in the state of the machine (memory, registers, etc. ) defines the meaning of the statement 40
Semantics w To use operational semantics for a high-level language, a virtual machine is needed w A hardware pure interpreter would be too expensive w A software pure interpreter also has problems: n n The detailed characteristics of the particular computer would make actions difficult to understand Such a semantic definition would be machine- dependent 41
Operational Semantics w A better alternative: A complete computer simulation w The process: n n Build a translator (translates source code to the machine code of an idealized computer) Build a simulator for the idealized computer w Evaluation of operational semantics: n n Good if used informally (language manuals, etc. ) Extremely complex if used formally (e. g. , VDL) 42
Operational Semantics w Example: for (exp 1; exp 2; exp 3) body; w Is equivalent to exp 1; loop: if (exp 2==0) goto out; body; exp 3; goto loop; out: 43
Operational Semantics w Example: while (exp) body; w Is equivalent to loop: if (exp==0) goto out; body; goto loop; out: 44
Semantics w Axiomatic Semantics n n Based on formal logic (predicate calculus) Original purpose: formal program verification Approach: Define axioms or inference rules for each statement type in the language (to allow transformations of expressions to other expressions) The expressions are called assertions 45
Axiomatic Semantics w An assertion before a statement (a precondition) states the relationships and constraints among variables that are true at that point in execution w An assertion following a statement is a postcondition w A weakest precondition is the least restrictive precondition that will guarantee the postcondition 46
Axiomatic Semantics w Pre-post form: {P} statement {Q} w An example: a = b + 1 {a > 1} One possible precondition: {b > 10} Weakest precondition: {b > 0} 47
Axiomatic Semantics w Program proof process: The postcondition for the whole program is the desired result. Work back through the program to the first statement. If the precondition on the first statement is the same as the program spec, the program is correct. 48
Axiomatic Semantics w An axiom for assignment statements (x = E): {Qx->E} x = E {Q} w The Rule of Consequence: 49
Axiomatic Semantics w Example: w {y > 14} is the weakest precondition. 50
Axiomatic Semantics w Example: w {y > 13 -x} is the weakest precondition. 51
Axiomatic Semantics w Example: w {x > 3} is the weakest precondition. 52
Axiomatic Semantics w An inference rule for sequences For a sequence S 1; S 2: {P 1} S 1 {P 2} S 2 {P 3} the inference rule is: 53
Axiomatic Semantics w Example: w Apply backward: Then y < 7 is postondition of the first statement. Then x < 2 is the precondition for the block. 54
Axiomatic Semantics w If statement the inference rule is: 55
Axiomatic Semantics w Example: T y=y-1 x>0 F y=y+1 {y>0} 56
Axiomatic Semantics w Example: {y>1} {y>-1} -1 1 57
Axiomatic Semantics w An inference rule for logical pretest loops For the loop construct: {P} while B do S end {Q} the inference rule is: B while (x != y ) S y = y+1 where I is the loop invariant (the inductive hypothesis) 58
Axiomatic Semantics w Characteristics of the loop invariant I must meet the following conditions: n n n P => I (the loop invariant must be true initially) {I} B {I} (evaluation of the Boolean must not change the validity of I) {I and B} S {I} (I is not changed by executing the body of the loop) (I and (not B)) => Q (if I is true and B is false, Q is implied) The loop terminates (this can be difficult to prove) 59
Axiomatic Semantics w The loop invariant I is a weakened version of the loop postcondition, and it is also a precondition. w 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 w During execution, I must not be affected by boolean evaluation of the loop expression and loop body. 60
Axiomatic Semantics w Thus, to prove correctness of the while loop, we show 61
Axiomatic Semantics w Example {y==x} w Find I by induction by # of steps: Thus is our I since implies 62.
Axiomatic Semantics w Next is to show the above five rules. 63
Axiomatic Semantics w Next is to show the above five rules. 64
Axiomatic Semantics w Example: prove correctness of factorial function: 65
Axiomatic Semantics w Divide code into portion: 66
Axiomatic Semantics w Divide code into portion: 67
Axiomatic Semantics w Proof each part: Find precond. of postcond becomes 1=1! 68
Axiomatic Semantics w Proof each part: { B and P} {P} as a loop invariant 69
Axiomatic Semantics w Consider each term: 70
Semantics w Evaluation of axiomatic semantics: n n Developing axioms or inference rules for all of the statements in a language is difficult It is a good tool for correctness proofs, and an excellent framework for reasoning about programs, but it is not as useful for language users and compiler writers 71
Semantics w Denotational Semantics n n n Based on recursive function theory The most abstract semantics description method Originally developed by Scott and Strachey (1970) 72
Denotational Semantics w The process of building a denotational spec for a language (not necessarily easy): n n Define a mathematical object for each language entity Define a function that maps instances of the language entities onto instances of the corresponding mathematical objects w The meaning of language constructs are defined by only the values of the program's variables 73
Semantics w The difference between denotational and operational semantics: n n In operational semantics, the state changes are defined by coded algorithms; in denotational semantics, they are defined by rigorous mathematical functions 74
Denotational Semantics w Example 75
Denotational Semantics w Example 76
Denotational Semantics w Example 77
Semantics w Decimal Numbers n The following denotational semantics description maps decimal numbers as strings of symbols into numeric values 78
Semantics <dec_num> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | <dec_num> (0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) Mdec('0') = 0, Mdec ('1') = 1, …, Mdec ('9') = 9 Mdec (<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 79
Denotational Semantics w The state of a program is the values of all its current variables s = {<i 1, v 1>, <i 2, v 2>, …, <in, vn>} Example: S={<x, 3>, <y, 2>} w 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: VARMAP( x, S)= 3 S={<x, 3>, <y, 2>} 80
Semantics w Expressions n n Map expressions onto Z {error} We assume expressions are decimal numbers, variables, or binary expressions having one arithmetic operator and two operands, each of which can be an expression 81
<exp> <dec_num> | <var> | <binary_exp> Example: 3, x, x+y Semantics 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 error else 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). . . Check error x+y left_expr right_expr 82
Semantics w Assignment Statements n Maps state sets to state sets S={<x, 3>, <y, 2>} E x=x+y Ma(x : = E, s) = if Me(E, s) == error S’={<x, 5>, <y, 2>} then error else s’ = {<i 1’, v 1’>, <i 2’, v 2’>, . . . , <in’, vn’>}, where for j = 1, 2, . . . , n, vj’ = VARMAP(ij, s) if ij <> x = Me(E, s) if ij == x 83
Semantics w Logical Pretest Loops n Maps state sets to state sets Ml(while B do L, s) = if Mb(B, s) == undef then error else if Mb(B, s) == false New state then s returned by Recursive call executing the L else if Msl(L, s) == error One more round (loop body) then error else Ml(while B do L, Msl(L, s)) 84
Semantics w Selection Mif(if B then s 1 else s 2, s) = if Mb(B, s) == undef then error else if Mb(B, s) == true then Msl(s 1, s) else Msl(s 2, s) 85
Semantics w Example Me(leftexpression, S)+Me(rightexpression, S) 86
Semantics w Example 87
Semantics w Assume w Consider b 1 b 2 w Where initial state is 88
Semantics w Then 89
Semantics w Consider Ml M sl w Where initial state is 90
Semantics w Logical Pretest Loops Ml(while B do L, s) = if Mb(B, s) == undef then error else if Mb(B, s) == false One round of iteration. then s Result is used in the else if Msl(L, s) == error next round by recursion. then error else Ml (while B do L, Msl(L, s)) 91
Semantics w Consider 92
Semantics w 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 w In essence, the loop has been converted from iteration to recursion, where the recursive control is mathematically defined by other recursive state mapping functions w Recursion, when compared to iteration, is easier to describe with mathematical rigor 93
Semantics w Evaluation of denotational semantics: n n Can be used to prove the correctness of programs Provides a rigorous way to think about programs Can be an aid to language design Has been used in compiler generation systems 94
Static type validity check w To declared variables must not have the same name. Variables must be declared uniquely. int x; float y; Not: int x; float x; 95
Static type validity check A language B has types: Boolean , int. It has an expression of the form: <exp> const | <var> | <binary_exp> | <unary_exp> Type of <exp> which is const is the type of that const. Eg: 3 Type of <exp> which is <var> is the type of that var. Eg: int x; Type of x is int. Type of <exp> which is <binary_exp> depends on its operator. if <exp> is: x+y ‘+’ is arithmetic operator. Then <binary_exp> has type int. x|| y ‘||’ is boolean operator. Then <binary_exp> has type boolean x<y ‘<’ is relational operator. Then <binary_exp> has type boole Type of <exp> which is <unary_exp> is boolean. Eg. !x 96
Static type validity check Given a type map: Type of expression is formally defined as: type. Of(Expression e, Typemap tm) : = since ‘+’ is arithmetic operator. type. Of(x+2*y, tm) = int type. Of(x < 2*y, tm) = boolean since ‘<’ is relational operator. type. Of(x < y && !x, tm) = boolean since ‘<’ is boolean operator. 97
Static type validity check Next we define the Valid function. V The <exp> is valid if V(<exp>, tm) w It is a value. Eg. Constant value : 9 w It is in a type map. Eg. tm={<int, x> < int, y> }, then x tm w For <binary_exp>, n n it has a valid left operand, valid right operand, and type of both operands must be int if its operator is arithmetic, relational. it has a valid left operand, valid right operand, and type of both operands must be boolean if its operator is boolean. w For <unary_exp>, it has a valid operand, and type of the operand must be boolean. 98
Static type validity check <binary_exp> <e. term 1> <e. op> <e. term 2> <unary_exp> ><e. op> <e. term 1>99
Static type validity check 100
Static type validity check 101
Static type validity check Consider statement consisting of: Consider validity rule. s. target=s. souce While s. test do s. body If s. test Then s. thenbranch Else s. elsebranch 102
Static type validity check s. test s. target s. then s. body s. source 103
Static type validity check Valid s. test and type of s. test must be boole Valid s. body: b 1; b 2; -valid b 1 and valid b 2. b 1: Valid if statement: -must be valid s. test, Type of test==boolean and valid s. thenbranch b 2: Valid assign statement: -must be valid s. source, valid s. target, and type of s. source = type of s. target 104
- Slides: 104