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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
//! Declaration model: [`KtFile`] → [`KtDecl`] (classes, functions,
//! properties, type aliases, raw blocks). Chained builders throughout.
//! Rendering lives in [`super::render`]; this module is pure data.

use super::{code::KtCode, slot::KtPropertyValue, types::KtType};

/// Visibility modifier. `Public` renders explicitly (matching the existing
/// generated style); `Default` renders nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum KtVis {
    #[default]
    Default,
    Public,
    Internal,
    Private,
}

impl KtVis {
    pub(crate) fn prefix(self) -> &'static str {
        match self {
            KtVis::Default => "",
            KtVis::Public => "public ",
            KtVis::Internal => "internal ",
            KtVis::Private => "private ",
        }
    }
}

/// One Kotlin source file fragment: a package plus top-level declarations.
/// Fragments of the same package are merged by [`super::file::merge_files`].
#[derive(Clone, Debug)]
pub struct KtFile {
    pub package: String,
    pub decls: Vec<KtDecl>,
    /// FQNs referenced only inside raw text the model can't see (e.g. body
    /// strings built with pre-shortened type names). Registered into the
    /// file's import set before any declaration renders.
    pub extra_imports: Vec<String>,
    /// Override the banner line prepended to the rendered file.
    /// `None` uses the default banner constant from the renderer. `Some("")` suppresses it.
    pub banner: Option<String>,
}

impl KtFile {
    pub fn new(package: impl Into<String>) -> Self {
        Self {
            package: package.into(),
            decls: Vec::new(),
            extra_imports: Vec::new(),
            banner: None,
        }
    }

    /// Override the banner comment prepended to the rendered file.
    /// Pass `""` to suppress the banner entirely.
    pub fn banner(mut self, text: impl Into<String>) -> Self {
        self.banner = Some(text.into());
        self
    }

    pub fn decl(mut self, d: impl Into<KtDecl>) -> Self {
        self.decls.push(d.into());
        self
    }

    /// Register an FQN referenced only inside raw text.
    pub fn import(mut self, fqn: impl Into<String>) -> Self {
        self.extra_imports.push(fqn.into());
        self
    }

    pub fn imports(mut self, fqns: impl IntoIterator<Item = String>) -> Self {
        self.extra_imports.extend(fqns);
        self
    }
}

/// A top-level (or member-level, for `Raw`) declaration.
#[derive(Clone, Debug)]
pub enum KtDecl {
    Class(KtClass),
    Fun(KtFun),
    FunInterface(KtFunInterface),
    Property(KtProperty),
    TypeAlias {
        vis: KtVis,
        name: String,
        target: KtType,
    },
    /// Pre-rendered code at declaration position. `name` is the identity
    /// used for duplicate detection during merge.
    Raw {
        name: String,
        code: KtCode,
    },
}

impl KtDecl {
    /// Identity for duplicate detection within a merged package.
    pub fn name(&self) -> &str {
        match self {
            KtDecl::Class(c) => &c.name,
            KtDecl::Fun(f) => &f.name,
            KtDecl::FunInterface(i) => &i.name,
            KtDecl::Property(p) => &p.name,
            KtDecl::TypeAlias { name, .. } => name,
            KtDecl::Raw { name, .. } => name,
        }
    }
}

impl From<KtClass> for KtDecl {
    fn from(c: KtClass) -> Self {
        KtDecl::Class(c)
    }
}
impl From<KtFunInterface> for KtDecl {
    fn from(i: KtFunInterface) -> Self {
        KtDecl::FunInterface(i)
    }
}
impl From<KtFun> for KtDecl {
    fn from(f: KtFun) -> Self {
        KtDecl::Fun(f)
    }
}
impl From<KtProperty> for KtDecl {
    fn from(p: KtProperty) -> Self {
        KtDecl::Property(p)
    }
}

