项目作者: svstanev

项目描述 :
Recursive descent expression parser in Go
高级语言: Go
项目地址: git://github.com/svstanev/goexp.git
创建时间: 2019-02-14T14:00:24Z
项目社区:https://github.com/svstanev/goexp

开源协议:MIT License

下载


goexp

Recursive descent expression parser in Go

Installation

  1. go get -u github.com/svstanev/goexp

Usage

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "github.com/svstanev/goexp"
  6. "github.com/svstanev/goexp/types"
  7. )
  8. func main() {
  9. context := goexp.NewEvalContext(nil)
  10. context.AddName("x", types.Integer(1))
  11. context.AddName("y", types.Integer(3))
  12. context.AddName("z", types.Integer(5))
  13. context.AddMethod("max", func(args ...types.Integer) (interface{}, error) {
  14. var res int64 = math.MinInt64
  15. for _, value := range args {
  16. n := int64(value)
  17. if n > res {
  18. res = n
  19. }
  20. }
  21. return types.Integer(res), nil
  22. })
  23. res, err := goexp.EvalString("max(x, y, z)", context)
  24. if err != nil {
  25. panic(err)
  26. }
  27. fmt.Println(res)
  28. }

Expression language

Syntax Grammar

  1. expression -> logical_or
  2. logical_or -> logical_and (("||") logical_and)*;
  3. logical_and -> logical_not (("&&") logical_not)*;
  4. logical_not -> "!"? equality;
  5. equality -> comparison (("==" | "!=") comparison)*;
  6. comparison -> addition (("<" | "<=" | ">" | ">=") addition)*;
  7. addition -> multiplication (("+" | "-") multiplication)*;
  8. multiplication -> negate (("*" | "/" | "%") negate)*;
  9. power -> negate ("**" negate)*;
  10. negate -> "-"? call;
  11. call -> primary (("(" arguments? ")") | ("." IDENTIFIER))*;
  12. primary -> "false" | "true" | "nil" | IDENTIFIER | NUMBER | STRING | "(" expression ")";
  13. arguments -> expression ("," expression)*;

Lexical Grammar

  1. IDENTIFIER -> ALPHA (ALPHA | DIGIT)*;
  2. NUMBER -> DIGIT* ("." DIGIT*)?;
  3. STRING -> "'" <any char except "'">* "'"
  4. | '"' <any char except '"'>* '"';
  5. DIGIT -> '0'...'9'
  6. ALPHA -> 'a'...'z'|'A'...'Z'|'_'