forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
2101 lines (2023 loc) · 78 KB
/
Copy pathmain.rs
File metadata and controls
2101 lines (2023 loc) · 78 KB
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Nulang CLI entry point.
//!
//! Usage:
//! nulang [OPTIONS] <FILE>
//! nulang --repl
//! nulang --eval <CODE>
//! nulang --check <FILE>
//! nulang --lsp
//! nulang --dap [FILE]
//! nulang nula <new|build|build-wasm|test|run|add|remove|publish|deploy|watch|doc>
//! nulang fmt [--check] [<file>]
//!
//! Options:
//! -r, --repl Start interactive REPL
//! -e, --eval <CODE> Evaluate a code string
//! -c, --check <FILE> Type-check a file (don't run)
//! --doc Generate Markdown API docs (docs/api.md)
//! --emit-stdlib-docs <dir> Generate per-effect stdlib docs into <dir>
//! --lsp Start Language Server (stdio)
//! --dap Start Debug Adapter (stdio); program from launch request or FILE
//! --backend <b> Backend: bytecode (default, full language) | native
//! (pure-functional subset only — effects/actors/FFI
//! error with a specific unsupported-construct message)
//! | wasm* (IO.print/read only; no user-defined effect
//! handlers, no actor mailbox — requires wasm-backend)
//! --out <file> Output file (WASM backends / --emit-nbc)
//! --emit-nbc Compile <FILE> to a .nbc artifact; don't run
//! <FILE>.nbc Run a pre-compiled .nbc artifact directly
//! --verify <src> Verify .nbc source hash against <src>
//! nula <cmd> Package manager (new, init, build, build-wasm, test, run, add, remove, publish, deploy, list, clean)
//! --version, -V Print version and exit
//! -v, --verbose Show bytecode and AST
//! --bench [N] Benchmark: run N times (default 10), print min/mean/median/max
//! --color auto|always|never Colorize error output (default: auto)
//! -h, --help Show this help message
use mimalloc::MiMalloc;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;
const VERSION: &str = "0.1.0";
use nulang::effect_checker::{CapContext, CapabilityAnalyzer, EffectChecker};
use nulang::lexer::Lexer;
use nulang::parser::Parser;
use nulang::repl::Repl;
use nulang::stdlib::StdLib;
use nulang::typechecker::TypeChecker;
use nulang::types::{NuError, NuResult, Span, Type};
use nulang::vm::VM;
use std::io::IsTerminal;
use std::io::Read;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::path::PathBuf;
use std::time::Instant;
use tracing::instrument;
fn main() {
// Initialize structured tracing (RUST_LOG env var controls verbosity).
// Default level: warn (silent for normal runs). Users opt in with
// RUST_LOG=nulang=debug or RUST_LOG=info.
#[cfg(feature = "otel")]
{
// Forward spans to both the terminal and OTLP (when a tracer
// provider has been configured). Fall back to terminal-only logging
// if the subscriber cannot be installed.
match nulang::observability::init_tracing("nulang-runtime") {
Ok(()) => {}
Err(e) => {
eprintln!("OTLP tracing init failed ({e}); terminal logging only");
use tracing_subscriber::{fmt, EnvFilter};
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn"));
fmt().with_env_filter(env_filter).with_target(false).init();
}
}
}
#[cfg(not(feature = "otel"))]
{
use tracing_subscriber::{fmt, EnvFilter};
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn"));
fmt().with_env_filter(env_filter).with_target(false).init();
}
let args: Vec<String> = std::env::args().collect();
if args.len() <= 1 {
// If stdin is piped, execute as a script; otherwise start REPL.
if !std::io::stdin().is_terminal() {
let mut source = String::new();
std::io::stdin()
.read_to_string(&mut source)
.expect("Failed to read stdin");
let opts = Options::default();
let use_color = color_enabled(&opts);
if let Err(e) = run_source(
&source,
None,
opts.verbose,
&opts.backend,
opts.out_file.as_deref(),
opts.metrics_port,
&opts.target,
) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
return;
}
let mut repl = Repl::new();
repl.run();
return;
}
// `nulang registry serve` — start a package registry server.
if args.len() >= 3 && args[1] == "registry" && args[2] == "serve" {
let mut bind = "127.0.0.1:8087".to_string();
let mut data_dir = ".nula-registry".to_string();
let mut auth_token: Option<String> = None;
let mut i = 3;
while i < args.len() {
match args[i].as_str() {
"--bind" => {
i += 1;
if i < args.len() {
bind = args[i].clone();
}
}
"--dir" => {
i += 1;
if i < args.len() {
data_dir = args[i].clone();
}
}
"--token" => {
i += 1;
if i < args.len() {
auth_token = Some(args[i].clone());
}
}
other => {
eprintln!("Unknown registry serve option: {}", other);
std::process::exit(1);
}
}
i += 1;
}
let server =
nulang::registry::RegistryServer::new(std::path::PathBuf::from(&data_dir), auth_token);
eprintln!("Registry listening on {} (data: {})", bind, data_dir);
if let Err(e) = server.start(&bind) {
eprintln!("Registry server error: {}", e);
std::process::exit(1);
}
// Run until interrupted
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
// `nulang nula <cmd>` dispatches to the package manager.
if args[1] == "fmt" {
let mut check_mode = false;
let mut file_arg: Option<&str> = None;
let mut i = 2;
while i < args.len() {
if args[i] == "--check" {
check_mode = true;
} else if !args[i].starts_with('-') {
file_arg = Some(&args[i]);
} else {
eprintln!("Unknown fmt option: {}", args[i]);
std::process::exit(1);
}
i += 1;
}
if let Some(p) = file_arg {
let s = std::fs::read_to_string(p).unwrap_or_else(|e| {
eprintln!("Cannot read '{}': {}", p, e);
std::process::exit(1);
});
match nulang::fmt::format_source(&s) {
Ok(f) => {
if check_mode {
if f != s {
eprintln!("Would reformat {}", p);
std::process::exit(1);
}
} else {
if f != s {
std::fs::write(p, &f).unwrap_or_else(|e| {
eprintln!("Cannot write '{}': {}", p, e);
std::process::exit(1);
});
println!("Formatted {}", p);
}
}
}
Err(e) => {
eprintln!("{}: {}", p, e);
std::process::exit(1);
}
}
} else {
let dir = std::path::Path::new("src");
if !dir.is_dir() {
eprintln!("Not a package directory (no src/)");
std::process::exit(1);
}
if let Err(e) = nulang::fmt::format_directory(dir, check_mode) {
eprintln!("{}", e);
std::process::exit(exit_code(&e));
}
}
return;
}
// `nulang node --listen <ADDR> [--seed <ADDR>] ...` — run a distributed
// actor node (shard 0, network-enabled).
if args[1] == "node" {
if let Err(e) = run_node_cmd(&args[2..]) {
print_error(&e, true);
std::process::exit(exit_code(&e));
}
return;
}
if args[1] == "nula" {
if let Err(e) = nulang::package::commands::run(&args[2..]) {
print_error(&e, true);
std::process::exit(exit_code(&e));
}
return;
}
// Parse arguments
let mut opts = Options::default();
let mut positional = Vec::new();
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
"-r" | "--repl" => opts.repl = true,
"-e" | "--eval" => {
if i + 1 < args.len() {
opts.eval_code = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("Error: --eval requires a code argument");
std::process::exit(1);
}
}
"-c" | "--check" => {
if i + 1 < args.len() {
opts.check_file = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("Error: --check requires a file argument");
std::process::exit(1);
}
}
"--version" | "-V" => {
println!("nulang {}", VERSION);
println!(
"language {}",
nulang::format::constants::LANGUAGE_VERSION_STR
);
return;
}
"--language-version" => {
println!("{}", nulang::format::constants::LANGUAGE_VERSION_STR);
return;
}
"--lsp" => opts.lsp = true,
"--dap" => opts.dap = true,
"--doc" => opts.doc = true,
"--backend" => {
if i + 1 < args.len() {
opts.backend = args[i + 1].clone();
i += 1;
} else {
eprintln!(
"Error: --backend requires an argument (bytecode | native{})",
if cfg!(feature = "wasm-backend") {
" | wasm | wasm-run | wasm-aot"
} else {
""
}
);
std::process::exit(1);
}
}
"--target" => {
if i + 1 < args.len() {
opts.target = args[i + 1].clone();
i += 1;
} else {
eprintln!("Error: --target requires an argument (native | ptx | riscv64)");
std::process::exit(1);
}
}
"--out" => {
if i + 1 < args.len() {
opts.out_file = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("Error: --out requires a file path argument");
std::process::exit(1);
}
}
"--ffi-sandbox" => opts.ffi_sandbox = true,
"--ffi-allow" => {
if i + 1 < args.len() {
opts.ffi_allow.push(args[i + 1].clone());
i += 1;
} else {
eprintln!("Error: --ffi-allow requires a library name or path argument");
std::process::exit(1);
}
}
"--" => {
// Everything after -- is a positional argument.
for arg in args[i + 1..].iter() {
positional.push(arg.to_string());
}
break;
}
"--emit-stdlib-docs" => {
if i + 1 < args.len() {
opts.emit_stdlib_docs = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("Error: --emit-stdlib-docs requires a directory argument");
std::process::exit(1);
}
}
"init" => {
if i + 1 < args.len() {
opts.init = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("init requires a name");
std::process::exit(1);
}
}
"--watch" => {
if i + 1 < args.len() {
opts.watch = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("--watch requires a file");
std::process::exit(1);
}
}
"--explain" => {
if i + 1 < args.len() {
opts.explain = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("--explain requires a code");
std::process::exit(1);
}
}
"-v" | "--verbose" => opts.verbose = true,
"--all-errors" => opts.all_errors = true,
"--metrics-port" => {
if i + 1 < args.len() {
match args[i + 1].parse::<u16>() {
Ok(port) => opts.metrics_port = Some(port),
Err(_) => {
eprintln!("Error: --metrics-port requires a valid port number");
std::process::exit(1);
}
}
i += 1;
} else {
eprintln!("Error: --metrics-port requires a port number");
std::process::exit(1);
}
}
"--color" => {
if i + 1 < args.len() {
let val = args[i + 1].clone();
if val != "auto" && val != "always" && val != "never" {
eprintln!(
"Error: --color must be 'auto', 'always', or 'never', got '{}'",
val
);
std::process::exit(1);
}
opts.color = val;
i += 1;
} else {
eprintln!("Error: --color requires an argument (auto|always|never)");
std::process::exit(1);
}
}
"--emit-nbc" => opts.emit_nbc = true,
"--verify" => {
if i + 1 < args.len() {
opts.verify_source = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("Error: --verify requires a source file path argument");
std::process::exit(1);
}
}
"--bench" => {
opts.bench_count = Some(10); // default
if i + 1 < args.len() {
if let Ok(n) = args[i + 1].parse::<usize>() {
if n > 0 {
opts.bench_count = Some(n);
i += 1;
}
}
}
}
"-h" | "--help" => {
print_help();
return;
}
arg if arg.starts_with('-') => {
let known: &[&str] = &[
"--repl",
"--eval",
"--check",
"--lsp",
"--dap",
"--doc",
"--backend",
"--out",
"--emit-nbc",
"--verify",
"--bench",
"--version",
"--verbose",
"--color",
"--help",
"--emit-stdlib-docs",
"-r",
"-e",
"-c",
"-V",
"-v",
"-h",
];
let suggestion = known
.iter()
.min_by_key(|k| levenshtein_distance(arg, k))
.filter(|k| levenshtein_distance(arg, k) <= 3);
eprint!("Error: Unknown option: {}", arg);
if let Some(sug) = suggestion {
eprint!(". Did you mean '{}'?", sug);
}
eprintln!();
eprintln!("Run with --help for usage information.");
std::process::exit(1);
}
arg => positional.push(arg.to_string()),
}
i += 1;
}
// Resolve color mode once after all args are parsed.
let use_color = color_enabled(&opts);
// Apply FFI policy
if opts.ffi_sandbox {
use nulang::ffi::native::FfiPolicy;
use std::collections::HashSet;
let allowed = opts.ffi_allow.clone().into_iter().collect::<HashSet<_>>();
let mut reg = nulang::ffi::native::FFI_REGISTRY
.get_or_init(|| std::sync::Mutex::new(nulang::ffi::native::FfiRegistry::new()))
.lock()
.unwrap();
reg.set_policy(FfiPolicy::Allowlist(allowed));
}
if opts.doc {
let root = match std::env::current_dir() {
Ok(dir) => dir,
Err(e) => {
eprintln!("Error: Cannot determine current directory: {}", e);
std::process::exit(1);
}
};
match nulang::docgen::write_project_docs(&root) {
Ok(path) => println!("Wrote {}", path.display()),
Err(e) => {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
}
return;
}
if let Some(dir) = opts.emit_stdlib_docs {
match emit_stdlib_docs(&dir) {
Ok(()) => println!("Stdlib docs written to {}", dir),
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
return;
}
if opts.lsp {
#[cfg(feature = "lsp")]
{
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async { nulang::lsp::run_lsp_server().await });
return;
}
#[cfg(not(feature = "lsp"))]
{
eprintln!("Error: this build was compiled without the 'lsp' feature.");
std::process::exit(1);
}
}
if opts.dap {
nulang::dap::run_dap_server();
return;
}
if let Some(n) = &opts.init {
let d = std::path::PathBuf::from(n);
if d.exists() {
eprintln!("dir exists");
std::process::exit(1);
}
std::fs::create_dir_all(&d).unwrap();
let m = d.join("main.nula");
std::fs::write(
&m,
format!(
"// {} - Nulang experiment\nperform IO.print(\"Hello!\")\n",
n
),
)
.unwrap();
println!("Created {}", m.display());
return;
}
if let Some(c) = &opts.explain {
use nulang::types::ErrorCode;
let e = match c.to_uppercase().as_str() {
"E001" => ErrorCode::E001UnclosedDelimiter,
"E002" => ErrorCode::E002UnboundVariable,
"E003" => ErrorCode::E003TypeMismatch,
"E004" => ErrorCode::E004MissingEffect,
"E005" => ErrorCode::E005SendabilityViolation,
"E006" => ErrorCode::E006LinearUseAfterConsume,
"E007" => ErrorCode::E007InfiniteType,
"E008" => ErrorCode::E008FieldNotFound,
"E009" => ErrorCode::E009WrongArity,
"E010" => ErrorCode::E010MatchNoArms,
"E011" => ErrorCode::E011StepLimitExceeded,
"E012" => ErrorCode::E012UnhandledEffect,
_ => {
eprintln!("Unknown: {}", c);
std::process::exit(1);
}
};
println!("{}", e.explain());
return;
}
if let Some(p) = &opts.watch {
let p = p.clone();
let v = opts.verbose;
let b = opts.backend.clone();
let uc = color_enabled(&opts);
eprintln!("Watching {}...", p);
let mut lm = std::fs::metadata(&p).ok().and_then(|m| m.modified().ok());
loop {
std::thread::sleep(std::time::Duration::from_millis(500));
let cm = std::fs::metadata(&p).ok().and_then(|m| m.modified().ok());
if cm != lm {
lm = cm;
eprintln!("\n--- {} ---", p);
if let Ok(s) = std::fs::read_to_string(&p) {
if let Err(e) = run_source(&s, Some(&p), v, &b, None, None, &opts.target) {
print_error(&e, uc);
}
}
}
}
}
if opts.repl {
let mut repl = Repl::new();
repl.run();
return;
}
if let Some(code) = opts.eval_code {
if opts.emit_nbc {
let out = opts
.out_file
.clone()
.unwrap_or_else(|| "out.nbc".to_string());
if let Err(e) = compile_source_to_nbc(&code, &out) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
return;
}
if let Some(n) = opts.bench_count {
if let Err(e) = run_bench(
|| {
run_source(
&code,
None,
opts.verbose,
&opts.backend,
opts.out_file.as_deref(),
opts.metrics_port,
&opts.target,
)
},
n,
) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
} else {
if let Err(e) = run_source(
&code,
None,
opts.verbose,
&opts.backend,
opts.out_file.as_deref(),
opts.metrics_port,
&opts.target,
) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
}
}
if let Some(path) = opts.check_file {
let source = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) => {
eprintln!("Error: Cannot read file '{}': {}", path, e);
std::process::exit(1);
}
};
if let Err(e) = check_source(&source, Some(&path), opts.verbose, opts.all_errors) {
let code = exit_code(&e);
if opts.all_errors {
let all = collect_all_frontend_errors(&source, Some(&path));
if all.is_empty() {
print_error(&e, use_color);
} else {
for err in &all {
print_error(err, use_color);
}
}
} else {
print_error(&e, use_color);
}
std::process::exit(code);
}
println!("Type check passed.");
return;
}
// Run a source file, or a pre-compiled `.nbc` artifact.
if !positional.is_empty() {
let path = &positional[0];
// A `.nbc` artifact: load and run directly without invoking the
// compiler. This is the durable-distribution path — a `.nbc` minted
// in 2026 runs on any conforming runtime in 2126.
if path.ends_with(".nbc") {
if let Err(e) = run_nbc_file(path, opts.verify_source.as_deref()) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
return;
}
let source = match std::fs::read_to_string(path) {
Ok(s) => s,
Err(e) => {
eprintln!("Error: Cannot read file '{}': {}", path, e);
std::process::exit(1);
}
};
// `--emit-nbc`: compile to a `.nbc` artifact and write it, don't run.
if opts.emit_nbc {
let out = opts.out_file.clone().unwrap_or_else(|| {
// foo.nula -> foo.nbc; anything else -> <path>.nbc
if let Some(stem) = path.strip_suffix(".nula") {
format!("{stem}.nbc")
} else {
format!("{path}.nbc")
}
});
if let Err(e) = compile_source_to_nbc(&source, &out) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
return;
}
if let Some(n) = opts.bench_count {
let verbose = opts.verbose;
let backend = &opts.backend;
let out_file = opts.out_file.as_deref();
if let Err(e) = run_bench(
|| {
run_source(
&source,
Some(path),
verbose,
backend,
out_file,
opts.metrics_port,
&opts.target,
)
},
n,
) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
} else {
if let Err(e) = run_source(
&source,
Some(path),
opts.verbose,
&opts.backend,
opts.out_file.as_deref(),
opts.metrics_port,
&opts.target,
) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
// Metrics node: the metrics server runs on a background thread and
// would die with the process once the program finishes. When
// `--metrics-port` is set, stay alive so /metrics keeps serving
// the final snapshot published by run_with_runtime (same contract
// as `registry serve`). Stop with Ctrl-C.
if let Some(port) = opts.metrics_port {
eprintln!("Program finished; serving /metrics on :{port} (Ctrl-C to stop)");
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
}
return;
}
// No arguments and no options: if stdin is piped, execute as script.
if !std::io::stdin().is_terminal() {
let mut source = String::new();
std::io::stdin()
.read_to_string(&mut source)
.expect("Failed to read stdin");
if let Err(e) = run_source(
&source,
None,
opts.verbose,
&opts.backend,
opts.out_file.as_deref(),
opts.metrics_port,
&opts.target,
) {
print_error(&e, use_color);
std::process::exit(exit_code(&e));
}
return;
}
let mut repl = Repl::new();
repl.run();
}
struct Options {
repl: bool,
eval_code: Option<String>,
check_file: Option<String>,
lsp: bool,
dap: bool,
doc: bool,
verbose: bool,
backend: String,
out_file: Option<String>,
/// Compile the input to a `.nbc` artifact and write it, don't run.
emit_nbc: bool,
/// When running a `.nbc` artifact, verify its recorded source hash against
/// this source file before executing. Refuses on mismatch.
verify_source: Option<String>,
/// Output directory for --emit-stdlib-docs.
emit_stdlib_docs: Option<String>,
/// Color mode: "auto" (default), "always", or "never".
color: String,
init: Option<String>,
watch: Option<String>,
explain: Option<String>,
all_errors: bool,
bench_count: Option<usize>,
/// Start a Prometheus-format metrics server on this port.
metrics_port: Option<u16>,
ffi_sandbox: bool,
ffi_allow: Vec<String>,
/// Target ISA for AOT compilation: native (default), ptx, riscv64
target: String,
}
impl Default for Options {
fn default() -> Self {
Options {
repl: false,
eval_code: None,
check_file: None,
lsp: false,
dap: false,
doc: false,
verbose: false,
backend: "bytecode".to_string(),
out_file: None,
emit_nbc: false,
verify_source: None,
emit_stdlib_docs: None,
color: "auto".to_string(),
init: None,
watch: None,
explain: None,
all_errors: false,
bench_count: None,
metrics_port: None,
ffi_sandbox: false,
ffi_allow: Vec::new(),
target: "native".to_string(),
}
}
}
fn print_help() {
println!("Usage: nulang [OPTIONS] <FILE>");
println!(" nulang --repl");
println!(" nulang --eval <CODE>");
println!(" nulang --check <FILE>");
println!(" nulang --lsp");
println!(" nulang --dap");
println!(" nulang fmt [--check] [<file>]");
println!(" nulang node --listen <ADDR> [--seed <ADDR>] [--expected-nodes <N>]");
println!(" nulang --doc");
println!();
println!("Options:");
println!(" -r, --repl Start interactive REPL");
println!(" -e, --eval Evaluate a code string");
println!(" -c, --check Type-check a file (don't run)");
println!(" --doc Generate Markdown API docs (docs/api.md)");
println!(" --emit-stdlib-docs <dir> Generate per-effect stdlib Markdown docs into <dir>");
println!(" --lsp Start Language Server (stdio)");
println!(" --dap Start Debug Adapter (stdio; program via launch request)");
print!(" --backend <b> Backend: bytecode (default) | native | core-vm");
if cfg!(feature = "wasm-backend") {
print!(" | wasm | wasm-run | wasm-aot");
}
println!();
println!(" core-vm: frozen Core interpreter (Stage 3 bootstrap)");
println!(" native: pure-functional subset only (no effects,");
println!(" actors, or FFI — errors name the unsupported");
println!(" construct; use bytecode for full-language programs)");
if cfg!(feature = "wasm-backend") {
println!(" wasm*: IO.print/read only (no user-defined effect");
println!(" handlers, no actor mailbox)");
}
if cfg!(feature = "wasmfx-backend") {
println!(" wasmfx*: suspending effects lower to WasmFX stack");
println!(" switching (LLM.ask, Signal.wait, ReceiveWait)");
}
println!(" --target <t> Target ISA for native backend: native (default) | ptx | riscv64");
if cfg!(feature = "wasm-backend") {
println!(" --out <file> Output file for WASM backends (default: out.wasm)");
}
println!(" --out <file> Output path for --emit-nbc (default: <FILE> with .nbc extension)");
println!(" <FILE>.nbc Run a pre-compiled .nbc artifact directly (no compiler invoked)");
println!(
" --verify <src> When running a .nbc artifact, verify its source hash against <src>"
);
println!(
" nula <cmd> Package manager (new, init, build, build-wasm, test, run, add, remove, watch, doc, list, clean)"
);
println!(" --version, -V Print version and exit");
println!(" init <name> Scaffold experiment");
println!(" --watch <file> Re-run on changes");
println!(" --explain <CODE> Error code help");
println!(" --all-errors Report all type errors (not just the first)");
println!(" --bench [N] Benchmark: run N times (default 10), print timing stats");
println!(" fmt [--check] [<file>] Format file(s); no file → all src/**/*.nula");
println!(" -v, --verbose Show bytecode and AST");
println!(" --metrics-port <N> Start Prometheus metrics server on port N");
println!(" --color auto|always|never Colorize error output (default: auto)");
println!(" -h, --help Show this help message");
}
/// Generate per-effect stdlib Markdown docs into the given directory.
fn emit_stdlib_docs(dir: &str) -> Result<(), String> {
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
let out_dir = PathBuf::from(dir);
fs::create_dir_all(&out_dir)
.map_err(|e| format!("Cannot create directory '{}': {}", dir, e))?;
let stdlib = StdLib::new();
let mut by_effect: BTreeMap<&str, Vec<&nulang::stdlib::BuiltinOp>> = BTreeMap::new();
for op in stdlib.ops() {
by_effect.entry(op.effect).or_default().push(op);
}
for (&effect_name, ops) in &by_effect {
// Build a per-effect Starlight docs page.
// These files are auto-generated — never edit them by hand.
// Source of truth: `src/stdlib.rs` (the `StdLib::new()` registry).
let mut page = String::new();
page.push_str("---\n");
page.push_str(&format!("title: \"{} Effect\"\n", effect_name));
page.push_str(&format!(
"description: \"Built-in {} effect operations (auto-generated from src/stdlib.rs)\"\n",
effect_name
));
page.push_str("sidebar:\n");
page.push_str(&format!(" label: \"{}\"\n", effect_name));
page.push_str("editUrl: false\n");
page.push_str("---\n\n");
page.push_str("> **This page is auto-generated from `src/stdlib.rs`.**\n");
page.push_str(
"> Do not edit it by hand — your changes will be overwritten on the next CI run.\n",
);
page.push_str("> To add or update a built-in operation, edit the `StdLib::new()` registry in `src/stdlib.rs`.\n\n");
page.push_str(&format!("# {} Effect\n\n", effect_name));
page.push_str(&format!(
"The `{}` effect provides the following built-in operations, wired into the VM and runtime.\n\n",
effect_name
));
page.push_str("| Operation | Signature | Description |\n");
page.push_str("|-----------|-----------|-------------|\n");
for op in ops {
page.push_str(&format!(
"| `{}` | `{}` | {} |\n",
op.name,
op.signature.replace('|', "\\|"),
op.description
));
}
page.push_str(&format!(
"\n_Implementation site: {}_\n",
match ops.first().map(|o| o.implemented_in) {
Some(nulang::stdlib::ImplSite::StandaloneVm) => "Standalone VM",
Some(nulang::stdlib::ImplSite::RuntimeHost) => "Runtime Host",
None => "Unknown",
}
));
let filename = out_dir.join(format!("{}.md", effect_name.to_lowercase()));
let mut file = fs::File::create(&filename)
.map_err(|e| format!("Cannot create '{}': {}", filename.display(), e))?;
file.write_all(page.as_bytes())
.map_err(|e| format!("Cannot write '{}': {}", filename.display(), e))?;
}
Ok(())
}
/// Run a distributed Nulang node: parse arguments, create a Runtime,
/// enable distribution, join a seed cluster if requested, and run forever.
fn run_node_cmd(args: &[String]) -> NuResult<()> {
let mut listen_addr = "127.0.0.1:9000".to_string();
let mut seed_addr: Option<String> = None;
let mut expected_nodes: Option<usize> = None;
let mut tls_cert: Option<String> = None;
let mut tls_key: Option<String> = None;
let mut tls_ca: Option<String> = None;
let mut plaintext = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--listen" => {
if i + 1 < args.len() {
listen_addr = args[i + 1].clone();
i += 1;
} else {
eprintln!("Error: --listen requires an address argument");
std::process::exit(1);
}
}
"--seed" => {
if i + 1 < args.len() {
seed_addr = Some(args[i + 1].clone());
i += 1;
} else {
eprintln!("Error: --seed requires an address argument");
std::process::exit(1);
}
}