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
#![warn(missing_docs)]
pub mod error;
pub mod key;
#[macro_use]
mod macros;
#[doc(hidden)]
pub mod position;
pub mod settings;
mod string;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use error::{Error, ParseError, Result};
use error::ErrorType::{MissingArgument, NoCommand, Parse, UnknownCommand};
use key::{Key, parse_keys};
use position::Pos;
use string::{StrExt, check_ident, maybe_word, word, words};
use Command::*;
use Value::*;
pub trait CompletionValues {
fn completion_values() -> Vec<String>;
}
impl CompletionValues for bool {
fn completion_values() -> Vec<String> {
vec!["true".to_string(), "false".to_string()]
}
}
impl CompletionValues for i64 {
fn completion_values() -> Vec<String> {
vec![]
}
}
impl CompletionValues for String {
fn completion_values() -> Vec<String> {
vec![]
}
}
pub trait EnumFromStr
where Self: Sized
{
fn create(variant: &str, argument: &str) -> std::result::Result<Self, String>;
fn has_argument(variant: &str) -> std::result::Result<bool, String>;
}
pub trait EnumMetaData {
fn get_metadata() -> HashMap<String, MetaData>;
}
#[derive(Debug)]
pub struct MetaData {
pub completion_hidden: bool,
pub help_text: String,
pub is_special_command: bool,
}
pub trait SettingCompletion {
fn get_value_completions() -> HashMap<String, Vec<String>>;
}
#[derive(Debug, PartialEq)]
pub enum Command<T> {
App(String),
Custom(T),
Map {
action: String,
keys: Vec<Key>,
mode: String,
},
Set(String, Value),
Unmap {
keys: Vec<Key>,
mode: String,
},
}
#[derive(Default)]
pub struct Config {
pub application_commands: Vec<String>,
pub mapping_modes: Vec<&'static str>,
}
pub struct Parser<T> {
column: usize,
config: Config,
include_path: PathBuf,
line: usize,
_phantom: PhantomData<T>,
}
impl<T: EnumFromStr> Parser<T> {
pub fn new() -> Self {
Parser {
column: 1,
config: Config::default(),
include_path: Path::new("./").to_path_buf(),
line: 1,
_phantom: PhantomData,
}
}
pub fn new_with_config(config: Config) -> Self {
Parser {
column: 1,
config: config,
include_path: Path::new("./").to_path_buf(),
line: 1,
_phantom: PhantomData,
}
}
fn check_eol(&self, line: &str, index: usize) -> Result<()> {
if line.len() > index {
let rest = &line[index..];
if let Some(word) = maybe_word(rest) {
let index = rest.find(word).unwrap();
return Err(Error::Parse(ParseError::new(
Parse,
rest.to_string(),
"<end of line>".to_string(),
Pos::new(self.line, self.column + index),
)));
}
}
Ok(())
}
fn custom_command(&self, line: &str, word: &str, start_index: usize, index: usize) -> Result<Command<T>> {
let args =
if line.len() > start_index {
line[start_index..].trim()
}
else if let Ok(true) = T::has_argument(word) {
return Err(self.missing_args(start_index));
}
else {
""
};
if let Ok(command) = T::create(word, args) {
Ok(Custom(command))
}
else if self.config.application_commands.contains(&word.to_string()) {
Ok(App(word.to_string()))
}
else {
Err(Error::Parse(ParseError::new(
UnknownCommand,
word.to_string(),
"command or comment".to_string(),
Pos::new(self.line, index + 1)
)))
}
}
fn get_rest<'a>(&self, line: &'a str, column: usize) -> Result<&'a str> {
if line.len() > column {
Ok(&line[column..])
}
else {
Err(self.missing_args(column))
}
}
fn line(&mut self, line: &str) -> Result<Vec<Command<T>>> {
if let Some(word) = maybe_word(line) {
let index = line.find(word).unwrap();
let start_index = index + word.len() + 1;
self.column = start_index + 1;
let (start3, end3) = word.rsplit_at(3);
let (start5, end5) = word.rsplit_at(5);
if word.starts_with('#') {
return Ok(vec![]);
}
if word == "include" {
let rest = self.get_rest(line, start_index)?;
self.include_command(rest)
}
else {
let command =
if word == "set" {
let rest = self.get_rest(line, start_index)?;
self.set_command(rest)
}
else if end3 == "map" && self.config.mapping_modes.contains(&start3) {
let rest = self.get_rest(line, start_index)?;
self.map_command(rest, start3)
}
else if end5 == "unmap" && self.config.mapping_modes.contains(&start5) {
let rest = self.get_rest(line, start_index)?;
self.unmap_command(rest, start5)
}
else {
self.custom_command(line, word, start_index, index)
};
command.map(|command| vec![command])
}
}
else {
Ok(vec![])
}
}
fn include_command(&mut self, line: &str) -> Result<Vec<Command<T>>> {
let word = word(line);
let index = line.find(word).unwrap();
let after_index = index + word.len() + 1;
self.column += after_index;
self.check_eol(line, after_index)?;
let path = Path::new(&self.include_path).join(word);
let file = File::open(path)?;
let buf_reader = BufReader::new(file);
let commands = self.parse(buf_reader)?;
Ok(commands)
}
fn map_command(&self, line: &str, mode: &str) -> Result<Command<T>> {
let word = word(line);
let index = line.find(word).unwrap();
let rest = &line[index + word.len() ..].trim();
if !rest.is_empty() {
Ok(Map {
action: rest.to_string(),
keys: parse_keys(word, self.line, self.column + index)?,
mode: mode.to_string(),
})
}
else {
Err(Error::Parse(ParseError::new(
Parse,
"<end of line>".to_string(),
"mapping action".to_string(),
Pos::new(self.line, self.column + line.len())
)))
}
}
fn missing_args(&self, column: usize) -> Error {
Error::Parse(ParseError::new(
MissingArgument,
"<end of line>".to_string(),
"command arguments".to_string(),
Pos::new(self.line, column)
))
}
pub fn parse<R: BufRead>(&mut self, input: R) -> Result<Vec<Command<T>>> {
let mut commands = vec![];
for (line_num, input_line) in input.lines().enumerate() {
self.line = line_num + 1;
let mut new_commands = self.line(&input_line?)?;
commands.append(&mut new_commands);
}
Ok(commands)
}
pub fn parse_line(&mut self, line: &str) -> Result<Command<T>> {
let mut commands = self.parse(line.as_bytes())?;
match commands.pop() {
Some(command) => Ok(command),
None => Err(Error::Parse(ParseError::new(
NoCommand,
"comment or <end of line>".to_string(),
"command".to_string(),
Pos::new(self.line, self.column + line.len())
)))
}
}
fn set_command(&mut self, line: &str) -> Result<Command<T>> {
if let Some(words) = words(line, 2) {
let index = line.find(words[0]).unwrap();
let identifier = check_ident(words[0].to_string(), &Pos::new(self.line, self.column + index))?;
let operator = words[1];
let operator_index = line.find(operator).unwrap();
if operator == "=" {
let rest = &line[operator_index + 1..];
self.column += operator_index + 1;
Ok(Set(identifier.to_string(), self.value(rest)?))
}
else {
Err(Error::Parse(ParseError::new(
Parse,
operator.to_string(),
"=".to_string(),
Pos::new(self.line, self.column + operator_index)
)))
}
}
else {
Err(Error::Parse(ParseError::new(
Parse,
"<end of line>".to_string(),
"=".to_string(),
Pos::new(self.line, self.column + line.len()),
)))
}
}
pub fn set_include_path<P: AsRef<Path>>(&mut self, directory: P) {
self.include_path = directory.as_ref().to_path_buf();
}
fn unmap_command(&mut self, line: &str, mode: &str) -> Result<Command<T>> {
let word = word(line);
let index = line.find(word).unwrap();
let after_index = index + word.len() + 1;
self.column += after_index;
self.check_eol(line, after_index)?;
Ok(Unmap {
keys: parse_keys(word, self.line, self.column + index)?,
mode: mode.to_string(),
})
}
fn value(&self, input: &str) -> Result<Value> {
let string: String = input.chars().take_while(|&character| character != '#').collect();
let string = string.trim();
match string {
"" => Err(Error::Parse(ParseError::new(
Parse,
"<end of line>".to_string(),
"value".to_string(),
Pos::new(self.line, self.column + string.len())
))),
"true" => Ok(Bool(true)),
"false" => Ok(Bool(false)),
_ => {
if string.chars().all(|character| character.is_digit(10)) {
Ok(Int(string.parse().unwrap()))
}
else if string.chars().all(|character| character.is_digit(10) || character == '.') {
Ok(Float(string.parse().unwrap()))
}
else {
Ok(Str(input.trim().to_string()))
}
},
}
}
}
#[derive(Debug, PartialEq)]
pub enum Value {
Bool(bool),
Float(f64),
Int(i64),
Str(String),
}
impl Value {
pub fn to_type(&self) -> &str {
match *self {
Bool(_) => "bool",
Float(_) => "float",
Int(_) => "int",
Str(_) => "string",
}
}
}