Beispiel #1
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [expressions...]\n", os.Args[0])
		flag.PrintDefaults()
		fmt.Fprint(os.Stderr, "\nEvaluates and prints the result of each expression.\n")
	}
	flag.Parse()

	for _, arg := range flag.Args() {
		expr, err := exprel.Parse(arg)
		if err != nil {
			fmt.Printf("error: %s\n", err)
			continue
		}
		result, err := expr.Evaluate(exprel.Base)
		if err != nil {
			fmt.Printf("error: %s\n", err)
		}
		switch result.(type) {
		case string:
			fmt.Printf("string: %v\n", result)
		case bool:
			fmt.Printf("bool: %v\n", result)
		case float64:
			fmt.Printf("number: %v\n", result)
		}
	}
}
Beispiel #2
0
func testBool(t *testing.T, expr string, expected bool, source exprel.Source) {
	e, err := exprel.Parse(expr)
	if err != nil {
		t.Fatalf("could not parse expression: %s\n", err)
	}
	val, err := exprel.Boolean(e.Evaluate(source))
	if err != nil {
		t.Fatalf("could not evaluate expression: %s\n", err)
	}
	if val != expected {
		t.Fatalf("incorrect value (expecting %v, got %v)\n", expected, val)
	}

	raw, err := e.MarshalText()
	if err != nil {
		t.Fatalf("MarshalText error: %s\n", err)
	}
	var e2 exprel.Expression
	if err := e2.UnmarshalText(raw); err != nil {
		t.Fatalf("UnmarshalText error: %s\n", err)
	}
	val2, err := exprel.Boolean(e2.Evaluate(source))
	if err != nil {
		t.Fatalf("could not evaluate unmarshaled expression: %s\n", err)
	}
	if val2 != expected {
		t.Fatalf("incorrect unmarshaled value (expecting %v, got %v)\n", expected, val)
	}
}
Beispiel #3
0
func testSyntaxError(t *testing.T, expr, messageRegex string, source exprel.Source) {
	_, err := exprel.Parse(expr)
	if err == nil {
		t.Fatalf("expecting parsing error\n")
	}
	syntaxErr, ok := err.(*exprel.SyntaxError)
	if !ok {
		t.Fatalf("expecting syntax error\n")
	}
	matched, err := regexp.MatchString(messageRegex, syntaxErr.Message)
	if err != nil {
		panic(err)
	}
	if !matched {
		t.Fatalf("error message does not match (regex `%s`, got `%s`)", messageRegex, syntaxErr.Message)
	}
}
Beispiel #4
0
func testRuntimeError(t *testing.T, expr, messageRegex string, source exprel.Source) {
	e, err := exprel.Parse(expr)
	if err != nil {
		t.Fatalf("could not parse expression: %s\n", err)
	}
	_, err = e.Evaluate(source)
	if err == nil {
		t.Fatalf("expecting runtime error\n")
	}
	runtimeErr, ok := err.(*exprel.RuntimeError)
	if !ok {
		t.Fatalf("expecting runtime error\n")
	}
	matched, err := regexp.MatchString(messageRegex, runtimeErr.Message)
	if err != nil {
		panic(err)
	}
	if !matched {
		t.Fatalf("error message does not match (regex `%s`, got `%s`)", messageRegex, runtimeErr.Message)
	}
}