Recursive-Descent Parsing How might we write code to parse this grammar rule? (Suppose the input is a#, or perhaps b#) X -> a X() { if current token is 'a' advance token else throw error } We should also make a function to start the parser. parse() { // call the function for the start symbol X(); // need to check for the end marker if current token is '#' advance token else throw error } How might we write code to parse this rule? Y -> b c Y() { if current token is 'b' advance token else throw error if current token is 'c' advance token else throw error } We'll repeat the same code for each terminal. We should move it to a support function. match(t) { if current token is t advance token else throw error } Y() { match('b'); match('c'); } Write code to parse these rules. (Suppose the input is abcd#) R -> X Y d X -> a Y -> b c Write code to parse these rules. S -> X | Y X -> a Y -> b c Write code to parse these rules. S -> X S | Y X -> a Y -> b c Write code to parse these rules. S -> X S | epsilon X -> a Write code to parse these rules. T -> S | d S -> X | Y X -> a Y -> b c Write a recursive-descent parser for the grammar. (Note how this connects with the parse table.) (Write a function for each row of the table.) (Trace execution with input: 2+2) E -> T A A -> + T A | - T A | epsilon T -> ( E ) | 2 Classwork You may work with a partner. Write a recursive-descent parser for the grammar. (Please treat 'if' as a single token and 'then' as a single token.) S -> if E then S S -> E = E E -> 2 | x How do you write a Recursive-Descent Parser? write a function for each nonterminal in the grammar What does the function for a nonterminal do? the function simulates applying and selecting rules How does the function apply a rule? call a function for each symbol on the right side for terminals, call the match function for nonterminals, call the function for the nonterminal How does the function select the correct rule? use the rule whose right side starts with the current token How do you start parsing? call the function for the Start Symbol How does the parser complete parsing? check that the current token is the End Marker What must be true about the grammar for this to work? the grammar must be LL(1) must be able to decide which rule to use with only one symbol of look-ahead