toon-lsp 0.7.21

Language Server Protocol implementation for TOON (Token-Oriented Object Notation)
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
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2024-2025 w0wl0lxd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Command-line interface for TOON operations.

use clap::{Parser, Subcommand, ValueEnum};
use std::path::PathBuf;
use tower_lsp::{LspService, Server};
use tracing::Level;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

pub mod check;
pub mod convert;
pub mod decode;
pub mod diagnose;
pub mod encode;
pub mod error;
pub mod format;
pub mod graph;
pub mod io_utils;
pub mod symbols;

use error::{CliError, ExitCode};

/// Shared entry point for the `toon-lsp` and `cargo-toon` binaries.
pub async fn run() {
    // Parse CLI arguments
    let cli = Cli::parse();

    // Initialize tracing with verbosity level
    let log_level = match cli.verbose {
        0 => Level::WARN,
        1 => Level::INFO,
        2 => Level::DEBUG,
        _ => Level::TRACE,
    };

    tracing_subscriber::registry()
        .with(
            tracing_subscriber::fmt::layer()
                .with_target(false)
                .with_thread_ids(false)
                .with_thread_names(false)
                .compact(),
        )
        .with(
            tracing_subscriber::EnvFilter::builder()
                .with_default_directive(log_level.into())
                .from_env_lossy(),
        )
        .init();

    // Execute command or start LSP server
    match cli.command {
        Some(Command::Lsp) | None => {
            tracing::info!("Starting TOON Language Server");

            let stdin = tokio::io::stdin();
            let stdout = tokio::io::stdout();

            let (service, socket) = LspService::new(crate::lsp::ToonLanguageServer::new);
            Server::new(stdin, stdout, socket).serve(service).await;
        }
        Some(Command::Encode(args)) => {
            handle_result(encode::execute(&args), encode::error_exit_code);
        }
        Some(Command::Decode(args)) => {
            handle_result(decode::execute(&args), decode::error_exit_code);
        }
        Some(Command::Check(args)) => {
            handle_result(check::execute(&args), CliError::exit_code);
        }
        Some(Command::Format(args)) => {
            handle_result(format::execute(&args), format::error_exit_code);
        }
        Some(Command::Symbols(args)) => {
            handle_result(symbols::execute(&args), symbols::error_exit_code);
        }
        Some(Command::Diagnose(args)) => {
            handle_result(diagnose::execute(&args), diagnose::error_exit_code);
        }
        Some(Command::Graph(args)) => {
            handle_result(graph::execute(&args), CliError::exit_code);
        }
    }
}

/// Handle CLI command result with error reporting and exit code.
fn handle_result<F>(result: Result<(), CliError>, exit_code_fn: F)
where
    F: FnOnce(&CliError) -> ExitCode,
{
    if let Err(e) = result {
        eprintln!("Error: {e}");
        std::process::exit(i32::from(exit_code_fn(&e)));
    }
}

/// TOON Language Server and CLI tools
#[derive(Debug, Parser)]
#[command(name = "toon-lsp")]
#[command(version, about, long_about = None)]
pub struct Cli {
    /// Increase verbosity (-v for info, -vv for debug, -vvv for trace)
    #[arg(short, long, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// Subcommand to execute (defaults to LSP mode if omitted)
    #[command(subcommand)]
    pub command: Option<Command>,
}

/// Available CLI commands
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Convert JSON or YAML to TOON format
    Encode(EncodeArgs),

    /// Convert TOON to JSON or YAML format
    Decode(DecodeArgs),

    /// Check TOON syntax without output
    Check(CheckArgs),

    /// Format TOON files with consistent style
    Format(FormatArgs),

    /// Extract document symbols (keys) from TOON
    Symbols(SymbolsArgs),

    /// Run diagnostics and output structured results
    Diagnose(DiagnoseArgs),

    /// Export reference dependency graph as Mermaid flowchart
    Graph(GraphArgs),

    /// Start LSP server (stdin/stdout communication)
    Lsp,
}

