yog-script-analyze 0.4.0

Yog Script (.ys, .yns) analyzed: its lexer, parser and syntax tree, names resolved, the class index model — what the build and the editors read a source with.
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Members and calls: a member of the source's own types (their
//! components' too) or of a game class (by C#'s names); a call matched to
//! the method's parameters.

use yog_ids::script_problem;

use super::Checker;
use super::context::Context;
use super::game::{self, Found};
use super::model::Type;
use super::own::TypeKey;
use crate::ast::{Expr, ExprKind, Method, Pass};
use crate::source::token::Span;

/// What a call's callee stands for.
pub(super) enum Callee {
    /// The source's own methods, each with the type parameters its type
    /// binds (`Box<i32>`'s `T` is `i32`; an inherited one's, by the
    /// arguments its base is given: `Dictionary<K, V>`'s `ICollection`'s
    /// `T` is `KeyValuePair<K, V>`).
    Own(Vec<(Method, Context)>),
    /// Extension methods of the receiver (`xs.Where(…)`): it's their first argument.
    Extension(Vec<(Method, Context)>),
    /// Methods typed already: a game class's, Yog's.
    Typed(Vec<Signature>),
    Unknown,
}

/// What a call is matched against.
pub(super) struct Signature {
    pub params: Vec<Type>,
    /// How each parameter takes its argument (`in`, `ref`, …): only the
    /// source's own methods say.
    pub passes: Vec<Option<Pass>>,
    pub required: usize,
    pub ret: Type,
    /// A generic method's type parameters, inferred from a call.
    pub generics: Vec<String>,
    /// Those of them given before (`F<i32>(…)`).
    pub bound: super::generics::Bound,
    /// Its last parameter is `params T[] rest`: the arguments past the
    /// others go in it, or an array of them does (C#'s).
    pub rest: bool,
}

