Skip to content

Commit

Permalink
ast: Improve error reporting for attachment error
Browse files Browse the repository at this point in the history
Previously the parser would panic if the annotation was unattached
because no scope can be unattached currently.

Signed-off-by: Torin Sandall <[email protected]>
  • Loading branch information
tsandall committed Apr 27, 2021
1 parent 6d56317 commit 6f502bf
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
12 changes: 8 additions & 4 deletions ast/parser_ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -691,19 +691,23 @@ func validateAnnotationScopeAttachment(a *Annotations) *Error {
if _, ok := a.node.(*Rule); ok {
return nil
}
return newScopeAttachmentErr(a)
return newScopeAttachmentErr(a, "rule")
case annotationScopePackage, annotationScopeSubpackages:
if _, ok := a.node.(*Package); ok {
return nil
}
return newScopeAttachmentErr(a)
return newScopeAttachmentErr(a, "package")
}

return NewError(ParseErr, a.Loc(), "invalid annotation scope '%v'", a.Scope)
}

func newScopeAttachmentErr(a *Annotations) *Error {
return NewError(ParseErr, a.Loc(), "annotation scope '%v' cannot be applied to %v statement", a.Scope, TypeName(a.node))
func newScopeAttachmentErr(a *Annotations, want string) *Error {
var have string
if a.node != nil {
have = fmt.Sprintf(" (have %v)", TypeName(a.node))
}
return NewError(ParseErr, a.Loc(), "annotation scope '%v' must be applied to %v%v", a.Scope, want, have)
}

func setRuleModule(rule *Rule, module *Module) {
Expand Down
14 changes: 11 additions & 3 deletions ast/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3061,23 +3061,31 @@ package test
p := 7`,
expNumComments: 2,
expError: "annotation scope 'rule' cannot be applied to package statement",
expError: "test.rego:2: rego_parse_error: annotation scope 'rule' must be applied to rule (have package)",
},
{
note: "Scope attachment error: document on import",
module: `package test
# METADATA
# scope: document
import data.foo.bar`,
expError: "test.rego:2: rego_parse_error: annotation scope 'document' cannot be applied to import statement",
expError: "test.rego:2: rego_parse_error: annotation scope 'document' must be applied to rule (have import)",
},
{
note: "Scope attachment error: unattached",
module: `package test
# METADATA
# scope: package`,
expError: "test.rego:3: rego_parse_error: annotation scope 'package' must be applied to package",
},
{
note: "Scope attachment error: package on non-package",
module: `package test
# METADATA
# scope: package
import data.foo`,
expError: "test.rego:2: rego_parse_error: annotation scope 'package' cannot be applied to import statement",
expError: "test.rego:2: rego_parse_error: annotation scope 'package' must be applied to package (have import)",
},
{
note: "Inline schema definition",
Expand Down

0 comments on commit 6f502bf

Please sign in to comment.