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
//! Rendering: model → formatted Kotlin source. Two passes per file —
//! declarations render into a body buffer while registering imports in an
//! [`ImportSet`], then banner / `package` / sorted imports / body are
//! assembled.

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

/// The default first line of every generated file — the "do not edit" marker
/// a reader needs to know the file is machine-written.
///
/// A file renders this line unless [`KtFile::banner`] sets one of its own, in
/// which case that text is used verbatim — and `""` suppresses the line
/// entirely. Public so a consumer prepending its own header, or recognising a
/// file as machine-written, has something to match against.
pub const KOTLIN_BANNER: &str = "// Auto-generated by kotlin-codegen — do not edit by hand.";

/// When a function's single-line signature (from the indentation through the
/// closing parenthesis and return type) would exceed this many columns, the
/// parameter list is broken onto one parameter per line. Keeps generated
/// signatures readable instead of emitting one very long line.
pub(crate) const MAX_SIGNATURE_WIDTH: usize = 100;

impl KtFile {
    /// Render the complete file: banner, package, sorted imports, then
    /// declarations in insertion order separated by blank lines.
    pub fn render(&self) -> String {
        let mut imports = ImportSet::new(&self.package);
        // Raw-text imports (file-level extras + Code-carried) register FIRST:
        // raw text already uses short names, so its imports must own them —
        // a colliding model-rendered type then falls back to its FQN.
        for fqn in &self.extra_imports {
            imports.register(fqn);
        }
        let mut raw_imports = Vec::new();
        for d in &self.decls {
            collect_decl_imports(d, &mut raw_imports);
        }
        for fqn in raw_imports {
            imports.register(&fqn);
        }
        let mut body = String::new();
        for (i, d) in self.decls.iter().enumerate() {
            if i > 0 {
                body.push('\n');
            }
            render_decl(d, 0, &mut imports, &mut body);
        }

        let mut out = String::new();
        let banner_text = self.banner.as_deref().unwrap_or(KOTLIN_BANNER);
        if !banner_text.is_empty() {
            out.push_str(banner_text);
            out.push('\n');
        }
        if !self.package.is_empty() {
            out.push_str(&format!("package {}\n", self.package));
        }
        let import_lines = imports.import_lines();
        if !import_lines.is_empty() {
            out.push('\n');
            for l in &import_lines {
                out.push_str(l);
                out.push('\n');
            }
        }
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&body);
        if !out.ends_with('\n') {
            out.push('\n');
        }
        out
    }
}

/// Render a `KtCode` value to a trimmed single-line string.
fn render_code_inline(c: &KtCode) -> String {
    let mut s = String::new();
    c.render(0, &mut s);
    s.trim_end().to_string()
}

/// Gather the imports referenced by raw `KtCode` values within a declaration.
fn collect_decl_imports(d: &KtDecl, sink: &mut Vec<String>) {
    match d {
        KtDecl::Class(c) => {
            for p in c.ctor_params() {
                if let Some(default) = &p.default {
                    default.collect_imports(sink);
                }
            }
            for (_, args) in c.supertypes.iter() {
                if let Some(args) = args {
                    args.collect_imports(sink);
                }
            }
            for e in c.kind.entries() {
                if let Some(args) = &e.args {
                    args.collect_imports(sink);
                }
            }
            for m in &c.members {
                collect_decl_imports(m, sink);
            }
            if let Some(comp) = &c.companion {
                collect_companion_imports(comp, sink);
            }
        }
        KtDecl::Fun(f) => collect_fun_imports(f, sink),
        KtDecl::FunInterface(i) => collect_fun_sig_imports(&i.method, sink),
        KtDecl::Property(p) => {
            p.value.collect_imports(sink);
            if let Some(a) = &p.accessors {
                a.collect_imports(sink);
            }
        }
        KtDecl::TypeAlias { .. } => {}
        KtDecl::Raw { code, .. } => code.collect_imports(sink),
    }
}

