ezno 0.0.23

A fast and correct TypeScript type checker and compiler with additional experiments. For use as a library or through the CLI
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
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
#[allow(unused)]
use std::{
	collections::HashSet,
	env, fs,
	path::{Path, PathBuf},
	process::Command,
	process::ExitCode,
	time::{Duration, Instant},
};

use crate::{
	build::{build, BuildConfig, BuildOutput, FailedBuildOutput},
	check::check,
	reporting::report_diagnostics_to_cli,
	utilities::{print_to_cli, MaxDiagnostics},
};
use argh::FromArgs;
use checker::{CheckOutput, TypeCheckOptions};
use parser::ParseOptions;

/// The Ezno type-checker & compiler
#[derive(FromArgs, Debug)]
struct TopLevel {
	#[argh(subcommand)]
	nested: CompilerSubCommand,
}

#[derive(FromArgs, Debug)]
#[argh(subcommand)]
enum CompilerSubCommand {
	Info(Info),
	ASTExplorer(crate::ast_explorer::ExplorerArguments),
	Check(CheckArguments),
	Experimental(ExperimentalArguments),
	Repl(crate::repl::ReplArguments),
	// Run(RunArguments),
	// #[cfg(debug_assertions)]
	// Pack(Pack),
}

/// Display Ezno information
#[derive(FromArgs, Debug)]
#[argh(subcommand, name = "info")]
struct Info {}

/// Experimental Ezno features
#[derive(FromArgs, Debug)]
#[argh(subcommand, name = "experimental")]
pub(crate) struct ExperimentalArguments {
	#[argh(subcommand)]
	nested: ExperimentalSubcommand,
}

#[derive(FromArgs, Debug)]
#[argh(subcommand)]
pub(crate) enum ExperimentalSubcommand {
	Build(BuildArguments),
	Format(FormatArguments),
	#[cfg(not(target_family = "wasm"))]
	Upgrade(UpgradeArguments),
}

// TODO definition file as list
/// Build project
#[derive(FromArgs, Debug)]
#[argh(subcommand, name = "build")]
// TODO: Can be refactored with bit to reduce memory
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct BuildArguments {
	/// path to input file (accepts glob)
	#[argh(positional)]
	pub input: String,
	/// path to output
	#[argh(positional)]
	pub output: Option<PathBuf>,
	/// paths to definition files
	#[argh(option, short = 'd')]
	pub definition_file: Option<PathBuf>,

	/// whether to minify build output
	#[argh(switch, short = 'm')]
	pub minify: bool,
	/// build source maps
	#[argh(switch)]
	pub source_maps: bool,
	/// compact diagnostics
	#[argh(switch)]
	pub compact_diagnostics: bool,
	/// enable optimising transforms (warning can currently break code)
	#[argh(switch)]
	pub tree_shake: bool,
	/// maximum diagnostics to print (defaults to 30, pass `all` for all and `0` to count)
	#[argh(option, default = "MaxDiagnostics::default()")]
	pub max_diagnostics: MaxDiagnostics,

	#[cfg(not(target_family = "wasm"))]
	/// whether to display compile times
	#[argh(switch)]
	pub timings: bool,
	// /// whether to re-build on file changes
	// #[argh(switch)]
	// watch: bool,
}

/// Type check project
#[derive(FromArgs, Debug)]
#[argh(subcommand, name = "check")]
pub(crate) struct CheckArguments {
	/// path to input file (accepts glob)
	#[argh(positional)]
	pub input: String,
	/// paths to definition files
	#[argh(option, short = 'd')]
	pub definition_file: Option<PathBuf>,
	/// whether to re-check on file changes
	#[argh(switch)]
	pub watch: bool,
	/// whether to display check time
	#[argh(switch)]
	pub timings: bool,
	/// compact diagnostics
	#[argh(switch)]
	pub compact_diagnostics: bool,
	/// more behavior for numbers
	#[argh(switch)]
	pub advanced_numbers: bool,
	/// maximum diagnostics to print (defaults to 30, pass `all` for all and `0` to count)
	#[argh(option, default = "MaxDiagnostics::default()")]
	pub max_diagnostics: MaxDiagnostics,
}

