layouttk 0.4.1

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
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
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use layouttk::file_workflows::{self, ClipOptions, Window};
use layouttk::{DEFAULT_OAS_BUDGET, Layer, Point, ReadOptions};
use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use output::Output;

#[path = "layouttk/batch.rs"]
mod batch;
#[path = "layouttk/create.rs"]
mod create;
#[path = "layouttk/edit.rs"]
mod edit;
#[path = "layouttk/font.rs"]
mod font;
#[path = "layouttk/gds.rs"]
mod gds;
#[path = "layouttk/geometry.rs"]
mod geometry;
#[path = "layouttk/output.rs"]
mod output;
#[path = "layouttk/query.rs"]
mod query;
#[path = "layouttk/raster.rs"]
mod raster;
#[path = "layouttk/view.rs"]
mod view;

#[derive(Parser)]
#[command(
    version,
    about = "Create, inspect, edit, compare and convert GDSII and OASIS layouts",
    after_help = "Examples:\n  layouttk inventory chip.oas\n  layouttk extract chip.oas metal.gds --top TOP --layer 7/0\n  layouttk clip chip.oas roi.oas --top TOP --layer 7/0 --window=0,0,100,40\n\nRead top_cells and shape_layers from inventory before choosing a cell and layer.\n7/0 means layer 7, datatype 0. DBU is one grid step. Multiply coordinates by dbu_nm to get nanometres.\n\nUse layouttk <command> --help for examples and options.\nUse layouttk guide --lang zh-CN for the built-in Chinese guide, or guide --lang en for English.\nUse layouttk describe --json for the complete command index, or describe --json query bounds for one command.\nFor scripts, use --format json for a single result or batch for a JSONL request stream."
)]
struct Cli {
    /// Budget in bytes for retained OASIS data, independent of compressed file size.
    #[arg(long, global = true, default_value_t = DEFAULT_OAS_BUDGET)]
    oas_budget_bytes: usize,
    /// Use a versioned JSON report for each result, including file writes and errors.
    #[arg(long, global = true, value_enum)]
    format: Option<OutputFormat>,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Create a layout from a versioned JSON specification. Use - to read stdin.
    #[command(after_help = create::EXAMPLE, after_long_help = create::HELP)]
    Create {
        /// JSON layout specification. Pass - to read it from stdin.
        #[arg(value_name = "SPEC.json|-")]
        spec: PathBuf,
        /// Layout to write. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Exact integer grid refinement. 2 halves the physical DBU and doubles all coordinates.
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Print library metadata, top cells, layers and stored element counts as JSON.
    #[command(
        after_help = "Example: layouttk inspect chip.oas\nStdout is JSON with top_cells, layers, cell_count, element_counts and dbu_meters (metres per grid step). Counts are stored records, so one compact array counts once. Use inventory for per-cell and repetition counts."
    )]
    Inspect {
        /// GDSII or OASIS file to inspect.
        input: PathBuf,
    },
    /// Scan a file for cell definitions, dependencies, layer pairs and repetition counts.
    #[command(
        after_help = "Examples: layouttk inventory chip.oas\n          layouttk inventory chip.oas --top TOP --layer 7/0\nRead report.top_cells, report.shape_layers, report.text_layers and report.dbu_nm first. Shape layers have number and datatype. Text layers use texttype in the datatype field. Per-cell counts describe stored records and local repetitions. They do not expand every placement from the top cell."
    )]
    Inventory {
        /// GDSII or OASIS file to scan.
        input: PathBuf,
        /// Include only this cell and its dependencies. Omit to scan every cell.
        #[arg(long)]
        top: Option<String>,
        /// Select a layer/type pair such as 7/0. Repeat to keep several pairs.
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
    },
    /// Verify stored records and placed layer geometry of two files on the same grid.
    #[command(
        after_help = "Example: layouttk verify source.gds copy.oas --left-top TOP --right-top TOP\nInputs must use matching grids. If needed, use resample first.\nRead report.geometry_equal for placed material and report.stored_equal for stored cells, placements, text and properties. Use report.cell_differences and report.layer_differences to locate changes. Status equal returns exit 0. Status different or a processing error returns exit 1."
    )]
    Verify {
        /// First layout file, typically the reference.
        left: PathBuf,
        /// Second layout file, typically the candidate.
        right: PathBuf,
        /// Cell to compare in LEFT. Omit if LEFT has exactly one top cell.
        #[arg(long)]
        left_top: Option<String>,
        /// Cell to compare in RIGHT. Omit if RIGHT has exactly one top cell.
        #[arg(long)]
        right_top: Option<String>,
        /// Compare only this layer/type pair. Repeat to select several pairs.
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
        /// Maximum expanded placements and elements per input.
        #[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
        limit: usize,
        /// Outline tolerance for paths and circles in DBU. This is not an XOR area threshold.
        #[arg(long, default_value_t = 0.25)]
        tolerance_dbu: f64,
    },
    /// Scan a file twice and write one flat geometry cell per requested window.
    #[command(
        after_help = "Example: layouttk clip chip.oas roi.oas --top TOP --layer 7/0 --window=0,0,1000,800\nRepeat --window for multiple windows. Each produces a cell named WIN_1, WIN_2 and so on, including empty windows. The JSON report maps windows to cells. Output is flat filled polygons in the original top-cell coordinates. For labels, properties and hierarchy, use extract to preserve the selected layer records."
    )]
    Clip {
        /// GDSII or OASIS input file. The command scans it twice.
        input: PathBuf,
        /// Layout to write. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Cell whose coordinate system defines all windows.
        #[arg(long)]
        top: String,
        /// Lower-left and upper-right corners in integer DBU. Use --window=-10,0,100,40 for negatives.
        #[arg(long = "window", value_parser = parse_window, value_name = "X0,Y0,X1,Y1", required = true, allow_hyphen_values = true)]
        windows: Vec<Window>,
        /// Keep a layer/datatype pair. Repeat to select several pairs. Omit to keep all shape layers.
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
        /// Maximum number of placements to expand.
        #[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
        placement_limit: usize,
        /// Maximum total polygon vertices written across all windows.
        #[arg(long, default_value_t = 4_000_000)]
        output_vertex_limit: usize,
        /// Outline tolerance for paths and circles in DBU.
        #[arg(long, default_value_t = 0.25)]
        tolerance_dbu: f64,
    },
    /// Check that a target format can encode the source, without creating an output.
    #[command(
        after_help = "Example: layouttk check chip.oas --to gds --json\nRead can_write and diagnostics. Each diagnostic identifies a field and can identify a cell, element or layer. Exit 0 means the target can be written. Exit 1 means an error occurred. Without --json, success is quiet and the first error goes to stderr."
    )]
    Check {
        /// GDSII or OASIS file to check.
        input: PathBuf,
        /// Output format to check, gds for GDSII or oas for OASIS.
        #[arg(long, value_name = "gds|oas")]
        to: layouttk::Format,
        /// Print all destination constraints and metadata normalizations as JSON.
        #[arg(long)]
        json: bool,
        /// Exact integer grid refinement. 2 halves the physical DBU and doubles all coordinates.
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Read and rewrite a layout. The output suffix selects the format.
    #[command(
        after_help = "Example: layouttk convert chip.oas chip.gds\nRun layouttk check chip.oas --to gds --json to see conversion diagnostics first. Successful conversion writes OUTPUT and is quiet. If encoding fails, an existing OUTPUT stays intact."
    )]
    Convert {
        /// GDSII or OASIS file to read.
        input: PathBuf,
        /// Destination layout. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Exact grid refinement. 2 halves the physical DBU and doubles coordinates.
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Select layers during read and optionally retain one cell with its dependencies.
    #[command(
        after_help = "Example: layouttk extract chip.oas metal.gds --top TOP --layer 7/0\nFirst run layouttk inventory chip.oas to find cell names and layer pairs. Repeat --layer to keep several pairs. Kept cells retain their hierarchy and representable properties, and some definitions may be empty. Successful extraction is quiet. Run layouttk inventory metal.gds to check the result."
    )]
    Extract {
        /// GDSII or OASIS file to read.
        input: PathBuf,
        /// Layout to write. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Keep this cell and its dependencies. Omit to keep every definition.
        #[arg(long)]
        top: Option<String>,
        /// Keep a layer/type pair. Repeat to keep several pairs. Omit to keep all layers.
        #[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        layers: Vec<Layer>,
        /// Exact grid refinement. 2 halves the physical DBU and doubles coordinates.
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Calculate polygon and path geometry from JSON without opening a layout file.
    #[command(
        subcommand,
        after_help = "Run layouttk geometry <method> --help for its JSON example, fields and result. Save the example JSON in a file and pass its filename, or pass - and send JSON on stdin. Read report.result on success. A ring is a list of [x,y] points with an implicit closing edge. For filled regions, use counterclockwise outer rings and clockwise holes. Lengths use grid steps (DBU). Continuous DBU accept fractional values."
    )]
    Geometry(geometry::Command),
    /// Compute a Boolean operation on two placed layers and write the result.
    #[command(
        after_help = "Example: layouttk boolean a.oas b.oas result.gds --op difference --left-top TOP --right-top TOP --left-layer 7/0 --right-layer 8/0 --output-layer 7/0\nInputs must have the same grid. Both layers are resolved into their respective top-cell coordinates. Difference subtracts RIGHT from LEFT. The result is a flat TOP cell, with holes split into independently filled polygons. Empty results are valid and contain an empty TOP cell. Read report.file and report.polygons."
    )]
    Boolean {
        /// Layout supplying the first layer.
        left: PathBuf,
        /// Layout supplying the second layer. It may be the same file as LEFT.
        right: PathBuf,
        /// Layout to write. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Choose union, intersection, difference, or xor.
        #[arg(long)]
        op: layouttk::geometry::BooleanOp,
        /// Cell whose placed shapes supply the first layer.
        #[arg(long)]
        left_top: String,
        /// Cell whose placed shapes supply the second layer.
        #[arg(long)]
        right_top: String,
        /// Shape layer/datatype to use from LEFT.
        #[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        left_layer: Layer,
        /// Shape layer/datatype to use from RIGHT.
        #[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        right_layer: Layer,
        /// Layer/datatype for the resulting polygons in TOP.
        #[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
        output_layer: Layer,
        /// Outline tolerance for paths and circles in DBU.
        #[arg(long, default_value_t = 0.25)]
        tolerance_dbu: f64,
        /// Maximum expanded placements and elements per input.
        #[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
        limit: usize,
    },
    /// Get placed shapes, bounds, areas, labels, or cell information as JSON.
    #[command(
        subcommand,
        after_help = "Example: layouttk query bounds chip.oas --cell TOP\nFind an exact cell name with layouttk inventory. Run layouttk query <method> --help for the result fields, units and a command example."
    )]
    Query(query::Command),
    /// Apply a versioned set of cell, layer, or element edits in one file write.
    #[command(after_help = edit::EXAMPLE, after_long_help = edit::HELP)]
    Edit {
        /// GDSII or OASIS file to edit.
        input: PathBuf,
        /// JSON list of operations. Pass - to read it from stdin.
        #[arg(value_name = "EDITS.json|-")]
        spec: PathBuf,
        /// Layout to write after all edits succeed. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Exact grid refinement when encoding the edited layout.
        #[arg(long, default_value_t = 1)]
        regrid_factor: u32,
    },
    /// Re-express the layout on a new grid while preserving physical dimensions.
    #[command(
        after_help = "Example: layouttk resample chip.oas fine.oas --dbu-nm 0.5\nThe default exact mode fails if any dimension falls between points on the target grid. Use --rounding nearest to allow rounding. It rounds half-grid ties away from zero. The output file is written only after validation succeeds."
    )]
    Resample {
        /// GDSII or OASIS file on the original grid.
        input: PathBuf,
        /// Layout to write on the target grid. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Physical size of one new grid step in nanometres.
        #[arg(long)]
        dbu_nm: f64,
        /// Use nearest-grid rounding when an exact conversion is unavailable.
        #[arg(long, value_enum, default_value = "exact")]
        rounding: Rounding,
    },
    /// Change the physical size of a grid step, keeping stored coordinates unchanged.
    #[command(
        after_help = "Example: layouttk reinterpret-dbu chip.oas scaled.oas --dbu-nm 2\nA length of 100 DBU stays 100 DBU. On a 2 nm grid it measures 200 nm. Use resample to preserve physical dimensions while changing the stored coordinates."
    )]
    ReinterpretDbu {
        /// GDSII or OASIS file to rescale.
        input: PathBuf,
        /// Layout to write with the new units. Use a .gds or .oas suffix.
        output: PathBuf,
        /// Physical size of one new grid step in nanometres.
        #[arg(long)]
        dbu_nm: f64,
    },
    /// Inspect GDSII units and records, hash content, or work with raw cells.
    #[command(
        subcommand,
        after_help = "Example: layouttk gds index chip.gds\nUse layouttk gds <method> --help for the input format, output and options. Use inventory for GDSII or OASIS layout content."
    )]
    Gds(gds::Command),
    /// Exchange binary masks with layout layers, or export a window as PNG.
    #[command(
        subcommand,
        after_help = "Example: layouttk raster png chip.oas roi.png --cell TOP --layer 7/0 --window=0,0,100,40 --pixel-size 5\nRow 0 is the top row. Use layouttk raster <method> --help for pixel sizes and examples."
    )]
    Raster(raster::Command),
    /// Export layer drawings as SVG or a self-contained HTML preview.
    #[command(
        subcommand,
        after_help = "Example: layouttk view html chip.oas preview.html --cell TOP\nOpen the result in a browser on the same machine. It uses no network assets."
    )]
    View(view::Command),
    /// Export or import the stored model as versioned JSON, including properties.
    #[command(
        after_help = "Example: layouttk model export chip.oas --output chip.json\n         layouttk model import chip.json restored.oas\nThe JSON includes stored records, properties and repetitions. Use create for a shorter input format for simple layouts."
    )]
    Model {
        #[command(subcommand)]
        command: edit::Model,
    },
    /// List the commands and parameters supported by this binary.
    #[command(
        after_help = "Examples: layouttk describe --json\n          layouttk describe --json geometry offset\nWith no command path, the JSON contains the full command tree. Supplying a path returns only that command or group and its arguments. Without --json, this prints help text."
    )]
    Describe {
        /// Print the command index as JSON on stdout.
        #[arg(long)]
        json: bool,
        /// Optional command path, for example query bounds.
        #[arg(value_name = "COMMAND")]
        command: Vec<String>,
    },
    /// Run a stream of layouttk commands with one JSON result per request.
    #[command(after_help = batch::HELP)]
    Batch(batch::Args),
    /// Print the built-in command-line guide in English or Simplified Chinese.
    #[command(
        after_help = "Example: layouttk guide --lang zh-CN\nStdout is a Markdown guide with examples for extracting, checking and processing layouts. It is built into the binary."
    )]
    Guide {
        /// Language of the guide.
        #[arg(long, value_enum, default_value = "en")]
        lang: Language,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum OutputFormat {
    Json,
}

#[derive(Clone, Copy, ValueEnum)]
enum Language {
    En,
    #[value(name = "zh-CN", aliases = ["zh-cn", "zh"])]
    ZhCn,
}

#[derive(Clone, Copy, ValueEnum)]
enum Rounding {
    Exact,
    Nearest,
}

type CliResult<T> = Result<T, Box<dyn std::error::Error>>;

fn read_json<T: serde::de::DeserializeOwned>(path: &Path, input: &mut dyn BufRead) -> CliResult<T> {
    Ok(if path.as_os_str() == "-" {
        serde_json::from_reader(input)?
    } else {
        serde_json::from_reader(BufReader::new(File::open(path)?))?
    })
}

fn write_file(path: &Path, write: impl FnOnce(&mut File) -> CliResult<()>) -> CliResult<()> {
    let dir = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut temp = tempfile::NamedTempFile::new_in(dir)?;
    write(temp.as_file_mut())?;
    temp.as_file_mut().flush()?;
    temp.persist(path).map_err(|e| e.error)?;
    Ok(())
}

fn stdout_contract(path: &[&str]) -> serde_json::Value {
    let (default, conditional, json) = match path {
        ["batch"] => ("jsonl", None, "jsonl"),
        ["check"] => ("none", Some(("--json", "json")), "report"),
        ["describe"] => ("help", Some(("--json", "report")), "report"),
        ["model", "export"] => ("model_json", Some(("--output", "none")), "report"),
        ["inspect"] => ("json", None, "report"),
        ["guide"] => ("markdown", None, "report"),
        ["create" | "convert" | "extract" | "resample" | "reinterpret-dbu"]
        | [
            "gds",
            "canonical" | "raw-cell" | "cell" | "element" | "timestamp" | "assemble",
        ]
        | ["model", "import"]
        | ["raster", "add-mask" | "png"]
        | ["view", _] => ("none", None, "report"),
        _ => ("report", None, "report"),
    };
    serde_json::json!({
        "default": default,
        "conditional": conditional.map(|(option, kind)| serde_json::json!({"option": option, "kind": kind})),
        "format_json": json,
    })
}

fn command_index(command: &clap::Command, path: &[&str]) -> serde_json::Value {
    let commands: Vec<_> = command
        .get_subcommands()
        .filter(|sub| sub.get_name() != "help")
        .map(|sub| {
            let mut path = path.to_vec();
            path.push(sub.get_name());
            command_index(sub, &path)
        })
        .collect();
    let stdin = command.get_positionals().find_map(|arg| {
        let name = arg.get_value_names()?.first()?.as_str();
        let format = if name.ends_with(".json|-") {
            "json"
        } else if name.ends_with(".jsonl|-") {
            "jsonl"
        } else {
            return None;
        };
        Some(serde_json::json!({"argument": arg.get_id().as_str(), "value": "-", "format": format}))
    });
    serde_json::json!({
        "path": path,
        "aliases": command.get_visible_aliases().collect::<Vec<_>>(),
        "name": command.get_name(),
        "about": command.get_about().map(ToString::to_string),
        "details": command.get_after_long_help().or_else(|| command.get_after_help()).map(ToString::to_string),
        "arguments": command.get_arguments().map(|arg| serde_json::json!({
            "id": arg.get_id().as_str(),
            "long": arg.get_long(),
            "short": arg.get_short(),
            "position": arg.get_index(),
            "required": arg.is_required_set(),
            "global": arg.is_global_set(),
            "min_values": arg.get_num_args().map(|range| range.min_values()),
            "max_values": arg.get_num_args().map(|range| range.max_values()).filter(|max| *max != usize::MAX),
            "help": arg.get_help().map(ToString::to_string),
            "value_names": arg.get_value_names().into_iter().flatten().map(|name| name.as_str()).collect::<Vec<_>>(),
            "defaults": arg.get_default_values().iter().map(|v| v.to_string_lossy()).collect::<Vec<_>>(),
            "takes_values": arg.get_action().takes_values(),
            "repeatable": matches!(arg.get_action(), clap::ArgAction::Append | clap::ArgAction::Count),
            "choices": arg.get_possible_values().iter().map(|v| v.get_name()).collect::<Vec<_>>(),
        })).collect::<Vec<_>>(),
        "stdin": stdin,
        "stdout": commands.is_empty().then(|| stdout_contract(path)),
        "commands": commands,
    })
}

fn describe(json: bool, path: &[String], out: &mut Output<'_>) -> CliResult<()> {
    let mut root = Cli::command();
    root.build();
    let mut command = &mut root;
    let mut canonical_path = Vec::new();
    for (index, name) in path.iter().enumerate() {
        command = command.find_subcommand_mut(name).ok_or_else(|| {
            format!(
                "unknown command path {:?}. Use layouttk --help",
                path[..=index].join(" ")
            )
        })?;
        canonical_path.push(command.get_name().to_owned());
    }
    if json || out.json {
        let path: Vec<_> = canonical_path.iter().map(String::as_str).collect();
        out.report(
            "ok",
            serde_json::json!({"version": env!("CARGO_PKG_VERSION"), "cli": command_index(command, &path)}),
        )?;
    } else {
        out.text(&command.render_long_help().to_string())?;
    }
    Ok(())
}

fn parse_layer(value: &str) -> Result<Layer, String> {
    let (number, datatype) = value.split_once('/').ok_or("expected LAYER/DATATYPE")?;
    Ok(Layer {
        number: number.parse().map_err(|_| "invalid layer number")?,
        datatype: datatype.parse().map_err(|_| "invalid datatype")?,
    })
}

fn parse_window(value: &str) -> Result<Window, String> {
    let error = "expected four signed integers X0,Y0,X1,Y1";
    let coords = value
        .split(',')
        .map(str::parse::<i64>)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| error)?;
    let [x0, y0, x1, y1] = coords.as_slice() else {
        return Err(error.into());
    };
    Window::new(Point { x: *x0, y: *y0 }, Point { x: *x1, y: *y1 }).map_err(|e| e.to_string())
}

