1use regex::Regex;
6use seq_map::SeqMap;
7use source_map_cache::SourceMap;
8use source_map_cache::SourceMapWrapper;
9use std::env::current_dir;
10use std::io;
11use std::path::Path;
12use std::path::PathBuf;
13use std::str::FromStr;
14use swamp_analyzer::Analyzer;
15pub use swamp_analyzer::prelude::Program;
16use swamp_core::text::core_text;
17use swamp_dep_loader::{
18 DependencyParser, ParsedAstModule, parse_local_modules_and_get_order,
19 parse_single_module_from_text, swamp_registry_path,
20};
21use swamp_error_report::analyze::show_analyzer_error;
22use swamp_error_report::prelude::Kind;
23use swamp_error_report::{ScriptResolveError, prelude::show_script_resolve_error};
24use swamp_modules::modules::{ModuleRef, Modules};
25use swamp_modules::prelude::Module;
26use swamp_modules::symtbl::{SymbolTable, SymbolTableRef};
27use swamp_pretty_print::{ImplsDisplay, SourceMapDisplay, SymbolTableDisplay};
28use swamp_program_analyzer::analyze_modules_in_order;
29use swamp_semantic::err::Error;
30use swamp_semantic::{AssociatedImpls, ProgramState, formal_module_name};
31use swamp_std::std_text;
32use swamp_types::prelude::print_types;
33use time_dilation::ScopedTimer;
34use tiny_ver::TinyVersion;
35use tracing::{info, trace};
36
37pub const COMPILER_VERSION: &str = "0.0.0";
38pub const CORE_VERSION: &str = "core-0.0.0";
39
40pub fn analyze_ast_module_skip_expression(
43 analyzer: &mut Analyzer,
44 parsed_ast_module: &ParsedAstModule,
45) {
46 for definition in &parsed_ast_module.ast_module.definitions {
47 analyzer.analyze_definition(definition);
48 }
49}
50
51#[must_use]
52pub fn analyze_single_module(
53 state: &mut ProgramState,
54 default_symbol_table: SymbolTable,
55 modules: &Modules,
56 core_symbol_table: SymbolTableRef,
57 parsed_ast_module: &ParsedAstModule,
58 source_map: &SourceMap,
59 versioned_module_path: &[String],
60) -> SymbolTable {
61 let mut analyzer = Analyzer::new(
62 state,
63 modules,
64 core_symbol_table,
65 source_map,
66 versioned_module_path,
67 parsed_ast_module.file_id,
68 );
69
70 analyzer.shared.lookup_table = default_symbol_table;
71
72 analyze_ast_module_skip_expression(&mut analyzer, parsed_ast_module);
75
76 analyzer.shared.definition_table
77}
78
79pub fn create_source_map(registry_path: &Path, local_path: &Path) -> io::Result<SourceMap> {
80 trace!(?registry_path, ?local_path, "mounting source map");
81
82 let mut mounts = SeqMap::new();
83 mounts
84 .insert("crate".to_string(), local_path.to_path_buf())
85 .unwrap();
86
87 mounts
88 .insert("registry".to_string(), registry_path.to_path_buf())
89 .unwrap();
90
91 SourceMap::new(&mounts)
92}
93
94pub fn create_registry_source_map(registry_path: &Path) -> io::Result<SourceMap> {
95 trace!(?registry_path, "mounting registry path source map");
96
97 let mut mounts = SeqMap::new();
98 mounts
99 .insert("registry".to_string(), registry_path.to_path_buf())
100 .unwrap();
101
102 SourceMap::new(&mounts)
103}
104
105#[derive(Debug)]
106pub struct BootstrapResult {
107 pub program: Program,
108 pub core_module_path: Vec<String>,
109}
110
111pub fn bootstrap_modules(
118 source_map: &mut SourceMap,
119) -> Result<BootstrapResult, ScriptResolveError> {
120 let compiler_version = TinyVersion::from_str(COMPILER_VERSION).unwrap();
121 trace!(%compiler_version, "booting up compiler");
122 let mut state = ProgramState::new();
123
124 let mut modules = Modules::new();
125
126 let core_module_with_intrinsics =
127 swamp_core::create_module(&compiler_version, &mut state.types);
128
129 let core_path = core_module_with_intrinsics.symbol_table.module_path();
130 let core_parsed_ast_module =
131 parse_single_module_from_text(source_map, &core_path, &core_text())?;
132
133 let half_completed_core_symbol_table = core_module_with_intrinsics.symbol_table.clone();
134 let default_symbol_table_for_core_with_intrinsics = half_completed_core_symbol_table.clone();
135
136 let mut analyzed_core_symbol_table = analyze_single_module(
137 &mut state,
138 default_symbol_table_for_core_with_intrinsics.clone(),
139 &modules,
140 half_completed_core_symbol_table.clone().into(),
141 &core_parsed_ast_module,
142 source_map,
143 &core_module_with_intrinsics.symbol_table.module_path(),
144 );
145
146 analyzed_core_symbol_table
148 .extend_basic_from(&core_module_with_intrinsics.symbol_table)
149 .expect("couldn't extend core");
150 let mut default_module = swamp_core::create_module_with_name(&[]);
151 default_module
152 .symbol_table
153 .extend_alias_from(&analyzed_core_symbol_table)
154 .expect("extend basic alias and functions from core");
155
156 let core_module = Module::new(analyzed_core_symbol_table, vec![], None);
157 modules.add(ModuleRef::from(core_module));
158
159 let source_map_display = SourceMapDisplay {
162 source_map: &SourceMapWrapper {
163 source_map,
164 current_dir: PathBuf::default(),
165 },
166 };
167
168 let symbol_table_display = SymbolTableDisplay {
169 symbol_table: &default_module.symbol_table,
170 source_map_display: &source_map_display,
171 };
172
173 let std_path = &["std".to_string()];
177 let std_module_with_intrinsics = swamp_core::create_module_with_name(std_path);
178 let std_ast_module = parse_single_module_from_text(source_map, std_path, &std_text())?;
179 let analyzed_std_symbol_table = analyze_single_module(
180 &mut state,
181 default_symbol_table_for_core_with_intrinsics,
182 &modules,
183 half_completed_core_symbol_table.into(),
184 &std_ast_module,
185 source_map,
186 &std_module_with_intrinsics.symbol_table.module_path(),
187 );
188 default_module
189 .symbol_table
190 .extend_basic_from(&analyzed_std_symbol_table)
191 .expect("extend basics from core");
192
193 let analyzed_std_module = Module::new(analyzed_std_symbol_table, vec![], None);
194
195 modules.add(ModuleRef::from(analyzed_std_module));
196
197 let bootstrap_program = Program::new(state, modules, default_module.symbol_table);
198
199 let result = BootstrapResult {
200 program: bootstrap_program,
201 core_module_path: core_path,
202 };
203
204 Ok(result)
205}
206
207pub fn compile_and_analyze_all_modules(
208 module_path: &[String],
209 resolved_program: &mut Program,
210 source_map: &mut SourceMap,
211 core_symbol_table: SymbolTableRef,
212) -> Result<(), ScriptResolveError> {
213 let mut dependency_parser = DependencyParser::new();
214
215 let module_paths_in_order =
216 parse_local_modules_and_get_order(module_path, &mut dependency_parser, source_map)?;
217
218 analyze_modules_in_order(
219 &mut resolved_program.state,
220 &resolved_program.default_symbol_table,
221 &mut resolved_program.modules,
222 &core_symbol_table,
223 source_map,
224 &module_paths_in_order,
225 &dependency_parser,
226 )?;
227
228 Ok(())
229}
230
231#[must_use]
232pub fn remove_version_from_package_name_regex(package_name_with_version: &str) -> String {
233 let re = Regex::new(
234 r"-(?P<version>[0-9]+(?:\.[0-9]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)?(?:\+.*)?$",
235 )
236 .unwrap();
237 re.replace(package_name_with_version, "").to_string()
238}
239
240#[must_use]
241pub fn current_path() -> PathBuf {
242 current_dir().unwrap()
243}
244
245pub struct CompileOptions {
246 pub show_semantic: bool,
247 pub show_modules: bool,
248 pub show_errors: bool,
249 pub show_types: bool,
250}
251
252pub fn bootstrap_and_compile(
257 source_map: &mut SourceMap,
258 root_path: &[String],
259 options: &CompileOptions,
260) -> Result<Program, ScriptResolveError> {
261 let bootstrap_timer = ScopedTimer::new("bootstrap");
262 let bootstrap_result = bootstrap_modules(source_map).inspect_err(|err| {
263 show_script_resolve_error(err, source_map, ¤t_path());
264 })?;
265 drop(bootstrap_timer);
266 let mut program = bootstrap_result.program;
267
268 let core_symbol_table = program
269 .modules
270 .get(&bootstrap_result.core_module_path)
271 .unwrap()
272 .symbol_table
273 .clone();
274
275 let compile_all_modules_timer = ScopedTimer::new("compile all modules");
284 compile_and_analyze_all_modules(
285 root_path,
286 &mut program,
287 source_map,
288 core_symbol_table.into(),
289 )
290 .inspect_err(|err| {
291 show_script_resolve_error(err, source_map, ¤t_path());
292 })?;
293
294 drop(compile_all_modules_timer);
295
296 if options.show_modules {
297 debug_all_modules(&program.modules, source_map);
298 }
299
300 if options.show_semantic {
301 debug_all_impl_functions(&program.state.associated_impls, source_map);
302 }
303
304 if options.show_types {
305 let mut str = String::new();
306 print_types(&mut str, &program.state.types).expect("should work");
307 eprintln!("{str}");
308 }
310
311 if options.show_errors {
312 let source_map_wrapper = SourceMapWrapper {
313 source_map,
314 current_dir: current_dir().unwrap(),
315 };
316 show_errors(&program.state.errors, &source_map_wrapper);
317 show_hints(&program.state.hints, &source_map_wrapper);
318 show_information(&program.state.infos, &source_map_wrapper);
319 }
320
321
322 Ok(program)
323}
324
325fn show_errors(errors: &[Error], source_map_wrapper: &SourceMapWrapper) {
326 for err in errors {
327 show_analyzer_error(
328 err,
329 Kind::Error,
330 source_map_wrapper.source_map,
331 &source_map_wrapper.current_dir,
332 );
333 }
334}
335
336fn show_hints(errors: &[Error], source_map_wrapper: &SourceMapWrapper) {
337 for err in errors {
338 show_analyzer_error(
339 err,
340 Kind::Warning,
341 source_map_wrapper.source_map,
342 &source_map_wrapper.current_dir,
343 );
344 }
345}
346
347fn show_information(errors: &[Error], source_map_wrapper: &SourceMapWrapper) {
348 for err in errors {
349 show_analyzer_error(
350 err,
351 Kind::Help,
352 source_map_wrapper.source_map,
353 &source_map_wrapper.current_dir,
354 );
355 }
356}
357
358pub fn debug_all_modules(modules: &Modules, source_map: &SourceMap) {
359 for (_name, module) in modules.modules() {
360 debug_module(&module.symbol_table, source_map);
361 }
362}
363pub fn debug_module(symbol_table: &SymbolTable, source_map: &SourceMap) {
364 let source_map_lookup = SourceMapWrapper {
365 source_map,
366 current_dir: current_dir().unwrap(),
367 };
368 let pretty_printer = SourceMapDisplay {
369 source_map: &source_map_lookup,
370 };
371
372 let symbol_table_display = SymbolTableDisplay {
373 symbol_table,
374 source_map_display: &pretty_printer,
375 };
376
377 info!(
378 "module: {}{}",
379 formal_module_name(&symbol_table.module_path()),
380 symbol_table_display
381 );
382}
383
384fn debug_all_impl_functions(all_impls: &AssociatedImpls, source_map: &mut SourceMap) {
385 let source_map_lookup = SourceMapWrapper {
386 source_map,
387 current_dir: current_dir().unwrap(),
388 };
389 let pretty_printer = SourceMapDisplay {
390 source_map: &source_map_lookup,
391 };
392
393 let symbol_table_display = ImplsDisplay {
394 all_impls,
395 source_map: &pretty_printer,
396 };
397
398 info!("impls: {}", symbol_table_display);
399}
400
401#[must_use]
402pub fn compile_string(script: &str) -> (Program, ModuleRef, SourceMap) {
403 let mut source_map = SourceMap::new(&SeqMap::default()).unwrap();
404 let file_id = 0xffff;
405
406 if let Some(swamp_home) = swamp_registry_path() {
407 source_map.add_mount("registry", &swamp_home).unwrap();
408 }
409
410 source_map.add_mount("crate", Path::new("/tmp/")).unwrap();
411 source_map.add_to_cache("crate", Path::new("test.swamp"), script, file_id);
412
413 let resolved_path_str = vec!["crate".to_string(), "test".to_string()];
414 let compile_options = CompileOptions {
415 show_semantic: false,
416 show_modules: false,
417 show_errors: true,
418 show_types: false,
419 };
420 let program =
421 bootstrap_and_compile(&mut source_map, &resolved_path_str, &compile_options).unwrap();
422 let main_module = program.modules.get(&resolved_path_str).unwrap().clone();
423
424 (program, main_module, source_map)
425}