Skip to main content

ferro_jtype/types/
descriptor.rs

1use crate::{ClassName, DescriptorError};
2
3/// A JVM primitive type from a field or method descriptor.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5pub enum PrimitiveType {
6    /// The `Z` descriptor type.
7    Boolean,
8    /// The `B` descriptor type.
9    Byte,
10    /// The `C` descriptor type.
11    Char,
12    /// The `S` descriptor type.
13    Short,
14    /// The `I` descriptor type.
15    Int,
16    /// The `F` descriptor type.
17    Float,
18    /// The `J` descriptor type.
19    Long,
20    /// The `D` descriptor type.
21    Double,
22}
23
24impl PrimitiveType {
25    /// Returns the number of JVM local-variable or operand-stack slots used.
26    ///
27    /// `long` and `double` use two slots; every other primitive uses one.
28    #[must_use]
29    pub const fn slot_width(self) -> u8 {
30        match self {
31            Self::Long | Self::Double => 2,
32            Self::Boolean | Self::Byte | Self::Char | Self::Short | Self::Int | Self::Float => 1,
33        }
34    }
35}
36
37/// A non-void JVM field type descriptor.
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub enum TypeDescriptor {
40    /// A primitive descriptor type.
41    Primitive(PrimitiveType),
42    /// A reference to a class identified by its JVM internal name.
43    Reference(ClassName),
44    /// An array descriptor with its dimension count and element descriptor.
45    Array {
46        /// Number of leading `[` characters in the descriptor.
47        dimensions: u8,
48        /// Type stored at the array's innermost dimension.
49        element: Box<TypeDescriptor>,
50    },
51}
52
53impl TypeDescriptor {
54    /// Parses one complete non-void JVM field descriptor.
55    ///
56    /// For example, `I` describes an integer and `[Ljava/lang/String;`
57    /// describes an array of strings.
58    pub fn parse(input: &str) -> Result<Self, DescriptorError> {
59        let mut parser = DescriptorParser::new(input);
60        let descriptor = parser.parse_field_type()?;
61
62        if !parser.is_finished() {
63            return Err(DescriptorError::TrailingInput {
64                offset: parser.offset(),
65            });
66        }
67
68        Ok(descriptor)
69    }
70
71    /// Returns the number of JVM local-variable or operand-stack slots used.
72    #[must_use]
73    pub const fn slot_width(&self) -> u8 {
74        match self {
75            Self::Primitive(primitive) => primitive.slot_width(),
76            Self::Reference(_) | Self::Array { .. } => 1,
77        }
78    }
79}
80
81/// A JVM method return descriptor.
82#[derive(Debug, Clone, PartialEq, Eq, Hash)]
83pub enum ReturnType {
84    /// The `V` method return descriptor.
85    Void,
86    /// A method that returns a non-void value.
87    Type(TypeDescriptor),
88}
89
90/// A parsed JVM method descriptor.
91#[derive(Debug, Clone, PartialEq, Eq, Hash)]
92pub struct MethodDescriptor {
93    parameters: Vec<TypeDescriptor>,
94    return_type: ReturnType,
95}
96
97impl MethodDescriptor {
98    /// Parses one complete JVM method descriptor.
99    ///
100    /// For example, `(I)Ljava/lang/String;` describes a method that accepts an
101    /// integer and returns a string.
102    pub fn parse(input: &str) -> Result<Self, DescriptorError> {
103        let mut parser = DescriptorParser::new(input);
104        parser.expect('(')?;
105
106        let mut parameters = Vec::new();
107        while !parser.consume(')')? {
108            parameters.push(parser.parse_field_type()?);
109        }
110
111        let return_type = if parser.consume('V')? {
112            ReturnType::Void
113        } else {
114            ReturnType::Type(parser.parse_field_type()?)
115        };
116
117        if !parser.is_finished() {
118            return Err(DescriptorError::TrailingInput {
119                offset: parser.offset(),
120            });
121        }
122
123        Ok(Self {
124            parameters,
125            return_type,
126        })
127    }
128
129    /// Returns parameter descriptors in declaration order.
130    #[must_use]
131    pub fn parameters(&self) -> &[TypeDescriptor] {
132        &self.parameters
133    }
134
135    /// Returns the method's return descriptor.
136    #[must_use]
137    pub const fn return_type(&self) -> &ReturnType {
138        &self.return_type
139    }
140
141    /// Returns the combined JVM slot width of all parameters.
142    ///
143    /// This does not include an instance method's implicit `this` parameter.
144    #[must_use]
145    pub fn parameter_slot_count(&self) -> u16 {
146        self.parameters
147            .iter()
148            .map(|parameter| u16::from(parameter.slot_width()))
149            .sum()
150    }
151}
152
153struct DescriptorParser<'input> {
154    input: &'input [u8],
155    cursor: usize,
156}
157
158impl<'input> DescriptorParser<'input> {
159    const fn new(input: &'input str) -> Self {
160        Self {
161            input: input.as_bytes(),
162            cursor: 0,
163        }
164    }
165
166    fn expect(&mut self, expected: char) -> Result<(), DescriptorError> {
167        if self.consume(expected)? {
168            Ok(())
169        } else {
170            Err(DescriptorError::Expected {
171                expected,
172                offset: self.cursor,
173            })
174        }
175    }
176
177    fn consume(&mut self, expected: char) -> Result<bool, DescriptorError> {
178        let Some(actual) = self.peek()? else {
179            return Ok(false);
180        };
181
182        if actual == expected as u8 {
183            self.cursor += 1;
184            Ok(true)
185        } else {
186            Ok(false)
187        }
188    }
189
190    fn parse_field_type(&mut self) -> Result<TypeDescriptor, DescriptorError> {
191        let offset = self.cursor;
192        let tag = self
193            .next()?
194            .ok_or(DescriptorError::UnexpectedEnd { offset })?;
195
196        let primitive = match tag {
197            b'Z' => Some(PrimitiveType::Boolean),
198            b'B' => Some(PrimitiveType::Byte),
199            b'C' => Some(PrimitiveType::Char),
200            b'S' => Some(PrimitiveType::Short),
201            b'I' => Some(PrimitiveType::Int),
202            b'F' => Some(PrimitiveType::Float),
203            b'J' => Some(PrimitiveType::Long),
204            b'D' => Some(PrimitiveType::Double),
205            _ => None,
206        };
207
208        if let Some(primitive) = primitive {
209            return Ok(TypeDescriptor::Primitive(primitive));
210        }
211
212        match tag {
213            b'L' => self.parse_reference_type(),
214            b'[' => self.parse_array_type(),
215            tag => Err(DescriptorError::InvalidTag {
216                tag: char::from(tag),
217                offset,
218            }),
219        }
220    }
221
222    fn parse_reference_type(&mut self) -> Result<TypeDescriptor, DescriptorError> {
223        let start = self.cursor;
224        while let Some(next) = self.peek()? {
225            if next == b';' {
226                break;
227            }
228            self.cursor += 1;
229        }
230
231        if self.cursor == self.input.len() {
232            return Err(DescriptorError::UnexpectedEnd {
233                offset: self.cursor,
234            });
235        }
236
237        let name = std::str::from_utf8(&self.input[start..self.cursor]).map_err(|_| {
238            DescriptorError::InvalidTag {
239                tag: '\u{fffd}',
240                offset: start,
241            }
242        })?;
243        self.cursor += 1;
244
245        Ok(TypeDescriptor::Reference(ClassName::parse(name)?))
246    }
247
248    fn parse_array_type(&mut self) -> Result<TypeDescriptor, DescriptorError> {
249        let mut dimensions = 1_u8;
250        while self.consume('[')? {
251            dimensions = dimensions
252                .checked_add(1)
253                .ok_or(DescriptorError::TooManyArrayDimensions)?;
254        }
255
256        let element = self.parse_field_type()?;
257        Ok(TypeDescriptor::Array {
258            dimensions,
259            element: Box::new(element),
260        })
261    }
262
263    fn peek(&self) -> Result<Option<u8>, DescriptorError> {
264        Ok(self.input.get(self.cursor).copied())
265    }
266
267    fn next(&mut self) -> Result<Option<u8>, DescriptorError> {
268        let next = self.peek()?;
269        if next.is_some() {
270            self.cursor += 1;
271        }
272        Ok(next)
273    }
274
275    const fn offset(&self) -> usize {
276        self.cursor
277    }
278
279    const fn is_finished(&self) -> bool {
280        self.cursor == self.input.len()
281    }
282}