kotlin-codegen 0.2.0

A declaration model and renderer for generating Kotlin source code
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Checking a [`KtFile`] before it is written.
//!
//! A *program* builds the declaration model, so the mistakes are program
//! mistakes: a name derived from a Rust field that happens to be `object`, two
//! generated classes that mangle to the same name. Without a check here those
//! surface much later, when the Kotlin compiler runs — often in a different
//! build, against a generated file that gives no hint about what produced it.
//!
//! Two rules bound what belongs here:
//!
//! 1. **Only what the model proves.** No type resolution, no parsing of the raw
//!    text inside [`KtCode`](super::KtCode) bodies. Whether `io.zenoh.ZSession`
//!    exists is the compiler's question, not ours.
//! 2. **No false positives.** A check that occasionally fires on correct output
//!    is worse than no check, because the first false alarm teaches people to
//!    switch the checks off.
//!
//! Validation is a **separate read-only pass**: the model stays a plain data
//! structure, the builders stay infallible, and
//! [`render`](super::KtFile::render) stays infallible too — rendering a model
//! you already know is broken is exactly what you want while debugging a
//! generator. The checks run on the *write* path instead
//! ([`merge_files`](super::merge_files), [`write_files`](super::write_files)).

use std::collections::{BTreeMap, BTreeSet};

use super::{
    ident::{is_valid_kotlin_package, is_writable_kotlin_ident},
    model::{
        KtBody, KtClass, KtClassKind, KtClassModifier, KtCompanion, KtCtorParam, KtDecl, KtFile,
        KtFun, KtParam,
    },
    slot::KtPropertyValue,
};

/// Which check produced a [`Diagnostic`].
///
/// Consumers match on this to override a severity, so it is the stable name of
/// a check rather than its message.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Check {
    /// A declared name is not something Kotlin can write.
    InvalidIdentifier,
    /// A file's package is not a legal Kotlin package path.
    InvalidPackage,
    /// Two type declarations in one scope share a name — classes, `fun
    /// interface`s and type aliases all live in Kotlin's *classifier*
    /// namespace.
    DuplicateType,
    /// Two value declarations in one scope share a name — properties and
    /// `val`/`var` constructor parameters.
    DuplicateValue,
    /// Two functions in one scope share a name *and* a parameter type list.
    /// Same-named functions with different parameters are overloads and pass.
    DuplicateFunction,
    /// Two `Raw` blocks in one scope share a name. Identical ones are merged
    /// rather than reported (see [`merge_files`](super::merge_files)), so this
    /// means two different blocks are claiming one identity.
    DuplicateRaw,
    /// A property has no type, no value and no accessors — `val x` alone,
    /// which is never legal.
    PropertyWithoutTypeOrValue,
    /// An `enum class` declares primary-constructor parameters, but an entry
    /// passes no arguments.
    EnumEntryMissingArguments,
    /// A function has no body somewhere a bodiless function is not allowed.
    FunctionWithoutBody,
    /// Two distinct FQNs referenced from raw text share a simple name, so the
    /// text cannot be made to refer to both.
    ImportCollision,
}

impl Check {
    /// Every check, so a policy can be built over all of them. Adding a check
    /// extends this list, which is what keeps
    /// [`ValidationPolicy::warn_all`] correct as the set grows.
    pub const ALL: &'static [Check] = &[
        Check::InvalidIdentifier,
        Check::InvalidPackage,
        Check::DuplicateType,
        Check::DuplicateValue,
        Check::DuplicateFunction,
        Check::DuplicateRaw,
        Check::PropertyWithoutTypeOrValue,
        Check::EnumEntryMissingArguments,
        Check::FunctionWithoutBody,
        Check::ImportCollision,
    ];

    /// The stable, greppable name of this check.
    pub fn name(self) -> &'static str {
        match self {
            Check::InvalidIdentifier => "invalid-identifier",
            Check::InvalidPackage => "invalid-package",
            Check::DuplicateType => "duplicate-type",
            Check::DuplicateValue => "duplicate-value",
            Check::DuplicateFunction => "duplicate-function",
            Check::DuplicateRaw => "duplicate-raw",
            Check::PropertyWithoutTypeOrValue => "property-without-type-or-value",
            Check::EnumEntryMissingArguments => "enum-entry-missing-arguments",
            Check::FunctionWithoutBody => "function-without-body",
            Check::ImportCollision => "import-collision",
        }
    }
}