/// Arguments for encode command
#[derive(Debug, Parser)]
pub struct EncodeArgs {
    /// Input file (JSON or YAML), or stdin if omitted
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,

    /// Output file, or stdout if omitted
    #[arg(short, long, value_name = "FILE")]
    pub output: Option<PathBuf>,

    /// Input format
    #[arg(short = 'f', long, value_enum, default_value = "json")]
    pub input_format: InputFormat,

    /// Indentation size in spaces (TOON spec prohibits tabs)
    #[arg(short, long, default_value = "2")]
    pub indent: usize,
}

/// Arguments for decode command
#[derive(Debug, Parser)]
pub struct DecodeArgs {
    /// Input file (TOON), or stdin if omitted
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,

    /// Output file, or stdout if omitted
    #[arg(short, long, value_name = "FILE")]
    pub output: Option<PathBuf>,

    /// Output format
    #[arg(short = 'f', long, value_enum, default_value = "json")]
    pub output_format: OutputFormat,

    /// Pretty-print JSON output
    #[arg(short, long)]
    pub pretty: bool,
}

/// Arguments for check command
#[derive(Debug, Parser)]
pub struct CheckArgs {
    /// Input file(s) (TOON), or stdin if omitted or "-"
    #[arg(value_name = "FILE")]
    pub input: Vec<PathBuf>,

    /// Diagnostic output format
    #[arg(short = 'f', long, value_enum, default_value = "text")]
    pub format: DiagnosticFormat,

    /// Minimum severity level to report
    #[arg(short, long, value_enum, default_value = "error")]
    pub severity: Severity,
}

/// Arguments for format command
#[derive(Debug, Parser)]
pub struct FormatArgs {
    /// Input file (TOON), or stdin if omitted
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,

    /// Output file, or stdout if omitted
    #[arg(short, long, value_name = "FILE")]
    pub output: Option<PathBuf>,

    /// Indentation size in spaces (TOON spec prohibits tabs)
    #[arg(short, long, default_value = "2")]
    pub indent: usize,

    /// Check formatting without writing changes
    #[arg(long)]
    pub check: bool,
}

/// Arguments for symbols command
#[derive(Debug, Parser)]
pub struct SymbolsArgs {
    /// Input file (TOON), or stdin if omitted
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,

    /// Output format
    #[arg(short = 'f', long, value_enum, default_value = "tree")]
    pub format: SymbolsFormat,

    /// Show value types in output
    #[arg(short, long)]
    pub types: bool,

    /// Show positions (line:column) in output
    #[arg(short, long)]
    pub positions: bool,
}

/// Arguments for diagnose command
#[derive(Debug, Parser)]
pub struct DiagnoseArgs {
    /// Input file (TOON), or stdin if omitted
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,

    /// Output format
    #[arg(short = 'f', long, value_enum, default_value = "json")]
    pub format: DiagnoseFormat,

    /// Include source code context in diagnostics
    #[arg(short, long)]
    pub context: bool,

    /// Minimum severity level to report
    #[arg(short, long, value_enum, default_value = "error")]
    pub severity: Severity,
}

/// Arguments for graph command
#[derive(Debug, Parser)]
pub struct GraphArgs {
    /// Input file (TOON), or stdin if omitted
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,

    /// Output file, or stdout if omitted
    #[arg(short, long, value_name = "FILE")]
    pub output: Option<PathBuf>,
}

/// Diagnostic output format
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[non_exhaustive]
pub enum DiagnosticFormat {
    /// Human-readable text with colors
    Text,
    /// JSON output
    Json,
    /// GitHub Actions annotations
    Github,
}

/// Symbol output format
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[non_exhaustive]
pub enum SymbolsFormat {
    /// Tree structure with indentation
    Tree,
    /// JSON output
    Json,
    /// Flat list with paths
    Flat,
}

/// Diagnostic output format for diagnose command
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[non_exhaustive]
pub enum DiagnoseFormat {
    /// JSON output
    Json,
    /// SARIF (Static Analysis Results Interchange Format)
    Sarif,
}

