opy-cli 0.3.8

Standalone OPY CLI: check, compile, inspect, and version.
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
//! `opy-cli` — the standalone Workshop-independent OPY CLI.
//!
//! The CLI owns command parsing and presentation. `opy-rs` owns OPY
//! parsing, semantic resolution, and structured diagnostics.
//!
//! Exit codes remain: 0 clean/success, 1 source diagnostics, and 2 usage or
//! I/O errors. Machine-readable output is written directly to stdout without
//! passing through human or GitHub Actions presentation.

mod cli;
mod present;

use std::process::ExitCode;

use clap::{CommandFactory, Parser, error::ErrorKind};
use clap_complete::{generate, shells};
use opy_rs::lookup::{LookupHit, LookupOutcome, LookupQuery, LookupScope, lookup};
use opy_rs::tooling::{CheckOutcome, Diagnostic as OpyDiagnostic, SourceLocation, check};
use opy_rs::{CompileDiagnostic, CompileStatus, Compiler};
use opy_rs::{FilesystemProject, LANGUAGE_NAME, LANGUAGE_VERSION};
use serde::Serialize;

use crate::cli::{
    CheckArgs, Cli, Command, CompileArgs, FileArgs, LookupArgs, LookupScopeArg, OutputFormatArg,
};
use crate::present::{CheckView, DiagnosticView, PositionView, Presentation, SpanView};

fn main() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(error) => match error.kind() {
            ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => {
                print!("{error}");
                return ExitCode::SUCCESS;
            }
            _ => {
                if error.kind() == ErrorKind::InvalidSubcommand {
                    eprintln!("opy-cli: unknown command");
                }
                eprint!("{error}");
                return ExitCode::from(2);
            }
        },
    };

    let presentation = Presentation::from_cli(cli.renderer, cli.color);
    if cli.version {
        return cmd_version();
    }
    match cli.command {
        None => {
            eprintln!("{}", Cli::command().render_help());
            ExitCode::from(2)
        }
        Some(Command::Check(args)) => cmd_check(&args, presentation),
        Some(Command::Compile(args)) => cmd_compile(&args, presentation),
        Some(Command::Inspect(args)) => cmd_inspect(&args, presentation),
        Some(Command::Lookup(args)) => cmd_lookup(&args),
        Some(Command::Completion(args)) => cmd_completion(args.shell),
        Some(Command::Help) => {
            print!("{}", Cli::command().render_help());
            ExitCode::SUCCESS
        }
        Some(Command::Version) => cmd_version(),
    }
}

fn read_main(args: &FileArgs) -> Result<FilesystemProject, ExitCode> {
    FilesystemProject::load(&args.main).map_err(|error| {
        eprintln!("opy-cli: cannot read '{}': {error}", args.main.display());
        ExitCode::from(2)
    })
}

fn cmd_check(args: &CheckArgs, presentation: Presentation) -> ExitCode {
    let project = match read_main(&args.file) {
        Ok(project) => project,
        Err(code) => return code,
    };
    let outcome = check(
        project.source(),
        &project.main_path().to_string_lossy(),
        project.root(),
    );
    if args.format == OutputFormatArg::Json {
        return match print_json(&CheckReport {
            ok: outcome.is_clean(),
            diagnostics: &outcome.diagnostics,
        }) {
            Ok(()) => diagnostic_exit(&outcome),
            Err(code) => code,
        };
    }

    let code = diagnostic_exit(&outcome);
    presentation.render_check(&check_view(&outcome));
    code
}

fn cmd_compile(args: &CompileArgs, presentation: Presentation) -> ExitCode {
    let project = match read_main(&args.file) {
        Ok(project) => project,
        Err(code) => return code,
    };
    let compiler = match Compiler::new() {
        Ok(compiler) => compiler,
        Err(error) => {
            eprintln!("opy-cli: cannot initialize compiler: {error}");
            return ExitCode::from(2);
        }
    };
    let report = compiler.compile_source_report_with_language(
        project.source(),
        &project.main_path().to_string_lossy(),
        project.root(),
        &args.language,
    );
    if args.format == OutputFormatArg::Json {
        return match print_json(&report) {
            Ok(()) => ExitCode::from(report.compile.exit_code),
            Err(code) => code,
        };
    }

    if report.compile.status == CompileStatus::Success {
        if !report.compile.diagnostics.is_empty() {
            let diagnostics = report
                .compile
                .diagnostics
                .iter()
                .map(compile_diagnostic_view)
                .collect::<Vec<_>>();
            presentation.render_diagnostics("compile", &diagnostics);
        }
        print!("{}", report.compile.workshop_exact);
        ExitCode::SUCCESS
    } else {
        let diagnostics = report
            .compile
            .diagnostics
            .iter()
            .map(compile_diagnostic_view)
            .collect::<Vec<_>>();
        presentation.render_diagnostics("compile", &diagnostics);
        ExitCode::from(report.compile.exit_code)
    }
}

