tailwind-rs-postcss 0.15.4

PostCSS integration for Tailwind-RS Core
Documentation
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
//! CSS Parser implementation
//!
//! This module provides CSS parsing functionality with support for
//! modern CSS features and PostCSS compatibility.

use crate::ast::{CSSAtRule, CSSDeclaration, CSSNode, CSSRule, SourcePosition};
use crate::error::{PostCSSError, Result};
use serde::{Deserialize, Serialize};
// use std::collections::HashMap;

/// CSS parser with configurable options
#[derive(Debug, Clone)]
pub struct CSSParser {
    options: ParseOptions,
}

/// Parser configuration options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParseOptions {
    /// Enable source position tracking
    pub track_positions: bool,
    /// Enable strict parsing
    pub strict_mode: bool,
    /// Enable CSS custom properties support
    pub custom_properties: bool,
    /// Enable CSS nesting support
    pub nesting: bool,
    /// Enable CSS container queries support
    pub container_queries: bool,
    /// Enable CSS cascade layers support
    pub cascade_layers: bool,
    /// Maximum nesting depth
    pub max_nesting_depth: usize,
    /// Custom parser plugins
    pub plugins: Vec<String>,
}

impl Default for ParseOptions {
    fn default() -> Self {
        Self {
            track_positions: true,
            strict_mode: false,
            custom_properties: true,
            nesting: true,
            container_queries: true,
            cascade_layers: true,
            max_nesting_depth: 10,
            plugins: Vec::new(),
        }
    }
}

impl CSSParser {
    /// Create a new CSS parser with options
    pub fn new(options: ParseOptions) -> Self {
        Self { options }
    }

    /// Parse CSS input into AST
    pub fn parse(&self, input: &str) -> Result<CSSNode> {
        let mut parser_state = ParserState::new(input, &self.options);
        self.parse_stylesheet(&mut parser_state)
    }

    /// Parse a stylesheet (root level)
    fn parse_stylesheet(&self, state: &mut ParserState) -> Result<CSSNode> {
        let mut rules = Vec::new();

        while !state.is_eof() {
            state.skip_whitespace();

            if state.is_eof() {
                break;
            }

            // Handle at-rules
            if state.peek() == Some('@') {
                if let Ok(at_rule) = self.parse_at_rule(state) {
                    rules.push(CSSRule {
                        selector: format!("@{}", at_rule.name),
                        declarations: Vec::new(),
                        nested_rules: vec![CSSRule {
                            selector: at_rule.params.clone(),
                            declarations: Vec::new(),
                            nested_rules: Vec::new(),
                            media_query: None,
                            specificity: 0,
                            position: at_rule.position.clone(),
                        }],
                        media_query: None,
                        specificity: 0,
                        position: at_rule.position.clone(),
                    });
                }
            } else {
                // Parse regular rule
                if let Ok(rule) = self.parse_rule(state) {
                    rules.push(rule);
                }
            }
        }

        Ok(CSSNode::Stylesheet(rules))
    }

    /// Parse a CSS rule
    fn parse_rule(&self, state: &mut ParserState) -> Result<CSSRule> {
        let start_pos = state.position();

        // Parse selector
        let selector = self.parse_selector(state)?;
        state.skip_whitespace();

        // Expect opening brace
        if state.peek() != Some('{') {
            return Err(PostCSSError::ParseError {
                message: "Expected '{' after selector".to_string(),
                line: state.line(),
                column: state.column(),
            });
        }
        state.advance(); // consume '{'

        // Parse declarations
        let mut declarations = Vec::new();
        state.skip_whitespace();

        while !state.is_eof() && state.peek() != Some('}') {
            if let Ok(declaration) = self.parse_declaration(state) {
                declarations.push(declaration);
            }
            state.skip_whitespace();
        }

        // Expect closing brace
        if state.peek() != Some('}') {
            return Err(PostCSSError::ParseError {
                message: "Expected '}' after declarations".to_string(),
                line: state.line(),
                column: state.column(),
            });
        }
        state.advance(); // consume '}'

        Ok(CSSRule {
            selector,
            declarations,
            nested_rules: Vec::new(),
            media_query: None,
            specificity: 0,
            position: if self.options.track_positions {
                Some(SourcePosition {
                    line: start_pos.line,
                    column: start_pos.column,
                    source: None,
                })
            } else {
                None
            },
        })
    }

