harn-cli 0.5.1

CLI for the Harn programming language — run, test, REPL, format, and lint
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
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process;

use harn_fmt::format_source;
use harn_lint::{lint_with_config, LintSeverity};
use harn_parser::{DiagnosticSeverity, Node, SNode, TypeChecker};

use crate::package::CheckConfig;
use crate::parse_source_file;

fn print_lint_diagnostics(path: &str, diagnostics: &[harn_lint::LintDiagnostic]) -> bool {
    let mut has_error = false;
    for diag in diagnostics {
        let severity = match diag.severity {
            LintSeverity::Warning => "warning",
            LintSeverity::Error => {
                has_error = true;
                "error"
            }
        };
        println!(
            "{path}:{}:{}: {severity}[{}]: {}",
            diag.span.line, diag.span.column, diag.rule, diag.message
        );
        if let Some(ref suggestion) = diag.suggestion {
            println!("  suggestion: {suggestion}");
        }
    }
    has_error
}

pub(crate) fn check_file(path: &str, config: &CheckConfig) {
    let (source, program) = parse_source_file(path);

    let mut has_error = false;
    let mut has_warning = false;
    let mut diagnostic_count = 0;

    // Type checking
    let type_diagnostics = TypeChecker::new().check(&program);
    for diag in &type_diagnostics {
        let severity = match diag.severity {
            DiagnosticSeverity::Error => {
                has_error = true;
                "error"
            }
            DiagnosticSeverity::Warning => {
                has_warning = true;
                "warning"
            }
        };
        diagnostic_count += 1;
        if let Some(span) = &diag.span {
            let rendered = harn_parser::diagnostic::render_diagnostic(
                &source,
                path,
                span,
                severity,
                &diag.message,
                None,
                diag.help.as_deref(),
            );
            eprint!("{rendered}");
        } else {
            eprintln!("{severity}: {}", diag.message);
        }
    }

    // Linting
    let lint_diagnostics = lint_with_config(&program, &config.disable_rules);
    diagnostic_count += lint_diagnostics.len();
    if lint_diagnostics
        .iter()
        .any(|d| d.severity == LintSeverity::Warning)
    {
        has_warning = true;
    }
    if print_lint_diagnostics(path, &lint_diagnostics) {
        has_error = true;
    }

    let preflight_diagnostics = collect_preflight_diagnostics(Path::new(path), &source, &program);
    for diag in &preflight_diagnostics {
        has_error = true;
        diagnostic_count += 1;
        let rendered = harn_parser::diagnostic::render_diagnostic(
            &diag.source,
            &diag.path,
            &diag.span,
            "error",
            &diag.message,
            Some("preflight failure"),
            diag.help.as_deref(),
        );
        eprint!("{rendered}");
    }

    if diagnostic_count == 0 {
        println!("{path}: ok");
    }

    if has_error || (config.strict && has_warning) {
        process::exit(1);
    }
}

pub(crate) fn lint_file(path: &str, config: &CheckConfig) {
    let (_source, program) = parse_source_file(path);

    let diagnostics = lint_with_config(&program, &config.disable_rules);

    if diagnostics.is_empty() {
        println!("{path}: no issues found");
        return;
    }

    let has_warning = diagnostics
        .iter()
        .any(|d| d.severity == LintSeverity::Warning);
    let has_error = print_lint_diagnostics(path, &diagnostics);

    if has_error || (config.strict && has_warning) {
        process::exit(1);
    }
}

/// Format one or more files or directories. Accepts multiple targets.
pub(crate) fn fmt_targets(targets: &[&str], check_mode: bool) {
    let mut files = Vec::new();
    for target in targets {
        let path = std::path::Path::new(target);
        if path.is_dir() {
            collect_harn_files(path, &mut files);
        } else {
            files.push(path.to_path_buf());
        }
    }
    if files.is_empty() {
        eprintln!("No .harn files found");
        process::exit(1);
    }
    let mut has_error = false;
    for file in &files {
        let path_str = file.to_string_lossy();
        if !fmt_file_inner(&path_str, check_mode) {
            has_error = true;
        }
    }
    if has_error {
        process::exit(1);
    }
}

/// Recursively collect .harn files in a directory.
fn collect_harn_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
    if let Ok(entries) = std::fs::read_dir(dir) {
        let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();
        entries.sort_by_key(|e| e.path());
        for entry in entries {
            let path = entry.path();
            if path.is_dir() {
                collect_harn_files(&path, out);
            } else if path.extension().is_some_and(|ext| ext == "harn") {
                out.push(path);
            }
        }
    }
}