fn collect_companion_imports(c: &KtCompanion, sink: &mut Vec<String>) {
    for (_, args) in c.supertypes.iter() {
        if let Some(args) = args {
            args.collect_imports(sink);
        }
    }
    for m in &c.members {
        collect_decl_imports(m, sink);
    }
}

fn collect_fun_imports(f: &KtFun, sink: &mut Vec<String>) {
    match &f.body {
        KtBody::Expr(c) | KtBody::Block(c) => c.collect_imports(sink),
        KtBody::None | KtBody::External => {}
    }
    collect_param_imports(&f.params, sink);
}

/// A signature has no body, so only parameter defaults can carry imports.
fn collect_fun_sig_imports(f: &KtFunSig, sink: &mut Vec<String>) {
    collect_param_imports(&f.params, sink);
}

fn collect_param_imports(params: &[KtParam], sink: &mut Vec<String>) {
    for p in params {
        if let Some(default) = &p.default {
            default.collect_imports(sink);
        }
    }
}

fn indent(level: usize, out: &mut String) {
    for _ in 0..level {
        out.push_str("    ");
    }
}

/// KDoc: `/** … */` with ` * ` continuations for multi-line docs.
fn render_kdoc(doc: &str, level: usize, out: &mut String) {
    let lines: Vec<&str> = doc.lines().collect();
    if lines.len() == 1 {
        indent(level, out);
        out.push_str(&format!("/** {} */\n", lines[0]));
        return;
    }
    indent(level, out);
    out.push_str("/**\n");
    for l in &lines {
        indent(level, out);
        if l.is_empty() {
            out.push_str(" *\n");
        } else {
            out.push_str(&format!(" * {l}\n"));
        }
    }
    indent(level, out);
    out.push_str(" */\n");
}

fn render_decl(d: &KtDecl, level: usize, imports: &mut ImportSet, out: &mut String) {
    match d {
        KtDecl::Class(c) => render_class(c, level, imports, out),
        KtDecl::Fun(f) => render_fun(f, level, imports, out),
        KtDecl::FunInterface(i) => render_fun_interface(i, level, imports, out),
        KtDecl::Property(p) => render_property(p, level, imports, out),
        KtDecl::TypeAlias { vis, name, target } => {
            indent(level, out);
            out.push_str(&format!(
                "{}typealias {name} = {}\n",
                vis.prefix(),
                target.render(imports)
            ));
        }
        KtDecl::Raw { code, .. } => code.render(level, out),
    }
}

fn render_ctor_param(p: &KtCtorParam, imports: &mut ImportSet) -> String {
    let mut s = String::new();
    for a in &p.annotations {
        s.push_str(&format!("@{a} "));
    }
    s.push_str(p.vis.prefix());
    if p.overrides {
        s.push_str("override ");
    }
    match p.prop {
        Some(false) => s.push_str("val "),
        Some(true) => s.push_str("var "),
        None => {}
    }
    s.push_str(&format!("{}: {}", p.name, p.ty.render(imports)));
    if let Some(d) = &p.default {
        s.push_str(&format!(" = {}", render_code_inline(d)));
    }
    s
}

/// `: Superclass(args), Interface, …` — the superclass, if any, first.
fn render_supertypes(supertypes: &KtSupertypes, imports: &mut ImportSet, out: &mut String) {
    if supertypes.is_empty() {
        return;
    }
    let sts: Vec<String> = supertypes
        .iter()
        .map(|(ty, args)| {
            let t = ty.render(imports);
            match args {
                Some(a) => format!("{t}({})", render_code_inline(a)),
                None => t,
            }
        })
        .collect();
    out.push_str(&format!(" : {}", sts.join(", ")));
}

/// A `companion object`: like a class body, but with no primary constructor
/// and an optional name (absent renders the anonymous form).
fn render_companion(c: &KtCompanion, level: usize, imports: &mut ImportSet, out: &mut String) {
    if let Some(doc) = &c.kdoc {
        render_kdoc(doc, level, out);
    }
    for a in &c.annotations {
        indent(level, out);
        out.push_str(&format!("@{a}\n"));
    }
    indent(level, out);
    out.push_str(c.vis.prefix());
    out.push_str("companion object");
    if let Some(name) = &c.name {
        out.push(' ');
        out.push_str(name);
    }
    render_supertypes(&c.supertypes, imports, out);
    if c.members.is_empty() {
        out.push('\n');
        return;
    }
    out.push_str(" {\n");
    for (i, m) in c.members.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        render_decl(m, level + 1, imports, out);
    }
    indent(level, out);
    out.push_str("}\n");
}

