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