dust-lang 0.4.2

General purpose programming language
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
//! Command line interface for the dust programming language.

use clap::{Parser, Subcommand};
use colored::Colorize;
use crossterm::event::{KeyCode, KeyModifiers};
use nu_ansi_term::{Color, Style};
use reedline::{
    default_emacs_keybindings, ColumnarMenu, Completer, DefaultHinter, EditCommand, Emacs, Prompt,
    Reedline, ReedlineEvent, ReedlineMenu, Signal, Span, SqliteBackedHistory, Suggestion,
};

use std::{borrow::Cow, fs::read_to_string, io::Write, path::PathBuf, process::Command};

use dust_lang::{
    built_in_values::all_built_in_values, Context, ContextMode, Error, Interpreter, Value,
    ValueData,
};

/// Command-line arguments to be parsed.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// Dust source code to evaluate.
    #[arg(short, long)]
    command: Option<String>,

    /// Command for alternate functionality besides running the source.
    #[command(subcommand)]
    cli_command: Option<CliCommand>,

    /// Location of the file to run.
    path: Option<String>,
}

#[derive(Subcommand, Debug)]
pub enum CliCommand {
    /// Output a formatted version of the input.
    Format,

    /// Output a concrete syntax tree of the input.
    Syntax { path: String },
}

fn main() {
    env_logger::Builder::from_env("DUST_LOG")
        .format(|buffer, record| {
            let args = record.args();
            let log_level = record.level().to_string().bold();
            let timestamp = buffer.timestamp_seconds().to_string().dimmed();

            writeln!(buffer, "[{log_level} {timestamp}] {args}")
        })
        .init();

    let args = Args::parse();
    let context = Context::new(ContextMode::AllowGarbage);

    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;
    }

    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)
    };

    let mut interpreter = Interpreter::new(context);

    if let Some(CliCommand::Syntax { path }) = args.cli_command {
        let source = read_to_string(path).unwrap();
        let syntax_tree_sexp = interpreter.syntax_tree(&source).unwrap();

        println!("{syntax_tree_sexp}");

        return;
    }

    if let Some(CliCommand::Format) = args.cli_command {
        let formatted = interpreter.format(&source).unwrap();

        println!("{formatted}");

        return;
    }

    let eval_result = interpreter.run(&source);

    match eval_result {
        Ok(value) => {
            if !value.is_none() {
                println!("{value}")
            }
        }
        Err(error) => eprintln!("{}", error.create_report(&source)),
    }
}

// struct DustHighlighter {
//     context: Context,
// }

// impl DustHighlighter {
//     fn new(context: Context) -> Self {
//         Self { context }
//     }
// }

// const HIGHLIGHT_TERMINATORS: [char; 8] = [' ', ':', '(', ')', '{', '}', '[', ']'];

// impl Highlighter for DustHighlighter {
//     fn highlight(&self, line: &str, _cursor: usize) -> reedline::StyledText {
//         let mut styled = StyledText::new();

//         for word in line.split_inclusive(&HIGHLIGHT_TERMINATORS) {
//             let mut word_is_highlighted = false;

//             for key in self.context.inner().unwrap().keys() {
//                 if key == &word {
//                     styled.push((Style::new().bold(), word.to_string()));
//                 }

//                 word_is_highlighted = true;
//             }

//             for built_in_value in built_in_values() {
//                 if built_in_value.name() == word {
//                     styled.push((Style::new().bold(), word.to_string()));
//                 }

//                 word_is_highlighted = true;
//             }

//             if word_is_highlighted {
//                 let final_char = word.chars().last().unwrap();

//                 if HIGHLIGHT_TERMINATORS.contains(&final_char) {
//                     let mut terminator_style = Style::new();

//                     terminator_style.foreground = Some(Color::Cyan);

//                     styled.push((terminator_style, final_char.to_string()));
//                 }
//             } else {
//                 styled.push((Style::new(), word.to_string()));
//             }
//         }

//         styled
//     }
// }

struct StarshipPrompt {
    left: String,
    right: String,
}

impl StarshipPrompt {
    fn new() -> Self {
        Self {
            left: String::new(),
            right: String::new(),
        }
    }

    fn reload(&mut self) {
        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()
        };

        self.left = left_prompt;
        self.right = right_prompt;
    }
}

impl Prompt for StarshipPrompt {
    fn render_prompt_left(&self) -> Cow<str> {
        Cow::Borrowed(&self.left)
    }