impl std::fmt::Display for Check {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name())
    }
}

/// How much a diagnostic matters. A [`Check`] set to neither is off.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
    /// Reported, but does not stop generation.
    Warning,
    /// Stops generation.
    Error,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Severity::Warning => "warning",
            Severity::Error => "error",
        })
    }
}

/// One problem found in a [`KtFile`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagnostic {
    pub check: Check,
    pub severity: Severity,
    /// Where the problem is, as a path through the declaration tree —
    /// `io.zenoh.jni.session/ZSession/Companion`. The model has no source
    /// positions, so this is how a diagnostic is located.
    pub scope: String,
    pub message: String,
}

impl std::fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} [{}] in `{}`: {}",
            self.severity, self.check, self.scope, self.message
        )
    }
}

/// Per-check severity, so a consumer can downgrade or disable a check instead
/// of pinning an old version of this crate when one misfires.
///
/// Every check is an error by default.
///
/// ```
/// use kotlin_codegen::{Check, Severity, ValidationPolicy};
/// let policy = ValidationPolicy::new().warn(Check::DuplicateType);
/// assert_eq!(
///     policy.severity_of(Check::DuplicateType),
///     Some(Severity::Warning)
/// );
/// ```
#[derive(Clone, Debug, Default)]
pub struct ValidationPolicy {
    /// Only the overrides; anything absent is [`Severity::Error`].
    overrides: BTreeMap<Check, Option<Severity>>,
}

impl ValidationPolicy {
    /// Every check an error.
    pub fn new() -> Self {
        Self::default()
    }

    /// Report `check` but keep generating.
    pub fn warn(mut self, check: Check) -> Self {
        self.overrides.insert(check, Some(Severity::Warning));
        self
    }

    /// Stop generating on `check` (the default).
    pub fn deny(mut self, check: Check) -> Self {
        self.overrides.insert(check, Some(Severity::Error));
        self
    }

    /// Downgrade *every* check to a warning.
    ///
    /// The way to adopt validation in a generator that already produces
    /// output: run it in warning mode first, look at what comes back, and
    /// switch to the default once it is quiet. Reaching a clean run and then
    /// dropping this call is much less disruptive than having a build start
    /// failing on output that was fine yesterday.
    ///
    /// ```
    /// use kotlin_codegen::{Check, Severity, ValidationPolicy};
    /// let policy = ValidationPolicy::warn_all();
    /// for check in Check::ALL {
    ///     assert_eq!(policy.severity_of(*check), Some(Severity::Warning));
    /// }
    /// ```
    pub fn warn_all() -> Self {
        let mut policy = Self::new();
        for check in Check::ALL {
            policy = policy.warn(*check);
        }
        policy
    }

    /// Turn `check` off entirely.
    pub fn allow(mut self, check: Check) -> Self {
        self.overrides.insert(check, None);
        self
    }

    /// The effective severity of `check`, or `None` when it is off.
    pub fn severity_of(&self, check: Check) -> Option<Severity> {
        self.overrides
            .get(&check)
            .copied()
            .unwrap_or(Some(Severity::Error))
    }
}

/// A child scope path. The root package is the empty string, so joining
/// naively would yield a leading `/` and make diagnostics inconsistent between
/// the root package and every other one.
fn scope_join(scope: &str, child: &str) -> String {
    if scope.is_empty() {
        child.to_string()
    } else {
        format!("{scope}/{child}")
    }
}