/// A function *signature*: everything a [`KtFun`] has except a body and
/// modifiers.
///
/// This is what an abstract member is — a `fun interface`'s single method, an
/// interface member, an abstract class member. Having no body field at all is
/// what makes a bodied SAM method unrepresentable: a `fun interface` whose one
/// method has a body has no abstract method, and does not compile.
///
/// Converts into [`KtFun`] (with [`KtBody::None`]) and so into [`KtDecl`], for
/// use as an interface member; [`KtFun::signature`] goes the other way.
#[derive(Clone, Debug)]
pub struct KtFunSig {
    pub name: String,
    pub vis: KtVis,
    pub annotations: Vec<String>,
    pub kdoc: Option<String>,
    /// Generic type-variable names: `["R"]` → `fun <R> …`.
    pub generics: Vec<String>,
    /// Extension receiver: `Some(Foo)` → `fun Foo.name(…)`. A separate field
    /// rather than part of `name`, so `name` stays a plain identifier that can
    /// be checked as one.
    pub receiver: Option<KtType>,
    pub params: Vec<KtParam>,
    pub ret: Option<KtType>,
}

impl KtFunSig {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            vis: KtVis::Default,
            annotations: Vec::new(),
            kdoc: None,
            generics: Vec::new(),
            receiver: None,
            params: Vec::new(),
            ret: None,
        }
    }
    pub fn vis(mut self, v: KtVis) -> Self {
        self.vis = v;
        self
    }
    /// Make this an extension function on `ty`: `fun <R> Foo<R>.name(…)`.
    pub fn receiver(mut self, ty: KtType) -> Self {
        self.receiver = Some(ty);
        self
    }
    pub fn annotation(mut self, a: impl Into<String>) -> Self {
        self.annotations.push(a.into());
        self
    }
    pub fn kdoc(mut self, d: impl Into<String>) -> Self {
        self.kdoc = Some(d.into());
        self
    }
    pub fn generic(mut self, g: impl Into<String>) -> Self {
        self.generics.push(g.into());
        self
    }
    pub fn param(mut self, p: KtParam) -> Self {
        self.params.push(p);
        self
    }
    pub fn returns(mut self, ty: KtType) -> Self {
        self.ret = Some(ty);
        self
    }
}

impl From<KtFunSig> for KtFun {
    /// A signature as a body-less function — an abstract member.
    fn from(s: KtFunSig) -> Self {
        KtFun {
            name: s.name,
            vis: s.vis,
            modifiers: Vec::new(),
            annotations: s.annotations,
            kdoc: s.kdoc,
            generics: s.generics,
            receiver: s.receiver,
            params: s.params,
            ret: s.ret,
            body: KtBody::None,
        }
    }
}

impl From<KtFunSig> for KtDecl {
    fn from(s: KtFunSig) -> Self {
        KtDecl::Fun(s.into())
    }
}

/// A `fun interface` (SAM) declaration: exactly one abstract method.
///
/// The method is a [`KtFunSig`], so it cannot carry a body; its JNI-callable
/// JVM name is the method's `name` verbatim — keep the interface and the
/// method `public` and its params free of `@JvmInline` value classes, or
/// Kotlin mangles the JVM method name and native `GetMethodID` fails at
/// runtime.
#[derive(Clone, Debug)]
pub struct KtFunInterface {
    pub vis: KtVis,
    pub name: String,
    /// Type parameters with variance as written, e.g. `["out R"]`.
    pub type_params: Vec<String>,
    pub kdoc: Option<String>,
    /// The single abstract method.
    pub method: KtFunSig,
}

impl KtFunInterface {
    pub fn new(name: impl Into<String>, method: KtFunSig) -> Self {
        Self {
            vis: KtVis::Default,
            name: name.into(),
            type_params: Vec::new(),
            kdoc: None,
            method,
        }
    }
    pub fn vis(mut self, v: KtVis) -> Self {
        self.vis = v;
        self
    }
    pub fn type_param(mut self, p: impl Into<String>) -> Self {
        self.type_params.push(p.into());
        self
    }
    pub fn kdoc(mut self, d: impl Into<String>) -> Self {
        self.kdoc = Some(d.into());
        self
    }
}

/// The modifier a `class` carries, if any.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KtClassModifier {
    Abstract,
    Open,
    Sealed,
}

