views:

138

answers:

3

Is there a BNF or EBNF that describes the grammar for Java's annotations?

+1  A: 

`/* Annotation syntax follows. */

Annotation ::= NormalAnnotation | SingleMemberAnnotation | MarkerAnnotation NormalAnnotation ::= "@" Name "(" ( MemberValuePairs )? ")" MarkerAnnotation ::= "@" Name SingleMemberAnnotation ::= "@" Name "(" MemberValue ")" MemberValuePairs ::= MemberValuePair ( "," MemberValuePair )* MemberValuePair ::= "=" MemberValue MemberValue ::= Annotation | MemberValueArrayInitializer | ConditionalExpression MemberValueArrayInitializer ::= "{" ( MemberValue ( "," MemberValue )* ( "," )? )? "}"

/* Annotation Types. */

AnnotationTypeDeclaration ::= "@" "interface" AnnotationTypeBody AnnotationTypeBody ::= "{" ( AnnotationTypeMemberDeclaration )* "}" AnnotationTypeMemberDeclaration ::= Modifiers ( Type "(" ")" ( DefaultValue )? ";" | ClassOrInterfaceDeclaration | EnumDeclaration | AnnotationTypeDeclaration | FieldDeclaration ) | ( ";" ) DefaultValue ::= "default" MemberValue` from here. Also see his blog post.

ig0774
+2  A: 

The authoritative source for Java-related grammar, is, of course, the JLS.

JLS 18.1 The Grammar of the Java Programming Language

Annotations:
        Annotation [Annotations]

Annotation:
        @ TypeName [( [Identifier =] ElementValue)]

ElementValue:
        ConditionalExpression
        Annotation
        ElementValueArrayInitializer

... rest ommitted
polygenelubricants
Cool! This was what I was looking for.
Vivin Paliath
+1  A: 

Java language grammar

  1. Any Type may be prefixed by [Annotations]:

    Type: [Annotations] Identifier [TypeArguments] {. Identifier [TypeArguments]} {[]} [Annotations] BasicType

  2. To permit annotations on levels of an array (in declarations, not constructors), change “{[]}” to “{[Annotations] []}”. (This was abstracted out as “BracketsOpt” in the 2nd edition of the JLS [GJSB00].) For example:

Type: [Annotations] Identifier [TypeArguments]{ . Identifier [TypeArguments]} {[Annotations] []} [Annotations] BasicType

Also permit annotations on varargs (...): FormalParameterDeclsRest: VariableDeclaratorId [, FormalParameterDecls] [Annotations] ... VariableDeclaratorId

  1. Annotations may appear on the receiver type by changing uses of “FormalParameters” (in all 5 places it appears in the grammar) to “FormalParameters [Annotations]”. For example:

    VoidMethodDeclaratorRest: FormalParameters [Annotations] [throws QualifiedIdentifierList] ( MethodBody | ; )

Rachel