/// Collects diagnostics under the active policy, dropping the ones that are
/// switched off so no check pays for a report nobody wants.
pub(crate) struct Diagnostics<'a> {
    policy: &'a ValidationPolicy,
    out: Vec<Diagnostic>,
}

impl<'a> Diagnostics<'a> {
    pub(crate) fn new(policy: &'a ValidationPolicy) -> Self {
        Self {
            policy,
            out: Vec::new(),
        }
    }

    pub(crate) fn push(&mut self, check: Check, scope: &str, message: String) {
        if let Some(severity) = self.policy.severity_of(check) {
            self.out.push(Diagnostic {
                check,
                severity,
                scope: scope.to_string(),
                message,
            });
        }
    }

    pub(crate) fn finish(self) -> Vec<Diagnostic> {
        self.out
    }
}

impl KtFile {
    /// Every problem in this file, with each check at its default severity
    /// (error).
    ///
    /// An empty result means the file is as good as the *model* can prove:
    /// names, redeclarations and declaration shapes are checked, and [`Check`]
    /// enumerates exactly which. Anything needing type resolution, or reading
    /// the raw text inside [`KtCode`](super::KtCode) bodies, stays the Kotlin
    /// compiler's job.
    pub fn validate(&self) -> Vec<Diagnostic> {
        self.validate_with(&ValidationPolicy::new())
    }

    /// [`KtFile::validate`] with per-check severities.
    pub fn validate_with(&self, policy: &ValidationPolicy) -> Vec<Diagnostic> {
        let mut d = Diagnostics::new(policy);
        check_identifiers(self, &mut d);
        check_scope(&self.decls, &[], None, &self.package, &mut d);
        check_shapes(&self.decls, Container::File, &self.package, &mut d);
        check_extra_imports(self, &mut d);
        d.finish()
    }
}

/// The names declared in one scope must not collide — but Kotlin keeps three
/// *separate* namespaces, so what counts as a collision depends on the kind.
///
/// A scope is one declaration container: the file, a class body, a companion
/// body. Nested classes and companions are walked recursively, which is where
/// most generated declarations actually live.
///
/// | Namespace | Holds | Rule |
/// |---|---|---|
/// | types | classes, `fun interface`s, type aliases | unique by name |
/// | values | properties, `val`/`var` constructor parameters | unique by name |
/// | functions | functions | unique by name **and** parameter types |
///
/// Keeping types and values apart is what allows `class Foo` and `val Foo` to
/// coexist, which Kotlin permits and this check used to reject.
///
/// **Limitation.** There is no type resolver here, so a function's parameter
/// types — and its extension receiver — are compared *as written*: `io.p.Foo`
/// and `Foo` are different keys even when they name the same type, and
/// `fun <T> f(x: T)` does not collide with `fun <R> f(x: R)`. The check
/// therefore misses some real duplicates. It is a net, not a proof — and a net
/// that never catches a fish it shouldn't.
fn check_scope<'a>(
    decls: &'a [KtDecl],
    ctor_params: &'a [KtCtorParam],
    companion: Option<&'a KtCompanion>,
    scope: &str,
    d: &mut Diagnostics<'_>,
) {
    let mut types: BTreeSet<&str> = BTreeSet::new();
    let mut values: BTreeSet<&str> = BTreeSet::new();
    let mut funs: BTreeSet<String> = BTreeSet::new();
    let mut raws: BTreeSet<&str> = BTreeSet::new();

    // `val`/`var` constructor parameters are properties of the class, so they
    // share the value namespace with its members. A plain (non-property)
    // parameter is constructor-local and declares nothing.
    for p in ctor_params.iter().filter(|p| p.prop.is_some()) {
        if !p.name.is_empty() && !values.insert(&p.name) {
            d.push(
                Check::DuplicateValue,
                scope,
                format!("duplicate value `{}` (constructor property)", p.name),
            );
        }
    }

    for decl in decls {
        match decl {
            KtDecl::Class(c) => {
                declare_name(&mut types, &c.name, Check::DuplicateType, "type", scope, d);
                check_class_scope(c, scope, d);
            }
            KtDecl::FunInterface(i) => {
                declare_name(&mut types, &i.name, Check::DuplicateType, "type", scope, d);
            }
            KtDecl::TypeAlias { name, .. } => {
                declare_name(&mut types, name, Check::DuplicateType, "type", scope, d);
            }
            KtDecl::Property(p) => {
                declare_name(
                    &mut values,
                    &p.name,
                    Check::DuplicateValue,
                    "value",
                    scope,
                    d,
                );
            }
            KtDecl::Fun(f) => {
                if f.name.is_empty() {
                    continue;
                }
                let sig = fun_signature(f);
                if !funs.insert(sig.clone()) {
                    d.push(
                        Check::DuplicateFunction,
                        scope,
                        format!("duplicate function `{sig}`"),
                    );
                }
            }
            KtDecl::Raw { name, .. } => {
                declare_name(&mut raws, name, Check::DuplicateRaw, "raw block", scope, d);
            }
        }
    }

    // A *named* companion object is a classifier nested in this class, so its
    // name shares the type namespace with the class's other type members —
    // `class Factory` alongside `companion object Factory` is a redeclaration.
    //
    // The implicit `Companion` is deliberately left out: that name is one this
    // crate supplies rather than one the model declares, so treating it as a
    // declaration could fire on a generator that manages the collision itself
    // by renaming the companion.
    if let Some(name) = companion.and_then(|c| c.name.as_deref()) {
        if !name.is_empty() && !types.insert(name) {
            d.push(
                Check::DuplicateType,
                scope,
                format!("companion object `{name}` collides with another type of that name"),
            );
        }
    }
}