/// The kind of class-like declaration, carrying whatever that kind — and only
/// that kind — can hold.
///
/// Primary-constructor parameters live here rather than on [`KtClass`] so the
/// shapes Kotlin rejects cannot be built at all: an `object` has no field to
/// put them in, a `value class` holds exactly one, and a `data class` is
/// constructed with at least one.
#[derive(Clone, Debug)]
pub enum KtClassKind {
    /// `class` / `abstract class` / `open class` / `sealed class`.
    Class {
        modifier: Option<KtClassModifier>,
        ctor: Vec<KtCtorParam>,
    },
    /// `data class` — Kotlin requires at least one constructor property, which
    /// [`KtClass::data`] takes.
    Data {
        ctor: Vec<KtCtorParam>,
    },
    /// `@JvmInline value class` (the annotation is added by the renderer) —
    /// exactly one property.
    Value {
        field: Box<KtCtorParam>,
    },
    /// `enum class` with its entries and an optional primary constructor the
    /// entries pass arguments to.
    Enum {
        ctor: Vec<KtCtorParam>,
        entries: Vec<KtEnumEntry>,
    },
    Object,
    /// A plain `interface` — members with no body render as abstract
    /// signatures.
    Interface,
    /// A `sealed interface` — an exhaustive set of alternatives whose
    /// implementations are nested inside it as [`Self::Data`] classes and
    /// [`Self::DataObject`]s.
    SealedInterface,
    /// A `data object` — the singleton counterpart of a `data class`, for an
    /// alternative that carries no payload.
    DataObject,
}

impl KtClassKind {
    /// The primary-constructor parameters this kind carries — empty for the
    /// kinds that have no primary constructor.
    pub fn ctor_params(&self) -> &[KtCtorParam] {
        match self {
            KtClassKind::Class { ctor, .. }
            | KtClassKind::Data { ctor }
            | KtClassKind::Enum { ctor, .. } => ctor,
            KtClassKind::Value { field } => std::slice::from_ref(field),
            KtClassKind::Object
            | KtClassKind::Interface
            | KtClassKind::SealedInterface
            | KtClassKind::DataObject => &[],
        }
    }

    /// The entries of an `enum class`; empty for every other kind.
    pub fn entries(&self) -> &[KtEnumEntry] {
        match self {
            KtClassKind::Enum { entries, .. } => entries,
            _ => &[],
        }
    }

    /// The Kotlin keyword(s) introducing this kind.
    pub(crate) fn keyword(&self) -> &'static str {
        match self {
            KtClassKind::Class { modifier: None, .. } => "class",
            KtClassKind::Class {
                modifier: Some(KtClassModifier::Abstract),
                ..
            } => "abstract class",
            KtClassKind::Class {
                modifier: Some(KtClassModifier::Open),
                ..
            } => "open class",
            KtClassKind::Class {
                modifier: Some(KtClassModifier::Sealed),
                ..
            } => "sealed class",
            KtClassKind::Data { .. } => "data class",
            KtClassKind::Enum { .. } => "enum class",
            KtClassKind::Value { .. } => "value class",
            KtClassKind::Object => "object",
            KtClassKind::Interface => "interface",
            KtClassKind::SealedInterface => "sealed interface",
            KtClassKind::DataObject => "data object",
        }
    }
}

#[derive(Clone, Debug)]
pub struct KtEnumEntry {
    pub name: String,
    /// Constructor arguments as raw Kotlin text: `NAME(0)`.
    pub args: Option<KtCode>,
}

impl KtEnumEntry {
    /// An entry with no constructor arguments.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            args: None,
        }
    }
    /// An entry with constructor arguments as raw Kotlin text.
    pub fn with_args(name: impl Into<String>, args: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            args: Some(KtCode::new().line(args.into())),
        }
    }
}

/// Primary-constructor parameter, optionally a `val`/`var` property.
#[derive(Clone, Debug)]
pub struct KtCtorParam {
    pub name: String,
    pub ty: KtType,
    /// `None` = plain ctor param; `Some(false)` = `val`, `Some(true)` = `var`.
    pub prop: Option<bool>,
    /// Render the `override` modifier (`override val id: Long`) — the
    /// property implements an abstract of a supertype interface.
    pub overrides: bool,
    pub vis: KtVis,
    pub default: Option<KtCode>,
    pub annotations: Vec<String>,
}

