langkit 1.0.0-beta.2

A builder library for creating programming languages in Rust
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
use crate::types::Cli;
use std::io::{self, BufRead, Write};
use std::path::PathBuf;

pub struct CliRunner {
    pub commands: Vec<(String, Cli)>,
    pub extension: String,
    pub lang_name: String,
}

impl CliRunner {
    pub fn new(lang_name: &str, extension: &str) -> Self {
        Self {
            commands: vec![],
            extension: extension.to_string(),
            lang_name: lang_name.to_string(),
        }
    }

    pub fn register(&mut self, name: &str, cli: Cli) {
        self.commands.push((name.to_string(), cli));
    }

    pub fn run_with_args(
        &self,
        args: Vec<String>,
        run_source: &dyn Fn(&str) -> Result<(), String>,
        run_path: &dyn Fn(&str) -> Result<(), String>,
        check_path: &dyn Fn(&str) -> Result<(), String>,
        build_path: &dyn Fn(&str) -> Result<String, String>,
        lsp_analyzer: &dyn Fn(Option<&str>, &str) -> Result<(), String>,
    ) {
        let cmd = args.get(1).map(|s| s.as_str()).unwrap_or("help");
        let file = args.get(2).map(|s| s.as_str()).unwrap_or("");
        let lsp_mode = args.iter().any(|a| a == "--lsp");

        match cmd {
            "lsp" => {
                self.run_lsp_server(lsp_analyzer);
            }
            "help" => self.print_help(),
            "version" => println!("{} language toolkit", self.lang_name),
            c => {
                let found = self.commands.iter().find(|(name, _)| name == c);
                match found {
                    Some((_, Cli::Run)) => {
                        if file.is_empty() {
                            eprintln!("Usage: {} run <file>", self.lang_name);
                            return;
                        }
                        if let Err(e) = run_path(file) {
                            eprintln!("Error: {}", e);
                            std::process::exit(1);
                        }
                    }
                    Some((_, Cli::Repl)) => self.run_repl(run_source),
                    Some((_, Cli::Test)) => {
                        let dir = if file.is_empty() { "tests" } else { file };
                        if let Err(e) = self.run_tests(dir, run_path) {
                            eprintln!("Test error: {}", e);
                            std::process::exit(1);
                        }
                    }
                    Some((_, Cli::Add)) => {
                        if file.is_empty() {
                            eprintln!("Usage: {} add <name>", self.lang_name);
                            return;
                        }
                        if let Err(e) = self.add_package(file) {
                            eprintln!("Add error: {}", e);
                            std::process::exit(1);
                        }
                    }
                    Some((_, Cli::Check)) => {
                        if file.is_empty() {
                            eprintln!("Usage: {} check <file>", self.lang_name);
                            return;
                        }
                        match check_path(file) {
                            Ok(_) => {
                                if lsp_mode {
                                    println!("{}", lsp_ok_json(file));
                                } else {
                                    println!("OK");
                                }
                            }
                            Err(e) => {
                                if lsp_mode {
                                    println!("{}", lsp_error_json(file, &e));
                                } else {
                                    eprintln!("Error: {}", e);
                                }
                            }
                        }
                    }
                    Some((_, Cli::New)) => {
                        if file.is_empty() {
                            eprintln!("Usage: {} new <name>", self.lang_name);
                            return;
                        }
                        std::fs::create_dir_all(file).ok();
                        std::fs::write(
                            format!("{}/main{}", file, self.extension),
                            format!("// {} project\n", file),
                        )
                        .ok();
                        let _ = std::fs::write(
                            format!("{}/langkit.toml", file),
                            format!(
                                "name = \"{}\"\nextension = \"{}\"\nbuild_dir = \"build\"\nlibs_dir = \"libs\"\n",
                                self.lang_name, self.extension
                            ),
                        );
                        println!("Created project '{}'", file);
                    }
                    Some((_, Cli::Format)) => println!("Formatter not yet implemented"),
                    Some((_, Cli::Build)) => {
                        if file.is_empty() {
                            eprintln!("Usage: {} build <file>", self.lang_name);
                            return;
                        }
                        match build_path(file) {
                            Ok(out) => println!("Built {}", out),
                            Err(e) => eprintln!("Build error: {}", e),
                        }
                    }
                    Some((_, Cli::Update)) => println!("Update not yet implemented"),
                    Some((_, Cli::Docs)) => println!("Docs not yet implemented"),
                    Some((_, Cli::Cancel)) => println!("Nothing to cancel"),
                    Some((_, Cli::Lsp)) => self.run_lsp_server(lsp_analyzer),
                    Some((_, Cli::Custom(f))) => f(args),
                    None => eprintln!("Unknown command: '{}'. Run '{} help'", c, self.lang_name),
                }
            }
        }
    }

