1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
|
// nolint: govet
package main
import (
"encoding/json"
"fmt"
"math"
"os"
"strings"
"github.com/alecthomas/kong"
"github.com/alecthomas/participle/v2"
)
var cli struct {
AST bool `help:"Print AST for expression."`
Set map[string]float64 `short:"s" help:"Set variables."`
Expression []string `arg required help:"Expression to evaluate."`
}
type Operator int
const (
OpMul Operator = iota
OpDiv
OpAdd
OpSub
)
var operatorMap = map[string]Operator{"+": OpAdd, "-": OpSub, "*": OpMul, "/": OpDiv}
func (o *Operator) Capture(s []string) error {
*o = operatorMap[s[0]]
return nil
}
// E --> T {( "+" | "-" ) T}
// T --> F {( "*" | "/" ) F}
// F --> P ["^" F]
// P --> v | "(" E ")" | "-" T
type Value struct {
Number *float64 ` @(Float|Int)`
Variable *string `| @Ident`
Subexpression *Expression `| "(" @@ ")"`
}
type Factor struct {
Base *Value `@@`
Exponent *Value `( "^" @@ )?`
}
type OpFactor struct {
Operator Operator `@("*" | "/")`
Factor *Factor `@@`
}
type Term struct {
Left *Factor `@@`
Right []*OpFactor `@@*`
}
type OpTerm struct {
Operator Operator `@("+" | "-")`
Term *Term `@@`
}
type Expression struct {
Left *Term `@@`
Right []*OpTerm `@@*`
}
// Display
func (o Operator) String() string {
switch o {
case OpMul:
return "*"
case OpDiv:
return "/"
case OpSub:
return "-"
case OpAdd:
return "+"
}
panic("unsupported operator")
}
func (v *Value) String() string {
if v.Number != nil {
return fmt.Sprintf("%g", *v.Number)
}
if v.Variable != nil {
return *v.Variable
}
return "(" + v.Subexpression.String() + ")"
}
func (f *Factor) String() string {
out := f.Base.String()
if f.Exponent != nil {
out += " ^ " + f.Exponent.String()
}
return out
}
func (o *OpFactor) String() string {
return fmt.Sprintf("%s %s", o.Operator, o.Factor)
}
func (t *Term) String() string {
out := []string{t.Left.String()}
for _, r := range t.Right {
out = append(out, r.String())
}
return strings.Join(out, " ")
}
func (o *OpTerm) String() string {
return fmt.Sprintf("%s %s", o.Operator, o.Term)
}
func (e *Expression) String() string {
out := []string{e.Left.String()}
for _, r := range e.Right {
out = append(out, r.String())
}
return strings.Join(out, " ")
}
// Evaluation
func (o Operator) Eval(l, r float64) float64 {
switch o {
case OpMul:
return l * r
case OpDiv:
return l / r
case OpAdd:
return l + r
case OpSub:
return l - r
}
panic("unsupported operator")
}
func (v *Value) Eval(ctx Context) float64 {
switch {
case v.Number != nil:
return *v.Number
case v.Variable != nil:
value, ok := ctx[*v.Variable]
if !ok {
panic("no such variable " + *v.Variable)
}
return value
default:
return v.Subexpression.Eval(ctx)
}
}
func (f *Factor) Eval(ctx Context) float64 {
b := f.Base.Eval(ctx)
if f.Exponent != nil {
return math.Pow(b, f.Exponent.Eval(ctx))
}
return b
}
func (t *Term) Eval(ctx Context) float64 {
n := t.Left.Eval(ctx)
for _, r := range t.Right {
n = r.Operator.Eval(n, r.Factor.Eval(ctx))
}
return n
}
func (e *Expression) Eval(ctx Context) float64 {
l := e.Left.Eval(ctx)
for _, r := range e.Right {
l = r.Operator.Eval(l, r.Term.Eval(ctx))
}
return l
}
type Context map[string]float64
var parser = participle.MustBuild[Expression]()
func main() {
ctx := kong.Parse(&cli,
kong.Description("A basic expression parser and evaluator."),
kong.UsageOnError(),
)
expr, err := parser.ParseString("", strings.Join(cli.Expression, " "))
ctx.FatalIfErrorf(err)
if cli.AST {
json.NewEncoder(os.Stdout).Encode(expr)
} else {
fmt.Println(expr, "=", expr.Eval(cli.Set))
}
}
|