interp

package
v1.1.1-0...-c57de61 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2018 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package interp is the GoAWK interpreter (a simple tree-walker).

For basic usage, use the Exec function. For more complicated use cases and configuration options, first use the parser package to parse the AWK source, and then use ExecProgram to execute it with a specific configuration.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/ktye/awk/interp"
)

func main() {
	input := bytes.NewReader([]byte("foo bar\n\nbaz buz"))
	err := interp.Exec("$0 { print $1 }", " ", input, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

foo
baz
Example (Fieldsep)
package main

import (
	"bytes"
	"fmt"

	"github.com/ktye/awk/interp"
)

func main() {
	// Use ',' as the field separator
	input := bytes.NewReader([]byte("1,2\n3,4"))
	err := interp.Exec("{ print $1, $2 }", ",", input, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

1 2
3 4
Example (Funcs)
package main

import (
	"fmt"
	"strings"

	"github.com/ktye/awk/interp"
	"github.com/ktye/awk/parser"
)

func main() {
	src := `BEGIN { print sum(), sum(1), sum(2, 3, 4), repeat("xyz", 3) }`

	parserConfig := &parser.ParserConfig{
		Funcs: map[string]interface{}{
			"sum": func(args ...float64) float64 {
				sum := 0.0
				for _, a := range args {
					sum += a
				}
				return sum
			},
			"repeat": strings.Repeat,
		},
	}
	prog, err := parser.ParseProgram([]byte(src), parserConfig)
	if err != nil {
		fmt.Println(err)
		return
	}
	interpConfig := &interp.Config{
		Funcs: parserConfig.Funcs,
	}
	_, err = interp.ExecProgram(prog, interpConfig)
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

0 1 9 xyzxyzxyz
Example (Program)
package main

import (
	"bytes"
	"fmt"

	"github.com/ktye/awk/interp"
	"github.com/ktye/awk/parser"
)

func main() {
	src := "{ print NR, tolower($0) }"
	input := "A\naB\nAbC"

	prog, err := parser.ParseProgram([]byte(src), nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	config := &interp.Config{
		Stdin: bytes.NewReader([]byte(input)),
		Vars:  []string{"OFS", ":"},
	}
	_, err = interp.ExecProgram(prog, config)
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

1:a
2:ab
3:abc

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Exec

func Exec(source, fieldSep string, input io.Reader, output io.Writer) error

Exec provides a simple way to parse and execute an AWK program with the given field separator. Exec reads input from the given reader (nil means use os.Stdin) and writes output to stdout (nil means use a buffered version of os.Stdout).

func ExecProgram

func ExecProgram(program *Program, config *Config) (int, error)

ExecProgram executes the parsed program using the given interpreter config, returning the exit status code of the program. Error is nil on successful execution of the program, even if the program returns a non-zero status code.

Types

type Config

type Config struct {
	// Standard input reader (defaults to os.Stdin)
	Stdin io.Reader

	// Writer for normal output (defaults to a buffered version of
	// os.Stdout)
	Output io.Writer

	// Writer for non-fatal error messages (defaults to a buffered
	// version of os.Stderr)
	Error io.Writer

	// The name of the executable (accessible via ARGV[0])
	Argv0 string

	// Input arguments (usually filenames): empty slice means read
	// only from Stdin, and a filename of "-" means read from Stdin
	// instead of a real file.
	Args []string

	// List of name-value pairs for variables to set before executing
	// the program (useful for setting FS and other built-in
	// variables, for example []string{"FS", ",", "OFS", ","}).
	Vars []string

	// Map of named Go functions to allow calling from AWK. You need
	// to pass this same map to the parser.ParseProgram config.
	//
	// Functions can have any number of parameters, and variadic
	// functions are supported. Functions can have no return values,
	// one return value, or two return values (result, error). In the
	// two-value case, if the function returns a non-nil error,
	// program execution will stop and ExecProgram will return that
	// error.
	//
	// Apart from the error return value, the types supported are
	// bool, integer and floating point types (excluding complex),
	// and string types (string or []byte).
	//
	// It's not an error to call a Go function from AWK with fewer
	// arguments than it has parameters in Go. In this case, the zero
	// value will be used for any additional parameters. However, it
	// is a parse error to call a non-variadic function from AWK with
	// more arguments than it has parameters in Go.
	//
	// Functions defined with the "function" keyword in AWK code
	// take precedence over functions in Funcs.
	Funcs map[string]interface{}
}

Config defines the interpreter configuration for ExecProgram.

type Error

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

Error (actually *Error) is returned by Exec and Eval functions on interpreter error, for example a negative field index.

func (*Error) Error

func (e *Error) Error() string

Jump to

Keyboard shortcuts

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