    fn render_prompt_right(&self) -> Cow<str> {
        Cow::Borrowed(&self.right)
    }

    fn render_prompt_indicator(&self, _prompt_mode: reedline::PromptEditMode) -> Cow<str> {
        Cow::Borrowed(" ")
    }

    fn render_prompt_multiline_indicator(&self) -> Cow<str> {
        Cow::Borrowed("")
    }

    fn render_prompt_history_search_indicator(
        &self,
        _history_search: reedline::PromptHistorySearch,
    ) -> Cow<str> {
        Cow::Borrowed("")
    }
}

pub struct DustCompleter {
    context: Context,
}

impl DustCompleter {
    fn new(context: Context) -> Self {
        DustCompleter { context }
    }
}

impl Completer for DustCompleter {
    fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
        let mut suggestions = Vec::new();
        let last_word = if let Some(word) = line.rsplit([' ', ':']).next() {
            word
        } else {
            line
        };

        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 {
                        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"
                        };

                        suggestions.push(Suggestion {
                            value: entry.path().to_string_lossy().to_string(),
                            description: Some(description.to_string()),
                            extra: None,
                            span: Span::new(pos - last_word.len(), pos),
                            append_whitespace: false,
                        });
                    }
                }
            }
        }

        for built_in_value in all_built_in_values() {
            let name = built_in_value.name();
            let description = built_in_value.description();

            if built_in_value.name().contains(last_word) {
                suggestions.push(Suggestion {
                    value: name.to_string(),
                    description: Some(description.to_string()),
                    extra: None,
                    span: Span::new(pos - last_word.len(), pos),
                    append_whitespace: false,
                });
            }

            if let Value::Map(map) = built_in_value.get() {
                for (key, value) in map.inner() {
                    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,
                        });
                    }
                }
            }
        }

        for (key, (value_data, _counter)) in self.context.inner().unwrap().iter() {
            let value = match value_data {
                ValueData::Value(value) => value,
                ValueData::TypeHint(_) => continue,
                ValueData::TypeDefinition(_) => continue,
            };

            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),
                    append_whitespace: false,
                });
            }
        }

        suggestions
    }
}

fn run_shell(context: Context) -> Result<(), Error> {
    let mut interpreter = Interpreter::new(context.clone());
    let mut keybindings = default_emacs_keybindings();

    keybindings.add_binding(
        KeyModifiers::CONTROL,
        KeyCode::Char(' '),
        ReedlineEvent::Edit(vec![EditCommand::InsertNewline]),
    );
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::Enter,
        ReedlineEvent::SubmitOrNewline,
    );
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::Tab,
        ReedlineEvent::Edit(vec![EditCommand::InsertString("    ".to_string())]),
    );
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::Tab,
        ReedlineEvent::Multiple(vec![
            ReedlineEvent::Menu("context menu".to_string()),
            ReedlineEvent::MenuNext,
        ]),
    );

    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."),
    );
    let hinter = Box::new(DefaultHinter::default().with_style(Style::new().dimmed()));
    let completer = DustCompleter::new(context.clone());

    let mut line_editor = Reedline::create()
        .with_edit_mode(edit_mode)
        .with_history(history)
        .with_hinter(hinter)
        .use_kitty_keyboard_enhancement(true)
        .with_completer(Box::new(completer))
        .with_menu(ReedlineMenu::EngineCompleter(Box::new(
            ColumnarMenu::default()
                .with_name("context menu")
                .with_text_style(Style::new().fg(Color::White))
                .with_columns(1)
                .with_column_padding(10),
        )));
    let mut prompt = StarshipPrompt::new();

    prompt.reload();

    loop {
        let sig = line_editor.read_line(&prompt);

        match sig {
            Ok(Signal::Success(buffer)) => {
                if buffer.trim().is_empty() {
                    continue;
                }

                let run_result = interpreter.run(&buffer);

                match run_result {
                    Ok(value) => {
                        if !value.is_none() {
                            println!("{value}")
                        }
                    }
                    Err(error) => println!("{error}"),
                }

                prompt.reload();
            }
            Ok(Signal::CtrlD) | Ok(Signal::CtrlC) => {
                println!("\nLeaving the Dust shell.");
                break;
            }
            x => {
                println!("Unknown event: {:?}", x);
            }
        }
    }

    Ok(())
}