impl KtCtorParam {
    pub fn new(name: impl Into<String>, ty: KtType) -> Self {
        Self {
            name: name.into(),
            ty,
            prop: None,
            overrides: false,
            vis: KtVis::Default,
            default: None,
            annotations: Vec::new(),
        }
    }
    pub fn val(mut self) -> Self {
        self.prop = Some(false);
        self
    }
    /// Mark the property as overriding a supertype-interface abstract.
    pub fn overrides(mut self) -> Self {
        self.overrides = true;
        self
    }
    pub fn var(mut self) -> Self {
        self.prop = Some(true);
        self
    }
    pub fn vis(mut self, v: KtVis) -> Self {
        self.vis = v;
        self
    }
    pub fn default(mut self, d: impl Into<String>) -> Self {
        self.default = Some(KtCode::new().line(d.into()));
        self
    }
    pub fn annotation(mut self, a: impl Into<String>) -> Self {
        self.annotations.push(a.into());
        self
    }
}

/// The one superclass a class may construct: `: NativeHandle(initialPtr)`.
#[derive(Clone, Debug)]
pub struct KtSuperclass {
    pub ty: KtType,
    /// Constructor arguments. `None` renders a bare `: NativeHandle`, which is
    /// what a subclass with no primary constructor writes — it delegates from
    /// its secondary constructors instead.
    pub args: Option<KtCode>,
}

/// What a class extends and implements.
///
/// Kotlin lets a class construct **at most one** superclass and implement any
/// number of interfaces. Keeping those apart — rather than in one list where
/// any element may carry constructor arguments — makes `class A : B(x), C(y)`
/// unrepresentable.
#[derive(Clone, Debug, Default)]
pub struct KtSupertypes {
    pub superclass: Option<KtSuperclass>,
    /// Implemented interfaces; never constructed.
    pub interfaces: Vec<KtType>,
}

impl KtSupertypes {
    /// Every supertype in render order: the superclass first, then interfaces.
    pub fn iter(&self) -> impl Iterator<Item = (&KtType, Option<&KtCode>)> {
        self.superclass
            .iter()
            .map(|s| (&s.ty, s.args.as_ref()))
            .chain(self.interfaces.iter().map(|t| (t, None)))
    }

    pub fn is_empty(&self) -> bool {
        self.superclass.is_none() && self.interfaces.is_empty()
    }

    /// # Panics
    ///
    /// If a superclass is already set. Kotlin permits at most one, so a second
    /// call is a generator bug — and silently replacing the first would lose a
    /// supertype the caller meant to keep.
    fn set_superclass(&mut self, ty: KtType, args: Option<&str>, what: &str) {
        if let Some(existing) = &self.superclass {
            panic!(
                "{what} already extends `{}`; Kotlin allows only one superclass \
                 (use `implements` for interfaces)",
                existing.ty
            );
        }
        self.superclass = Some(KtSuperclass {
            ty,
            args: args.map(|s| KtCode::new().line(s.to_string())),
        });
    }
}

/// A `companion object`.
///
/// Its own type rather than a [`KtClassKind`] variant, because a companion is
/// only meaningful inside a class body: reachable solely as
/// [`KtClass::companion`], it cannot be built as a top-level declaration.
///
/// A companion has no primary constructor, so — unlike the [`KtClass`] it used
/// to borrow its shape from — there is nowhere to put constructor parameters.
///
/// There is no `impl Into<KtDecl>`, so a companion cannot reach a declaration
/// position at all:
///
/// ```compile_fail
/// use kotlin_codegen::{KtCompanion, KtFile};
/// // `companion object` is meaningless at file level — and unbuildable.
/// let _ = KtFile::new("io.p").decl(KtCompanion::new());
/// ```
#[derive(Clone, Debug, Default)]
pub struct KtCompanion {
    /// `None` renders the anonymous form `companion object { … }` (Kotlin names
    /// it `Companion` implicitly). `Some(n)` renders `companion object n { … }`,
    /// which an emitter needs when the implicit `Companion` would collide with
    /// a sibling declaration.
    pub name: Option<String>,
    pub vis: KtVis,
    pub kdoc: Option<String>,
    pub annotations: Vec<String>,
    /// What the companion extends and implements.
    pub supertypes: KtSupertypes,
    pub members: Vec<KtDecl>,
}

