simplecss-0.2.2/.cargo_vcs_info.json0000644000000001360000000000100130370ustar { "git": { "sha1": "6eacb39ca5c4c2390bfde374ed0651f0e35c9d8d" }, "path_in_vcs": "" }simplecss-0.2.2/AUTHORS000064400000000000000000000004631046102023000127020ustar 00000000000000# This is the list of SimpleCSS's significant contributors. # # This does not necessarily list everyone who has contributed code, # especially since many employees of one corporation may be contributing. # To see the full list of contributors, see the revision history in # source control. Yevhenii Reizner simplecss-0.2.2/CHANGELOG.md000064400000000000000000000030761046102023000134460ustar 00000000000000# Changelog The latest published SimpleCSS release is [0.2.2](#022-2025-01-06) which was released on 2022-01-06. You can find its changes [documented below](#022-2025-01-06). ## [Unreleased] This release has an [MSRV][] of 1.65. ## [0.2.2][] (2025-01-06) This release has an [MSRV][] of 1.65. This is the first release under the stewardship of [Linebender][], who is now responsible for maintenance of this crate. Many thanks to Yevhenii Reizner for the years of hard work that he has poured into this and other crates. ### Added - Support for `no_std`. ([#17][] by [@waywardmonkeys][]) ## [0.2.1][] (2021-07-20) - Add rules sorting by specificity. ([#7][] by [@baskerville][]) ## [0.2.0][] (2019-08-17) - A complete rewrite. ## 0.1.0 (2017-01-14) - Initial release. [MSRV]: README.md#minimum-supported-rust-version-msrv [Linebender]: https://github.com/linebender [#7]: https://github.com/linebender/simplecss/pull/7 [#17]: https://github.com/linebender/simplecss/pull/17 [@baskerville]: https://github.com/baskerville [@waywardmonkeys]: https://github.com/waywardmonkeys [Unreleased]: https://github.com/RazrFalcon/simplecss/compare/v0.2.2...HEAD [0.2.2]: https://github.com/RazrFalcon/simplecss/compare/v0.2.1...v0.2.2 [0.2.1]: https://github.com/RazrFalcon/simplecss/compare/v0.2.0...v0.2.1 [0.2.0]: https://github.com/RazrFalcon/simplecss/compare/v0.1.0...v0.2.0 simplecss-0.2.2/Cargo.lock0000644000000020310000000000100110060ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "env_filter" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0" dependencies = [ "log", ] [[package]] name = "env_logger" version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcaee3d8e3cfc3fd92428d477bc97fc29ec8716d180c0d74c643bb26166660e0" dependencies = [ "env_filter", "log", ] [[package]] name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "roxmltree" version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "simplecss" version = "0.2.2" dependencies = [ "env_logger", "log", "roxmltree", ] simplecss-0.2.2/Cargo.toml0000644000000064570000000000100110510ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65" name = "simplecss" version = "0.2.2" build = false exclude = [ ".github", ".clippy.toml", ".gitignore", ".typos.toml", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A simple CSS 2 parser and selector." readme = "README.md" keywords = [ "css", "parser", "selector", ] categories = ["parser-implementations"] license = "Apache-2.0 OR MIT" repository = "https://github.com/linebender/simplecss" [lib] name = "simplecss" path = "src/lib.rs" [[example]] name = "parse" path = "examples/parse.rs" [[example]] name = "select" path = "examples/select.rs" [[test]] name = "declaration_tokenizer" path = "tests/declaration_tokenizer.rs" [[test]] name = "select" path = "tests/select.rs" [[test]] name = "selector_tokenizer" path = "tests/selector_tokenizer.rs" [[test]] name = "specificity" path = "tests/specificity.rs" [[test]] name = "stylesheet" path = "tests/stylesheet.rs" [[test]] name = "warnings" path = "tests/warnings.rs" [dependencies.log] version = "0.4.22" default-features = false [dev-dependencies.env_logger] version = "0.11.6" default-features = false [dev-dependencies.roxmltree] version = "0.20.0" [features] default = ["std"] std = ["log/std"] [lints.clippy] allow_attributes = "warn" allow_attributes_without_reason = "warn" cargo_common_metadata = "warn" cast_possible_truncation = "warn" collection_is_never_read = "warn" dbg_macro = "warn" debug_assert_with_mut_call = "warn" doc_markdown = "warn" exhaustive_enums = "warn" fn_to_numeric_cast_any = "warn" infinite_loop = "warn" large_include_file = "warn" large_stack_arrays = "warn" match_same_arms = "warn" mismatching_type_param_order = "warn" missing_assert_message = "warn" missing_errors_doc = "warn" missing_fields_in_debug = "warn" missing_panics_doc = "warn" negative_feature_names = "warn" partial_pub_fields = "warn" redundant_feature_names = "warn" return_self_not_must_use = "warn" same_functions_in_if_condition = "warn" semicolon_if_nothing_returned = "warn" shadow_unrelated = "warn" should_panic_without_expect = "warn" todo = "warn" too_many_arguments = "allow" unseparated_literal_suffix = "warn" use_self = "warn" wildcard_dependencies = "warn" wildcard_imports = "warn" [lints.rust] elided_lifetimes_in_paths = "warn" keyword_idents_2024 = "forbid" let_underscore_drop = "warn" missing_debug_implementations = "warn" missing_docs = "warn" non_ascii_idents = "forbid" non_local_definitions = "forbid" single_use_lifetimes = "warn" trivial_numeric_casts = "warn" unexpected_cfgs = "warn" unit_bindings = "warn" unnameable_types = "warn" unreachable_pub = "warn" unsafe_code = "forbid" unsafe_op_in_unsafe_fn = "forbid" unused_import_braces = "warn" unused_lifetimes = "warn" unused_macro_rules = "warn" unused_qualifications = "warn" variant_size_differences = "warn" simplecss-0.2.2/Cargo.toml.orig000064400000000000000000000053731046102023000145260ustar 00000000000000[package] name = "simplecss" version = "0.2.2" license = "Apache-2.0 OR MIT" edition = "2021" description = "A simple CSS 2 parser and selector." repository = "https://github.com/linebender/simplecss" keywords = ["css", "parser", "selector"] categories = ["parser-implementations"] readme = "README.md" # Keep in sync with RUST_MIN_VER in .github/workflows/ci.yml and with the relevant README.md files. # and with the MSRV in the `Unreleased` section of CHANGELOG.md. rust-version = "1.65" exclude = [".github", ".clippy.toml", ".gitignore", ".typos.toml"] [lints] rust.unsafe_code = "forbid" # LINEBENDER LINT SET - Cargo.toml - v3 # See https://linebender.org/wiki/canonical-lints/ rust.keyword_idents_2024 = "forbid" rust.non_ascii_idents = "forbid" rust.non_local_definitions = "forbid" rust.unsafe_op_in_unsafe_fn = "forbid" rust.elided_lifetimes_in_paths = "warn" rust.let_underscore_drop = "warn" rust.missing_debug_implementations = "warn" rust.missing_docs = "warn" rust.single_use_lifetimes = "warn" rust.trivial_numeric_casts = "warn" rust.unexpected_cfgs = "warn" rust.unit_bindings = "warn" rust.unnameable_types = "warn" rust.unreachable_pub = "warn" rust.unused_import_braces = "warn" rust.unused_lifetimes = "warn" rust.unused_macro_rules = "warn" rust.unused_qualifications = "warn" rust.variant_size_differences = "warn" clippy.too_many_arguments = "allow" clippy.allow_attributes = "warn" clippy.allow_attributes_without_reason = "warn" clippy.cast_possible_truncation = "warn" clippy.collection_is_never_read = "warn" clippy.dbg_macro = "warn" clippy.debug_assert_with_mut_call = "warn" clippy.doc_markdown = "warn" clippy.exhaustive_enums = "warn" clippy.fn_to_numeric_cast_any = "warn" clippy.infinite_loop = "warn" clippy.large_include_file = "warn" clippy.large_stack_arrays = "warn" clippy.match_same_arms = "warn" clippy.mismatching_type_param_order = "warn" clippy.missing_assert_message = "warn" clippy.missing_errors_doc = "warn" clippy.missing_fields_in_debug = "warn" clippy.missing_panics_doc = "warn" clippy.partial_pub_fields = "warn" clippy.return_self_not_must_use = "warn" clippy.same_functions_in_if_condition = "warn" clippy.semicolon_if_nothing_returned = "warn" clippy.shadow_unrelated = "warn" clippy.should_panic_without_expect = "warn" clippy.todo = "warn" clippy.unseparated_literal_suffix = "warn" clippy.use_self = "warn" clippy.wildcard_imports = "warn" clippy.cargo_common_metadata = "warn" clippy.negative_feature_names = "warn" clippy.redundant_feature_names = "warn" clippy.wildcard_dependencies = "warn" # END LINEBENDER LINT SET [features] default = ["std"] std = ["log/std"] [dependencies] log = { version = "0.4.22", default-features = false } [dev-dependencies] env_logger = { version = "0.11.6", default-features = false } roxmltree = "0.20.0" simplecss-0.2.2/LICENSE-APACHE000064400000000000000000000251371046102023000135630ustar 00000000000000 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.2/LICENSE-MIT000064400000000000000000000020721046102023000132640ustar 00000000000000The 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.2/README.md000064400000000000000000000070671046102023000131200ustar 00000000000000
# SimpleCSS **A simple [CSS 2.1](https://www.w3.org/TR/CSS21/) parser and selector.** [![Linebender Zulip, #resvg channel](https://img.shields.io/badge/Linebender-%23resvg-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/465085-resvg) [![dependency status](https://deps.rs/repo/github/linebender/simplecss/status.svg)](https://deps.rs/repo/github/linebender/simplecss) [![Apache 2.0 or MIT license.](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](#license) [![Build status](https://github.com/linebender/simplecss/workflows/CI/badge.svg)](https://github.com/linebender/simplecss/actions) [![Crates.io](https://img.shields.io/crates/v/simplecss.svg)](https://crates.io/crates/simplecss) [![Docs](https://docs.rs/simplecss/badge.svg)](https://docs.rs/simplecss) ![](https://img.shields.io/badge/unsafe-forbidden-brightgreen.svg)
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. - Unicode escape, like `\26`, is not supported. ## Features - Selector matching support. - The rules are sorted by specificity. - `!important` parsing support. - Has a high-level parsers and low-level, zero-allocation tokenizers. - No unsafe. ## Minimum supported Rust Version (MSRV) This version of SimpleCSS has been verified to compile with **Rust 1.65** and later. Future versions of SimpleCSS might increase the Rust version requirement. It will not be treated as a breaking change and as such can even happen with small patch releases.
Click here if compiling fails. As time has passed, some of SimpleCSS's dependencies could have released versions with a higher Rust requirement. If you encounter a compilation issue due to a dependency and don't want to upgrade your Rust toolchain, then you could downgrade the dependency. ```sh # Use the problematic dependency's name and version cargo update -p package_name --precise 0.1.1 ```
## Community [![Linebender Zulip, #resvg channel](https://img.shields.io/badge/Linebender-%23resvg-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/465085-resvg) Discussion of SimpleCSS development happens in the Linebender Zulip at , specifically the [#resvg channel](https://xi.zulipchat.com/#narrow/channel/465085-resvg). All public content can be read without logging in. ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) - MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. ## Contribution Contributions are welcome by pull request. The [Rust code of conduct] applies. Please feel free to add your name to the [AUTHORS] file in any substantive pull request. 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 licensed as above, without any additional terms or conditions. [Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct [AUTHORS]: ./AUTHORS simplecss-0.2.2/examples/parse.rs000064400000000000000000000015731046102023000151330ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Parse use 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.2/examples/select.rs000064400000000000000000000050531046102023000152750ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Select struct 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)?; self.0 .descendants() .filter(|n| n.is_element()) .find(|&node| selectors.matches(&XmlNode(node))) } } 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", "selected wrong element" ); assert_eq!( root.select("[color=red]").unwrap().attribute("id").unwrap(), "rect2", "selected wrong element" ); assert_eq!( root.select("svg rect").unwrap().attribute("id").unwrap(), "rect1", "selected wrong element" ); assert_eq!( root.select("svg > g > rect") .unwrap() .attribute("id") .unwrap(), "rect1", "selected wrong element" ); assert_eq!( root.select(".blue").unwrap().attribute("id").unwrap(), "rect1", "selected wrong element" ); } simplecss-0.2.2/src/lib.rs000064400000000000000000000344611046102023000135420ustar 00000000000000// Copyright 2016 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT /*! 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. - Unicode escape, like `\26`, is not supported. ## Features - Selector matching support. - The rules are sorted by specificity. - `!important` parsing support. - Has a high-level parsers and low-level, zero-allocation tokenizers. - No unsafe. */ // LINEBENDER LINT SET - lib.rs - v2 // See https://linebender.org/wiki/canonical-lints/ // These lints aren't included in Cargo.toml because they // shouldn't apply to examples and tests #![warn(unused_crate_dependencies)] #![warn(clippy::print_stdout, clippy::print_stderr)] // Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit. #![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))] // END LINEBENDER LINT SET #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![cfg_attr(all(not(feature = "std"), not(test)), no_std)] // The following lints are part of the Linebender standard set, // but resolving them has been deferred for now. // Feel free to send a PR that solves one or more of these. #![allow( missing_debug_implementations, unreachable_pub, clippy::use_self, clippy::missing_assert_message, clippy::missing_panics_doc, clippy::exhaustive_enums, clippy::unseparated_literal_suffix )] #![cfg_attr(test, allow(unused_crate_dependencies))] // Some dev dependencies are only used in tests extern crate alloc; use alloc::vec::Vec; use core::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") } } } } #[cfg(feature = "std")] 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()); // Sort the rules by specificity. self.rules .sort_by_cached_key(|rule| rule.selector.specificity()); } } 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(()) } } impl Default for StyleSheet<'_> { fn default() -> Self { Self::new() } } 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) = 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 rule in rules.iter_mut().skip(start_rule_idx) { rule.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(b'0'..=b'9') = s.curr_byte() { s.advance(1); } } 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.2/src/selector.rs000064400000000000000000000475331046102023000146200ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT use alloc::{vec, vec::Vec}; use core::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 AttributeOperator<'_> { /// 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 } /// Compute the selector's specificity. /// /// Cf. . pub fn specificity(&self) -> [u8; 3] { let mut spec = [0u8; 3]; for selector in self.components.iter().map(|c| &c.selector) { if matches!(selector.kind, SimpleSelectorType::Type(_)) { spec[2] = spec[2].saturating_add(1); } for sub in &selector.subselectors { match sub { SubSelector::Attribute("id", _) => spec[0] = spec[0].saturating_add(1), _ => spec[1] = spec[1].saturating_add(1), } } } spec } /// 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 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 fmt::Display for Selector<'_> { 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.2/src/stream.rs000064400000000000000000000163101046102023000142600ustar 00000000000000// Copyright 2016 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT use core::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) } } 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; s.pos = core::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.2/tests/declaration_tokenizer.rs000064400000000000000000000074741046102023000177320ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Declaration Tokenizer use 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.2/tests/select.rs000064400000000000000000000210551046102023000146210ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Select use 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 Element for XmlNode<'_, '_> { fn parent_element(&self) -> Option { self.0.parent_element().map(XmlNode) } fn prev_sibling_element(&self) -> Option { self.0.prev_sibling_element().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.2/tests/selector_tokenizer.rs000064400000000000000000000227461046102023000172640ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Selector Tokenizer use 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.2/tests/specificity.rs000064400000000000000000000022671046102023000156610ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Specificity use simplecss::*; #[test] fn spec_01() { let selectors = Selector::parse("*").unwrap(); assert_eq!(selectors.specificity(), [0, 0, 0]); } #[test] fn spec_02() { let selectors = Selector::parse("li").unwrap(); assert_eq!(selectors.specificity(), [0, 0, 1]); } #[test] fn spec_03() { let selectors = Selector::parse("ul li").unwrap(); assert_eq!(selectors.specificity(), [0, 0, 2]); } #[test] fn spec_04() { let selectors = Selector::parse("ul ol + li").unwrap(); assert_eq!(selectors.specificity(), [0, 0, 3]); } #[test] fn spec_05() { let selectors = Selector::parse("h1 + *[rel=up]").unwrap(); assert_eq!(selectors.specificity(), [0, 1, 1]); } #[test] fn spec_06() { let selectors = Selector::parse("ul ol li.red").unwrap(); assert_eq!(selectors.specificity(), [0, 1, 3]); } #[test] fn spec_07() { let selectors = Selector::parse("li.red.level").unwrap(); assert_eq!(selectors.specificity(), [0, 2, 1]); } #[test] fn spec_08() { let selectors = Selector::parse("#x34y").unwrap(); assert_eq!(selectors.specificity(), [1, 0, 0]); } simplecss-0.2.2/tests/stylesheet.rs000064400000000000000000000063311046102023000155330ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Stylesheet use 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.2/tests/warnings.rs000064400000000000000000000017111046102023000151670ustar 00000000000000// Copyright 2019 the SimpleCSS Authors // SPDX-License-Identifier: Apache-2.0 OR MIT //! Warnings fn 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" ); }