Skip to main content

java_lang/ast/
attribute.rs

1//! Annotation types.
2
3use crate::span::Span;
4
5use super::expr::Expr;
6use super::path::Path;
7
8/// A Java annotation (e.g., `@Override`, `@SuppressWarnings("unchecked")`).
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
10pub enum Annotation {
11    /// `@TypeName`
12    Marker { at_token: Span, name: Path },
13    /// `@TypeName(value)`
14    SingleElement {
15        at_token: Span,
16        name: Path,
17        eq_token: Span,
18        value: Box<ElementValue>,
19    },
20    /// `@TypeName(key1 = val1, key2 = val2)`
21    Normal {
22        at_token: Span,
23        name: Path,
24        paren_span: (Span, Span), // (open, close)
25        pairs: Vec<ElementValuePair>,
26    },
27}
28
29impl Annotation {
30    pub fn span(&self) -> Span {
31        match self {
32            Self::Marker { at_token, name } => at_token.join(name.span),
33            Self::SingleElement {
34                at_token, value, ..
35            } => at_token.join(value.span()),
36            Self::Normal {
37                at_token,
38                paren_span,
39                ..
40            } => at_token.join(paren_span.1),
41        }
42    }
43
44    pub fn path(&self) -> &Path {
45        match self {
46            Self::Marker { name, .. } => name,
47            Self::SingleElement { name, .. } => name,
48            Self::Normal { name, .. } => name,
49        }
50    }
51}
52
53/// A key-value pair in a normal annotation.
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub struct ElementValuePair {
56    pub key: crate::ident::Ident,
57    pub eq_span: Span,
58    pub value: ElementValue,
59}
60
61/// An element value in an annotation.
62#[derive(Debug, Clone, PartialEq, Eq, Hash)]
63pub enum ElementValue {
64    /// An expression (constant).
65    Expr(Expr),
66    /// An array initializer.
67    Array {
68        brace_span: (Span, Span),
69        values: Vec<ElementValue>,
70        trailing_comma: bool,
71    },
72    /// A nested annotation.
73    Annotation(Annotation),
74}
75
76impl ElementValue {
77    pub fn span(&self) -> Span {
78        match self {
79            Self::Expr(e) => e.span(),
80            Self::Array { brace_span, .. } => brace_span.0.join(brace_span.1),
81            Self::Annotation(a) => a.span(),
82        }
83    }
84}