earley

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2021 License: BSD-3-Clause Imports: 10 Imported by: 1

README

Earley-Parsing

A great introduction to Earley-parsing may be found at Loup Vaillant's Blog. Here is what he has to say:

The biggest advantage of Earley Parsing is its accessibility. Most other tools such as parser generators, parsing expression grammars, or combinator libraries feature restrictions that often make them hard to use. Use the wrong kind of grammar, and your PEG will enter an infinite loop. Use another wrong kind of grammar, and most parser generators will fail. To a beginner, these restrictions feel most arbitrary: it looks like it should work, but it doesn't. There are workarounds of course, but they make these tools more complex.

Earley parsing Just Works™.

On the flip side, to get this generality we must sacrifice some speed. Earley parsing cannot compete with speed demons such as Flex/Bison in terms of raw speed.

If speed (or the lack thereof) is critical to your project, you should probably grab ANTLR or Bison. I used both a lot in my programming life. However, there are many scenarios where I wished I had a more lightweight alternative at hand. Oftentimes I found myself writing recursive-descent parsers for small ad-hoc languages by hand, sometimes mixing them with the lexer-part of one of the big players.

Documentation

Overview

Package earley provides an Earley-Parser.

Earleys algorithm for parsing ambiguous grammars has been known since 1968. Despite its benefits, until recently it has lead a reclusive life outside the mainstream discussion about parsers. Many textbooks on parsing do not even discuss it (the "Dragon book" only mentions it in the appendix).

A very accessible and practical discussion has been done by Loup Vaillant in a superb blog series (http://loup-vaillant.fr/tutorials/earley-parsing/), and it even boasts an implementation in Lua/OcaML. (A port of Loup's ideas in Go is available at https://github.com/jakub-m/gearley.)

I can do no better than Loup to explain the advantages of Earley-parsing:

----------------------------------------------------------------------

The biggest advantage of Earley Parsing is its accessibility. Most other tools such as parser generators, parsing expression grammars, or combinator libraries feature restrictions that often make them hard to use. Use the wrong kind of grammar, and your PEG will enter an infinite loop. Use another wrong kind of grammar, and most parser generators will fail. To a beginner, these restrictions feel most arbitrary: it looks like it should work, but it doesn't. There are workarounds of course, but they make these tools more complex.

Earley parsing Just Works™.

On the flip side, to get this generality we must sacrifice some speed. Earley parsing cannot compete with speed demons such as Flex/Bison in terms of raw speed.

----------------------------------------------------------------------

If speed (or the lack thereof) is critical to your project, you should probably grab ANTLR or Bison. I used both a lot in my programming life. However, there are many scenarios where I wished I had a more lightweight alternative at hand. Oftentimes I found myself writing recursive-descent parsers for small ad-hoc languages by hand, sometimes mixing them with the lexer-part of one of the big players. My hope is that an Earley parser will prove to be handy in these kinds of situations.

A thorough introduction to Earley-parsing may be found in "Parsing Techniques" by Dick Grune and Ceriel J.H. Jacobs (https://dickgrune.com/Books/PTAPG_2nd_Edition/), section 7.2. A recent evaluation has been done by Mark Fulbright in "An Evaluation of Two Approaches to Parsing" (https://apps.cs.utexas.edu/tech_reports/reports/tr/TR-2199.pdf). It references an interesting approach to view parsing as path-finding in graphs, by Keshav Pingali and Gianfranco Bilardi (https://apps.cs.utexas.edu/tech_reports/reports/tr/TR-2102.pdf).

BSD License

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of this software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func T

func T() tracing.Trace

T traces to the global syntax tracer.

Types

type Listener

type Listener interface {
	Reduce(sym *lr.Symbol, rule int, rhs []*RuleNode, span lr.Span, level int) interface{}
	Terminal(tokenValue int, token interface{}, span lr.Span, level int) interface{}
}

Listener is a type for walking a parse tree/forest.

type Option

type Option func(p *Parser)

Option configures a parser.

func GenerateTree

func GenerateTree(b bool) Option

GenerateTree configures the parser to create a parse tree/forest for a successful parse. Defaults to false.

func StoreTokens

func StoreTokens(b bool) Option

StoreTokens configures the parser to remember all input tokens. This is necessary for listeners during tree walks to have access to the values/tokens of non-terminals. Defaults to true.

type Parser

type Parser struct {
	Error func(p *Parser, msg string) // Error is called for each error encountered
	// contains filtered or unexported fields
}

Parser is an Earley-parser type. Create and initialize one with earley.NewParser(...)

func NewParser

func NewParser(ga *lr.LRAnalysis, opts ...Option) *Parser

NewParser creates and initializes an Earley parser.

func (*Parser) Parse

func (p *Parser) Parse(scan scanner.Tokenizer, listener Listener) (accept bool, err error)

Parse starts a new parse, given a scanner tokenizing the input. The parser must have been initialized with an analyzed grammar. It returns true if the input string has been accepted.

Clients may provide a Listener to perform semantic actions.

func (*Parser) ParseForest

func (p *Parser) ParseForest() *sppf.Forest

ParseForest returns the parse forest for the last Parse-run, if any. Parser option GenerateTree must have been set to true at parser-creation time. In case of serious parsing errors, generation of a forest may have been abandoned by the parser.

func (*Parser) TokenAt

func (p *Parser) TokenAt(pos uint64) interface{}

TokenAt returns the input token at position pos.

func (*Parser) WalkDerivation

func (p *Parser) WalkDerivation(listener Listener) *RuleNode

WalkDerivation walks the grammar items which occured during the parse. It uses a listener, which gets called for every terminal and for every non-terminal reduction.

type RuleNode

type RuleNode struct {
	Extent lr.Span     // span of intput symbols this rule reduced
	Value  interface{} // user defined value
	// contains filtered or unexported fields
}

RuleNode represents a node occuring during a parse tree/forest walk.

func (*RuleNode) Symbol

func (rnode *RuleNode) Symbol() *lr.Symbol

Symbol returns the grammar symbol a RuleNode refers to. It is either a terminal or the LHS of a reduced rule.

type TreeBuilder

type TreeBuilder struct {
	// contains filtered or unexported fields
}

TreeBuilder is a DerivationListener which is able to create a parse tree/forest from the Earley-states. Users may create one and call it themselves, but the more common usage pattern is by setting the option 'GenerateTree' for a parser and retrieving the parse-tree/forest with `parser.Forest()`.

func NewTreeBuilder

func NewTreeBuilder(g *lr.Grammar) *TreeBuilder

NewTreeBuilder creates a TreeBuilder given an input grammar. This should obviously be the same grammar as the one used for parsing, but this is not enforced.

The TreeBuilder uses the grammar for access to rules and their symbols, which are a pre-requisite for generating the derivation path(s).

func (*TreeBuilder) Forest

func (tb *TreeBuilder) Forest() *sppf.Forest

Forest returns the parse forest after walking the derivation tree.

func (*TreeBuilder) Reduce

func (tb *TreeBuilder) Reduce(sym *lr.Symbol, rule int, rhs []*RuleNode, span lr.Span, level int) interface{}

Reduce is a listener method, called for Earley-completions.

func (*TreeBuilder) Terminal

func (tb *TreeBuilder) Terminal(tokval int, token interface{}, span lr.Span, level int) interface{}

Terminal is a listener method, called when matching input tokens.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL