esyn 0.9.1

De/Serialization Rust In Rust.
Documentation
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use crate::{visit::*, *};

use std::cell::OnceCell;
use syn::*;

#[derive(Debug)]
pub struct Esyn<'ast> {
    ast: File,
    // ?sync::OnceLock
    pub map_fn: OnceCell<VisitItemFn<'ast>>,
}

#[derive(Debug)]
pub struct EsynBuilder {
    fn_name: String,
    let_name: Option<String>,
    flag_res: bool,
}

#[derive(Debug)]
pub struct FnBlock<'ast> {
    pub inner: &'ast ItemFn,
    //pub ident: &'ast Ident,
    //pub stmts: &'ast Vec<Stmt>,

    // e.g.
    //   let ident = expr;
    pub map_local: VisitLocal<'ast>,
    // e.g.
    //   ident = expr;
    pub map_assign: VisitExprAssign<'ast>,
    // e.g.
    //   ::alias(xxx, yyy);
    //   xxx = 123;
    pub map_alias: CallAlias<'ast>,

    pub ret: RetType,
    //pub ext_expr:Vec<Expr>
}

#[derive(Debug, Default, PartialEq)]
pub enum RetType {
    #[default]
    Unit,
    Named,
    Unnamed,

    Any,

    Unknown(Box<Type>),
}

impl<'ast> Esyn<'ast> {
    pub fn new(code: &str) -> Self {
        Self {
            ast: syn::parse_str(code).unwrap(),
            map_fn: OnceCell::new(),
        }
    }

    pub fn init(&'ast self) -> Res<()> {
        self.update_map_fn()
    }

    pub fn get_value<T>(&self, fn_name: &str, let_name: &str) -> Res<Wrap<T>>
    where
        T: DeRs<Expr> + MutPath,
    {
        let mut res: T = self.inner_get_value(fn_name, let_name)?;

        let fn_name = quote::format_ident!("{fn_name}");
        let fb = self
            .map_fn
            .get()
            .unwrap()
            .inner
            .get(&fn_name)
            .ok_or(err! { NotFound: "{fn_name}" })?;

        fb.exec(&mut res, let_name)?;

        Ok(Wrap::new(res))
    }

    // e.g.
    //   f() -> Any { ... }
    pub fn get_res<T>(&self, fn_name: &str) -> Res<Wrap<T>>
    where
        T: DeRs<Expr>,
    {
        let fn_name = quote::format_ident!("{fn_name}");
        let FnBlock { inner, ret, .. } = self
            .map_fn
            .get()
            .ok_or(MyErr::Todo)?
            .inner
            .get(&fn_name)
            .ok_or(err! { NotFound: "{fn_name}" })?;

        if ret != &RetType::Any {
            return err!(Expected "Any", ret.to_string());
        }

        let Stmt::Expr(expr, None) = &inner.block.stmts[0] else {
            unreachable!("{inner:#?}")
        };

        Ok(Wrap::new(<T as DeRs<Expr>>::de(expr)?))
    }

    fn inner_get_value<T>(&self, fn_name: &str, let_name: &str) -> Res<T>
    where
        T: DeRs<Expr> + MutPath,
    {
        let fn_name = quote::format_ident!("{fn_name}");
        let let_name = quote::format_ident!("{let_name}");

        let expr = {
            let map = &self.map_fn.get().ok_or(MyErr::Todo)?.inner;
            let map = &map.get(&fn_name).ok_or(MyErr::Todo)?.map_local.inner;

            map.get(&let_name).ok_or(MyErr::Todo)?
        };

        <T as DeRs<Expr>>::de(expr)
    }

    fn update_map_fn(&'ast self) -> Res<()> {
        let mut tmp: VisitItemFn = Default::default();
        tmp.visit_file(&self.ast);

        // update fields
        for (.., fb) in tmp.inner.iter_mut() {
            for ast in fb.inner.block.stmts.iter() {
                fb.visit_stmt(ast);
            }
        }

        //let crate_fn = crate_fn.unwrap_or(|_| Ok(()));
        //for (.., f) in tmp.inner.iter_mut() {
        //   f.visit()?;
        //}

        // init
        self.map_fn.set(tmp).unwrap();

        Ok(())
    }
}

