1use std::fmt;
14use std::ops::Range;
15
16use cssparser::{
17 AtRuleParser, BasicParseErrorKind, CowRcStr, ParseError, ParseErrorKind, Parser, ParserInput,
18 ParserState, QualifiedRuleParser, RuleBodyParser, SourceLocation, StyleSheetParser,
19 match_ignore_ascii_case,
20};
21use selectors::SelectorList;
22use selectors::parser::{ParseRelative, SelectorParseErrorKind};
23
24use crate::Warning;
25use crate::pages::Side;
26use crate::style::element::{Fleuron, PseudoElement};
27use crate::style::properties::{
28 AlignContent, BackgroundRepeat, BorderStyle, Color, Content, Declaration, Edge, Length,
29 MarginBox, Marks, Pending, SizeSource, Url,
30};
31
32mod color;
33mod custom;
34mod declaration;
35mod face;
36mod page;
37mod value;
38mod vocabulary;
39
40pub use face::{FontFace, Src};
41
42pub(crate) use color::NAMED;
43pub(crate) use custom::{
44 Unresolved, longhands, margin_longhands, page_longhands, read_pending, read_pending_margin,
45 read_pending_page, substitute,
46};
47pub(crate) use declaration::{PROPERTIES, Spec};
48pub(crate) use face::FONT_FACE_DESCRIPTORS;
49#[cfg(test)]
50pub(crate) use face::FaceDeclaration;
51pub(crate) use page::{MARGIN_BOX_PROPERTIES, PAGE_PROPERTIES, PAGE_SELECTORS, PAGE_SIZES};
52pub(crate) use value::UNITS;
53pub(crate) use vocabulary::{
54 COMBINATORS, COMPOUNDS, CUSTOM_PROPERTY, DECLARATION, FIRST_LINE_PROPERTIES, PSEUDO_CLASSES,
55 PSEUDO_ELEMENTS, SELECTOR_LIST, VAR,
56};
57
58use declaration::declarations;
59use face::font_face;
60use page::{PageBody, PageItem, page_selector};
61
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
66pub enum Origin {
67 UserAgent,
69 #[default]
71 Author,
72}
73
74#[derive(Debug, Clone)]
77pub struct Source<'a> {
78 pub name: &'a str,
80 pub css: &'a str,
82 pub origin: Origin,
84}
85
86impl<'a> Source<'a> {
87 pub fn author(name: &'a str, css: &'a str) -> Source<'a> {
89 Source {
90 name,
91 css,
92 origin: Origin::Author,
93 }
94 }
95
96 pub fn user_agent(name: &'a str, css: &'a str) -> Source<'a> {
98 Source {
99 name,
100 css,
101 origin: Origin::UserAgent,
102 }
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
109pub enum Importance {
110 Normal,
111 Important,
112}
113
114#[derive(Debug, Clone, Default, PartialEq, Eq)]
118pub struct SheetPosition {
119 pub sheet: String,
121 pub line: u32,
123 pub column: u32,
125}
126
127impl SheetPosition {
128 pub(super) fn at(sheet: &str, location: SourceLocation) -> SheetPosition {
129 SheetPosition {
130 sheet: sheet.to_string(),
131 line: location.line + 1,
132 column: location.column,
133 }
134 }
135}
136
137impl fmt::Display for SheetPosition {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 write!(f, "{}:{}:{}", self.sheet, self.line, self.column)
140 }
141}
142
143#[derive(Debug, Clone, PartialEq)]
146pub struct Written {
147 pub property: String,
149 pub value: String,
151 pub important: bool,
153 pub longhands: Range<usize>,
156 pub position: SheetPosition,
158}
159
160#[derive(Debug)]
162pub struct StyleRule {
163 pub selectors: SelectorList<Fleuron>,
164 pub declarations: Vec<(Declaration, Importance)>,
165 pub written: Vec<Written>,
167 pub position: SheetPosition,
169}
170
171#[derive(Debug, Default, Clone)]
174pub struct PageRule {
175 pub name: Option<String>,
177 pub first: bool,
179 pub blank: bool,
181 pub side: Option<Side>,
183 pub declarations: Vec<PageDeclaration>,
184 pub boxes: Vec<MarginRule>,
185 pub selector: String,
187 pub position: SheetPosition,
189}
190
191#[derive(Debug, Clone)]
193pub struct MarginRule {
194 pub which: MarginBox,
195 pub declarations: Vec<MarginDeclaration>,
196 pub written: Vec<Written>,
198}
199
200impl PageRule {
201 pub fn specificity(&self) -> (u8, u8, u8) {
204 (
205 self.name.is_some() as u8,
206 (self.first || self.blank) as u8,
207 self.side.is_some() as u8,
208 )
209 }
210}
211
212#[derive(Debug, Clone, PartialEq)]
214pub enum PageDeclaration {
215 Size(f32, f32),
217 Margin(Edge, Length),
218 BackgroundColor(Option<Color>),
219 BackgroundImage(Option<Url>),
220 BackgroundRepeat(BackgroundRepeat),
221 BackgroundSize(SizeSource),
222 BackgroundPosition(Length, Length),
224 ColumnCount(Option<u32>),
226 ColumnWidth(Option<Length>),
228 ColumnGap(Option<Length>),
230 ColumnRuleWidth(Length),
231 ColumnRuleStyle(BorderStyle),
232 AlignContent(AlignContent),
233 Bleed(Option<Length>),
235 Marks(Marks),
236 Pending(Pending),
238}
239
240#[derive(Debug, Clone, PartialEq)]
242pub enum MarginDeclaration {
243 Content(Content),
244 Style(Declaration),
246 Pending(Pending),
248}
249
250#[derive(Debug, Default)]
252pub struct Sheet {
253 pub origin: Origin,
254 pub rules: Vec<StyleRule>,
255 pub pages: Vec<PageRule>,
256 pub faces: Vec<FontFace>,
257}
258
259#[derive(Debug, Clone)]
261pub enum StyleError<'i> {
262 UnsupportedProperty(CowRcStr<'i>),
263 NotOnFirstLine(CowRcStr<'i>),
264 UnsupportedValue(CowRcStr<'i>),
265 UnsupportedAtRule(CowRcStr<'i>),
266 UnsupportedPageSelector,
267 Selector(SelectorParseErrorKind<'i>),
268}
269
270impl<'i> From<SelectorParseErrorKind<'i>> for StyleError<'i> {
271 fn from(kind: SelectorParseErrorKind<'i>) -> Self {
272 StyleError::Selector(kind)
273 }
274}
275
276pub fn parse(source: &Source<'_>) -> (Sheet, Vec<Warning>) {
279 let mut input = ParserInput::new(source.css);
280 let mut parser = Parser::new(&mut input);
281 let mut top = TopLevel {
282 sheet: Sheet {
283 origin: source.origin,
284 ..Sheet::default()
285 },
286 warnings: Vec::new(),
287 name: source.name.to_string(),
288 };
289 let rules = StyleSheetParser::new(&mut parser, &mut top);
290 let collected: Vec<_> = rules
291 .map(|result| result.map_err(|(error, _)| error))
292 .collect();
293 for result in collected {
294 match result {
295 Ok(rule) => top.keep(rule),
296 Err(error) => top.warn(&error),
297 }
298 }
299 (top.sheet, top.warnings)
300}
301
302pub enum Rule {
304 Style(StyleRule),
305 Page(PageRule),
306 FontFace(FontFace),
307}
308
309struct TopLevel {
310 sheet: Sheet,
311 warnings: Vec<Warning>,
312 name: String,
313}
314
315impl TopLevel {
316 fn keep(&mut self, rule: Rule) {
317 match rule {
318 Rule::Style(rule) => self.sheet.rules.push(rule),
319 Rule::Page(rule) => self.sheet.pages.push(rule),
320 Rule::FontFace(face) => self.sheet.faces.push(face),
321 }
322 }
323
324 fn warn(&mut self, error: &ParseError<'_, StyleError<'_>>) {
325 self.warnings.push(warning(&self.name, error));
326 }
327}
328
329const IGNORED_DECLARATION: &str = "The declaration is ignored.";
331
332const IGNORED_RULE: &str = "The rule is ignored.";
334
335pub fn warning(sheet: &str, error: &ParseError<'_, StyleError<'_>>) -> Warning {
338 let message = match &error.kind {
339 ParseErrorKind::Custom(StyleError::UnsupportedProperty(name)) => {
340 format!("Unsupported property `{name}`. {IGNORED_DECLARATION}")
341 }
342 ParseErrorKind::Custom(StyleError::NotOnFirstLine(name)) => {
343 format!("Unsupported property `{name}` on `::first-line`. {IGNORED_DECLARATION}")
344 }
345 ParseErrorKind::Custom(StyleError::UnsupportedValue(name)) => {
346 format!("Unsupported value for `{name}`. {IGNORED_DECLARATION}")
347 }
348 ParseErrorKind::Custom(StyleError::UnsupportedAtRule(name)) => {
349 format!("Unsupported at-rule `@{name}`. {IGNORED_RULE}")
350 }
351 ParseErrorKind::Custom(StyleError::UnsupportedPageSelector) => {
352 format!("Unsupported `@page` selector. {IGNORED_RULE}")
353 }
354 ParseErrorKind::Custom(StyleError::Selector(
355 SelectorParseErrorKind::UnsupportedPseudoClassOrElement(name),
356 )) => format!("Unsupported selector `:{name}`. {IGNORED_RULE}"),
357 ParseErrorKind::Custom(StyleError::Selector(_)) => {
358 format!("Unsupported selector. {IGNORED_RULE}")
359 }
360 ParseErrorKind::Basic(BasicParseErrorKind::AtRuleInvalid(name)) => {
361 format!("Unsupported at-rule `@{name}`. {IGNORED_RULE}")
362 }
363 ParseErrorKind::Basic(_) => format!("Malformed CSS. {IGNORED_DECLARATION}"),
364 };
365 Warning {
366 message,
367 origin: Some(position(sheet, error.location)),
368 }
369}
370
371pub(super) fn position(sheet: &str, location: SourceLocation) -> String {
373 SheetPosition::at(sheet, location).to_string()
374}
375
376impl<'i> QualifiedRuleParser<'i> for TopLevel {
377 type Prelude = SelectorList<Fleuron>;
378 type QualifiedRule = Rule;
379 type Error = StyleError<'i>;
380
381 fn parse_prelude<'t>(
382 &mut self,
383 input: &mut Parser<'i, 't>,
384 ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {
385 SelectorList::parse(&Selectors, input, ParseRelative::No)
386 }
387
388 fn parse_block<'t>(
389 &mut self,
390 selectors: Self::Prelude,
391 start: &ParserState,
392 input: &mut Parser<'i, 't>,
393 ) -> Result<Self::QualifiedRule, ParseError<'i, Self::Error>> {
394 let first_line = selectors
395 .slice()
396 .iter()
397 .all(|selector| selector.pseudo_element() == Some(&PseudoElement::FirstLine));
398 let (declarations, written, warnings) = declarations(input, &self.name, first_line);
399 self.warnings.extend(warnings);
400 Ok(Rule::Style(StyleRule {
401 selectors,
402 declarations,
403 written,
404 position: SheetPosition::at(&self.name, start.source_location()),
405 }))
406 }
407}
408
409impl<'i> AtRuleParser<'i> for TopLevel {
410 type Prelude = AtRule;
411 type AtRule = Rule;
412 type Error = StyleError<'i>;
413
414 fn parse_prelude<'t>(
415 &mut self,
416 name: CowRcStr<'i>,
417 input: &mut Parser<'i, 't>,
418 ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {
419 match_ignore_ascii_case! { &name,
420 "page" => {
421 let from = input.position();
422 let mut rule = page_selector(input)?;
423 rule.selector = format!("@page {}", input.slice_from(from).trim())
424 .trim_end()
425 .to_string();
426 Ok(AtRule::Page(rule))
427 },
428 "font-face" => Ok(AtRule::FontFace),
429 _ => Err(input.new_custom_error(StyleError::UnsupportedAtRule(name.clone()))),
430 }
431 }
432
433 fn parse_block<'t>(
434 &mut self,
435 prelude: Self::Prelude,
436 start: &ParserState,
437 input: &mut Parser<'i, 't>,
438 ) -> Result<Self::AtRule, ParseError<'i, Self::Error>> {
439 match prelude {
440 AtRule::Page(mut rule) => {
441 rule.position = SheetPosition::at(&self.name, start.source_location());
442 let mut body = PageBody {
443 name: self.name.clone(),
444 warnings: Vec::new(),
445 };
446 let items: Vec<_> = RuleBodyParser::new(input, &mut body)
447 .map(|result| result.map_err(|(error, _)| error))
448 .collect();
449 self.warnings.append(&mut body.warnings);
450 for item in items {
451 match item {
452 Ok(parsed) => {
453 for item in parsed {
454 match item {
455 PageItem::Declaration(declaration) => {
456 rule.declarations.push(declaration)
457 }
458 PageItem::Box(margin) => rule.boxes.push(margin),
459 }
460 }
461 }
462 Err(error) => self.warnings.push(warning(&self.name, &error)),
463 }
464 }
465 Ok(Rule::Page(rule))
466 }
467 AtRule::FontFace => {
468 let (face, warnings) = font_face(input, &self.name);
469 self.warnings.extend(warnings);
470 Ok(Rule::FontFace(face))
471 }
472 }
473 }
474}
475
476pub enum AtRule {
478 Page(PageRule),
479 FontFace,
480}
481
482struct Selectors;
485
486impl<'i> selectors::Parser<'i> for Selectors {
487 type Impl = Fleuron;
488 type Error = StyleError<'i>;
489
490 fn parse_is_and_where(&self) -> bool {
491 true
492 }
493
494 fn parse_nth_child_of(&self) -> bool {
495 true
496 }
497
498 fn parse_has(&self) -> bool {
499 true
500 }
501
502 fn parse_pseudo_element(
503 &self,
504 location: SourceLocation,
505 name: CowRcStr<'i>,
506 ) -> Result<PseudoElement, ParseError<'i, StyleError<'i>>> {
507 match_ignore_ascii_case! { &name,
508 "first-letter" => Ok(PseudoElement::FirstLetter),
509 "first-line" => Ok(PseudoElement::FirstLine),
510 "before" => Ok(PseudoElement::Before),
511 "after" => Ok(PseudoElement::After),
512 _ => Err(location.new_custom_error(
513 SelectorParseErrorKind::UnsupportedPseudoClassOrElement(name.clone()),
514 )),
515 }
516 }
517}
518
519#[cfg(test)]
520mod tests {
521 use super::*;
522
523 #[test]
527 fn a_rule_records_the_position_a_warning_names() {
528 let kept = "p { color: red }\n\n h1 { color: red }";
529 let refused = "p { color: red }\n\n !h1 { color: red }";
530 let (sheet, _) = parse(&Source::author("author.css", kept));
531 let (_, warnings) = parse(&Source::author("author.css", refused));
532
533 let rule = &sheet.rules[1];
534 assert_eq!(
535 rule.position,
536 SheetPosition {
537 sheet: "author.css".into(),
538 line: 3,
539 column: 3,
540 }
541 );
542 assert_eq!(warnings.len(), 1, "{warnings:?}");
543 assert_eq!(
544 warnings[0].origin.as_deref(),
545 Some(rule.position.to_string().as_str())
546 );
547
548 let page = "\n@page :left {\n @top-left { content: \"Left\" }\n}";
549 let (sheet, _) = parse(&Source::author("pages.css", page));
550 assert_eq!(sheet.pages[0].position.to_string(), "pages.css:2:1");
551 assert_eq!(sheet.pages[0].selector, "@page :left");
552 }
553
554 #[test]
557 fn a_declaration_keeps_what_was_written() {
558 let css = "p { MARGIN: 1em 2em; color: red !important }";
559 let (sheet, _) = parse(&Source::author("author.css", css));
560 let rule = &sheet.rules[0];
561 assert_eq!(
562 rule.written,
563 vec![
564 Written {
565 property: "margin".into(),
566 value: "1em 2em".into(),
567 important: false,
568 longhands: 0..4,
569 position: SheetPosition {
570 sheet: "author.css".into(),
571 line: 1,
572 column: 5,
573 },
574 },
575 Written {
576 property: "color".into(),
577 value: "red".into(),
578 important: true,
579 longhands: 4..5,
580 position: SheetPosition {
581 sheet: "author.css".into(),
582 line: 1,
583 column: 22,
584 },
585 },
586 ]
587 );
588 assert_eq!(rule.declarations.len(), 5);
589 }
590
591 #[test]
595 fn a_custom_property_is_kept_as_written() {
596 let css = "p {\n --Accent: rgb(214, 7, 94) !important;\n color: var(--Accent, black);\n}";
597 let (sheet, warnings) = parse(&Source::author("author.css", css));
598 assert!(warnings.is_empty(), "{warnings:?}");
599 let rule = &sheet.rules[0];
600 assert_eq!(
601 rule.declarations,
602 vec![
603 (
604 Declaration::Custom(crate::style::properties::Custom {
605 name: "--Accent".into(),
606 value: "rgb(214, 7, 94)".into(),
607 origin: "author.css:2:3".into(),
608 }),
609 Importance::Important,
610 ),
611 (
612 Declaration::Pending(Pending {
613 property: "color".into(),
614 value: "var(--Accent, black)".into(),
615 origin: "author.css:3:3".into(),
616 }),
617 Importance::Normal,
618 ),
619 ]
620 );
621 assert_eq!(rule.written[0].property, "--Accent");
622 assert_eq!(rule.written[1].value, "var(--Accent, black)");
623 }
624}