Skip to main content

parsed_html/
lib.rs

1#[derive(Debug)]
2pub enum Event {
3    StartElement(String),
4    EndElement(String),
5    TextContent(String),
6    Attribute(String, String),
7}
8
9pub struct Lexer {
10    content: Vec<char>,
11    tag_stack: Vec<String>,
12    events: Vec<Event>,
13}
14
15// ADD MORE NON-CLOSING TAGS
16const NON_CLOSING_TAG_NAME: [ &str;3 ] = [ "meta", "hr", "br" ];
17
18impl Lexer {
19    pub fn new(content: String) -> Self {
20        Self {
21            content: content.chars().collect::<Vec<char>>(),
22            tag_stack: Vec::new(),
23            events: Vec::new(),
24        }
25    }
26
27    pub fn parse(&mut self) -> &[Event] {
28        while !self.content.is_empty() {
29            self.take_whitespaces();
30
31            if self.content.is_empty() {
32                break;
33            }
34
35            if self.content.len() > 1 && self.content[0] == '<' && self.content[1] == '!' {
36                self.take_doctype();
37            }
38
39            // TODO: Implement html comment.
40
41            // End element
42            if self.content.len() > 1 && self.content[0] == '<' && self.content[1] == '/' {
43                self.take_end_element();
44            }
45
46            // Start element
47            if !self.content.is_empty() && self.content[0] == '<' {
48                self.take_start_element();
49            }
50
51            // Text content
52            if !self.content.is_empty() {
53                self.take_text_content();
54            }
55        }
56
57        &self.events
58    }
59
60    fn take_doctype(&mut self) {
61        let tag_name = self.take_tag_name(2);
62        self.events.push(Event::StartElement(tag_name.clone()));
63        self.tag_stack.push(tag_name.clone());
64
65        self.take_whitespaces();
66        let doctype_type = 
67            self.take_while(|x| x.is_alphabetic());
68
69        // LET THE DEV USE THE DOCTYPE TYPE DETECTION
70        self.events.push(Event::Attribute("type".to_string(), doctype_type));
71
72        self.take_whitespaces();
73
74        // End element validation
75        if self.tag_stack.last() == Some(&tag_name) {
76            self.tag_stack.pop();
77            self.events.push(Event::EndElement(tag_name.clone()));
78        } else {
79            eprintln!("ERROR: Invalid closing tag `{tag_name}`.")
80        }
81
82        if self.content[0] == '>' {
83            self.get_slice(0, 1);
84        } else {
85            eprintln!("ERROR: Invalid closing tag with extra args.");
86        }
87    }
88
89    // `</TAG_NAME>``
90    fn take_end_element(&mut self) {
91        let tag_name = self.take_tag_name(2);
92        self.events.push(Event::EndElement(tag_name.clone()));
93
94        // End element validation
95        if self.tag_stack.last() == Some(&tag_name) {
96            self.tag_stack.pop();
97        } else {
98            eprintln!("ERROR: Invalid closing tag `{tag_name}`.")
99        }
100
101        self.take_whitespaces();
102
103        if self.content[0] == '>' {
104            self.get_slice(0, 1);
105        } else {
106            eprintln!("ERROR: Invalid closing tag with extra args.");
107        }
108    }
109
110    // `<TAG_NAME ATTRIBUTES>` | `<TAG_NAME ATTRIBUTES/>`
111    fn take_start_element(&mut self) {
112        let tag_name = self.take_tag_name(1);
113        self.events.push(Event::StartElement(tag_name.clone()));
114        self.tag_stack.push(tag_name.clone());
115
116        self.take_attributes();
117        self.take_whitespaces();
118
119        // SELF_END_ELEMENT `/>`
120        if self.content.len() > 1 && self.content[0] == '/' && self.content[1] == '>' {
121            self.get_slice(0, 2);
122
123            if let Some(last_tag) = self.tag_stack.pop() {
124                self.events.push(Event::EndElement(last_tag));
125            } else {
126                eprintln!("ERROR: there is no tag.");
127            }
128        }
129        // EXPECTED `>`
130        else if self.content[0] == '>' {
131            self.get_slice(0, 1);
132
133            // DETECT IF IT'S A NON-CLOSING TAG
134            if NON_CLOSING_TAG_NAME.contains(&tag_name.as_str()) {
135                if let Some(last_tag) = self.tag_stack.pop() {
136                    self.events.push(Event::EndElement(last_tag));
137                } else {
138                    eprintln!("ERROR: there is no tag.");
139                }
140            }
141        } else {
142            eprintln!("ERROR: expected `>` on start element.");
143        }
144    }
145
146    fn take_tag_name(&mut self, start: usize) -> String {
147        self.take_while_from(start, |x| x.is_alphabetic() || x.is_alphanumeric())
148    }
149
150    fn take_text_content(&mut self) {
151        let value = self.take_while(|x| x != '<');
152        let value = value.replace("\n", "");
153        let value = value.replace("\t", "");
154        let value = value.trim().to_string();
155
156        if value.is_empty() {
157            return;
158        }
159
160        self.events.push(Event::TextContent(value));
161    }
162
163    fn take_attributes(&mut self) {
164        // after start a element, until we go to '>' | '/', means we are collecting attributes
165        // eg, `<tag key=value key=value>` || `<tag key=value />`;
166        while (self.content[0] != '>') && (self.content[0] != '/') {
167            self.take_attribute()
168        }
169    }
170
171    // `KEY=VALUE` || `KEY`
172    fn take_attribute(&mut self) {
173        self.take_whitespaces();
174
175        let key =
176            self.take_while(|x| x.is_alphabetic() || x.is_alphanumeric() || x == '-' || x == '_');
177
178        let value = self.take_attribute_value();
179
180        self.events.push(Event::Attribute(key, value));
181
182        self.take_whitespaces();
183    }
184
185    fn take_attribute_value(&mut self) -> String {
186        if self.content.is_empty() || self.content[0] != '=' {
187            return String::from("");
188        }
189
190        self.get_slice(0, 1);
191
192        let mut qoute_count = 0;
193
194        // TODO: Implement string logic.
195        let value = self.take_while(|x| {
196            // String identifire
197            if x == '"' {
198                qoute_count += 1;
199                return if qoute_count == 2 { false } else { true };
200            }
201
202            // If value is a string
203            if qoute_count == 1 {
204                return true;
205            }
206
207            x != ' ' || x != '>' || x != '/'
208        });
209
210        if qoute_count == 0 {
211            return value;
212        }
213
214        // when qoute == 2 THEN we break, means we don't count ending '"'
215        // we need to clean up that '"'
216        self.get_slice(0, 1);
217
218        value[1..].to_string()
219    }
220
221    fn take_whitespaces(&mut self) {
222        self.take_while(|x| x.is_whitespace());
223    }
224
225    fn take_while<F>(&mut self, predict: F) -> String
226    where
227        F: FnMut(char) -> bool,
228    {
229        self.take_while_from(0, predict)
230    }
231
232    fn take_while_from<F>(&mut self, start: usize, mut predict: F) -> String
233    where
234        F: FnMut(char) -> bool,
235    {
236        let mut i = start;
237
238        while self.content.len() > i && predict(self.content[i]) {
239            i += 1;
240        }
241
242        self.get_slice(start, i)
243    }
244
245    fn get_slice(&mut self, from: usize, to: usize) -> String {
246        let value = self.content[from..to].iter().collect::<String>();
247        self.content = self.content[to..].to_vec();
248
249        value
250    }
251}