fn selection<'a>(layers: &'a BTreeSet<Layer>, options: ReadOptions<'a>) -> ReadOptions<'a> {
    ReadOptions {
        layers: (!layers.is_empty()).then_some(layers),
        ..options
    }
}

fn run(cli: Cli, stdin: &mut dyn BufRead, out: &mut Output<'_>) -> CliResult<()> {
    let options = ReadOptions {
        oas_budget_bytes: cli.oas_budget_bytes,
        ..Default::default()
    };
    match cli.command {
        Command::Create {
            spec,
            output,
            regrid_factor,
        } => {
            let layout = if spec.as_os_str() == "-" {
                create::read(&mut *stdin)?
            } else {
                create::read(BufReader::new(File::open(spec)?))?
            };
            layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), &output)?;
            out.file(&output)?;
        }
        Command::Check {
            input,
            to,
            json,
            regrid_factor,
        } => {
            if !json && !out.json {
                let layout = options.read(input)?;
                layouttk::check_write(layout.with_regrid(regrid_factor)?.as_ref(), to)?;
            } else {
                use layouttk::conversion::{Diagnostic, Severity};
                let report = options
                    .read(&input)
                    .map_err(|e| ("input", e))
                    .and_then(|layout| {
                        let target = layout
                            .with_regrid(regrid_factor)
                            .map_err(|e| ("regrid_factor", e))?;
                        Ok(target.conversion_diagnostics(to))
                    });
                let rows = report.unwrap_or_else(|(field, err)| {
                    vec![Diagnostic {
                        severity: Severity::Error,
                        cell: None,
                        element: None,
                        layer: None,
                        field: field.into(),
                        reason: err.to_string(),
                    }]
                });
                let can_write = rows.iter().all(|row| row.severity != Severity::Error);
                let target = match to {
                    layouttk::Format::Gdsii => "gds",
                    layouttk::Format::Oasis => "oas",
                };
                let mut data = serde_json::json!({
                    "file": input.to_string_lossy(), "target_format": target, "regrid_factor": regrid_factor,
                    "can_write": can_write, "diagnostics": rows,
                });
                if !can_write {
                    let message = "conversion preflight failed";
                    if out.json {
                        data["code"] = "conversion_preflight_failed".into();
                        data["message"] = message.into();
                        out.report("error", data)?;
                    } else {
                        out.data(data)?;
                    }
                    return Err(message.into());
                }
                out.data(data)?;
            }
        }
        Command::Inspect { input } => {
            let layout = options.read(input)?;
            out.data(layout.summary())?;
        }
        Command::Inventory { input, top, layers } => {
            let layers = layers.into_iter().collect();
            let inventory =
                file_workflows::inventory(selection(&layers, options), input, top.as_deref())?;
            out.report("ok", inventory)?;
        }
        Command::Verify {
            left,
            right,
            left_top,
            right_top,
            layers,
            limit,
            tolerance_dbu,
        } => {
            let layers: BTreeSet<_> = layers.into_iter().collect();
            let comparison = file_workflows::verify(
                selection(&layers, options),
                left,
                right,
                left_top.as_deref(),
                right_top.as_deref(),
                limit,
                tolerance_dbu,
            )?;
            let equal = comparison.geometry_equal && comparison.stored_equal;
            out.report(if equal { "equal" } else { "different" }, comparison)?;
            if !equal {
                return Err("verification found differences".into());
            }
        }
        Command::Clip {
            input,
            output,
            top,
            windows,
            layers,
            placement_limit,
            output_vertex_limit,
            tolerance_dbu,
        } => {
            let layers = layers.into_iter().collect();
            let layout = file_workflows::clip_file(
                input,
                &top,
                &windows,
                ClipOptions {
                    read: selection(&layers, options),
                    placement_limit,
                    output_vertex_limit,
                    tolerance_dbu,
                },
            )?;
            layouttk::write(&layout, &output)?;
            let rows: Vec<_> = windows.iter().zip(&layout.cells).map(|(window, cell)|
                serde_json::json!({"cell": cell.name, "window": window, "polygons": cell.elements.len()})
            ).collect();
            out.report(
                "ok",
                serde_json::json!({
                    "file": output.to_string_lossy(), "top": top, "dbu_nm": layout.dbu_meters * 1e9,
                    "dbu_meters": layout.dbu_meters, "output_kind": "flat_polygons",
                    "tolerance_dbu": tolerance_dbu, "windows": rows,
                }),
            )?;
        }
        Command::Convert {
            input,
            output,
            regrid_factor,
        } => {
            let layout = options.read(input)?;
            layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), &output)?;
            out.file(&output)?;
        }
        Command::Extract {
            input,
            output,
            top,
            layers,
            regrid_factor,
        } => {
            let layers: BTreeSet<_> = layers.into_iter().collect();
            let mut layout = selection(&layers, options).read(input)?;
            if let Some(top) = top {
                layout.retain_tree(&top)?;
            }
            layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), &output)?;
            out.file(&output)?;
        }
        Command::Geometry(command) => command.run(stdin, out)?,
        Command::Boolean {
            left,
            right,
            output,
            op,
            left_top,
            right_top,
            left_layer,
            right_layer,
            output_layer,
            tolerance_dbu,
            limit,
        } => {
            if !tolerance_dbu.is_finite() || tolerance_dbu <= 0.0 || limit == 0 {
                return Err("use a positive tolerance and expansion limit".into());
            }
            let a = selection(&BTreeSet::from([left_layer]), options).read(left)?;
            let b = selection(&BTreeSet::from([right_layer]), options).read(right)?;
            if a.dbu_meters != b.dbu_meters {
                return Err("input grids differ; use layouttk resample to match them".into());
            }
            let left = file_workflows::placed_rings(&a, &left_top, limit, tolerance_dbu)?;
            let right = file_workflows::placed_rings(&b, &right_top, limit, tolerance_dbu)?;
            let subject = left.get(&left_layer).map(Vec::as_slice).unwrap_or_default();
            let clip = right
                .get(&right_layer)
                .map(Vec::as_slice)
                .unwrap_or_default();
            let rings = layouttk::geometry::boolean(subject, clip, op)?;
            let polygons = layouttk::geometry::fracture(&rings, 8_190)?;
            let mut layout = layouttk::Layout::new("BOOLEAN", a.dbu_meters)?;
            let top = layout.add_cell("TOP")?;
            top.elements.extend(
                polygons
                    .into_iter()
                    .map(|points| layouttk::Element::Polygon {
                        layer: output_layer,
                        points,
                    }),
            );
            let count = top.elements.len();
            layouttk::write(&layout, &output)?;
            out.report(
                "ok",
                serde_json::json!({"file": output.to_string_lossy(), "top": "TOP", "polygons": count}),
            )?;
        }
        Command::Query(command) => command.run(options, out)?,
        Command::Edit {
            input,
            spec,
            output,
            regrid_factor,
        } => {
            edit::run(input, spec, output, regrid_factor, options, stdin, out)?;
        }
        Command::Resample {
            input,
            output,
            dbu_nm,
            rounding,
        } => {
            let rounding = match rounding {
                Rounding::Exact => layouttk::GridRounding::Exact,
                Rounding::Nearest => layouttk::GridRounding::Nearest,
            };
            let layout = options.read(input)?.resample(dbu_nm / 1e9, rounding)?;
            layouttk::write(&layout, &output)?;
            out.file(&output)?;
        }
        Command::ReinterpretDbu {
            input,
            output,
            dbu_nm,
        } => {
            let layout = options.read(input)?.reinterpret_dbu(dbu_nm / 1e9)?;
            layouttk::write(&layout, &output)?;
            out.file(&output)?;
        }
        Command::Gds(command) => command.run(options, stdin, out)?,
        Command::Raster(command) => command.run(options, stdin, out)?,
        Command::View(command) => command.run(options, out)?,
        Command::Model { command } => command.run(options, stdin, out)?,
        Command::Describe { json, command } => describe(json, &command, out)?,
        Command::Batch(args) => batch::run(args, cli.oas_budget_bytes, stdin, out.writer)?,
        Command::Guide { lang } => {
            let guide = match lang {
                Language::En => include_str!("../../docs/en/command-line.md"),
                Language::ZhCn => include_str!("../../docs/zh-CN/command-line.md"),
            };
            out.text(guide)?;
        }
    }
    Ok(())
}

