earley

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2022 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package earley contains an implementation of glean.Grammar using a simple Earley-style parser.

Example

Example uses a parser to add two integers

package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"

	"github.com/pat42smith/glean/earley"
)

// Example uses a parser to add two integers
func main() {
	gocmd := runtime.GOROOT() + "/bin/go"
	if runtime.GOOS == "windows" {
		gocmd += ".exe"
	}

	tmp, e := os.MkdirTemp("", "")
	if e != nil {
		panic(e)
	}
	defer func() { os.Remove(tmp) }()

	mainGo := filepath.Join(tmp, "main.go")
	e = os.WriteFile(mainGo, []byte(mainText), 0444)
	if e != nil {
		panic(e)
	}
	defer func() { os.Remove(mainGo) }()

	var g earley.Grammar
	e = g.AddRule("RuleAdd", "Sum", []string{"int", "int"})
	if e != nil {
		panic(e)
	}
	parserText, e := g.WriteParser("Sum", "main", "_")
	if e != nil {
		panic(e)
	}

	parserGo := filepath.Join(tmp, "parser.go")
	e = os.WriteFile(parserGo, []byte(parserText), 0444)
	if e != nil {
		panic(e)
	}
	defer func() { os.Remove(parserGo) }()

	out, _ := exec.Command(gocmd, "run", mainGo, parserGo).CombinedOutput()
	fmt.Printf("%s", out)
}

var mainText = `
package main

import "fmt"

type Sum int

func RuleAdd(i, j int) Sum {
	return Sum(i + j)
}

func main() {
	sum, e := _Parse([]interface{}{ 2, 5 })
	if e != nil {
		panic(e)
	}
	fmt.Println(sum)
}
`
Output:

7

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Grammar

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

*Grammar is an Earley implentation of glean.Grammar.

func (*Grammar) AddRule

func (g *Grammar) AddRule(name, target string, items []string) error

Implements glean.RuleAdder.AddRule.

func (*Grammar) WriteParser

func (g *Grammar) WriteParser(goal, packname, prepend string) (string, error)

Implements glean.ParserWriter.WriteParser.

Jump to

Keyboard shortcuts

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