/// A function's overload identity, as it reads in a diagnostic:
/// `f(Int)`, or `Foo.f(Int)` for an extension function.
///
/// The receiver is part of the identity because Kotlin dispatches an extension
/// on it — `Foo.f()` and `Bar.f()` are two declarations in one package, not a
/// redeclaration. It is parenthesized on the same rule the renderer uses, so
/// the diagnostic reads as the syntax it is describing.
fn fun_signature(f: &KtFun) -> String {
    let params = param_signature(&f.params);
    match &f.receiver {
        Some(r) if r.needs_receiver_parens() => format!("({r}).{}({params})", f.name),
        Some(r) => format!("{r}.{}({params})", f.name),
        None => format!("{}({params})", f.name),
    }
}

/// A function's parameter types as written, which is the only signature the
/// model can offer — see the note on [`check_scope`].
fn param_signature(params: &[KtParam]) -> String {
    params
        .iter()
        .map(|p| p.ty.to_string())
        .collect::<Vec<_>>()
        .join(", ")
}

fn declare_name<'a>(
    set: &mut BTreeSet<&'a str>,
    name: &'a str,
    check: Check,
    what: &str,
    scope: &str,
    d: &mut Diagnostics<'_>,
) {
    if name.is_empty() {
        return;
    }
    if !set.insert(name) {
        d.push(check, scope, format!("duplicate {what} `{name}`"));
    }
}

/// A class body is its own scope, and so is its companion's.
fn check_class_scope(c: &KtClass, scope: &str, d: &mut Diagnostics<'_>) {
    let inner = scope_join(scope, &c.name);
    // The companion is part of this class's scope, not a member of it — its
    // name is declared here, while its body is a scope of its own.
    check_scope(
        &c.members,
        c.ctor_params(),
        c.companion.as_deref(),
        &inner,
        d,
    );
    if let Some(comp) = &c.companion {
        let cscope = scope_join(&inner, comp.name.as_deref().unwrap_or("Companion"));
        check_scope(&comp.members, &[], None, &cscope, d);
    }
}