fn render_class(c: &KtClass, level: usize, imports: &mut ImportSet, out: &mut String) {
    if let Some(doc) = &c.kdoc {
        render_kdoc(doc, level, out);
    }
    let mut annotations = c.annotations.clone();
    if matches!(c.kind, KtClassKind::Value { .. }) && !annotations.iter().any(|a| a == "JvmInline")
    {
        annotations.insert(0, "JvmInline".to_string());
    }
    for a in &annotations {
        indent(level, out);
        out.push_str(&format!("@{a}\n"));
    }

    indent(level, out);
    out.push_str(c.vis.prefix());
    out.push_str(c.kind.keyword());
    out.push(' ');
    out.push_str(&c.name);
    let ctor_params = c.ctor_params();
    if !ctor_params.is_empty() {
        let ps: Vec<String> = ctor_params
            .iter()
            .map(|p| render_ctor_param(p, imports))
            .collect();
        out.push_str(&format!("({})", ps.join(", ")));
    }
    render_supertypes(&c.supertypes, imports, out);

    let entries = c.kind.entries();
    let has_body = !entries.is_empty() || !c.members.is_empty() || c.companion.is_some();
    if !has_body {
        out.push('\n');
        return;
    }
    out.push_str(" {\n");

    if !entries.is_empty() {
        for (i, e) in entries.iter().enumerate() {
            indent(level + 1, out);
            out.push_str(&e.name);
            if let Some(args) = &e.args {
                out.push_str(&format!("({})", render_code_inline(args)));
            }
            out.push_str(if i + 1 == entries.len() { ";\n" } else { ",\n" });
        }
        if !c.members.is_empty() || c.companion.is_some() {
            out.push('\n');
        }
    }

    let mut first = true;
    for m in &c.members {
        if !first {
            out.push('\n');
        }
        first = false;
        render_decl(m, level + 1, imports, out);
    }
    if let Some(comp) = &c.companion {
        if !first {
            out.push('\n');
        }
        render_companion(comp, level + 1, imports, out);
    }

    indent(level, out);
    out.push_str("}\n");
}

/// Render one parameter for the multiline signature layout, given the indent
/// `level` of the parameter line itself. The type renders width-aware (see
/// [`render_type_wrapped`]). A default value always renders inline and is
/// deliberately excluded from the width decision: breaking the *type* cannot
/// shorten a long default expression, so counting it would only force a
/// pointless wrap.
fn render_signature_param(p: &KtParam, imports: &mut ImportSet, level: usize) -> String {
    let name_prefix = format!("{}: ", p.name);
    let default = p
        .default
        .as_ref()
        .map(|d| format!(" = {}", render_code_inline(d)))
        .unwrap_or_default();
    // Column where the type begins on the parameter line.
    let type_col = level * 4 + name_prefix.len();
    format!(
        "{name_prefix}{}{default}",
        render_type_wrapped(&p.ty, imports, level, type_col)
    )
}