    fn run_repl(&self, runner: &dyn Fn(&str) -> Result<(), String>) {
        println!("{} REPL - type 'exit' to quit", self.lang_name);
        let mut rl = rustyline::DefaultEditor::new().ok();
        let history_path = repl_history_path();
        if let (Some(ref mut r), Some(ref path)) = (rl.as_mut(), history_path.as_ref()) {
            let _ = r.load_history(path);
        }
        loop {
            let line = if let Some(ref mut r) = rl {
                match r.readline("> ") {
                    Ok(l) => l,
                    Err(_) => break,
                }
            } else {
                print!("> ");
                io::stdout().flush().ok();
                let mut line = String::new();
                if io::stdin().read_line(&mut line).is_err() {
                    break;
                }
                line
            };
            let line = line.trim();
            if line == "exit" || line == "quit" {
                break;
            }
            if line.is_empty() {
                continue;
            }
            if let Some(ref mut r) = rl {
                let _ = r.add_history_entry(line);
            }
            if let Err(e) = runner(line) {
                eprintln!("Error: {}", e);
            }
        }
        if let (Some(ref mut r), Some(ref path)) = (rl.as_mut(), history_path.as_ref()) {
            let _ = r.save_history(path);
        }
    }

    fn run_lsp_server(&self, analyzer: &dyn Fn(Option<&str>, &str) -> Result<(), String>) {
        let stdin = io::stdin();
        let mut reader = io::BufReader::new(stdin.lock());
        let mut docs: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        loop {
            let msg = match read_lsp_message(&mut reader) {
                Ok(Some(m)) => m,
                Ok(None) => break,
                Err(_) => break,
            };
            let parsed: serde_json::Value = match serde_json::from_str(&msg) {
                Ok(v) => v,
                Err(_) => continue,
            };
            let method = parsed.get("method").and_then(|m| m.as_str());
            if method.is_none() {
                continue;
            }
            let method = method.unwrap();
            match method {
                "initialize" => {
                    if let Some(id) = parsed.get("id") {
                        let result = serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": id,
                            "result": {
                                "capabilities": {
                                    "textDocumentSync": 1
                                }
                            }
                        });
                        send_lsp_message(&result.to_string());
                    }
                }
                "shutdown" => {
                    if let Some(id) = parsed.get("id") {
                        let result = serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": id,
                            "result": null
                        });
                        send_lsp_message(&result.to_string());
                    }
                }
                "exit" => break,
                "textDocument/didOpen" => {
                    if let Some(params) = parsed.get("params") {
                        let uri = params
                            .get("textDocument")
                            .and_then(|d| d.get("uri"))
                            .and_then(|u| u.as_str());
                        let text = params
                            .get("textDocument")
                            .and_then(|d| d.get("text"))
                            .and_then(|t| t.as_str());
                        if let (Some(uri), Some(text)) = (uri, text) {
                            docs.insert(uri.to_string(), text.to_string());
                            publish_diagnostics(uri, text, analyzer);
                        }
                    }
                }
                "textDocument/didChange" => {
                    if let Some(params) = parsed.get("params") {
                        let uri = params
                            .get("textDocument")
                            .and_then(|d| d.get("uri"))
                            .and_then(|u| u.as_str());
                        let text = params
                            .get("contentChanges")
                            .and_then(|c| c.get(0))
                            .and_then(|c| c.get("text"))
                            .and_then(|t| t.as_str());
                        if let (Some(uri), Some(text)) = (uri, text) {
                            docs.insert(uri.to_string(), text.to_string());
                            publish_diagnostics(uri, text, analyzer);
                        }
                    }
                }
                "textDocument/didSave" => {
                    if let Some(params) = parsed.get("params") {
                        let uri = params
                            .get("textDocument")
                            .and_then(|d| d.get("uri"))
                            .and_then(|u| u.as_str());
                        if let Some(uri) = uri {
                            if let Some(text) = docs.get(uri) {
                                publish_diagnostics(uri, text, analyzer);
                            }
                        }
                    }
                }
                _ => {}
            }
        }
    }

    fn print_help(&self) {
        println!("Usage: {} <command> [file]\n\nCommands:", self.lang_name);
        for (name, _) in &self.commands {
            println!("  {}", name);
        }
        println!("  help\n  version\n  lsp");
        println!("\nOptions:\n  --lsp  Output LSP-style JSON diagnostics (check only)");
    }
}

