Echo Writes Code

orchid_cli.rs

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
mod render;

use crate::render::{ Render };

use colored::*;
use clap::{ Args, Parser, Subcommand };

use std::fmt;
use std::fs;
use std::io;
use std::process::{ ExitCode };

// -------------------------------------------------------------------------------------------------
// Error handling ----------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

type Result<T> = ::std::result::Result<T, Error>;

#[derive(Debug)]
enum Error {
	IOError(io::Error),
	OrchidError(orchid::Error),
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		use Error::*;

		match *self {
			IOError(ref e) => write!(f, "IO error: {}", e),
			OrchidError(ref e) => write!(f, "Orchid error: {}", e),
		}
	}
}

impl From<io::Error> for Error {
	fn from(e: io::Error) -> Error {
		Error::IOError(e)
	}
}

impl From<orchid::Error> for Error {
	fn from(e: orchid::Error) -> Error {
		Error::OrchidError(e)
	}
}

// -------------------------------------------------------------------------------------------------
// Argument parsing --------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

#[derive(Parser)]
#[command(author, version, about, propagate_version = true)]
struct Arguments {
	#[command(subcommand)]
	command: Command,
}

#[derive(Subcommand)]
enum Command {
	/// Generates a token stream from an Orchid source file
	Tokenize(TokenizeArguments),

	/// Generates a syntax tree from an Orchid source file
	Parse(ParseArguments),

	/// Performs semantic checking and type inference on an Orchid source file
	Check(CheckArguments),
}

#[derive(Args)]
struct TokenizeArguments {
	/// The Orchid source file to tokenize
	#[arg(allow_hyphen_values = true)]
	source_file: String,

	/// The output file to write the token stream into (default: standard output)
	#[arg(short, long)]
	output_file: Option<String>,
}

#[derive(Args)]
struct ParseArguments {
	/// The Orchid source file to parse
	#[arg(allow_hyphen_values = true)]
	source_file: String,

	/// The output file to write the syntax tree into (default: standard output)
	#[arg(short, long)]
	output_file: Option<String>,
}

#[derive(Args)]
struct CheckArguments {
	/// The Orchid source file to check
	#[arg(allow_hyphen_values = true)]
	source_file: String,

	/// The output file to write the annotated syntax tree to (default: standard output)
	#[arg(short, long)]
	output_file: Option<String>
}

// -------------------------------------------------------------------------------------------------
// Source files ------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

struct LineData {
	line_to_span: Vec<orchid::SourceSpan>,
}

impl LineData {
	/// Scan `text` to produce an index of its line boundaries.
	///
	/// Complexity: linear in `text.len()`.
	fn new(text: &str) -> LineData {
		// TODO: port this to std::ascii::Char once that API enters stable
		const LINE_FEED: u8 = 0x0a;
		const CARRIAGE_RETURN: u8 = 0x0d;

		let mut line_to_span = Vec::new();
		let mut current_line = 1;
		let mut current_line_start = orchid::SourceLocation::start();
		let mut had_cr = false;

		// 0th..(N-1)th line
		for (i, &byte) in text.as_bytes().iter().enumerate() {
			if byte == CARRIAGE_RETURN {
				had_cr = true;
				continue;
			}

			if byte == LINE_FEED {
				let current_line_end = {
					if had_cr {
						// `\r\n` ends at the `\r`, not the `\n`
						orchid::SourceLocation::new(current_line, i - 1)
					} else {
						orchid::SourceLocation::new(current_line, i)
					}
				};

				let span = orchid::SourceSpan::new(current_line_start, current_line_end);
				line_to_span.push(span);

				// Regardless of whether we have an `\r\n` or just an `\n`, the next line begins at the byte
				// after the `\n`
				current_line += 1;
				current_line_start = orchid::SourceLocation::new(current_line, i + 1);
			}

			// Reset `had_cr` regardless of the following byte, so that we don't think that an orphan `\r`
			// means that the next `\n` is an `\r\n` sequence
			had_cr = false;
		}

		// The final line ends 1 byte past the end of the text (it may be empty if the file ends with a
		// newline)
		let current_line_end = orchid::SourceLocation::new(current_line, text.len());

		let span = orchid::SourceSpan::new(current_line_start, current_line_end);
		line_to_span.push(span);

		LineData {
			line_to_span
		}
	}

	/// Look up a line in the line index.
	///
	/// Complexity: constant.
	///
	/// Note: `line` starts from 1.
	fn lookup(&self, line: usize) -> Option<orchid::SourceSpan> {
		assert!(line >= 1);
		self.line_to_span.get(line - 1).cloned()
	}
}

struct SourceFile {
	path: String,
	text: String,
	line_data: LineData,
}

impl SourceFile {
	fn from_file(path: &str) -> io::Result<SourceFile> {
		let file = fs::File::open(path)?;
		let text = io::read_to_string(file)?;
		let line_data = LineData::new(&text);

		Ok(SourceFile {
			path: path.to_string(),
			text,
			line_data,
		})
	}