/// Diagnostic severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
#[non_exhaustive]
pub enum Severity {
    /// Hints for improvements
    Hint,
    /// Informational messages
    Info,
    /// Warnings about potential issues
    Warning,
    /// Errors that prevent parsing
    Error,
}

/// Input format for encoding
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[non_exhaustive]
pub enum InputFormat {
    /// JSON input
    Json,
    /// YAML input
    Yaml,
}

/// Output format for decoding
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[non_exhaustive]
pub enum OutputFormat {
    /// JSON output
    Json,
    /// YAML output
    Yaml,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cli_defaults() {
        let cli = Cli::parse_from(["toon-lsp"]);
        assert_eq!(cli.verbose, 0);
        assert!(cli.command.is_none());
    }

    #[test]
    fn test_cli_verbose_flags() {
        let cli = Cli::parse_from(["toon-lsp", "-v"]);
        assert_eq!(cli.verbose, 1);

        let cli = Cli::parse_from(["toon-lsp", "-vv"]);
        assert_eq!(cli.verbose, 2);

        let cli = Cli::parse_from(["toon-lsp", "-vvv"]);
        assert_eq!(cli.verbose, 3);
    }

    #[test]
    fn test_encode_defaults() {
        let cli = Cli::parse_from(["toon-lsp", "encode"]);
        if let Some(Command::Encode(args)) = cli.command {
            assert_eq!(args.indent, 2);
            assert_eq!(args.input_format, InputFormat::Json);
        } else {
            panic!("Expected Encode command");
        }
    }

    #[test]
    fn test_decode_defaults() {
        let cli = Cli::parse_from(["toon-lsp", "decode"]);
        if let Some(Command::Decode(args)) = cli.command {
            assert_eq!(args.output_format, OutputFormat::Json);
            assert!(!args.pretty);
        } else {
            panic!("Expected Decode command");
        }
    }

    #[test]
    fn test_check_defaults() {
        let cli = Cli::parse_from(["toon-lsp", "check"]);
        if let Some(Command::Check(args)) = cli.command {
            assert_eq!(args.format, DiagnosticFormat::Text);
            assert_eq!(args.severity, Severity::Error);
        } else {
            panic!("Expected Check command");
        }
    }

    #[test]
    fn test_format_defaults() {
        let cli = Cli::parse_from(["toon-lsp", "format"]);
        if let Some(Command::Format(args)) = cli.command {
            assert_eq!(args.indent, 2);
            assert!(!args.check);
        } else {
            panic!("Expected Format command");
        }
    }

    #[test]
    fn test_symbols_defaults() {
        let cli = Cli::parse_from(["toon-lsp", "symbols"]);
        if let Some(Command::Symbols(args)) = cli.command {
            assert_eq!(args.format, SymbolsFormat::Tree);
            assert!(!args.types);
            assert!(!args.positions);
        } else {
            panic!("Expected Symbols command");
        }
    }

    #[test]
    fn test_diagnose_defaults() {
        let cli = Cli::parse_from(["toon-lsp", "diagnose"]);
        if let Some(Command::Diagnose(args)) = cli.command {
            assert_eq!(args.format, DiagnoseFormat::Json);
            assert!(!args.context);
            assert_eq!(args.severity, Severity::Error);
        } else {
            panic!("Expected Diagnose command");
        }
    }

    #[test]
    fn test_graph_defaults() {
        let cli = Cli::parse_from(["toon-lsp", "graph"]);
        if let Some(Command::Graph(args)) = cli.command {
            assert!(args.input.is_none());
            assert!(args.output.is_none());
        } else {
            panic!("Expected Graph command");
        }
    }

    #[test]
    fn test_lsp_command() {
        let cli = Cli::parse_from(["toon-lsp", "lsp"]);
        assert!(matches!(cli.command, Some(Command::Lsp)));
    }

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Error > Severity::Warning);
        assert!(Severity::Warning > Severity::Info);
        assert!(Severity::Info > Severity::Hint);
    }
}