    /// Parse a CSS selector
    fn parse_selector(&self, state: &mut ParserState) -> Result<String> {
        let mut selector = String::new();

        while !state.is_eof() && state.peek() != Some('{') {
            let ch = state.peek().unwrap();
            if ch == ';' || ch == '}' {
                break;
            }
            selector.push(ch);
            state.advance();
        }

        Ok(selector.trim().to_string())
    }

    /// Parse a CSS declaration
    fn parse_declaration(&self, state: &mut ParserState) -> Result<CSSDeclaration> {
        let start_pos = state.position();

        // Parse property name
        let property = self.parse_property_name(state)?;
        state.skip_whitespace();

        // Expect colon
        if state.peek() != Some(':') {
            return Err(PostCSSError::ParseError {
                message: "Expected ':' after property name".to_string(),
                line: state.line(),
                column: state.column(),
            });
        }
        state.advance(); // consume ':'
        state.skip_whitespace();

        // Parse value
        let value = self.parse_property_value(state)?;
        state.skip_whitespace();

        // Check for !important
        let mut important = false;
        if state.peek() == Some('!') {
            state.advance(); // consume '!'
            if state.peek() == Some('i') || state.peek() == Some('I') {
                let important_str = state.read_while(|ch| ch.is_alphabetic());
                if important_str.to_lowercase() == "important" {
                    important = true;
                }
            }
        }

        // Expect semicolon or end of rule
        if state.peek() == Some(';') {
            state.advance(); // consume ';'
        }

        Ok(CSSDeclaration {
            property,
            value,
            important,
            position: if self.options.track_positions {
                Some(SourcePosition {
                    line: start_pos.line,
                    column: start_pos.column,
                    source: None,
                })
            } else {
                None
            },
        })
    }

    /// Parse property name
    fn parse_property_name(&self, state: &mut ParserState) -> Result<String> {
        let name = state.read_while(|ch| ch.is_alphanumeric() || ch == '-');
        if name.is_empty() {
            return Err(PostCSSError::ParseError {
                message: "Expected property name".to_string(),
                line: state.line(),
                column: state.column(),
            });
        }
        Ok(name)
    }

    /// Parse property value
    fn parse_property_value(&self, state: &mut ParserState) -> Result<String> {
        let mut value = String::new();
        let mut depth = 0;

        while !state.is_eof() {
            let ch = state.peek().unwrap();

            match ch {
                '(' | '[' | '{' => {
                    depth += 1;
                    value.push(ch);
                    state.advance();
                }
                ')' | ']' | '}' => {
                    if depth > 0 {
                        depth -= 1;
                        value.push(ch);
                        state.advance();
                    } else {
                        break;
                    }
                }
                ';' | '!' => {
                    if depth == 0 {
                        break;
                    }
                    value.push(ch);
                    state.advance();
                }
                _ => {
                    value.push(ch);
                    state.advance();
                }
            }
        }

        Ok(value.trim().to_string())
    }

    /// Parse an at-rule
    fn parse_at_rule(&self, state: &mut ParserState) -> Result<CSSAtRule> {
        let start_pos = state.position();

        // Consume '@'
        state.advance();

        // Parse at-rule name
        let name = state.read_while(|ch| ch.is_alphanumeric() || ch == '-');
        if name.is_empty() {
            return Err(PostCSSError::ParseError {
                message: "Expected at-rule name".to_string(),
                line: state.line(),
                column: state.column(),
            });
        }

        state.skip_whitespace();

        // Parse parameters
        let params = if state.peek() == Some('{') {
            String::new()
        } else {
            self.parse_at_rule_params(state)?
        };

        // Parse body if present
        let mut body = Vec::new();
        if state.peek() == Some('{') {
            state.advance(); // consume '{'
            state.skip_whitespace();

            while !state.is_eof() && state.peek() != Some('}') {
                if let Ok(rule) = self.parse_rule(state) {
                    body.push(CSSNode::Rule(rule));
                }
                state.skip_whitespace();
            }

            if state.peek() == Some('}') {
                state.advance(); // consume '}'
            }
        }

        Ok(CSSAtRule {
            name,
            params,
            body,
            position: if self.options.track_positions {
                Some(SourcePosition {
                    line: start_pos.line,
                    column: start_pos.column,
                    source: None,
                })
            } else {
                None
            },
        })
    }