impl KtCompanion {
    /// An anonymous `companion object`.
    pub fn new() -> Self {
        Self::default()
    }
    /// A named `companion object Factory { … }`.
    ///
    /// # Panics
    ///
    /// On an empty name, which would render as `companion object ` with a
    /// dangling space. [`KtCompanion::new`] is the anonymous form.
    pub fn named(name: impl Into<String>) -> Self {
        let name = name.into();
        assert!(
            !name.is_empty(),
            "a companion object's name cannot be empty — use `KtCompanion::new()` \
             for the anonymous form"
        );
        Self {
            name: Some(name),
            ..Self::default()
        }
    }
    pub fn vis(mut self, v: KtVis) -> Self {
        self.vis = v;
        self
    }
    pub fn kdoc(mut self, d: impl Into<String>) -> Self {
        self.kdoc = Some(d.into());
        self
    }
    pub fn annotation(mut self, a: impl Into<String>) -> Self {
        self.annotations.push(a.into());
        self
    }
    /// Set the one superclass this companion extends. Kotlin allows a
    /// companion object to extend a class, the same as any other object.
    ///
    /// # Panics
    ///
    /// If a superclass is already set — see [`KtClass::extends`].
    pub fn extends(mut self, ty: KtType, args: Option<&str>) -> Self {
        self.supertypes.set_superclass(ty, args, "companion object");
        self
    }

    /// Implement an interface.
    pub fn implements(mut self, ty: KtType) -> Self {
        self.supertypes.interfaces.push(ty);
        self
    }
    pub fn member(mut self, d: impl Into<KtDecl>) -> Self {
        self.members.push(d.into());
        self
    }
}

fn describe_prop(prop: Option<bool>) -> &'static str {
    match prop {
        None => "a plain constructor parameter",
        Some(false) => "a `val`",
        Some(true) => "a `var`",
    }
}

/// Every primary-constructor parameter of a `data class` must be a property.
fn assert_data_property(p: &KtCtorParam) {
    assert!(
        p.prop.is_some(),
        "every `data class` constructor parameter must be a property, but `{}` is {} — \
         call `.val()` or `.var()` on it",
        p.name,
        describe_prop(p.prop),
    );
}

/// A class / object / enum / data / value-class declaration.
#[derive(Clone, Debug)]
pub struct KtClass {
    /// The kind, carrying this kind's primary constructor and enum entries.
    pub kind: KtClassKind,
    pub name: String,
    pub vis: KtVis,
    pub annotations: Vec<String>,
    pub kdoc: Option<String>,
    /// What the class extends and implements.
    pub supertypes: KtSupertypes,
    pub members: Vec<KtDecl>,
    /// Boxed to keep [`KtClass`] — and so `KtDecl::Class`, the largest
    /// variant of an enum whose others are half the size — from carrying a
    /// companion's 232 bytes inline in every class that has none.
    pub companion: Option<Box<KtCompanion>>,
}

impl KtClass {
    pub fn new(kind: KtClassKind, name: impl Into<String>) -> Self {
        Self {
            kind,
            name: name.into(),
            vis: KtVis::Default,
            annotations: Vec::new(),
            kdoc: None,
            supertypes: KtSupertypes::default(),
            members: Vec::new(),
            companion: None,
        }
    }

