dust/src/main.rs

418 lines
12 KiB
Rust
Raw Normal View History

2023-10-26 20:00:06 +00:00
//! Command line interface for the dust programming language.
2024-01-17 17:48:51 +00:00
2024-01-06 10:00:36 +00:00
use clap::{Parser, Subcommand};
use crossterm::event::{KeyCode, KeyModifiers};
2024-01-27 02:03:54 +00:00
use nu_ansi_term::{Color, Style};
use reedline::{
default_emacs_keybindings, ColumnarMenu, Completer, DefaultHinter, EditCommand, Emacs, Prompt,
Reedline, ReedlineEvent, ReedlineMenu, Signal, Span, SqliteBackedHistory, Suggestion,
2023-08-22 15:40:50 +00:00
};
2024-01-28 18:45:08 +00:00
use std::{borrow::Cow, fs::read_to_string, path::PathBuf, process::Command};
2023-08-22 15:40:50 +00:00
2024-02-11 01:50:49 +00:00
use dust_lang::{built_in_values, Context, Error, Interpreter, Value, ValueData};
2023-08-22 15:40:50 +00:00
/// Command-line arguments to be parsed.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
2023-10-26 20:00:06 +00:00
/// Dust source code to evaluate.
2023-08-22 15:40:50 +00:00
#[arg(short, long)]
command: Option<String>,
2023-10-26 20:00:06 +00:00
/// Data to assign to the "input" variable.
#[arg(short, long)]
input: Option<String>,
2024-01-17 17:48:51 +00:00
/// File whose contents will be assigned to the "input" variable.
2023-10-26 20:00:06 +00:00
#[arg(short = 'p', long)]
input_path: Option<String>,
2024-01-17 17:48:51 +00:00
/// Command for alternate functionality besides running the source.
2024-01-06 10:00:36 +00:00
#[command(subcommand)]
cli_command: Option<CliCommand>,
2023-08-23 04:39:46 +00:00
/// Location of the file to run.
path: Option<String>,
2023-08-22 15:40:50 +00:00
}
2024-01-06 10:00:36 +00:00
#[derive(Subcommand, Debug)]
pub enum CliCommand {
2024-01-13 18:39:30 +00:00
/// Output a formatted version of the input.
2024-01-06 10:00:36 +00:00
Format,
2024-01-13 18:39:30 +00:00
/// Output a concrete syntax tree of the input.
2024-01-28 22:46:15 +00:00
Syntax { path: String },
2024-01-06 10:00:36 +00:00
}
fn main() {
2024-01-13 18:30:50 +00:00
env_logger::init();
2023-08-22 15:40:50 +00:00
let args = Args::parse();
2024-02-11 01:50:49 +00:00
let context = Context::new();
2023-10-26 20:00:06 +00:00
2023-10-28 14:28:43 +00:00
if let Some(input) = args.input {
context
2024-02-11 01:50:49 +00:00
.set_value("input".to_string(), Value::string(input))
.unwrap();
2023-10-28 14:28:43 +00:00
}
2023-10-26 20:00:06 +00:00
if let Some(path) = args.input_path {
let file_contents = read_to_string(path).unwrap();
2023-10-26 20:00:06 +00:00
context
2024-02-11 01:50:49 +00:00
.set_value("input".to_string(), Value::string(file_contents))
.unwrap();
2023-10-26 20:00:06 +00:00
}
2024-01-24 23:57:36 +00:00
if args.path.is_none() && args.command.is_none() {
let run_shell_result = run_shell(context);
match run_shell_result {
Ok(_) => {}
Err(error) => eprintln!("{error}"),
}
return;
2024-01-24 23:57:36 +00:00
}
let source = if let Some(path) = &args.path {
read_to_string(path).unwrap()
} else if let Some(command) = args.command {
command
} else {
String::with_capacity(0)
};
2023-12-30 17:02:58 +00:00
let mut interpreter = Interpreter::new(context);
2023-11-15 00:37:19 +00:00
2024-01-28 22:46:15 +00:00
if let Some(CliCommand::Syntax { path }) = args.cli_command {
let source = read_to_string(path).unwrap();
2024-01-30 23:13:30 +00:00
let syntax_tree_sexp = interpreter.syntax_tree(&source).unwrap();
2024-01-28 22:46:15 +00:00
2024-01-30 23:13:30 +00:00
println!("{syntax_tree_sexp}");
2024-01-13 18:39:30 +00:00
return;
2023-11-15 00:37:19 +00:00
}
2024-01-13 18:39:30 +00:00
if let Some(CliCommand::Format) = args.cli_command {
2024-01-30 23:13:30 +00:00
let formatted = interpreter.format(&source).unwrap();
2024-01-28 22:46:15 +00:00
2024-01-30 23:13:30 +00:00
println!("{formatted}");
2024-01-13 18:39:30 +00:00
return;
}
2024-01-24 23:57:36 +00:00
let eval_result = interpreter.run(&source);
2023-10-09 19:54:47 +00:00
match eval_result {
2023-10-24 00:45:47 +00:00
Ok(value) => {
if !value.is_none() {
2023-10-24 00:45:47 +00:00
println!("{value}")
}
}
2023-10-09 19:54:47 +00:00
Err(error) => eprintln!("{error}"),
2023-08-22 15:40:50 +00:00
}
}
2024-02-13 13:10:34 +00:00
// struct DustHighlighter {
// context: Context,
// }
2023-08-22 15:40:50 +00:00
2024-02-13 13:10:34 +00:00
// impl DustHighlighter {
// fn new(context: Context) -> Self {
// Self { context }
// }
// }
2023-08-28 20:14:55 +00:00
2024-02-13 13:10:34 +00:00
// const HIGHLIGHT_TERMINATORS: [char; 8] = [' ', ':', '(', ')', '{', '}', '[', ']'];
2024-01-27 02:03:54 +00:00
2024-02-13 13:10:34 +00:00
// impl Highlighter for DustHighlighter {
// fn highlight(&self, line: &str, _cursor: usize) -> reedline::StyledText {
// let mut styled = StyledText::new();
2024-02-11 01:50:49 +00:00
2024-02-13 13:10:34 +00:00
// for word in line.split_inclusive(&HIGHLIGHT_TERMINATORS) {
// let mut word_is_highlighted = false;
2024-02-11 01:50:49 +00:00
2024-02-13 13:10:34 +00:00
// for key in self.context.inner().unwrap().keys() {
// if key == &word {
// styled.push((Style::new().bold(), word.to_string()));
// }
2024-02-13 13:10:34 +00:00
// word_is_highlighted = true;
// }
2024-02-13 13:10:34 +00:00
// for built_in_value in built_in_values() {
// if built_in_value.name() == word {
// styled.push((Style::new().bold(), word.to_string()));
// }
2024-02-13 13:10:34 +00:00
// word_is_highlighted = true;
// }
2023-08-22 15:40:50 +00:00
2024-02-13 13:10:34 +00:00
// if word_is_highlighted {
// let final_char = word.chars().last().unwrap();
2023-08-22 15:40:50 +00:00
2024-02-13 13:10:34 +00:00
// if HIGHLIGHT_TERMINATORS.contains(&final_char) {
// let mut terminator_style = Style::new();
2024-01-27 02:03:54 +00:00
2024-02-13 13:10:34 +00:00
// terminator_style.foreground = Some(Color::Cyan);
2024-01-27 02:03:54 +00:00
2024-02-13 13:10:34 +00:00
// styled.push((terminator_style, final_char.to_string()));
// }
// } else {
// styled.push((Style::new(), word.to_string()));
// }
// }
2023-08-22 15:40:50 +00:00
2024-02-13 13:10:34 +00:00
// styled
// }
// }
2023-08-22 15:40:50 +00:00
2024-01-27 02:03:54 +00:00
struct StarshipPrompt {
2024-01-26 23:28:37 +00:00
left: String,
right: String,
}
2024-01-27 02:03:54 +00:00
impl StarshipPrompt {
2024-01-26 23:28:37 +00:00
fn new() -> Self {
Self {
left: String::new(),
right: String::new(),
}
}
fn reload(&mut self) {
2024-01-27 02:03:54 +00:00
let run_starship_left = Command::new("starship").arg("prompt").output();
let run_starship_right = Command::new("starship")
.args(["prompt", "--right"])
.output();
let left_prompt = if let Ok(output) = &run_starship_left {
String::from_utf8_lossy(&output.stdout).trim().to_string()
} else {
">".to_string()
};
let right_prompt = if let Ok(output) = &run_starship_right {
String::from_utf8_lossy(&output.stdout).trim().to_string()
} else {
"".to_string()
2024-01-27 02:03:54 +00:00
};
self.left = left_prompt;
self.right = right_prompt;
2024-01-26 23:28:37 +00:00
}
}
2024-01-26 22:14:57 +00:00
2024-01-27 02:03:54 +00:00
impl Prompt for StarshipPrompt {
2024-01-26 22:14:57 +00:00
fn render_prompt_left(&self) -> Cow<str> {
2024-01-26 23:28:37 +00:00
Cow::Borrowed(&self.left)
2024-01-26 22:14:57 +00:00
}
fn render_prompt_right(&self) -> Cow<str> {
2024-01-26 23:28:37 +00:00
Cow::Borrowed(&self.right)
2024-01-26 22:14:57 +00:00
}
fn render_prompt_indicator(&self, _prompt_mode: reedline::PromptEditMode) -> Cow<str> {
2024-01-27 02:03:54 +00:00
Cow::Borrowed(" ")
2024-01-26 22:14:57 +00:00
}
2024-01-26 22:14:57 +00:00
fn render_prompt_multiline_indicator(&self) -> Cow<str> {
2024-01-26 23:28:37 +00:00
Cow::Borrowed("")
2024-01-26 22:14:57 +00:00
}
2024-01-26 22:14:57 +00:00
fn render_prompt_history_search_indicator(
&self,
_history_search: reedline::PromptHistorySearch,
) -> Cow<str> {
2024-01-26 23:28:37 +00:00
Cow::Borrowed("")
2024-01-26 22:14:57 +00:00
}
}
2024-01-27 02:03:54 +00:00
pub struct DustCompleter {
2024-02-11 01:50:49 +00:00
context: Context,
2024-01-27 02:03:54 +00:00
}
impl DustCompleter {
2024-02-11 01:50:49 +00:00
fn new(context: Context) -> Self {
2024-01-27 02:03:54 +00:00
DustCompleter { context }
}
}
impl Completer for DustCompleter {
2024-01-28 17:04:33 +00:00
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
let mut suggestions = Vec::new();
2024-01-28 18:45:08 +00:00
let last_word = if let Some(word) = line.rsplit([' ', ':']).next() {
2024-01-28 17:04:33 +00:00
word
} else {
2024-01-28 22:46:15 +00:00
line
2024-01-28 17:04:33 +00:00
};
2024-01-28 18:45:08 +00:00
if let Ok(path) = PathBuf::try_from(last_word) {
if let Ok(read_dir) = path.read_dir() {
for entry in read_dir {
if let Ok(entry) = entry {
2024-01-28 22:46:15 +00:00
let description = if let Ok(file_type) = entry.file_type() {
if file_type.is_dir() {
"directory"
} else if file_type.is_file() {
"file"
} else if file_type.is_symlink() {
"symlink"
} else {
"unknown"
}
} else {
"unknown"
};
2024-01-28 18:45:08 +00:00
suggestions.push(Suggestion {
2024-01-28 22:46:15 +00:00
value: entry.path().to_string_lossy().to_string(),
description: Some(description.to_string()),
2024-01-28 18:45:08 +00:00
extra: None,
2024-01-28 22:46:15 +00:00
span: Span::new(pos - last_word.len(), pos),
2024-01-28 18:45:08 +00:00
append_whitespace: false,
});
}
}
}
}
2024-01-28 17:04:33 +00:00
for built_in_value in built_in_values() {
2024-01-28 17:14:43 +00:00
let name = built_in_value.name();
let description = built_in_value.description();
2024-01-28 17:04:33 +00:00
if built_in_value.name().contains(last_word) {
suggestions.push(Suggestion {
2024-01-28 17:14:43 +00:00
value: name.to_string(),
description: Some(description.to_string()),
2024-01-28 17:04:33 +00:00
extra: None,
span: Span::new(pos - last_word.len(), pos),
2024-01-28 17:07:25 +00:00
append_whitespace: false,
});
}
2024-01-28 17:14:43 +00:00
if let Value::Map(map) = built_in_value.get() {
2024-02-12 20:07:41 +00:00
for (key, value) in map.inner().unwrap().iter() {
2024-01-28 17:14:43 +00:00
if key.contains(last_word) {
suggestions.push(Suggestion {
value: format!("{name}:{key}"),
description: Some(value.to_string()),
extra: None,
span: Span::new(pos - last_word.len(), pos),
append_whitespace: false,
});
}
}
}
2024-01-28 17:07:25 +00:00
}
2024-02-11 01:50:49 +00:00
for (key, value_data) in self.context.inner().unwrap().iter() {
let value = match value_data {
ValueData::Value { inner, .. } => inner,
ValueData::ExpectedType { .. } => continue,
2024-02-15 03:38:45 +00:00
ValueData::TypeDefinition(_) => continue,
2024-02-11 01:50:49 +00:00
};
2024-01-28 17:07:25 +00:00
if key.contains(last_word) {
suggestions.push(Suggestion {
value: key.to_string(),
description: Some(value.to_string()),
extra: None,
span: Span::new(pos - last_word.len(), pos),
2024-01-28 17:04:33 +00:00
append_whitespace: false,
});
}
2024-01-27 02:03:54 +00:00
}
suggestions
}
}
2024-02-11 01:50:49 +00:00
fn run_shell(context: Context) -> Result<(), Error> {
2024-01-26 22:14:57 +00:00
let mut interpreter = Interpreter::new(context.clone());
let mut keybindings = default_emacs_keybindings();
2024-01-25 07:17:45 +00:00
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char(' '),
ReedlineEvent::Edit(vec![EditCommand::InsertNewline]),
);
keybindings.add_binding(
2024-01-26 22:14:57 +00:00
KeyModifiers::NONE,
2024-01-26 23:28:37 +00:00
KeyCode::Enter,
2024-01-27 02:03:54 +00:00
ReedlineEvent::SubmitOrNewline,
);
keybindings.add_binding(
2024-01-26 23:28:37 +00:00
KeyModifiers::NONE,
KeyCode::Tab,
ReedlineEvent::Edit(vec![EditCommand::InsertString(" ".to_string())]),
);
2024-01-27 02:03:54 +00:00
keybindings.add_binding(
2024-01-28 22:46:15 +00:00
KeyModifiers::NONE,
KeyCode::Tab,
ReedlineEvent::Multiple(vec![
ReedlineEvent::Menu("context menu".to_string()),
ReedlineEvent::MenuNext,
]),
2024-01-27 02:03:54 +00:00
);
let edit_mode = Box::new(Emacs::new(keybindings));
let history = Box::new(
SqliteBackedHistory::with_file(PathBuf::from("target/history"), None, None)
.expect("Error loading history."),
);
2024-01-27 02:03:54 +00:00
let hinter = Box::new(DefaultHinter::default().with_style(Style::new().dimmed()));
let completer = DustCompleter::new(context.clone());
2024-01-28 17:04:33 +00:00
let mut line_editor = Reedline::create()
.with_edit_mode(edit_mode)
.with_history(history)
2024-01-26 22:14:57 +00:00
.with_hinter(hinter)
2024-01-27 02:03:54 +00:00
.use_kitty_keyboard_enhancement(true)
.with_completer(Box::new(completer))
.with_menu(ReedlineMenu::EngineCompleter(Box::new(
2024-01-28 17:04:33 +00:00
ColumnarMenu::default()
2024-01-28 22:46:15 +00:00
.with_name("context menu")
.with_text_style(Style::new().fg(Color::White))
.with_columns(1)
.with_column_padding(10),
2024-01-27 02:03:54 +00:00
)));
let mut prompt = StarshipPrompt::new();
2024-01-26 23:28:37 +00:00
prompt.reload();
2023-08-28 20:14:55 +00:00
loop {
let sig = line_editor.read_line(&prompt);
2024-01-26 23:28:37 +00:00
match sig {
Ok(Signal::Success(buffer)) => {
2024-01-25 07:17:45 +00:00
if buffer.trim().is_empty() {
continue;
}
2023-08-28 20:14:55 +00:00
let run_result = interpreter.run(&buffer);
2023-08-28 20:14:55 +00:00
match run_result {
Ok(value) => {
if !value.is_none() {
println!("{value}")
}
2024-01-03 20:25:53 +00:00
}
2024-01-28 22:46:15 +00:00
Err(error) => println!("{error}"),
2023-08-28 20:14:55 +00:00
}
2024-01-28 22:46:15 +00:00
prompt.reload();
2023-08-28 20:14:55 +00:00
}
Ok(Signal::CtrlD) | Ok(Signal::CtrlC) => {
2024-01-28 17:04:33 +00:00
println!("\nLeaving the Dust shell.");
break;
}
x => {
2024-01-28 17:04:33 +00:00
println!("Unknown event: {:?}", x);
}
2023-08-28 20:14:55 +00:00
}
2023-08-22 15:40:50 +00:00
}
Ok(())
2023-08-22 15:40:50 +00:00
}