1. The following grammar should be able to describe the name of any student in this class.
COMPILER YourName $CN CHARACTERS letter = "aBCDeFGHiJKLMNoPQRSTuVWXYZ" . digit = "0123456789" . TOKENS name = letter { letter | "-" } . number = digit digit letter digit digit digit digit . PRODUCTIONS YourName = "(" FirstName ")" Surname [ Surname ] number . FirstName = name . Surname = name . END YourName .
Carefully write down your own name in a form that would be acceptable to a system developed from this grammar [3 marks]
( PaT ) TeRRY 63T0844
(Only lower case vowels and upper case consonants are allowed in this grammar.)
2. Consider the familiar grammar below for describing a set of EBNF productions.
Show how the productions would be attributed so as to parse a set of productions given in the Wirth notation and reproduce them one to a line in an alternative EBNF notation that uses e and the Kleene closure symbol *. Assume that e is available in the underlying character set. [7 marks]
For example, a production like
Program = [ Header ] { Statement } .
should be transformed to
Program = ( Header | e ) ( Statement )* .
This is easily achieved with a few write statements!
using Library; // C# version - Java is virtually identical COMPILER EBNF $CN CHARACTERS letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" . digit = "0123456789" . noquote1 = ANY - "'" . noquote2 = ANY - '"' . TOKENS nonterminal = letter {letter | digit } . terminal = "'" noquote1 { noquote1 } "'" | '"' noquote2 { noquote2 } '"' . IGNORE CHR(9) .. CHR(13) PRODUCTIONS EBNF = { Production } EOF . Production = nonterminal (. IO.Write(token.val, -15); .) "=" (. IO.Write(" = "); .) Expression "." (. IO.WriteLine("."); .) . Expression = Term { "|" (. IO.Write(" |"); .) Term } . Term = Factor { Factor } . Factor = nonterminal (. IO.Write(token.val, 0); .) | terminal (. IO.Write(token.val, 0); .) | "[" (. IO.Write("(", 0); .) Expression "]" (. IO.Write("| e )", 0); .) | "(" (. IO.Write("(", 0); .) Expression ")" (. IO.Write(")", 0); .) | "{" (. IO.Write("(", 0); .) Expression "}" (. IO.Write(")*", 0); .) . END EBNF.
Alternatively one could pass a StringBuilder object between the methods as a parameter:
PRODUCTIONS EBNF = { Production } EOF . Production (. StringBuilder s = new StringBuilder(); .) = nonterminal (. s.Append(token.val); .) "=" (. s.Append(" = "); .) Expression<s> "." (. IO.WriteLine(s.ToString()); .) . Expression<StringBuilder s> = Term<s> { "|" (. s.Append(" | "); .) Term<s> } . Term<StringBuilder s> = Factor<s> { Factor<s> } . Factor<StringBuilder s> = nonterminal (. s.Append(" " + token.val); .) | terminal (. s.Append(" " + token.val); .) | "[" (. s.Append(" ("); .) Expression<s> "]" (. s.Append(" | e) "); .) | "(" (. s.Append(" ( "); .) Expression<s> ")" (. s.Append(" ) "); .) | "{" (. s.Append(" ( "); .) Expression<s> "}" (. s.Append(")* "); .) . END EBNF.
Home © P.D. Terry