impl Checker<'_, '_, '_> {
    /// `on.name` (`on?.name` when `safe`): its type; what's missing reported.
    pub(super) fn member(&mut self, on: &Type, name: &str, safe: bool, at: Span) -> Type {
        if is_side_call(name) {
            return Type::Unknown;
        }
        if let Some(t) = self.nullable_member(on, name) {
            return t;
        }
        if on.is_nullable() && !safe {
            self.report.error(
                script_problem::NULLABLE,
                at,
                format!("this may be `null`: `?.{name}` reads `{name}` only when it isn't"),
            );
        }
        let t = match on.non_null() {
            Type::Tuple(types, names) => match Self::tuple_item(types, names, name) {
                Some(t) => t,
                None => {
                    self.unknown_member(on.non_null(), name, at);
                    Type::Unknown
                }
            },
            Type::Static(of, args) => {
                let t = self.statics_type(of, args);
                let found = self.own_member(&t, name);
                let case = self
                    .own
                    .named(of)
                    .is_some_and(|(_, o)| o.cases.iter().any(|c| c == name));
                if !found.known() && !case && !self.own_has_method(&t, name) {
                    self.unknown_member(on.non_null(), name, at);
                }
                self.static_field_read(of, name, &found, at);
                found
            }
            Type::Own(..) => {
                let t = self.own_member(on.non_null(), name);
                if !t.known() && !self.own_has_method(on.non_null(), name) {
                    self.unknown_member(on.non_null(), name, at);
                }
                t
            }
            Type::Game(class) => match self.extension_value(class, name) {
                Some(t) => t,
                None => self.game_value(class, name, at),
            },
            // A type reached through its namespace (`System.Logging.LogLevel`):
            // its statics, as its name alone reaches them.
            Type::Namespace(ns) => match self.in_namespace(&super::names::split(ns), name, at) {
                Type::Own(t, args) => Type::Static(t, args),
                other => other,
            },
            Type::Param(p) => match self.param_member(p, name) {
                Some((_, t)) => t,
                None => self.object_member(on.non_null(), name, at),
            },
            Type::Yog(type_name) => match self.extension_value(type_name, name) {
                Some(t) => t,
                None => self.yog_value(type_name, name, at),
            },
            other => match self.hosted(other) {
                Some(host) => {
                    let t = self.own_member(&host, name);
                    if !t.known() && !self.own_has_method(&host, name) {
                        self.unknown_member(other, name, at);
                    }
                    t
                }
                None => Type::Unknown,
            },
        };
        if safe { t.nullable() } else { t }
    }

    /// The type of member `name` of the source's own type `t` (or of a
    /// component it has, or the component itself).
    pub(super) fn own_member(&mut self, t: &Type, name: &str) -> Type {
        let (type_name, args) = match t {
            Type::Own(n, args) => (n, args),
            Type::Game(class) | Type::Yog(class) => {
                return self.extension_value(class, name).unwrap_or(Type::Unknown);
            }
            _ => return Type::Unknown,
        };
        for (key, args) in self.member_lineage(type_name, args) {
            let context = self.context_of(&key.name, &args);
            let found = self.in_context(&context, |c| c.own_member_of(&key, name));
            if found.known() {
                return found;
            }
        }
        Type::Unknown
    }

    /// Member `name` declared by own type `key` itself (or by a component
    /// it has); a case is a value of the enum.
    fn own_member_of(&mut self, key: &TypeKey, name: &str) -> Type {
        let Some(own) = self.own.of_key(key) else {
            return Type::Unknown;
        };
        if let Some(written) = own.values.get(name).cloned() {
            return self.type_of(&written);
        }
        // A case is a value of its enum, of the arguments it's reached with
        // (`Maybe<i32>.Nothing`); those not given are unknown, as Rust infers.
        if own.cases.iter().any(|c| c == name) {
            let args = own
                .generics
                .clone()
                .iter()
                .map(|g| match self.type_param(g) {
                    Some(Type::Param(_)) | None => Type::Unknown,
                    Some(t) => t,
                })
                .collect();
            return Type::Own(key.name.clone(), args);
        }
        let components = own.components.clone();
        if components.iter().any(|c| c == name) {
            return Type::own(name.to_string());
        }
        components
            .iter()
            .map(|c| self.own_member(&Type::own(c.clone()), name))
            .find(Type::known)
            .unwrap_or(Type::Unknown)
    }

    /// What `extend` adds to game class `class`: member `name`'s type, a
    /// component it has, or one of the component's members.
    fn extension_value(&mut self, class: &str, name: &str) -> Option<Type> {
        let ext = self.own.extended.get(crate::index::simple_name(class))?;
        if let Some(written) = ext.values.get(name).cloned() {
            return Some(self.type_of(&written));
        }
        let components = ext.components.clone();
        if components.iter().any(|c| c == name) {
            return Some(Type::own(name.to_string()));
        }
        components
            .iter()
            .map(|c| self.own_member(&Type::own(c.clone()), name))
            .find(Type::known)
    }

    pub(super) fn extension_methods(
        &self,
        class: &str,
        name: &str,
    ) -> Option<Vec<(Method, Context)>> {
        let ext = self.own.extended.get(crate::index::simple_name(class))?;
        match ext.methods.get(name) {
            Some(methods) => Some(self.unbound(methods)),
            None => ext
                .components
                .iter()
                .find_map(|c| self.own_methods(&Type::own(c.clone()), name)),
        }
    }

    pub(super) fn own_has_method(&self, t: &Type, name: &str) -> bool {
        self.own_methods(t, name).is_some()
    }

    fn game_value(&mut self, class: &str, name: &str, at: Span) -> Type {
        let Some(lookup) = &self.lookup else {
            return Type::Unknown;
        };
        let Some(c) = lookup.class(class) else {
            return Type::Unknown;
        };
        match game::member(lookup, c, name, false) {
            Found::Value(t) => t,
            Found::Nothing if matches!(game::member(lookup, c, name, true), Found::Nothing) => {
                self.unknown_member(&Type::Game(class.to_string()), name, at);
                Type::Unknown
            }
            _ => Type::Unknown,
        }
    }

    /// Member `name` of Yog's `type_name`: a struct's field (`Health` is
    /// `health`), an enum's case, a group's group (`Client.Control`); a
    /// method is reached by calling it.
    fn yog_value(&mut self, type_name: &str, name: &str, at: Span) -> Type {
        let surface = &*super::surface::SURFACE;
        if let Some(s) = surface.structs.get(type_name) {
            if let Some(f) = s
                .fields
                .iter()
                .find(|f| yog_codegen::pascal(f.name) == name)
            {
                return Type::of_shape(&(f.shape)());
            }
        } else if let Some(e) = surface.enums.get(type_name) {
            if e.variants
                .iter()
                .any(|v| yog_codegen::pascal(v.name) == name)
            {
                return Type::Yog(type_name.to_string());
            }
        } else {
            let sub = super::surface::subgroup(type_name, name);
            if surface.groups.contains_key(&sub) {
                return Type::Yog(sub);
            }
            // An event: a delegate taking its arguments (`Player.Join += e => …`).
            if let Some(args) = surface
                .groups
                .get(type_name)
                .and_then(|g| g.events.get(name))
            {
                return Type::Fn(vec![Type::Yog(args.clone())], Box::new(Type::Void));
            }
            if surface
                .groups
                .get(type_name)
                .is_some_and(|g| g.methods.contains_key(name))
            {
                return Type::Unknown;
            }
        }
        self.unknown_member(&Type::Yog(type_name.to_string()), name, at);
        Type::Unknown
    }

    pub(super) fn unknown_member(&mut self, on: &Type, name: &str, at: Span) {
        self.report.error(
            script_problem::UNKNOWN_MEMBER,
            at,
            format!("`{on}` has no member `{name}`"),
        );
    }

    /// Whether `e` is a delegate (its type looked at quietly: it's checked after).
    fn is_delegate_value(&mut self, e: &Expr) -> bool {
        let t = self.quietly(|c| c.expr(e));
        self.delegate_sig(&t).is_some()
    }

    /// What `callee` calls.
    pub(super) fn callee(&mut self, callee: &Expr) -> Callee {
        match &callee.kind {
            // A delegate called: `handler(x)`.
            ExprKind::Ident(name) if self.delegate(name).is_some() => {
                // The name's type kept: a compiler calls a delegate by it.
                let t = self.expr(callee);
                self.types.set(callee, t);
                self.delegate(name)
                    .map_or(Callee::Unknown, |sig| Callee::Typed(vec![sig]))
            }
            // `Charged?.Invoke(…)`: a delegate's own call (`MethodInfo`'s
            // `Invoke` is a method like any).
            ExprKind::Member { expr, name, .. }
                if name.text == yog_script_ids::clr::INVOKE && self.is_delegate_value(expr) =>
            {
                let t = self.expr(expr);
                match self.delegate_sig(&t) {
                    Some((params, ret)) => Callee::Typed(vec![signature_of(&params, &ret)]),
                    None => Callee::Unknown,
                }
            }
            ExprKind::Ident(name) if self.local(name).is_none() => {
                let methods = self.callable(name);
                if methods.is_empty() {
                    // `Ok(v)`, `Err(e)`: the prelude's cases, by their names.
                    match self.variant_ctor(yog_script_ids::system::RESULT, name) {
                        Callee::Unknown => self.static_import(name, callee.span),
                        made => made,
                    }
                } else {
                    if let Some(Type::Own(of, _)) = self.this.clone()
                        && self.own_methods(&Type::own(of.clone()), name).is_some()
                    {
                        self.called_on(None, &of, name, callee.span);
                        self.method_read(&of, name, callee.span);
                    }
                    Callee::Own(methods)
                }
            }
            ExprKind::Member { expr, name, .. } => self.method_of(expr, name),
            _ => {
                self.expr(callee);
                Callee::Unknown
            }
        }
    }

    /// The source's own methods `name` reachable unqualified here: `this`'s
    /// (its components' and extensions' too), else the file's.
    pub(super) fn callable(&self, name: &str) -> Vec<(Method, Context)> {
        let local: Vec<(Method, Context)> = self
            .local_fns
            .iter()
            .filter(|(_, m)| m.name.text == name)
            .map(|(_, m)| (m.clone(), self.here()))
            .collect();
        if !local.is_empty() {
            return local;
        }
        let in_this = self.this.clone().and_then(|t| match &t {
            Type::Game(class) | Type::Yog(class) => self.extension_methods(class, name),
            _ => self.own_methods(&t, name),
        });
        in_this
            .or_else(|| self.own.methods.get(name).map(|m| self.unbound(m)))
            .unwrap_or_default()
    }

    /// An own method's parameters' and result's types.
    pub(super) fn signature_types(&mut self, m: &Method) -> (Vec<Type>, Type) {
        let s = self.signature(m);
        (s.params, s.ret)
    }

    /// Methods `name` of own type `t` or the nearest type it inherits that
    /// declares them (or a component of it), each with its type's bound.
    pub(super) fn own_methods(&self, t: &Type, name: &str) -> Option<Vec<(Method, Context)>> {
        let Type::Own(type_name, args) = t else {
            return None;
        };
        self.member_lineage(type_name, args)
            .into_iter()
            .find_map(|(key, args)| {
                let own = self.own.of_key(&key)?;
                match own.methods.get(name) {
                    Some(methods) => {
                        let context = self.context_of(&key.name, &args);
                        Some(
                            methods
                                .iter()
                                .map(|m| (m.clone(), context.clone()))
                                .collect(),
                        )
                    }
                    None => own
                        .components
                        .iter()
                        .find_map(|c| self.own_methods(&Type::own(c.clone()), name)),
                }
            })
    }

    /// A name whose value is a delegate (a local, a member, an event): its signature.
    fn delegate(&mut self, name: &str) -> Option<Signature> {
        let t = match self.local(name) {
            Some(t) => t.clone(),
            None => self.this.clone().map(|this| self.own_member(&this, name))?,
        };
        self.delegate_sig(&t)
            .map(|(params, ret)| signature_of(&params, &ret))
    }

    /// Method `name` a `using static` brings in (`using static Yog.Chat;`
    /// → `Broadcast(…)`).
    fn static_import(&mut self, name: &str, at: Span) -> Callee {
        let statics = self.directives.statics.clone();
        for path in statics {
            let names: Vec<crate::ast::Name> = path
                .iter()
                .map(|text| crate::ast::Name {
                    text: text.clone(),
                    span: at,
                })
                .collect();
            if let Type::Yog(group) = self.qualified(&names, at)
                && super::surface::SURFACE
                    .groups
                    .get(&group)
                    .is_some_and(|g| g.methods.contains_key(name))
            {
                return self.yog_methods(&group, name, at);
            }
        }
        // Nothing of that name: a method of the game's class a `.yns`
        // reaches through `this` can't be told apart without its classes.
        let game_this = matches!(self.this, Some(Type::Game(_)));
        if !(self.nanites || game_this) {
            self.report.error(
                script_problem::UNKNOWN_MEMBER,
                at,
                format!("no method `{name}` here (another file's are its own: a type's are reached through it)"),
            );
        }
        Callee::Unknown
    }

    /// Group `group`'s methods `name`: each one's parameters and answer.
    pub(super) fn yog_methods(&mut self, group: &str, name: &str, at: Span) -> Callee {
        let surface = &*super::surface::SURFACE;
        let Some(g) = surface.groups.get(group) else {
            return Callee::Unknown;
        };
        let Some(methods) = g.methods.get(name) else {
            self.unknown_member(&Type::Yog(group.to_string()), name, at);
            return Callee::Unknown;
        };
        if !self.to_server
            && methods
                .iter()
                .any(|m| m.address == yog_ids::service_net::SEND_TO_SERVER)
        {
            self.report.error(
                script_problem::UNDECLARED,
                at,
                "this mod sends to the server without saying so: `[network]` `to_server = true` in yog.toml (it then needs Yog on the server too)",
            );
        }
        Callee::Typed(
            methods
                .iter()
                .map(|m| Signature {
                    params: m
                        .params
                        .iter()
                        .map(|p| Type::of_shape(&(p.shape)()))
                        .collect(),
                    passes: vec![None; m.params.len()],
                    required: m.params.iter().take_while(|p| p.required).count(),
                    ret: Type::of_shape(&m.reply),
                    generics: Vec::new(),
                    bound: Default::default(),
                    rest: false,
                })
                .collect(),
        )
    }

    pub(super) fn game_methods(&mut self, class: &str, name: &str, at: Span) -> Callee {
        let Some(lookup) = &self.lookup else {
            return Callee::Unknown;
        };
        let Some(c) = lookup.class(class) else {
            return Callee::Unknown;
        };
        match game::member(lookup, c, name, true) {
            Found::Methods(sigs) => Callee::Typed(
                sigs.into_iter()
                    .map(|(params, ret)| Signature {
                        passes: vec![None; params.len()],
                        required: params.len(),
                        params,
                        ret,
                        generics: Vec::new(),
                        bound: Default::default(),
                        rest: false,
                    })
                    .collect(),
            ),
            Found::Nothing => {
                self.unknown_member(&Type::Game(class.to_string()), name, at);
                Callee::Unknown
            }
            _ => Callee::Unknown,
        }
    }
}

