pinoc 0.3.6

A CLI tool for setting up pinocchio program project
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
//! Detects Codama's own Rust derive macros (`CodamaAccount`, `CodamaInstructions`,
//! etc.) and, when present, extracts a native Codama IDL directly instead of
//! going through the shank IDL + compatibility-shim path.

use super::constants::Constant;
use super::manual_errors::ManualErrors;
use anyhow::{Context, Result};
use heck::ToLowerCamelCase;
use serde_json::Value;
use std::path::Path;
use syn::{Item, Token};

const CODAMA_DERIVES: &[&str] = &[
    "CodamaAccount",
    "CodamaAccounts",
    "CodamaErrors",
    "CodamaEvent",
    "CodamaEvents",
    "CodamaInstruction",
    "CodamaInstructions",
    "CodamaPda",
    "CodamaType",
];

/// The `codama` release pinoc's own extractor is built from.
pub const BUNDLED_CODAMA: &str = "0.13.2";

/// Either crate provides the derives. `codama-macros` is the one a program
/// using `nostd_panic_handler!` can depend on, since the `codama` facade links `std`.
const CODAMA_CRATES: &[&str] = &["codama", "codama-macros"];

/// How a program uses Codama's derive macros.
pub struct CodamaUsage {
    /// The Codama crate the manifest depends on, if any.
    pub dependency: Option<String>,
    /// At least one source file derives a Codama macro.
    pub derives: bool,
}

impl CodamaUsage {
    pub fn detected(&self) -> bool {
        self.dependency.is_some() && self.derives
    }

    /// Why Codama was not detected, for the messages that say so.
    pub fn undetected_reason(&self) -> &'static str {
        if self.derives && self.dependency.is_none() {
            "Codama derives found, but neither `codama` nor `codama-macros` is a dependency"
        } else {
            "no Codama macros detected"
        }
    }
}

pub fn codama_usage(crate_root: &Path, src_dir: &Path) -> Result<CodamaUsage> {
    let cargo_toml = crate_root.join("Cargo.toml");
    let content = std::fs::read_to_string(&cargo_toml)
        .with_context(|| format!("Failed to read {}", cargo_toml.display()))?;
    let manifest: toml::Value = toml::from_str(&content)
        .with_context(|| format!("Failed to parse {}", cargo_toml.display()))?;
    Ok(CodamaUsage {
        dependency: codama_dependency(&manifest).map(|(name, _)| name),
        derives: scan_for_codama_derives(src_dir)?,
    })
}

/// True if the program depends on `codama` or `codama-macros` and at least one
/// file under `src_dir` derives one of Codama's macros.
pub fn codama_macros_detected(crate_root: &Path, src_dir: &Path) -> Result<bool> {
    Ok(codama_usage(crate_root, src_dir)?.detected())
}

/// The Codama crate in `[dependencies]` or any `[target.<cfg>.dependencies]`,
/// with its declared version requirement. A renamed dependency is matched on
/// its `package`.
fn codama_dependency(manifest: &toml::Value) -> Option<(String, Option<String>)> {
    let targets = manifest
        .get("target")
        .and_then(|t| t.as_table())
        .into_iter()
        .flat_map(|t| t.values());
    std::iter::once(manifest)
        .chain(targets)
        .filter_map(|section| section.get("dependencies")?.as_table())
        .flatten()
        .find_map(|(key, spec)| {
            let name = spec.get("package").and_then(|p| p.as_str()).unwrap_or(key);
            if !CODAMA_CRATES.contains(&name) {
                return None;
            }
            let version = spec.as_str().or_else(|| spec.get("version")?.as_str());
            Some((name.to_string(), version.map(str::to_string)))
        })
}

/// A note for a program whose Codama macros are from a different minor release
/// than pinoc's extractor, or `None` when they match or the version is unknown.
/// A directive is parsed twice, by the program's `codama-macros` when it
/// compiles and by pinoc's extractor here, and either side can lack one.
pub fn version_mismatch(crate_root: &Path) -> Option<String> {
    let version = program_codama_version(crate_root)?;
    let (program, bundled) = (minor_of(&version)?, minor_of(BUNDLED_CODAMA)?);
    if program > bundled {
        Some(format!(
            "this program uses codama-macros {version}, newer than the codama {BUNDLED_CODAMA} pinoc extracts with. A `#[codama(..)]` directive added after {BUNDLED_CODAMA} stops the extraction"
        ))
    } else if program < bundled {
        Some(format!(
            "this program uses codama-macros {version}, older than the codama {BUNDLED_CODAMA} pinoc extracts with. A `#[codama(..)]` directive added after {version} extracts here but does not compile; bump codama-macros to use one"
        ))
    } else {
        None
    }
}

