Computer Science 112 Fundamentals of Programming II Recursive Processing of Languages.

Slides:



Advertisements
Similar presentations
Application: Yacc A parser generator A context-free grammar An LR parser Yacc Yacc input file:... definitions... %... production rules... %... user-defined.
Advertisements

Translator Architecture Code Generator ParserTokenizer string of characters (source code) string of tokens abstract program string of integers (object.
Computer Science 112 Fundamentals of Programming II Applications of Stacks.
Grammars, Languages and Parse Trees. Language Let V be an alphabet or vocabulary V* is set of all strings over V A language L is a subset of V*, i.e.,
Grammars.
Chapter 2 Syntax. Syntax The syntax of a programming language specifies the structure of the language The lexical structure specifies how words can be.
CSE 3302 Programming Languages Chengkai Li, Weimin He Spring 2008 Syntax Lecture 2 - Syntax, Spring CSE3302 Programming Languages, UT-Arlington ©Chengkai.
9/27/2006Prof. Hilfinger, Lecture 141 Syntax-Directed Translation Lecture 14 (adapted from slides by R. Bodik)
Chapter 4 Lexical and Syntax Analysis Sections 1-4.
CS 330 Programming Languages 09 / 13 / 2007 Instructor: Michael Eckmann.
Chapter 9 Compilers and Language Translation. The Compilation Process Phase I: Lexical analysis Phase I: Lexical analysis Phase II: Parsing Phase II:
CS 330 Programming Languages 09 / 23 / 2008 Instructor: Michael Eckmann.
Chapter 3: Formal Translation Models
COP4020 Programming Languages
S YNTAX. Outline Programming Language Specification Lexical Structure of PLs Syntactic Structure of PLs Context-Free Grammar / BNF Parse Trees Abstract.
Computer Science 111 Fundamentals of Programming I Sequences: Lists.
(2.1) Grammars  Definitions  Grammars  Backus-Naur Form  Derivation – terminology – trees  Grammars and ambiguity  Simple example  Grammar hierarchies.
1.3 Executing Programs. How is Computer Code Transformed into an Executable? Interpreters Compilers Hybrid systems.
1 Syntax and Semantics The Purpose of Syntax Problem of Describing Syntax Formal Methods of Describing Syntax Derivations and Parse Trees Sebesta Chapter.
2.2 A Simple Syntax-Directed Translator Syntax-Directed Translation 2.4 Parsing 2.5 A Translator for Simple Expressions 2.6 Lexical Analysis.
Grammars.
Chpater 3. Outline The definition of Syntax The Definition of Semantic Most Common Methods of Describing Syntax.
Computer Science 112 Fundamentals of Programming II Expression Trees.
Software II: Principles of Programming Languages
ICS611 Introduction to Compilers Set 1. What is a Compiler? A compiler is software (a program) that translates a high-level programming language to machine.
CPSC 388 – Compiler Design and Construction Parsers – Context Free Grammars.
Parsing arithmetic expressions Reading material: These notes and an implementation (see course web page). The best way to prepare [to be a programmer]
Chapter 1 Introduction Dr. Frank Lee. 1.1 Why Study Compiler? To write more efficient code in a high-level language To provide solid foundation in parsing.
Chapter 10: Compilers and Language Translation Invitation to Computer Science, Java Version, Third Edition.
CSI 3120, Grammars, page 1 Language description methods Major topics in this part of the course: –Syntax and semantics –Grammars –Axiomatic semantics (next.
Winter 2007SEG2101 Chapter 71 Chapter 7 Introduction to Languages and Compiler.
Syntax and Backus Naur Form
CSCI 3130: Automata theory and formal languages Andrej Bogdanov The Chinese University of Hong Kong Context-free.
Syntax: 10/18/2015IT 3271 Semantics: Describe the structures of programs Describe the meaning of programs Programming Languages (formal languages) -- How.
Lesson 3 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
D. M. Akbar Hussain: Department of Software & Media Technology 1 Compiler is tool: which translate notations from one system to another, usually from source.
ISBN Chapter 3 Describing Syntax and Semantics.
1 Syntax In Text: Chapter 3. 2 Chapter 3: Syntax and Semantics Outline Syntax: Recognizer vs. generator BNF EBNF.
CSCI 3130: Automata theory and formal languages Andrej Bogdanov The Chinese University of Hong Kong Context-free.
CPS 506 Comparative Programming Languages Syntax Specification.
D Goforth COSC Translating High Level Languages.
D Goforth COSC Translating High Level Languages Note error in assignment 1: #4 - refer to Example grammar 3.4, p. 126.
Chapter 3 Describing Syntax and Semantics
Artificial Intelligence: Natural Language
The Functions and Purposes of Translators Syntax (& Semantic) Analysis.
Syntax The Structure of a Language. Lexical Structure The structure of the tokens of a programming language The scanner takes a sequence of characters.
GRAMMARS & PARSING Lecture 8 CS2110 – Spring If you are going to form a group for A2, please do it before tomorrow (Friday) noon.
Compiler Construction By: Muhammad Nadeem Edited By: M. Bilal Qureshi.
1 A Simple Syntax-Directed Translator CS308 Compiler Theory.
Syntax and Semantics Form and Meaning of Programming Languages Copyright © by Curt Hill.
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.
CS 330 Programming Languages 09 / 25 / 2007 Instructor: Michael Eckmann.
Composing Music with Grammars. grammar the whole system and structure of a language or of languages in general, usually taken as consisting of syntax.
7.2 Programming Languages - An Introduction to Informatics WMN Lab. Hye-Jin Lee.
ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 13 CS2110 – Spring
PROGRAMMING LANGUAGES
System Software Unit-1 (Language Processors) A TOY Compiler
Fundamentals of Programming II Recursive Processing of Languages
Fundamentals of Programming I A Sentence Generator
Chapter 4 Syntax Analysis.
Lexical and Syntax Analysis
ENERGY 211 / CME 211 Lecture 15 October 22, 2008.
Computer Science 210 Computer Organization
R.Rajkumar Asst.Professor CSE
CMPE 152: Compiler Design August 21/23 Lab
CS 3304 Comparative Languages
Chapter 10: Compilers and Language Translation
Text Files and Random Numbers
Presentation transcript:

Computer Science 112 Fundamentals of Programming II Recursive Processing of Languages

Languages and Grammars A grammar specifies the rules for constructing well-formed sentences in a language Every language, including a programming language, has a grammar

Applications Grammar checkers in word processors Programming language compilers Natural language queries (Google, etc.)

Generate Sentences in English Given a vocabulary and grammar rules, one can generate some random and perhaps rather silly sentences Vocabulary - the set of words belonging to the parts of speech (nouns, verbs, articles, prepositions) Grammar - the set of rules for building phrases in a sentence (noun phrase, verb phrase, prepositional phrase)

The Structure of a Sentence sentence noun phrase verb phrase A sentence is a noun phrase followed by a verb phrase

The Structure of a Sentence sentence noun phrase verb phrase article noun A noun phrase is an article followed by a noun

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun the girl Pick actual words for those parts of speech at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase the girl A verb phrase is a verb followed by a noun phrase and a prepositional phrase

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase the girl hit Pick a verb at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun the girl hit Expand a noun phrase again

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun the girl hit the boy Pick an article and a noun at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase the girl hit the boy A prepositional phrase is a preposition followed by a noun phrase

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase the girl hit the boy with Pick a preposition at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase article noun the girl hit the boy with Expand another noun phrase

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase article noun the girl hit the boy with a bat More random words from the parts of speech

Representing the Vocabulary nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair', 'fence', 'table', 'computer', 'cake', 'field'] verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped'] prepositions = ['with', 'to', 'from', 'on', 'below', 'above', 'beside'] articles = ['a', 'the'] Use a list of words for each part of speech (lexical category)

Picking a Word at Random nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair', 'fence', 'table', 'computer', 'cake', 'field'] verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped'] prepositions = ['with', 'to', 'from', 'on', 'below', 'above', 'beside'] articles = ['a', 'the'] import random print(random.choice(verbs)) # Prints a randomly chosen verb The random module includes functions to select numbers, sequence elements, etc., at random