/// Format a single file. Returns true on success, false on error.
fn fmt_file_inner(path: &str, check_mode: bool) -> bool {
    let source = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Error reading {path}: {e}");
            return false;
        }
    };

    let formatted = match format_source(&source) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("{path}: {e}");
            return false;
        }
    };

    if check_mode {
        if source != formatted {
            eprintln!("{path}: would be reformatted");
            return false;
        }
    } else if source != formatted {
        match std::fs::write(path, &formatted) {
            Ok(()) => println!("formatted {path}"),
            Err(e) => {
                eprintln!("Error writing {path}: {e}");
                return false;
            }
        }
    }
    true
}

struct PreflightDiagnostic {
    path: String,
    source: String,
    span: harn_lexer::Span,
    message: String,
    help: Option<String>,
}

fn collect_preflight_diagnostics(
    path: &Path,
    source: &str,
    program: &[SNode],
) -> Vec<PreflightDiagnostic> {
    let mut diagnostics = Vec::new();
    let mut visited = HashSet::new();
    let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    scan_program_preflight(&canonical, source, program, &mut visited, &mut diagnostics);
    diagnostics
}

fn scan_program_preflight(
    file_path: &Path,
    source: &str,
    program: &[SNode],
    visited: &mut HashSet<PathBuf>,
    diagnostics: &mut Vec<PreflightDiagnostic>,
) {
    let canonical = file_path
        .canonicalize()
        .unwrap_or_else(|_| file_path.to_path_buf());
    if !visited.insert(canonical.clone()) {
        return;
    }
    for node in program {
        scan_node_preflight(node, &canonical, source, visited, diagnostics);
    }
}

