simplecss-0.2.0/.gitignore010064400017500001750000000000361352144377600137370ustar0000000000000000target Cargo.lock .idea *.iml simplecss-0.2.0/.travis.yml010064400017500001750000000000401352144505300140410ustar0000000000000000language: rust rust: - stable simplecss-0.2.0/CHANGELOG.md010064400017500001750000000007421352574665400135710ustar0000000000000000# Change Log All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ## [0.2.0] - 2019-08-17 - A complete rewrite. ## [0.1.0] - 2017-01-14 - Initial release. [Unreleased]: https://github.com/RazrFalcon/simplecss/compare/v0.2.0...HEAD [0.1.0]: https://github.com/RazrFalcon/simplecss/compare/v0.1.0...v0.2.0 simplecss-0.2.0/Cargo.toml.orig010064400017500001750000000007771352501000300146230ustar0000000000000000[package] name = "simplecss" version = "0.2.0" authors = ["Reizner Evgeniy "] license = "MIT/Apache-2.0" readme = "README.md" description = "A simple CSS 2 parser and selector." repository = "https://github.com/RazrFalcon/simplecss" keywords = ["css", "parser", "selector"] categories = ["parser-implementations"] edition = "2018" exclude = ["testing-tools/**"] [dependencies] log = "0.4.8" [dev-dependencies] env_logger = { version = "0.6", default-features = false } roxmltree = "0.7" simplecss-0.2.0/Cargo.toml0000644000000020470000000000000110750ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "simplecss" version = "0.2.0" authors = ["Reizner Evgeniy "] exclude = ["testing-tools/**"] description = "A simple CSS 2 parser and selector." readme = "README.md" keywords = ["css", "parser", "selector"] categories = ["parser-implementations"] license = "MIT/Apache-2.0" repository = "https://github.com/RazrFalcon/simplecss" [dependencies.log] version = "0.4.8" [dev-dependencies.env_logger] version = "0.6" default-features = false [dev-dependencies.roxmltree] version = "0.7" simplecss-0.2.0/LICENSE-APACHE010064400017500001750000000251371322753041200136670ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. simplecss-0.2.0/LICENSE-MIT010064400017500001750000000020721326664711400134030ustar0000000000000000The MIT License (MIT) Copyright (c) 2018 Reizner Evgeniy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. simplecss-0.2.0/README.md010064400017500001750000000032631352574674200132360ustar0000000000000000## simplecss [![Build Status](https://travis-ci.org/RazrFalcon/simplecss.svg?branch=master)](https://travis-ci.org/RazrFalcon/simplecss) [![Crates.io](https://img.shields.io/crates/v/simplecss.svg)](https://crates.io/crates/simplecss) [![Documentation](https://docs.rs/simplecss/badge.svg)](https://docs.rs/simplecss) A simple [CSS 2.1](https://www.w3.org/TR/CSS21/) parser and selector. This is not a browser-grade CSS parser. If you need one, use [cssparser](https://crates.io/crates/cssparser) + [selectors](https://crates.io/crates/selectors). Since it's very simple we will start with limitations: ### Limitations - [At-rules](https://www.w3.org/TR/CSS21/syndata.html#at-rules) are not supported. They will be skipped during parsing. - Property values are not parsed. In CSS like `* { width: 5px }` you will get a `width` property with a `5px` value as a string. - CDO/CDC comments are not supported. - Parser is case sensitive. All keywords must be lowercase. - Rule specifily is not supported. - Unicode escape, like `\26`, is not supported. ### Features - Selector matching support. - `!import` parsing support. - Has a high-level parsers and low-level, zero-allocation tokenizers. - No unsafe. ### License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. simplecss-0.2.0/examples/parse.rs010064400017500001750000000014611352142315600152360ustar0000000000000000use std::io::{Read, Write}; fn main() { let args: Vec<_> = std::env::args().collect(); if args.len() != 2 { println!("Usage:\n\tparse style.css\n\tparse - 'p {{ color:red }}'"); std::process::exit(1); } std::env::set_var("RUST_LOG", "simplecss=warn"); env_logger::builder() .format(|buf, record| { writeln!(buf, "{}: {}", record.level(), record.args()) }) .init(); let text = if args[1] == "-" { let mut buffer = String::new(); let stdin = std::io::stdin(); let mut handle = stdin.lock(); handle.read_to_string(&mut buffer).unwrap(); buffer } else { std::fs::read_to_string(&args[1]).unwrap() }; let style = simplecss::StyleSheet::parse(&text); println!("{:#?}", style); } simplecss-0.2.0/examples/select.rs010064400017500001750000000042431352500306100153750ustar0000000000000000struct XmlNode<'a, 'input: 'a>(roxmltree::Node<'a, 'input>); impl<'a, 'input: 'a> XmlNode<'a, 'input> { fn select(&self, text: &str) -> Option> { let selectors = simplecss::Selector::parse(text)?; for node in self.0.descendants().filter(|n| n.is_element()) { if selectors.matches(&XmlNode(node)) { return Some(node); } } None } } impl simplecss::Element for XmlNode<'_, '_> { fn parent_element(&self) -> Option { self.0.parent_element().map(XmlNode) } fn prev_sibling_element(&self) -> Option { self.0.prev_siblings().filter(|n| n.is_element()).nth(0).map(XmlNode) } fn has_local_name(&self, local_name: &str) -> bool { self.0.tag_name().name() == local_name } fn attribute_matches(&self, local_name: &str, operator: simplecss::AttributeOperator) -> bool { match self.0.attribute(local_name) { Some(value) => operator.matches(value), None => false, } } fn pseudo_class_matches(&self, class: simplecss::PseudoClass) -> bool { match class { simplecss::PseudoClass::FirstChild => self.prev_sibling_element().is_none(), _ => false, // Since we are querying a static XML we can ignore other pseudo-classes. } } } fn main() { let doc = roxmltree::Document::parse( " " ).unwrap(); let root = XmlNode(doc.root_element()); assert_eq!( root.select("rect:first-child").unwrap().attribute("id").unwrap(), "rect1" ); assert_eq!( root.select("[color=red]").unwrap().attribute("id").unwrap(), "rect2" ); assert_eq!( root.select("svg rect").unwrap().attribute("id").unwrap(), "rect1" ); assert_eq!( root.select("svg > g > rect").unwrap().attribute("id").unwrap(), "rect1" ); assert_eq!( root.select(".blue").unwrap().attribute("id").unwrap(), "rect1" ); } simplecss-0.2.0/src/lib.rs010064400017500001750000000314721352574673400136660ustar0000000000000000/*! A simple [CSS 2.1](https://www.w3.org/TR/CSS21/) parser and selector. This is not a browser-grade CSS parser. If you need one, use [cssparser](https://crates.io/crates/cssparser) + [selectors](https://crates.io/crates/selectors). Since it's very simple we will start with limitations: ## Limitations - [At-rules](https://www.w3.org/TR/CSS21/syndata.html#at-rules) are not supported. They will be skipped during parsing. - Property values are not parsed. In CSS like `* { width: 5px }` you will get a `width` property with a `5px` value as a string. - CDO/CDC comments are not supported. - Parser is case sensitive. All keywords must be lowercase. - Rule specifily is not supported. - Unicode escape, like `\26`, is not supported. ## Features - Selector matching support. - `!import` parsing support. - Has a high-level parsers and low-level, zero-allocation tokenizers. - No unsafe. */ #![doc(html_root_url = "https://docs.rs/simplecss/0.2.0")] #![forbid(unsafe_code)] #![warn(missing_docs)] use std::fmt; use log::warn; mod selector; mod stream; pub use selector::*; use stream::Stream; /// A list of possible errors. #[derive(Clone, Copy, PartialEq, Debug)] pub enum Error { /// The steam ended earlier than we expected. /// /// Should only appear on invalid input data. UnexpectedEndOfStream, /// An invalid ident. InvalidIdent(TextPos), /// An unclosed comment. InvalidComment(TextPos), /// An invalid declaration value. InvalidValue(TextPos), /// An invalid byte. #[allow(missing_docs)] InvalidByte { expected: u8, actual: u8, pos: TextPos }, /// A missing selector. SelectorMissing, /// An unexpected selector. UnexpectedSelector, /// An unexpected combinator. UnexpectedCombinator, /// An invalid or unsupported attribute selector. InvalidAttributeSelector, /// An invalid language pseudo-class. InvalidLanguagePseudoClass, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::UnexpectedEndOfStream => { write!(f, "unexpected end of stream") } Error::InvalidIdent(pos) => { write!(f, "invalid ident at {}", pos) } Error::InvalidComment(pos) => { write!(f, "invalid comment at {}", pos) } Error::InvalidValue(pos) => { write!(f, "invalid value at {}", pos) } Error::InvalidByte { expected, actual, pos } => { write!(f, "expected '{}' not '{}' at {}", expected as char, actual as char, pos) } Error::SelectorMissing => { write!(f, "selector missing") } Error::UnexpectedSelector => { write!(f, "unexpected selector") } Error::UnexpectedCombinator => { write!(f, "unexpected combinator") } Error::InvalidAttributeSelector => { write!(f, "invalid or unsupported attribute selector") } Error::InvalidLanguagePseudoClass => { write!(f, "invalid language pseudo-class") } } } } impl std::error::Error for Error {} /// A position in text. /// /// Position indicates a row/line and a column in the original text. Starting from 1:1. #[derive(Clone, Copy, PartialEq, Debug)] #[allow(missing_docs)] pub struct TextPos { pub row: u32, pub col: u32, } impl TextPos { /// Constructs a new `TextPos`. /// /// Should not be invoked manually, but rather via `Stream::gen_text_pos`. pub fn new(row: u32, col: u32) -> TextPos { TextPos { row, col } } } impl fmt::Display for TextPos { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.row, self.col) } } /// A declaration. #[derive(Clone, Copy, PartialEq, Debug)] #[allow(missing_docs)] pub struct Declaration<'a> { pub name: &'a str, pub value: &'a str, pub important: bool, } /// A rule. #[derive(Clone, Debug)] pub struct Rule<'a> { /// A rule selector. pub selector: Selector<'a>, /// A rule declarations. pub declarations: Vec>, } /// A style sheet. #[derive(Clone, Debug)] pub struct StyleSheet<'a> { /// A list of rules. pub rules: Vec>, } impl<'a> StyleSheet<'a> { /// Creates an empty style sheet. pub fn new() -> Self { StyleSheet { rules: Vec::new() } } /// Parses a style sheet from text. /// /// At-rules are not supported and will be skipped. /// /// # Errors /// /// Doesn't produce any errors. In worst case scenario will return an empty stylesheet. /// /// All warnings will be logged. pub fn parse(text: &'a str) -> Self { let mut sheet = StyleSheet::new(); sheet.parse_more(text); sheet } /// Parses a style sheet from a text to the current style sheet. pub fn parse_more(&mut self, text: &'a str) { let mut s = Stream::from(text); if s.skip_spaces_and_comments().is_err() { return; } while !s.at_end() { if s.skip_spaces_and_comments().is_err() { break; } let _ = consume_statement(&mut s, &mut self.rules); } if !s.at_end() { warn!("{} bytes were left.", s.slice_tail().len()); } // Remove empty rules. self.rules.retain(|rule| !rule.declarations.is_empty()); } } impl fmt::Display for StyleSheet<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, rule) in self.rules.iter().enumerate() { write!(f, "{} {{ ", rule.selector)?; for dec in &rule.declarations { write!(f, "{}:{}", dec.name, dec.value)?; if dec.important { write!(f, " !important")?; } write!(f, ";")?; } write!(f, " }}")?; if i != self.rules.len() - 1 { writeln!(f)?; } } Ok(()) } } fn consume_statement<'a>(s: &mut Stream<'a>, rules: &mut Vec>) -> Result<(), Error> { if s.curr_byte() == Ok(b'@') { s.advance(1); consume_at_rule(s) } else { consume_rule_set(s, rules) } } fn consume_at_rule(s: &mut Stream) -> Result<(), Error> { let ident = s.consume_ident()?; warn!("The @{} rule is not supported. Skipped.", ident); s.skip_bytes(|c| c != b';' && c != b'{'); match s.curr_byte()? { b';' => s.advance(1), b'{' => consume_block(s), _ => {} } Ok(()) } fn consume_rule_set<'a>(s: &mut Stream<'a>, rules: &mut Vec>) -> Result<(), Error> { let start_rule_idx = rules.len(); while s.curr_byte()? == b',' || start_rule_idx == rules.len() { if s.curr_byte()? == b',' { s.advance(1); } let (selector, offset) = crate::selector::parse(s.slice_tail()); s.advance(offset); s.skip_spaces(); if let Some(selector) = selector { rules.push(Rule { selector, declarations: Vec::new() }); } match s.curr_byte()? { b'{' => break, b',' => {} _ => { s.skip_bytes(|c| c != b'{'); break; } } } s.try_consume_byte(b'{'); let declarations = consume_declarations(s)?; for i in start_rule_idx..rules.len() { rules[i].declarations = declarations.clone(); } s.try_consume_byte(b'}'); Ok(()) } fn consume_block(s: &mut Stream) { s.try_consume_byte(b'{'); consume_until_block_end(s); } fn consume_until_block_end(s: &mut Stream) { // Block can have nested blocks, so we have to check for matching braces. // We simply counting the number of opening braces, which is incorrect, // since `{` can be inside a string, but it's fine for majority of the cases. let mut braces = 0; while !s.at_end() { match s.curr_byte_unchecked() { b'{' => { braces += 1; } b'}' => { if braces == 0 { break; } else { braces -= 1; } } _ => {} } s.advance(1); } s.try_consume_byte(b'}'); } fn consume_declarations<'a>(s: &mut Stream<'a>) -> Result>, Error> { let mut declarations = Vec::new(); while !s.at_end() && s.curr_byte() != Ok(b'}') { match consume_declaration(s) { Ok(declaration) => declarations.push(declaration), Err(_) => { consume_until_block_end(s); break; } } } Ok(declarations) } /// A declaration tokenizer. /// /// Tokenizer will stop at the first invalid token. /// /// # Example /// /// ``` /// use simplecss::{DeclarationTokenizer, Declaration}; /// /// let mut t = DeclarationTokenizer::from("background: url(\"img.png\"); color:red !important"); /// assert_eq!(t.next().unwrap(), Declaration { name: "background", value: "url(\"img.png\")", important: false }); /// assert_eq!(t.next().unwrap(), Declaration { name: "color", value: "red", important: true }); /// ``` pub struct DeclarationTokenizer<'a> { stream: Stream<'a>, } impl<'a> From<&'a str> for DeclarationTokenizer<'a> { fn from(text: &'a str) -> Self { DeclarationTokenizer { stream: Stream::from(text), } } } impl<'a> Iterator for DeclarationTokenizer<'a> { type Item = Declaration<'a>; fn next(&mut self) -> Option { let _ = self.stream.skip_spaces_and_comments(); if self.stream.at_end() { return None; } match consume_declaration(&mut self.stream) { Ok(v) => Some(v), Err(_) => { self.stream.jump_to_end(); None } } } } fn consume_declaration<'a>(s: &mut Stream<'a>) -> Result, Error> { s.skip_spaces_and_comments()?; // Parse name. // https://snook.ca/archives/html_and_css/targetting_ie7 if s.curr_byte() == Ok(b'*') { s.advance(1); } let name = s.consume_ident()?; s.skip_spaces_and_comments()?; s.consume_byte(b':')?; s.skip_spaces_and_comments()?; // Parse value. let start = s.pos(); let mut end = s.pos(); while consume_term(s).is_ok() { end = s.pos(); s.skip_spaces_and_comments()?; } let value = s.slice_range(start, end).trim(); s.skip_spaces_and_comments()?; // Check for `important`. let mut important = false; if s.curr_byte() == Ok(b'!') { s.advance(1); s.skip_spaces_and_comments()?; if s.slice_tail().starts_with("important") { s.advance(9); important = true; } } s.skip_spaces_and_comments()?; while s.curr_byte() == Ok(b';') { s.advance(1); s.skip_spaces_and_comments()?; } s.skip_spaces_and_comments()?; if value.is_empty() { return Err(Error::InvalidValue(s.gen_text_pos_from(start))); } Ok(Declaration { name, value, important }) } fn consume_term(s: &mut Stream) -> Result<(), Error> { fn consume_digits(s: &mut Stream) { while let Ok(c) = s.curr_byte() { match c { b'0'...b'9' => s.advance(1), _ => break, } } } match s.curr_byte()? { b'#' => { s.advance(1); match s.consume_ident() { Ok(_) => {} Err(_) => { // Try consume as a hex color. while let Ok(c) = s.curr_byte() { match c { b'0'...b'9' | b'a'...b'f' | b'A'...b'F' => s.advance(1), _ => break, } } } } } b'+' | b'-' | b'0'...b'9' | b'.' => { // Consume number. s.advance(1); consume_digits(s); if s.curr_byte() == Ok(b'.') { s.advance(1); consume_digits(s); } if s.curr_byte() == Ok(b'%') { s.advance(1); } else { // Consume suffix if any. let _ = s.consume_ident(); } } b'\'' | b'"' => { s.consume_string()?; } b',' => { s.advance(1); } _ => { let _ = s.consume_ident()?; // Consume function. if s.curr_byte() == Ok(b'(') { s.skip_bytes(|c| c != b')'); s.consume_byte(b')')?; } } } Ok(()) } simplecss-0.2.0/src/selector.rs010064400017500001750000000462331352500751000147170ustar0000000000000000use std::fmt; use log::warn; use crate::stream::Stream; use crate::Error; /// An attribute selector operator. #[derive(Clone, Copy, PartialEq, Debug)] pub enum AttributeOperator<'a> { /// `[attr]` Exists, /// `[attr=value]` Matches(&'a str), /// `[attr~=value]` Contains(&'a str), /// `[attr|=value]` StartsWith(&'a str), } impl<'a> AttributeOperator<'a> { /// Checks that value is matching the operator. pub fn matches(&self, value: &str) -> bool { match *self { AttributeOperator::Exists => { true } AttributeOperator::Matches(v) => { value == v } AttributeOperator::Contains(v) => { value.split(' ').any(|s| s == v) } AttributeOperator::StartsWith(v) => { // exactly `v` or beginning with `v` immediately followed by `-` if value == v { true } else if value.starts_with(v) { value.get(v.len()..v.len()+1) == Some("-") } else { false } } } } } /// A pseudo-class. #[derive(Clone, Copy, PartialEq, Debug)] #[allow(missing_docs)] pub enum PseudoClass<'a> { FirstChild, Link, Visited, Hover, Active, Focus, Lang(&'a str), } impl fmt::Display for PseudoClass<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { PseudoClass::FirstChild => write!(f, "first-child"), PseudoClass::Link => write!(f, "link"), PseudoClass::Visited => write!(f, "visited"), PseudoClass::Hover => write!(f, "hover"), PseudoClass::Active => write!(f, "active"), PseudoClass::Focus => write!(f, "focus"), PseudoClass::Lang(lang) => write!(f, "lang({})", lang), } } } /// A trait to query an element node metadata. pub trait Element: Sized { /// Returns a parent element. fn parent_element(&self) -> Option; /// Returns a previous sibling element. fn prev_sibling_element(&self) -> Option; /// Checks that the element has a specified local name. fn has_local_name(&self, name: &str) -> bool; /// Checks that the element has a specified attribute. fn attribute_matches(&self, local_name: &str, operator: AttributeOperator) -> bool; /// Checks that the element matches a specified pseudo-class. fn pseudo_class_matches(&self, class: PseudoClass) -> bool; } #[derive(Clone, Copy, PartialEq, Debug)] enum SimpleSelectorType<'a> { Type(&'a str), Universal, } #[derive(Clone, Copy, PartialEq, Debug)] enum SubSelector<'a> { Attribute(&'a str, AttributeOperator<'a>), PseudoClass(PseudoClass<'a>), } #[derive(Clone, Debug)] struct SimpleSelector<'a> { kind: SimpleSelectorType<'a>, subselectors: Vec>, } #[derive(Clone, Copy, PartialEq, Debug)] enum Combinator { None, Descendant, Child, AdjacentSibling, } #[derive(Clone, Debug)] struct Component<'a> { /// A combinator that precede the selector. combinator: Combinator, selector: SimpleSelector<'a>, } /// A selector. #[derive(Clone, Debug)] pub struct Selector<'a> { components: Vec> } impl<'a> Selector<'a> { /// Parses a selector from a string. /// /// Will log any errors as a warnings. /// /// Parsing will be stopped at EOF, `,` or `{`. pub fn parse(text: &'a str) -> Option { parse(text).0 } /// Checks that the provided element matches the current selector. pub fn matches(&self, element: &E) -> bool { assert!(!self.components.is_empty(), "selector must not be empty"); assert_eq!(self.components[0].combinator, Combinator::None, "the first component must not have a combinator"); self.matches_impl(self.components.len() - 1, element) } fn matches_impl(&self, idx: usize, element: &E) -> bool { let ref component = self.components[idx]; if !match_selector(&component.selector, element) { return false; } match component.combinator { Combinator::Descendant => { let mut parent = element.parent_element(); while let Some(e) = parent { if self.matches_impl(idx - 1, &e) { return true; } parent = e.parent_element(); } false } Combinator::Child => { if let Some(parent) = element.parent_element() { if self.matches_impl(idx - 1, &parent) { return true; } } false } Combinator::AdjacentSibling => { if let Some(prev) = element.prev_sibling_element() { if self.matches_impl(idx - 1, &prev) { return true; } } false } Combinator::None => { true } } } } fn match_selector(selector: &SimpleSelector, element: &E) -> bool { if let SimpleSelectorType::Type(ident) = selector.kind { if !element.has_local_name(ident) { return false; } } for sub in &selector.subselectors { match sub { SubSelector::Attribute(name, operator) => { if !element.attribute_matches(name, *operator) { return false; } } SubSelector::PseudoClass(class) => { if !element.pseudo_class_matches(*class) { return false; } } } } true } pub(crate) fn parse(text: &str) -> (Option, usize) { let mut components: Vec = Vec::new(); let mut combinator = Combinator::None; let mut tokenizer = SelectorTokenizer::from(text); for token in &mut tokenizer { let mut add_sub = |sub| { if combinator == Combinator::None && !components.is_empty() { if let Some(ref mut component) = components.last_mut() { component.selector.subselectors.push(sub); } } else { components.push(Component { selector: SimpleSelector { kind: SimpleSelectorType::Universal, subselectors: vec![sub], }, combinator, }); combinator = Combinator::None; } }; let token = match token { Ok(t) => t, Err(e) => { warn!("Selector parsing failed cause {}.", e); return (None, tokenizer.stream.pos()); } }; match token { SelectorToken::UniversalSelector => { components.push(Component { selector: SimpleSelector { kind: SimpleSelectorType::Universal, subselectors: Vec::new(), }, combinator, }); combinator = Combinator::None; } SelectorToken::TypeSelector(ident) => { components.push(Component { selector: SimpleSelector { kind: SimpleSelectorType::Type(ident), subselectors: Vec::new(), }, combinator, }); combinator = Combinator::None; } SelectorToken::ClassSelector(ident) => { add_sub(SubSelector::Attribute("class", AttributeOperator::Contains(ident))); } SelectorToken::IdSelector(id) => { add_sub(SubSelector::Attribute("id", AttributeOperator::Matches(id))); } SelectorToken::AttributeSelector(name, op) => { add_sub(SubSelector::Attribute(name, op)); } SelectorToken::PseudoClass(ident) => { let class = match ident { "first-child" => PseudoClass::FirstChild, "link" => PseudoClass::Link, "visited" => PseudoClass::Visited, "hover" => PseudoClass::Hover, "active" => PseudoClass::Active, "focus" => PseudoClass::Focus, _ => { warn!("':{}' is not supported. Selector skipped.", ident); return (None, tokenizer.stream.pos()); } }; // TODO: duplicates // TODO: order add_sub(SubSelector::PseudoClass(class)); } SelectorToken::LangPseudoClass(lang) => { add_sub(SubSelector::PseudoClass(PseudoClass::Lang(lang))); } SelectorToken::DescendantCombinator => { combinator = Combinator::Descendant; } SelectorToken::ChildCombinator => { combinator = Combinator::Child; } SelectorToken::AdjacentCombinator => { combinator = Combinator::AdjacentSibling; } } } if components.is_empty() { (None, tokenizer.stream.pos()) } else if components[0].combinator != Combinator::None { debug_assert_eq!(components[0].combinator, Combinator::None, "the first component must not have a combinator"); (None, tokenizer.stream.pos()) } else { (Some(Selector { components }), tokenizer.stream.pos()) } } impl<'a> fmt::Display for Selector<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for component in &self.components { match component.combinator { Combinator::Descendant => write!(f, " ")?, Combinator::Child => write!(f, " > ")?, Combinator::AdjacentSibling => write!(f, " + ")?, Combinator::None => {} } match component.selector.kind { SimpleSelectorType::Universal => write!(f, "*")?, SimpleSelectorType::Type(ident) => write!(f, "{}", ident)?, }; for sel in &component.selector.subselectors { match sel { SubSelector::Attribute(name, operator) => { match operator { AttributeOperator::Exists => { write!(f, "[{}]", name)?; } AttributeOperator::Matches(value) => { write!(f, "[{}='{}']", name, value)?; } AttributeOperator::Contains(value) => { write!(f, "[{}~='{}']", name, value)?; } AttributeOperator::StartsWith(value) => { write!(f, "[{}|='{}']", name, value)?; } }; } SubSelector::PseudoClass(class) => write!(f, ":{}", class)?, } } } Ok(()) } } /// A selector token. #[derive(Clone, Copy, PartialEq, Debug)] pub enum SelectorToken<'a> { /// `*` UniversalSelector, /// `div` TypeSelector(&'a str), /// `.class` ClassSelector(&'a str), /// `#id` IdSelector(&'a str), /// `[color=red]` AttributeSelector(&'a str, AttributeOperator<'a>), /// `:first-child` PseudoClass(&'a str), /// `:lang(en)` LangPseudoClass(&'a str), /// `a b` DescendantCombinator, /// `a > b` ChildCombinator, /// `a + b` AdjacentCombinator, } /// A selector tokenizer. /// /// # Example /// /// ``` /// use simplecss::{SelectorTokenizer, SelectorToken}; /// /// let mut t = SelectorTokenizer::from("div > p:first-child"); /// assert_eq!(t.next().unwrap().unwrap(), SelectorToken::TypeSelector("div")); /// assert_eq!(t.next().unwrap().unwrap(), SelectorToken::ChildCombinator); /// assert_eq!(t.next().unwrap().unwrap(), SelectorToken::TypeSelector("p")); /// assert_eq!(t.next().unwrap().unwrap(), SelectorToken::PseudoClass("first-child")); /// assert!(t.next().is_none()); /// ``` pub struct SelectorTokenizer<'a> { stream: Stream<'a>, after_combinator: bool, finished: bool, } impl<'a> From<&'a str> for SelectorTokenizer<'a> { fn from(text: &'a str) -> Self { SelectorTokenizer { stream: Stream::from(text), after_combinator: true, finished: false, } } } impl<'a> Iterator for SelectorTokenizer<'a> { type Item = Result, Error>; fn next(&mut self) -> Option { if self.finished || self.stream.at_end() { if self.after_combinator { self.after_combinator = false; return Some(Err(Error::SelectorMissing)); } return None; } macro_rules! try2 { ($e:expr) => { match $e { Ok(v) => v, Err(e) => { self.finished = true; return Some(Err(e)); } } }; } match self.stream.curr_byte_unchecked() { b'*' => { if !self.after_combinator { self.finished = true; return Some(Err(Error::UnexpectedSelector)); } self.after_combinator = false; self.stream.advance(1); Some(Ok(SelectorToken::UniversalSelector)) } b'#' => { self.after_combinator = false; self.stream.advance(1); let ident = try2!(self.stream.consume_ident()); Some(Ok(SelectorToken::IdSelector(ident))) } b'.' => { self.after_combinator = false; self.stream.advance(1); let ident = try2!(self.stream.consume_ident()); Some(Ok(SelectorToken::ClassSelector(ident))) } b'[' => { self.after_combinator = false; self.stream.advance(1); let ident = try2!(self.stream.consume_ident()); let op = match try2!(self.stream.curr_byte()) { b']' => { AttributeOperator::Exists } b'=' => { self.stream.advance(1); let value = try2!(self.stream.consume_string()); AttributeOperator::Matches(value) } b'~' => { self.stream.advance(1); try2!(self.stream.consume_byte(b'=')); let value = try2!(self.stream.consume_string()); AttributeOperator::Contains(value) } b'|' => { self.stream.advance(1); try2!(self.stream.consume_byte(b'=')); let value = try2!(self.stream.consume_string()); AttributeOperator::StartsWith(value) } _ => { self.finished = true; return Some(Err(Error::InvalidAttributeSelector)); } }; try2!(self.stream.consume_byte(b']')); Some(Ok(SelectorToken::AttributeSelector(ident, op))) } b':' => { self.after_combinator = false; self.stream.advance(1); let ident = try2!(self.stream.consume_ident()); if ident == "lang" { try2!(self.stream.consume_byte(b'(')); let lang = self.stream.consume_bytes(|c| c != b')').trim(); try2!(self.stream.consume_byte(b')')); if lang.is_empty() { self.finished = true; return Some(Err(Error::InvalidLanguagePseudoClass)); } Some(Ok(SelectorToken::LangPseudoClass(lang))) } else { Some(Ok(SelectorToken::PseudoClass(ident))) } } b'>' => { if self.after_combinator { self.after_combinator = false; self.finished = true; return Some(Err(Error::UnexpectedCombinator)); } self.stream.advance(1); self.after_combinator = true; Some(Ok(SelectorToken::ChildCombinator)) } b'+' => { if self.after_combinator { self.after_combinator = false; self.finished = true; return Some(Err(Error::UnexpectedCombinator)); } self.stream.advance(1); self.after_combinator = true; Some(Ok(SelectorToken::AdjacentCombinator)) } b' ' | b'\t' | b'\n' | b'\r' | b'\x0C' => { self.stream.skip_spaces(); if self.after_combinator { return self.next(); } while self.stream.curr_byte() == Ok(b'/') { try2!(self.stream.skip_comment()); self.stream.skip_spaces(); } match self.stream.curr_byte() { Ok(b'>') | Ok(b'+') | Ok(b',') | Ok(b'{') | Err(_) => { self.next() } _ => { if self.after_combinator { self.after_combinator = false; self.finished = true; return Some(Err(Error::UnexpectedSelector)); } self.after_combinator = true; Some(Ok(SelectorToken::DescendantCombinator)) } } } b'/' => { if self.stream.next_byte() == Ok(b'*') { try2!(self.stream.skip_comment()); } else { self.finished = true; } self.next() } b',' | b'{' => { self.finished = true; self.next() } _ => { let ident = try2!(self.stream.consume_ident()); if !self.after_combinator { self.finished = true; return Some(Err(Error::UnexpectedSelector)); } self.after_combinator = false; Some(Ok(SelectorToken::TypeSelector(ident))) } } } } simplecss-0.2.0/src/stream.rs010064400017500001750000000161741352143072700144010ustar0000000000000000use std::str; use crate::{Error, TextPos}; trait CssCharExt { fn is_name_start(&self) -> bool; fn is_name_char(&self) -> bool; fn is_non_ascii(&self) -> bool; fn is_escape(&self) -> bool; } impl CssCharExt for char { #[inline] fn is_name_start(&self) -> bool { match *self { '_' | 'a'...'z' | 'A'...'Z' => true, _ => self.is_non_ascii() || self.is_escape(), } } #[inline] fn is_name_char(&self) -> bool { match *self { '_' | 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' => true, _ => self.is_non_ascii() || self.is_escape(), } } #[inline] fn is_non_ascii(&self) -> bool { *self as u32 > 237 } #[inline] fn is_escape(&self) -> bool { // TODO: this false } } #[derive(Clone, Copy, PartialEq, Debug)] pub(crate) struct Stream<'a> { text: &'a str, pos: usize, end: usize, } impl<'a> From<&'a str> for Stream<'a> { fn from(text: &'a str) -> Self { Stream::new(text.into()).into() } } impl<'a> Stream<'a> { pub fn new(text: &'a str) -> Self { Stream { text, pos: 0, end: text.len(), } } #[inline] pub fn pos(&self) -> usize { self.pos } #[inline] pub fn jump_to_end(&mut self) { self.pos = self.end; } #[inline] pub fn at_end(&self) -> bool { self.pos >= self.end } #[inline] pub fn curr_byte(&self) -> Result { if self.at_end() { return Err(Error::UnexpectedEndOfStream); } Ok(self.curr_byte_unchecked()) } #[inline] pub fn curr_byte_unchecked(&self) -> u8 { self.text.as_bytes()[self.pos] } #[inline] pub fn next_byte(&self) -> Result { if self.pos + 1 >= self.end { return Err(Error::UnexpectedEndOfStream); } Ok(self.text.as_bytes()[self.pos + 1]) } #[inline] pub fn advance(&mut self, n: usize) { debug_assert!(self.pos + n <= self.end); self.pos += n; } pub fn consume_byte(&mut self, c: u8) -> Result<(), Error> { if self.curr_byte()? != c { return Err(Error::InvalidByte { expected: c, actual: self.curr_byte()?, pos: self.gen_text_pos(), }); } self.advance(1); Ok(()) } pub fn try_consume_byte(&mut self, c: u8) { if self.curr_byte() == Ok(c) { self.advance(1); } } pub fn consume_bytes(&mut self, f: F) -> &'a str where F: Fn(u8) -> bool { let start = self.pos; self.skip_bytes(f); self.slice_back(start) } pub fn skip_bytes(&mut self, f: F) where F: Fn(u8) -> bool { while !self.at_end() && f(self.curr_byte_unchecked()) { self.advance(1); } } #[inline] fn chars(&self) -> str::Chars<'a> { self.text[self.pos..self.end].chars() } #[inline] pub fn slice_range(&self, start: usize, end: usize) -> &'a str { &self.text[start..end] } #[inline] pub fn slice_back(&self, pos: usize) -> &'a str { &self.text[pos..self.pos] } #[inline] pub fn slice_tail(&self) -> &'a str { &self.text[self.pos..] } #[inline] pub fn skip_spaces(&mut self) { while !self.at_end() { match self.curr_byte_unchecked() { b' ' | b'\t' | b'\n' | b'\r' | b'\x0C' => self.advance(1), _ => break, } } } #[inline] pub fn skip_spaces_and_comments(&mut self) -> Result<(), Error> { self.skip_spaces(); while self.curr_byte() == Ok(b'/') && self.next_byte() == Ok(b'*') { self.skip_comment()?; self.skip_spaces(); } Ok(()) } pub fn consume_ident(&mut self) -> Result<&'a str, Error> { let start = self.pos(); if self.curr_byte() == Ok(b'-') { self.advance(1); } let mut iter = self.chars(); if let Some(c) = iter.next() { if c.is_name_start() { self.advance(c.len_utf8()); } else { return Err(Error::InvalidIdent(self.gen_text_pos_from(start))); } } for c in iter { if c.is_name_char() { self.advance(c.len_utf8()); } else { break; } } if start == self.pos() { return Err(Error::InvalidIdent(self.gen_text_pos_from(start))); } let name = self.slice_back(start); Ok(name) } pub fn consume_string(&mut self) -> Result<&'a str, Error> { // Check for opening quote. let quote = self.curr_byte()?; if quote == b'\'' || quote == b'"' { let mut prev = quote; self.advance(1); let start = self.pos(); while !self.at_end() { let curr = self.curr_byte_unchecked(); // Advance until the closing quote. if curr == quote { // Check for escaped quote. if prev != b'\\' { break; } } prev = curr; self.advance(1); } let value = self.slice_back(start); // Check for closing quote. self.consume_byte(quote)?; Ok(value) } else { self.consume_ident() } } pub fn skip_comment(&mut self) -> Result<(), Error> { let start = self.pos(); self.skip_comment_impl() .map_err(|_| Error::InvalidComment(self.gen_text_pos_from(start)))?; Ok(()) } fn skip_comment_impl(&mut self) -> Result<(), Error> { self.consume_byte(b'/')?; self.consume_byte(b'*')?; while !self.at_end() { let curr = self.curr_byte_unchecked(); if curr == b'*' && self.next_byte() == Ok(b'/') { break; } self.advance(1); } self.consume_byte(b'*')?; self.consume_byte(b'/')?; Ok(()) } #[inline(never)] pub fn gen_text_pos(&self) -> TextPos { let row = Self::calc_curr_row(self.text, self.pos); let col = Self::calc_curr_col(self.text, self.pos); TextPos::new(row, col) } #[inline(never)] pub fn gen_text_pos_from(&self, pos: usize) -> TextPos { let mut s = self.clone(); s.pos = std::cmp::min(pos, self.text.len()); s.gen_text_pos() } fn calc_curr_row(text: &str, end: usize) -> u32 { let mut row = 1; for c in &text.as_bytes()[..end] { if *c == b'\n' { row += 1; } } row } fn calc_curr_col(text: &str, end: usize) -> u32 { let mut col = 1; for c in text[..end].chars().rev() { if c == '\n' { break; } else { col += 1; } } col } } simplecss-0.2.0/tests/declaration_tokenizer.rs010064400017500001750000000071401352500115400200210ustar0000000000000000use simplecss::*; macro_rules! tokenize { ($name:ident, $text:expr, $( $token:expr ),*) => ( #[test] fn $name() { let mut t = DeclarationTokenizer::from($text); $( assert_eq!(t.next().unwrap(), $token); )* assert!(t.next().is_none()); } ) } fn declare<'a>(name: &'a str, value: &'a str) -> Declaration<'a> { Declaration { name, value, important: false } } fn declare_important<'a>(name: &'a str, value: &'a str) -> Declaration<'a> { Declaration { name, value, important: true } } tokenize!(tokenize_01, "", ); tokenize!(tokenize_02, " ", ); tokenize!(tokenize_03, "/**/", ); tokenize!(tokenize_04, "color:red", declare("color", "red") ); tokenize!(tokenize_05, "color:red;", declare("color", "red") ); tokenize!(tokenize_06, "color:red ", declare("color", "red") ); tokenize!(tokenize_07, " color: red; ", declare("color", "red") ); tokenize!(tokenize_08, " color : red ; ", declare("color", "red") ); tokenize!(tokenize_09, " color:red;;;;color:red; ", declare("color", "red"), declare("color", "red") ); tokenize!(tokenize_10, "background: url(\"img.png\");", declare("background", "url(\"img.png\")") ); tokenize!(tokenize_11, "background: url(\"{}\");", declare("background", "url(\"{}\")") ); tokenize!(tokenize_12, "color: red ! important", declare_important("color", "red") ); tokenize!(tokenize_13, "color: red !important", declare_important("color", "red") ); tokenize!(tokenize_14, "color: red!important", declare_important("color", "red") ); tokenize!(tokenize_15, "color: red !/**/important", declare_important("color", "red") ); tokenize!(tokenize_16, "border: 1em solid blue", declare("border", "1em solid blue") ); tokenize!(tokenize_17, "background: navy url(support/diamond.png) -2em -2em no-repeat", declare("background", "navy url(support/diamond.png) -2em -2em no-repeat") ); tokenize!(tokenize_18, "/**/color:red", declare("color", "red") ); tokenize!(tokenize_19, "/* *\\/*/color: red;", declare("color", "red") ); tokenize!(tokenize_20, "/**/color/**/:/**/red/**/;/**/", declare("color", "red") ); tokenize!(tokenize_21, "\ncolor\n:\nred\n;\n", declare("color", "red") ); tokenize!(tokenize_22, "{color:red}", ); tokenize!(tokenize_23, "(color:red)", ); tokenize!(tokenize_24, "[color:red]", ); tokenize!(tokenize_25, "color:", ); tokenize!(tokenize_26, "value:\"text\"", declare("value", "\"text\"") ); tokenize!(tokenize_27, "value:'text'", declare("value", "'text'") ); tokenize!(tokenize_28, "color:#fff", declare("color", "#fff") ); tokenize!(tokenize_29, "color:0.5", declare("color", "0.5") ); tokenize!(tokenize_30, "color:.5", declare("color", ".5") ); tokenize!(tokenize_31, "color:#FFF", declare("color", "#FFF") ); tokenize!(tokenize_32, "content: counter(chapno, upper-roman) \". \"", declare("content", "counter(chapno, upper-roman) \". \"") ); tokenize!(tokenize_33, "font-family:'Noto Serif','DejaVu Serif',serif", declare("font-family", "'Noto Serif','DejaVu Serif',serif") ); tokenize!(tokenize_34, "*zoom:1;", declare("zoom", "1") ); //tokenize!(tokenize_, "@unsupported { splines: reticulating } color: green", // declare("color", "green") //); //tokenize!(tokenize_, "/*\\*/*/color: red;", declare("color", "red")); //tokenize!(tokenize_, "\"this is a string]}\"\"[{\\\"'\"; /*should be parsed as a string but be ignored*/ // {{}}[]''; /*should be parsed as nested blocks and a string but be ignored*/ // color: red;", declare("color", "red")); simplecss-0.2.0/tests/select.rs010064400017500001750000000177401352500740100147310ustar0000000000000000use simplecss::*; struct XmlNode<'a, 'input: 'a>(roxmltree::Node<'a, 'input>); impl<'a, 'input: 'a> XmlNode<'a, 'input> { fn select(&self, text: &str) -> Vec> { let selectors = Selector::parse(text).unwrap(); let mut nodes = Vec::new(); for node in self.0.descendants().filter(|n| n.is_element()) { if selectors.matches(&XmlNode(node)) { nodes.push(node); } } nodes } } impl simplecss::Element for XmlNode<'_, '_> { fn parent_element(&self) -> Option { self.0.parent_element().map(XmlNode) } fn prev_sibling_element(&self) -> Option { self.0.prev_siblings().filter(|n| n.is_element()).nth(0).map(XmlNode) } fn has_local_name(&self, local_name: &str) -> bool { self.0.tag_name().name() == local_name } fn attribute_matches(&self, local_name: &str, operator: AttributeOperator) -> bool { match self.0.attribute(local_name) { Some(value) => operator.matches(value), None => false, } } fn pseudo_class_matches(&self, class: PseudoClass) -> bool { match class { PseudoClass::FirstChild => self.prev_sibling_element().is_none(), _ => false, } } } macro_rules! match_single { ($doc:expr, $selector:expr) => {{ let nodes = XmlNode($doc.root_element()).select($selector); assert_eq!(nodes.len(), 1); nodes[0].attribute("id").unwrap() }}; } macro_rules! match_none { ($doc:expr, $selector:expr) => {{ assert_eq!(XmlNode($doc.root_element()).select($selector).len(), 0); }}; } #[test] fn select_01() { let doc = roxmltree::Document::parse("
").unwrap(); assert_eq!(match_single!(doc, "*"), "div1"); } #[test] fn select_02() { let doc = roxmltree::Document::parse("
").unwrap(); assert_eq!(match_single!(doc, "div"), "div1"); match_none!(doc, "p"); } #[test] fn select_03() { let doc = roxmltree::Document::parse("
").unwrap(); assert_eq!(match_single!(doc, "#div1"), "div1"); match_none!(doc, "#d1"); } #[test] fn select_04() { let doc = roxmltree::Document::parse("
").unwrap(); match_none!(doc, "p#div1"); } #[test] fn select_05() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div p"), "p1"); } #[test] fn select_06() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div p"), "p1"); } #[test] fn select_07() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div p"), "p1"); } #[test] fn select_08() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div p"), "p1"); } #[test] fn select_09() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div g p"), "p1"); } #[test] fn select_10() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "div g p"); } #[test] fn select_11() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div * p"), "p1"); } #[test] fn select_12() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div p *[color]"), "rect2"); assert_eq!(match_single!(doc, "div p [color]"), "rect2"); } #[test] fn select_13() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div > p"), "p1"); } #[test] fn select_14() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "div > p"); } #[test] fn select_15() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "div > p"); } #[test] fn select_16() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "div ol>li p"), "p1"); } #[test] fn select_17() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "div ol>li p"); } #[test] fn select_18() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "g + p"), "p1"); } #[test] fn select_19() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "g + p"), "p1"); } #[test] fn select_20() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "g + p"); } #[test] fn select_21() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "div + p"); } #[test] fn select_22() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "[id=p1]"), "p1"); } #[test] fn select_23() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "[class~=warn]"), "p1"); } #[test] fn select_24() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "[class~='test warn']"); } #[test] fn select_25() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "[lang=en]"), "p1"); assert_eq!(match_single!(doc, "[lang|=en]"), "p1"); } #[test] fn select_26() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "[lang='en-US']"), "p1"); assert_eq!(match_single!(doc, "[lang|=en]"), "p1"); } #[test] fn select_27() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, ".marine.pastoral"), "p1"); } #[test] fn select_28() { let doc = roxmltree::Document::parse("\

