plotnik-cli 0.1.0

CLI for plotnik - typed query language for tree-sitter AST
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
use std::fmt::Write;
use std::fs;
use std::io::{self, Read};
use std::path::PathBuf;

use plotnik_langs::{Lang, NodeFieldId, NodeTypeId};
use plotnik_lib::Query;
use plotnik_lib::ir::{
    CompiledQuery, NodeKindResolver, QueryEmitter, STRING_NONE, TYPE_NODE, TYPE_STR, TYPE_VOID,
    TypeId, TypeKind,
};

pub struct TypesArgs {
    pub query_text: Option<String>,
    pub query_file: Option<PathBuf>,
    pub lang: Option<String>,
    pub format: String,
    pub root_type: String,
    pub verbose_nodes: bool,
    pub no_node_type: bool,
    pub export: bool,
    pub output: Option<PathBuf>,
}

struct LangResolver(Lang);

impl NodeKindResolver for LangResolver {
    fn resolve_kind(&self, name: &str) -> Option<NodeTypeId> {
        self.0.resolve_named_node(name)
    }

    fn resolve_field(&self, name: &str) -> Option<NodeFieldId> {
        self.0.resolve_field(name)
    }
}

pub fn run(args: TypesArgs) {
    if let Err(msg) = validate(&args) {
        eprintln!("error: {}", msg);
        std::process::exit(1);
    }

    let query_source = load_query(&args);
    if query_source.trim().is_empty() {
        eprintln!("error: query cannot be empty");
        std::process::exit(1);
    }
    let lang = resolve_lang_required(&args.lang);

    // Parse and validate query
    let mut query = Query::new(&query_source).exec().unwrap_or_else(|e| {
        eprintln!("error: {}", e);
        std::process::exit(1);
    });

    if !query.is_valid() {
        eprint!("{}", query.diagnostics().render(&query_source));
        std::process::exit(1);
    }

    // Link query against language
    query.link(&lang);
    if !query.is_valid() {
        eprint!("{}", query.diagnostics().render(&query_source));
        std::process::exit(1);
    }

    // Build transition graph and type info
    let mut query = query.build_graph();
    if query.has_type_errors() {
        eprint!("{}", query.diagnostics().render(&query_source));
        std::process::exit(1);
    }

    // Auto-wrap definitions with root node if available
    if let Some(root_id) = lang.root()
        && let Some(root_kind) = lang.node_type_name(root_id)
    {
        query = query.wrap_with_root(root_kind);
    }

    // Emit compiled query (IR)
    let resolver = LangResolver(lang.clone());
    let emitter = QueryEmitter::new(query.graph(), query.type_info(), resolver);
    let compiled = emitter.emit().unwrap_or_else(|e| {
        eprintln!("error: emit failed: {:?}", e);
        std::process::exit(1);
    });

    // Generate TypeScript
    let output = generate_typescript(&compiled, &args);

    // Write output
    if let Some(path) = &args.output {
        fs::write(path, &output).unwrap_or_else(|e| {
            eprintln!("error: failed to write {}: {}", path.display(), e);
            std::process::exit(1);
        });
    } else {
        print!("{}", output);
    }
}