fn cmd_inspect(args: &FileArgs, presentation: Presentation) -> ExitCode {
    let project = match read_main(args) {
        Ok(project) => project,
        Err(code) => return code,
    };
    let outcome = check(
        project.source(),
        &project.main_path().to_string_lossy(),
        project.root(),
    );
    if !outcome.is_clean() {
        let diagnostics = outcome
            .diagnostics
            .iter()
            .map(diagnostic_view)
            .collect::<Vec<_>>();
        presentation.render_diagnostics("inspect", &diagnostics);
        return ExitCode::from(1);
    }
    if !outcome.diagnostics.is_empty() {
        let diagnostics = outcome
            .diagnostics
            .iter()
            .map(diagnostic_view)
            .collect::<Vec<_>>();
        presentation.render_diagnostics("inspect", &diagnostics);
    }
    let model = outcome
        .model
        .as_ref()
        .expect("a clean check produces a model");
    match print_json(model) {
        Ok(()) => ExitCode::SUCCESS,
        Err(code) => code,
    }
}

fn cmd_lookup(args: &LookupArgs) -> ExitCode {
    let scope = if args.scope.is_empty() {
        LookupScope::ALL
    } else {
        args.scope.iter().fold(
            LookupScope {
                functions: false,
                enums: false,
                settings: false,
                events: false,
            },
            |mut scope, arg| {
                match arg {
                    LookupScopeArg::Functions => scope.functions = true,
                    LookupScopeArg::Enums => scope.enums = true,
                    LookupScopeArg::Settings => scope.settings = true,
                    LookupScopeArg::Events => scope.events = true,
                }
                scope
            },
        )
    };
    let outcome = lookup(&LookupQuery {
        text: args.query.clone(),
        scope,
        within: None,
        locale: None,
        limit: args.limit,
    });
    let code = match &outcome {
        LookupOutcome::Matched { .. } => ExitCode::SUCCESS,
        LookupOutcome::UnknownWithin { .. } | LookupOutcome::Unsupported { .. } => {
            ExitCode::from(1)
        }
    };
    if args.format == OutputFormatArg::Json {
        return match print_json(&outcome) {
            Ok(()) => code,
            Err(code) => code,
        };
    }
    match &outcome {
        LookupOutcome::Matched { results, .. } => {
            if results.is_empty() {
                println!("no matches");
            }
            for hit in results {
                println!("{}", lookup_hit_line(hit));
            }
        }
        LookupOutcome::UnknownWithin { within } => {
            eprintln!("opy-cli: lookup cannot be answered: unknown scope {within:?}");
        }
        LookupOutcome::Unsupported { reason, .. } => {
            eprintln!("opy-cli: lookup cannot be answered: {reason}");
        }
    }
    code
}

/// One human-readable line per lookup hit; JSON output is the machine
/// contract, so the text form stays terse.
fn lookup_hit_line(hit: &LookupHit) -> String {
    match hit {
        LookupHit::Function {
            spelling,
            function_kind,
            params,
            matched_on,
            ..
        } => format!(
            "{} {spelling}({})  [{}]",
            function_kind.as_str(),
            params
                .iter()
                .map(|param| param.name.as_str())
                .collect::<Vec<_>>()
                .join(", "),
            matched_on.as_str()
        ),
        LookupHit::EnumDomain {
            domain,
            members,
            matched_on,
            ..
        } => format!(
            "enumDomain {domain}  {}  [{}]",
            members
                .as_ref()
                .map(|members| format!("{} members", members.len()))
                .unwrap_or_else(|| "contextual".to_string()),
            matched_on.as_str()
        ),
        LookupHit::EnumMember {
            spelling,
            display_name,
            matched_on,
            ..
        } => format!(
            "enumMember {spelling}{}  [{}]",
            display_name
                .as_deref()
                .map(|name| format!("  \"{name}\""))
                .unwrap_or_default(),
            matched_on.as_str()
        ),
        LookupHit::Setting {
            path,
            display_name,
            value,
            matched_on,
        } => format!(
            "setting {path}  {}{}  [{}]",
            value.kind.as_str(),
            display_name
                .as_deref()
                .map(|name| format!("  \"{name}\""))
                .unwrap_or_default(),
            matched_on.as_str()
        ),
        LookupHit::Parameter {
            callable,
            param,
            matched_on,
        } => format!(
            "parameter {}.{callable}  [{}]",
            param.name,
            matched_on.as_str()
        ),
        LookupHit::SettingPath { path, matched_on } => {
            format!("settingPath {path}  [{}]", matched_on.as_str())
        }
        LookupHit::Event {
            spelling,
            accepts_filters,
            display_name,
            matched_on,
        } => format!(
            "event {spelling}{}{}  [{}]",
            if *accepts_filters {
                ""
            } else {
                " (no filters)"
            },
            display_name
                .as_deref()
                .map(|name| format!("  \"{name}\""))
                .unwrap_or_default(),
            matched_on.as_str()
        ),
    }
}

