-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinter.rs
More file actions
110 lines (92 loc) · 2.72 KB
/
linter.rs
File metadata and controls
110 lines (92 loc) · 2.72 KB
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
use std::collections::HashMap;
#[derive(Debug, Default)]
struct Stack<T> {
data: Vec<T>,
}
impl<T> Stack<T> {
fn push(&mut self, element: T) {
self.data.push(element);
}
fn pop(&mut self) -> Option<T> {
self.data.pop()
}
fn read(&self) -> Option<&T> {
self.data.last()
}
}
#[derive(Debug)]
pub struct Linter {
stack: Stack<char>,
braces: HashMap<char, char>,
}
impl Linter {
pub fn new() -> Self {
Self {
stack: Default::default(),
braces: HashMap::from([('(', ')'), ('[', ']'), ('{', '}')]),
}
}
pub fn lint(&mut self, text: &str) -> Result<bool, String> {
for ch in text.chars() {
if self.is_opening_brace(ch) {
self.stack.push(ch);
} else if self.is_closing_brace(ch) {
if let Some(popped_brace) = self.stack.pop() {
if !self.is_match(popped_brace, ch) {
return Err(format!("'{ch}' has mismatched opening brace"));
}
} else {
return Err(format!("'{ch}' does not have opening brace"));
}
}
}
if let Some(last) = self.stack.read() {
return Err(format!("'{last}' does not have closing brace"));
}
Ok(true)
}
fn is_opening_brace(&self, ch: char) -> bool {
self.braces.contains_key(&ch)
}
fn is_closing_brace(&self, ch: char) -> bool {
self.braces.values().any(|&x| x == ch)
}
fn is_match(&self, opening_brace: char, closing_brace: char) -> bool {
*self.braces.get(&opening_brace).unwrap() == closing_brace
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stack() {
let mut stack = Stack {
data: vec![10, 40, 30],
};
assert_eq!(stack.data, vec![10, 40, 30]);
stack.push(33);
assert_eq!(stack.data, vec![10, 40, 30, 33]);
let popped = stack.pop();
assert_eq!(popped, Some(33));
assert_eq!(stack.data, vec![10, 40, 30]);
assert_eq!(stack.read(), Some(&30));
}
#[test]
fn test_lint() {
assert_eq!(
Linter::new().lint("(var x = 2").unwrap_err(),
String::from("'(' does not have closing brace")
);
assert_eq!(
Linter::new().lint("var x = 2;)").unwrap_err(),
String::from("')' does not have opening brace")
);
assert_eq!(
Linter::new().lint("(var x = [1, 2, 3)]").unwrap_err(),
String::from("')' has mismatched opening brace")
);
assert!(Linter::new()
.lint("( var x = { y: [1, 2, 3] } )")
.is_ok());
}
}