1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
//mod expanded;
///traits and types specific to rlua
#[cfg(feature = "rlua")]
pub mod rlu;

///traits and types specific to mlua
#[cfg(feature = "mlua")]
pub mod mlu;

mod export_instance;
mod exported_function;
mod teal_multivalue;
mod type_generator;
mod type_representation;
mod type_walker;

use std::{borrow::Cow, collections::HashSet};

pub use exported_function::ExportedFunction;
use serde::{Deserialize, Serialize};
pub use teal_multivalue::{TealMultiValue, TealType};

///Implements [ToTypename](crate::ToTypename).
///
///`TypeName::get_type_name` will return the name of the rust type.
#[cfg(feature = "derive")]
pub use tealr_derive::ToTypename;

pub use type_generator::{EnumGenerator, Field, NameContainer, RecordGenerator, TypeGenerator};
pub use type_representation::{type_parts_to_str, KindOfType, NamePart, TypeBody, TypeName};
pub use type_walker::{ExtraPage, GlobalInstance, TypeWalker};

#[cfg(feature = "compile")]
pub use tealr_derive::compile_inline_teal;

#[cfg(any(
    feature = "embed_compiler_from_local",
    feature = "embed_compiler_from_download"
))]
pub use tealr_derive::embed_compiler;

/// Gets the current version of tealr.
///
/// Useful when consuming the .json files to check if it is a supported version
pub fn get_tealr_version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

#[derive(PartialEq, Eq, Hash, Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
    all(feature = "mlua", feature = "derive", not(feature = "rlua")),
    derive(crate::mlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(feature = "rlua", feature = "derive", not(feature = "mlua")),
    derive(crate::rlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))),
    tealr(tealr_name = crate)
)]
///The name of a type
pub struct Name(
    #[cfg_attr(
    all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))),
    tealr(remote =  String))]
    pub Cow<'static, str>,
);
impl core::fmt::Display for Name {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<T: AsRef<str>> From<T> for Name {
    fn from(value: T) -> Self {
        Name(value.as_ref().to_owned().into())
    }
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
    all(feature = "mlua", feature = "derive", not(feature = "rlua")),
    derive(crate::mlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(feature = "rlua", feature = "derive", not(feature = "mlua")),
    derive(crate::rlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))),
    tealr(tealr_name = crate)
)]
///A singular type
pub struct SingleType {
    ///The name of the type
    pub name: Name,
    ///The kind of type that is being represented
    pub kind: KindOfType,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
    all(feature = "mlua", feature = "derive", not(feature = "rlua")),
    derive(crate::mlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(feature = "rlua", feature = "derive", not(feature = "mlua")),
    derive(crate::rlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))),
    tealr(tealr_name = crate)
)]
///A parameter for a function
pub struct FunctionParam {
    ///If the parameter has a name (will default to Param{number} if None)
    pub param_name: Option<Name>,
    ///The type of the parameter
    pub ty: Type,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(
    all(feature = "mlua", feature = "derive", not(feature = "rlua")),
    derive(crate::mlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(feature = "rlua", feature = "derive", not(feature = "mlua")),
    derive(crate::rlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))),
    tealr(tealr_name = crate)
)]
///The representation of a function type
pub struct FunctionRepresentation {
    ///The parameters
    pub params: Vec<FunctionParam>,
    ///the return types
    pub returns: Vec<Type>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(
    all(feature = "mlua", feature = "derive", not(feature = "rlua")),
    derive(crate::mlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(feature = "rlua", feature = "derive", not(feature = "mlua")),
    derive(crate::rlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))),
    tealr(tealr_name = crate)
)]
///The representation of a Map<K,T> type
pub struct MapRepresentation {
    #[cfg_attr(
        all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))),
        tealr(remote =  Type))]
    ///The type of the key
    pub key: Box<Type>,
    #[cfg_attr(
        all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))),
        tealr(remote =  Type))]
    ///The type of the value
    pub value: Box<Type>,
}

type NewTypeArray = Vec<Type>;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(
    all(feature = "mlua", feature = "derive", not(feature = "rlua")),
    derive(crate::mlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(feature = "rlua", feature = "derive", not(feature = "mlua")),
    derive(crate::rlu::FromToLua, crate::ToTypename)
)]
#[cfg_attr(
    all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))),
    tealr(tealr_name = crate)
)]
///A type
pub enum Type {
    ///The type is a function
    Function(FunctionRepresentation),
    ///The type is a simple, singular type
    Single(SingleType),
    ///The type is a Map<K,V> (Think HashMap<K,V> and similar)
    Map(MapRepresentation),
    ///The type is a union (A | B)
    Or(
        #[cfg_attr(
            all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))),
            tealr(remote =  NewTypeArray))]
        Vec<Type>,
    ),
    ///The type is an array
    Array(
        #[cfg_attr(
            all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))),
            tealr(remote =  Type))]
        Box<Type>,
    ),
    ///This one doesn't really exist in lua/teal but will expand in (A,B,C)
    ///Sometimes useful for the return type or parameters but should be used _very_ carefully
    ///As it can _easily_ break things
    Tuple(
        #[cfg_attr(
            all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))),
            tealr(remote =  NewTypeArray))]
        Vec<Type>,
    ),
}