fn cmd_completion(shell: cli::ShellArg) -> ExitCode {
    let mut command = Cli::command();
    let mut stdout = std::io::stdout();
    match shell {
        cli::ShellArg::Bash => generate(shells::Bash, &mut command, "opy-cli", &mut stdout),
        cli::ShellArg::Zsh => generate(shells::Zsh, &mut command, "opy-cli", &mut stdout),
        cli::ShellArg::Fish => generate(shells::Fish, &mut command, "opy-cli", &mut stdout),
        cli::ShellArg::PowerShell => {
            generate(shells::PowerShell, &mut command, "opy-cli", &mut stdout)
        }
    }
    ExitCode::SUCCESS
}

fn cmd_version() -> ExitCode {
    println!("opy-cli {}", env!("CARGO_PKG_VERSION"));
    println!("language: {LANGUAGE_NAME} {LANGUAGE_VERSION}");
    println!(
        "protocol: {} v{}",
        opy_rs::hir::types::PROTOCOL_NAME,
        opy_rs::hir::types::PROTOCOL_MAJOR
    );
    ExitCode::SUCCESS
}

#[derive(Serialize)]
struct CheckReport<'a> {
    ok: bool,
    diagnostics: &'a [OpyDiagnostic],
}

fn check_view(outcome: &CheckOutcome) -> CheckView {
    CheckView {
        clean: outcome.is_clean(),
        diagnostics: outcome.diagnostics.iter().map(diagnostic_view).collect(),
        file_count: outcome.files.len(),
        declaration_count: outcome
            .model
            .as_ref()
            .map_or(0, |model| model.declarations().len()),
        rule_count: outcome
            .model
            .as_ref()
            .map_or(0, |model| model.rules().len()),
        symbol_count: outcome
            .model
            .as_ref()
            .map_or(0, |model| model.symbols().len()),
    }
}

fn diagnostic_view(diagnostic: &OpyDiagnostic) -> DiagnosticView {
    DiagnosticView {
        severity: diagnostic.severity.into(),
        code: diagnostic.code.clone(),
        message: diagnostic.message.clone(),
        span: diagnostic.span.as_ref().map(diagnostic_span_view),
    }
}

fn compile_diagnostic_view(diagnostic: &CompileDiagnostic) -> DiagnosticView {
    DiagnosticView {
        severity: diagnostic.severity.into(),
        code: diagnostic.code.clone(),
        message: diagnostic.message.clone(),
        span: diagnostic.span.as_ref().map(diagnostic_span_view),
    }
}

fn diagnostic_span_view(span: &SourceLocation) -> SpanView {
    SpanView {
        path: span.path.clone(),
        start: PositionView {
            line: span.start.line,
            col: span.start.col,
        },
        end: PositionView {
            line: span.end.line,
            col: span.end.col,
        },
    }
}

fn diagnostic_exit(outcome: &CheckOutcome) -> ExitCode {
    if outcome.is_clean() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

fn print_json<T: Serialize>(value: &T) -> Result<(), ExitCode> {
    match serde_json::to_string_pretty(value) {
        Ok(rendered) => {
            println!("{rendered}");
            Ok(())
        }
        Err(error) => {
            eprintln!("opy-cli: cannot serialize output: {error}");
            Err(ExitCode::from(2))
        }
    }
}