Presentation is loading. Please wait.

Presentation is loading. Please wait.

ENERGY 211 / CME 211 Lecture 15 October 22, 2008.

Similar presentations


Presentation on theme: "ENERGY 211 / CME 211 Lecture 15 October 22, 2008."— Presentation transcript:

1 ENERGY 211 / CME 211 Lecture 15 October 22, 2008

2 Scanning and Parsing Input
Characters are scanned from left to right and grouped into tokens (e.g. numbers, operators, parentheses) Tokens are parsed from left to right according to a hierarchical grammar Example: an expression is a sum of terms, which is a product of factors At lowest level of grammar, tokens are compared against syntactic rules

3 Evaluation by Stack Stacks are useful for evaluating postfix expressions, where operands precede operators (e.g * for (3+4)*5) Operands are pushed onto a stack When operator is encountered, pop the operands, perform the operation, then push the result Parsing expressions recursively naturally generates postfix form

4 Specifying Languages For compiling, programming languages must have formal descriptions of their constructs and operations In Project 2, we used regular expressions to specify tokens These expressions are insufficient for specifying syntax, because of their nonrecursive nature They have “no memory”—e.g. can’t do strings of balanced parentheses

5 Context-Free Grammars
A context-free grammar is typically used to specify the syntax of a programming language It consists of: productions, the rules of the grammar terminal and nonterminal symbols terminals are the tokens nonterminals are higher-level constructs The start symbol, the highest-level nonterminal

6 Example: Expressions Terminals: num, +, -, *, /
Nonterminals: E (expression), T (term), F (factor); E is start symbol Productions: E -> E + T | E - T | T T -> T * F | T / F | F F -> -F | num In description, | separates alternatives In English: a factor is either the negation of another factor, or a number

7 Recursive-Descent Parsing
Recursive-descent parsing is a one approach to implementing parsers for grammars Productions provide a blueprint for implementation: each nonterminal gets its own function, which calls functions for other nonterminals Must modify grammar to remove left recursion such as E -> E + T Remedy: call T, stop if next token not +

8 Next Time Basics of classes Declaration and Implementation
Access specifiers Overloading operators Testing


Download ppt "ENERGY 211 / CME 211 Lecture 15 October 22, 2008."

Similar presentations


Ads by Google