/// Width-aware type rendering: single-line when it fits within
/// [`MAX_SIGNATURE_WIDTH`] starting at column `start_col`. A function type
/// that doesn't fit breaks its parameters one-per-line at `level + 1` with
/// the `) -> Ret` closer back at `level` (a nullable one keeps its `(…)?`
/// wrapper around the broken form); each parameter type and the return type
/// recurse at their own columns, so arbitrarily nested function types keep
/// breaking. Non-function types render single-line regardless of width.
fn render_type_wrapped(
    ty: &KtType,
    imports: &mut ImportSet,
    level: usize,
    start_col: usize,
) -> String {
    let single = ty.render(imports);
    if start_col + single.len() <= MAX_SIGNATURE_WIDTH {
        return single;
    }
    let KtType::Function {
        params,
        ret,
        nullable,
    } = ty
    else {
        return single;
    };
    if params.is_empty() {
        return single;
    }
    let mut s = String::from(if *nullable { "((" } else { "(" });
    s.push('\n');
    for (name, pty) in params {
        indent(level + 1, &mut s);
        let prefix = if name.is_empty() {
            String::new()
        } else {
            format!("{name}: ")
        };
        s.push_str(&prefix);
        let col = (level + 1) * 4 + prefix.len();
        s.push_str(&render_type_wrapped(pty, imports, level + 1, col));
        s.push_str(",\n");
    }
    indent(level, &mut s);
    let closer = ") -> ";
    s.push_str(closer);
    s.push_str(&render_type_wrapped(
        ret,
        imports,
        level,
        level * 4 + closer.len(),
    ));
    if *nullable {
        s.push_str(")?");
    }
    s
}

/// The parts of a declaration that render as a function signature. Lets
/// [`KtFun`] and [`KtFunSig`] share one layout implementation — including the
/// width-driven parameter breaking — without either owning the other.
struct SigView<'a> {
    kdoc: Option<&'a String>,
    annotations: &'a [String],
    vis: KtVis,
    modifiers: &'a [String],
    /// `external` renders ahead of the other modifiers; it lives on the body.
    external: bool,
    generics: &'a [String],
    /// Extension receiver, rendered as `Recv.` before the name.
    receiver: Option<&'a KtType>,
    name: &'a str,
    params: &'a [KtParam],
    ret: Option<&'a KtType>,
}

impl<'a> From<&'a KtFun> for SigView<'a> {
    fn from(f: &'a KtFun) -> Self {
        SigView {
            kdoc: f.kdoc.as_ref(),
            annotations: &f.annotations,
            vis: f.vis,
            modifiers: &f.modifiers,
            external: matches!(f.body, KtBody::External),
            generics: &f.generics,
            receiver: f.receiver.as_ref(),
            name: &f.name,
            params: &f.params,
            ret: f.ret.as_ref(),
        }
    }
}

impl<'a> From<&'a KtFunSig> for SigView<'a> {
    fn from(f: &'a KtFunSig) -> Self {
        SigView {
            kdoc: f.kdoc.as_ref(),
            annotations: &f.annotations,
            vis: f.vis,
            modifiers: &[],
            external: false,
            generics: &f.generics,
            receiver: f.receiver.as_ref(),
            name: &f.name,
            params: &f.params,
            ret: f.ret.as_ref(),
        }
    }
}

/// Everything up to but not including the body: kdoc, annotations, visibility,
/// modifiers, `fun <generics> name(params): Ret`.
fn render_fun_signature(f: &SigView<'_>, level: usize, imports: &mut ImportSet, out: &mut String) {
    if let Some(doc) = f.kdoc {
        render_kdoc(doc, level, out);
    }
    for a in f.annotations {
        indent(level, out);
        out.push_str(&format!("@{a}\n"));
    }
    indent(level, out);
    out.push_str(f.vis.prefix());
    if f.external {
        out.push_str("external ");
    }
    for m in f.modifiers {
        out.push_str(m);
        out.push(' ');
    }
    out.push_str("fun ");
    if !f.generics.is_empty() {
        out.push_str(&format!("<{}> ", f.generics.join(", ")));
    }
    if let Some(recv) = f.receiver {
        // Receiver position, not ordinary type position: a function type needs
        // parentheses here (see `KtType::render_receiver`).
        out.push_str(&recv.render_receiver(imports));
        out.push('.');
    }
    out.push_str(f.name);
    let ps: Vec<String> = f
        .params
        .iter()
        .map(|p| {
            let mut s = format!("{}: {}", p.name, p.ty.render(imports));
            if let Some(d) = &p.default {
                s.push_str(&format!(" = {}", render_code_inline(d)));
            }
            s
        })
        .collect();
    // Render the return-type suffix up front so the width decision accounts for
    // the whole signature.
    let ret_suffix = match f.ret {
        Some(rt) => {
            let rendered = rt.render(imports);
            if rendered != KtType::UNIT {
                format!(": {rendered}")
            } else {
                String::new()
            }
        }
        None => String::new(),
    };
    // Column at which the parameter list opens: length of the current (last)
    // line already accumulated in `out` (indentation + `fun name`).
    let header_col = out.rsplit('\n').next().map_or(out.len(), str::len);
    let single_line = format!("({}){ret_suffix}", ps.join(", "));
    if !ps.is_empty() && header_col + single_line.len() > MAX_SIGNATURE_WIDTH {
        // One parameter per line, indented one level deeper, with a trailing
        // comma and the closing paren back at the function's indent level. A
        // parameter whose type is itself a wide function type breaks its own
        // parameters one-per-line too (see `render_signature_param`).
        out.push_str("(\n");
        for p in f.params {
            indent(level + 1, out);
            out.push_str(&render_signature_param(p, imports, level + 1));
            out.push_str(",\n");
        }
        indent(level, out);
        out.push(')');
        out.push_str(&ret_suffix);
    } else {
        out.push_str(&single_line);
    }
}