/// Extra imports carry pre-shortened raw-text references, so a simple-name
/// collision between two distinct FQNs cannot be repaired by qualifying a use
/// site the way a modelled type's can — the raw text already says `Foo`.
///
/// Lowercase simple names are exempt: those are top-level *function* imports,
/// which Kotlin allows to overload across packages.
fn check_extra_imports(file: &KtFile, d: &mut Diagnostics<'_>) {
    let mut by_simple: BTreeMap<&str, &str> = BTreeMap::new();
    for imp in &file.extra_imports {
        let simple = imp.rsplit_once('.').map(|(_, s)| s).unwrap_or(imp.as_str());
        if simple.chars().next().is_some_and(|c| c.is_lowercase()) {
            continue;
        }
        // First registration owns the simple name — the same rule `ImportSet`
        // uses — so with three or more colliding FQNs every diagnostic points
        // at the one owner rather than at whichever was seen most recently.
        let owner = *by_simple.entry(simple).or_insert(imp.as_str());
        if owner != imp.as_str() {
            d.push(
                Check::ImportCollision,
                &file.package,
                format!("import simple-name collision: `{owner}` and `{imp}`"),
            );
        }
    }
}

/// Every name the model will write out is a legal Kotlin identifier.
///
/// Deliberately *not* checked, because they are free-form fragments rather than
/// plain identifiers and checking them would produce false positives: generic
/// parameter lists (`out R`, `T : Comparable<T>`), annotations, modifier
/// keywords, and a `Raw` block's name — that last one is a merge identity, not
/// something rendered.
fn check_identifiers(file: &KtFile, d: &mut Diagnostics<'_>) {
    if !is_valid_kotlin_package(&file.package) {
        d.push(
            Check::InvalidPackage,
            &file.package,
            format!("`{}` is not a valid Kotlin package path", file.package),
        );
    }
    for decl in &file.decls {
        check_decl_identifiers(decl, &file.package, d);
    }
}

fn check_ident(name: &str, what: &str, scope: &str, d: &mut Diagnostics<'_>) {
    if !is_writable_kotlin_ident(name) {
        d.push(
            Check::InvalidIdentifier,
            scope,
            format!("{what} name `{name}` is not a valid Kotlin identifier"),
        );
    }
}

fn check_decl_identifiers(decl: &KtDecl, scope: &str, d: &mut Diagnostics<'_>) {
    match decl {
        KtDecl::Class(c) => check_class_identifiers(c, scope, d),
        KtDecl::Fun(f) => {
            check_ident(&f.name, "function", scope, d);
            let inner = scope_join(scope, &f.name);
            for p in &f.params {
                check_ident(&p.name, "parameter", &inner, d);
            }
        }
        KtDecl::FunInterface(i) => {
            check_ident(&i.name, "fun interface", scope, d);
            let inner = scope_join(scope, &i.name);
            check_ident(&i.method.name, "function", &inner, d);
            let method = scope_join(&inner, &i.method.name);
            for p in &i.method.params {
                check_ident(&p.name, "parameter", &method, d);
            }
        }
        KtDecl::Property(p) => check_ident(&p.name, "property", scope, d),
        KtDecl::TypeAlias { name, .. } => check_ident(name, "type alias", scope, d),
        // A `Raw` block's name is its merge identity, never rendered.
        KtDecl::Raw { .. } => {}
    }
}

fn check_class_identifiers(c: &KtClass, scope: &str, d: &mut Diagnostics<'_>) {
    check_ident(&c.name, "class", scope, d);
    let inner = scope_join(scope, &c.name);
    for p in c.ctor_params() {
        check_ident(&p.name, "constructor parameter", &inner, d);
    }
    for e in c.kind.entries() {
        check_ident(&e.name, "enum entry", &inner, d);
    }
    for m in &c.members {
        check_decl_identifiers(m, &inner, d);
    }
    if let Some(comp) = &c.companion {
        if let Some(name) = &comp.name {
            check_ident(name, "companion object", &inner, d);
        }
        let cscope = scope_join(&inner, comp.name.as_deref().unwrap_or("Companion"));
        for m in &comp.members {
            check_decl_identifiers(m, &cscope, d);
        }
    }
}