    /// A plain `class` with no primary-constructor parameters yet — add them
    /// with [`KtClass::ctor_param`].
    pub fn class_(name: impl Into<String>) -> Self {
        Self::new(
            KtClassKind::Class {
                modifier: None,
                ctor: Vec::new(),
            },
            name,
        )
    }
    /// A `class` carrying `abstract` / `open` / `sealed`.
    pub fn class_with(modifier: KtClassModifier, name: impl Into<String>) -> Self {
        Self::new(
            KtClassKind::Class {
                modifier: Some(modifier),
                ctor: Vec::new(),
            },
            name,
        )
    }
    /// A `data class`. Kotlin requires at least one constructor property, so
    /// the first is mandatory here; add more with [`KtClass::ctor_param`].
    ///
    /// # Panics
    ///
    /// If `first` is not a `val`/`var`. Every primary-constructor parameter of
    /// a `data class` must be a property — a plain parameter is a compile
    /// error, not a stylistic choice.
    pub fn data(name: impl Into<String>, first: KtCtorParam) -> Self {
        assert_data_property(&first);
        Self::new(KtClassKind::Data { ctor: vec![first] }, name)
    }
    /// A `@JvmInline value class` wrapping exactly one property.
    ///
    /// # Panics
    ///
    /// If `field` is not a `val`. A value class wraps a single *read-only*
    /// property; `var` and plain parameters are both rejected by Kotlin.
    pub fn value(name: impl Into<String>, field: KtCtorParam) -> Self {
        assert!(
            field.prop == Some(false),
            "`value class` wraps a single read-only property, but `{}` is {} — \
             call `.val()` on it",
            field.name,
            describe_prop(field.prop),
        );
        Self::new(
            KtClassKind::Value {
                field: Box::new(field),
            },
            name,
        )
    }
    /// An `enum class` with no entries yet — add them with [`KtClass::entry`].
    pub fn enum_(name: impl Into<String>) -> Self {
        Self::new(
            KtClassKind::Enum {
                ctor: Vec::new(),
                entries: Vec::new(),
            },
            name,
        )
    }
    pub fn object_(name: impl Into<String>) -> Self {
        Self::new(KtClassKind::Object, name)
    }
    pub fn data_object(name: impl Into<String>) -> Self {
        Self::new(KtClassKind::DataObject, name)
    }
    pub fn interface_(name: impl Into<String>) -> Self {
        Self::new(KtClassKind::Interface, name)
    }
    pub fn sealed_interface(name: impl Into<String>) -> Self {
        Self::new(KtClassKind::SealedInterface, name)
    }
    /// The primary-constructor parameters, whichever kind holds them.
    pub fn ctor_params(&self) -> &[KtCtorParam] {
        self.kind.ctor_params()
    }

    pub fn vis(mut self, v: KtVis) -> Self {
        self.vis = v;
        self
    }
    pub fn annotation(mut self, a: impl Into<String>) -> Self {
        self.annotations.push(a.into());
        self
    }
    pub fn kdoc(mut self, d: impl Into<String>) -> Self {
        self.kdoc = Some(d.into());
        self
    }
    /// Append a primary-constructor parameter.
    ///
    /// # Panics
    ///
    /// If this kind has no primary constructor (`object`, `data object`,
    /// `interface`, `sealed interface`) or holds a fixed
    /// number of parameters (`value class` — pass its one property to
    /// [`KtClass::value`]). Both are generator bugs that would otherwise
    /// render as Kotlin that does not compile.
    pub fn ctor_param(mut self, p: KtCtorParam) -> Self {
        if matches!(self.kind, KtClassKind::Data { .. }) {
            assert_data_property(&p);
        }
        match &mut self.kind {
            KtClassKind::Class { ctor, .. }
            | KtClassKind::Data { ctor }
            | KtClassKind::Enum { ctor, .. } => ctor.push(p),
            other => panic!(
                "`{}` has no primary constructor to add parameter `{}` to",
                other.keyword(),
                p.name
            ),
        }
        self
    }