    /// Parse at-rule parameters
    fn parse_at_rule_params(&self, state: &mut ParserState) -> Result<String> {
        let mut params = String::new();
        let mut depth = 0;

        while !state.is_eof() {
            let ch = state.peek().unwrap();

            match ch {
                '(' | '[' | '{' => {
                    depth += 1;
                    params.push(ch);
                    state.advance();
                }
                ')' | ']' | '}' => {
                    if depth > 0 {
                        depth -= 1;
                        params.push(ch);
                        state.advance();
                    } else {
                        break;
                    }
                }
                _ => {
                    params.push(ch);
                    state.advance();
                }
            }
        }

        Ok(params.trim().to_string())
    }
}

/// Parser state for tracking position and input
#[derive(Debug)]
struct ParserState<'a> {
    input: &'a str,
    position: usize,
    line: usize,
    column: usize,
    options: &'a ParseOptions,
}

impl<'a> ParserState<'a> {
    fn new(input: &'a str, options: &'a ParseOptions) -> Self {
        Self {
            input,
            position: 0,
            line: 1,
            column: 1,
            options,
        }
    }

    fn is_eof(&self) -> bool {
        self.position >= self.input.len()
    }

    fn peek(&self) -> Option<char> {
        self.input.chars().nth(self.position)
    }

    fn advance(&mut self) {
        if let Some(ch) = self.peek() {
            if ch == '\n' {
                self.line += 1;
                self.column = 1;
            } else {
                self.column += 1;
            }
            self.position += 1;
        }
    }

    fn skip_whitespace(&mut self) {
        while !self.is_eof() {
            match self.peek() {
                Some(ch) if ch.is_whitespace() => {
                    self.advance();
                }
                Some('/') if self.peek_ahead(1) == Some('*') => {
                    // Skip CSS comments
                    self.advance(); // consume '/'
                    self.advance(); // consume '*'
                    while !self.is_eof() {
                        if self.peek() == Some('*') && self.peek_ahead(1) == Some('/') {
                            self.advance(); // consume '*'
                            self.advance(); // consume '/'
                            break;
                        }
                        self.advance();
                    }
                }
                _ => break,
            }
        }
    }

    fn peek_ahead(&self, offset: usize) -> Option<char> {
        self.input.chars().nth(self.position + offset)
    }

    fn read_while<F>(&mut self, predicate: F) -> String
    where
        F: Fn(char) -> bool,
    {
        let mut result = String::new();
        while !self.is_eof() {
            if let Some(ch) = self.peek() {
                if predicate(ch) {
                    result.push(ch);
                    self.advance();
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        result
    }

    fn position(&self) -> SourcePosition {
        SourcePosition {
            line: self.line,
            column: self.column,
            source: None,
        }
    }

    fn line(&self) -> usize {
        self.line
    }

    fn column(&self) -> usize {
        self.column
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_css_parsing() {
        let parser = CSSParser::new(ParseOptions::default());
        let input = ".test { color: red; font-size: 16px; }";
        let result = parser.parse(input);

        assert!(result.is_ok());

        if let Ok(CSSNode::Stylesheet(rules)) = result {
            assert_eq!(rules.len(), 1);
            assert_eq!(rules[0].selector, ".test");
            assert_eq!(rules[0].declarations.len(), 2);
            assert_eq!(rules[0].declarations[0].property, "color");
            assert_eq!(rules[0].declarations[0].value, "red");
        }
    }

    #[test]
    fn test_at_rule_parsing() {
        let parser = CSSParser::new(ParseOptions::default());
        let input = "@media (max-width: 768px) { .mobile { display: block; } }";
        let result = parser.parse(input);

        assert!(result.is_ok());
    }

    #[test]
    fn test_important_declaration() {
        let parser = CSSParser::new(ParseOptions::default());
        let input = ".test { color: red !important; }";
        let result = parser.parse(input);

        assert!(result.is_ok());

        if let Ok(CSSNode::Stylesheet(rules)) = result {
            assert!(rules[0].declarations[0].important);
        }
    }

    #[test]
    fn test_parser_state() {
        let options = ParseOptions::default();
        let mut state = ParserState::new("test input", &options);

        assert!(!state.is_eof());
        assert_eq!(state.peek(), Some('t'));

        state.advance();
        assert_eq!(state.peek(), Some('e'));
        assert_eq!(state.line(), 1);
        assert_eq!(state.column(), 2);
    }
}