Skip to main content

fic/parser/
types.rs

1//! Parser for the Fiducia type grammar and information flow security labels.
2//!
3//! See [`crate::ast::types`] for the type system's AST node documentation
4//! (primitives, page sizes, permissions, addresses) and
5//! [`crate::ast::infoflow`] for the `SecurityLabel` type documentation.
6//!
7//! ```text
8//! High MemoryRegion secret(0x1000);   // confidential
9//! MemoryRegion public(0x1000);        // Low by default
10//! ```
11
12use winnow::ascii::dec_uint;
13use winnow::combinator::{alt, delimited, opt};
14use winnow::error::StrContext;
15use winnow::Parser;
16
17use super::lexer::{binder, identifier, keyword, reserved, ws, Input, PResult};
18use crate::ast::{ArraySize, PrimitiveType, SecurityLabel, Type};
19
20/// Parse a security label keyword (`High` or `Low`).
21pub fn security_label(input: &mut Input<'_>) -> PResult<SecurityLabel> {
22    alt((
23        reserved(keyword::HIGH).value(SecurityLabel::High),
24        reserved(keyword::LOW).value(SecurityLabel::Low),
25    ))
26    .parse_next(input)
27}
28
29/// Parse a single typed identifier in `ident: Type` form.
30///
31/// Returns `(Type, name)` — the canonical storage order used throughout
32/// the AST — so callers get a `(Type, String)` pair without any
33/// field-order gymnastics.
34///
35/// ```text
36/// x: int        →  (Type::Primitive(Int), "x")
37/// pkt: uint32   →  (Type::Primitive(UInt32), "pkt")
38/// ```
39pub fn typed_param(input: &mut Input<'_>) -> PResult<(Type, String)> {
40    let (name, _, ty) = (binder, (ws, ':', ws), parse).parse_next(input)?;
41    Ok((ty, name.to_string()))
42}
43
44/// Parse a type expression, including an optional fixed-size array suffix.
45///
46/// ```text
47/// Type     ::= BaseType ('[' ArrayLen ']')?
48/// BaseType ::= int | int8 | int16 | int32 | int64
49///            | uint | uint8 | uint16 | uint32 | uint64
50///            | bool | byte | Address | StructName
51/// ArrayLen ::= integer-literal | const-name
52/// ```
53pub fn parse(input: &mut Input<'_>) -> PResult<Type> {
54    (
55        base_type,
56        opt(delimited((ws, '[', ws), array_size, (ws, ']'))),
57    )
58        .map(|(base, size)| match size {
59            Some(size) => Type::Array {
60                elem: Box::new(base),
61                size,
62            },
63            None => base,
64        })
65        .parse_next(input)
66}
67
68/// Parse a fixed-size array length: an integer literal or a `const` name.
69pub(super) fn array_size(input: &mut Input<'_>) -> PResult<ArraySize> {
70    alt((
71        dec_uint.map(ArraySize::Lit),
72        identifier.map(|name: &str| ArraySize::Named(name.to_string())),
73    ))
74    .context(StrContext::Label(
75        "array length (integer literal or const name)",
76    ))
77    .parse_next(input)
78}
79
80/// Parse a base (non-array) type expression.
81fn base_type(input: &mut Input<'_>) -> PResult<Type> {
82    alt((
83        alt((
84            reserved(keyword::INT).value(Type::Primitive(PrimitiveType::Int)),
85            reserved(keyword::INT8).value(Type::Primitive(PrimitiveType::Int8)),
86            reserved(keyword::INT16).value(Type::Primitive(PrimitiveType::Int16)),
87            reserved(keyword::INT32).value(Type::Primitive(PrimitiveType::Int32)),
88            reserved(keyword::INT64).value(Type::Primitive(PrimitiveType::Int64)),
89        ))
90        .context(StrContext::Label("int type")),
91        alt((
92            reserved(keyword::UINT).value(Type::Primitive(PrimitiveType::UInt)),
93            reserved(keyword::UINT8).value(Type::Primitive(PrimitiveType::UInt8)),
94            reserved(keyword::UINT16).value(Type::Primitive(PrimitiveType::UInt16)),
95            reserved(keyword::UINT32).value(Type::Primitive(PrimitiveType::UInt32)),
96            reserved(keyword::UINT64).value(Type::Primitive(PrimitiveType::UInt64)),
97        ))
98        .context(StrContext::Label("uint type")),
99        reserved(keyword::BOOL)
100            .value(Type::Primitive(PrimitiveType::Bool))
101            .context(StrContext::Label("bool type")),
102        reserved(keyword::BYTE)
103            .value(Type::Primitive(PrimitiveType::Byte))
104            .context(StrContext::Label("byte type")),
105        reserved(keyword::ADDRESS)
106            .value(Type::Primitive(PrimitiveType::Address))
107            .context(StrContext::Label("Address type")),
108        // Fallback: any other identifier is a named struct type, resolved
109        // against the `.fis` struct declarations during validation (#124).
110        identifier
111            .map(|name: &str| Type::Struct(name.to_string()))
112            .context(StrContext::Label("struct type name")),
113    ))
114    .parse_next(input)
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    fn ty(src: &str) -> Type {
122        let mut input = winnow::stream::LocatingSlice::new(src);
123        parse(&mut input).expect("parse type")
124    }
125
126    #[test]
127    fn parses_scalar_types() {
128        assert_eq!(ty("uint32"), Type::Primitive(PrimitiveType::UInt32));
129        assert_eq!(ty("byte"), Type::Primitive(PrimitiveType::Byte));
130        assert_eq!(ty("Packet"), Type::Struct("Packet".to_string()));
131    }
132
133    #[test]
134    fn parses_fixed_size_array() {
135        assert_eq!(
136            ty("byte[16]"),
137            Type::Array {
138                elem: Box::new(Type::Primitive(PrimitiveType::Byte)),
139                size: ArraySize::Lit(16),
140            }
141        );
142        assert_eq!(
143            ty("byte[PACKET_BUFFER_SIZE]"),
144            Type::Array {
145                elem: Box::new(Type::Primitive(PrimitiveType::Byte)),
146                size: ArraySize::Named("PACKET_BUFFER_SIZE".to_string()),
147            }
148        );
149    }
150}