-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparser.rs
1767 lines (1572 loc) · 56.7 KB
/
parser.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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::errors::{Error, GuraError, ValueError};
use crate::pretty_print_float::PrettyPrintFloatWithFallback;
use indexmap::IndexMap;
use itertools::Itertools;
use lazy_static::lazy_static;
use std::{
borrow::Cow,
cmp::Ordering,
collections::{HashMap, HashSet},
env,
f64::{INFINITY, NAN, NEG_INFINITY},
fmt::{self, Write as _},
fs,
ops::Index,
path::Path,
usize,
};
use unicode_segmentation::UnicodeSegmentation;
/// Number chars
const BASIC_NUMBERS_CHARS: &str = "0-9";
const HEX_OCT_BIN: &str = "A-Fa-fxob";
const INF_AND_NAN: &str = "in"; // The rest of the chars are defined in hex_oct_bin
/// Acceptable chars for keys
const KEY_ACCEPTABLE_CHARS: &str = "0-9A-Za-z_";
/// New line chars
const NEW_LINE_CHARS: &str = "\n\x0c\x0b\x08";
lazy_static! {
/// Special characters that need escaped when parsing Gura texts
static ref CHARS_TO_ESCAPE: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("b", "\x08");
m.insert("f", "\x0c");
m.insert("n", "\n");
m.insert("r", "\r");
m.insert("t", "\t");
m.insert("\"", "\"");
m.insert("\\", "\\");
m.insert("$", "$");
m
};
/// Sequences that need escaped when dumping string values
static ref SEQUENCES_TO_ESCAPE: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("\x08", "\\b");
m.insert("\x0c", "\\f");
m.insert("\n", "\\n");
m.insert("\r", "\\r");
m.insert("\t", "\\t");
m.insert("\"", "\\\"");
m.insert("\\", "\\\\");
m
};
}
// Indentation of 4 spaces
const INDENT: &str = " ";
/// Useful for number parsing
#[derive(Debug, PartialEq, Eq)]
enum NumberType {
Integer,
Float,
}
type RuleResult = Result<GuraType, GuraError>;
type Rules = Vec<Box<dyn Fn(&mut Input) -> RuleResult>>;
impl Eq for VariableValueType {}
impl PartialEq for VariableValueType {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(VariableValueType::String(value1), VariableValueType::String(value2)) => {
value1 == value2
}
(VariableValueType::Integer(value1), VariableValueType::Integer(value2)) => {
value1 == value2
}
(VariableValueType::Float(value1), VariableValueType::Float(value2)) => {
value1.partial_cmp(value2) == Some(Ordering::Equal)
}
_ => false,
}
}
}
/// Defines all the possible types for a variable: numbers or strings
#[derive(Debug, Clone)]
enum VariableValueType {
String(String),
Integer(isize),
Float(f64),
}
/// Data types to be returned by match expression methods.
#[derive(Debug, Clone, PartialEq)]
pub enum GuraType {
/// Null values.
Null,
/// Indentation (intended to be used internally).
Indentation(usize),
/// An empty line (intended to be used internally).
UselessLine,
/// Pair of key/value. (intended to be used internally. Users normally uses Object to map key/values).
Pair(String, Box<GuraType>, usize),
/// Comment (intended to be used internally).
Comment,
/// Importing sentence (intended to be used internally).
Import(String),
/// Indicates matching with a variable definition (intended to be used internally).
Variable,
// Uses IndexMap as it preserves the order of insertion
/// Object with information about indentation (intended to be used internally).
ObjectWithWs(IndexMap<String, GuraType>, usize),
/// Object with its key/value pairs.
Object(IndexMap<String, GuraType>),
/// Boolean values.
Bool(bool),
/// String values.
String(String),
/// Integer values.
Integer(isize),
/// Big integer values.
BigInteger(i128),
/// Float values.
Float(f64),
/// List of Gura values.
Array(Vec<GuraType>),
/// Spaces or new line characters (intended to be used internally).
WsOrNewLine,
/// Indicates the ending of an object (intended to be used internally).
BreakParent,
}
impl fmt::Display for GuraType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&dump(self))
}
}
/// Implements indexing by `&str` to easily access object members:
impl<T> Index<T> for GuraType
where
T: AsRef<str>,
{
type Output = GuraType;
fn index(&self, index: T) -> &GuraType {
match *self {
GuraType::Object(ref object) => &object[index.as_ref()],
_ => panic!("Using index in an non object type. Check if the Gura object contains the key first"),
}
}
}
/// Implements Eq with primitive types
// TODO: refactor with macros
impl PartialEq<bool> for GuraType {
fn eq(&self, other: &bool) -> bool {
match self {
GuraType::Bool(value) => value == other,
_ => false,
}
}
}
impl PartialEq<GuraType> for bool {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<isize> for GuraType {
fn eq(&self, other: &isize) -> bool {
match self {
GuraType::Integer(value) => value == other,
_ => false,
}
}
}
impl PartialEq<GuraType> for isize {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<i32> for GuraType {
fn eq(&self, other: &i32) -> bool {
match self {
GuraType::Integer(value) => (*value as i32) == *other,
GuraType::BigInteger(value) => (*value as i32) == *other,
_ => false,
}
}
}
impl PartialEq<GuraType> for i32 {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<i64> for GuraType {
fn eq(&self, other: &i64) -> bool {
match self {
GuraType::Integer(value) => (*value as i64) == *other,
GuraType::BigInteger(value) => (*value as i64) == *other,
_ => false,
}
}
}
impl PartialEq<GuraType> for i64 {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<i128> for GuraType {
fn eq(&self, other: &i128) -> bool {
match self {
GuraType::Integer(value) => (*value as i128) == *other,
GuraType::BigInteger(value) => value == other,
_ => false,
}
}
}
impl PartialEq<GuraType> for i128 {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<f32> for GuraType {
fn eq(&self, other: &f32) -> bool {
match self {
GuraType::Float(value) => *value == *other as f64,
_ => false,
}
}
}
impl PartialEq<GuraType> for f32 {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<f64> for GuraType {
fn eq(&self, other: &f64) -> bool {
match self {
GuraType::Float(value) => (value.is_nan() && other.is_nan()) || value == other,
_ => false,
}
}
}
impl PartialEq<GuraType> for f64 {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<&str> for GuraType {
fn eq(&self, other: &&str) -> bool {
match self {
GuraType::String(value) => value == *other,
_ => false,
}
}
}
impl PartialEq<GuraType> for &str {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl PartialEq<String> for GuraType {
fn eq(&self, other: &String) -> bool {
match self {
GuraType::String(value) => *value == *other,
_ => false,
}
}
}
impl PartialEq<GuraType> for String {
fn eq(&self, other: &GuraType) -> bool {
other.eq(self)
}
}
impl GuraType {
/// Gets an iterator over the references to the elements of an object.
///
/// Returns an error if the Gura type is not an object
pub fn iter(&self) -> Result<indexmap::map::Iter<'_, String, GuraType>, &str> {
match self {
GuraType::Object(hash_map) => Ok(hash_map.iter()),
_ => Err("This struct is not an object"),
}
}
/// Gets an iterator over the elements of an object.
///
/// Returns an error if the Gura type is not an object
pub fn iter_mut(&mut self) -> Result<indexmap::map::IterMut<'_, String, GuraType>, &str> {
match self {
GuraType::Object(hash_map) => Ok(hash_map.iter_mut()),
_ => Err("This struct is not an object"),
}
}
/// Checks if a specific key is defined in the Gura Object
///
/// If the Gura type is not an object it returns `false`
pub fn contains_key(&self, key: &str) -> bool {
match self {
GuraType::Object(hash_map) => hash_map.contains_key(key),
_ => false,
}
}
}
/// Struct to handle user Input internally
struct Input {
/// Text as a Vec of Unicode chars (grapheme clusters)
text: Vec<String>,
pos: isize,
line: usize,
len: isize,
/// Vec of Grapheme clusters vecs
cache: HashMap<String, Vec<Vec<String>>>,
variables: HashMap<String, VariableValueType>,
indentation_levels: Vec<usize>,
imported_files: HashSet<String>,
}
impl Input {
// TODO: replace this with the same logic as restart_params
fn new() -> Self {
Input {
cache: HashMap::new(),
pos: -1,
line: 1,
len: 0,
text: Vec::new(),
variables: HashMap::new(),
indentation_levels: Vec::new(),
imported_files: HashSet::new(),
}
}
/// Sets the params to start parsing from a specific text.
///
/// # Arguments
///
/// * text - Text to set as the internal text to be parsed.
fn restart_params(&mut self, text: &str) {
let graph = get_graphemes_cluster(text);
self.text = graph;
self.pos = -1;
self.line = 1;
self.len = self.text.len() as isize - 1;
}
/// Removes, if exists, the last indentation level.
fn remove_last_indentation_level(&mut self) {
if !self.indentation_levels.is_empty() {
self.indentation_levels.pop();
}
}
}
/// Generates a Vec with every Grapheme cluster from an String
fn get_graphemes_cluster(text: &str) -> Vec<String> {
UnicodeSegmentation::graphemes(text, true)
.map(String::from)
.collect()
}
/// Computes imports and matches the first expression of the file.Finally consumes all the useless lines.
fn start(text: &mut Input) -> RuleResult {
compute_imports(text, None)?;
let result = matches(text, vec![Box::new(object)])?;
eat_ws_and_new_lines(text);
Ok(result)
}
/// Matches with any primitive or complex type.
fn any_type(text: &mut Input) -> RuleResult {
let result = maybe_match(text, vec![Box::new(primitive_type)])?;
if let Some(result) = result {
Ok(result)
} else {
matches(text, vec![Box::new(complex_type)])
}
}
/// Matches with a primitive value: null, bool, strings(all of the four kind of string), number or variables values.
fn primitive_type(text: &mut Input) -> RuleResult {
maybe_match(text, vec![Box::new(ws)])?;
let result = matches(
text,
vec![
Box::new(null),
Box::new(boolean),
Box::new(basic_string),
Box::new(literal_string),
Box::new(number),
Box::new(variable_value),
Box::new(empty_object),
],
);
maybe_match(text, vec![Box::new(ws)])?;
result
}
/// Matches with a useless line. A line is useless when it contains only whitespaces
/// and/or a comment finishing in a new line.
fn useless_line(text: &mut Input) -> RuleResult {
matches(text, vec![Box::new(ws)])?;
let comment = maybe_match(text, vec![Box::new(comment)])?;
let initial_line = text.line;
maybe_match(text, vec![Box::new(new_line)])?;
let is_new_line = (text.line - initial_line) == 1;
if comment.is_none() && !is_new_line {
return Err(GuraError {
pos: text.pos + 1,
line: text.line,
msg: String::from("It is a valid line"),
kind: Error::ParseError,
});
}
Ok(GuraType::UselessLine)
}
/// Matches with a list or an object.
fn complex_type(text: &mut Input) -> RuleResult {
matches(text, vec![Box::new(list), Box::new(object)])
}
/// Consumes `null` keyword and returns null.
fn null(text: &mut Input) -> RuleResult {
keyword(text, &["null"])?;
Ok(GuraType::Null)
}
/// Consumes `empty` keyword and returns an empty object.
fn empty_object(text: &mut Input) -> RuleResult {
keyword(text, &["empty"])?;
Ok(GuraType::Object(IndexMap::new()))
}
/// Matches boolean values.
fn boolean(text: &mut Input) -> RuleResult {
let value = keyword(text, &["true", "false"])? == "true";
Ok(GuraType::Bool(value))
}
/// Matches with a simple / multiline basic string.
fn basic_string(text: &mut Input) -> RuleResult {
let quote = keyword(text, &["\"\"\"", "\""])?;
let is_multiline = quote == "\"\"\"";
// NOTE: a newline immediately following the opening delimiter will be trimmed.All other whitespace and
// newline characters remain intact.
if is_multiline && maybe_char(text, &Some(String::from("\n")))?.is_some() {
text.line += 1;
}
let mut final_string: String = String::new();
loop {
let closing_quote = maybe_keyword(text, &["e])?;
if closing_quote.is_some() {
break;
}
let current_char = char(text, &None)?;
if current_char == "\\" {
let escape = char(text, &None)?;
// Checks backslash followed by a newline to trim all whitespaces
if is_multiline && escape == "\n" {
eat_ws_and_new_lines(text)
} else {
// Supports Unicode of 16 and 32 bits representation
if escape == "u" || escape == "U" {
let num_chars_code_point = if escape == "u" { 4 } else { 8 };
let mut code_point: String = String::with_capacity(num_chars_code_point);
for _ in 0..num_chars_code_point {
let code_point_char = char(text, &Some(String::from("0-9a-fA-F")))?;
code_point.push_str(&code_point_char);
}
// Gets hex value and gets the corresponding char
let hex_value = u32::from_str_radix(&code_point, 16);
match hex_value {
Err(_) => {
return Err(GuraError {
pos: text.pos,
line: text.line,
msg: String::from("Bad hex value"),
kind: Error::ParseError,
});
}
Ok(hex_value) => {
let char_value = char::from_u32(hex_value).unwrap(); // Converts from UNICODE to string
final_string.push(char_value)
}
};
} else {
// Gets escaped char or interprets as literal
let escaped_char = match CHARS_TO_ESCAPE.get(escape.as_str()) {
Some(v) => Cow::Borrowed(*v),
None => Cow::Owned(current_char + &escape),
};
final_string.push_str(&escaped_char);
}
}
} else {
// Computes variables values in string
if current_char == "$" {
let initial_pos = text.pos;
let initial_line = text.line;
let var_name = get_var_name(text)?;
let var_value_str: String =
match get_variable_value(text, &var_name, initial_pos, initial_line)? {
GuraType::Integer(number) => number.to_string(),
GuraType::Float(number) => number.to_string(),
GuraType::String(value) => value,
_ => "".to_string(),
};
final_string.push_str(&var_value_str);
} else {
final_string.push_str(¤t_char);
}
}
}
Ok(GuraType::String(final_string))
}
/// Gets a variable name char by char.
fn get_var_name(text: &mut Input) -> Result<String, GuraError> {
let key_acceptable_chars = Some(String::from(KEY_ACCEPTABLE_CHARS));
let mut var_name = String::new();
while let Some(var_name_char) = maybe_char(text, &key_acceptable_chars)? {
var_name.push_str(&var_name_char);
}
Ok(var_name)
}
/// Computes all the import sentences in Gura file taking into consideration relative paths to imported files.
///
/// # Arguments
///
/// * parentDirPath - Current parent directory path to join with imported files.
/// * importedFiles - Set with already imported files to raise an error in case of importing the same file more than once.
///
/// Returns a set with imported files after all the imports to reuse in the importation process of the imported Gura files.
fn compute_imports(text: &mut Input, parent_dir_path: Option<String>) -> Result<(), GuraError> {
let mut files_to_import: Vec<(String, Option<String>)> = Vec::new();
// First, consumes all the import sentences to replace all of them
while text.pos < text.len {
let match_result = maybe_match(
text,
vec![
Box::new(gura_import),
Box::new(variable),
Box::new(useless_line),
],
)?;
if match_result.is_none() {
break;
}
// Checks, it could be a comment
if let Some(GuraType::Import(file_to_import)) = match_result {
files_to_import.push((file_to_import, parent_dir_path.clone()));
}
}
let mut final_content = String::new();
if !files_to_import.is_empty() {
for (mut file_to_import, origin_file_path) in files_to_import {
// Gets the final file path considering parent directory
if let Some(origin_path) = origin_file_path {
file_to_import = Path::new(&origin_path)
.join(&file_to_import)
.to_string_lossy()
.to_string();
}
// Files can be imported only once. This prevents circular reference
if text.imported_files.contains(&file_to_import) {
return Err(GuraError {
pos: text.pos - file_to_import.len() as isize - 1, // -1 for the quotes (")
line: text.line,
msg: format!("The file \"{}\" has been already imported", file_to_import),
kind: Error::DuplicatedImportError,
});
}
// Gets content considering imports
let content = match fs::read_to_string(&file_to_import) {
Ok(content) => content,
Err(_) => {
return Err(GuraError {
pos: 0,
line: 0,
msg: format!("The file \"{}\" does not exist", file_to_import),
kind: Error::FileNotFoundError,
});
}
};
let parent_dir_path = Path::new(&file_to_import).parent().unwrap();
let mut empty_input = Input::new();
let content_with_import = get_text_with_imports(
&mut empty_input,
&content,
parent_dir_path.to_str().unwrap().to_owned(),
)?;
final_content.push_str(&(content_with_import.iter().cloned().collect::<String>()));
final_content.push('\n');
text.imported_files.insert(file_to_import);
}
// Sets as new text
let pos_usize = (text.pos + 1) as usize;
let rest_of_content = get_string_from_slice(&text.text[pos_usize..]);
text.restart_params(&(final_content + &rest_of_content));
}
Ok(())
}
/// Matches with an already defined variable and gets its value.
fn variable_value(text: &mut Input) -> RuleResult {
// TODO: consider using char(text, vec![String::from("\"")])
keyword(text, &["$"])?;
if let GuraType::String(key_name) = matches(text, vec![Box::new(unquoted_string)])? {
let pos = text.pos - key_name.len() as isize;
let line = text.line;
let var_value = get_variable_value(text, &key_name, pos, line)?;
Ok(var_value)
} else {
Err(GuraError {
pos: text.pos,
line: text.line,
msg: String::from("Invalid variable name"),
kind: Error::ParseError,
})
}
}
/// Checks that the parser has reached the end of file, otherwise it will raise a `ParseError`.
///
/// # Errors
///
/// * ParseError - If EOL has not been reached.
fn assert_end(text: &mut Input) -> Result<(), GuraError> {
if text.pos < text.len {
let error_pos = text.pos + 1;
Err(GuraError {
pos: error_pos,
line: text.line,
msg: format!(
"Expected end of string but got \"{}\"",
text.text[error_pos as usize]
),
kind: Error::ParseError,
})
} else {
Ok(())
}
}
/// Generates a String from a slice of Strings (Grapheme clusters)
fn get_string_from_slice(slice: &[String]) -> String {
slice.iter().cloned().collect()
}
/// Generates a list of char from a list of char which could container char ranges (i.e. a-z or 0-9).
///
/// Returns a Vec of Grapheme clusters vectors.
fn split_char_ranges(text: &mut Input, chars: &str) -> Result<Vec<Vec<String>>, ValueError> {
if text.cache.contains_key(chars) {
return Ok(text.cache.get(chars).unwrap().to_vec());
}
let chars_graph = get_graphemes_cluster(chars);
let length = chars_graph.len();
let mut result: Vec<Vec<String>> = Vec::new();
let mut index = 0;
while index < length {
if index + 2 < length && chars_graph[index + 1] == "-" {
if chars_graph[index] >= chars_graph[index + 2] {
return Err(ValueError {});
}
let some_chars = &chars_graph[index..index + 3];
result.push(some_chars.to_vec());
index += 3;
} else {
// Array of one char
result.push(vec![chars_graph[index].clone()]);
index += 1;
}
}
text.cache.insert(chars.to_string(), result.clone());
Ok(result)
}
/// Matches a list of specific chars and returns the first that matched. If any matched, it will raise a `ParseError`.
///
/// `chars` argument can be a range like "a-zA-Z" and they will be properly handled.
fn char(text: &mut Input, chars: &Option<String>) -> Result<String, GuraError> {
if text.pos >= text.len {
return Err(GuraError {
pos: text.pos + 1,
line: text.line,
msg: format!(
"Expected {} but got end of string",
match chars {
None => String::from("next character"),
Some(chars) => format!("[{}]", chars),
}
),
kind: Error::ParseError,
});
}
let next_char_pos = text.pos + 1;
let next_char_pos_usize = next_char_pos as usize;
match chars {
None => {
let next_char = &text.text[next_char_pos_usize];
text.pos += 1;
Ok(next_char.to_string())
}
Some(chars_value) => {
// Unwrap is safe as ValueError can only raise if the crate contains a bug in a char range
for char_range in split_char_ranges(text, chars_value).unwrap() {
if char_range.len() == 1 {
let next_char = &text.text[next_char_pos_usize];
if *next_char == char_range[0] {
text.pos += 1;
return Ok(next_char.to_string());
}
} else if char_range.len() == 3 {
let next_char = &text.text[next_char_pos_usize];
let bottom = &char_range[0];
let top = &char_range[2];
if bottom <= next_char && next_char <= top {
text.pos += 1;
return Ok(next_char.to_string());
}
}
}
Err(GuraError {
pos: next_char_pos,
line: text.line,
msg: format!(
"Expected chars [{}] but got \"{}\"",
chars_value, text.text[next_char_pos_usize]
),
kind: Error::ParseError,
})
}
}
}
/// Matches specific keywords. If any matched, it will raise a `ParseError`.
fn keyword(text: &mut Input, keywords: &[&str]) -> Result<String, GuraError> {
if text.pos >= text.len {
return Err(GuraError {
pos: text.pos,
line: text.line,
msg: format!(
"Expected \"{}\" but got end of string",
keywords.iter().join(", ")
),
kind: Error::ParseError,
});
}
for keyword in keywords {
let low = (text.pos + 1) as usize;
let high = (low + keyword.len()).min(text.text.len());
// This checking prevents index out of range
let substring = get_string_from_slice(&text.text[low..high]);
if substring == *keyword {
text.pos += keyword.len() as isize;
return Ok(keyword.to_string());
}
}
let error_pos = text.pos + 1;
Err(GuraError {
pos: error_pos,
line: text.line,
msg: format!(
"Expected \"{}\" but got \"{}\"",
keywords.iter().join(", "),
text.text[error_pos as usize]
),
kind: Error::ParseError,
})
}
/// Gets the Exception line and position considering indentation. Useful for InvalidIndentationError exceptions
fn exception_data_with_initial_data(
child_indentation_level: usize,
initial_line: usize,
initial_pos: isize,
) -> (usize, isize) {
let exception_pos = initial_pos + 2 + child_indentation_level as isize;
let exception_line = initial_line + 1;
(exception_line, exception_pos)
}
/// Matches specific rules. A rule does not match if its method raises `ParseError`.
///
/// Returns the first matched rule method's result.
fn matches(text: &mut Input, rules: Rules) -> RuleResult {
let mut last_error_pos: isize = -1;
let mut last_exception: Option<GuraError> = None;
for rule in rules {
let initial_pos = text.pos;
let initial_line = text.line;
match rule(text) {
Err(an_error) => {
// Only considers ParseError instances
if an_error.kind == Error::ParseError {
text.pos = initial_pos;
text.line = initial_line;
if an_error.pos > last_error_pos {
last_error_pos = an_error.pos;
last_exception = Some(an_error);
}
} else {
// Any other kind of exception must be raised
return Err(an_error);
}
}
result => return result,
}
}
// Unwrap is safe as if this line is reached no rule matched
Err(last_exception.unwrap())
}
// TODO: consider changing chars: &Option<&str>
/// Like char() but returns None instead of raising ParseError
fn maybe_char(text: &mut Input, chars: &Option<String>) -> Result<Option<String>, GuraError> {
match char(text, chars) {
Err(e) => {
if e.kind == Error::ParseError {
Ok(None)
} else {
Err(e)
}
}
result => Ok(result.ok()),
}
}
/// Like match() but returns None instead of raising ParseError
fn maybe_match(text: &mut Input, rules: Rules) -> Result<Option<GuraType>, GuraError> {
match matches(text, rules) {
Err(e) => {
if e.kind == Error::ParseError {
Ok(None)
} else {
Err(e)
}
}
result => Ok(result.ok()),
}
}
/// Like keyword() but returns None instead of raising ParseError
fn maybe_keyword(text: &mut Input, keywords: &[&str]) -> Result<Option<String>, GuraError> {
match keyword(text, keywords) {
Err(e) => {
if e.kind == Error::ParseError {
Ok(None)
} else {
Err(e)
}
}
result => Ok(result.ok()),
}
}
/// Converts a GuraType::ObjectWithWs in GuraType::Object.
/// Any other types are returned as they are
fn object_ws_to_simple_object(object: GuraType) -> GuraType {
if let GuraType::ObjectWithWs(values, _) = object {
GuraType::Object(values)
} else {
object
}
}
/// Parses a text in Gura format.
///
/// # Examples
///
/// ```
/// use gura::parse;
///
/// let gura_string = r##"
/// title: "Gura Example"
/// number: 13.4
/// an_object:
/// name: "John"
/// surname: "Wick"
/// has_pet: false
/// "##.to_string();
///
/// let parsed = parse(&gura_string).unwrap();
///
/// assert_eq!("Gura Example", parsed["title"]);
/// assert_eq!(13.4, parsed["number"]);
///
/// let obj = &parsed["an_object"];
/// assert_eq!("John", obj["name"]);
/// assert_eq!("Wick", obj["surname"]);
/// assert_eq!(false, obj["has_pet"]);
/// ```
///
/// # Errors
///
/// This function could throw any kind of error listed
/// in [Gura specs](https://gura.netlify.app/docs/gura#standard-errors).
pub fn parse(text: &str) -> RuleResult {
let text_parser: &mut Input = &mut Input::new();
text_parser.restart_params(text);
let result = start(text_parser)?;
assert_end(text_parser)?;
// Only objects are valid as final result
match result {
GuraType::ObjectWithWs(values, _) => Ok(GuraType::Object(values)),
_ => Ok(GuraType::Object(IndexMap::new())),
}
}
/// Matches with a new line. I.e any of the following chars:
/// * \n - U+000A
/// * \f - U+000C
/// * \v - U+000B
/// * \r - U+0008
fn new_line(text: &mut Input) -> RuleResult {
let new_line_chars = Some(String::from(NEW_LINE_CHARS));
char(text, &new_line_chars)?;
// If this line is reached then new line matched as no exception was raised
text.line += 1;
Ok(GuraType::WsOrNewLine)
}
/// Matches with a comment.
fn comment(text: &mut Input) -> RuleResult {
keyword(text, &["#"])?;
while text.pos < text.len {
let pos_usize = (text.pos + 1) as usize;
let char = &text.text[pos_usize];
text.pos += 1;