[PDF] Syntax and Semantics
[PDF] Syntax and Semantics
[PDF] Syntax and Semantics
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
(b) Context free grammars• A context free grammar (CFG) consists of the following:– A set of terminal symbols which are the characters in the strings generated by a grammar(e.g., tokens in our case)– A set of nonterminal symbols (variables), which are place-holders for patterns of terminalsymbols that can be generated by the nonterminal symbols.– A set of productions, which are rules for replacing (or rewriting) nonterminal symbols (onthe left side of the production) in a string with other nonterminal or terminal symbols(on the right side of the production).– A start symbol, which is a special nonterminal symbol that appears in the initial stringgenerated by the grammar.• To generate a string of terminal symbols from a CFG, we:i. Begin with a string consisting of the start symbol;ii. Apply one of the productions with the start symbol on the left h<strong>and</strong> size, replacing thestart symbol with the right h<strong>and</strong> side of the production;iii. Repeat the process of selecting nonterminal symbols in the string, <strong>and</strong> replacing themwith the right h<strong>and</strong> side of some corresponding production, until all nonterminals havebeen replaced by terminal symbols.• Example: a CFG for a arithmetic expressionsexpr → numexpr → ( expr )expr → expr + exprexpr → expr − exprexpr → expr ∗ exprexpr → expr / exprThe only nonterminal is expr which is also the start. The terminals are (, ), +, -, * /,num. We can generate a string in this language by starting with expr <strong>and</strong> then applyingvarious productions as follows:expr ⇒ expr ∗ expr⇒⇒⇒⇒⇒expr + expr ∗ expr(expr) + expr ∗ expr(num) + expr ∗ expr(num) + expr ∗ num(num) + num ∗ numNote that we always replaced the leftmost nonterminal, so we call this a leftmost derivationof the resulting string.(c) Backus-Naur form• Backus-Naur form (BNF) is a metalanguage that mimics CFG’s for describing programminglanguage syntax. We use angle brackets to delimit non-terminals, the pipe symbol | tomean “logical or,” <strong>and</strong> ::= to separate the left <strong>and</strong> right h<strong>and</strong> side of a production.• Example: Pascal if statement ::= if then | if then else 2