	fn from_standard_input() -> io::Result<SourceFile> {
		let path = "<standard input>";
		let text = io::read_to_string(io::stdin())?;
		let line_data = LineData::new(&text);

		Ok(SourceFile {
			path: path.to_string(),
			text,
			line_data,
		})
	}

	fn line_containing(&self, location: orchid::SourceLocation) -> Option<orchid::SourceSpan> {
		self.line_data.lookup(location.line)
	}
}

impl fmt::Display for SourceFile {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "{}", self.path)
	}
}

// -------------------------------------------------------------------------------------------------
// Entry point -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

fn main() -> ExitCode {
	let arguments = Arguments::parse();

	let result = match arguments.command {
		Command::Tokenize(tokenize_arguments) => do_tokenize_command(tokenize_arguments),
		Command::Parse(parse_arguments) => do_parse_command(parse_arguments),
		Command::Check(check_arguments) => do_check_command(check_arguments),
	};

	match result {
		Ok(_) => ExitCode::SUCCESS,
		// Don't print anything else for Orchid errors, because we already ran `diagnose()`
		Err(Error::OrchidError(_)) => ExitCode::FAILURE,
		Err(e) => {
			eprintln!("{}", e);
			ExitCode::FAILURE
		},
	}
}

fn do_tokenize_command(arguments: TokenizeArguments) -> Result<()> {
	let source_file = open_source_file(&arguments.source_file)?;
	let token_stream = orchid::run_tokenizer(&source_file.text)
		.inspect_err(|e| {
			diagnose(&source_file, e);
		})?;

	write_token_stream_to_output_file(&arguments.output_file, token_stream)
}

fn do_parse_command(arguments: ParseArguments) -> Result<()> {
	let source_file = open_source_file(&arguments.source_file)?;
	let syntax_tree = orchid::run_parser(&source_file.text)
		.inspect_err(|e| {
			diagnose(&source_file, e);
		})?;

	write_syntax_tree_to_output_file(&arguments.output_file, syntax_tree)
}

fn do_check_command(_arguments: CheckArguments) -> Result<()> {
	/*
	let source_file = open_source_file(&arguments.source_file)?;
	let annotated_syntax_tree = orchid::run_checker(&source_file.text)
		.inspect_err(|e| {
			diagnose(&source_file, e);
		})?;

	write_syntax_tree_to_output_file(&arguments.output_file, syntax_tree)
	*/
	Ok(())
}

fn open_source_file(path: &str) -> Result<SourceFile> {
	let f = {
		if path == "-" {
			SourceFile::from_standard_input()
		} else {
			SourceFile::from_file(path)
		}
	}?;

	Ok(f)
}

fn write_token_stream_to_output_file(output_file: &Option<String>, token_stream: Vec<orchid::Token>) -> Result<()> {
	let mut output_writer = open_output_writer(output_file)?;
	token_stream.render(&mut output_writer)?;
	Ok(())
}

fn write_syntax_tree_to_output_file(output_file: &Option<String>, syntax_tree: orchid::SyntaxTree) -> Result<()> {
	let mut output_writer = open_output_writer(output_file)?;
	syntax_tree.render(&mut output_writer)?;
	Ok(())
}

fn open_output_writer(output_file: &Option<String>) -> Result<Box<dyn io::Write>> {
	match output_file {
		Some(ref path) if path != "-" => {
			let resolved = fs::canonicalize(path)?;
			let file = fs::File::create(resolved)?;
			Ok(Box::new(file))
		},
		Some(_) | None => {
			Ok(Box::new(io::stdout()))
		}
	}
}

fn diagnose(source_file: &SourceFile, e: &orchid::Error) {
	let span = e.span;

	eprintln!();
	eprintln!("{}: {}:{}: {}", "E".bright_red().bold(), source_file.path, span.start.line, e);

	if let Some(line) = source_file.line_containing(span.start) {
		if line.is_empty() || span.is_empty() {
			return;
		}

		// Remove the leading whitespace on the line so we don't have problems with `\t` characters
		// (and also because it looks nicer)
		let line_text = &source_file.text[line.start.byte..line.end.byte];
		let line_text_trimmed = line_text.trim_start();
		let line_length_difference = line_text.len() - line_text_trimmed.len();

		let line_number = format!("  {} ", span.start.line);
		let line_indent_size = line_number.len();
		let line_indent = " ".repeat(line_indent_size);

		// Defer this because the color bytes will add more width
		let line_number = line_number.magenta();

		let cursor_indent_size = span.start.byte - (line.start.byte + line_length_difference);
		let cursor_indent = " ".repeat(cursor_indent_size);
		let cursor = "^".repeat(e.span.len()).bright_red().bold();
		let gutter = "|".magenta();

		let message = format!("{e}").bright_red().bold();

		eprintln!("{line_indent}{gutter}");
		eprintln!("{line_number}{gutter}  {line_text_trimmed}");
		eprintln!("{line_indent}{gutter}  {cursor_indent}{cursor} {message}");
		eprintln!();
	}
}