/// The `codama-macros` version the program resolves to: from the nearest
/// `Cargo.lock` (the facade depends on the macros, so it is listed either
/// way), else the requirement in the manifest.
fn program_codama_version(crate_root: &Path) -> Option<String> {
    let locked = crate_root.ancestors().take(4).find_map(|dir| {
        let lock: toml::Value =
            toml::from_str(&std::fs::read_to_string(dir.join("Cargo.lock")).ok()?).ok()?;
        let versions: Vec<String> = lock
            .get("package")?
            .as_array()?
            .iter()
            .filter(|p| p.get("name").and_then(|n| n.as_str()) == Some("codama-macros"))
            .filter_map(|p| Some(p.get("version")?.as_str()?.to_string()))
            .collect();
        // With several in the lock file, report one that differs.
        versions
            .iter()
            .find(|v| minor_of(v) != minor_of(BUNDLED_CODAMA))
            .or(versions.first())
            .cloned()
    });
    locked.or_else(|| {
        let manifest: toml::Value =
            toml::from_str(&std::fs::read_to_string(crate_root.join("Cargo.toml")).ok()?).ok()?;
        let requirement = codama_dependency(&manifest)?.1?;
        Some(
            requirement
                .trim_start_matches(|c: char| !c.is_ascii_digit())
                .to_string(),
        )
    })
}

/// `(major, minor)` of a version or requirement such as `0.13.2` or `0.9`.
fn minor_of(version: &str) -> Option<(u64, u64)> {
    let mut parts = version.split('.');
    let major = parts.next()?.trim().parse().ok()?;
    let minor = parts
        .next()
        .and_then(|m| m.trim().parse().ok())
        .unwrap_or(0);
    Some((major, minor))
}