    /// Append an entry to an `enum class`.
    ///
    /// # Panics
    ///
    /// If this kind is not [`KtClassKind::Enum`].
    pub fn entry(mut self, e: KtEnumEntry) -> Self {
        match &mut self.kind {
            KtClassKind::Enum { entries, .. } => entries.push(e),
            other => panic!(
                "`{}` is not an enum class; cannot add entry `{}`",
                other.keyword(),
                e.name
            ),
        }
        self
    }
    /// Set the one superclass this class constructs: `: NativeHandle(args)`.
    /// `args` of `None` renders a bare `: NativeHandle`.
    ///
    /// # Panics
    ///
    /// If a superclass is already set. Kotlin permits at most one, so a second
    /// call is a generator bug — and silently replacing the first would lose a
    /// supertype the caller meant to keep.
    pub fn extends(mut self, ty: KtType, args: Option<&str>) -> Self {
        let what = format!("class `{}`", self.name);
        self.supertypes.set_superclass(ty, args, &what);
        self
    }

    /// Implement an interface. Any number are allowed.
    pub fn implements(mut self, ty: KtType) -> Self {
        self.supertypes.interfaces.push(ty);
        self
    }
    pub fn member(mut self, d: impl Into<KtDecl>) -> Self {
        self.members.push(d.into());
        self
    }
    pub fn companion(mut self, c: KtCompanion) -> Self {
        self.companion = Some(Box::new(c));
        self
    }
}

/// A function body — or the reason there isn't one.
#[derive(Clone, Debug, Default)]
pub enum KtBody {
    /// No body because the function is abstract. Whether that is legal is
    /// *positional* — an `interface` member needs no keyword, an abstract
    /// class member does — which no type here can capture, so this one stays
    /// a validated case rather than a guaranteed one.
    #[default]
    None,
    /// Single-expression body: `= <expr>`.
    Expr(KtCode),
    /// Block body: `{ … }`.
    Block(KtCode),
    /// `external fun f()` — implemented natively, so no body *by definition*.
    /// Being a body variant rather than a modifier keyword is what makes
    /// `external fun f() { … }` unrepresentable.
    External,
}

/// A function declaration (top-level or member).
#[derive(Clone, Debug)]
pub struct KtFun {
    pub name: String,
    pub vis: KtVis,
    /// Modifier keywords in render order, e.g. `external`, `inline`,
    /// `override`, `abstract`, `operator`.
    pub modifiers: Vec<String>,
    pub annotations: Vec<String>,
    pub kdoc: Option<String>,
    /// Generic type-variable names: `["R"]` → `fun <R> …`.
    pub generics: Vec<String>,
    /// Extension receiver: `Some(Foo)` → `fun Foo.name(…)`. See
    /// [`KtFunSig::receiver`].
    pub receiver: Option<KtType>,
    pub params: Vec<KtParam>,
    pub ret: Option<KtType>,
    pub body: KtBody,
}

impl KtFun {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            vis: KtVis::Default,
            modifiers: Vec::new(),
            annotations: Vec::new(),
            kdoc: None,
            generics: Vec::new(),
            receiver: None,
            params: Vec::new(),
            ret: None,
            body: KtBody::None,
        }
    }

    pub fn vis(mut self, v: KtVis) -> Self {
        self.vis = v;
        self
    }
    /// Make this an extension function on `ty`: `fun <R> Foo<R>.name(…)`.
    pub fn receiver(mut self, ty: KtType) -> Self {
        self.receiver = Some(ty);
        self
    }
    /// Add a modifier keyword (`override`, `inline`, `operator`, …).
    ///
    /// # Panics
    ///
    /// On `"external"` — it is a body kind, not a modifier, so that it cannot
    /// be combined with one. Use [`KtFun::external`].
    pub fn modifier(mut self, m: impl Into<String>) -> Self {
        let m = m.into();
        // A modifier string may hold several keywords ("final override"), so
        // check each word — `"external "` and `"external inline"` would
        // otherwise render the keyword and reopen the hole this closes.
        assert!(
            !m.split_whitespace().any(|w| w == "external"),
            "`external` is not a modifier here — use `KtFun::external()`, which \
             also rules out giving the function a body"
        );
        self.modifiers.push(m);
        self
    }
    pub fn annotation(mut self, a: impl Into<String>) -> Self {
        self.annotations.push(a.into());
        self
    }
    pub fn kdoc(mut self, d: impl Into<String>) -> Self {
        self.kdoc = Some(d.into());
        self
    }
    pub fn generic(mut self, g: impl Into<String>) -> Self {
        self.generics.push(g.into());
        self
    }
    pub fn param(mut self, p: KtParam) -> Self {
        self.params.push(p);
        self
    }
    pub fn returns(mut self, ty: KtType) -> Self {
        self.ret = Some(ty);
        self
    }
    pub fn body(mut self, c: KtCode) -> Self {
        self.body = KtBody::Block(c);
        self
    }
    pub fn expr_body(mut self, c: KtCode) -> Self {
        self.body = KtBody::Expr(c);
        self
    }
    /// `external fun f()` — natively implemented, and so bodiless.
    pub fn external(mut self) -> Self {
        self.body = KtBody::External;
        self
    }

    /// This function's signature: same name, generics, receiver, parameters and
    /// return type, with the body and modifiers dropped. What a concrete member
    /// looks like as an interface abstract.
    pub fn signature(&self) -> KtFunSig {
        KtFunSig {
            name: self.name.clone(),
            vis: self.vis,
            annotations: self.annotations.clone(),
            kdoc: self.kdoc.clone(),
            generics: self.generics.clone(),
            receiver: self.receiver.clone(),
            params: self.params.clone(),
            ret: self.ret.clone(),
        }
    }
}