fn generate_typescript(ir: &CompiledQuery, args: &TypesArgs) -> String {
    let mut out = String::new();
    let export_prefix = if args.export { "export " } else { "" };

    // Emit Node and Point types unless --no-node-type
    if !args.no_node_type {
        if args.verbose_nodes {
            writeln!(out, "{}interface Point {{", export_prefix).unwrap();
            writeln!(out, "  row: number;").unwrap();
            writeln!(out, "  column: number;").unwrap();
            writeln!(out, "}}").unwrap();
            writeln!(out).unwrap();
            writeln!(out, "{}interface Node {{", export_prefix).unwrap();
            writeln!(out, "  kind: string;").unwrap();
            writeln!(out, "  text: string;").unwrap();
            writeln!(out, "  start_byte: number;").unwrap();
            writeln!(out, "  end_byte: number;").unwrap();
            writeln!(out, "  start_point: Point;").unwrap();
            writeln!(out, "  end_point: Point;").unwrap();
            writeln!(out, "}}").unwrap();
        } else {
            writeln!(out, "{}interface Node {{", export_prefix).unwrap();
            writeln!(out, "  kind: string;").unwrap();
            writeln!(out, "  text: string;").unwrap();
            writeln!(out, "  range: [number, number];").unwrap();
            writeln!(out, "}}").unwrap();
        }
    }

    let emitter = TypeScriptEmitter::new(ir, export_prefix);

    // Emit composite types that are named and not inlinable
    for (idx, type_def) in ir.type_defs().iter().enumerate() {
        let type_id = idx as TypeId + 3; // TYPE_COMPOSITE_START
        if !emitter.should_emit_as_interface(type_id) {
            continue;
        }

        if !out.is_empty() {
            writeln!(out).unwrap();
        }
        emitter.emit_type_def(&mut out, type_id, type_def);
    }

    // Emit entrypoints as type aliases if they differ from their type name
    for entry in ir.entrypoints() {
        let raw_entry_name = ir.string(entry.name_id());
        // Replace anonymous entrypoint "_" with --root-type name
        let entry_name = if raw_entry_name == "_" {
            args.root_type.as_str()
        } else {
            raw_entry_name
        };
        let type_id = entry.result_type();
        let type_name = emitter.get_type_name(type_id);

        // Skip if entrypoint name matches type name (redundant alias)
        if type_name == entry_name {
            continue;
        }

        if !out.is_empty() {
            writeln!(out).unwrap();
        }
        writeln!(
            out,
            "{}type {} = {};",
            export_prefix,
            entry_name,
            emitter.format_type(type_id)
        )
        .unwrap();
    }

    out
}

struct TypeScriptEmitter<'a> {
    ir: &'a CompiledQuery,
    export_prefix: &'a str,
}

impl<'a> TypeScriptEmitter<'a> {
    fn new(ir: &'a CompiledQuery, export_prefix: &'a str) -> Self {
        Self { ir, export_prefix }
    }

    /// Returns true if this type should be emitted as a standalone interface.
    fn should_emit_as_interface(&self, type_id: TypeId) -> bool {
        if type_id < 3 {
            return false; // primitives
        }

        let idx = (type_id - 3) as usize;
        let Some(def) = self.ir.type_defs().get(idx) else {
            return false;
        };

        // Wrapper types are always inlined
        if def.is_wrapper() {
            return false;
        }

        // Named composites get their own interface
        def.name != STRING_NONE
    }

    /// Get the type name for a composite type, or generate one.
    fn get_type_name(&self, type_id: TypeId) -> String {
        match type_id {
            TYPE_VOID => "null".to_string(),
            TYPE_NODE => "Node".to_string(),
            TYPE_STR => "string".to_string(),
            _ => {
                let idx = (type_id - 3) as usize;
                if let Some(def) = self.ir.type_defs().get(idx)
                    && def.name != STRING_NONE
                {
                    return self.ir.string(def.name).to_string();
                }
                // Fallback for anonymous types
                format!("T{}", type_id)
            }
        }
    }

    /// Format a type reference (may be inline or named).
    fn format_type(&self, type_id: TypeId) -> String {
        match type_id {
            TYPE_VOID => "null".to_string(),
            TYPE_NODE => "Node".to_string(),
            TYPE_STR => "string".to_string(),
            _ => {
                let idx = (type_id - 3) as usize;
                let Some(def) = self.ir.type_defs().get(idx) else {
                    return format!("unknown /* T{} */", type_id);
                };

                // Wrapper types: inline
                if let Some(inner) = def.inner_type() {
                    let inner_fmt = self.format_type(inner);
                    return match def.kind {
                        TypeKind::Optional => format!("{} | null", inner_fmt),
                        TypeKind::ArrayStar => format!("{}[]", self.wrap_if_union(&inner_fmt)),
                        TypeKind::ArrayPlus => {
                            format!("[{}, ...{}[]]", inner_fmt, self.wrap_if_union(&inner_fmt))
                        }
                        _ => unreachable!(),
                    };
                }

                // Named composite: reference by name
                if def.name != STRING_NONE {
                    return self.ir.string(def.name).to_string();
                }

                // Anonymous composite: inline
                self.format_inline_composite(type_id, def.kind)
            }
        }
    }

