Skip to content

Commit

Permalink
ast: Fix panic in module parsing
Browse files Browse the repository at this point in the history
If the module contained a some statement the parser would panic. This
change fixes the parser to just return an error indicating the some
statement cannot be interpreted as a rule.

Signed-off-by: Torin Sandall <[email protected]>
  • Loading branch information
tsandall committed Jan 24, 2020
1 parent 890083b commit 4ffd5ff
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
10 changes: 10 additions & 0 deletions ast/parser_ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error) {
return nil, fmt.Errorf("negated expressions cannot be used for rule head")
}

if _, ok := expr.Terms.(*SomeDecl); ok {
return nil, errors.New("some declarations cannot be used for rule head")
}

if term, ok := expr.Terms.(*Term); ok {
switch v := term.Value.(type) {
case Ref:
Expand All @@ -151,6 +155,12 @@ func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error) {
}
}

if _, ok := expr.Terms.([]*Term); !ok {
// This is a defensive check in case other kinds of expression terms are
// introduced in the future.
return nil, errors.New("expression cannot be used for rule head")
}

if expr.IsAssignment() {

lhs, rhs := expr.Operand(0), expr.Operand(1)
Expand Down
12 changes: 12 additions & 0 deletions ast/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1427,6 +1427,11 @@ data = {"bar": 2} { true }`
"foo" := 1`

someDecl := `
package a
some x`

assertParseModuleError(t, "multiple expressions", multipleExprs)
assertParseModuleError(t, "non-equality", nonEquality)
assertParseModuleError(t, "non-var name", nonVarName)
Expand All @@ -1437,6 +1442,13 @@ data = {"bar": 2} { true }`
assertParseModuleError(t, "non ref term", nonRefTerm)
assertParseModuleError(t, "zero args", zeroArgs)
assertParseModuleError(t, "assign to term", assignToTerm)
assertParseModuleError(t, "some decl", someDecl)

if _, err := ParseRuleFromExpr(&Module{}, &Expr{
Terms: struct{}{},
}); err == nil {
t.Fatal("expected error for unknown expression term type")
}
}

func TestWildcards(t *testing.T) {
Expand Down

0 comments on commit 4ffd5ff

Please sign in to comment.