ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 12 CS2110 – Spring 2015 1.

Slides:



Advertisements
Similar presentations
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Advertisements

GRAMMARS & PARSING Lecture 7 CS2110 – Fall
Expression Trees What is an Expression tree? Expression tree implementation Why expression trees? Evaluating an expression tree (pseudo code) Prefix, Infix,
Prefix, Postfix, Infix Notation
GRAMMARS & PARSING Lecture 7 CS2110 – Fall Java Tips 2  Declare fields and methods public if they are to be visible outside the class; helper methods.
Topic 15 Implementing and Using Stacks
Stacks.
Context-Free Grammars Lecture 7
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Environments and Evaluation
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Topic 15 Implementing and Using Stacks
Class 4: Queues. cis 335 Fall 2001 Barry Cohen What is a queue? n A stack is an ordered sequence of items. n As in lists and stacks, each node contains.
Class 4: Stacks. cis 335 Fall 2001 Barry Cohen What is a stack? n A stack is an ordered sequence of items, of which only the last (‘top’) item can be.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Binary Trees. Node structure Data A data field and two pointers, left and right.
Grammars and Parsing. Sentence  Noun Verb Noun Noun  boys Noun  girls Noun  dogs Verb  like Verb  see Grammars Grammar: set of rules for generating.
2.2 A Simple Syntax-Directed Translator Syntax-Directed Translation 2.4 Parsing 2.5 A Translator for Simple Expressions 2.6 Lexical Analysis.
1 Introduction to Parsing Lecture 5. 2 Outline Regular languages revisited Parser overview Context-free grammars (CFG’s) Derivations.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
(c) University of Washington20d-1 CSC 143 Java Applications of Trees.
Parsing arithmetic expressions Reading material: These notes and an implementation (see course web page). The best way to prepare [to be a programmer]
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Information and Computer Sciences University of Hawaii, Manoa
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
1 Top Down Parsing. CS 412/413 Spring 2008Introduction to Compilers2 Outline Top-down parsing SLL(1) grammars Transforming a grammar into SLL(1) form.
PART I: overview material
Profs. Necula CS 164 Lecture Top-Down Parsing ICOM 4036 Lecture 5.
Lesson 3 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 12 CS2110 – Spring
CPS 506 Comparative Programming Languages Syntax Specification.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
GRAMMARS & PARSING Lecture 8 CS2110 – Spring If you are going to form a group for A2, please do it before tomorrow (Friday) noon.
Top-down Parsing lecture slides from C OMP 412 Rice University Houston, Texas, Fall 2001.
Compiler Construction By: Muhammad Nadeem Edited By: M. Bilal Qureshi.
Top-Down Parsing CS 671 January 29, CS 671 – Spring Where Are We? Source code: if (b==0) a = “Hi”; Token Stream: if (b == 0) a = “Hi”; Abstract.
Top-down Parsing. 2 Parsing Techniques Top-down parsers (LL(1), recursive descent) Start at the root of the parse tree and grow toward leaves Pick a production.
1 A Simple Syntax-Directed Translator CS308 Compiler Theory.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
Generics with ArrayList and HashSet 1 ge·ner·ic adjective \jə ̇ˈ nerik, -rēk\ relating or applied to or descriptive of all members of a genus, species,
Wednesday, March 2 Homework #2 is posted Homework #2 is posted Due Friday, March 4 (BOC) Due Friday, March 4 (BOC) Program #5 is posted Program #5 is posted.
Top-Down Parsing.
Parsing and Code Generation Set 24. Parser Construction Most of the work involved in constructing a parser is carried out automatically by a program,
GRAMMARS & PARSING. Parser Construction Most of the work involved in constructing a parser is carried out automatically by a program, referred to as a.
Prefix, Postfix, Infix Notation. Infix Notation  To add A, B, we write A+B  To multiply A, B, we write A*B  The operators ('+' and '*') go in between.
ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 13 CS2110 – Spring
Click to edit Master text styles Stacks Data Structure.
CMSC 330: Organization of Programming Languages Pushdown Automata Parsing.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
ASTs, Grammars, Parsing, Tree traversals
Grammars and Parsing.
A Simple Syntax-Directed Translator
ASTs, Grammars, Parsing, Tree traversals
Syntax-Directed Translation
ENERGY 211 / CME 211 Lecture 15 October 22, 2008.
ADTs, Grammars, Parsing, Tree traversals
Lecture 7: Introduction to Parsing (Syntax Analysis)
ASTs, Grammars, Parsing, Tree traversals
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Topic 15 Implementing and Using Stacks
CSC 143 Java Applications of Trees.
Trees, part 2 Lecture 13 CS2110 – Spring 2019
Presentation transcript:

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 12 CS2110 – Spring

