2008-09-23 BNF, Grammars, Simple Parsing ======================================================================== >>> BNF, Grammars Getting back to the theme of the course: we want to investigate programming languages, and we want to do that *using* a programming language. The first thing when we design a language is to specify the language. For this we use BNF (Backus-Naur Form). For example, here is the definition of a simple arithmetic language: ::= | + | - Explain the different parts. Specifically, this is a mixture of low-level (concrete) syntax definition with parsing. We use this to derive expressions in some language. We start with , which should be on of these: * a number * , the text "+", and another * the same but with "-" is a terminal: when we reach it in the derivation, we're done. is a non-terminal: when we reach it, we have to continue with one of the options. It should be clear that the "+" and the "-" are things we expect to find in the input -- because they are not wrapped in <>s. We could specify what is: ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | But we don't -- why? Because in Scheme we have numbers as primitives and we want to use Scheme to implement our languages. This makes life a lot easier, and we get free stuff like floats, rationals etc. For example, we can use this to prove that "1-2+3" is a valid expression: + ; (2) + ; (1) - + ; (3) - + 3 ; (num) - + 3 ; (1) - + 3 ; (1) 1 - + 3 ; (num) 1 - 2 + 3 ; (num) This would be one way of doing this. Instead, we can can visualize the derivation using a tree, with the rules used at every node. (Leave this on -- later show that this removes some confusion but not all.) These specifications suffer from being ambiguous: an expression can be derived in multiple ways. Even the little syntax for a number is ambiguous -- a number like "123" can be derived in two ways that result in trees that look different. This ambiguity is not a "real" problem now, but it will become one very soon. We want to get rid of this ambiguity, so that there is a single (= deterministic) way to derive all expressions. There is a standard way to resolve that -- we add another non-terminal to the definition, and make it so that each rule can continue to exactly one of its alternatives. For example, this is what we can do with numbers: ::= | ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 Similar solutions can be applied to the BNF -- we either restrict the way derivations can happen or we come up with new non-terminals to force a deterministic derivation trees. As an example of restricting derivations, we look at the current grammar: ::= | + | - and instead of allowing an on both sides of the operation, we force one to be a number: ::= | + | - Now there is a single way to derive any expression, and it is always associating operations to the right: an expression like "1+2+3" can only be derived as "1+(2+3)". To change this to left-association, we would use this: ::= | + | - But what if we want to force precedence? Say that our AE syntax has addition and multiplication: ::= | + | * We can do that same thing as above and add new non-terminals -- say one for "factors": ::= | + | ::= | * Now we must parse any AE expression as additions of multiplications (or numbers). First, note that if goes to and that goes to , then there is no need for an to go to a , so this is the same syntax: ::= + | ::= | * Now, if we want to still be able to multiply additions, we can force them to appear in parentheses: ::= + | ::= | * | ( ) Next, note that AE is still ambiguous about additions, which can be fixed by forcing the left hand side of an addition to be a factor: ::= + | ::= | * | ( ) We still have an ambiguity for multiplications, so we do the same thing and add another non-terminal for "atoms": ::= + | ::= * | ::= | ( ) And you can try to derive several expressions to be convinced that derivation is always deterministic now. But as you can see, this is exactly the cosmetics that we want to avoid -- it will lead us to things that might be interesting, but unrelated to the principles behind programming languages. It will also become much much worse when we have a real language rather such a tiny one. Is there a good solution? -- It is right in our face: do what Scheme does -- always use fully parenthesized expressions: ::= | ( + ) | ( - ) But in Scheme *everything* has a value -- including those `+'s and `-'s, which makes this extremely convenient with future operations that might have either more or less arguments than 2. In our toy language we will do this for now, but later we will want to have something more powerful. To get prepared for that, we simplify this further -- put the operator in the first place and the arguments follow, all separated by white spaces: ::= | ( + ) | ( - ) In a sense, Scheme code is written in a form of already-parsed syntax... ======================================================================== >>> Simple Parsing Implementing a "parser" Unrelated to what the syntax actually looks like, we want to parse it as soon as possible -- converting the concrete syntax to an abstract syntax tree. No matter how we write our syntax: - 3+4 (infix), - 3 4 + (postfix), - +(3,4) (prefix with args in parens), - (+ 3 4) (parenthesized prefix), we always mean the same abstract thing -- adding the number 3 and the number 4. The essence of this is basically a tree structure with an addition operation as the root and two leaves holding the two numerals. With the right data definition, we can describe this in Scheme as the expression (Add (Num 3) (Num 4)) Similarly, the expression (3-4)+7 will be described in Scheme as the expression: (Add (Sub (Num 3) (Num 4)) (Num 7)) Important note: "expression" was used in two *different* ways in the above -- each way corresponds to a different language. To define the data type and the necessary constructors we will use this: (define-type AE [Num (n Number)] [Add (lhs AE) (rhs AE)] [Sub (lhs AE) (rhs AE)]) * Note -- scheme follows the tradition of Lisp which makes syntax issues almost negligible -- the language we use is almost as if we are using the parse tree directly. Actually, it is a very simple syntax for parse trees, one that makes parsing extremely easy. (This has an interesting historical reason... Some Lisp history -- M-expressions vs. S-expressions, and the fact that we write code that is isomorphic to an AST. Later we will see some of the advantages that we get by doing this.) To make things at a very simple level, we will use the above fact through a double-level approach: * we first "parse" our language into an intermediate representation -- a Scheme list -- this is mostly done by a modified version of Scheme's `read' that uses curly braces "{}"s instead of round parens "()"s, * then we write our own `parse' function that will parse the resulting list into an instance of the AE type -- an abstract syntax tree (AST). This is achieved by the following simple recursive function: ;; parse-sexpr : Sexpr -> AE ;; to convert s-expressions into AEs (define (parse-sexpr sexpr) (cond [(number? sexpr) (Num sexpr)] [(and (list? sexpr) (= 3 (length sexpr))) (let ([make-node (match (first sexpr) ['+ Add] ['- Sub] [else (error 'parse-sexpr "don't know about ~s" (first sexpr))])]) (make-node (parse-sexpr (second sexpr)) (parse-sexpr (third sexpr))))] [else (error 'parse-sexpr "bad syntax in ~s" sexpr)])) This function is pretty simple, but as our languages grow, they will become more verbose and more difficult to write. So, instead, we use a new special form: `match', which is matching a value and binds new identifiers to different parts (try it with "Check Syntax"). Re-writing the above code using `match': ;; parse-sexpr : Sexpr -> AE ;; to convert s-expressions into AEs (define (parse-sexpr sexpr) (match sexpr [(number: n) (Num n)] [(list '+ left right) (Add (parse-sexpr left) (parse-sexpr right))] [(list '- left right) (Sub (parse-sexpr left) (parse-sexpr right))] [else (error 'parse-sexpr "bad syntax in ~s" sexpr)])) To make things less confusing, we will combine this with the function that parses a string into a sexpr so we can use strings to represent our programs: ;; parse : String -> AE ;; parses a string containing an AE expression to an AE (define (parse str) (parse-sexpr (string->sexpr str))) ========================================================================