impl<'ast> Esyn<'ast> {
    fn _get_fn(&'ast self, fn_name: &str) -> Res<&'ast FnBlock> {
        let fn_name = quote::format_ident!("{fn_name}");
        let fb = self
            .map_fn
            .get()
            .unwrap()
            .inner
            .get(&fn_name)
            .ok_or(err!(NotFound: "{fn_name}"))?;

        Ok(fb)
    }
}

impl<'ast> FnBlock<'ast> {
    pub fn new(inner: &'ast ItemFn, ret: RetType) -> Self {
        Self {
            inner,
            ret,
            map_local: Default::default(),
            map_assign: Default::default(),
            map_alias: Default::default(),
        }
    }

    fn _visit(&mut self) -> Res<()> {
        for stmt in self.inner.block.stmts.iter() {
            self.visit_stmt(stmt);
        }

        Ok(())
    }

    fn exec<T: MutPath>(&self, res: &mut T, let_name: &str) -> Res<()> {
        let map_assign = &self.map_assign;
        let map_alias = &self.map_alias;

        for InnerExprAssign {
            left_head,
            left_body,
            right,
        } in map_assign.inner.iter()
        {
            // assign:
            //   a.b.c.d = 456;
            //   │ └─┬─┘
            //   │   └── body
            //   └── head AND let_name
            //
            if *left_head == let_name {
                let mut path = left_body.clone();
                path.reverse();

                // update
                res.mut_path(&mut path.iter(), right)?;
            }
            // alias:
            //   ::alias(_alias, a.b.c.d);
            //   _alias.field = 123;
            //
            //                src_head
            //   InnerCall       │src_body
            //     ┌─┴─┐         │ ┌─┴─┐
            //   ::alias(_alias, a.b.c.d);
            //           └─┬──┘  └──┬──┘
            //             │        │
            //             │        └── src
            //             └── let_name/alias
            //
            //   _alias.field = 123;
            //   └─┬──┘ └─┬─┘    └─ val
            //     │      └── field
            //     └── let_name/alias
            //
            else if let Some(InnerCallAlias { src_head, src_body }) =
                map_alias.inner.get(left_head)
            {
                if *src_head == let_name {
                    let mut path = left_body.clone();

                    path.extend_from_slice(src_body.as_slice());
                    path.reverse();

                    res.mut_path(&mut path.iter(), right)?;
                }
            }
        }

        Ok(())
    }

    fn inner_visit_expr_call<'out: 'ast>(
        &mut self,
        ExprCall { func, args, .. }: &'out ExprCall,
    ) -> Res<()> {
        let Expr::Path(ExprPath {
            path: syn::Path {
                leading_colon,
                segments,
            },
            ..
        }) = func.as_ref()
        else {
            return Ok(());
        };

        let flag = leading_colon.is_some();
        let path = join_path_seg(segments, "::");

        match (flag, path.as_str()) {
            // e.g.
            //   ::alias(www, v.a.b.c);
            //   www = 123;
            //
            (true, "alias") => self.up_fn_alias(args),

            // e.g.
            //   crate::func( ... );
            //   (false, ..)
            //let name = join_path_seg(segments, "::");
            //(fn_block, name.as_str(), args).fm(crate_fn)?;
            _ => Ok(()),
        }
    }

    fn up_fn_alias<'out: 'ast>(&mut self, args: &'out Punctuated<Expr, Token![,]>) -> Res<()> {
        let (
            Expr::Path(ExprPath {
                path: Path { segments, .. },
                ..
            }),
            path,
        ) = (&args[0], &args[1])
        else {
            return err!(Panic "expected `path`");
        };

        let dst = &segments[0].ident;
        let (src_head, src_body) = get_field_path(path)?;

        self.map_alias
            .inner
            .insert(dst, InnerCallAlias { src_head, src_body });

        Ok(())
    }
}

impl EsynBuilder {
    pub fn new() -> Self {
        Self {
            fn_name: "main".to_string(),
            let_name: None,
            flag_res: false,
        }
    }

