diff --git a/ast/parser_ext.go b/ast/parser_ext.go index bc14dfd4e8..0f3e09678d 100644 --- a/ast/parser_ext.go +++ b/ast/parser_ext.go @@ -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) { diff --git a/ast/parser_test.go b/ast/parser_test.go index c2189f786a..57c051109f 100644 --- a/ast/parser_test.go +++ b/ast/parser_test.go @@ -3061,7 +3061,7 @@ 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", @@ -3069,7 +3069,15 @@ p := 7`, # 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", @@ -3077,7 +3085,7 @@ import data.foo.bar`, # 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",