ADT: Abstract Data Type 2 Just like a type: Bunch of values together with operations on them. Used often in discussing data structures Important: The definition says ntthing about the implementation, just about the behaviour of the operations –what they do. (Could describe necessary execution times of operations) Example: A stack is a list of values with these operations: 1. isEmpty: return true iff the stack is empty 2. Push: Put a value onto the front (top) of the stack 3. Pop: Remove and return the front (top) value of the stack Is a stack implemented in an array? singly linked list? doubly linked list? ArrayList? We don’t know.

ADT: Abstract Data Type 3 Just like a type: Bunch of values together with operations on them. /** an implementation of stack implements a LIFO list of values of type E. */ public interface stack { /** = “the list is empty.” */ boolean isEmpty(); /** Push v onto the top of the list. */ void push(E v); /** Remove top value on the list and return it. Precondition: the list is not empty. */ E pop(); Java interface is a great way to define an ADT!

Pointers to material 4  Parse trees: text, section  Definition of Java Language, sometimes useful: docs.oracle.com/javase/specs/jls/se7/html/index.html  Grammar for most of Java, for those who are curious: docs.oracle.com/javase/specs/jls/se7/html/jls-18.html docs.oracle.com/javase/specs/jls/se7/html/jls-18.html  Tree traversals –preorder, inorder, postorder: text, sections

Expression trees 5 Can draw a tree for (2 + 3) * (1 + (5 – 4) * – 4 public abstract class Exp { /* return the value of this Exp */ public abstract int eval(); } 5

Expression trees 6 public class Int extends Exp { int v; public int eval() { return v; } public class Add extends Exp { Exp left; Exp right; public int eval() { return left.eval() + right.eval(); } public abstract class Exp { /* return the value of this Exp */ public abstract int eval(); }

tree for (2 + 3) * (1 + – 4) 7 * – 4 Preorder traversal: 1. Visit the root 2. Visit left subtree, in preorder 3. Visit right subtree, in preorder * prefix and postfix notation proposed by Jan Lukasiewicz in 1951 Postfix (we see it later) is often called RPN for Reverse Polish Notation

tree for (2 + 3) * (1 + – 4) 8 * – 4 Postorder traversal: 1. Visit left subtree, in postorder 2. Visit right subtree, in postorder 3. Visit the root * In about 1974, Gries paid $300 for an HP calculator, which had some memory and used postfix notation! Still works. Come up to see it. Postfix notation

tree for (2 + 3) * (1 + – 4) 9 * – 4 Cornell tuition Calculator cost Percent 1973 $5030 $ $ 47,050 $ Then: (HP 45) RPN. 9 memory locations, 4-level stack, 1-line display Now: (HP 35S) RPN and infix. 30K user memory, 2-line display

tree for (2 + 3) * (1 + – 4) 10 * – * Postfix is easy to compute. Process elements left to right. Number? Push it on a stack Binary operator? Remove two top stack elements, apply operator to it, push result on stack Unary operator? Remove top stack element, apply operator to it, push result on stack Postfix notation

tree for (2 + 3) * (1 + – 4) 11 * – 4 Inorder traversal: 1. Visit left subtree, in inorder 2. Visit the root 3. Visit right subtree, in inorder To help out, put parens around expressions with operators (2 + 3) * (1 + (- 4))

Expression trees 12 public class Add extends Exp { Exp left; Exp right; /** Return the value of this exp. */ public int eval() {return left.eval() + right.eval();} /** Return the preorder.*/ public String pre() {return “+ “ + left.pre() + right.pre(); } /** Return the postorder.*/ public String post() {return left.post() + right.post() + “+ “; } } public abstract class Exp { public abstract int eval(); public abstract String pre(); public abstract String post(); }

Motivation for grammars 13  The cat ate the rat.  The cat ate the rat slowly.  The small cat ate the big rat slowly.  The small cat ate the big rat on the mat slowly.  The small cat that sat in the hat ate the big rat on the mat slowly, then got sick.  …  Not all sequences of words are legal sentences The ate cat rat the  How many legal sentences are there?  How many legal Java programs?  How do we know what programs are legal?

A Grammar Sentence  Noun Verb Noun Noun  boys Noun  girls Noun  bunnies Verb  like |see 14  White space between words does not matter  A very boring grammar because the set of Sentences is finite (exactly 18 sentences) Our sample grammar has these rules: A Sentence can be a Noun followed by a Verb followed by a Noun A Noun can be boys or girls or bunnies A Verb can be like or see

A Grammar Sentence  Noun Verb Noun Noun  boys Noun  girls Noun  bunnies Verb  like Verb  see 15 Grammar: set of rules for generating sentences of a language. Examples of Sentence:  boys see bunnies  bunnies like girls  The words boys, girls, bunnies, like, see are called tokens or terminals  The words Sentence, Noun, Verb are called nonterminals

A recursive grammar 16 Sentence  Sentence and Sentence Sentence  Sentence or Sentence Sentence  Noun Verb Noun Noun  boys Noun  girls Noun  bunnies Verb  like | see Grammar more interesting than previous one because the set of Sentences is infinite What makes this set infinite? Answer: Recursive definition of Sentence

Detour 17 What if we want to add a period at the end of every sentence? Sentence  Sentence and Sentence. Sentence  Sentence or Sentence. Sentence  Noun Verb Noun. Noun  … Does this work? No! This produces sentences like: girls like boys. and boys like bunnies.. Sentence

Sentences with periods 18 PunctuatedSentence  Sentence. Sentence  Sentence and Sentence Sentence  Sentence or Sentence Sentence  Noun VerbNoun Noun  boys Noun  girls Noun  bunnies Verb  like Verb  see  New rule adds a period only at end of sentence.  Tokens are the 7 words plus the period (.)  Grammar is ambiguous: boys like girls and girls like boys or girls like bunnies

Grammars for programming languages 19 Grammar describes every possible legal expression You could use the grammar for Java to list every possible Java program. (It would take forever.) Grammar tells the Java compiler how to “parse” a Java program docs.oracle.com/javase/specs/jls/se7/html/jls-2.html#jls-2.3

Grammar for simple expressions (not the best) 20 E  integer E  ( E + E ) Simple expressions:  An E can be an integer.  An E can be ‘(’ followed by an E followed by ‘+’ followed by an E followed by ‘)’ Set of expressions defined by this grammar is a recursively-defined set  Is language finite or infinite?  Do recursive grammars always yield infinite languages? Some legal expressions:  2  (3 + 34)  ((4+23) + 89) Some illegal expressions:  (3  Tokens of this grammar: ( + ) and any integer

Parsing 21 Use a grammar in two ways:  A grammar defines a language (i.e. the set of properly structured sentences)  A grammar can be used to parse a sentence (thus, checking if a string is asentence is in the language) To parse a sentence is to build a parse tree: much like diagramming a sentence  Example: Show that ((4+23) + 89) is a valid expression E by building a parse tree E ( E ) E+ 89 ( E ) E E  integer E  ( E + E )

Ambiguity 22 Grammar is ambiguous if it allows two parse trees for a sentence. The grammar below, using no parentheses, is ambiguous. The two parse trees to right show this. We don’t know which + to evaluate first in the expression E EE+ EE+ 12 E  integer E  E + E 3 22 E E E + EE + 12 E  integer E  E + E 3

Recursive descent parsing 23 Write a set of mutually recursive methods to check if a sentence is in the language (show how to generate parse tree later). One method for each nonterminal of the grammar. The method is completely determined by the rules for that nonterminal. On the next pages, we give a high-level version of the method for nonterminal E: E  integer E  ( E + E )

Parsing an E 24 /** Unprocessed input starts an E. Recognize that E, throwing away each piece from the input as it is recognized. Return false if error is detected and true if no errors. Upon return, processed tokens have been removed from input. */ public boolean parseE() E  integer E  ( E + E ) ( 2 + ( ) + 9 ) before call: already processed unprocessed ( 2 + ( ) + 9 ) after call: already processed unprocessed (call returns true)

Specification: /** Unprocessed input starts an E. …*/ 25 public boolean parseE() { if (first token is an integer) remove it from input and return true; if (first token is not ‘(‘ ) return false else remove it from input; if (!parseE()) return false; if (first token is not ‘+‘ ) return false else remove it from input; if (!parseE()) return false; if (first token is not ‘)‘ ) return false else remove it from input; return true; } E  integer E  ( E + E ) Same code used 3 times. Cries out for a method to do that

Illustration of parsing to check syntax 26 E  integer E  ( E + E ) ( 1 + ( ) ) E E E

The scanner constructs tokens 27 An object scanner of class Scanner is in charge of the input String. It constructs the tokens from the String as necessary. e.g. from the string “ ” build the token “1464”, the token “+”, and the token “634”. It is ready to work with the part of the input string that has not yet been processed and has thrown away the part that is already processed, in left-to-right fashion. already processed unprocessed ( 2 + ( ) + 9 )

Change parser to generate a tree 28 /** … Return a Tree for the E if no error. Return null if there was an error*/ public Tree parseE() { if (first token is an integer) remove it from input and return true; … } E  integer E  ( E + E ) if (first token is an integer) { Tree t= new Tree(the integer); Remove token from input; return t; }

Change parser to generate a tree 29 /** … Return a Tree for the E if no error. Return null if there was an error*/ public Tree parseE() { if (first token is an integer) … ; if (first token is not ‘(‘ ) return null else remove it from input; Tree t1= parse(E); if (t1 == null) return null; if (first token is not ‘+‘ ) return null else remove it from input; Tree t2= parse(E); if (t2 == null) return null; if (first token is not ‘)‘ ) return false else remove it from input; return new Tree(t1, ‘+’, t2); } E  integer E  ( E + E )

Code for a stack machine 30 Code for 2 + (3 + 4) PUSH 2 PUSH 3 PUSH 4 ADD ADD: remove two top values from stack, add them, and place result on stack It’s postfix notation! S t a c k

Code for a stack machine 31 Code for 2 + (3 + 4) PUSH 2 PUSH 3 PUSH 4 ADD ADD: remove two top values from stack, add them, and place result on stack It’s postfix notation! S t a c k 2 7 9

Use parser to generate code for a stack machine 32 Code for 2 + (3 + 4) PUSH 2 PUSH 3 PUSH 4 ADD ADD: remove two top values from stack, add them, and place result on stack parseE can generate code as follows:  For integer i, return string “PUSH ” + i + “\n”  For (E1 + E2), return a string containing  Code for E1  Code for E2  “ADD\n” It’s postfix notation!

Grammar that gives precedence to * over + 33 E -> T { + T } T -> F { * F } F -> integer F -> ( E ) * 4 says do * first T E Notation: { xxx } means 0 or more occurrences of xxx. E: Expression T: Term F: Factor F T FF T E F T F F * 4 Try to do + first, can’t complete tree

Does recursive descent always work? 34 Some grammars cannot be used for recursive descent Trivial example (causes infinite recursion): S  b S  Sa Can rewrite grammar S  b S  bA A  a A  aA For some constructs, recur- sive descent is hard to use Other parsing techniques exist – take the compiler writing course

Syntactic ambiguity 35 Sometimes a sentence has more than one parse tree S  A | aaxB A  x | aAb B  b | bB This kind of ambiguity sometimes shows up in programming languages. In the following, which then does the else go with? if E1 then if E2 then S1 else S2 aaxbb can be parsed in two ways

Syntactic ambiguity 36 This kind of ambiguity sometimes shows up in programming languages. In the following, which then does the else go with? if E1 then if E2 then S1 else S2 This ambiguity actually affects the program’s meaning Resolve it by either (1)Modify the grammar to eliminate the ambiguity (best) (2)Provide an extra non-grammar rule (e.g. else goes with closest if) Can also think of modifying the language (require end delimiters)

Summary: What you should know 37  preorder, inorder, and postorder traversal. How they can be used to get prefix notation, infix notation, and postfix notation for an expression tree.  Grammars: productions or rules, tokens or terminals, nonterminals. The parse tree for a sentence of a grammar.  Ambiguous grammar, because a sentence is ambiguous (has two different parse trees).  You should be able to tell whether string is a sentence of a simple grammar or not. You should be able to tell whether a grammar has an infinite number of sentences.  You are not responsible for recursive descent parsing

Exercises 38 Write a grammar and recursive descent parser for sentence palindromes that ignores white spaces & punctuation Was it Eliot's toilet I saw? No trace, not one carton Go deliver a dare, vile dog! Madam, I'm Adam Write a grammar and recursive program for strings A n B n AB AABB AAAAAAABBBBBBB Write a grammar and recursive program for Java identifiers [ or ] 0…N j27, but not 2j7