/// Formats file in-place
#[derive(FromArgs, PartialEq, Debug)]
#[argh(subcommand, name = "format")]
pub(crate) struct FormatArguments {
	/// path to input file
	#[argh(positional)]
	pub path: PathBuf,
	/// check whether file is formatted
	#[argh(switch)]
	pub check: bool,
}

/// Upgrade/update the ezno binary to the latest version
#[derive(FromArgs, PartialEq, Debug)]
#[argh(subcommand, name = "upgrade")]
#[cfg(not(target_family = "wasm"))]
pub(crate) struct UpgradeArguments {}

// /// Run project using Deno
// #[derive(FromArgs, PartialEq, Debug)]
// #[argh(subcommand, name = "run")]
// struct RunArguments {
// 	/// path to input file
// 	#[argh(positional)]
// 	input: PathBuf,

// 	/// path to output
// 	#[argh(positional)]
// 	output: PathBuf,

// 	/// whether to re-run on file changes
// 	#[argh(switch)]
// 	watch: bool,
// }

#[allow(unused)]
fn file_system_resolver(path: &Path) -> Option<String> {
	// Cheaty
	if path.to_str() == Some("BLANK") {
		return Some(String::new());
	}
	match fs::read_to_string(path) {
		Ok(source) => Some(source),
		Err(_) => None,
	}
}

fn run_checker<T: crate::ReadFromFS>(
	entry_points: Vec<PathBuf>,
	read_file: &T,
	timings: bool,
	definition_file: Option<PathBuf>,
	max_diagnostics: MaxDiagnostics,
	type_check_options: TypeCheckOptions,
	compact_diagnostics: bool,
) -> ExitCode {
	let result = check(entry_points, read_file, definition_file.as_deref(), type_check_options);

	let CheckOutput { diagnostics, module_contents, chronometer, types, .. } = result;

	let diagnostics_count = diagnostics.count();
	let current = timings.then(std::time::Instant::now);

	let result = if diagnostics.contains_error() {
		if let MaxDiagnostics::FixedTo(0) = max_diagnostics {
			let count = diagnostics.into_iter().count();
			print_to_cli(format_args!(
				"Found {count} type errors and warnings {}",
				console::Emoji(" 😬", ":/")
			))
		} else {
			report_diagnostics_to_cli(
				diagnostics,
				&module_contents,
				compact_diagnostics,
				max_diagnostics,
			)
			.unwrap();
		}
		ExitCode::FAILURE
	} else {
		// May be warnings or information here
		report_diagnostics_to_cli(
			diagnostics,
			&module_contents,
			compact_diagnostics,
			max_diagnostics,
		)
		.unwrap();
		print_to_cli(format_args!("No type errors found {}", console::Emoji("🎉", ":)")));
		ExitCode::SUCCESS
	};

	#[cfg(not(target_family = "wasm"))]
	if timings {
		let reporting = current.unwrap().elapsed();
		eprintln!("---\n");
		eprintln!("Diagnostics:\t{}", diagnostics_count);
		eprintln!("Types:      \t{}", types.count_of_types());
		eprintln!("Lines:      \t{}", chronometer.lines);
		eprintln!("Cache read: \t{:?}", chronometer.cached);
		eprintln!("FS read:    \t{:?}", chronometer.fs);
		eprintln!("Parsed in:  \t{:?}", chronometer.parse);
		eprintln!("Checked in: \t{:?}", chronometer.check);
		eprintln!("Reporting:  \t{:?}", reporting);
	}

	result
}

