Download Backus-Naur Form Grammar, Syntax Exercises and more Exercises Programming Languages in PDF only on Docsity! Programming Languages 3 Tutorial Exercises 1 Programming Languages 3 Tutorial Exercises (2013‐14) You should attempt these tutorial exercises before the PL3 tutorial session in the week concerned. Then you can contribute to the discussion during the tutorial session. Sample solutions will be posted at the PL3 Moodle site later in the course. Attempt each exercise before consulting the sample solution. Programming Languages 3 Tutorial Exercises 2 Exercises 1 (Syntax) 1A. (Regular expressions) In Cobol, an identifier consists of letters, digits, and hyphens (‘-’), but always starts with a letter. Hyphens may not occur consecutively, nor at the end of an identifier. Thus ‘setup’, ‘set-up’, and ‘s-et-up’ are well-formed identifiers, but ‘set--up’, ‘- setup’, and ‘setup-’ are ill-formed. (a) Write an RE that specifies the syntax of Cobol identifiers. (b) Write an EBNF grammar of Cobol identifiers. 1B. (Regular expressions) The Unix utility program egrep provides a pattern-matching notation, which is summarized in the course notes (slide 1-16). (a) Show how each of the following egrep patterns could be expressed in standard RE notation: b[aeiou]t b.t be*t b[aeiou]*t b(a|e|i)+t (b) Write and test egrep commands to do the following with a given file: (i) Find every line that contains ‘<H1>’, ‘<H2>’, …, or ‘<H9>’. (ii) Find every line that contains a sequence of one or more lower-case letters enclosed between ‘{’ and ‘}’. (iii) Find every line that contains a sequence of zero or more characters enclosed between ‘{’ and ‘}’. (iv) Find every line that contains ‘Mr’, ‘Ms’, ‘Mrs’, or ‘Miss’. (v) Find every line that contains ‘b’ followed by one or more consecutive occurrences of ‘an’ followed by ‘a’. 1C. (BNF) Consider the mini-English BNF grammar in the course notes (slide 1-22). That grammar generates some sentences, such as ‘I sees the cat .’, that would be ill- formed in the English language because the subject does not “agree” with the verb. (a) Modify the grammar to ensure that a 1st person subject agrees with a 1st person verb, and a 3rd person subject agrees with a 3rd person verb. (b) Add 2nd person subjects and verbs to the grammar. (c) (Optional) Add plurals to the grammar. 1D. (Phrase structure) Calc’s BNF grammar includes the following production rules: expr = prim | expr ‘+’ prim | expr ‘-’ prim | expr ‘*’ prim prim = num | id | ‘(’ expr ‘)’ (a) Draw the syntax trees of the following expressions: x+y*z x*y+z (b) Note that all operators have equal priority. Modify the grammar so that ‘*’ has higher priority than ‘+’ and ‘-’. For example, ‘x+y*z’ should be evaluated like ‘x+(y*z)’, but ‘x*y+z’ should be evaluated like ‘(x*y)+z’. 1E. (Ambiguity) Suppose that a programming language’s BNF grammar includes the following