/// A function parameter with an optional default-value expression.
#[derive(Clone, Debug)]
pub struct KtParam {
    pub name: String,
    pub ty: KtType,
    pub default: Option<KtCode>,
}

impl KtParam {
    pub fn new(name: impl Into<String>, ty: KtType) -> Self {
        Self {
            name: name.into(),
            ty,
            default: None,
        }
    }
    pub fn default(mut self, d: impl Into<String>) -> Self {
        self.default = Some(KtCode::new().line(d.into()));
        self
    }
}

/// A property declaration (top-level or member).
#[derive(Clone, Debug)]
pub struct KtProperty {
    pub name: String,
    pub ty: Option<KtType>,
    /// The initializer or the delegate — **never both**. The exclusion used to
    /// be two `Option<String>` fields plus a doc comment and a `debug_assert`;
    /// it is now a sum, so the illegal state is unrepresentable.
    pub value: KtPropertyValue,
    pub mutable: bool,
    pub vis: KtVis,
    /// Inline annotations rendered before the keyword: `@Volatile internal var …`.
    pub annotations: Vec<String>,
    /// Keyword modifiers rendered between visibility and `val`/`var`
    /// (`open`, `final override`, …).
    pub modifiers: Vec<String>,
    pub kdoc: Option<String>,
    /// Accessor code rendered after the property declaration.
    pub accessors: Option<KtCode>,
}

impl KtProperty {
    pub fn val(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ty: None,
            value: KtPropertyValue::None,
            mutable: false,
            vis: KtVis::Default,
            annotations: Vec::new(),
            modifiers: Vec::new(),
            kdoc: None,
            accessors: None,
        }
    }
    pub fn var(name: impl Into<String>) -> Self {
        Self {
            mutable: true,
            ..Self::val(name)
        }
    }
    pub fn ty(mut self, t: KtType) -> Self {
        self.ty = Some(t);
        self
    }
    pub fn initializer(mut self, i: impl Into<String>) -> Self {
        self.value = KtPropertyValue::Initializer(KtCode::new().line(i.into()));
        self
    }
    pub fn delegate(mut self, d: impl Into<String>) -> Self {
        self.value = KtPropertyValue::Delegate(KtCode::new().line(d.into()));
        self
    }
    pub fn vis(mut self, v: KtVis) -> Self {
        self.vis = v;
        self
    }
    pub fn annotation(mut self, a: impl Into<String>) -> Self {
        self.annotations.push(a.into());
        self
    }
    pub fn modifier(mut self, m: impl Into<String>) -> Self {
        self.modifiers.push(m.into());
        self
    }
    pub fn kdoc(mut self, d: impl Into<String>) -> Self {
        self.kdoc = Some(d.into());
        self
    }
    pub fn accessors(mut self, c: KtCode) -> Self {
        self.accessors = Some(c);
        self
    }
}