forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
1181 lines (1111 loc) · 39.7 KB
/
Copy pathmain.rs
File metadata and controls
1181 lines (1111 loc) · 39.7 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
#![allow(clippy::print_stderr, clippy::print_stdout)]
mod abi;
mod build;
mod check;
mod cli;
mod dependency_diagnostics;
mod doc;
#[cfg(feature = "doc-server")]
mod doc_serve;
mod metadata_input;
mod report;
mod test;
#[cfg(not(target_arch = "wasm32"))]
mod tree;
mod workspace_ingot;
use std::fs;
use std::sync::OnceLock;
use build::build;
use camino::Utf8PathBuf;
use check::check;
use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
use colored::Colorize;
use fmt as fe_fmt;
use similar::{ChangeTag, TextDiff};
use walkdir::WalkDir;
use crate::test::TestDebugOptions;
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ColorChoice {
Auto,
Always,
Never,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum BuildEmit {
Bytecode,
RuntimeBytecode,
Ir,
Abi,
Metadata,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum TestEmit {
Ir,
Rmir,
}
fn cli_version() -> &'static str {
static VERSION: OnceLock<String> = OnceLock::new();
VERSION
.get_or_init(|| match option_env!("FE_GIT_HASH") {
Some(hash) if !hash.is_empty() => format!("{} ({hash})", env!("CARGO_PKG_VERSION")),
_ => env!("CARGO_PKG_VERSION").to_string(),
})
.as_str()
}
#[derive(Debug, Clone, Parser)]
#[command(version = cli_version(), about, long_about = None)]
pub struct Options {
/// Control colored output (auto, always, never).
#[arg(long, global = true, value_enum, default_value = "auto")]
pub color: ColorChoice,
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Clone, Args)]
pub struct OptimizeArgs {
/// Optimization level.
///
/// 0 = none
/// 1 = fast compilation, usually close to `2` gas and bytecode size with Sonatina
/// 2 = optimizes heavily for runtime gas
/// s = size-oriented (currently similar to `2`)
///
/// Defaults to `1`
///
#[arg(
long = "optimize",
short = 'O',
value_name = "LEVEL",
value_parser = ["0", "1", "2", "s"],
verbatim_doc_comment
)]
optimize: Option<String>,
}
impl OptimizeArgs {
fn as_deref(&self) -> Option<&str> {
self.optimize.as_deref()
}
}
#[derive(Debug, Clone, Subcommand)]
pub enum Command {
/// Compile Fe code to EVM bytecode.
Build {
/// Path to an ingot/workspace directory (containing fe.toml), a workspace member name, or a .fe file.
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
/// Build artifacts for a single workspace ingot by member name.
///
/// This requires targeting a workspace root path.
#[arg(short = 'i', long = "ingot", value_name = "INGOT")]
ingot: Option<String>,
/// Treat a `.fe` file target as standalone, even if it is inside an ingot.
#[arg(long)]
standalone: bool,
/// Rebuild from a `<Contract>.metadata.json` recompilation input produced by
/// `--emit metadata` (`-` reads the JSON from stdin).
///
/// The recorded project is materialized into a temporary directory and built with
/// the settings captured in the metadata. Artifacts default to `./out`.
#[arg(
long,
value_name = "PATH",
conflicts_with_all = ["path", "ingot", "standalone", "report"]
)]
from_metadata: Option<Utf8PathBuf>,
/// Build a specific contract by name (defaults to all contracts in the target).
#[arg(long)]
contract: Option<String>,
#[command(flatten)]
optimize: OptimizeArgs,
/// Output directory for artifacts.
#[arg(long)]
out_dir: Option<Utf8PathBuf>,
/// Compilation profile to use when resolving profile-aware config.
#[arg(long, default_value = "release", value_name = "PROFILE")]
profile: String,
/// Comma-delimited artifacts to emit.
#[arg(
long,
short = 'e',
value_enum,
value_delimiter = ',',
default_value = "bytecode,runtime-bytecode,abi"
)]
emit: Vec<BuildEmit>,
/// Write a debugging report as a `.tar.gz` file (includes sources, IR, backend output, and bytecode artifacts).
#[arg(long)]
report: bool,
/// Output path for `--report` (must end with `.tar.gz`).
#[arg(
long,
value_name = "OUT",
default_value = "fe-build-report.tar.gz",
requires = "report"
)]
report_out: Utf8PathBuf,
/// Only write the report if `fe build` fails.
#[arg(long, requires = "report")]
report_failed_only: bool,
/// Use recovery mode when parsing.
#[arg(long, default_value = "false")]
recovery_mode: bool,
},
Check {
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
/// Check a single workspace ingot by member name.
///
/// This requires targeting a workspace root path.
#[arg(short = 'i', long = "ingot", value_name = "INGOT")]
ingot: Option<String>,
/// Treat a `.fe` file target as standalone, even if it is inside an ingot.
#[arg(long)]
standalone: bool,
/// Compilation profile to use when resolving profile-aware config.
#[arg(long, default_value = "dev", value_name = "PROFILE")]
profile: String,
#[arg(long)]
dump_mir: bool,
/// Write a debugging report as a `.tar.gz` file (includes sources and diagnostics).
#[arg(long)]
report: bool,
/// Output path for `--report` (must end with `.tar.gz`).
#[arg(
long,
value_name = "OUT",
default_value = "fe-check-report.tar.gz",
requires = "report"
)]
report_out: Utf8PathBuf,
/// Only write the report if `fe check` fails.
#[arg(long, requires = "report")]
report_failed_only: bool,
/// Use recovery mode when parsing.
#[arg(long, default_value = "false")]
recovery_mode: bool,
},
/// Generate documentation for a Fe project
Doc {
/// Path to a .fe file or ingot directory
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
/// Output directory for generated docs
#[arg(short, long)]
output: Option<Utf8PathBuf>,
/// Include builtin ingots (core, std) in generated docs
#[arg(long)]
builtins: bool,
/// Load core/std from a directory on disk instead of the embedded version.
/// The directory should contain `core/` and `std/` subdirectories.
#[arg(long)]
stdlib_path: Option<Utf8PathBuf>,
/// Include `#[test]` functions in generated docs.
///
/// Off by default to keep sidebars focused on the public API surface;
/// turn on for a test-centric overview of an ingot.
#[arg(long)]
include_tests: bool,
#[command(subcommand)]
action: Option<DocAction>,
},
#[cfg(not(target_arch = "wasm32"))]
Tree {
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
},
/// Format Fe source code.
Fmt {
/// Path to a Fe source file or directory. If omitted, formats all .fe files in the current project.
path: Option<Utf8PathBuf>,
/// Check if files are formatted, but do not write changes.
#[arg(long)]
check: bool,
},
/// Run Fe tests in a file or directory.
Test {
/// Path(s) to .fe files or directories containing ingots with tests.
///
/// Supports glob patterns (e.g. `crates/fe/tests/fixtures/fe_test/*.fe`).
///
/// When omitted, defaults to the current project root (like `cargo test`).
#[arg(value_name = "PATH", num_args = 0..)]
paths: Vec<Utf8PathBuf>,
/// Run tests for a single workspace ingot by member name
///
/// This requires targeting a workspace root path.
#[arg(short = 'i', long = "ingot", value_name = "INGOT")]
ingot: Option<String>,
/// Optional filter pattern for test names.
#[arg(short, long)]
filter: Option<String>,
/// Number of suites to run in parallel (0 = auto).
#[arg(long, default_value_t = 8, value_name = "N")]
jobs: usize,
/// Run suites as grouped jobs instead of splitting into per-test jobs.
#[arg(long)]
grouped: bool,
/// Show event logs from test execution.
#[arg(long)]
show_logs: bool,
/// Write test-module IR artifacts (`ir`, `rmir`) to the suite `out/` directory.
#[arg(long, value_enum, value_delimiter = ',')]
emit: Vec<TestEmit>,
/// Compilation profile to use when resolving profile-aware config.
#[arg(long, default_value = "test", value_name = "PROFILE")]
profile: String,
#[command(flatten)]
optimize: OptimizeArgs,
/// Trace executed EVM opcodes while running tests.
#[arg(long)]
trace_evm: bool,
/// How many EVM steps to keep in the trace ring buffer.
#[arg(long, default_value_t = 200)]
trace_evm_keep: usize,
/// How many stack items to print per EVM step in traces.
#[arg(long, default_value_t = 16)]
trace_evm_stack_n: usize,
/// Directory to write debug outputs (traces) into.
#[arg(long)]
debug_dir: Option<Utf8PathBuf>,
/// Write a debugging report as a `.tar.gz` file (includes sources, IR, bytecode, traces).
#[arg(long)]
report: bool,
/// Output path for `--report` (must end with `.tar.gz`).
#[arg(
long,
value_name = "OUT",
default_value = "fe-test-report.tar.gz",
requires = "report"
)]
report_out: Utf8PathBuf,
/// Write one `.tar.gz` report per input suite into this directory.
///
/// Useful when running a glob over many fixtures: each failing suite can be shared as a
/// standalone artifact.
#[arg(long, value_name = "DIR", conflicts_with = "report")]
report_dir: Option<Utf8PathBuf>,
/// When used with `--report-dir`, only write reports for suites that failed.
#[arg(long, requires = "report_dir")]
report_failed_only: bool,
/// Print a normalized call trace for each test.
#[arg(long)]
call_trace: bool,
/// Use recovery mode when parsing.
#[arg(long, default_value = "false")]
recovery_mode: bool,
},
/// Run gas benchmarks comparing Fe (Sonatina) against Solidity.
Bench {
/// Path to benchmark fixtures directory.
#[arg(value_name = "PATH", default_value = "bench_fixtures")]
path: Utf8PathBuf,
/// Filter benchmarks by name.
#[arg(short, long)]
filter: Option<String>,
/// solc binary to use (overrides FE_SOLC_PATH).
#[arg(long)]
solc: Option<String>,
/// Output directory for CSV reports.
#[arg(long, short)]
output: Option<Utf8PathBuf>,
},
/// Create a new ingot or workspace.
New {
/// Path to create the ingot or workspace in.
path: Utf8PathBuf,
/// Create a workspace instead of a single ingot.
#[arg(long)]
workspace: bool,
/// Override the default inferred name.
#[arg(long)]
name: Option<String>,
/// Override the default version (default: 0.1.0).
#[arg(long)]
version: Option<String>,
},
/// Generate shell completion scripts.
Completion {
/// Shell to generate completions for
#[arg(value_name = "shell")]
shell: clap_complete::Shell,
},
/// Generate LSIF index for code navigation.
Lsif {
/// Path to the ingot directory.
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
/// Output file (defaults to stdout).
#[arg(short, long)]
output: Option<Utf8PathBuf>,
},
/// Find the workspace or ingot root for a given path.
///
/// Walks up from the given path (or cwd) looking for fe.toml files.
/// Prints the workspace root if found, otherwise the nearest ingot root.
/// Useful for editor integrations that need to determine the project root.
Root {
/// Path to start searching from (default: current directory).
path: Option<Utf8PathBuf>,
},
/// Start the Fe language server (LSP).
#[cfg(feature = "lsp")]
Lsp {
/// Set the workspace root directory.
///
/// Used as the server's working directory. When the LSP client doesn't
/// send workspace folders, this directory is used as the fallback root
/// for ingot/workspace discovery.
#[arg(long)]
root: Option<Utf8PathBuf>,
/// Port for the combined doc+LSP server (default: auto-pick).
#[arg(long)]
port: Option<u16>,
/// Communication mode (default: stdio).
#[command(subcommand)]
mode: Option<LspMode>,
},
/// Generate SCIP index for code navigation.
Scip {
/// Path to the ingot directory.
#[arg(default_value_t = default_project_path())]
path: Utf8PathBuf,
/// Output file (defaults to index.scip).
#[arg(short, long, default_value = "index.scip")]
output: Utf8PathBuf,
},
}
#[derive(Debug, Clone, Subcommand)]
pub enum DocAction {
/// Generate a documentation site (separate files by default).
///
/// Default output: docs.json, index.html, fe-web.js, fe-highlight.css.
/// Use --self-contained for a single index.html with everything inlined.
Static {
/// Output a single self-contained index.html instead of separate files
#[arg(long)]
self_contained: bool,
},
/// Produce docs.json (DocIndex + SCIP data) for web components.
///
/// The JSON can be consumed by <fe-code-block src="docs.json">,
/// <fe-doc-item src="docs.json">, and <fe-doc-viewer src="docs.json">.
Json {
/// Merge into an existing docs.json (deduplicates items, symbols, and files)
#[arg(long)]
merge: Option<Utf8PathBuf>,
},
/// Write the fe-web.js component bundle and fe-highlight.css.
///
/// Does not require compiling a project — just outputs the reusable assets.
Bundle {
/// Also write fe-highlight.css alongside the bundle
#[arg(long)]
with_css: bool,
},
/// Generate Starlight-compatible markdown pages
Pages {
/// Base URL prefix for generated links
#[arg(long, default_value = "/api")]
base_url: String,
},
/// Start a live documentation server with hot reload
Serve {
/// Port for HTTP server
#[arg(long, default_value = "8080")]
port: u16,
},
}
#[cfg(feature = "lsp")]
#[derive(Debug, Clone, Subcommand)]
pub enum LspMode {
/// Start with TCP transport instead of stdio.
Tcp {
/// Port to listen on.
#[arg(short, long, default_value_t = 4242)]
port: u16,
/// Timeout in seconds to shut down if no clients are connected.
#[arg(short, long, default_value_t = 10)]
timeout: u64,
},
}
fn default_project_path() -> Utf8PathBuf {
Utf8PathBuf::from(".")
}
fn main() {
let opts = Options::parse();
run(&opts);
}
pub fn run(opts: &Options) {
let preference = match opts.color {
ColorChoice::Auto => common::color::ColorPreference::Auto,
ColorChoice::Always => common::color::ColorPreference::Always,
ColorChoice::Never => common::color::ColorPreference::Never,
};
common::color::set_color_preference(preference);
match preference {
common::color::ColorPreference::Auto => colored::control::unset_override(),
common::color::ColorPreference::Always => colored::control::set_override(true),
common::color::ColorPreference::Never => colored::control::set_override(false),
}
match &opts.command {
Command::Build {
path,
ingot,
standalone,
from_metadata,
contract,
optimize,
out_dir,
profile,
emit,
report,
report_out,
report_failed_only,
recovery_mode,
} => {
if let Some(metadata_path) = from_metadata {
build::build_from_metadata(
metadata_path,
contract.as_deref(),
optimize.as_deref(),
emit,
out_dir.as_ref(),
profile,
*recovery_mode,
);
return;
}
let opt_level = match effective_opt_level(optimize.as_deref()) {
Ok(level) => level,
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
};
build(
path,
ingot.as_deref(),
*standalone,
contract.as_deref(),
opt_level,
emit,
out_dir.as_ref(),
profile,
(*report).then_some(report_out),
*report_failed_only,
*recovery_mode,
)
}
Command::Check {
path,
ingot,
standalone,
profile,
dump_mir,
report,
report_out,
report_failed_only,
recovery_mode,
} => {
match check(
path,
ingot.as_deref(),
*standalone,
profile,
*dump_mir,
(*report).then_some(report_out),
*report_failed_only,
*recovery_mode,
) {
Ok(has_errors) => {
if has_errors {
std::process::exit(1);
}
}
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
}
}
Command::Doc {
path,
output,
builtins,
stdlib_path,
include_tests,
action,
} => {
if let Some(DocAction::Bundle { with_css }) = action {
let output_dir = output.clone().unwrap_or_else(|| Utf8PathBuf::from("."));
doc::write_bundle(&output_dir.join("fe-web.js"));
if *with_css {
doc::write_highlight_css(&output_dir.join("fe-highlight.css"));
doc::write_styles_css(&output_dir.join("styles.css"));
}
} else {
doc::generate_docs(
path,
output.as_ref(),
*builtins,
stdlib_path.as_ref(),
*include_tests,
action.as_ref(),
);
}
}
#[cfg(not(target_arch = "wasm32"))]
Command::Tree { path } => {
if tree::print_tree(path) {
std::process::exit(1);
}
}
Command::Fmt { path, check } => {
run_fmt(path.as_ref(), *check);
}
Command::Test {
paths,
ingot,
filter,
jobs,
grouped,
show_logs,
emit,
profile,
optimize,
trace_evm,
trace_evm_keep,
trace_evm_stack_n,
debug_dir,
report,
report_out,
report_dir,
report_failed_only,
call_trace,
recovery_mode,
} => {
let opt_level = match effective_opt_level(optimize.as_deref()) {
Ok(level) => level,
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
};
let debug = TestDebugOptions {
trace_evm: *trace_evm,
trace_evm_keep: *trace_evm_keep,
trace_evm_stack_n: *trace_evm_stack_n,
debug_dir: debug_dir.clone(),
};
let paths = if paths.is_empty() {
vec![default_project_path()]
} else {
paths.clone()
};
match test::run_tests(
&paths,
ingot.as_deref(),
filter.as_deref(),
*jobs,
*grouped,
*show_logs,
profile,
opt_level,
emit,
&debug,
(*report).then_some(report_out),
report_dir.as_ref(),
*report_failed_only,
*call_trace,
*recovery_mode,
) {
Ok(has_failures) => {
if has_failures {
std::process::exit(1);
}
}
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
}
}
Command::Bench {
path,
filter,
solc,
output,
} => match fe::bench::run_benchmarks(
path.as_path(),
filter.as_deref(),
solc.as_deref(),
output.as_ref().map(|p| p.as_path()),
) {
Ok(()) => {}
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
},
Command::New {
path,
workspace,
name,
version,
} => {
if let Err(err) = cli::new::run(path, *workspace, name.as_deref(), version.as_deref()) {
eprintln!("Error: {err}");
std::process::exit(1);
}
}
Command::Completion { shell } => {
clap_complete::generate(
*shell,
&mut Options::command(),
"fe",
&mut std::io::stdout(),
);
}
Command::Root { path } => {
run_root(path.as_ref());
}
#[cfg(feature = "lsp")]
Command::Lsp { root, port, mode } => {
// If --root is explicit, use it. Otherwise, auto-discover from cwd.
let resolved_root = match root {
Some(r) => Some(r.canonicalize_utf8().unwrap_or_else(|e| {
eprintln!("Error: invalid --root path {r}: {e}");
std::process::exit(1);
})),
None => driver::files::find_project_root(),
};
if let Some(root) = &resolved_root {
std::env::set_current_dir(root.as_std_path()).unwrap_or_else(|e| {
eprintln!("Error: cannot chdir to {root}: {e}");
std::process::exit(1);
});
}
let rt = tokio::runtime::Runtime::new().unwrap_or_else(|e| {
eprintln!("Error creating async runtime: {e}");
std::process::exit(1);
});
rt.block_on(async {
unsafe {
std::env::set_var("RUST_BACKTRACE", "full");
}
language_server::setup_panic_hook();
match mode {
Some(LspMode::Tcp { port, timeout }) => {
language_server::run_tcp_server(
*port,
std::time::Duration::from_secs(*timeout),
)
.await;
}
None => {
run_lsp_with_combined_server(resolved_root, *port).await;
}
}
});
}
Command::Lsif { path, output } => {
run_lsif(path, output.as_ref());
}
Command::Scip { path, output } => {
run_scip(path, output);
}
}
}
#[cfg(feature = "lsp")]
async fn run_lsp_with_combined_server(resolved_root: Option<Utf8PathBuf>, port: Option<u16>) {
use tokio::net::TcpListener;
// Bind the combined server listener
let addr = format!("127.0.0.1:{}", port.unwrap_or(0));
let listener = match TcpListener::bind(&addr).await {
Ok(l) => l,
Err(e) => {
eprintln!("Warning: could not bind combined server: {e}");
language_server::run_stdio_server(None).await;
return;
}
};
let actual_port = listener.local_addr().unwrap().port();
// Generate doc HTML for the workspace (best-effort)
let doc_html = generate_lsp_doc_html(resolved_root.as_ref());
eprintln!("Documentation: http://127.0.0.1:{actual_port}");
// Write .fe-lsp.json for discovery
let workspace_root_path = resolved_root
.as_ref()
.map(|r| r.as_std_path().to_path_buf())
.unwrap_or_else(|| std::env::current_dir().unwrap());
// Inspect any existing .fe-lsp.json. This is purely diagnostic: we
// always proceed with writing our own, since the file is a discovery
// pointer, not a lock. The outcome is still important for triage:
// stale files mean a previous crash, sibling-live means Zed respawned
// us without shutting the old instance down, and a root-mismatch
// means we're fighting with another instance over workspace root
// detection.
//
// These diagnostics are emitted via `eprintln!` rather than `tracing`
// because the tracing subscriber isn't installed until later, inside
// `language_server::run_stdio_server` -> `setup_default_subscriber`.
// Zed captures stderr for its LSP log panel, so users still see the
// messages in the same place they'd see a `tracing::warn!`.
let workspace_root_display = workspace_root_path.display();
let our_pid = std::process::id();
match doc::ExistingInstanceCheck::inspect(&workspace_root_path) {
doc::ExistingInstanceCheck::None => {
// Nothing to report in the common case; keep startup quiet.
}
doc::ExistingInstanceCheck::StaleFound {
stale_pid,
recorded_workspace_root,
} => {
eprintln!(
"fe-language-server: removing stale .fe-lsp.json at {workspace_root_display} \
(previous pid {stale_pid} not alive; recorded workspace_root={recorded_workspace_root:?}). \
Previous instance likely crashed without cleanup."
);
doc::LspServerInfo::remove_from_workspace(&workspace_root_path);
}
doc::ExistingInstanceCheck::SiblingLive {
sibling_pid,
sibling_docs_url,
} => {
eprintln!(
"fe-language-server: another fe lsp instance (pid {sibling_pid}) is already \
running for workspace {workspace_root_display} (sibling_docs_url={sibling_docs_url:?}); \
overwriting .fe-lsp.json with our info (pid {our_pid}). Zed may have respawned \
us before the previous instance finished shutting down."
);
}
doc::ExistingInstanceCheck::RootMismatch {
other_pid,
other_workspace_root,
our_workspace_root,
} => {
eprintln!(
"fe-language-server: ROOT MISMATCH: existing .fe-lsp.json (pid {other_pid}) refers \
to workspace_root={other_workspace_root:?}, but we detected {our_workspace_root}. \
This usually means either a workspace-root detection bug or a pid-reuse false \
positive in is_alive(). To triage, check what the two processes think their \
workspace_folders are in the initialize params. Our pid is {our_pid}."
);
}
doc::ExistingInstanceCheck::Malformed => {
eprintln!(
"fe-language-server: removing malformed .fe-lsp.json at {workspace_root_display} \
(parse failed; probably a leftover from an older fe version)."
);
doc::LspServerInfo::remove_from_workspace(&workspace_root_path);
}
}
let server_info = doc::LspServerInfo {
pid: our_pid,
port: Some(actual_port),
workspace_root: Some(workspace_root_path.display().to_string()),
docs_url: Some(format!("http://127.0.0.1:{actual_port}")),
};
if let Err(e) = server_info.write_to_workspace(&workspace_root_path) {
eprintln!(
"fe-language-server: could not write .fe-lsp.json at {workspace_root_display}: {e}"
);
}
let config = language_server::CombinedServerConfig {
listener,
doc_html,
docs_url: Some(format!("http://127.0.0.1:{actual_port}")),
};
language_server::run_stdio_server(Some(config)).await;
// Cleanup on exit
doc::LspServerInfo::remove_from_workspace(&workspace_root_path);
}
/// Initial doc data generation from a workspace root.
///
/// Discovers ingots via `discover_and_init` (requires `&mut`), then delegates
/// Generate doc + SCIP data for a workspace. Used at LSP startup.
/// Regenerate doc + SCIP data via salsa-tracked functions.
#[cfg(feature = "lsp")]
fn regenerate_doc_data(
db: &mut driver::DriverDataBase,
workspace_root: &camino::Utf8Path,
) -> (String, Option<String>) {
let root_path = workspace_root
.canonicalize_utf8()
.unwrap_or_else(|_| workspace_root.to_owned());
if let Ok(root_url) = url::Url::from_directory_path(&root_path) {
let _discovered = driver::discover_and_init(db, &root_url);
semantic_indexing::doc::regenerate(db)
} else {
let json = serde_json::to_string(&fe_web::model::DocIndex::new()).unwrap();
(json, None)
}
}
/// Generate the doc HTML for the combined server.
///
/// Uses `discover_context` (same discovery the LS uses) to find all ingots
/// under the workspace root, so it works for:
/// - Single ingots (directory with fe.toml)
/// - Workspaces (fe.toml with [workspace] members)
/// - Directories containing multiple ingots without a root fe.toml
/// - Sentinel workspaces with members=[] (discovers child ingots)
#[cfg(feature = "lsp")]
fn generate_lsp_doc_html(resolved_root: Option<&Utf8PathBuf>) -> String {
let root_path = resolved_root
.cloned()
.unwrap_or_else(|| Utf8PathBuf::from("."));
let mut db = driver::DriverDataBase::default();
let (json, scip_json) = regenerate_doc_data(&mut db, &root_path);
// Parse back the index to get the title
let index: fe_web::model::DocIndex =
serde_json::from_str(&json).unwrap_or_else(|_| fe_web::model::DocIndex::new());
let title = if let Some(root) = index.modules.first() {
format!("{} — Fe Documentation", root.name)
} else {
"Fe Documentation".to_string()
};
let mut html = fe_web::assets::html_shell_full(&title, &json, scip_json.as_deref(), None);
// Append auto-connect script
let connect_script =
r#"<script>window.FE_LSP = connectLsp(`${location.protocol==='https:'?'wss:':'ws:'}://${location.host}/lsp`);</script>"#.to_string();
if let Some(pos) = html.rfind("</body>") {
html.insert_str(pos, &connect_script);
}
html
}
fn effective_opt_level(optimize: Option<&str>) -> Result<codegen::OptLevel, String> {
optimize.unwrap_or("1").parse()
}
fn run_lsif(path: &Utf8PathBuf, output: Option<&Utf8PathBuf>) {
use driver::DriverDataBase;
let mut db = DriverDataBase::default();
let canonical_path = match path.canonicalize_utf8() {
Ok(p) => p,
Err(_) => {
eprintln!("Error: Invalid or non-existent directory path: {path}");
std::process::exit(1);
}
};
let ingot_url = match url::Url::from_directory_path(canonical_path.as_str()) {
Ok(url) => url,
Err(_) => {
eprintln!("Error: Invalid directory path: {path}");
std::process::exit(1);
}
};
let had_init_diagnostics = driver::init_ingot(&mut db, &ingot_url);
if had_init_diagnostics {
eprintln!("Warning: ingot had initialization diagnostics");
}
let result = if let Some(output_path) = output {
let file = match std::fs::File::create(output_path.as_std_path()) {
Ok(f) => f,
Err(e) => {
eprintln!("Error creating output file: {e}");
std::process::exit(1);
}
};
let writer = std::io::BufWriter::new(file);
semantic_indexing::lsif::generate_lsif(&db, &ingot_url, writer)
} else {
let stdout = std::io::stdout().lock();
let writer = std::io::BufWriter::new(stdout);
semantic_indexing::lsif::generate_lsif(&db, &ingot_url, writer)
};
if let Err(e) = result {
eprintln!("Error generating LSIF: {e}");
std::process::exit(1);
}
}
fn run_scip(path: &Utf8PathBuf, output: &Utf8PathBuf) {
use driver::DriverDataBase;
let mut db = DriverDataBase::default();
let canonical_path = match path.canonicalize_utf8() {
Ok(p) => p,
Err(_) => {
eprintln!("Error: Invalid or non-existent directory path: {path}");
std::process::exit(1);
}
};
let ingot_url = match url::Url::from_directory_path(canonical_path.as_str()) {
Ok(url) => url,
Err(_) => {
eprintln!("Error: Invalid directory path: {path}");
std::process::exit(1);
}
};
let had_init_diagnostics = driver::init_ingot(&mut db, &ingot_url);
if had_init_diagnostics {
eprintln!("Warning: ingot had initialization diagnostics");
}
let result =
semantic_indexing::scip_batch::generate_scip(&db, &ingot_url).unwrap_or_else(|e| {
eprintln!("Error generating SCIP: {e}");
std::process::exit(1);
});
if let Err(e) = scip::write_message_to_file(output.as_std_path(), result.index) {
eprintln!("Error writing SCIP file: {e}");
std::process::exit(1);
}
}