    pub fn set_fn<T: Into<String>>(mut self, i: T) -> Self {
        self.fn_name = i.into();

        self
    }

    pub fn set_let<T: Into<String>>(mut self, i: T) -> Self {
        self.let_name = Some(i.into());

        self
    }

    pub fn flag_res(mut self) -> Self {
        self.flag_res = true;

        self
    }

    //pub fn with_fn_expr<'scope, O>(f: FnExpr<'scope, O>) {}

    pub fn get_once<T>(&self, code: &str) -> Res<Wrap<T>>
    where
        T: DeRs<Expr> + MutPath,
    {
        let tmp = Esyn::new(code);
        tmp.update_map_fn()?;

        self.get(&tmp)
    }

    pub fn get<T>(&self, esyn: &Esyn) -> Res<Wrap<T>>
    where
        T: DeRs<Expr> + MutPath,
    {
        match &self {
            // e.g.
            //   let a = 1;
            //       ^
            Self {
                ref fn_name,
                let_name: Some(let_name),
                flag_res: false,
                ..
            } => esyn.get_value(fn_name, let_name),

            // e.g.
            //   fn main() -> Any {}
            //                ^^^
            Self {
                ref fn_name,
                let_name: None,
                flag_res: true,
                ..
            } => esyn.get_res(fn_name),

            _ => unreachable!("{self:#?}"),
        }
    }
}

impl RetType {
    pub fn from_ast(ast: &ReturnType) -> Self {
        let ReturnType::Type(.., ty) = ast else {
            return Default::default();
        };

        match ty.as_ref() {
            // e.g.
            //   fn f() -> Any { ... }
            Type::Path(TypePath { path, .. }) => {
                let len = path.segments.len();
                let head = &path.segments[0].ident;

                // TODO: Unit
                // TODO: Unnamed
                // TODO: Named
                match (len, head.to_string().as_str()) {
                    (1, "Any") => Self::Any,
                    _ => unimplemented!(),
                }
            }

            _ => Self::Unknown(ty.to_owned()),
        }
    }
}

impl<'ast> Visit<'ast> for FnBlock<'ast> {
    fn visit_stmt(&mut self, i: &'ast Stmt) {
        match i {
            Stmt::Expr(Expr::Block(_ast), Some(..)) => {
                // TODO:
                // ?Fn OR visit
            }

            Stmt::Local(ast) => self.map_local.visit_local(ast),

            Stmt::Expr(Expr::Assign(ast), Some(..)) => self.map_assign.visit_expr_assign(ast),
            Stmt::Expr(Expr::Call(ast), ..) => self.visit_expr_call(ast),

            _ => {}
        }
    }

    fn visit_expr_call(&mut self, i: &'ast ExprCall) {
        self.inner_visit_expr_call(i).unwrap();
    }
}

impl Default for EsynBuilder {
    fn default() -> Self {
        Self::new()
    }
}

fn _join_field_path(i: &[&Ident]) -> String {
    let mut res = Vec::with_capacity(i.len());
    for f in i.iter().rev() {
        res.push(f.to_string());
    }

    res.join(".")
}

pub fn join_path_seg(i: &punctuated::Punctuated<PathSegment, Token!(::)>, sep: &str) -> String {
    let mut res = Vec::with_capacity(i.len());
    for PathSegment { ident, .. } in i.iter() {
        res.push(ident.to_string());
    }

    res.join(sep)
}

pub fn get_field_path(i: &Expr) -> Res<(&Ident, Vec<&Ident>)> {
    // maybe 6
    let mut tmp = Vec::with_capacity(6);
    let mut expr = i;
    loop {
        match expr {
            Expr::Field(ExprField {
                member: Member::Named(i),
                base,
                ..
            }) => {
                tmp.push(i);
                expr = base;
            }

            Expr::Path(v) => return Ok((v.path.get_ident().unwrap(), tmp)),

            _ => unreachable!("{expr:#?}"),
        }
    }
}

impl ToString for RetType {
    fn to_string(&self) -> String {
        match self {
            Self::Any => "Any".to_string(),
            Self::Unknown(ty) => ty.into_token_stream().to_string(),
            _ => todo!(),
        }
    }
}