").unwrap(); assert_eq!(match_single!(doc, "p:first-child"), "p1"); } #[test] fn select_29() { let doc = roxmltree::Document::parse("\

").unwrap(); match_none!(doc, "p:first-child"); } #[test] fn select_30() { let doc = roxmltree::Document::parse("\

").unwrap(); let nodes = XmlNode(doc.root_element()).select(":first-child"); assert_eq!(nodes.len(), 2); assert_eq!(nodes[0].attribute("id").unwrap(), "div1"); assert_eq!(nodes[1].attribute("id").unwrap(), "p1"); } #[test] fn to_string() { let selectors = Selector::parse("a > b").unwrap(); assert_eq!(selectors.to_string(), "a > b"); } simplecss-0.2.0/tests/selector_tokenizer.rs010064400017500001750000000220301352501003100173410ustar0000000000000000use simplecss::*; macro_rules! tokenize { ($name:ident, $text:expr, $( $token:expr ),*) => ( #[test] fn $name() { let mut t = SelectorTokenizer::from($text); $( assert_eq!(t.next().unwrap().unwrap(), $token); )* assert!(t.next().is_none()); } ) } tokenize!(tokenize_01, "*", SelectorToken::UniversalSelector ); tokenize!(tokenize_02, "div", SelectorToken::TypeSelector("div") ); tokenize!(tokenize_03, "#div", SelectorToken::IdSelector("div") ); tokenize!(tokenize_04, ".div", SelectorToken::ClassSelector("div") ); tokenize!(tokenize_05, "[id]", SelectorToken::AttributeSelector("id", AttributeOperator::Exists) ); tokenize!(tokenize_06, "[id=test]", SelectorToken::AttributeSelector("id", AttributeOperator::Matches("test")) ); tokenize!(tokenize_07, "[id~=test]", SelectorToken::AttributeSelector("id", AttributeOperator::Contains("test")) ); tokenize!(tokenize_08, "[id|=test]", SelectorToken::AttributeSelector("id", AttributeOperator::StartsWith("test")) ); tokenize!(tokenize_09, "[id='test']", SelectorToken::AttributeSelector("id", AttributeOperator::Matches("test")) ); tokenize!(tokenize_10, "[id=\"test\"]", SelectorToken::AttributeSelector("id", AttributeOperator::Matches("test")) ); tokenize!(tokenize_11, "[id='te\\'st']", SelectorToken::AttributeSelector("id", AttributeOperator::Matches("te\\'st")) ); tokenize!(tokenize_12, "[id=\"te\\\"st\"]", SelectorToken::AttributeSelector("id", AttributeOperator::Matches("te\\\"st")) ); tokenize!(tokenize_13, "div:first-child", SelectorToken::TypeSelector("div"), SelectorToken::PseudoClass("first-child") ); tokenize!(tokenize_14, ":first-child", SelectorToken::PseudoClass("first-child") ); tokenize!(tokenize_15, "div p", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_16, "div p a", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("p"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("a") ); tokenize!(tokenize_17, "div>p", SelectorToken::TypeSelector("div"), SelectorToken::ChildCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_18, "div >p", SelectorToken::TypeSelector("div"), SelectorToken::ChildCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_19, "div> p", SelectorToken::TypeSelector("div"), SelectorToken::ChildCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_20, "div > p", SelectorToken::TypeSelector("div"), SelectorToken::ChildCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_21, "div .p", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::ClassSelector("p") ); tokenize!(tokenize_22, "div *", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::UniversalSelector ); tokenize!(tokenize_23, "div #p", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::IdSelector("p") ); tokenize!(tokenize_24, "div [id]", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::AttributeSelector("id", AttributeOperator::Exists) ); tokenize!(tokenize_25, "div :link", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::PseudoClass("link") ); tokenize!(tokenize_26, "div+p", SelectorToken::TypeSelector("div"), SelectorToken::AdjacentCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_27, "div +p", SelectorToken::TypeSelector("div"), SelectorToken::AdjacentCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_28, "div+ p", SelectorToken::TypeSelector("div"), SelectorToken::AdjacentCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_29, "div + p", SelectorToken::TypeSelector("div"), SelectorToken::AdjacentCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_30, "div {", SelectorToken::TypeSelector("div") ); tokenize!(tokenize_31, "div,", SelectorToken::TypeSelector("div") ); tokenize!(tokenize_32, "div{", SelectorToken::TypeSelector("div") ); tokenize!(tokenize_33, "div ,", SelectorToken::TypeSelector("div") ); tokenize!(tokenize_34, "div.test", SelectorToken::TypeSelector("div"), SelectorToken::ClassSelector("test") ); tokenize!(tokenize_35, "div.test.warn", SelectorToken::TypeSelector("div"), SelectorToken::ClassSelector("test"), SelectorToken::ClassSelector("warn") ); tokenize!(tokenize_36, "div#id", SelectorToken::TypeSelector("div"), SelectorToken::IdSelector("id") ); tokenize!(tokenize_37, "*[id]", SelectorToken::UniversalSelector, SelectorToken::AttributeSelector("id", AttributeOperator::Exists) ); tokenize!(tokenize_38, "*.test", SelectorToken::UniversalSelector, SelectorToken::ClassSelector("test") ); tokenize!(tokenize_39, "*#id", SelectorToken::UniversalSelector, SelectorToken::IdSelector("id") ); tokenize!(tokenize_40, "div * p", SelectorToken::TypeSelector("div"), SelectorToken::DescendantCombinator, SelectorToken::UniversalSelector, SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("p") ); tokenize!(tokenize_41, "div[id=test][color=red]", SelectorToken::TypeSelector("div"), SelectorToken::AttributeSelector("id", AttributeOperator::Matches("test")), SelectorToken::AttributeSelector("color", AttributeOperator::Matches("red")) ); tokenize!(tokenize_42, "a.external:visited", SelectorToken::TypeSelector("a"), SelectorToken::ClassSelector("external"), SelectorToken::PseudoClass("visited") ); tokenize!(tokenize_43, ":lang(en)", SelectorToken::LangPseudoClass("en") ); tokenize!(tokenize_44, "a\nb", SelectorToken::TypeSelector("a"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("b") ); tokenize!(tokenize_45, ".warn :first-child", SelectorToken::ClassSelector("warn"), SelectorToken::DescendantCombinator, SelectorToken::PseudoClass("first-child") ); macro_rules! malformed { ($name:ident, $text:expr, $err_str:expr) => ( #[test] fn $name() { for token in SelectorTokenizer::from($text) { match token { Ok(_) => {} Err(e) => { assert_eq!(e.to_string(), $err_str); return; } } } unreachable!() } ) } malformed!(malformed_01, ">", "unexpected combinator"); malformed!(malformed_02, "+", "unexpected combinator"); malformed!(malformed_03, "> a", "unexpected combinator"); malformed!(malformed_04, "a >", "selector missing"); malformed!(malformed_05, "*a", "unexpected selector"); malformed!(malformed_06, "a*", "unexpected selector"); malformed!(malformed_07, "a > ,", "selector missing"); malformed!(malformed_08, "a > >", "unexpected combinator"); malformed!(malformed_09, "a > {", "selector missing"); malformed!(malformed_10, "a/**/b", "unexpected selector"); malformed!(malformed_11, "a < b", "invalid ident at 1:3"); malformed!(malformed_12, ":lang()", "invalid language pseudo-class"); malformed!(malformed_13, ":lang( )", "invalid language pseudo-class"); malformed!(malformed_14, "::first-child", "invalid ident at 1:2"); malformed!(malformed_15, "[olor:red", "invalid or unsupported attribute selector"); malformed!(malformed_16, "", "selector missing"); malformed!(malformed_17, " ", "selector missing"); malformed!(malformed_18, "/**/", "selector missing"); tokenize!(comment_01, "/**/a", SelectorToken::TypeSelector("a") ); tokenize!(comment_02, "/* */a", SelectorToken::TypeSelector("a") ); tokenize!(comment_03, "/* comment */a", SelectorToken::TypeSelector("a") ); tokenize!(comment_04, "/**/ /**/a", SelectorToken::TypeSelector("a") ); tokenize!(comment_05, "/**/ a /**/", SelectorToken::TypeSelector("a") ); tokenize!(comment_06, "a /**/ b", SelectorToken::TypeSelector("a"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("b") ); tokenize!(comment_08, "a /**/b", SelectorToken::TypeSelector("a"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("b") ); tokenize!(comment_09, "a/**/ b", SelectorToken::TypeSelector("a"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("b") ); tokenize!(comment_10, "a/**/ /**/b", SelectorToken::TypeSelector("a"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("b") ); tokenize!(comment_11, "a /**/ /**/ b", SelectorToken::TypeSelector("a"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("b") ); tokenize!(comment_12, "a /**//**/ b", SelectorToken::TypeSelector("a"), SelectorToken::DescendantCombinator, SelectorToken::TypeSelector("b") ); simplecss-0.2.0/tests/stylesheet.rs010064400017500001750000000060761352500737100156510ustar0000000000000000use simplecss::*; #[test] fn style_01() { let style = StyleSheet::parse(""); assert_eq!(style.to_string(), ""); } #[test] fn style_02() { let style = StyleSheet::parse("a {}"); assert_eq!(style.to_string(), ""); } #[test] fn style_03() { let style = StyleSheet::parse("a { color:red }"); assert_eq!(style.to_string(), "a { color:red; }"); } #[test] fn style_04() { let style = StyleSheet::parse("/**/"); assert_eq!(style.to_string(), ""); } #[test] fn style_05() { let style = StyleSheet::parse("a { color:red } /**/"); assert_eq!(style.to_string(), "a { color:red; }"); } #[test] fn style_06() { let style = StyleSheet::parse("a, b { color:red }"); assert_eq!(style.to_string(), "a { color:red; }\nb { color:red; }"); } #[test] fn style_07() { let style = StyleSheet::parse("a, { color:red }"); assert_eq!(style.to_string(), "a { color:red; }"); } #[test] fn style_08() { let style = StyleSheet::parse("a,, { color:red }"); assert_eq!(style.to_string(), "a { color:red; }"); } #[test] fn style_09() { let style = StyleSheet::parse("a,,b { color:red }"); assert_eq!(style.to_string(), "a { color:red; }\nb { color:red; }"); } #[test] fn style_10() { let style = StyleSheet::parse(",a { color:red }"); assert_eq!(style.to_string(), "a { color:red; }"); } #[test] fn style_11() { let style = StyleSheet::parse("@import \"subs.css\";\na { color:red }"); assert_eq!(style.to_string(), "a { color:red; }"); } #[test] fn style_12() { let style = StyleSheet::parse("\ @media screen { p:before { content: 'Hello'; } } a { color:red }"); assert_eq!(style.to_string(), "a { color:red; }"); } #[test] fn style_13() { let style = StyleSheet::parse("a > { color:red }"); assert_eq!(style.to_string(), ""); } #[test] fn style_14() { let style = StyleSheet::parse("p { color:green; color }"); assert_eq!(style.to_string(), "p { color:green; }"); } #[test] fn style_15() { let style = StyleSheet::parse("p { color; color:green }"); assert_eq!(style.to_string(), ""); // TODO: should be 'p { color:green; }' } #[test] fn style_16() { let style = StyleSheet::parse("p { color:green; color: }"); assert_eq!(style.to_string(), "p { color:green; }"); } #[test] fn style_17() { let style = StyleSheet::parse("p { color:green; color:; color:red; }"); assert_eq!(style.to_string(), "p { color:green; }"); } #[test] fn style_18() { let style = StyleSheet::parse("p { color:green; color{;color:maroon} }"); assert_eq!(style.to_string(), "p { color:green; }"); } #[test] fn style_19() { let style = StyleSheet::parse("p { color{;color:maroon} color:green; }"); assert_eq!(style.to_string(), ""); // TODO: should be 'p { color:green; }' } #[test] fn style_20() { let style = StyleSheet::parse("\ h1 { color: green } h2 & h3 { color: red } h4 { color: black } "); assert_eq!(style.to_string(), "h1 { color:green; }\nh4 { color:black; }"); } #[test] fn style_21() { let style = StyleSheet::parse(":le>*"); assert_eq!(style.to_string(), ""); } simplecss-0.2.0/tests/warnings.rs010064400017500001750000000014511352143744300153030ustar0000000000000000fn run_process(input: &str) -> String { use std::io::Write; use std::process::Stdio; let mut child = std::process::Command::new("target/debug/examples/parse") .arg("-") .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn() .unwrap(); child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap(); let output = child.wait_with_output().expect("Failed to read stdout"); String::from_utf8(output.stderr).unwrap() } #[test] fn style_01() { assert_eq!(run_process("> {}"), "WARN: Selector parsing failed cause unexpected combinator.\n"); } #[test] fn style_02() { assert_eq!(run_process("@import 'subs.css';"), "WARN: The @import rule is not supported. Skipped.\n"); } simplecss-0.2.0/.cargo_vcs_info.json0000644000000001120000000000000130660ustar00{ "git": { "sha1": "01fab2f637e66be96d13816a3e3be8c030c71e00" } } simplecss-0.2.0/Cargo.lock0000644000000037050000000000000110540ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "cfg-if" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "env_logger" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "log" version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "roxmltree" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "xmlparser 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "simplecss" version = "0.2.0" dependencies = [ "env_logger 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "roxmltree 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "xmlparser" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" [metadata] "checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" "checksum env_logger 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3" "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" "checksum roxmltree 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "153c367ce9fb8ef7afe637ef92bd083ba0f88b03ef3fcf0287d40be05ae0a61c" "checksum xmlparser 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ecec95f00fb0ff019153e64ea520f87d1409769db3e8f4db3ea588638a3e1cee"