/
css.rs
277 lines (241 loc) · 7.59 KB
/
css.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
//! A simple parser for a tiny subset of CSS.
//!
//! To support more CSS syntax, it would probably be easiest to replace this
//! hand-rolled parser with one based on a library or parser generator.
use std::ascii::OwnedAsciiExt; // for `into_ascii_lower`
use std::str::FromStr;
use std::num::FromStrRadix;
// Data structures:
#[deriving(Show)]
pub struct Stylesheet {
pub rules: Vec<Rule>,
}
#[deriving(Show)]
pub struct Rule {
pub selectors: Vec<Selector>,
pub declarations: Vec<Declaration>,
}
#[deriving(Show)]
pub enum Selector {
Simple(SimpleSelector),
}
#[deriving(Show)]
pub struct SimpleSelector {
pub tag_name: Option<String>,
pub id: Option<String>,
pub class: Vec<String>,
}
#[deriving(Show)]
pub struct Declaration {
pub name: String,
pub value: Value,
}
#[deriving(Show, Clone, PartialEq)]
pub enum Value {
Keyword(String),
Length(f32, Unit),
ColorValue(Color),
}
#[deriving(Show, Clone, PartialEq)]
pub enum Unit {
Px,
}
#[deriving(Show, Clone, PartialEq, Default)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
pub type Specificity = (uint, uint, uint);
impl Selector {
pub fn specificity(&self) -> Specificity {
// http://www.w3.org/TR/selectors/#specificity
let Selector::Simple(ref simple) = *self;
let a = simple.id.iter().len();
let b = simple.class.len();
let c = simple.tag_name.iter().len();
(a, b, c)
}
}
impl Value {
/// Return the size of a length in px, or zero for non-lengths.
pub fn to_px(&self) -> f32 {
match *self {
Value::Length(f, Unit::Px) => f,
_ => 0.0
}
}
}
/// Parse a whole CSS stylesheet.
pub fn parse(source: String) -> Stylesheet {
let mut parser = Parser { pos: 0u, input: source };
Stylesheet { rules: parser.parse_rules() }
}
struct Parser {
pos: uint,
input: String,
}
impl Parser {
/// Parse a list of rule sets, separated by optional whitespace.
fn parse_rules(&mut self) -> Vec<Rule> {
let mut rules = Vec::new();
loop {
self.consume_whitespace();
if self.eof() { break }
rules.push(self.parse_rule());
}
return rules;
}
/// Parse a rule set: `<selectors> { <declarations> }`.
fn parse_rule(&mut self) -> Rule {
Rule {
selectors: self.parse_selectors(),
declarations: self.parse_declarations(),
}
}
/// Parse a comma-separated list of selectors.
fn parse_selectors(&mut self) -> Vec<Selector> {
let mut selectors = Vec::new();
loop {
selectors.push(Selector::Simple(self.parse_simple_selector()));
self.consume_whitespace();
match self.next_char() {
',' => { self.consume_char(); self.consume_whitespace(); }
'{' => break,
c => panic!("Unexpected character {} in selector list", c)
}
}
// Return selectors with highest specificity first, for use in matching.
selectors.sort_by(|a,b| b.specificity().cmp(&a.specificity()));
return selectors;
}
/// Parse one simple selector, e.g.: `type#id.class1.class2.class3`
fn parse_simple_selector(&mut self) -> SimpleSelector {
let mut selector = SimpleSelector { tag_name: None, id: None, class: Vec::new() };
while !self.eof() {
match self.next_char() {
'#' => {
self.consume_char();
selector.id = Some(self.parse_identifier());
}
'.' => {
self.consume_char();
selector.class.push(self.parse_identifier());
}
'*' => {
// universal selector
self.consume_char();
}
c if valid_identifier_char(c) => {
selector.tag_name = Some(self.parse_identifier());
}
_ => break
}
}
return selector;
}
/// Parse a list of declarations enclosed in `{ ... }`.
fn parse_declarations(&mut self) -> Vec<Declaration> {
assert!(self.consume_char() == '{');
let mut declarations = Vec::new();
loop {
self.consume_whitespace();
if self.next_char() == '}' {
self.consume_char();
break;
}
declarations.push(self.parse_declaration());
}
return declarations;
}
/// Parse one `<property>: <value>;` declaration.
fn parse_declaration(&mut self) -> Declaration {
let property_name = self.parse_identifier();
self.consume_whitespace();
assert!(self.consume_char() == ':')
self.consume_whitespace();
let value = self.parse_value();
self.consume_whitespace();
assert!(self.consume_char() == ';')
Declaration {
name: property_name,
value: value,
}
}
// Methods for parsing values:
fn parse_value(&mut self) -> Value {
match self.next_char() {
'0'...'9' => self.parse_length(),
'#' => self.parse_color(),
_ => Value::Keyword(self.parse_identifier())
}
}
fn parse_length(&mut self) -> Value {
Value::Length(self.parse_float(), self.parse_unit())
}
fn parse_float(&mut self) -> f32 {
let s = self.consume_while(|c| match c {
'0'...'9' | '.' => true,
_ => false
});
let f: Option<f32> = FromStr::from_str(s.as_slice());
f.unwrap()
}
fn parse_unit(&mut self) -> Unit {
match self.parse_identifier().into_ascii_lower().as_slice() {
"px" => Unit::Px,
_ => panic!("unrecognized unit")
}
}
fn parse_color(&mut self) -> Value {
assert!(self.consume_char() == '#');
Value::ColorValue(Color {
r: self.parse_hex_pair(),
g: self.parse_hex_pair(),
b: self.parse_hex_pair(),
a: 255 })
}
/// Parse two hexadecimal digits.
fn parse_hex_pair(&mut self) -> u8 {
let s = self.input.as_slice().slice(self.pos, self.pos + 2);
self.pos = self.pos + 2;
FromStrRadix::from_str_radix(s, 0x10).unwrap()
}
/// Parse a property name or keyword.
fn parse_identifier(&mut self) -> String {
self.consume_while(valid_identifier_char)
}
/// Consume and discard zero or more whitespace characters.
fn consume_whitespace(&mut self) {
self.consume_while(|c| c.is_whitespace());
}
/// Consume characters until `test` returns false.
fn consume_while(&mut self, test: |char| -> bool) -> String {
let mut result = String::new();
while !self.eof() && test(self.next_char()) {
result.push(self.consume_char());
}
return result;
}
/// Return the current character, and advance self.pos to the next character.
fn consume_char(&mut self) -> char {
let range = self.input.as_slice().char_range_at(self.pos);
self.pos = range.next;
return range.ch;
}
/// Read the current character without consuming it.
fn next_char(&self) -> char {
self.input.as_slice().char_at(self.pos)
}
/// Return true if all input is consumed.
fn eof(&self) -> bool {
self.pos >= self.input.len()
}
}
fn valid_identifier_char(c: char) -> bool {
match c {
'a'...'z' | 'A'...'Z' | '0'...'9' | '-' | '_' => true, // TODO: Include U+00A0 and higher.
_ => false,
}
}