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
use std::cell::RefCell;
use std::iter::Peekable;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Kind {
String,
Integer,
Boolean,
Identifier,
Curly,
Parentheses,
Colon,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Token {
pub kind: Kind,
pub binding: String,
}
impl Token {
pub fn new(kind: Kind, binding: &'static str) -> Token {
Token {
kind,
binding: String::from(binding),
}
}
pub fn change_kind(&self, kind: Kind) -> Token {
Token {
kind,
binding: self.binding.to_owned(),
}
}
}
fn tokenize_string<'a, It>(it: &mut Peekable<It>,
buffer: &RefCell<String>,
ch: char)
-> Result<String, &'a str>
where It: Iterator<Item = char>
{
let mut escaped = false;
let quote = ch.clone();
let quote_str = quote;
while let Some(ch) = it.peek().map(|c| *c) {
if escaped {
buffer.borrow_mut().push(ch);
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if ch == quote {
it.next();
let mut result = String::new();
result.push(quote_str);
result.push_str(buffer.borrow().as_str());
result.push(quote_str);
return Ok(result);
} else {
buffer.borrow_mut().push(ch);
}
it.next();
}
Err("Can't parse string")
}
pub fn scan(raw_query: &str) -> Vec<Token> {
let query = raw_query.to_owned() + " ";
let mut it = query.chars().peekable();
let tokens = RefCell::new(vec![]);
let buffer = RefCell::new(String::new());
let bind_identifier = |binding: String| if !binding.is_empty() {
tokens
.borrow_mut()
.push(
Token {
kind: Kind::Identifier,
binding,
},
);
buffer.borrow_mut().clear()
};
let consume_token = |token: Token| {
bind_identifier(buffer.clone().into_inner());
tokens.borrow_mut().push(token)
};
while let Some(ch) = it.next() {
match ch {
'"' | '\'' => {
let str = tokenize_string(&mut it, &buffer, ch).unwrap();
bind_identifier(str);
}
' ' => bind_identifier(buffer.clone().into_inner()),
':' => consume_token(Token::new(Kind::Colon, ":")),
'{' => consume_token(Token::new(Kind::Curly, "{")),
'}' => consume_token(Token::new(Kind::Curly, "}")),
'(' => consume_token(Token::new(Kind::Parentheses, "(")),
')' => consume_token(Token::new(Kind::Parentheses, ")")),
_ => buffer.borrow_mut().push(ch),
}
if ch != '"' || ch != '\'' {
continue;
}
}
tokens.to_owned().into_inner()
}