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
use crate::errwarn::ErrorGenerator;
use crate::lexer::Lexer;
use crate::parser::Parser;
use crate::runtime::Run;
use crate::store::VERSION;
use crate::util::{get_lang, SupportedLanguage};
use lazy_static::lazy_static;
use regex::Regex;
use rustyline::completion::Completer;
use rustyline::completion::Pair;
use rustyline::error::ReadlineError;
use rustyline::Editor;

// TODO: Finish completer
/// Completer in progress
struct InteractiveCompleter;
impl Completer for InteractiveCompleter {
    type Candidate = Pair;
    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &rustyline::Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        lazy_static! {
            static ref RE: Regex =
                Regex::new(r#"[^()\d,'"+\-*/><!=%?.@\s][^\s"':?=<>!/%*@,()]*"#).unwrap();
            static ref KNOWN_KEYWORDS: Vec<&'static str> = vec![
                "at", "ver", "de", "ise", "son", "iken", "yoksa", "doğru", "yanlış", "kpy", "tks",
                "üst", "veya", "ve", "dön", "girdi", "işlev", "yükle",
            ];
        }
        let matches = RE.find_iter(line);
        for m in matches.into_iter() {
            if m.end() == pos {
                return Ok((
                    m.start(),
                    KNOWN_KEYWORDS
                        .iter()
                        .filter(|a| a.starts_with(m.as_str()))
                        .map(|a| Pair {
                            display: a.to_string(),
                            replacement: a.to_string(),
                        })
                        .collect(),
                ));
            }
        }
        Ok((0, Vec::with_capacity(0)))
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum QuietLevel {
    None,
    Quiet,
    Quieter,
    Quietest,
}
impl QuietLevel {
    pub fn inc(&mut self) {
        match self {
            Self::None => *self = Self::Quiet,
            Self::Quiet => *self = Self::Quieter,
            Self::Quieter => *self = Self::Quietest,
            Self::Quietest => (),
        }
    }
    pub fn inc_by(&mut self, i: usize) {
        for _ in 0..i {
            self.inc()
        }
    }
}

pub struct Interactive {
    line: usize,
    quiet: QuietLevel,
}
impl Default for Interactive {
    fn default() -> Self {
        Self {
            line: 1,
            quiet: QuietLevel::None,
        }
    }
}
impl Interactive {
    pub fn new(quiet: QuietLevel) -> Self {
        Self {
            quiet,
            ..Default::default()
        }
    }
    pub fn start(&mut self) {
        if self.quiet == QuietLevel::None {
            match get_lang() {
                SupportedLanguage::Turkish => {
                    println!("tr-lang ({VERSION}) interaktif konsol");
                    println!("çıkmak için `#çık` yazın");
                    println!("yürütmek için `#yürüt` yazın");
                }
                SupportedLanguage::English => {
                    println!("tr-lang ({VERSION}) interactive console");
                    println!("type `#çık` to exit");
                    println!("type `#yürüt` to run");
                }
            }
        }
        let mut fbuf = String::new();
        let mut editor = Editor::<()>::new();
        if editor.load_history(".trlhistory").is_err() {
            match get_lang() {
                SupportedLanguage::Turkish => println!("Tarih bulunamadı."),
                SupportedLanguage::English => println!("No previous history."),
            }
        }
        loop {
            let pr = match self.quiet {
                QuietLevel::None => format!("trli:{:03}#> ", self.line),
                QuietLevel::Quiet => format!("{:03}#> ", self.line),
                QuietLevel::Quieter => "#> ".to_string(),
                QuietLevel::Quietest => "".to_string(),
            };
            let rl = editor.readline(&pr);
            match rl {
                Ok(buf) => match buf.as_str() {
                    "#çık" => break,
                    "#yürüt" => {
                        let (mut memcs, _) = Run::new(
                            match match Parser::from_lexer(&mut Lexer::new(fbuf.clone()), ".".to_string()) {
                                Ok(parser) => parser,
                                Err(e) => {
                                    e.eprint();
                                    continue;
                                }
                            }.parse() {
                                Ok(ptk) => ptk,
                                Err(e) => { e.eprint(); continue; }
                            },
                        )
                        .run("<trli>".to_string(), None, true)
                        .unwrap_or_else(|(s, h, e)| {
                            e.eprint();
                            (s, h)
                        });
                        println!();
                        if memcs.len() > 0 {
                            println!("=> {:?}", memcs.iter_vec());
                        }
                        fbuf = String::new();
                        self.line = 1;
                    }
                    _ => {
                        editor.add_history_entry(&buf);
                        fbuf.push_str(&buf);
                        fbuf.push('\n');
                        self.line += 1;
                    }
                },
                Err(ReadlineError::Interrupted) => {
                    eprintln!("Ctrl+C");
                }
                Err(ReadlineError::Eof) => break,
                Err(e) => match get_lang() {
                    SupportedLanguage::Turkish => ErrorGenerator::error(
                        "EditörHatası",
                        &format!("{}", e),
                        self.line,
                        0,
                        "<trli>".to_string(),
                        None,
                    ),
                    SupportedLanguage::English => ErrorGenerator::error(
                        "EditorError",
                        &format!("{}", e),
                        self.line,
                        0,
                        "<trli>".to_string(),
                        None,
                    ),
                }
                .eprint(),
            }
        }
        editor.save_history(".trlhistory").unwrap();
    }
}