pub fn run_cli<T: crate::ReadFromFS, U: crate::WriteToFS>(
	cli_arguments: &[&str],
	read_file: T,
	write_file: U,
) -> ExitCode {
	let command = match FromArgs::from_args(&["ezno-cli"], cli_arguments) {
		Ok(TopLevel { nested }) => nested,
		Err(err) => {
			print_to_cli(format_args!("{}", err.output));
			return ExitCode::FAILURE;
		}
	};

	match command {
		CompilerSubCommand::Info(_) => {
			crate::utilities::print_info();
			ExitCode::SUCCESS
		}
		CompilerSubCommand::Check(check_arguments) => {
			let CheckArguments {
				input,
				watch,
				definition_file,
				timings,
				compact_diagnostics,
				max_diagnostics,
				advanced_numbers,
			} = check_arguments;

			let type_check_options: TypeCheckOptions = if cfg!(target_family = "wasm") {
				Default::default()
			} else {
				TypeCheckOptions {
					measure_time: timings,
					advanced_numbers,
					..TypeCheckOptions::default()
				}
			};

			let entry_points = match get_entry_points(input) {
				Ok(entry_points) => entry_points,
				Err(_) => {
					print_to_cli(format_args!("Entry point error"));
					return ExitCode::FAILURE;
				}
			};

			// run_checker is written three times because cloning
			if watch {
				#[cfg(target_family = "wasm")]
				panic!("'watch' mode not supported on WASM");

				#[cfg(not(target_family = "wasm"))]
				{
					use notify::Watcher;
					use notify_debouncer_full::new_debouncer;

					let (tx, rx) = std::sync::mpsc::channel();
					let mut debouncer =
						new_debouncer(Duration::from_millis(200), None, tx).unwrap();

					for e in &entry_points {
						debouncer.watcher().watch(e, notify::RecursiveMode::Recursive).unwrap();
					}

					let _ = run_checker(
						entry_points.clone(),
						&read_file,
						timings,
						definition_file.clone(),
						max_diagnostics,
						type_check_options.clone(),
						compact_diagnostics,
					);

					for res in rx {
						match res {
							Ok(_e) => {
								let _out = run_checker(
									entry_points.clone(),
									&read_file,
									timings,
									definition_file.clone(),
									max_diagnostics,
									type_check_options.clone(),
									compact_diagnostics,
								);
							}
							Err(error) => eprintln!("Error: {error:?}"),
						}
					}

					unreachable!()
				}
			} else {
				run_checker(
					entry_points,
					&read_file,
					timings,
					definition_file,
					max_diagnostics,
					type_check_options,
					compact_diagnostics,
				)
			}
		}
		CompilerSubCommand::Experimental(ExperimentalArguments {
			nested: ExperimentalSubcommand::Build(build_config),
		}) => {
			let output_path = build_config.output.unwrap_or("ezno.out.js".into());

			let entry_points = match get_entry_points(build_config.input) {
				Ok(entry_points) => entry_points,
				Err(_) => {
					print_to_cli(format_args!("Entry point error"));
					return ExitCode::FAILURE;
				}
			};

			#[cfg(not(target_family = "wasm"))]
			let start = build_config.timings.then(std::time::Instant::now);

			let config = BuildConfig {
				tree_shake: build_config.tree_shake,
				strip_whitespace: build_config.minify,
				source_maps: build_config.source_maps,
				type_definition_module: build_config.definition_file,
				// TODO not sure
				output_path,
				other_transformers: None,
				lsp_mode: false,
			};

			let output = build(entry_points, &read_file, config);

			#[cfg(not(target_family = "wasm"))]
			if let Some(start) = start {
				eprintln!("Checked & built in {:?}", start.elapsed());
			};

			let compact_diagnostics = build_config.compact_diagnostics;

			match output {
				Ok(BuildOutput {
					artifacts,
					check_output: CheckOutput { module_contents, diagnostics, .. },
				}) => {
					for output in artifacts {
						write_file(output.output_path.as_path(), output.content);
					}
					report_diagnostics_to_cli(
						diagnostics,
						&module_contents,
						compact_diagnostics,
						build_config.max_diagnostics,
					)
					.unwrap();
					print_to_cli(format_args!(
						"Project built successfully {}",
						console::Emoji("🎉", ":)")
					));
					ExitCode::SUCCESS
				}
				Err(FailedBuildOutput(CheckOutput { module_contents, diagnostics, .. })) => {
					report_diagnostics_to_cli(
						diagnostics,
						&module_contents,
						compact_diagnostics,
						build_config.max_diagnostics,
					)
					.unwrap();
					ExitCode::FAILURE
				}
			}
		}
		CompilerSubCommand::Experimental(ExperimentalArguments {
			nested: ExperimentalSubcommand::Format(FormatArguments { path, check }),
		}) => {
			use parser::{source_map::FileSystem, ASTNode, Module, ToStringOptions};

			let input = match fs::read_to_string(&path) {
				Ok(string) => string,
				Err(err) => {
					print_to_cli(format_args!("{err:?}"));
					return ExitCode::FAILURE;
				}
			};
			let mut files =
				parser::source_map::MapFileStore::<parser::source_map::NoPathMap>::default();
			let source_id = files.new_source_id(path.clone(), input.clone());
			let res = Module::from_string(
				input.clone(),
				ParseOptions { retain_blank_lines: true, ..Default::default() },
			);
			match res {
				Ok(module) => {
					let options = ToStringOptions {
						trailing_semicolon: true,
						include_type_annotations: true,
						..Default::default()
					};
					let output = module.to_string(&options);
					if check {
						if input == output {
							ExitCode::SUCCESS
						} else {
							print_to_cli(format_args!(
								"{}",
								pretty_assertions::StrComparison::new(&input, &output)
							));
							ExitCode::FAILURE
						}
					} else {
						let _ = fs::write(path.clone(), output);
						print_to_cli(format_args!("Formatted {}", path.display()));
						ExitCode::SUCCESS
					}
				}
				Err(err) => {
					report_diagnostics_to_cli(
						std::iter::once((err, source_id).into()),
						&files,
						false,
						MaxDiagnostics::All,
					)
					.unwrap();
					ExitCode::FAILURE
				}
			}
		}
		#[cfg(not(target_family = "wasm"))]
		CompilerSubCommand::Experimental(ExperimentalArguments {
			nested: ExperimentalSubcommand::Upgrade(UpgradeArguments {}),
		}) => match crate::utilities::upgrade_self() {
			Ok(name) => {
				print_to_cli(format_args!("Successfully updated to {name}"));
				std::process::ExitCode::SUCCESS
			}
			Err(err) => {
				print_to_cli(format_args!("Error: {err}\nCould not upgrade binary. Retry manually from {repository}/releases", repository=env!("CARGO_PKG_REPOSITORY")));
				std::process::ExitCode::FAILURE
			}
		},
		CompilerSubCommand::ASTExplorer(mut repl) => {
			repl.run(&read_file);
			// TODO not always true
			ExitCode::SUCCESS
		}
		CompilerSubCommand::Repl(argument) => {
			crate::repl::run_repl(argument);
			// TODO not always true
			ExitCode::SUCCESS
		} // CompilerSubCommand::Run(run_arguments) => {
		  // 	let build_arguments = BuildArguments {
		  // 		input: run_arguments.input,
		  // 		output: Some(run_arguments.output.clone()),
		  // 		minify: true,
		  // 		no_comments: true,
		  // 		source_maps: false,
		  // 		watch: false,
		  // 		timings: false,
		  // 	};
		  // 	let output = build(build_arguments);

		  // 	if output.is_ok() {
		  // 		Command::new("deno")
		  // 			.args(["run", "--allow-all", run_arguments.output.to_str().unwrap()])
		  // 			.spawn()
		  // 			.unwrap()
		  // 			.wait()
		  // 			.unwrap();
		  // 	}
		  // }
		  // #[cfg(debug_assertions)]
		  // CompilerSubCommand::Pack(Pack { input, output }) => {
		  // 	let file = checker::definition_file_to_buffer(
		  // 		&file_system_resolver,
		  // 		&env::current_dir().unwrap(),
		  // 		&input,
		  // 	)
		  // 	.unwrap();

		  // 	let _root_ctx = checker::root_context_from_bytes(file);
		  // 	println!("Registered {} types", _root_ctx.types.len();
		  // }
	}
}

// `glob` library does not work on WASM :(
#[cfg(target_family = "wasm")]
fn get_entry_points(input: String) -> Result<Vec<PathBuf>, ()> {
	Ok(vec![input.into()])
}

#[cfg(not(target_family = "wasm"))]
fn get_entry_points(input: String) -> Result<Vec<PathBuf>, ()> {
	match glob::glob(&input) {
		Ok(files) => {
			let files = files
				.into_iter()
				.collect::<Result<Vec<PathBuf>, glob::GlobError>>()
				.map_err(|err| {
					eprintln!("{err:?}");
				})?;

			if files.is_empty() {
				eprintln!("Input {input:?} matched no files");
				Err(())
			} else {
				Ok(files)
			}
		}
		Err(err) => {
			eprintln!("{err:?}");
			Err(())
		}
	}
}