Skip to main content

ferro_jtype/types/
generic.rs

1use super::{ClassName, PrimitiveType};
2
3/// A generic JVM signature preserved from a `Signature` attribute.
4///
5/// Generic signatures complement erased descriptors. They are metadata rather
6/// than verifier input, so inference remains valid when they are absent or
7/// malformed. The value uses JVM generic-signature syntax verbatim.
8#[derive(Debug, Clone, PartialEq, Eq, Hash)]
9pub struct GenericSignature(String);
10
11impl GenericSignature {
12    /// Creates a generic signature from JVM signature text.
13    #[must_use]
14    pub fn parse(value: impl Into<String>) -> Self {
15        Self(value.into())
16    }
17
18    pub(crate) fn new(value: String) -> Self {
19        Self(value)
20    }
21
22    /// Returns the generic signature in JVM signature syntax.
23    #[must_use]
24    pub fn as_str(&self) -> &str {
25        &self.0
26    }
27
28    /// Consumes the signature and returns its JVM signature text.
29    #[must_use]
30    pub fn into_string(self) -> String {
31        self.0
32    }
33
34    /// Parses a field type signature into a typed generic representation.
35    ///
36    /// Returns `None` for malformed signatures or signatures that contain a
37    /// method/class declaration rather than one field type.
38    #[must_use]
39    pub fn parse_field_type(&self) -> Option<GenericType> {
40        let mut parser = Parser {
41            input: self.0.as_bytes(),
42            cursor: 0,
43        };
44        let ty = parser.parse_type()?;
45        (parser.cursor == parser.input.len()).then_some(ty)
46    }
47
48    /// Parses a class generic signature.
49    #[must_use]
50    pub fn parse_class(&self) -> Option<GenericClassSignature> {
51        let mut parser = Parser {
52            input: self.0.as_bytes(),
53            cursor: 0,
54        };
55        let parameters = parser.formals()?;
56        let superclass = parser.class_type()?;
57        let mut interfaces = Vec::new();
58        while parser.peek().is_some() {
59            interfaces.push(parser.class_type()?);
60        }
61        Some(GenericClassSignature {
62            parameters,
63            superclass,
64            interfaces,
65        })
66    }
67
68    /// Parses a method generic signature.
69    #[must_use]
70    pub fn parse_method(&self) -> Option<GenericMethodSignature> {
71        let mut parser = Parser {
72            input: self.0.as_bytes(),
73            cursor: 0,
74        };
75        let parameters = parser.formals()?;
76        parser.consume(b'(').then_some(())?;
77        let mut arguments = Vec::new();
78        while !parser.consume(b')') {
79            arguments.push(parser.parse_type()?);
80        }
81        let returns = if parser.consume(b'V') {
82            None
83        } else {
84            Some(parser.parse_type()?)
85        };
86        let mut throws = Vec::new();
87        while parser.consume(b'^') {
88            throws.push(parser.parse_type()?);
89        }
90        (parser.cursor == parser.input.len()).then_some(GenericMethodSignature {
91            parameters,
92            arguments,
93            returns,
94            throws,
95        })
96    }
97}
98
99/// Formal parameters and bounds from a class or method signature.
100#[derive(Debug, Clone, PartialEq, Eq, Hash)]
101pub struct GenericParameter {
102    /// Type-variable identifier.
103    pub name: String,
104    /// Explicit upper bounds.
105    pub bounds: Vec<GenericType>,
106}
107
108/// Parsed class generic signature.
109#[derive(Debug, Clone, PartialEq, Eq, Hash)]
110pub struct GenericClassSignature {
111    /// Formal type parameters.
112    pub parameters: Vec<GenericParameter>,
113    /// Generic superclass.
114    pub superclass: GenericClassType,
115    /// Generic superinterfaces.
116    pub interfaces: Vec<GenericClassType>,
117}
118
119/// Parsed method generic signature.
120#[derive(Debug, Clone, PartialEq, Eq, Hash)]
121pub struct GenericMethodSignature {
122    /// Formal type parameters.
123    pub parameters: Vec<GenericParameter>,
124    /// Generic argument types.
125    pub arguments: Vec<GenericType>,
126    /// Generic result type, or `None` for void.
127    pub returns: Option<GenericType>,
128    /// Declared thrown types.
129    pub throws: Vec<GenericType>,
130}
131
132/// A parsed JVM field type that preserves generic arguments.
133#[derive(Debug, Clone, PartialEq, Eq, Hash)]
134pub enum GenericType {
135    /// A primitive JVM type.
136    Primitive(PrimitiveType),
137    /// A parameterized or ordinary class type.
138    Class(GenericClassType),
139    /// An array type.
140    Array(Box<GenericType>),
141    /// A type-variable reference such as `TE;`.
142    Variable(String),
143}
144
145/// A parsed generic class type.
146#[derive(Debug, Clone, PartialEq, Eq, Hash)]
147pub struct GenericClassType {
148    /// JVM internal class name of the first class segment.
149    pub name: ClassName,
150    /// Type arguments on the first class segment.
151    pub arguments: Vec<GenericArgument>,
152    /// Nested class segments following the first segment.
153    pub nested: Vec<GenericClassSegment>,
154}
155
156/// A nested class segment in a generic class type.
157#[derive(Debug, Clone, PartialEq, Eq, Hash)]
158pub struct GenericClassSegment {
159    /// Source-level nested class name.
160    pub name: String,
161    /// Type arguments on this nested segment.
162    pub arguments: Vec<GenericArgument>,
163}
164
165/// An argument in a generic type argument list.
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167pub enum GenericArgument {
168    /// A concrete generic type argument.
169    Type(GenericType),
170    /// An unbounded, extends-bounded, or super-bounded wildcard.
171    Wildcard(GenericWildcard),
172}
173
174/// A Java wildcard bound.
175#[derive(Debug, Clone, PartialEq, Eq, Hash)]
176pub enum GenericWildcard {
177    /// An unbounded wildcard (`?`).
178    Unbounded,
179    /// An extends wildcard (`? extends T`).
180    Extends(GenericType),
181    /// A super wildcard (`? super T`).
182    Super(GenericType),
183}
184
185struct Parser<'a> {
186    input: &'a [u8],
187    cursor: usize,
188}
189
190impl Parser<'_> {
191    fn peek(&self) -> Option<u8> {
192        self.input.get(self.cursor).copied()
193    }
194
195    fn class_type(&mut self) -> Option<GenericClassType> {
196        if !self.consume(b'L') {
197            return None;
198        }
199        self.parse_class()
200    }
201
202    fn formals(&mut self) -> Option<Vec<GenericParameter>> {
203        let mut parameters = Vec::new();
204        if !self.consume(b'<') {
205            return Some(parameters);
206        }
207        while !self.consume(b'>') {
208            let name = self.until(b':')?;
209            let mut bounds = Vec::new();
210            if self.peek() != Some(b':') {
211                bounds.push(self.parse_type()?);
212            }
213            while self.consume(b':') {
214                bounds.push(self.parse_type()?);
215            }
216            parameters.push(GenericParameter { name, bounds });
217        }
218        Some(parameters)
219    }
220
221    fn parse_type(&mut self) -> Option<GenericType> {
222        let tag = self.next()?;
223        Some(match tag {
224            b'Z' => GenericType::Primitive(PrimitiveType::Boolean),
225            b'B' => GenericType::Primitive(PrimitiveType::Byte),
226            b'C' => GenericType::Primitive(PrimitiveType::Char),
227            b'S' => GenericType::Primitive(PrimitiveType::Short),
228            b'I' => GenericType::Primitive(PrimitiveType::Int),
229            b'F' => GenericType::Primitive(PrimitiveType::Float),
230            b'J' => GenericType::Primitive(PrimitiveType::Long),
231            b'D' => GenericType::Primitive(PrimitiveType::Double),
232            b'T' => {
233                let name = self.until(b';')?;
234                self.consume(b';').then_some(GenericType::Variable(name))?
235            }
236            b'[' => GenericType::Array(Box::new(self.parse_type()?)),
237            b'L' => GenericType::Class(self.parse_class()?),
238            _ => return None,
239        })
240    }
241
242    fn parse_class(&mut self) -> Option<GenericClassType> {
243        let name = self.until_any(&[b'<', b'.', b';'])?;
244        let name = ClassName::parse(name).ok()?;
245        let arguments = self.parse_arguments()?;
246        let mut nested = Vec::new();
247        while self.consume(b'.') {
248            let name = self.until_any(&[b'<', b'.', b';'])?;
249            let arguments = self.parse_arguments()?;
250            nested.push(GenericClassSegment { name, arguments });
251        }
252        self.consume(b';').then_some(GenericClassType {
253            name,
254            arguments,
255            nested,
256        })
257    }
258
259    fn parse_arguments(&mut self) -> Option<Vec<GenericArgument>> {
260        if !self.consume(b'<') {
261            return Some(Vec::new());
262        }
263        let mut arguments = Vec::new();
264        while !self.consume(b'>') {
265            let argument = match self.next()? {
266                b'*' => GenericArgument::Wildcard(GenericWildcard::Unbounded),
267                b'+' => GenericArgument::Wildcard(GenericWildcard::Extends(self.parse_type()?)),
268                b'-' => GenericArgument::Wildcard(GenericWildcard::Super(self.parse_type()?)),
269                _ => {
270                    self.cursor -= 1;
271                    GenericArgument::Type(self.parse_type()?)
272                }
273            };
274            arguments.push(argument);
275        }
276        Some(arguments)
277    }
278
279    fn until(&mut self, terminator: u8) -> Option<String> {
280        self.until_any(&[terminator])
281    }
282
283    fn until_any(&mut self, terminators: &[u8]) -> Option<String> {
284        let start = self.cursor;
285        while let Some(byte) = self.input.get(self.cursor) {
286            if terminators.contains(byte) {
287                break;
288            }
289            self.cursor += 1;
290        }
291        (start != self.cursor)
292            .then(|| String::from_utf8(self.input[start..self.cursor].to_vec()).ok())?
293    }
294
295    fn consume(&mut self, expected: u8) -> bool {
296        if self.input.get(self.cursor) == Some(&expected) {
297            self.cursor += 1;
298            true
299        } else {
300            false
301        }
302    }
303
304    fn next(&mut self) -> Option<u8> {
305        let byte = *self.input.get(self.cursor)?;
306        self.cursor += 1;
307        Some(byte)
308    }
309}