impl From<Box<Type>> for Type {
    fn from(value: Box<Type>) -> Self {
        *value
    }
}
impl Type {
    ///Creates a new singular type
    pub fn new_single(name: impl AsRef<str>, kind: KindOfType) -> Self {
        Self::Single(SingleType {
            name: name.into(),
            kind,
        })
    }
}
///This trait turns a A into a type representation for Lua/Teal
pub trait ToTypename {
    ///Used to get the old representation.
    ///Should basically never be used or implemented manually
    #[deprecated]
    fn to_old_type_parts() -> Cow<'static, [NamePart]> {
        #[allow(deprecated)]
        new_type_to_old(Self::to_typename(), false)
    }
    ///generates the type representation
    fn to_typename() -> Type;
    ///generates the type representation when used as a parameter
    ///By default will assume no name was given
    ///
    ///This is useful when the type you made is _specifically_ made to add more
    ///context to function parameters.
    fn to_function_param() -> Vec<FunctionParam> {
        vec![FunctionParam {
            param_name: None,
            ty: Self::to_typename(),
        }]
    }
}
impl<T: ToTypename> TypeName for T {
    fn get_type_parts() -> Cow<'static, [NamePart]> {
        #[allow(deprecated)]
        Self::to_old_type_parts()
    }
}
///Turns a type in the new representation into the old representation
#[deprecated]
pub fn new_type_to_old(a: Type, is_callback: bool) -> Cow<'static, [NamePart]> {
    match a {
        Type::Single(a) => Cow::Owned(vec![NamePart::Type(TealType {
            name: a.name.0,
            type_kind: a.kind,
            generics: None,
        })]),
        Type::Array(x) => {
            let mut parts = Vec::with_capacity(3);
            parts.push(NamePart::symbol("{"));
            parts.extend(new_type_to_old(*x, true).iter().cloned());
            parts.push(NamePart::symbol("}"));
            parts.into()
        }
        Type::Map(MapRepresentation { key, value }) => {
            let mut parts = Vec::with_capacity(5);
            parts.push(NamePart::symbol("{"));
            parts.extend(new_type_to_old(*key, true).iter().cloned());
            parts.push(NamePart::symbol(" : "));
            parts.extend(new_type_to_old(*value, true).iter().cloned());
            parts.push(NamePart::symbol("}"));
            parts.into()
        }
        Type::Or(x) => {
            if x.is_empty() {
                eprintln!("An NewType::Or found with empty contents. Skipping");
                return Vec::new().into();
            }
            let mut parts = Vec::with_capacity(x.len());
            parts.push(NamePart::symbol("("));

            for part in x {
                parts.extend(new_type_to_old(part, true).iter().cloned());
                parts.push(NamePart::symbol(" | "))
            }
            parts.pop();
            parts.push(NamePart::symbol(")"));
            parts.into()
        }
        Type::Tuple(x) => {
            if x.is_empty() {
                eprintln!("An NewType::Tuple found with empty contents. Skipping");
                return Vec::new().into();
            }
            let mut parts = Vec::with_capacity(x.len());
            parts.push(NamePart::symbol("("));
            for part in x {
                parts.extend(new_type_to_old(part, true).iter().cloned());
                parts.push(NamePart::symbol(" , "))
            }
            parts.pop();
            parts.push(NamePart::symbol(")"));
            parts.into()
        }
        Type::Function(FunctionRepresentation { params, returns }) => {
            let mut parts = Vec::with_capacity(params.len() + returns.len());
            parts.push(NamePart::symbol("function"));
            let generics: HashSet<_> = params
                .iter()
                .map(|v| &v.ty)
                .chain(returns.iter())
                .flat_map(get_generics)
                .collect();
            let generic_amount = generics.len();
            if (!is_callback) && generic_amount > 0 {
                parts.push(NamePart::Symbol("<".into()));
                for generic in generics {
                    parts.push(NamePart::Type(TealType {
                        name: generic.0.clone(),
                        type_kind: KindOfType::Generic,
                        generics: None,
                    }));
                    parts.push(NamePart::symbol(","));
                }
                parts.pop();
                parts.push(NamePart::symbol(">"));
            }
            parts.push(NamePart::symbol("("));
            let has_params = !params.is_empty();
            for param in params {
                if let Some(name) = param.param_name {
                    parts.push(NamePart::Symbol(name.0.clone()));
                    parts.push(NamePart::symbol(":"));
                }
                parts.extend(new_type_to_old(param.ty, true).iter().cloned());
                parts.push(NamePart::symbol(" , "));
            }
            if has_params {
                parts.pop();
            }
            parts.push(NamePart::symbol(")"));
            if !returns.is_empty() {
                parts.push(NamePart::symbol(":("));
                for ret in returns {
                    parts.extend(new_type_to_old(ret, true).iter().cloned());
                    parts.push(NamePart::symbol(" , "))
                }
                parts.pop();
                parts.push(NamePart::symbol(")"));
            }

            Cow::Owned(parts)
        }
    }
}
///Gets the generics of any given type
pub fn get_generics(to_check: &Type) -> HashSet<&Name> {
    match to_check {
        Type::Function(FunctionRepresentation { params, returns }) => params
            .iter()
            .map(|v| &v.ty)
            .chain(returns.iter())
            .flat_map(get_generics)
            .collect(),
        Type::Array(x) => get_generics(x.as_ref()),

        Type::Single(x) => {
            let mut set = HashSet::new();
            if x.kind == KindOfType::Generic {
                set.insert(&x.name);
            }
            set
        }
        Type::Or(x) | Type::Tuple(x) => x.iter().flat_map(get_generics).collect(),
        Type::Map(MapRepresentation { key, value }) => {
            let mut generics = get_generics(key);
            generics.extend(get_generics(value));
            generics
        }
    }
}