/// What encloses a declaration. A bodiless function is legal or not depending
/// on where it sits, which no type in the model can capture — so this is the
/// context the shape checks need.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Container {
    /// Top level of a file.
    File,
    /// An `interface` or `sealed interface`: members without a body are
    /// abstract by position, no keyword required.
    Interface,
    /// An `abstract` or `sealed` class: a member may be abstract, but must say
    /// so.
    Abstract,
    /// Anything else — every function needs a body.
    Concrete,
}

impl Container {
    fn of(c: &KtClass) -> Self {
        match &c.kind {
            KtClassKind::Interface | KtClassKind::SealedInterface => Container::Interface,
            KtClassKind::Class {
                modifier: Some(KtClassModifier::Abstract) | Some(KtClassModifier::Sealed),
                ..
            } => Container::Abstract,
            _ => Container::Concrete,
        }
    }
}

/// The shapes that [Part A](https://github.com/milyin/kotlin-codegen/pull/6)
/// could not make unrepresentable, because each depends on a relation between
/// fields or on where a declaration sits rather than on one field's type.
fn check_shapes(decls: &[KtDecl], container: Container, scope: &str, d: &mut Diagnostics<'_>) {
    for decl in decls {
        match decl {
            KtDecl::Property(p) => {
                // Only the all-absent case is unambiguously wrong. A type alone
                // is an abstract property; a value alone infers its type.
                if p.ty.is_none()
                    && matches!(p.value, KtPropertyValue::None)
                    && p.accessors.is_none()
                {
                    d.push(
                        Check::PropertyWithoutTypeOrValue,
                        scope,
                        format!(
                            "property `{}` has no type, no value and no accessors",
                            p.name
                        ),
                    );
                }
            }
            KtDecl::Fun(f) => {
                if !matches!(f.body, KtBody::None) {
                    continue;
                }
                let allowed = match container {
                    Container::Interface => true,
                    Container::Abstract => f
                        .modifiers
                        .iter()
                        .any(|m| m.split(' ').any(|w| w == "abstract")),
                    Container::File | Container::Concrete => false,
                };
                if !allowed {
                    d.push(
                        Check::FunctionWithoutBody,
                        scope,
                        format!(
                            "function `{}` has no body; only an interface member, or an \
                             `abstract` member of an abstract class, may omit one",
                            f.name
                        ),
                    );
                }
            }
            KtDecl::Class(c) => check_class_shapes(c, scope, d),
            KtDecl::FunInterface(_) | KtDecl::TypeAlias { .. } | KtDecl::Raw { .. } => {}
        }
    }
}

fn check_class_shapes(c: &KtClass, scope: &str, d: &mut Diagnostics<'_>) {
    let inner = scope_join(scope, &c.name);
    // Every entry of an enum with a primary constructor must call it.
    if let KtClassKind::Enum { ctor, entries } = &c.kind {
        if !ctor.is_empty() {
            for e in entries.iter().filter(|e| e.args.is_none()) {
                d.push(
                    Check::EnumEntryMissingArguments,
                    &inner,
                    format!(
                        "entry `{}` passes no arguments, but the enum declares {} \
                         constructor parameter(s)",
                        e.name,
                        ctor.len()
                    ),
                );
            }
        }
    }
    check_shapes(&c.members, Container::of(c), &inner, d);
    if let Some(comp) = &c.companion {
        let cscope = scope_join(&inner, comp.name.as_deref().unwrap_or("Companion"));
        // A companion object is concrete: its members need bodies.
        check_shapes(&comp.members, Container::Concrete, &cscope, d);
    }
}