/// `x.Client` / `x.Server`: a call on the other side (`ys-grammar.md`
/// §3.6), which every object has.
pub(super) fn is_side_call(name: &str) -> bool {
    [&crate::words::client::WORD, &crate::words::server::WORD]
        .iter()
        .any(|w| yog_codegen::pascal(w.text) == name)
}

/// What a delegate's call is matched against: every parameter required.
fn signature_of(params: &[Type], ret: &Type) -> Signature {
    Signature {
        params: params.to_vec(),
        passes: vec![None; params.len()],
        required: params.len(),
        ret: ret.clone(),
        generics: Vec::new(),
        bound: Default::default(),
        rest: false,
    }
}

/// An own type's type arguments (none for any other type).
pub(super) fn own_args(t: &Type) -> &[Type] {
    match t {
        Type::Own(_, args) | Type::Static(_, args) => args,
        _ => &[],
    }
}

impl Checker<'_, '_, '_> {
    /// Methods that bind no type parameters (the file's, an extension's),
    /// read where the code is.
    fn unbound(&self, methods: &[Method]) -> Vec<(Method, Context)> {
        let here = self.here();
        methods.iter().map(|m| (m.clone(), here.clone())).collect()
    }
}

impl Checker<'_, '_, '_> {
    /// A built-in type's members' declaration: its type in `System`
    /// (`string`'s `String`, `[Host]`), when the library declares one.
    pub(super) fn hosted(&self, t: &Type) -> Option<Type> {
        // An `ItemId`: a `ContentId<ItemId>`'s (`Yog`'s).
        if let Type::Content(_) = t {
            let of = yog_script_ids::system::CONTENT_ID.to_string();
            return Some(Type::Own(of, vec![t.clone()]));
        }
        // A tag's id: a `TagId<ItemId>`'s, its `ContentId`'s members.
        if let Type::Tag(kind) = t {
            let of = yog_script_ids::system::TAG_ID.to_string();
            return Some(Type::Own(of, vec![Type::Content(kind.clone())]));
        }
        let name = match t {
            Type::Array(..) => yog_script_ids::system::ARRAY,
            _ => super::builtin::system_name(t)?,
        };
        // A built-in type the library gives no members of its own has
        // `object`'s.
        [name, yog_script_ids::clr::OBJECT]
            .into_iter()
            .find(|n| {
                self.own
                    .namespaces
                    .get(*n)
                    .is_some_and(|ns| *ns == [yog_script_ids::system::ROOT])
            })
            .map(|n| Type::own(n.to_string()))
    }
}