impl CliRunner {
    fn run_tests(
        &self,
        dir: &str,
        run_path: &dyn Fn(&str) -> Result<(), String>,
    ) -> Result<(), String> {
        let root = std::path::Path::new(dir);
        if !root.exists() {
            return Err(format!("Tests directory '{}' not found", dir));
        }
        let mut total = 0usize;
        let mut failed = 0usize;
        for entry in std::fs::read_dir(root).map_err(|e| e.to_string())? {
            let entry = entry.map_err(|e| e.to_string())?;
            let path = entry.path();
            if path.is_file() {
                if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
                    let want = self.extension.trim_start_matches('.');
                    if ext != want {
                        continue;
                    }
                } else {
                    continue;
                }
                total += 1;
                let p = path.to_string_lossy().to_string();
                if let Err(e) = run_path(&p) {
                    failed += 1;
                    eprintln!("FAIL {}: {}", p, e);
                }
            }
        }
        if failed > 0 {
            return Err(format!("{} of {} tests failed", failed, total));
        }
        println!("OK ({} tests)", total);
        Ok(())
    }

    fn add_package(&self, name: &str) -> Result<(), String> {
        let path = std::path::Path::new("langkit.toml");
        let mut content = if path.exists() {
            std::fs::read_to_string(path).map_err(|e| e.to_string())?
        } else {
            String::new()
        };
        let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
        let mut stdlib_idx = None;
        for (i, line) in lines.iter().enumerate() {
            if line.trim_start().starts_with("stdlib") {
                stdlib_idx = Some(i);
                break;
            }
        }
        if let Some(i) = stdlib_idx {
            let line = lines[i].clone();
            if !line.contains(name) {
                if let Some(pos) = line.find('=') {
                    let mut val = line[pos + 1..].trim().to_string();
                    if !val.starts_with('[') {
                        val = format!("[{}]", val);
                    }
                    if val.ends_with(']') {
                        val.pop();
                    }
                    if !val.ends_with('[') {
                        val.push_str(", ");
                    }
                    val.push_str(&format!("\"{}\"]", name));
                    lines[i] = format!("stdlib = {}", val);
                }
            }
        } else {
            lines.push(format!("stdlib = [\"{}\"]", name));
        }
        content = lines.join("\n");
        std::fs::write(path, content).map_err(|e| e.to_string())?;
        println!("Added '{}' to langkit.toml", name);
        Ok(())
    }
}

fn lsp_ok_json(path: &str) -> String {
    let uri = path_to_uri(path);
    format!(
        "{{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/publishDiagnostics\",\"params\":{{\"uri\":\"{}\",\"diagnostics\":[]}}}}",
        uri
    )
}

fn lsp_error_json(path: &str, err: &str) -> String {
    let uri = path_to_uri(path);
    let (line, col, msg) = parse_line_col(err);
    let msg = json_escape(&msg);
    format!(
        "{{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/publishDiagnostics\",\"params\":{{\"uri\":\"{}\",\"diagnostics\":[{{\"range\":{{\"start\":{{\"line\":{},\"character\":{}}},\"end\":{{\"line\":{},\"character\":{}}}}},\"severity\":1,\"source\":\"langkit\",\"message\":\"{}\"}}]}}}}",
        uri,
        line,
        col,
        line,
        col.saturating_add(1),
        msg
    )
}

