Assignment of Bachelor's Thesis

Total Page:16

File Type:pdf, Size:1020Kb

Assignment of Bachelor's Thesis CZECH TECHNICAL UNIVERSITY IN PRAGUE FACULTY OF INFORMATION TECHNOLOGY ASSIGNMENT OF BACHELOR’S THESIS Title: Automata library - LR parser construction Student: Martin Kočička Supervisor: Ing. Jan Trávníček Study Programme: Informatics Study Branch: Computer Science Department: Department of Theoretical Computer Science Validity: Until the end of summer semester 2016/17 Instructions Get familiar with the current implementation of the Automata library toolkit[1]. Study LR(0) and SLR(1) parser construction. Propose suitable extensions of data structures in Automata library toolkit for representing LR(0) and SLR(1) parser. Implement these extensions of data structures. Extend the library to include LR(0) and SLR(1) parser construction algorithms using these new data structures. Implement an algorithm of syntactic analysis using the LR(0) and SLR(1) parser. Test the implemented extensions and algorithms. References [1] Martin Žák: Automatová knihovna – vnitřní a komunikační formát. Bakalářská práce, České vysoké učení technické v Praze, Fakulta informačních technologií, Praha, 2014. L.S. doc. Ing. Jan Janoušek, Ph.D. prof. Ing. Pavel Tvrdík, CSc. Head of Department Dean Prague January 9, 2016 Czech Technical University in Prague Faculty of Information Technology Department of Theoretical Computer Science Bachelor's thesis Automata library { LR parser construction Martin Koˇciˇcka Supervisor: Ing. Jan Tr´avn´ıˇcek 17th May 2016 Declaration I hereby declare that the presented thesis is my own work and that I have cited all sources of information in accordance with the Guideline for adhering to ethical principles when elaborating an academic final thesis. I acknowledge that my thesis is subject to the rights and obligations stip- ulated by the Act No. 121/2000 Coll., the Copyright Act, as amended. In accordance with Article 46(6) of the Act, I hereby grant a nonexclusive author- ization (license) to utilize this thesis, including any and all computer programs incorporated therein or attached thereto and all corresponding documentation (hereinafter collectively referred to as the \Work"), to any and all persons that wish to utilize the Work. Such persons are entitled to use the Work in any way (including for-profit purposes) that does not detract from its value. This authorization is not limited in terms of time, location and quantity. However, all persons that makes use of the above license shall be obliged to grant a license at least in the same scope as defined above with respect to each and every work that is created (wholly or in part) based on the Work, by modi- fying the Work, by combining the Work with another work, by including the Work in a collection of works or by adapting the Work (including translation), and at the same time make available the source code of such work at least in a way and scope that are comparable to the way and scope in which the source code of the Work is made available. In Prague on 17th May 2016 . Czech Technical University in Prague Faculty of Information Technology c 2016 Martin Koˇciˇcka. All rights reserved. This thesis is school work as defined by Copyright Act of the Czech Republic. It has been submitted at Czech Technical University in Prague, Faculty of Information Technology. The thesis is protected by the Copyright Act and its usage without author's permission is prohibited (with exceptions defined by the Copyright Act). Citation of this thesis Koˇciˇcka, Martin. Automata library { LR parser construction. Bachelor's thesis. Czech Technical University in Prague, Faculty of Information Techno- logy, 2016. Abstract This thesis covers basic LR parsing algorithms. We describe bottom-up and shift-reduce parsing methods in general, and then we focus on LR parsing. We go into more detail with two algorithms|LR(0) and SLR(1). Suitable algorithms and data structures are presented and implemented into the Auto- mata library. We also explore existing solutions and the Automata library itself. Keywords parsing, bottom-up parsing, shift-reduce parsing, LR parsing, SLR parser vii Abstrakt Pˇredmˇetemt´etopr´acejsou z´akladn´ıLR parsovac´ıalgoritmy. Pr´acev ´uvodu popisuje obecnˇebottom-up a shift-reduce parsov´an´ı. D´alese zamˇeˇrujena LR parsov´an´ı, specificky LR(0) a SLR(1) parsery. Pr´aceobsahuje n´avrh potˇrebn´ych datov´ych struktur a algoritm˚upro implementaci tˇechto parser˚u. Jsou prozkoum´anaexistuj´ıc´ıˇreˇsen´ı,a pˇrid´anz´akladn´ıpopis Automatov´ekni- hovny. Pr´aceje souˇc´ast´ıprojektu Automatov´aknihovna. Kl´ıˇcov´aslova parsov´an´ı,bottom-up parsov´an´ı,shift-reduce parsov´an´ı,LR parsov´an´ı,SLR parser viii Contents Introduction 1 1 Theory 3 1.1 Strings . 3 1.2 Grammars . 4 1.3 Deterministic finite automaton . 6 2 Bottom-up parsing 9 2.1 Reductions . 9 2.2 Shift-reduce parser . 10 2.3 Conflicts . 11 3 LR parsing 13 3.1 Action table . 13 3.2 Goto table . 15 3.3 Parsing algorithm . 15 4 LR(0) parsing 17 4.1 LR(0) item . 17 4.2 LR(0) closure . 18 4.3 Augmented grammar . 18 4.4 LR(0) automaton . 19 4.5 SLR(1) parsing . 21 5 Analysis 25 5.1 Existing solutions . 25 5.2 Automata library . 26 6 Implementation 29 6.1 Enumeration LRAction . 29 ix 6.2 Type definitions . 29 6.3 Class LRParser . 30 6.4 Class LR0Parser . 31 6.5 Class SLR1ParseTable . 31 6.6 Class LR0ItemsLabel . 32 6.7 Testing . 32 Conclusion 33 Bibliography 35 A List of used abbreviations 37 B Contents of enclosed memory card 39 x List of Figures 1.1 Parse tree for the expression grammar and sentential form id + id. 6 1.2 Example of a deterministic finite automaton. 7 3.1 LR parser. 14 4.1 LR(0) automaton for the expression grammar. 20 xi List of Tables 2.1 State of the shift-reduce parser after a successful parse. 10 2.2 Shift-reduce parse of a string (id + id) from the expression grammar. 11 3.1 Action table for the expression grammar. 15 3.2 Goto table for the expression grammar. 16 xiii Introduction Parsing (syntax analysis) is one of the most crucial tasks solved in computing. It has wide range of usages|from processing programming languages, struc- tured text such as XML, structured binary data, to DNA pattern recognition and many more. Parsing algorithms can be split into two categories: top-down and bottom- up. Names of these two methods are referring to parse trees, but it is easier to explain the parsing process using formal grammars. In top-down method, we start with the initial symbol of a grammar, and apply production rules until we produce the input string. On the other hand, in bottom-up method we start with the input string, and replace right-hand sides of the production rules by the nonterminals inside the string, until we reduce it to the start symbol. This thesis focuses on LR parsing. LR parsers are deterministic bottom- up parsers, which produce a correct parse in linear time, due to the fact that they don't do any guessing or backtracking. LR parsers read input from left to right, construct a rightmost derivation in reverse, and they can detect syntax errors as soon as possible. The objective of this thesis is to describe selected algorithms, and to im- plement them into the Automata library. Two algorithms, LR(0) and SLR(1), have been selected, since they are the foundation of almost all other powerful LR parsing methods. 1 Chapter 1 Theory 1.1 Strings Definition 1.1.1. Alphabet is a finite set of elements (called symbols). Example 1.1.1. Set f0; 1g is an alphabet consisting of two symbols. Definition 1.1.2. String is a finite sequence of symbols belonging to the alphabet. Instead of denoting the strings using the sequence notation, we will just append the symbols to each other. Example 1.1.2. The string (α0; α1; α2; α3) will be written as α0α1α2α3. Example 1.1.3. 0, 01 and 01101 are examples of strings over alphabet f0; 1g. Definition 1.1.3. The number of symbols in the sequence is called length of the string, and for an arbitrary string w, the length will be denoted jwj. Definition 1.1.4. An empty sequence of symbols is also a string, called empty string. It will be denoted using symbol ". Definition 1.1.5. Let x = (x0; x1; : : : ; xn−1; xn) and y = (y0; y1; : : : ; ym−1; ym) be strings. String z = (x0; x1; : : : ; xn−1; xn; y0; y1; : : : ; ym−1; ym) is called the concatenation of strings x and y, and will be denoted xy. Example 1.1.4. String 01101 is a concatenation of strings 01 and 101. Definition 1.1.6. Language is a set of strings over an alphabet. Example 1.1.5. Set f0; 01; 01101g is a language over the alphabet f0; 1g. 3 1. Theory 1.2 Grammars Definition 1.2.1. Grammar is a quadruple consisting of following elements: 1. Finite set of nonterminal symbols (often denoted N). 2. Finite set of terminal symbols (often denoted Σ). Finite set of production rules of the form α ! β 3. where α 2 (N [ Σ)∗N(N [ Σ)∗ and β 2 (N [ Σ)∗ (often denoted P ). 4. Start symbol which belongs to N (often denoted S). It is common to write the rules for the same left-hand side on one line, separating right-hand sides using the pipe symbol \j". Example 1.2.1. Production rules A ! α; A ! β; A ! γ could be written as A ! α j β j γ. 1.2.1 Context-free grammar Definition 1.2.2. Context-free grammar is a grammar where all the produc- tion rules are in format A ! α (A is a single nonterminal symbol and α is a string of nonterminal and/or terminal symbols).
Recommended publications
  • Parser Tables for Non-LR(1) Grammars with Conflict Resolution Joel E
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by Elsevier - Publisher Connector Science of Computer Programming 75 (2010) 943–979 Contents lists available at ScienceDirect Science of Computer Programming journal homepage: www.elsevier.com/locate/scico The IELR(1) algorithm for generating minimal LR(1) parser tables for non-LR(1) grammars with conflict resolution Joel E. Denny ∗, Brian A. Malloy School of Computing, Clemson University, Clemson, SC 29634, USA article info a b s t r a c t Article history: There has been a recent effort in the literature to reconsider grammar-dependent software Received 17 July 2008 development from an engineering point of view. As part of that effort, we examine a Received in revised form 31 March 2009 deficiency in the state of the art of practical LR parser table generation. Specifically, LALR Accepted 12 August 2009 sometimes generates parser tables that do not accept the full language that the grammar Available online 10 September 2009 developer expects, but canonical LR is too inefficient to be practical particularly during grammar development. In response, many researchers have attempted to develop minimal Keywords: LR parser table generation algorithms. In this paper, we demonstrate that a well known Grammarware Canonical LR algorithm described by David Pager and implemented in Menhir, the most robust minimal LALR LR(1) implementation we have discovered, does not always achieve the full power of Minimal LR canonical LR(1) when the given grammar is non-LR(1) coupled with a specification for Yacc resolving conflicts. We also detail an original minimal LR(1) algorithm, IELR(1) (Inadequacy Bison Elimination LR(1)), which we have implemented as an extension of GNU Bison and which does not exhibit this deficiency.
    [Show full text]
  • The Design & Implementation of an Abstract Semantic Graph For
    Clemson University TigerPrints All Dissertations Dissertations 12-2011 The esiD gn & Implementation of an Abstract Semantic Graph for Statement-Level Dynamic Analysis of C++ Applications Edward Duffy Clemson University, [email protected] Follow this and additional works at: https://tigerprints.clemson.edu/all_dissertations Part of the Computer Sciences Commons Recommended Citation Duffy, Edward, "The eD sign & Implementation of an Abstract Semantic Graph for Statement-Level Dynamic Analysis of C++ Applications" (2011). All Dissertations. 832. https://tigerprints.clemson.edu/all_dissertations/832 This Dissertation is brought to you for free and open access by the Dissertations at TigerPrints. It has been accepted for inclusion in All Dissertations by an authorized administrator of TigerPrints. For more information, please contact [email protected]. THE DESIGN &IMPLEMENTATION OF AN ABSTRACT SEMANTIC GRAPH FOR STATEMENT-LEVEL DYNAMIC ANALYSIS OF C++ APPLICATIONS A Dissertation Presented to the Graduate School of Clemson University In Partial Fulfillment of the Requirements for the Degree Doctor of Philosophy Computer Science by Edward B. Duffy December 2011 Accepted by: Dr. Brian A. Malloy, Committee Chair Dr. James B. von Oehsen Dr. Jason P. Hallstrom Dr. Pradip K. Srimani In this thesis, we describe our system, Hylian, for statement-level analysis, both static and dynamic, of a C++ application. We begin by extending the GNU gcc parser to generate parse trees in XML format for each of the compilation units in a C++ application. We then provide verification that the generated parse trees are structurally equivalent to the code in the original C++ application. We use the generated parse trees, together with an augmented version of the gcc test suite, to recover a grammar for the C++ dialect that we parse.
    [Show full text]
  • Parsing Techniques
    Dick Grune, Ceriel J.H. Jacobs Parsing Techniques 2nd edition — Monograph — September 27, 2007 Springer Berlin Heidelberg NewYork Hong Kong London Milan Paris Tokyo Contents Preface to the Second Edition : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : v Preface to the First Edition : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : xi 1 Introduction : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 1 1.1 Parsing as a Craft. 2 1.2 The Approach Used . 2 1.3 Outline of the Contents . 3 1.4 The Annotated Bibliography . 4 2 Grammars as a Generating Device : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 5 2.1 Languages as Infinite Sets . 5 2.1.1 Language . 5 2.1.2 Grammars . 7 2.1.3 Problems with Infinite Sets . 8 2.1.4 Describing a Language through a Finite Recipe . 12 2.2 Formal Grammars . 14 2.2.1 The Formalism of Formal Grammars . 14 2.2.2 Generating Sentences from a Formal Grammar . 15 2.2.3 The Expressive Power of Formal Grammars . 17 2.3 The Chomsky Hierarchy of Grammars and Languages . 19 2.3.1 Type 1 Grammars . 19 2.3.2 Type 2 Grammars . 23 2.3.3 Type 3 Grammars . 30 2.3.4 Type 4 Grammars . 33 2.3.5 Conclusion . 34 2.4 Actually Generating Sentences from a Grammar. 34 2.4.1 The Phrase-Structure Case . 34 2.4.2 The CS Case . 36 2.4.3 The CF Case . 36 2.5 To Shrink or Not To Shrink . 38 xvi Contents 2.6 Grammars that Produce the Empty Language . 41 2.7 The Limitations of CF and FS Grammars . 42 2.7.1 The uvwxy Theorem . 42 2.7.2 The uvw Theorem .
    [Show full text]
  • GLR* - an Efficient Noise-Skipping Parsing Algorithm for Context Free· Grammars
    GLR* - An Efficient Noise-skipping Parsing Algorithm For Context Free· Grammars Alon Lavie and Masaru Tomita School of Computer Scienc�, Carnegie Mellon University 5000 Forbes- Avenue, Pittsburgh, PA 15213 email: lavie©cs. emu . edu Abstract This paper describes GLR*, a parser that can parse any input sentence by ignoring unrec­ ognizable parts of the sentence. In case the standard parsing procedure fails to parse an input sentence, the parser nondeterministically skips some word(s) in the sentence, and returns the parse with fewest skipped words. Therefore, the parser will return some parse(s) with any input sentence, unless no part of the sentence can be recognized at all. The problem can be defined in the following way: Given a context-free grammar G and a sentence S, find and parse S' - the largest subset of words of S, such that S' E L(G). The algorithm described in this paper is a modificationof the Generalized LR (Tomita) parsing algorithm [Tomita, 1986]. The parser accommodates the skipping of words by allowing shift operations to be performed from inactive state nodes of the Graph Structured Stack. A heuristic similar to beam search makes the algorithm computationally tractable. There have been several other approaches to the problem of robust parsing, most of which are special purpose algorithms [Carbonell and Hayes, 1984), [Ward, 1991] and others. Because our approach is a modification to a standard context-free parsing algorithm, all the techniques and grammars developed for the standard parser can be applied as they are. Also, in case the input sentence is by itself grammatical, our parser behaves exactly as the standard GLR parser.
    [Show full text]
  • A Simple, Possibly Correct LR Parser for C11 Jacques-Henri Jourdan, François Pottier
    A Simple, Possibly Correct LR Parser for C11 Jacques-Henri Jourdan, François Pottier To cite this version: Jacques-Henri Jourdan, François Pottier. A Simple, Possibly Correct LR Parser for C11. ACM Transactions on Programming Languages and Systems (TOPLAS), ACM, 2017, 39 (4), pp.1 - 36. 10.1145/3064848. hal-01633123 HAL Id: hal-01633123 https://hal.archives-ouvertes.fr/hal-01633123 Submitted on 11 Nov 2017 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. 14 A simple, possibly correct LR parser for C11 Jacques-Henri Jourdan, Inria Paris, MPI-SWS François Pottier, Inria Paris The syntax of the C programming language is described in the C11 standard by an ambiguous context-free grammar, accompanied with English prose that describes the concept of “scope” and indicates how certain ambiguous code fragments should be interpreted. Based on these elements, the problem of implementing a compliant C11 parser is not entirely trivial. We review the main sources of difficulty and describe a relatively simple solution to the problem. Our solution employs the well-known technique of combining an LALR(1) parser with a “lexical feedback” mechanism. It draws on folklore knowledge and adds several original as- pects, including: a twist on lexical feedback that allows a smooth interaction with lookahead; a simplified and powerful treatment of scopes; and a few amendments in the grammar.
    [Show full text]
  • OPTIMAL AMBIGUITY PACKING in CONTEXT-FREE PARSERS with Intaloner Laleavie VED Unicarolynfica Pensttionein Rose Language Technologies Inst
    OPTIMAL AMBIGUITY PACKING IN CONTEXT-FREE PARSERS WITH INTAlonER LaLEAvie VED UNICarolynFICA PenstTIONein Rose Language Technologies Inst. Learning Res. and Dev. Center Carnegie Mellon University University of Pittsburgh Pittsburgh, PA 15213 Pittsburgh, PA 15213 alavie©cs . cmu .edu rosecpCpitt .edu Abstract Ambiguity packing is a well known technique for enhancing the efficiency of context-free parsers. However, in the case of unification-augmented context-free parsers where parsing is interleaved with feature unification, the propagation of feature structures imposes difficulties on the ability of the parser to effectively perform ambiguity packing. We demonstrate that a clever heuristic for prioritizing the execution order of grammar rules and parsing actions can achieve a high level of ambiguity packing that is provably optimal. We present empirical evaluations of the proposed technique, performed with both a Generalized LR parser and a chart parser, that demonstrate its effectiveness. 1 Introduction Efficient parsing algorithms for purely context-free grammars have long been known. Most natural language applications, however, require a far more linguistically detailed level of analysis that cannot be supported in a natural way by pure context-free grammars. Unification-based grammar formalisms (such as HPSG), on the other hand, are linguistically well founded, but are difficult to parse efficiently. Unification-augmented context-free grammar formalismshave thus become popular approaches where parsing can be based on an efficient context-free algorithm enhanced to produce linguistically rich representations. Whereas in some formalisms, such as the ANLT Grammar Formalism [2] [3], a context-free "backbone" is compiled from a pure unification grammar, in other formalisms [19] the grammar itself is written as a collection of context-free phrase structure rules augmented with unifi­ cation constraints that apply to feature structures that are associated with the grammar constituents.
    [Show full text]
  • Context-Aware Scanning and Determinism-Preserving Grammar Composition, in Theory and Practice
    Context-Aware Scanning and Determinism-Preserving Grammar Composition, in Theory and Practice A THESIS SUBMITTED TO THE FACULTY OF THE GRADUATE SCHOOL OF THE UNIVERSITY OF MINNESOTA BY August Schwerdfeger IN PARTIAL FULFILLMENT OF THE REQUIREMENTS FOR THE DEGREE OF DOCTOR OF PHILOSOPHY July, 2010 c August Schwerdfeger 2010 ALL RIGHTS RESERVED Acknowledgments I would like to thank all my colleagues in the MELT group for all their input and assis- tance through the course of the project, and especially for their help in providing ready- made tests and applications for my software. Thanks specifically to Derek Bodin and Ted Kaminski for their efforts in integrating the Copper parser generator into MELT’s attribute grammar tools; to Lijesh Krishnan for developing the ableJ system of Java ex- tensions and assisting me extensively with its further development; and to Yogesh Mali for implementing and testing the Promela grammar with Copper. I also thank my advisor, Eric Van Wyk, for his continuous guidance throughout my time as a student, and also for going well above and beyond the call of duty in helping me to edit and prepare this thesis for presentation. I thank the members of my thesis committee, Mats Heimdahl, Gopalan Nadathur, and Wayne Richter, for their time and efforts in serving and reviewing. I especially wish to thank Prof. Nadathur for his many detailed questions and helpful suggestions for improving this thesis. Work on this thesis has been partially funded by National Science Foundation Grants 0347860 and 0905581. Support has also been received from funds provided by the Institute of Technology (soon to be renamed the College of Science and Engi- neering) and the Department of Computer Science and Engineering at the University of Minnesota.
    [Show full text]
  • Elkhound: a Fast, Practical GLR Parser Generator
    Published in Proc. of Conference on Compiler Construction, 2004, pp. 73–88. Elkhound: A Fast, Practical GLR Parser Generator Scott McPeak and George C. Necula ? University of California, Berkeley {smcpeak,necula}@cs.berkeley.edu Abstract. The Generalized LR (GLR) parsing algorithm is attractive for use in parsing programming languages because it is asymptotically efficient for typical grammars, and can parse with any context-free gram- mar, including ambiguous grammars. However, adoption of GLR has been slowed by high constant-factor overheads and the lack of a general, user-defined action interface. In this paper we present algorithmic and implementation enhancements to GLR to solve these problems. First, we present a hybrid algorithm that chooses between GLR and ordinary LR on a token-by-token ba- sis, thus achieving competitive performance for determinstic input frag- ments. Second, we describe a design for an action interface and a new worklist algorithm that can guarantee bottom-up execution of actions for acyclic grammars. These ideas are implemented in the Elkhound GLR parser generator. To demonstrate the effectiveness of these techniques, we describe our ex- perience using Elkhound to write a parser for C++, a language notorious for being difficult to parse. Our C++ parser is small (3500 lines), efficient and maintainable, employing a range of disambiguation strategies. 1 Introduction The state of the practice in automated parsing has changed little since the intro- duction of YACC (Yet Another Compiler-Compiler), an LALR(1) parser genera- tor, in 1975 [1]. An LALR(1) parser is deterministic: at every point in the input, it must be able to decide which grammar rule to use, if any, utilizing only one token of lookahead [2].
    [Show full text]
  • A Simple, Possibly Correct LR Parser for C11
    14 A simple, possibly correct LR parser for C11 Jacques-Henri Jourdan, Inria Paris, MPI-SWS François Pottier, Inria Paris The syntax of the C programming language is described in the C11 standard by an ambiguous context-free grammar, accompanied with English prose that describes the concept of “scope” and indicates how certain ambiguous code fragments should be interpreted. Based on these elements, the problem of implementing a compliant C11 parser is not entirely trivial. We review the main sources of difficulty and describe a relatively simple solution to the problem. Our solution employs the well-known technique of combining an LALR(1) parser with a “lexical feedback” mechanism. It draws on folklore knowledge and adds several original as- pects, including: a twist on lexical feedback that allows a smooth interaction with lookahead; a simplified and powerful treatment of scopes; and a few amendments in the grammar. Although not formally verified, our parser avoids several pitfalls that other implementations have fallen prey to. We believe that its simplicity, its mostly-declarative nature, and its high similarity with the C11 grammar are strong informal arguments in favor of its correctness. Our parser is accompanied with a small suite of “tricky” C11 programs. We hope that it may serve as a reference or a starting point in the implementation of compilers and analysis tools. CCS Concepts: •Software and its engineering ! Parsers; Additional Key Words and Phrases: Compilation; parsing; ambiguity; lexical feedback; C89; C99; C11 ACM Reference Format: Jacques-Henri Jourdan and François Pottier. 2017. A simple, possibly correct LR parser for C11 ACM Trans.
    [Show full text]
  • A Tool for Generalised LR Parsing in Haskell
    A Tool for Generalised LR Parsing in Haskell Ben Medlock œ St. John‘s College Single Honours CS Project Report, April 2002 This report is submitted as part of the degree of Ben Medlock to the Board of Examiners in the Department of Computer Science, University of Durham. Word count: 17,857 Abstract Parsing is the process of deriving structure from sentences in a given language. This structure is derived from a specification of the language defined by a formal grammar. Many different types of grammar exist, but those most often used in the field of computer science are known as context-free (CF) grammars. The LR parsing technique can be used to efficiently parse a large class of unambiguous CF grammars. However, many languages can only be specified using ambiguous grammars. These include natural language (NL) grammars, as well as a host of simpler grammars. Tomita (85) proposed an extension to LR parsing known as generalised LR (GLR) parsing which allows languages derived from ambiguous CF grammars to be parsed efficiently. The project implements a version of Tomita’s algorithm in the functional programming language Haskell and integrates it with the Haskell-based LR parser-generator tool Happy. The amendments to Happy allow it to generate a GLR parser, based on Tomita’s algorithm, capable of parsing languages derived from ambiguous CF grammars. Our implementation of Tomita’s algorithm is analysed both theoretically (time and space orders) and through the use of Haskell profiling tools. Table of Contents Ch 1. Introduction ......................................................................1
    [Show full text]
  • Incremental Scannerless Generalized LR Parsing
    SPLASH: G: Incremental Scannerless Generalized LR Parsing Maarten P. Sijm Delft University of Technology Delft, The Netherlands [email protected] Abstract a separate lexing (or scanning) phase, supports modelling We present the Incremental Scannerless Generalized LR the entire language syntax in one single grammar, and al- (ISGLR) parsing algorithm, which combines the benefits of lows composition of grammars for different languages. One Incremental Generalized LR (IGLR) parsing and Scanner- notable disadvantage is that the SGLR parsing algorithm of less Generalized LR (SGLR) parsing. The ISGLR parser can Visser [9] is a batch algorithm, meaning that it must process reuse parse trees from unchanged regions in the input and each entire file in one pass. This becomes a problem for soft- thus only needs to parse changed regions. We also present ware projects that have large files, as every small change incremental techniques for imploding the parse tree to an requires the entire file to be parsed again. Abstract Syntax Tree (AST) and syntax highlighting. Scan- Incremental Generalized LR (IGLR) parsing is an improve- nerless parsing relies heavily on non-determinism during ment over batch Generalized LR (GLR) parsing. Amongst parsing, negatively impacting the incrementality of ISGLR others, Wagner [10] and TreeSitter [8] have created parsing parsing. We evaluated the ISGLR parsing algorithm using algorithms that allow rapid parsing of changes to large files. file histories from Git, achieving a speedup of up to 25 times However, these algorithms use a separate incremental lexical over non-incremental SGLR. analysis phase which complicates the implementation of in- cremental parsing [11] and does not directly allow language CCS Concepts • Software and its engineering → Incre- composition.
    [Show full text]
  • Faster Scannerless GLR Parsing
    Faster Scannerless GLR Parsing Giorgios Economopoulos, Paul Klint, Jurgen Vinju Centrum voor Wiskunde en Informatica (CWI), Kruislaan 413, 1098 SJ Amsterdam, The Netherlands Abstract. Analysis and renovation of large software portfolios requires syntax analysis of multiple, usually embedded, languages and this is be- yond the capabilities of many standard parsing techniques. The tradi- tional separation between lexer and parser falls short due to the limita- tions of tokenization based on regular expressions when handling multiple lexical grammars. In such cases scannerless parsing provides a viable so- lution. It uses the power of context-free grammars to be able to deal with a wide variety of issues in parsing lexical syntax. However, it comes at the price of less efficiency. The structure of tokens is obtained using a more powerful but more time and memory intensive parsing algorithm. Scan- nerless grammars are also more non-deterministic than their tokenized counterparts, increasing the burden on the parsing algorithm even fur- ther. In this paper we investigate the application of the Right-Nulled Gener- alized LR parsing algorithm (RNGLR) to scannerless parsing. We adapt the Scannerless Generalized LR parsing and filtering algorithm (SGLR) to implement the optimizations of RNGLR. We present an updated pars- ing and filtering algorithm, called SRNGLR, and analyze its performance in comparison to SGLR on ambiguous grammars for the programming languages C, Java, Python, SASL, and C++. Measurements show that SRNGLR is on average 33% faster than SGLR, but is 95% faster on the highly ambiguous SASL grammar. For the mainstream languages C, C++, Java and Python the average speedup is 16%.
    [Show full text]