/// An abstract member: a signature and nothing else.
fn render_fun_sig(f: &KtFunSig, level: usize, imports: &mut ImportSet, out: &mut String) {
    render_fun_signature(&f.into(), level, imports, out);
    out.push('\n');
}

fn render_fun(f: &KtFun, level: usize, imports: &mut ImportSet, out: &mut String) {
    render_fun_signature(&f.into(), level, imports, out);
    match &f.body {
        KtBody::None | KtBody::External => out.push('\n'),
        KtBody::Expr(c) => {
            let rendered = render_code_inline(c);
            if rendered.lines().count() <= 1 {
                out.push_str(&format!(" = {rendered}\n"));
            } else {
                out.push_str(" =\n");
                for line in rendered.lines() {
                    indent(level + 1, out);
                    out.push_str(line);
                    out.push('\n');
                }
            }
        }
        KtBody::Block(c) => {
            out.push_str(" {\n");
            c.render(level + 1, out);
            indent(level, out);
            out.push_str("}\n");
        }
    }
}

fn render_fun_interface(
    i: &KtFunInterface,
    level: usize,
    imports: &mut ImportSet,
    out: &mut String,
) {
    if let Some(doc) = &i.kdoc {
        render_kdoc(doc, level, out);
    }
    indent(level, out);
    out.push_str(i.vis.prefix());
    out.push_str("fun interface ");
    out.push_str(&i.name);
    if !i.type_params.is_empty() {
        out.push_str(&format!("<{}>", i.type_params.join(", ")));
    }
    out.push_str(" {\n");
    render_fun_sig(&i.method, level + 1, imports, out);
    indent(level, out);
    out.push_str("}\n");
}

fn render_property(p: &KtProperty, level: usize, imports: &mut ImportSet, out: &mut String) {
    if let Some(doc) = &p.kdoc {
        render_kdoc(doc, level, out);
    }
    indent(level, out);
    for a in &p.annotations {
        out.push_str(&format!("@{a} "));
    }
    out.push_str(p.vis.prefix());
    for m in &p.modifiers {
        out.push_str(m);
        out.push(' ');
    }
    out.push_str(if p.mutable { "var " } else { "val " });
    out.push_str(&p.name);
    if let Some(ty) = &p.ty {
        out.push_str(&format!(": {}", ty.render(imports)));
    }
    match &p.value {
        KtPropertyValue::None => {}
        KtPropertyValue::Delegate(d) => {
            out.push_str(&format!(" by {}", render_code_inline(d)));
        }
        KtPropertyValue::Initializer(i) => {
            out.push_str(&format!(" = {}", render_code_inline(i)));
        }
    }
    out.push('\n');
    if let Some(acc) = &p.accessors {
        acc.render(level + 1, out);
    }
}

#[cfg(test)]
pub(crate) fn render_one(d: &KtDecl, package: &str) -> String {
    KtFile::new(package).decl(d.clone()).render()
}