fn scan_for_codama_derives(dir: &Path) -> Result<bool> {
    for entry in std::fs::read_dir(dir)? {
        let path = entry?.path();
        if path.is_dir() {
            if scan_for_codama_derives(&path)? {
                return Ok(true);
            }
            continue;
        }
        if path.extension().and_then(|e| e.to_str()) != Some("rs") {
            continue;
        }
        let Ok(src) = std::fs::read_to_string(&path) else {
            continue;
        };
        let Ok(file) = syn::parse_file(&src) else {
            continue;
        };
        for item in &file.items {
            if item_has_codama_derive(item) {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

fn item_has_codama_derive(item: &Item) -> bool {
    let attrs = match item {
        Item::Struct(s) => &s.attrs,
        Item::Enum(e) => &e.attrs,
        _ => return false,
    };
    derives(attrs, CODAMA_DERIVES)
}

/// Whether `attrs` derive any of `names`, written bare or qualified
/// (`CodamaAccount` or `codama::CodamaAccount`).
fn derives(attrs: &[syn::Attribute], names: &[&str]) -> bool {
    attrs.iter().any(|attr| {
        if !attr.path().is_ident("derive") {
            return false;
        }
        let Ok(paths) = attr
            .parse_args_with(syn::punctuated::Punctuated::<syn::Path, Token![,]>::parse_terminated)
        else {
            return false;
        };
        paths.iter().any(|p| {
            p.segments
                .last()
                .is_some_and(|seg| names.iter().any(|name| seg.ident == name))
        })
    })
}

/// Runs Codama's extractor and injects `resolved_address`, since Codama's own
/// `declare_id!` detection doesn't recognize Pinocchio's macro path.
///
/// `fallback_errors` is the error list of the shank IDL (`{code, name, msg}`,
/// including the manual-`ProgramError` fallback). It fills `program.errors` only
/// when Codama extracted none, so a program without `CodamaErrors` keeps the
/// errors the shank path reports.
pub fn extract_native_codama_idl(
    crate_root: &Path,
    src_dir: &Path,
    resolved_address: Option<&str>,
    fallback_errors: &[Value],
    manual: Option<&ManualErrors>,
    constants: &[Constant],
) -> Result<String> {
    let json = codama::Codama::load(crate_root)
        .and_then(|codama| codama.get_json_idl())
        .map_err(|e| extraction_error(e, crate_root, src_dir))?;
    let mut value: Value = serde_json::from_str(&json)?;
    restore_empty_lists(&mut value);
    // Codama has no directive that declares a program constant.
    if let Some(list) = value["program"]["constants"].as_array_mut() {
        for constant in constants {
            let node = constant.to_codama();
            if !list.iter().any(|existing| existing["name"] == node["name"]) {
                list.push(node);
            }
        }
    }
    if let Some(address) = resolved_address {
        value["program"]["publicKey"] = Value::String(address.to_string());
    }

    let has_native_errors = value["program"]["errors"]
        .as_array()
        .is_some_and(|a| !a.is_empty());
    let fills_errors = !has_native_errors && !fallback_errors.is_empty();

    // Codama::load() doesn't error on a crate with no Codama macros at all,
    // it just returns an empty program, which is easy to mistake for success.
    if program_is_empty(&value) {
        if fills_errors {
            println!("⚠️  Native Codama extraction found no instructions or accounts (does this program use Codama's derive macros?). Its {} error(s) in .codama.json come from the shank IDL.", fallback_errors.len());
        } else {
            println!("⚠️  Native Codama extraction found no instructions, accounts, or errors. Does this program actually use Codama's derive macros?");
        }
    } else if fills_errors {
        println!(
            "ℹ️  No `CodamaErrors` found; added {} error(s) from the shank IDL to .codama.json",
            fallback_errors.len()
        );
    }

    if has_native_errors {
        // Each node named by an override is given its variant's name while codes
        // and messages are paired by variant, then the name that was asked for.
        let directives = error_directives(src_dir)?;
        let renames = pair_error_names(&mut value["program"]["errors"], &directives.names)?;
        backfill_messages(&mut value["program"]["errors"], fallback_errors);
        if let Some(manual) = manual.filter(|m| m.changes_codes()) {
            convert_discriminant_codes(&mut value["program"]["errors"], manual);
        }
        if !renames.is_empty() {
            for (index, name) in &renames {
                value["program"]["errors"][*index]["name"] = Value::from(name.as_str());
            }
            println!(
                "ℹ️  {} error name(s) in .codama.json taken from `#[codama(name = \"..\")]`",
                renames.len()
            );
        }
        if !directives.skipped.is_empty() {
            println!(
                "ℹ️  {} error variant(s) left out of .codama.json by `#[codama(skip)]`: {}",
                directives.skipped.len(),
                directives.skipped.join(", ")
            );
        }
    }
    if fills_errors {
        value["program"]["errors"] = Value::Array(fallback_errors.iter().map(error_node).collect());
    }

    Ok(serde_json::to_string_pretty(&value)?)
}

/// List fields codama 0.13 leaves out when empty and earlier releases always
/// wrote, by node kind. The JS renderers read these without a default: a missing
/// `accounts` renders as `Vec::with_capacity(NaN + ..)` in the Rust client.
const LIST_FIELDS: &[(&str, &[&str])] = &[
    ("rootNode", &["additionalPrograms"]),
    (
        "programNode",
        &[
            "accounts",
            "constants",
            "definedTypes",
            "errors",
            "events",
            "instructions",
            "pdas",
        ],
    ),
    ("instructionNode", &["accounts", "arguments"]),
    ("pdaNode", &["seeds"]),
    ("pdaValueNode", &["seeds"]),
    ("structTypeNode", &["fields"]),
    ("enumTypeNode", &["variants"]),
    ("tupleTypeNode", &["items"]),
    ("hiddenPrefixTypeNode", &["prefix"]),
    ("hiddenSuffixTypeNode", &["suffix"]),
    ("structValueNode", &["fields"]),
    ("arrayValueNode", &["items"]),
    ("setValueNode", &["items"]),
    ("tupleValueNode", &["items"]),
    ("mapValueNode", &["entries"]),
];

/// Writes the empty lists back, so the IDL keeps the shape its consumers expect.
fn restore_empty_lists(value: &mut Value) {
    match value {
        Value::Object(map) => {
            let kind = map.get("kind").and_then(|k| k.as_str()).unwrap_or_default();
            if let Some((_, fields)) = LIST_FIELDS.iter().find(|(k, _)| *k == kind) {
                for field in *fields {
                    map.entry(*field)
                        .or_insert_with(|| Value::Array(Vec::new()));
                }
            }
            map.values_mut().for_each(restore_empty_lists);
        }
        Value::Array(items) => items.iter_mut().for_each(restore_empty_lists),
        _ => {}
    }
}

/// `(variant, name)` for each variant of a `CodamaErrors` enum that carries
/// `#[codama(name = "..")]`. Codama applies the attribute but passes the value
/// through its own camelCase conversion, so `name = "notAMint"` still comes out
/// as `notAmint`; this is what lets the name be kept as written.
///
/// Errors if a name would collide with another variant of the same enum, which
/// Codama resolves by silently keeping one of the two errors.
fn error_directives(src_dir: &Path) -> Result<ErrorDirectives> {
    fn collect(items: &[Item], out: &mut ErrorDirectives) -> Result<()> {
        for item in items {
            match item {
                Item::Mod(m) => {
                    if let Some((_, inner)) = &m.content {
                        collect(inner, out)?;
                    }
                }
                Item::Enum(e) if derives(&e.attrs, &["CodamaErrors"]) => {
                    // A skipped variant has no node, so its name names nothing
                    // and cannot collide.
                    let (skipped, kept): (Vec<_>, Vec<_>) = e
                        .variants
                        .iter()
                        .partition(|v| codama_directive(&v.attrs).skip);
                    out.skipped
                        .extend(skipped.iter().map(|v| v.ident.to_string()));
                    let variants: Vec<(String, Option<String>)> = kept
                        .iter()
                        .map(|v| (v.ident.to_string(), codama_directive(&v.attrs).name))
                        .collect();
                    for (index, (variant, name)) in variants.iter().enumerate() {
                        let Some(name) = name else {
                            continue;
                        };
                        let collision = variants.iter().enumerate().find(|(i, (ident, other))| {
                            *i != index
                                && name_key(other.as_ref().unwrap_or(ident)) == name_key(name)
                        });
                        if let Some((_, (other, _))) = collision {
                            anyhow::bail!(
                                "`#[codama(name = \"{name}\")]` on error variant `{variant}` collides with variant `{other}`; Codama would keep only one of the two errors"
                            );
                        }
                        out.names.push((variant.clone(), name.clone()));
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }
    let mut files = Vec::new();
    let _ = collect_sources(src_dir, &mut files);
    let mut out = ErrorDirectives::default();
    for (_, src) in files {
        if let Ok(file) = syn::parse_file(&src) {
            collect(&file.items, &mut out)?;
        }
    }
    Ok(out)
}

/// What the `#[codama(..)]` attributes on `CodamaErrors` variants ask for.
#[derive(Default)]
struct ErrorDirectives {
    /// `(variant, name)` for each `name = ".."`.
    names: Vec<(String, String)>,
    /// Variants carrying `skip`.
    skipped: Vec<String>,
}

#[derive(Default)]
struct CodamaDirective {
    name: Option<String>,
    skip: bool,
}

/// The `name = ".."` and `skip` of an item's `#[codama(..)]` attributes.
fn codama_directive(attrs: &[syn::Attribute]) -> CodamaDirective {
    let mut out = CodamaDirective::default();
    for attr in attrs.iter().filter(|a| a.path().is_ident("codama")) {
        let _ = attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("name") {
                out.name = Some(meta.value()?.parse::<syn::LitStr>()?.value());
            } else if meta.path.is_ident("skip") {
                out.skip = true;
            } else if meta.input.peek(Token![=]) {
                meta.value()?.parse::<syn::Expr>()?;
            } else if meta.input.peek(syn::token::Paren) {
                let content;
                syn::parenthesized!(content in meta.input);
                content.parse::<proc_macro2::TokenStream>()?;
            }
            Ok(())
        });
    }
    out
}

/// Finds the error node each override applies to (Codama has already named it
/// from the override, re-cased) and names it after its variant for now, so the
/// code and message steps can pair it. Returns `(node index, name as written)`.
fn pair_error_names(
    errors: &mut Value,
    overrides: &[(String, String)],
) -> Result<Vec<(usize, String)>> {
    let Some(nodes) = errors.as_array_mut() else {
        return Ok(Vec::new());
    };
    let mut renames = Vec::new();
    for (variant, name) in overrides {
        let camel_case = name.chars().next().is_some_and(|c| c.is_ascii_lowercase())
            && name.chars().all(|c| c.is_ascii_alphanumeric());
        if !camel_case {
            anyhow::bail!(
                "`#[codama(name = \"{name}\")]` on error variant `{variant}` is not a camelCase name (a lowercase letter, then letters and digits)"
            );
        }
        let key = name_key(name);
        let mut matching = nodes
            .iter()
            .enumerate()
            .filter(|(_, node)| name_key(node["name"].as_str().unwrap_or_default()) == key)
            .map(|(index, _)| index);
        // A variant Codama skipped has no node.
        if let (Some(index), None) = (matching.next(), matching.next()) {
            nodes[index]["name"] = Value::from(variant.as_str());
            renames.push((index, name.clone()));
        }
    }
    Ok(renames)
}

/// Lowercased alphanumerics of a name. Pairs a Rust variant with Codama's
/// camelCase name without depending on how either side splits words
/// (`NotAMint` is `notAmint` to Codama and `notAMint` to heck).
fn name_key(name: &str) -> String {
    name.chars()
        .filter(char::is_ascii_alphanumeric)
        .map(|c| c.to_ascii_lowercase())
        .collect()
}

/// Codama emits an empty message for an error without a `#[error("..")]`
/// attribute. Fills those from the shank IDL's entry of the same name.
fn backfill_messages(errors: &mut Value, fallback_errors: &[Value]) {
    let Some(nodes) = errors.as_array_mut() else {
        return;
    };
    for node in nodes {
        if !node["message"].as_str().unwrap_or_default().is_empty() {
            continue;
        }
        let key = name_key(node["name"].as_str().unwrap_or_default());
        let fallback = fallback_errors
            .iter()
            .find(|e| name_key(e["name"].as_str().unwrap_or_default()) == key)
            .and_then(|e| e["msg"].as_str());
        if let Some(message) = fallback.filter(|m| !m.is_empty()) {
            node["message"] = Value::from(message);
        }
    }
}

/// Codama takes an error's code from the variant's discriminant unless the
/// program sets one explicitly. Rewrites each code that is still the raw
/// discriminant to what the program's `From` impl returns, and reports every
/// error it had to leave alone.
fn convert_discriminant_codes(errors: &mut Value, manual: &ManualErrors) {
    let Some(nodes) = errors.as_array_mut() else {
        return;
    };
    let mut converted = 0;
    let mut unmatched = Vec::new();
    let mut explicit = Vec::new();
    for node in nodes.iter_mut() {
        let name = node["name"].as_str().unwrap_or_default().to_string();
        let key = name_key(&name);
        let mut matches = manual
            .discriminants
            .iter()
            .enumerate()
            .filter(|(_, (variant, _))| name_key(variant) == key);
        let (Some((index, (_, discriminant))), None) = (matches.next(), matches.next()) else {
            unmatched.push(format!("`{name}`"));
            continue;
        };
        let program_code = manual.errors[index].code;
        let native_code = node["code"].as_u64();
        if native_code == Some(u64::from(program_code)) {
            continue;
        }
        if native_code == Some(u64::from(*discriminant)) {
            node["code"] = Value::from(program_code);
            converted += 1;
        } else {
            explicit.push(format!(
                "`{name}` (Codama {}, program {program_code})",
                node["code"]
            ));
        }
    }

    let total = nodes.len();
    if converted == total {
        println!(
            "ℹ️  .codama.json error codes converted the same way (Codama reads raw discriminants)"
        );
    } else if converted > 0 {
        println!("ℹ️  .codama.json: {converted} of {total} error codes converted the same way (Codama reads raw discriminants)");
    }
    if !unmatched.is_empty() {
        println!(
            "⚠️  .codama.json: {} error code(s) left as raw discriminants, because no variant of the enum behind `impl From<_> for ProgramError` matches: {}. They will not match the codes the program returns.",
            unmatched.len(),
            listed(&unmatched)
        );
    }
    if !explicit.is_empty() {
        println!(
            "⚠️  .codama.json: {} error(s) keep a Codama code that is neither the discriminant nor what `impl From<_> for ProgramError` returns: {}.",
            explicit.len(),
            listed(&explicit)
        );
    }
}

fn listed(names: &[String]) -> String {
    const SHOWN: usize = 5;
    let mut out = names
        .iter()
        .take(SHOWN)
        .cloned()
        .collect::<Vec<_>>()
        .join(", ");
    if names.len() > SHOWN {
        out.push_str(&format!(", and {} more", names.len() - SHOWN));
    }
    out
}

/// Maps a shank IDL error (`{code, name, msg}`) to a Codama `errorNode`.
fn error_node(error: &Value) -> Value {
    let name = error["name"].as_str().unwrap_or_default();
    serde_json::json!({
        "kind": "errorNode",
        "name": name.to_lower_camel_case(),
        "code": error["code"],
        "message": error["msg"].as_str().unwrap_or_default(),
    })
}

/// Codama reports a rejected attribute as a `syn::Error`, which has a span but
/// no file, and prints it as its own source. Flattens it to one message per
/// problem, each with the file and line the span points at.
fn extraction_error(
    error: codama::CodamaError,
    crate_root: &Path,
    src_dir: &Path,
) -> anyhow::Error {
    let codama::CodamaError::Compilation(syn_error) = error else {
        return anyhow::anyhow!("{error}");
    };
    let mut files = Vec::new();
    let _ = collect_sources(src_dir, &mut files);
    for (path, _) in &mut files {
        if let Ok(relative) = path.strip_prefix(crate_root) {
            *path = relative.to_path_buf();
        }
    }
    let problems: Vec<String> = syn_error
        .into_iter()
        .map(|e| {
            let start = e.span().start();
            let token = e.span().source_text().unwrap_or_default();
            // The span of a rejected field starts at its doc comments and
            // attributes. Report the first line of the item itself.
            let skipped = token
                .lines()
                .take_while(|line| {
                    let line = line.trim_start();
                    line.starts_with("//") || line.starts_with("#[")
                })
                .count();
            let item = token.lines().nth(skipped).unwrap_or_default().trim();
            let item_note = if item.is_empty() {
                String::new()
            } else {
                format!(" `{item}`")
            };
            let line_number = start.line + skipped;

            // A span carries no file: find the sources that have this token at this position.
            let first_line = token.lines().next().unwrap_or_default();
            let matches: Vec<&(std::path::PathBuf, String)> = files
                .iter()
                .filter(|(_, src)| {
                    !first_line.is_empty()
                        && src
                            .lines()
                            .nth(start.line.saturating_sub(1))
                            .and_then(|line| line.get(char_to_byte(line, start.column)..))
                            .is_some_and(|rest| rest.starts_with(first_line))
                })
                .collect();
            let column = |src: &str| {
                let line = src.lines().nth(line_number - 1).unwrap_or_default();
                if skipped == 0 {
                    start.column + 1
                } else {
                    line.len() - line.trim_start().len() + 1
                }
            };
            match matches.as_slice() {
                [(path, src)] => format!(
                    "{e}{item_note}\n  --> {}:{line_number}:{}\n   |  {}",
                    path.display(),
                    column(src),
                    src.lines().nth(line_number - 1).unwrap_or_default().trim()
                ),
                [] => format!("{e}{item_note} (line {line_number})"),
                several => format!(
                    "{e}{item_note} at line {line_number} of one of: {}",
                    several
                        .iter()
                        .map(|(path, _)| path.display().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            }
        })
        .collect();
    anyhow::anyhow!(problems.join("\n"))
}

/// Byte offset of the `column`-th character of `line` (spans count characters).
fn char_to_byte(line: &str, column: usize) -> usize {
    line.char_indices()
        .nth(column)
        .map(|(i, _)| i)
        .unwrap_or(line.len())
}

fn collect_sources(dir: &Path, out: &mut Vec<(std::path::PathBuf, String)>) -> Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let path = entry?.path();
        if path.is_dir() {
            collect_sources(&path, out)?;
        } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
            if let Ok(src) = std::fs::read_to_string(&path) {
                out.push((path, src));
            }
        }
    }
    out.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(())
}

fn program_is_empty(root: &Value) -> bool {
    let is_empty_array = |key: &str| {
        root["program"][key]
            .as_array()
            .map(|a| a.is_empty())
            .unwrap_or(true)
    };
    is_empty_array("instructions") && is_empty_array("accounts") && is_empty_array("errors")
}