Skip to main content

rust_anything/ts/
shape.rs

1//! The shape of a TS type, for generating values that fit it.
2
3use oxc_allocator::Allocator;
4use oxc_ast::ast::{
5    PropertyKey, Statement, TSLiteral, TSSignature, TSTupleElement, TSType, TSTypeName,
6};
7use oxc_parser::Parser;
8use oxc_span::SourceType;
9
10use super::exports::LocalType;
11
12#[derive(Clone, Debug, PartialEq)]
13pub enum Shape {
14    Str,
15    Num,
16    /// `int` in the type dialect.
17    Int,
18    Bool,
19    Null,
20    Undefined,
21    LitStr(String),
22    LitNum(f64),
23    LitBool(bool),
24    Union(Vec<Shape>),
25    Array(Box<Shape>),
26    Tuple(Vec<Shape>),
27    /// Named properties `(name, optional, shape)`, and the value shape of an index signature.
28    Object(Vec<(String, bool, Shape)>, Option<Box<Shape>>),
29    /// A named type, resolved against the types in scope when values are generated.
30    Ref(String, Vec<Shape>),
31    /// Anything: `any`, `unknown`, or what this module does not model.
32    Any,
33}
34
35/// Parses a type as written in TS source.
36pub fn parse(text: &str) -> Shape {
37    let source = format!("type __T = {text};");
38    let allocator = Allocator::default();
39    let ret = Parser::new(&allocator, &source, SourceType::ts()).parse();
40    for statement in &ret.program.body {
41        if let Statement::TSTypeAliasDeclaration(alias) = statement {
42            return convert(&alias.type_annotation);
43        }
44    }
45    Shape::Any
46}
47
48/// The shape a named type stands for, from the types in scope.
49pub fn resolve(name: &str, args: &[Shape], types: &[LocalType]) -> Shape {
50    match (name, args) {
51        ("Array" | "ReadonlyArray" | "Set" | "ReadonlySet", [item]) => {
52            Shape::Array(Box::new(item.clone()))
53        }
54        ("Record", [_, value]) => Shape::Object(Vec::new(), Some(Box::new(value.clone()))),
55        ("Readonly" | "Promise" | "NonNullable", [inner]) => inner.clone(),
56        ("Partial", [inner]) => match inner {
57            Shape::Object(props, index) => Shape::Object(
58                props
59                    .iter()
60                    .map(|(n, _, s)| (n.clone(), true, s.clone()))
61                    .collect(),
62                index.clone(),
63            ),
64            other => other.clone(),
65        },
66        ("int", []) => Shape::Int,
67        _ => match types.iter().find(|t| t.name == name) {
68            Some(t) if t.alias => parse(&t.text),
69            // An interface: its body is a type literal (`extends` is not followed).
70            Some(t) => t.text.find('{').map_or(Shape::Any, |i| parse(&t.text[i..])),
71            None => Shape::Any,
72        },
73    }
74}
75
76fn convert(ty: &TSType) -> Shape {
77    match ty {
78        TSType::TSStringKeyword(_) => Shape::Str,
79        TSType::TSNumberKeyword(_) => Shape::Num,
80        TSType::TSBooleanKeyword(_) => Shape::Bool,
81        TSType::TSNullKeyword(_) => Shape::Null,
82        TSType::TSUndefinedKeyword(_) | TSType::TSVoidKeyword(_) => Shape::Undefined,
83        TSType::TSLiteralType(lit) => match &lit.literal {
84            TSLiteral::StringLiteral(s) => Shape::LitStr(s.value.display().to_string()),
85            TSLiteral::NumericLiteral(n) => Shape::LitNum(n.value),
86            TSLiteral::BooleanLiteral(b) => Shape::LitBool(b.value),
87            _ => Shape::Any,
88        },
89        TSType::TSUnionType(u) => Shape::Union(u.types.iter().map(convert).collect()),
90        TSType::TSArrayType(a) => Shape::Array(Box::new(convert(&a.element_type))),
91        TSType::TSTypeOperatorType(op) => convert(&op.type_annotation),
92        TSType::TSParenthesizedType(p) => convert(&p.type_annotation),
93        TSType::TSTupleType(t) => Shape::Tuple(
94            t.element_types
95                .iter()
96                .map(|e| match e {
97                    TSTupleElement::TSOptionalType(o) => convert(&o.type_annotation),
98                    TSTupleElement::TSRestType(r) => convert(&r.type_annotation),
99                    other => other.as_ts_type().map_or(Shape::Any, convert),
100                })
101                .collect(),
102        ),
103        TSType::TSTypeLiteral(lit) => {
104            let mut props = Vec::new();
105            let mut index = None;
106            for member in &lit.members {
107                match member {
108                    TSSignature::TSPropertySignature(p) => {
109                        let Some(name) = property_name(&p.key) else {
110                            continue;
111                        };
112                        let shape = p
113                            .type_annotation
114                            .as_ref()
115                            .map_or(Shape::Any, |a| convert(&a.type_annotation));
116                        props.push((name, p.optional, shape));
117                    }
118                    TSSignature::TSIndexSignature(s) => {
119                        index = Some(Box::new(convert(&s.type_annotation.type_annotation)));
120                    }
121                    _ => {}
122                }
123            }
124            Shape::Object(props, index)
125        }
126        TSType::TSIntersectionType(i) => {
127            // `A & { b: string }`: merge the object parts.
128            let mut props = Vec::new();
129            let mut index = None;
130            for part in i.types.iter().map(convert) {
131                match part {
132                    Shape::Object(p, idx) => {
133                        props.extend(p);
134                        index = index.or(idx);
135                    }
136                    other => return other,
137                }
138            }
139            Shape::Object(props, index)
140        }
141        TSType::TSTypeReference(r) => {
142            let name = match &r.type_name {
143                TSTypeName::IdentifierReference(id) => id.name.as_str().to_string(),
144                _ => return Shape::Any,
145            };
146            let args = r
147                .type_arguments
148                .as_ref()
149                .map(|a| a.params.iter().map(convert).collect())
150                .unwrap_or_default();
151            Shape::Ref(name, args)
152        }
153        _ => Shape::Any,
154    }
155}
156
157fn property_name(key: &PropertyKey) -> Option<String> {
158    match key {
159        PropertyKey::StaticIdentifier(id) => Some(id.name.as_str().to_string()),
160        PropertyKey::StringLiteral(s) => Some(s.value.display().to_string()),
161        _ => None,
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn parses_shapes() {
171        assert_eq!(
172            parse("{ readonly key: string, n?: number, kind: 'a' | 'b' }"),
173            Shape::Object(
174                vec![
175                    ("key".into(), false, Shape::Str),
176                    ("n".into(), true, Shape::Num),
177                    (
178                        "kind".into(),
179                        false,
180                        Shape::Union(vec![Shape::LitStr("a".into()), Shape::LitStr("b".into())])
181                    ),
182                ],
183                None
184            )
185        );
186        assert_eq!(
187            parse("readonly string[]"),
188            Shape::Array(Box::new(Shape::Str))
189        );
190        assert_eq!(
191            parse("Record<string, Leaf>"),
192            Shape::Ref(
193                "Record".into(),
194                vec![Shape::Str, Shape::Ref("Leaf".into(), vec![])]
195            )
196        );
197        assert_eq!(
198            parse("{ [k: string]: number }"),
199            Shape::Object(vec![], Some(Box::new(Shape::Num)))
200        );
201    }
202
203    #[test]
204    fn resolves_named_types() {
205        let types = super::super::exports::local_types(
206            "m.ts",
207            "export interface Range { readonly start: number\n readonly end: number }\nexport type Leaf = string | null\n",
208        );
209        assert_eq!(
210            resolve("Range", &[], &types),
211            Shape::Object(
212                vec![
213                    ("start".into(), false, Shape::Num),
214                    ("end".into(), false, Shape::Num)
215                ],
216                None
217            )
218        );
219        assert_eq!(
220            resolve("Leaf", &[], &types),
221            Shape::Union(vec![Shape::Str, Shape::Null])
222        );
223        assert_eq!(
224            resolve("Partial", &[parse("{ a: string }")], &types),
225            Shape::Object(vec![("a".into(), true, Shape::Str)], None)
226        );
227    }
228}