impl Checker<'_, '_, '_> {
    /// `on.name(…)` that `on`'s type doesn't declare: the extension methods
    /// of the name in reach (C#'s: an instance method comes first), or a
    /// report (when `on`'s type is known).
    pub(super) fn extension_or_unknown(&mut self, on: &Type, name: &crate::ast::Name) -> Callee {
        let methods: Vec<(Method, Context)> = self
            .own
            .extension_methods
            .get(&name.text)
            .into_iter()
            .flatten()
            .filter(|(key, _)| self.own_in_reach(&key.name))
            .map(|(key, m)| (m.clone(), self.context_of(&key.name, &[])))
            .collect();
        if !methods.is_empty() {
            return Callee::Extension(methods);
        }
        if on.known() {
            self.unknown_member(on, &name.text, name.span);
        }
        Callee::Unknown
    }
}

impl Checker<'_, '_, '_> {
    /// Own type `of` named for its statics, with the arguments written (or
    /// its parameters, none written: `Comparer.Create` is `Comparer<T>`'s).
    pub(super) fn statics_type(&self, of: &str, args: &[Type]) -> Type {
        if !args.is_empty() {
            return Type::Own(of.to_string(), args.to_vec());
        }
        let params = self
            .own
            .named(of)
            .map(|(_, t)| t.generics.iter().map(|g| Type::Param(g.clone())).collect())
            .unwrap_or_default();
        Type::Own(of.to_string(), params)
    }
}