Grammar Rules sentence = nounphrase verbphrase nounphrase = article noun verbphrase = verb nounphrase prepositionalphrase prepositonalphrase = preposition nounphrase A sentence is a noun phrase followed by a verb phrase Etc., etc.

Define a Function for Each Rule # sentence = nounphrase verbphrase def sentence(): return nounphrase() + ' ' + verbphrase() Each function builds and returns a string that is an instance of the phrase Separate phrases and words with a space

Define a Function for Each Rule # sentence = nounphrase verbphrase def sentence(): return nounphrase() + ' ' + verbphrase() # nounphrase = article noun def nounphrase(): return random.choice(articles) + ' ' + random.choice(nouns) When a part of speech is reached, select an instance at random from the relevant list of words

Call sentence() to Try It Out # sentence = nounphrase verbphrase def sentence(): return nounphrase() + ' ' + verbphrase() # nounphrase = article noun def nounphrase(): return random.choice(articles) + ' ' + random.choice(nouns) … for x in range(10): print(sentence()) # Display 10 sentences You can also generate examples of the other phrases by calling their functions

Kinds of Symbols in a Grammar Terminal symbols: words in the vocabulary of the language Non-terminal symbols: words that describe phrases or portions of sentences Metasymbols: used to construct rules

Metasymbols for a Grammar MetasymbolsUse "" Enclose literal items = Means "is defined as" [ ] Enclose optional items { } Enclose zero or more items ( ) Group together required choices | Indicates a choice