fn scan_node_preflight(
    node: &SNode,
    file_path: &Path,
    source: &str,
    visited: &mut HashSet<PathBuf>,
    diagnostics: &mut Vec<PreflightDiagnostic>,
) {
    match &node.node {
        Node::ImportDecl { path } | Node::SelectiveImport { path, .. } => {
            if path.starts_with("std/") {
                return;
            }
            match resolve_import_path(file_path, path) {
                Some(import_path) => {
                    let import_str = import_path.to_string_lossy().to_string();
                    let (import_source, import_program) = parse_source_file(&import_str);
                    scan_program_preflight(
                        &import_path,
                        &import_source,
                        &import_program,
                        visited,
                        diagnostics,
                    );
                }
                None => diagnostics.push(PreflightDiagnostic {
                    path: file_path.display().to_string(),
                    source: source.to_string(),
                    span: node.span,
                    message: format!("preflight: unresolved import '{path}'"),
                    help: Some("verify the import path and packaged module layout".to_string()),
                }),
            }
        }
        Node::FunctionCall { name, args } if name == "render" => {
            if let Some(Node::StringLiteral(template_path)) = args.first().map(|arg| &arg.node) {
                let resolved = resolve_source_relative(file_path, template_path);
                if !resolved.exists() {
                    diagnostics.push(PreflightDiagnostic {
                        path: file_path.display().to_string(),
                        source: source.to_string(),
                        span: args[0].span,
                        message: format!(
                            "preflight: render target '{}' does not exist at {}",
                            template_path,
                            resolved.display()
                        ),
                        help: Some(
                            "keep template paths relative to the pipeline source file or ship the bundled resource"
                                .to_string(),
                        ),
                    });
                }
            }
        }
        Node::FunctionCall { name, args } if name == "host_invoke" => {
            if matches!(
                (args.first().map(|arg| &arg.node), args.get(1).map(|arg| &arg.node)),
                (Some(Node::StringLiteral(cap)), Some(Node::StringLiteral(op)))
                    if cap == "template" && op == "render"
            ) {
                if let Some(template_path) = host_render_path_arg(args.get(2)) {
                    let resolved = resolve_source_relative(file_path, &template_path);
                    if !resolved.exists() {
                        diagnostics.push(PreflightDiagnostic {
                            path: file_path.display().to_string(),
                            source: source.to_string(),
                            span: args[2].span,
                            message: format!(
                                "preflight: host template render target '{}' does not exist at {}",
                                template_path,
                                resolved.display()
                            ),
                            help: Some(
                                "verify the template path before ACP or embedded-host execution"
                                    .to_string(),
                            ),
                        });
                    }
                }
            }
            scan_children(args, file_path, source, visited, diagnostics);
        }
        Node::IfElse {
            condition,
            then_body,
            else_body,
        } => {
            scan_node_preflight(condition, file_path, source, visited, diagnostics);
            scan_children(then_body, file_path, source, visited, diagnostics);
            if let Some(else_body) = else_body {
                scan_children(else_body, file_path, source, visited, diagnostics);
            }
        }
        Node::ForIn { iterable, body, .. }
        | Node::WhileLoop {
            condition: iterable,
            body,
        } => {
            scan_node_preflight(iterable, file_path, source, visited, diagnostics);
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::Retry { count, body } => {
            scan_node_preflight(count, file_path, source, visited, diagnostics);
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::ReturnStmt { value } => {
            if let Some(value) = value {
                scan_node_preflight(value, file_path, source, visited, diagnostics);
            }
        }
        Node::TryCatch {
            body,
            catch_body,
            finally_body,
            ..
        } => {
            scan_children(body, file_path, source, visited, diagnostics);
            scan_children(catch_body, file_path, source, visited, diagnostics);
            if let Some(finally_body) = finally_body {
                scan_children(finally_body, file_path, source, visited, diagnostics);
            }
        }
        Node::TryExpr { body } | Node::SpawnExpr { body } | Node::MutexBlock { body } => {
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::GuardStmt {
            condition,
            else_body,
        } => {
            scan_node_preflight(condition, file_path, source, visited, diagnostics);
            scan_children(else_body, file_path, source, visited, diagnostics);
        }
        Node::AskExpr { fields } | Node::DictLiteral(fields) => {
            for field in fields {
                scan_node_preflight(&field.value, file_path, source, visited, diagnostics);
            }
        }
        Node::DeadlineBlock { duration, body } => {
            scan_node_preflight(duration, file_path, source, visited, diagnostics);
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::YieldExpr { value } => {
            if let Some(value) = value {
                scan_node_preflight(value, file_path, source, visited, diagnostics);
            }
        }
        Node::Parallel { count, body, .. } => {
            scan_node_preflight(count, file_path, source, visited, diagnostics);
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::ParallelMap { list, body, .. } | Node::ParallelSettle { list, body, .. } => {
            scan_node_preflight(list, file_path, source, visited, diagnostics);
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::SelectExpr {
            cases,
            timeout,
            default_body,
        } => {
            for case in cases {
                scan_node_preflight(&case.channel, file_path, source, visited, diagnostics);
                scan_children(&case.body, file_path, source, visited, diagnostics);
            }
            if let Some((timeout_expr, body)) = timeout {
                scan_node_preflight(timeout_expr, file_path, source, visited, diagnostics);
                scan_children(body, file_path, source, visited, diagnostics);
            }
            if let Some(body) = default_body {
                scan_children(body, file_path, source, visited, diagnostics);
            }
        }
        Node::FunctionCall { args, .. } => {
            scan_children(args, file_path, source, visited, diagnostics);
        }
        Node::MethodCall { object, args, .. } | Node::OptionalMethodCall { object, args, .. } => {
            scan_node_preflight(object, file_path, source, visited, diagnostics);
            scan_children(args, file_path, source, visited, diagnostics);
        }
        Node::PropertyAccess { object, .. }
        | Node::OptionalPropertyAccess { object, .. }
        | Node::UnaryOp {
            operand: object, ..
        } => {
            scan_node_preflight(object, file_path, source, visited, diagnostics);
        }
        Node::SubscriptAccess { object, index } => {
            scan_node_preflight(object, file_path, source, visited, diagnostics);
            scan_node_preflight(index, file_path, source, visited, diagnostics);
        }
        Node::SliceAccess { object, start, end } => {
            scan_node_preflight(object, file_path, source, visited, diagnostics);
            if let Some(start) = start {
                scan_node_preflight(start, file_path, source, visited, diagnostics);
            }
            if let Some(end) = end {
                scan_node_preflight(end, file_path, source, visited, diagnostics);
            }
        }
        Node::BinaryOp { left, right, .. } => {
            scan_node_preflight(left, file_path, source, visited, diagnostics);
            scan_node_preflight(right, file_path, source, visited, diagnostics);
        }
        Node::Ternary {
            condition,
            true_expr,
            false_expr,
        } => {
            scan_node_preflight(condition, file_path, source, visited, diagnostics);
            scan_node_preflight(true_expr, file_path, source, visited, diagnostics);
            scan_node_preflight(false_expr, file_path, source, visited, diagnostics);
        }
        Node::Assignment { target, value, .. } => {
            scan_node_preflight(target, file_path, source, visited, diagnostics);
            scan_node_preflight(value, file_path, source, visited, diagnostics);
        }
        Node::ThrowStmt { value } => {
            scan_node_preflight(value, file_path, source, visited, diagnostics);
        }
        Node::EnumConstruct { args, .. } | Node::ListLiteral(args) => {
            scan_children(args, file_path, source, visited, diagnostics);
        }
        Node::StructConstruct { fields, .. } => {
            for field in fields {
                scan_node_preflight(&field.value, file_path, source, visited, diagnostics);
            }
        }
        Node::RangeExpr { start, end, .. } => {
            scan_node_preflight(start, file_path, source, visited, diagnostics);
            scan_node_preflight(end, file_path, source, visited, diagnostics);
        }
        Node::Pipeline { body, .. }
        | Node::OverrideDecl { body, .. }
        | Node::FnDecl { body, .. } => {
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::LetBinding { value, .. } | Node::VarBinding { value, .. } => {
            scan_node_preflight(value, file_path, source, visited, diagnostics);
        }
        Node::MatchExpr { value, arms } => {
            scan_node_preflight(value, file_path, source, visited, diagnostics);
            for arm in arms {
                scan_children(&arm.body, file_path, source, visited, diagnostics);
                scan_node_preflight(&arm.pattern, file_path, source, visited, diagnostics);
            }
        }
        Node::ImplBlock { methods, .. } => {
            scan_children(methods, file_path, source, visited, diagnostics);
        }
        Node::Spread(expr) | Node::TryOperator { operand: expr } => {
            scan_node_preflight(expr, file_path, source, visited, diagnostics);
        }
        Node::Block(body) | Node::Closure { body, .. } => {
            scan_children(body, file_path, source, visited, diagnostics);
        }
        Node::TypeDecl { .. }
        | Node::EnumDecl { .. }
        | Node::StructDecl { .. }
        | Node::InterfaceDecl { .. }
        | Node::DurationLiteral(_)
        | Node::InterpolatedString(_)
        | Node::StringLiteral(_)
        | Node::IntLiteral(_)
        | Node::FloatLiteral(_)
        | Node::BoolLiteral(_)
        | Node::NilLiteral
        | Node::Identifier(_)
        | Node::BreakStmt
        | Node::ContinueStmt => {}
    }
}

fn scan_children(
    nodes: &[SNode],
    file_path: &Path,
    source: &str,
    visited: &mut HashSet<PathBuf>,
    diagnostics: &mut Vec<PreflightDiagnostic>,
) {
    for node in nodes {
        scan_node_preflight(node, file_path, source, visited, diagnostics);
    }
}

fn resolve_import_path(current_file: &Path, import_path: &str) -> Option<PathBuf> {
    let base = current_file.parent().unwrap_or(Path::new("."));
    let mut file_path = base.join(import_path);
    if !file_path.exists() && file_path.extension().is_none() {
        file_path.set_extension("harn");
    }
    if file_path.exists() {
        return Some(file_path);
    }
    for pkg_dir in [".harn/packages", ".burin/packages"] {
        let pkg_path = base.join(pkg_dir).join(import_path);
        if pkg_path.exists() {
            return Some(if pkg_path.is_dir() {
                let lib = pkg_path.join("lib.harn");
                if lib.exists() {
                    lib
                } else {
                    pkg_path
                }
            } else {
                pkg_path
            });
        }
        let mut pkg_harn = pkg_path.clone();
        pkg_harn.set_extension("harn");
        if pkg_harn.exists() {
            return Some(pkg_harn);
        }
    }
    None
}

fn resolve_source_relative(current_file: &Path, target: &str) -> PathBuf {
    let candidate = PathBuf::from(target);
    if candidate.is_absolute() {
        candidate
    } else {
        current_file
            .parent()
            .unwrap_or(Path::new("."))
            .join(candidate)
    }
}

fn host_render_path_arg(arg: Option<&SNode>) -> Option<String> {
    let Node::DictLiteral(entries) = &arg?.node else {
        return None;
    };
    entries
        .iter()
        .find_map(|entry| match (&entry.key.node, &entry.value.node) {
            (Node::Identifier(key), Node::StringLiteral(path)) if key == "path" => {
                Some(path.clone())
            }
            (Node::StringLiteral(key), Node::StringLiteral(path)) if key == "path" => {
                Some(path.clone())
            }
            _ => None,
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use harn_lexer::Lexer;
    use harn_parser::Parser;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn parse_program(source: &str) -> Vec<SNode> {
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize().expect("tokenize");
        let mut parser = Parser::new(tokens);
        parser.parse().expect("parse")
    }

    fn unique_temp_dir(prefix: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("{prefix}-{nanos}"))
    }

    #[test]
    fn preflight_reports_missing_literal_render_target() {
        let dir = unique_temp_dir("harn-check");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("main.harn");
        let source = r#"
pipeline main() {
  let text = render("missing.txt")
  println(text)
}
"#;
        let program = parse_program(source);
        let diagnostics = collect_preflight_diagnostics(&file, source, &program);
        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics[0].message.contains("render target"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn preflight_resolves_imports_with_implicit_harn_extension() {
        let dir = unique_temp_dir("harn-check");
        std::fs::create_dir_all(dir.join("lib")).unwrap();
        std::fs::write(dir.join("lib").join("helpers.harn"), "pub fn x() { 1 }\n").unwrap();
        let file = dir.join("main.harn");
        let resolved = resolve_import_path(&file, "lib/helpers");
        assert_eq!(resolved, Some(dir.join("lib").join("helpers.harn")));
        let _ = std::fs::remove_dir_all(&dir);
    }
}