fn parse(
    args: impl IntoIterator<Item = impl Into<OsString> + Clone>,
    budget: usize,
) -> Result<Cli, clap::Error> {
    let matches = Cli::command().try_get_matches_from(args)?;
    let mut cli = Cli::from_arg_matches(&matches)?;
    if matches.value_source("oas_budget_bytes") == Some(clap::parser::ValueSource::DefaultValue) {
        cli.oas_budget_bytes = budget;
    }
    Ok(cli)
}

fn main() -> ExitCode {
    let args: Vec<_> = std::env::args_os().collect();
    let mut stdin = io::stdin().lock();
    let mut stdout = io::stdout().lock();
    let mut out = Output {
        writer: &mut stdout,
        json: false,
        row: None,
        reported: false,
    };
    let cli = match parse(args.iter(), DEFAULT_OAS_BUDGET) {
        Ok(cli) => cli,
        Err(err) => {
            let explicit_json = args
                .iter()
                .skip(1)
                .take_while(|arg| *arg != "--")
                .enumerate()
                .any(|(index, arg)| {
                    arg == "--format=json"
                        || (arg == "--format"
                            && args.get(index + 2).is_some_and(|value| value == "json"))
                });
            if explicit_json && err.use_stderr() {
                out.json = true;
                let _ = out.error("invalid_arguments", &err.to_string());
            }
            let _ = err.print();
            return ExitCode::from(err.exit_code() as u8);
        }
    };
    out.json = cli.format.is_some();
    let structured_error = matches!(
        cli.command,
        Command::Inventory { .. }
            | Command::Verify { .. }
            | Command::Clip { .. }
            | Command::Boolean { .. }
            | Command::Geometry(_)
            | Command::Query(_)
            | Command::Edit { .. }
            | Command::Resample { .. }
            | Command::ReinterpretDbu { .. }
            | Command::Gds(_)
            | Command::Model { .. }
            | Command::Raster(_)
            | Command::View(_)
            | Command::Describe { json: true, .. }
    );
    let is_batch = matches!(cli.command, Command::Batch(_));
    match run(cli, &mut stdin, &mut out) {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            if !is_batch && !out.reported && (out.json || structured_error) {
                let _ = out.error("operation_failed", &err.to_string());
            }
            eprintln!("layouttk: {err}");
            ExitCode::FAILURE
        }
    }
}