A Grammar of Arithmetic Expressions expression = term { addingOperator term } term = factor { multiplyOperator factor } factor = primary ["^" primary ] primary = number | "(" expression ")" number = digit { digit } digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" addingOperator = "+" | "-" multiplyingOperator = "*" | "/" Example sentences: 3, 4 + 5, * 3, (5 + 2) * 3 ^ 4

Alternative Notation: Train Track term = factor { multiplyingOperator factor } factor * / primary = number | "(" expression ")" number () expression

Parsing A parser analyzes a source program to determine whether or not it is syntactically correct Parser Source language program Syntax error messages OK or not OK

Scanning A scanner picks out words in a source program and sends these to the parser Parser Source language program Syntax error messages Ok or not OK Scanner Lexical error messages Tokens

Scanner(aString)Creates a scanner on a source string get()Returns the current token (at the cursor) next()Advances the cursor to the next token The Scanner Interface

Tokens A Token object has two attributes: –type (indicating an operand or operator) –value (an int if it ’ s an operand, or the source string otherwise) Token types are –Token.EOE –Token.PLUS, Token.MINUS –Token.MUL, Token.DIV –Token.INT –Token.UNKNOWN

The Token Interface Token(source)Creates a token from a source string str(aToken)String representation isOperator()True if an operator, false otherwise getType()Returns the type getValue()Returns the value

Recursive Descent Parsing Each rule in the grammar translates to a Python parsing method def expression(self): self.term() token = self.scanner.get() while token.getType() in (Token.PLUS, Token.MINUS): self.scanner.next() self.term() token = self.scanner.get() expression = term { addingOperator term }

Recursive Descent Parsing Each method is responsible for a phrase in an expression def term(self): self.factor() token = self.scanner.get() while token.getType() in (Token.MUL, Token.DIV): self.scanner.next() self.factor() token = self.scanner.get() term = factor { multiplyingOperator factor }

Recursive Descent Parsing primary = number | "(" expression ")" def primary(self): token = self.scanner.get() if token.getType() == Token.INT: self.scanner.next() elif token.getType() == Token.L_PAR: self.scanner.next() self.expression() self.accept(self._scanner.get(), Token.R_PAR, "')' expected") self.scanner.next() else: self.fatalError(token, "bad primary")

For Monday Expression Trees