fn parse_line_col(err: &str) -> (usize, usize, String) {
    let mut line = 0usize;
    let mut col = 0usize;
    let mut msg = err.to_string();
    if let Some(idx) = err.find("Line ") {
        let rest = &err[idx + 5..];
        let mut parts = rest.splitn(2, ':');
        if let Some(line_str) = parts.next() {
            if let Ok(l) = line_str.trim().parse::<usize>() {
                line = l.saturating_sub(1);
            }
        }
        if let Some(after_line) = parts.next() {
            let mut col_parts = after_line.splitn(2, ':');
            if let Some(col_str) = col_parts.next() {
                if let Ok(c) = col_str.trim().parse::<usize>() {
                    col = c.saturating_sub(1);
                }
            }
            if let Some(rest_msg) = col_parts.next() {
                msg = rest_msg.trim().to_string();
            }
        }
    }
    (line, col, msg)
}

fn json_escape(s: &str) -> String {
    let mut out = String::new();
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            _ => out.push(c),
        }
    }
    out
}

fn path_to_uri(path: &str) -> String {
    let abs = std::fs::canonicalize(path).unwrap_or_else(|_| path.into());
    let mut s = abs.to_string_lossy().replace('\\', "/");
    if !s.starts_with('/') {
        s = format!("/{}", s);
    }
    format!("file://{}", s)
}

fn read_lsp_message(reader: &mut dyn BufRead) -> io::Result<Option<String>> {
    let mut content_length = None;
    let mut line = String::new();
    loop {
        line.clear();
        if reader.read_line(&mut line)? == 0 {
            return Ok(None);
        }
        let trimmed = line.trim();
        if trimmed.is_empty() {
            break;
        }
        if let Some(rest) = trimmed.strip_prefix("Content-Length:") {
            content_length = rest.trim().parse::<usize>().ok();
        }
    }
    let len = match content_length {
        Some(l) => l,
        None => return Ok(None),
    };
    let mut buf = vec![0u8; len];
    reader.read_exact(&mut buf)?;
    Ok(Some(String::from_utf8_lossy(&buf).to_string()))
}

fn send_lsp_message(payload: &str) {
    let mut out = io::stdout();
    let header = format!("Content-Length: {}\r\n\r\n", payload.as_bytes().len());
    let _ = out.write_all(header.as_bytes());
    let _ = out.write_all(payload.as_bytes());
    let _ = out.flush();
}

fn publish_diagnostics(
    uri: &str,
    text: &str,
    analyzer: &dyn Fn(Option<&str>, &str) -> Result<(), String>,
) {
    let path = uri_to_path(uri);
    let result = analyzer(path.as_deref(), text);
    let diag = match result {
        Ok(()) => serde_json::json!([]),
        Err(e) => {
            let (line, col, msg) = parse_line_col(&e);
            serde_json::json!([{
                "range": {
                    "start": { "line": line, "character": col },
                    "end": { "line": line, "character": col + 1 }
                },
                "severity": 1,
                "source": "langkit",
                "message": msg
            }])
        }
    };
    let payload = serde_json::json!({
        "jsonrpc": "2.0",
        "method": "textDocument/publishDiagnostics",
        "params": {
            "uri": uri,
            "diagnostics": diag
        }
    });
    send_lsp_message(&payload.to_string());
}

fn uri_to_path(uri: &str) -> Option<String> {
    if let Some(path) = uri.strip_prefix("file://") {
        let mut decoded = path.replace("%20", " ");
        if decoded.len() > 2 && decoded.as_bytes()[0] == b'/' && decoded.as_bytes()[2] == b':' {
            decoded = decoded[1..].to_string();
        }
        return Some(decoded);
    }
    None
}

fn repl_history_path() -> Option<PathBuf> {
    if let Ok(home) = std::env::var("HOME") {
        return Some(PathBuf::from(home).join(".langkit_history"));
    }
    if let Ok(home) = std::env::var("USERPROFILE") {
        return Some(PathBuf::from(home).join(".langkit_history"));
    }
    None
}