    /// Wrap type in parens if it contains a union (for array element types).
    fn wrap_if_union(&self, ty: &str) -> String {
        if ty.contains(" | ") {
            format!("({})", ty)
        } else {
            ty.to_string()
        }
    }

    /// Format an anonymous composite type inline.
    fn format_inline_composite(&self, type_id: TypeId, kind: TypeKind) -> String {
        let idx = (type_id - 3) as usize;
        let Some(def) = self.ir.type_defs().get(idx) else {
            return "unknown".to_string();
        };

        let Some(members_slice) = def.members_slice() else {
            return "unknown".to_string();
        };

        let members = self.ir.resolve_type_members(members_slice);

        match kind {
            TypeKind::Record => {
                let fields: Vec<String> = members
                    .iter()
                    .map(|m| format!("{}: {}", self.ir.string(m.name), self.format_type(m.ty)))
                    .collect();
                format!("{{ {} }}", fields.join("; "))
            }
            TypeKind::Enum => {
                let variants: Vec<String> = members
                    .iter()
                    .map(|m| {
                        let tag = self.ir.string(m.name);
                        let data = self.format_type(m.ty);
                        format!("{{ $tag: \"{}\"; $data: {} }}", tag, data)
                    })
                    .collect();
                variants.join(" | ")
            }
            _ => "unknown".to_string(),
        }
    }

    /// Emit a type definition as an interface or type alias.
    fn emit_type_def(&self, out: &mut String, type_id: TypeId, def: &plotnik_lib::ir::TypeDef) {
        let name = if def.name != STRING_NONE {
            self.ir.string(def.name).to_string()
        } else {
            format!("T{}", type_id)
        };

        let Some(members_slice) = def.members_slice() else {
            return;
        };

        let members = self.ir.resolve_type_members(members_slice);

        match def.kind {
            TypeKind::Record => {
                writeln!(out, "{}interface {} {{", self.export_prefix, name).unwrap();
                for m in members {
                    writeln!(
                        out,
                        "  {}: {};",
                        self.ir.string(m.name),
                        self.format_type(m.ty)
                    )
                    .unwrap();
                }
                writeln!(out, "}}").unwrap();
            }
            TypeKind::Enum => {
                let variants: Vec<String> = members
                    .iter()
                    .map(|m| {
                        let tag = self.ir.string(m.name);
                        let data = self.format_type(m.ty);
                        format!("{{ $tag: \"{}\"; $data: {} }}", tag, data)
                    })
                    .collect();
                writeln!(
                    out,
                    "{}type {} =\n  | {};",
                    self.export_prefix,
                    name,
                    variants.join("\n  | ")
                )
                .unwrap();
            }
            _ => {}
        }
    }
}

fn load_query(args: &TypesArgs) -> String {
    if let Some(ref text) = args.query_text {
        return text.clone();
    }
    if let Some(ref path) = args.query_file {
        if path.as_os_str() == "-" {
            let mut buf = String::new();
            io::stdin()
                .read_to_string(&mut buf)
                .expect("failed to read stdin");
            return buf;
        }
        return fs::read_to_string(path).expect("failed to read query file");
    }
    unreachable!("validation ensures query input exists")
}

fn resolve_lang_required(lang: &Option<String>) -> Lang {
    let name = lang.as_ref().expect("--lang is required");
    plotnik_langs::from_name(name).unwrap_or_else(|| {
        eprintln!("error: unknown language: {}", name);
        std::process::exit(1);
    })
}

fn validate(args: &TypesArgs) -> Result<(), &'static str> {
    let has_query = args.query_text.is_some() || args.query_file.is_some();

    if !has_query {
        return Err("query is required: use -q/--query or --query-file");
    }

    if args.lang.is_none() {
        return Err("--lang is required for type generation");
    }

    let fmt = args.format.to_lowercase();
    if fmt != "typescript" && fmt != "ts" {
        return Err("--format must be 'typescript' or 'ts'");
    }

    Ok(())
}