file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
crates/swc_typescript/tests/typescript.rs
Rust
use std::path::PathBuf; use swc_common::{comments::SingleThreadedComments, Mark}; use swc_ecma_codegen::to_code_with_comments; use swc_ecma_parser::{parse_file_as_program, Syntax, TsSyntax}; use swc_ecma_transforms_base::{fixer::paren_remover, resolver}; use swc_typescript::fast_dts::{FastDts, FastDtsOptions}; use testing::NormalizedOutput; #[testing::fixture("tests/**/*.ts")] #[testing::fixture("tests/**/*.tsx")] fn fixture(input: PathBuf) { let mut dts_code = String::new(); let res = testing::run_test2(false, |cm, handler| { let fm = cm.load_file(&input).expect("failed to load test case"); let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let comments = SingleThreadedComments::default(); let mut program = parse_file_as_program( &fm, Syntax::Typescript(TsSyntax { tsx: true, ..Default::default() }), Default::default(), Some(&comments), &mut Vec::new(), ) .map_err(|err| err.into_diagnostic(&handler).emit()) .map(|program| program.apply(resolver(unresolved_mark, top_level_mark, true))) .map(|program| program.apply(paren_remover(None))) .unwrap(); let internal_annotations = FastDts::get_internal_annotations(&comments); let mut checker = FastDts::new( fm.name.clone(), unresolved_mark, FastDtsOptions { internal_annotations: Some(internal_annotations), }, ); let issues = checker.transform(&mut program); dts_code = to_code_with_comments(Some(&comments), &program); for issue in issues { handler .struct_span_err(issue.range.span, &issue.message) .emit(); } if handler.has_errors() { Err(()) } else { Ok(()) } }); let mut output = format!("```==================== .D.TS ====================\n\n{dts_code}\n\n"); if let Err(issues) = res { output.push_str(&format!( "==================== Errors ====================\n{issues}\n\n```" )); } let output_path = input.with_extension("snap"); NormalizedOutput::from(output) .compare_to_file(output_path) .unwrap(); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_visit/src/lib.rs
Rust
//! Visitor generator for the rust language. //! //! //! There are three variants of visitor in swc. Those are `Fold`, `VisitMut`, //! `Visit`. //! //! # Comparisons //! //! ## `Fold` vs `VisitMut` //! //! `Fold` and `VisitMut` do almost identical tasks, but `Fold` is easier to use //! while being slower and weak to stack overflow for very deep asts. `Fold` is //! fast enough for almost all cases so it would be better to start with `Fold`. //! //! By very deep asts, I meant code like thousands of `a + a + a + a + ...`. //! //! //! # `Fold` //! //! > WARNING: `Fold` is slow, and it's recommended to use VisitMut if you are //! > experienced. //! //! //! `Fold` takes ownership of value, which means you have to return the new //! value. Returning new value means returning ownership of the value. But you //! don't have to care about ownership or about managing memories while using //! such visitors. `rustc` handles them automatically and all allocations will //! be freed when it goes out of the scope. //! //! You can invoke your `Fold` implementation like `node.fold_with(&mut //! visitor)` where `visitor` is your visitor. Note that as it takes ownership //! of value, you have to call `node.fold_children_with(self)` in e.g. `fn //! fold_module(&mut self, m: Module) -> Module` if you override the default //! behavior. Also you have to store return value from `fold_children_with`, //! like `let node = node.fold_children_with(self)`. Order of execution can be //! controlled using this. If there is some logic that should be applied to the //! parent first, you can call `fold_children_with` after such logic. //! //! # `VisitMut` //! //! `VisitMut` uses a mutable reference to AST nodes (e.g. `&mut Expr`). You can //! use `Take` from `swc_common::util::take::Take` to get owned value from a //! mutable reference. //! //! You will typically use code like //! //! ```ignore //! *e = return_value.take(); //! ``` //! //! where `e = &mut Expr` and `return_value` is also `&mut Expr`. `take()` is an //! extension method defined on `MapWithMut`. It's almost identical to `Fold`, //! so I'll skip memory management. //! //! You can invoke your `VisitMut` implementation like `node.visit_mut_with(&mut //! visitor)` where `visitor` is your visitor. Again, you need to call //! `node.visit_mut_children_with(self)` in visitor implementation if you want //! to modify children nodes. You don't need to store the return value in this //! case. //! //! //! # `Visit` //! //!`Visit` uses non-mutable references to AST nodes. It can be used to see if //! an AST node contains a specific node nested deeply in the AST. This is //! useful for checking if AST node contains `this`. This is useful for lots of //! cases - `this` in arrow expressions are special and we need to generate //! different code if a `this` expression is used. //! //! You can use your `Visit` implementation like `node.visit_with(&Invalid{ //! span: DUMMY_SP, }, &mut visitor`. I think API is mis-designed, but it works //! and there are really lots of code using `Visit` already. //! //! //! //! # Cargo features //! //! You should add //! ```toml //! [features] //! path = [] //! ``` //! //! If you want to allow using path-aware visitor. //! //! //! # Path-aware visitor //! //! Path-aware visitor is a visitor that can be used to visit AST nodes with //! current path from the entrypoint. //! //! `VisitMutAstPath` and `FoldAstPath` can be used to transform AST nodes with //! the path to the node. use std::ops::{Deref, DerefMut}; pub use either::Either; pub mod util; /// Visit all children nodes. This converts `VisitAll` to `Visit`. The type /// parameter `V` should implement `VisitAll` and `All<V>` implements `Visit`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct All<V> { pub visitor: V, } /// A visitor which visits node only if `enabled` is true. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Optional<V> { pub enabled: bool, pub visitor: V, } impl<V> Optional<V> { pub const fn new(visitor: V, enabled: bool) -> Self { Self { enabled, visitor } } } /// Trait for a pass which is designed to invoked multiple time to same input. /// /// See [Repeat]. pub trait Repeated { /// Should run again? fn changed(&self) -> bool; /// Reset. fn reset(&mut self); } macro_rules! impl_repeated_for_tuple { ( [$idx:tt, $name:ident], $([$idx_rest:tt, $name_rest:ident]),* ) => { impl<$name, $($name_rest),*> Repeated for ($name, $($name_rest),*) where $name: Repeated, $($name_rest: Repeated),* { fn changed(&self) -> bool { self.$idx.changed() || $(self.$idx_rest.changed() ||)* false } fn reset(&mut self) { self.$idx.reset(); $(self.$idx_rest.reset();)* } } }; } impl_repeated_for_tuple!([0, A], [1, B]); impl_repeated_for_tuple!([0, A], [1, B], [2, C]); impl_repeated_for_tuple!([0, A], [1, B], [2, C], [3, D]); impl_repeated_for_tuple!([0, A], [1, B], [2, C], [3, D], [4, E]); impl_repeated_for_tuple!([0, A], [1, B], [2, C], [3, D], [4, E], [5, F]); impl_repeated_for_tuple!([0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G]); impl_repeated_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H] ); impl_repeated_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I] ); impl_repeated_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J] ); impl_repeated_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J], [10, K] ); impl_repeated_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J], [10, K], [11, L] ); impl_repeated_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J], [10, K], [11, L], [12, M] ); /// A visitor which applies `V` again and again if `V` modifies the node. /// /// # Note /// `V` should return `true` from `changed()` to make the pass run multiple /// time. /// /// See: [Repeated] #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct Repeat<V> where V: Repeated, { pub pass: V, } impl<V> Repeat<V> where V: Repeated, { pub fn new(pass: V) -> Self { Self { pass } } } impl<V> Repeated for Repeat<V> where V: Repeated, { fn changed(&self) -> bool { self.pass.changed() } fn reset(&mut self) { self.pass.reset() } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct AstKindPath<K> where K: ParentKind, { path: Vec<K>, } impl<K> std::ops::Deref for AstKindPath<K> where K: ParentKind, { type Target = Vec<K>; fn deref(&self) -> &Self::Target { &self.path } } impl<K> Default for AstKindPath<K> where K: ParentKind, { fn default() -> Self { Self { path: Default::default(), } } } impl<K> AstKindPath<K> where K: ParentKind, { pub fn new(path: Vec<K>) -> Self { Self { path } } pub fn with_guard(&mut self, kind: K) -> AstKindPathGuard<K> { self.path.push(kind); AstKindPathGuard { path: self } } pub fn with_index_guard(&mut self, index: usize) -> AstKindPathIndexGuard<K> { self.path.last_mut().unwrap().set_index(index); AstKindPathIndexGuard { path: self } } #[deprecated = "Use with_guard instead"] pub fn with<Ret>(&mut self, path: K, op: impl FnOnce(&mut Self) -> Ret) -> Ret { self.path.push(path); let ret = op(self); self.path.pop(); ret } #[deprecated = "Use with_index_guard instead"] pub fn with_index<Ret>(&mut self, index: usize, op: impl FnOnce(&mut Self) -> Ret) -> Ret { self.path.last_mut().unwrap().set_index(index); let res = op(self); self.path.last_mut().unwrap().set_index(usize::MAX); res } } pub struct AstKindPathGuard<'a, K> where K: ParentKind, { path: &'a mut AstKindPath<K>, } impl<K> Deref for AstKindPathGuard<'_, K> where K: ParentKind, { type Target = AstKindPath<K>; #[inline] fn deref(&self) -> &Self::Target { self.path } } impl<K> DerefMut for AstKindPathGuard<'_, K> where K: ParentKind, { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.path } } impl<K> Drop for AstKindPathGuard<'_, K> where K: ParentKind, { fn drop(&mut self) { self.path.path.pop(); } } pub struct AstKindPathIndexGuard<'a, K> where K: ParentKind, { path: &'a mut AstKindPath<K>, } impl<K> Deref for AstKindPathIndexGuard<'_, K> where K: ParentKind, { type Target = AstKindPath<K>; #[inline] fn deref(&self) -> &Self::Target { self.path } } impl<K> DerefMut for AstKindPathIndexGuard<'_, K> where K: ParentKind, { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.path } } impl<K> Drop for AstKindPathIndexGuard<'_, K> where K: ParentKind, { fn drop(&mut self) { self.path.path.last_mut().unwrap().set_index(usize::MAX); } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct AstNodePath<N> where N: NodeRef, { kinds: AstKindPath<N::ParentKind>, path: Vec<N>, } impl<N> std::ops::Deref for AstNodePath<N> where N: NodeRef, { type Target = Vec<N>; fn deref(&self) -> &Self::Target { &self.path } } impl<N> Default for AstNodePath<N> where N: NodeRef, { fn default() -> Self { Self { kinds: Default::default(), path: Default::default(), } } } impl<N> AstNodePath<N> where N: NodeRef, { pub fn new(kinds: AstKindPath<N::ParentKind>, path: Vec<N>) -> Self { Self { kinds, path } } pub fn kinds(&self) -> &AstKindPath<N::ParentKind> { &self.kinds } pub fn with_guard(&mut self, node: N) -> AstNodePathGuard<N> { self.kinds.path.push(node.kind()); self.path.push(node); AstNodePathGuard { path: self } } pub fn with_index_guard(&mut self, index: usize) -> AstNodePathIndexGuard<N> { self.kinds.path.last_mut().unwrap().set_index(index); self.path.last_mut().unwrap().set_index(index); AstNodePathIndexGuard { path: self } } #[deprecated = "Use with_guard instead"] pub fn with<F, Ret>(&mut self, node: N, op: F) -> Ret where F: for<'aa> FnOnce(&'aa mut AstNodePath<N>) -> Ret, { let kind = node.kind(); self.kinds.path.push(kind); self.path.push(node); let ret = op(self); self.path.pop(); self.kinds.path.pop(); ret } #[deprecated = "Use with_index_guard instead"] pub fn with_index<F, Ret>(&mut self, index: usize, op: F) -> Ret where F: for<'aa> FnOnce(&'aa mut AstNodePath<N>) -> Ret, { self.kinds.path.last_mut().unwrap().set_index(index); self.path.last_mut().unwrap().set_index(index); let res = op(self); self.path.last_mut().unwrap().set_index(usize::MAX); self.kinds.path.last_mut().unwrap().set_index(usize::MAX); res } } pub trait NodeRef: Copy { type ParentKind: ParentKind; fn kind(&self) -> Self::ParentKind; fn set_index(&mut self, index: usize); } pub trait ParentKind: Copy { fn set_index(&mut self, index: usize); } pub struct AstNodePathGuard<'a, N> where N: NodeRef, { path: &'a mut AstNodePath<N>, } impl<N> Deref for AstNodePathGuard<'_, N> where N: NodeRef, { type Target = AstNodePath<N>; #[inline] fn deref(&self) -> &Self::Target { self.path } } impl<N> DerefMut for AstNodePathGuard<'_, N> where N: NodeRef, { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.path } } impl<N> Drop for AstNodePathGuard<'_, N> where N: NodeRef, { fn drop(&mut self) { self.path.path.pop(); self.path.kinds.path.pop(); } } pub struct AstNodePathIndexGuard<'a, N> where N: NodeRef, { path: &'a mut AstNodePath<N>, } impl<N> Deref for AstNodePathIndexGuard<'_, N> where N: NodeRef, { type Target = AstNodePath<N>; #[inline] fn deref(&self) -> &Self::Target { self.path } } impl<N> DerefMut for AstNodePathIndexGuard<'_, N> where N: NodeRef, { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.path } } impl<N> Drop for AstNodePathIndexGuard<'_, N> where N: NodeRef, { fn drop(&mut self) { self.path.path.last_mut().unwrap().set_index(usize::MAX); self.path .kinds .path .last_mut() .unwrap() .set_index(usize::MAX); } } /// NOT A PUBLIC API #[doc(hidden)] pub fn wrong_ast_path() { unsafe { debug_unreachable::debug_unreachable!("Wrong ast path"); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_visit/src/util/map.rs
Rust
use std::ptr; /// Copied from `syntax::ptr::P` of rustc. pub trait Map<T> { /// Transform the inner value, consuming `self` and producing a new `P<T>`. /// /// # Memory leak /// /// This will leak `self` if the given closure panics. fn map<F>(self, f: F) -> Self where F: FnOnce(T) -> T; } impl<T> Map<T> for Box<T> { fn map<F>(self, f: F) -> Self where F: FnOnce(T) -> T, { // Leak self in case of panic. // FIXME(eddyb) Use some sort of "free guard" that // only deallocates, without dropping the pointee, // in case the call the `f` below ends in a panic. let p = Box::into_raw(self); unsafe { ptr::write(p, f(ptr::read(p))); // Recreate self from the raw pointer. Box::from_raw(p) } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_visit/src/util/mod.rs
Rust
//! Some utilities for generated visitors. pub mod map; pub mod move_map;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_visit/src/util/move_map.rs
Rust
use std::{iter, ptr}; /// Modifiers vector in-place. pub trait MoveMap<T>: Sized { /// Map in place. fn move_map<F>(self, mut f: F) -> Self where F: FnMut(T) -> T, { self.move_flat_map(|e| iter::once(f(e))) } /// This will be very slow if you try to extend vector using this method. /// /// This method exists to drop useless nodes. You can return Option to do /// such shortening. fn move_flat_map<F, I>(self, f: F) -> Self where F: FnMut(T) -> I, I: IntoIterator<Item = T>; } impl<T> MoveMap<T> for Vec<T> { /// This reduces binary size. fn move_map<F>(mut self, mut f: F) -> Self where F: FnMut(T) -> T, { unsafe { let old_len = self.len(); self.set_len(0); // make sure we just leak elements in case of panic for index in 0..old_len { let item_ptr = self.as_mut_ptr().add(index); // move the item out of the vector and map it let item = ptr::read(item_ptr); let item = f(item); ptr::write(item_ptr, item); } // restore the original length self.set_len(old_len); } self } fn move_flat_map<F, I>(mut self, mut f: F) -> Self where F: FnMut(T) -> I, I: IntoIterator<Item = T>, { let mut read_i = 0; let mut write_i = 0; unsafe { let mut old_len = self.len(); self.set_len(0); // make sure we just leak elements in case of panic while read_i < old_len { // move the read_i'th item out of the vector and map it // to an iterator let e = ptr::read(self.as_ptr().add(read_i)); let iter = f(e).into_iter(); read_i += 1; for e in iter { if write_i < read_i { ptr::write(self.as_mut_ptr().add(write_i), e); write_i += 1; } else { // If this is reached we ran out of space // in the middle of the vector. // However, the vector is in a valid state here, // so we just do a somewhat inefficient insert. self.set_len(old_len); self.insert(write_i, e); old_len = self.len(); self.set_len(0); read_i += 1; write_i += 1; } } } // write_i tracks the number of actually written new items. self.set_len(write_i); } self } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml/src/lib.rs
Rust
pub extern crate swc_xml_ast as ast; pub extern crate swc_xml_codegen as codegen; pub extern crate swc_xml_parser as parser; pub extern crate swc_xml_visit as visit;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_ast/src/base.rs
Rust
use is_macro::Is; use string_enum::StringEnum; use swc_atoms::Atom; use swc_common::{ast_node, EqIgnoreSpan, Span}; #[ast_node("Document")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct Document { pub span: Span, pub children: Vec<Child>, } #[derive(StringEnum, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, EqIgnoreSpan)] pub enum DocumentMode { /// `no-quirks` NoQuirks, /// `limited-quirks` LimitedQuirks, /// `quirks` Quirks, } #[ast_node] #[derive(Eq, Hash, Is, EqIgnoreSpan)] pub enum Child { #[tag("DocumentType")] DocumentType(DocumentType), #[tag("Element")] Element(Element), #[tag("Text")] Text(Text), #[tag("CdataSection")] CdataSection(CdataSection), #[tag("Comment")] Comment(Comment), #[tag("ProcessingInstruction")] ProcessingInstruction(ProcessingInstruction), } #[ast_node("DocumentType")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct DocumentType { pub span: Span, pub name: Option<Atom>, pub public_id: Option<Atom>, pub system_id: Option<Atom>, pub raw: Option<Atom>, } #[derive(StringEnum, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, EqIgnoreSpan)] pub enum Namespace { /// `http://www.w3.org/1999/xhtml` HTML, /// `http://www.w3.org/1998/Math/MathML` MATHML, /// `http://www.w3.org/2000/svg` SVG, /// `http://www.w3.org/1999/xlink` XLINK, /// `http://www.w3.org/XML/1998/namespace` XML, /// `http://www.w3.org/2000/xmlns/` XMLNS, } #[ast_node("Element")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct Element { pub span: Span, pub tag_name: Atom, pub attributes: Vec<Attribute>, pub children: Vec<Child>, } #[ast_node("Attribute")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct Attribute { pub span: Span, pub namespace: Option<Namespace>, pub prefix: Option<Atom>, pub name: Atom, pub raw_name: Option<Atom>, pub value: Option<Atom>, pub raw_value: Option<Atom>, } #[ast_node("Text")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct Text { pub span: Span, pub data: Atom, pub raw: Option<Atom>, } #[ast_node("CdataSection")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct CdataSection { pub span: Span, pub data: Atom, pub raw: Option<Atom>, } #[ast_node("ProcessingInstruction")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct ProcessingInstruction { pub span: Span, pub target: Atom, pub data: Atom, } #[ast_node("Comment")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct Comment { pub span: Span, pub data: Atom, pub raw: Option<Atom>, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_ast/src/lib.rs
Rust
#![deny(clippy::all)] #![allow(clippy::large_enum_variant)] //! AST definitions for XML. pub use self::{base::*, token::*}; mod base; mod token;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_ast/src/token.rs
Rust
#[cfg(feature = "serde-impl")] use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::{ast_node, EqIgnoreSpan, Span}; #[ast_node("TokenAndSpan")] #[derive(Eq, Hash, EqIgnoreSpan)] pub struct TokenAndSpan { pub span: Span, pub token: Token, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EqIgnoreSpan)] #[cfg_attr(feature = "serde-impl", derive(Serialize, Deserialize))] pub struct AttributeToken { pub span: Span, pub name: Atom, pub raw_name: Option<Atom>, pub value: Option<Atom>, pub raw_value: Option<Atom>, } #[derive(Debug, Clone, PartialEq, Eq, Hash, EqIgnoreSpan)] #[cfg_attr(feature = "serde-impl", derive(Serialize, Deserialize))] pub enum Token { Doctype { // Name name: Option<Atom>, // Public identifier public_id: Option<Atom>, // System identifier system_id: Option<Atom>, // Raw value raw: Option<Atom>, }, StartTag { tag_name: Atom, attributes: Vec<AttributeToken>, }, EndTag { tag_name: Atom, attributes: Vec<AttributeToken>, }, EmptyTag { tag_name: Atom, attributes: Vec<AttributeToken>, }, Comment { data: Atom, raw: Atom, }, Character { value: char, raw: Option<Atom>, }, ProcessingInstruction { target: Atom, data: Atom, }, Cdata { data: Atom, raw: Atom, }, Eof, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/src/ctx.rs
Rust
use std::ops::{Deref, DerefMut}; use crate::{writer::XmlWriter, CodeGenerator}; impl<'b, W> CodeGenerator<'b, W> where W: XmlWriter, { /// Original context is restored when returned guard is dropped. #[inline] pub(super) fn with_ctx(&mut self, ctx: Ctx) -> WithCtx<'_, 'b, W> { let orig_ctx = self.ctx; self.ctx = ctx; WithCtx { orig_ctx, inner: self, } } } #[derive(Debug, Default, Clone, Copy)] pub(crate) struct Ctx { pub need_escape_text: bool, } pub(super) struct WithCtx<'w, 'a, I: 'w + XmlWriter> { inner: &'w mut CodeGenerator<'a, I>, orig_ctx: Ctx, } impl<'w, I: XmlWriter> Deref for WithCtx<'_, 'w, I> { type Target = CodeGenerator<'w, I>; fn deref(&self) -> &CodeGenerator<'w, I> { self.inner } } impl<'w, I: XmlWriter> DerefMut for WithCtx<'_, 'w, I> { fn deref_mut(&mut self) -> &mut CodeGenerator<'w, I> { self.inner } } impl<I: XmlWriter> Drop for WithCtx<'_, '_, I> { fn drop(&mut self) { self.inner.ctx = self.orig_ctx; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/src/emit.rs
Rust
use std::fmt::Result; use swc_common::Spanned; /// /// # Type parameters /// /// ## `T` /// /// The type of the ast node. pub trait Emit<T> where T: Spanned, { fn emit(&mut self, node: &T) -> Result; } impl<T, E> Emit<&'_ T> for E where E: Emit<T>, T: Spanned, { #[allow(clippy::only_used_in_recursion)] #[inline] fn emit(&mut self, node: &&'_ T) -> Result { self.emit(&**node) } } impl<T, E> Emit<Box<T>> for E where E: Emit<T>, T: Spanned, { #[inline] fn emit(&mut self, node: &Box<T>) -> Result { self.emit(&**node) } } impl<T, E> Emit<Option<T>> for E where E: Emit<T>, T: Spanned, { #[inline] fn emit(&mut self, node: &Option<T>) -> Result { match node { Some(node) => self.emit(node), None => Ok(()), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/src/lib.rs
Rust
#![deny(clippy::all)] #![allow(clippy::needless_update)] #![allow(non_local_definitions)] pub use std::fmt::Result; use std::{iter::Peekable, str::Chars}; use swc_common::Spanned; use swc_xml_ast::*; use swc_xml_codegen_macros::emitter; use writer::XmlWriter; pub use self::emit::*; use self::{ctx::Ctx, list::ListFormat}; #[macro_use] mod macros; mod ctx; mod emit; mod list; pub mod writer; #[derive(Debug, Clone, Default)] pub struct CodegenConfig<'a> { pub minify: bool, pub scripting_enabled: bool, /// Should be used only for `DocumentFragment` code generation pub context_element: Option<&'a Element>, } #[derive(Debug)] pub struct CodeGenerator<'a, W> where W: XmlWriter, { wr: W, config: CodegenConfig<'a>, ctx: Ctx, } impl<'a, W> CodeGenerator<'a, W> where W: XmlWriter, { pub fn new(wr: W, config: CodegenConfig<'a>) -> Self { CodeGenerator { wr, config, ctx: Default::default(), } } #[emitter] fn emit_document(&mut self, n: &Document) -> Result { self.emit_list(&n.children, ListFormat::NotDelimited)?; } #[emitter] fn emit_child(&mut self, n: &Child) -> Result { match n { Child::DocumentType(n) => emit!(self, n), Child::Element(n) => emit!(self, n), Child::Text(n) => emit!(self, n), Child::Comment(n) => emit!(self, n), Child::ProcessingInstruction(n) => emit!(self, n), Child::CdataSection(n) => emit!(self, n), } } #[emitter] fn emit_document_doctype(&mut self, n: &DocumentType) -> Result { let mut doctype = String::with_capacity( 10 + if let Some(name) = &n.name { name.len() + 1 } else { 0 } + if let Some(public_id) = &n.public_id { let mut len = public_id.len() + 10; if let Some(system_id) = &n.system_id { len += system_id.len() + 3 } len } else if let Some(system_id) = &n.system_id { system_id.len() + 10 } else { 0 }, ); doctype.push('<'); doctype.push('!'); if self.config.minify { doctype.push_str("doctype"); } else { doctype.push_str("DOCTYPE"); } if let Some(name) = &n.name { doctype.push(' '); doctype.push_str(name); } if let Some(public_id) = &n.public_id { doctype.push(' '); if self.config.minify { doctype.push_str("public"); } else { doctype.push_str("PUBLIC"); } doctype.push(' '); let public_id_quote = if public_id.contains('"') { '\'' } else { '"' }; doctype.push(public_id_quote); doctype.push_str(public_id); doctype.push(public_id_quote); if let Some(system_id) = &n.system_id { doctype.push(' '); let system_id_quote = if system_id.contains('"') { '\'' } else { '"' }; doctype.push(system_id_quote); doctype.push_str(system_id); doctype.push(system_id_quote); } } else if let Some(system_id) = &n.system_id { doctype.push(' '); if self.config.minify { doctype.push_str("system"); } else { doctype.push_str("SYSTEM"); } doctype.push(' '); let system_id_quote = if system_id.contains('"') { '\'' } else { '"' }; doctype.push(system_id_quote); doctype.push_str(system_id); doctype.push(system_id_quote); } doctype.push('>'); write_raw!(self, n.span, &doctype); formatting_newline!(self); } fn basic_emit_element(&mut self, n: &Element) -> Result { let has_attributes = !n.attributes.is_empty(); let is_void_element = n.children.is_empty(); write_raw!(self, "<"); write_raw!(self, &n.tag_name); if has_attributes { space!(self); self.emit_list(&n.attributes, ListFormat::SpaceDelimited)?; } if is_void_element { if !self.config.minify { write_raw!(self, " "); } write_raw!(self, "/"); } write_raw!(self, ">"); if is_void_element { return Ok(()); } if !n.children.is_empty() { let ctx = self.create_context_for_element(n); self.with_ctx(ctx) .emit_list(&n.children, ListFormat::NotDelimited)?; } write_raw!(self, "<"); write_raw!(self, "/"); write_raw!(self, &n.tag_name); write_raw!(self, ">"); Ok(()) } #[emitter] fn emit_element(&mut self, n: &Element) -> Result { self.basic_emit_element(n)?; } #[emitter] fn emit_attribute(&mut self, n: &Attribute) -> Result { let mut attribute = String::with_capacity( if let Some(prefix) = &n.prefix { prefix.len() + 1 } else { 0 } + n.name.len() + if let Some(value) = &n.value { value.len() + 1 } else { 0 }, ); if let Some(prefix) = &n.prefix { attribute.push_str(prefix); attribute.push(':'); } attribute.push_str(&n.name); if let Some(value) = &n.value { attribute.push('='); let normalized = normalize_attribute_value(value); attribute.push_str(&normalized); } write_multiline_raw!(self, n.span, &attribute); } #[emitter] fn emit_text(&mut self, n: &Text) -> Result { if self.ctx.need_escape_text { let mut data = String::with_capacity(n.data.len()); if self.config.minify { data.push_str(&minify_text(&n.data)); } else { data.push_str(&escape_string(&n.data, false)); } write_multiline_raw!(self, n.span, &data); } else { write_multiline_raw!(self, n.span, &n.data); } } #[emitter] fn emit_comment(&mut self, n: &Comment) -> Result { let mut comment = String::with_capacity(n.data.len() + 7); comment.push_str("<!--"); comment.push_str(&n.data); comment.push_str("-->"); write_multiline_raw!(self, n.span, &comment); } #[emitter] fn emit_processing_instruction(&mut self, n: &ProcessingInstruction) -> Result { let mut processing_instruction = String::with_capacity(n.target.len() + n.data.len() + 5); processing_instruction.push_str("<?"); processing_instruction.push_str(&n.target); processing_instruction.push(' '); processing_instruction.push_str(&n.data); processing_instruction.push_str("?>"); write_multiline_raw!(self, n.span, &processing_instruction); } #[emitter] fn emit_cdata_section(&mut self, n: &CdataSection) -> Result { let mut cdata_section = String::with_capacity(n.data.len() + 12); cdata_section.push_str("<![CDATA["); cdata_section.push_str(&n.data); cdata_section.push_str("]]>"); write_multiline_raw!(self, n.span, &cdata_section); } fn create_context_for_element(&self, n: &Element) -> Ctx { let need_escape_text = match &*n.tag_name { "noscript" => !self.config.scripting_enabled, _ => true, }; Ctx { need_escape_text, ..self.ctx } } fn emit_list<N>(&mut self, nodes: &[N], format: ListFormat) -> Result where Self: Emit<N>, N: Spanned, { for (idx, node) in nodes.iter().enumerate() { if idx != 0 { self.write_delim(format)?; if format & ListFormat::LinesMask == ListFormat::MultiLine { formatting_newline!(self); } } emit!(self, node) } Ok(()) } fn write_delim(&mut self, f: ListFormat) -> Result { match f & ListFormat::DelimitersMask { ListFormat::None => {} ListFormat::SpaceDelimited => { space!(self) } _ => unreachable!(), } Ok(()) } } fn normalize_attribute_value(value: &str) -> String { if value.is_empty() { return "\"\"".to_string(); } let mut normalized = String::with_capacity(value.len() + 2); normalized.push('"'); normalized.push_str(&escape_string(value, true)); normalized.push('"'); normalized } #[allow(clippy::unused_peekable)] fn minify_text(value: &str) -> String { let mut result = String::with_capacity(value.len()); let mut chars = value.chars().peekable(); while let Some(c) = chars.next() { match c { '&' => { result.push_str(&minify_amp(&mut chars)); } '<' => { result.push_str("&lt;"); } '>' => { result.push_str("&gt;"); } _ => result.push(c), } } result } fn minify_amp(chars: &mut Peekable<Chars>) -> String { let mut result = String::with_capacity(7); match chars.next() { Some(hash @ '#') => { match chars.next() { // HTML CODE // Prevent `&amp;#38;` -> `&#38` Some(number @ '0'..='9') => { result.push_str("&amp;"); result.push(hash); result.push(number); } Some(x @ 'x' | x @ 'X') => { match chars.peek() { // HEX CODE // Prevent `&amp;#x38;` -> `&#x38` Some(c) if c.is_ascii_hexdigit() => { result.push_str("&amp;"); result.push(hash); result.push(x); } _ => { result.push('&'); result.push(hash); result.push(x); } } } any => { result.push('&'); result.push(hash); if let Some(any) = any { result.push(any); } } } } // Named entity // Prevent `&amp;current` -> `&current` Some(c @ 'a'..='z') | Some(c @ 'A'..='Z') => { let mut entity_temporary_buffer = String::with_capacity(33); entity_temporary_buffer.push('&'); entity_temporary_buffer.push(c); result.push('&'); result.push_str(&entity_temporary_buffer[1..]); } any => { result.push('&'); if let Some(any) = any { result.push(any); } } } result } // Escaping a string (for the purposes of the algorithm above) consists of // running the following steps: // // 1. Replace any occurrence of the "&" character by the string "&amp;". // // 2. Replace any occurrences of the U+00A0 NO-BREAK SPACE character by the // string "&nbsp;". // // 3. If the algorithm was invoked in the attribute mode, replace any // occurrences of the """ character by the string "&quot;". // // 4. If the algorithm was not invoked in the attribute mode, replace any // occurrences of the "<" character by the string "&lt;", and any occurrences of // the ">" character by the string "&gt;". fn escape_string(value: &str, is_attribute_mode: bool) -> String { let mut result = String::with_capacity(value.len()); for c in value.chars() { match c { '&' => { result.push_str("&amp;"); } '"' if is_attribute_mode => result.push_str("&quot;"), '<' => { result.push_str("&lt;"); } '>' if !is_attribute_mode => { result.push_str("&gt;"); } _ => result.push(c), } } result }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/src/list.rs
Rust
#![allow(non_upper_case_globals)] use bitflags::bitflags; bitflags! { #[derive(PartialEq, Eq, Clone, Copy)] pub struct ListFormat: u16 { const None = 0; // Line separators /// Prints the list on a single line (default). const SingleLine = 0; /// Prints the list on multiple lines. const MultiLine = 1 << 0; /// Prints the list using line preservation if possible. const PreserveLines = 1 << 1; const LinesMask = Self::MultiLine.bits() | Self::PreserveLines.bits(); // Delimiters const NotDelimited = 0; const SpaceDelimited = 1 << 2; const DelimitersMask = Self::SpaceDelimited.bits(); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/src/macros.rs
Rust
macro_rules! emit { ($g:expr,$n:expr) => {{ use crate::Emit; $g.emit(&$n)?; }}; } macro_rules! write_raw { ($g:expr,$span:expr,$n:expr) => {{ $g.wr.write_raw(Some($span), $n)?; }}; ($g:expr,$n:expr) => {{ $g.wr.write_raw(None, $n)?; }}; } macro_rules! write_multiline_raw { ($g:expr,$span:expr,$n:expr) => {{ $g.wr.write_multiline_raw($span, $n)?; }}; } // macro_rules! newline { // ($g:expr) => {{ // $g.wr.write_newline()?; // }}; // } macro_rules! formatting_newline { ($g:expr) => {{ if !$g.config.minify { $g.wr.write_newline()?; } }}; } macro_rules! space { ($g:expr) => {{ $g.wr.write_space()?; }}; } // macro_rules! increase_indent { // ($g:expr) => {{ // if !$g.config.minify { // $g.wr.increase_indent(); // } // }}; // } // // macro_rules! decrease_indent { // ($g:expr) => {{ // if !$g.config.minify { // $g.wr.decrease_indent(); // } // }}; // }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/src/writer/basic.rs
Rust
use std::fmt::{Result, Write}; use rustc_hash::FxHashSet; use swc_common::{BytePos, LineCol, Span}; use super::XmlWriter; #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub enum IndentType { Tab, #[default] Space, } #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub enum LineFeed { #[default] LF, CRLF, } pub struct BasicXmlWriterConfig { pub indent_type: IndentType, pub indent_width: i32, pub linefeed: LineFeed, } impl Default for BasicXmlWriterConfig { fn default() -> Self { BasicXmlWriterConfig { indent_type: IndentType::default(), indent_width: 2, linefeed: LineFeed::default(), } } } pub struct BasicXmlWriter<'a, W> where W: Write, { line_start: bool, line: usize, col: usize, indent_type: &'a str, indent_level: usize, linefeed: &'a str, srcmap: Option<&'a mut Vec<(BytePos, LineCol)>>, srcmap_done: FxHashSet<(BytePos, u32, u32)>, /// Used to avoid including whitespaces created by indention. pending_srcmap: Option<BytePos>, config: BasicXmlWriterConfig, w: W, } impl<'a, W> BasicXmlWriter<'a, W> where W: Write, { pub fn new( writer: W, srcmap: Option<&'a mut Vec<(BytePos, LineCol)>>, config: BasicXmlWriterConfig, ) -> Self { let indent_type = match config.indent_type { IndentType::Tab => "\t", IndentType::Space => " ", }; let linefeed = match config.linefeed { LineFeed::LF => "\n", LineFeed::CRLF => "\r\n", }; BasicXmlWriter { line_start: true, line: 0, col: 0, indent_type, indent_level: 0, linefeed, config, srcmap, w: writer, pending_srcmap: Default::default(), srcmap_done: Default::default(), } } fn write_indent_string(&mut self) -> Result { for _ in 0..(self.config.indent_width * self.indent_level as i32) { self.raw_write(self.indent_type)?; } Ok(()) } fn raw_write(&mut self, data: &str) -> Result { self.w.write_str(data)?; self.col += data.chars().count(); Ok(()) } fn write(&mut self, span: Option<Span>, data: &str) -> Result { if !data.is_empty() { if self.line_start { self.write_indent_string()?; self.line_start = false; if let Some(pending) = self.pending_srcmap.take() { self.srcmap(pending); } } if let Some(span) = span { if !span.is_dummy() { self.srcmap(span.lo()) } } self.raw_write(data)?; if let Some(span) = span { if !span.is_dummy() { self.srcmap(span.hi()) } } } Ok(()) } fn srcmap(&mut self, byte_pos: BytePos) { if byte_pos.is_dummy() { return; } if let Some(ref mut srcmap) = self.srcmap { if self .srcmap_done .insert((byte_pos, self.line as _, self.col as _)) { let loc = LineCol { line: self.line as _, col: self.col as _, }; srcmap.push((byte_pos, loc)); } } } } impl<W> XmlWriter for BasicXmlWriter<'_, W> where W: Write, { fn write_space(&mut self) -> Result { self.write_raw(None, " ") } fn write_newline(&mut self) -> Result { let pending = self.pending_srcmap.take(); if !self.line_start { self.raw_write(self.linefeed)?; self.line += 1; self.col = 0; self.line_start = true; if let Some(pending) = pending { self.srcmap(pending) } } Ok(()) } fn write_raw(&mut self, span: Option<Span>, text: &str) -> Result { debug_assert!( !text.contains('\n'), "write_raw should not contains new lines, got '{}'", text, ); self.write(span, text)?; Ok(()) } fn write_multiline_raw(&mut self, span: Span, s: &str) -> Result { if !s.is_empty() { if !span.is_dummy() { self.srcmap(span.lo()) } self.write(None, s)?; let line_start_of_s = compute_line_starts(s); if line_start_of_s.len() > 1 { self.line = self.line + line_start_of_s.len() - 1; let last_line_byte_index = line_start_of_s.last().cloned().unwrap_or(0); self.col = s[last_line_byte_index..].chars().count(); } if !span.is_dummy() { self.srcmap(span.hi()) } } Ok(()) } fn increase_indent(&mut self) { self.indent_level += 1; } fn decrease_indent(&mut self) { debug_assert!( (self.indent_level as i32) >= 0, "indent should zero or greater than zero", ); self.indent_level -= 1; } } fn compute_line_starts(s: &str) -> Vec<usize> { let mut res = Vec::new(); let mut line_start = 0; let mut chars = s.char_indices().peekable(); while let Some((pos, c)) = chars.next() { match c { '\r' => { if let Some(&(_, '\n')) = chars.peek() { let _ = chars.next(); } } '\n' => { res.push(line_start); line_start = pos + 1; } _ => {} } } // Last line. res.push(line_start); res }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/src/writer/mod.rs
Rust
use std::fmt::Result; use auto_impl::auto_impl; use swc_common::Span; pub mod basic; #[auto_impl(&mut, Box)] pub trait XmlWriter { fn write_space(&mut self) -> Result; fn write_newline(&mut self) -> Result; fn write_raw(&mut self, span: Option<Span>, text: &str) -> Result; fn write_multiline_raw(&mut self, span: Span, s: &str) -> Result; fn increase_indent(&mut self); fn decrease_indent(&mut self); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen/tests/fixture.rs
Rust
#![allow(clippy::needless_update)] use std::{ mem::take, path::{Path, PathBuf}, }; use swc_common::{FileName, Span}; use swc_xml_ast::*; use swc_xml_codegen::{ writer::basic::{BasicXmlWriter, BasicXmlWriterConfig, IndentType, LineFeed}, CodeGenerator, CodegenConfig, Emit, }; use swc_xml_parser::{parse_file_as_document, parser::ParserConfig}; use swc_xml_visit::{VisitMut, VisitMutWith}; use testing::{assert_eq, run_test2, NormalizedOutput}; fn print_document( input: &Path, parser_config: Option<ParserConfig>, writer_config: Option<BasicXmlWriterConfig>, codegen_config: Option<CodegenConfig>, ) { let dir = input.parent().unwrap(); let parser_config = parser_config.unwrap_or_default(); let writer_config = writer_config.unwrap_or_default(); let codegen_config = codegen_config.unwrap_or_default(); let output = if codegen_config.minify { dir.join(format!( "output.min.{}", input.extension().unwrap().to_string_lossy() )) } else { dir.join(format!( "output.{}", input.extension().unwrap().to_string_lossy() )) }; run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); let mut errors = Vec::new(); let mut document: Document = parse_file_as_document(&fm, parser_config, &mut errors).unwrap(); for err in take(&mut errors) { err.to_diagnostics(&handler).emit(); } let mut xml_str = String::new(); let wr = BasicXmlWriter::new(&mut xml_str, None, writer_config); let mut gen = CodeGenerator::new(wr, codegen_config); gen.emit(&document).unwrap(); let fm_output = cm.load_file(&output).unwrap(); NormalizedOutput::new_raw(xml_str) .compare_to_file(output) .unwrap(); let mut errors = Vec::new(); let mut document_parsed_again = parse_file_as_document(&fm_output, parser_config, &mut errors).map_err(|err| { err.to_diagnostics(&handler).emit(); })?; for error in take(&mut errors) { error.to_diagnostics(&handler).emit(); } document.visit_mut_with(&mut DropSpan); document_parsed_again.visit_mut_with(&mut DropSpan); assert_eq!(document, document_parsed_again); Ok(()) }) .unwrap(); } fn verify_document( input: &Path, parser_config: Option<ParserConfig>, writer_config: Option<BasicXmlWriterConfig>, codegen_config: Option<CodegenConfig>, ignore_errors: bool, ) { let parser_config = parser_config.unwrap_or_default(); let writer_config = writer_config.unwrap_or_default(); let codegen_config = codegen_config.unwrap_or_default(); testing::run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); let mut errors = Vec::new(); let mut document = parse_file_as_document(&fm, parser_config, &mut errors).map_err(|err| { err.to_diagnostics(&handler).emit(); })?; if !ignore_errors { for err in take(&mut errors) { err.to_diagnostics(&handler).emit(); } } let mut xml_str = String::new(); let wr = BasicXmlWriter::new(&mut xml_str, None, writer_config); let mut gen = CodeGenerator::new(wr, codegen_config); gen.emit(&document).unwrap(); let new_fm = cm.new_source_file(FileName::Anon.into(), xml_str); let mut parsed_errors = Vec::new(); let mut document_parsed_again = parse_file_as_document(&new_fm, parser_config, &mut parsed_errors).map_err(|err| { err.to_diagnostics(&handler).emit(); })?; if !ignore_errors { for err in parsed_errors { err.to_diagnostics(&handler).emit(); } } document.visit_mut_with(&mut DropSpan); document_parsed_again.visit_mut_with(&mut DropSpan); assert_eq!(document, document_parsed_again); Ok(()) }) .unwrap(); } struct DropSpan; impl VisitMut for DropSpan { fn visit_mut_document_type(&mut self, n: &mut DocumentType) { n.visit_mut_children_with(self); n.raw = None; } fn visit_mut_comment(&mut self, n: &mut Comment) { n.visit_mut_children_with(self); n.raw = None; } fn visit_mut_text(&mut self, n: &mut Text) { n.visit_mut_children_with(self); n.raw = None; } fn visit_mut_attribute(&mut self, n: &mut Attribute) { n.visit_mut_children_with(self); n.raw_name = None; n.raw_value = None; } fn visit_mut_span(&mut self, n: &mut Span) { *n = Default::default() } } #[testing::fixture("tests/fixture/**/input.xml")] fn test_document(input: PathBuf) { print_document( &input, None, None, Some(CodegenConfig { scripting_enabled: false, minify: false, ..Default::default() }), ); print_document( &input, None, None, Some(CodegenConfig { scripting_enabled: false, minify: true, ..Default::default() }), ); } #[testing::fixture("tests/options/indent_type/**/input.xml")] fn test_indent_type_option(input: PathBuf) { print_document( &input, None, Some(BasicXmlWriterConfig { indent_type: IndentType::Tab, indent_width: 2, linefeed: LineFeed::default(), }), None, ); } #[testing::fixture("../swc_xml_parser/tests/fixture/**/*.xml")] fn parser_verify(input: PathBuf) { verify_document(&input, None, None, None, false); verify_document( &input, None, None, Some(CodegenConfig { scripting_enabled: false, minify: true, ..Default::default() }), false, ); verify_document( &input, None, None, Some(CodegenConfig { scripting_enabled: false, minify: true, ..Default::default() }), false, ); } #[testing::fixture("../swc_xml_parser/tests/recovery/**/*.xml")] fn parser_recovery_verify(input: PathBuf) { verify_document( &input, None, None, Some(CodegenConfig { scripting_enabled: false, minify: true, ..Default::default() }), true, ); verify_document( &input, None, None, Some(CodegenConfig { scripting_enabled: false, minify: true, ..Default::default() }), true, ); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_codegen_macros/src/lib.rs
Rust
#![deny(clippy::all)] extern crate proc_macro; use quote::ToTokens; use syn::{parse_quote, FnArg, ImplItemFn, Type, TypeReference}; #[proc_macro_attribute] pub fn emitter( _attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let item: ImplItemFn = syn::parse(item).expect("failed to parse input as an item"); let item = expand(item); item.into_token_stream().into() } fn expand(i: ImplItemFn) -> ImplItemFn { let mtd_name = i.sig.ident.clone(); assert!( format!("{}", i.sig.ident).starts_with("emit_"), "#[emitter] methods should start with `emit_`" ); let block = { let node_type = { i.sig .inputs .clone() .into_iter() .nth(1) .and_then(|arg| match arg { FnArg::Typed(ty) => Some(ty.ty), _ => None, }) .map(|ty| { // &Ident -> Ident match *ty { Type::Reference(TypeReference { elem, .. }) => *elem, _ => panic!( "Type of node parameter should be reference but got {}", ty.into_token_stream() ), } }) .expect( "#[emitter] methods should have signature of fn (&mut self, node: Node) -> Result; ", ) }; let block = &i.block; parse_quote!({ impl<W> crate::Emit<#node_type> for crate::CodeGenerator<'_, W> where W: crate::writer::XmlWriter, { fn emit(&mut self, n: &#node_type) -> crate::Result { self.#mtd_name(n) } } #block // Emitter methods return Result<_, _> // We inject this to avoid writing Ok(()) every time. #[allow(unreachable_code)] { return Ok(()); } }) }; ImplItemFn { block, ..i } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/error.rs
Rust
use std::borrow::Cow; use swc_common::{ errors::{DiagnosticBuilder, Handler}, Span, }; /// Size is same as a size of a pointer. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Error { inner: Box<(Span, ErrorKind)>, } impl Error { pub fn kind(&self) -> &ErrorKind { &self.inner.1 } pub fn into_inner(self) -> Box<(Span, ErrorKind)> { self.inner } pub fn new(span: Span, kind: ErrorKind) -> Self { Error { inner: Box::new((span, kind)), } } pub fn message(&self) -> Cow<'static, str> { match &self.inner.1 { ErrorKind::Eof => "Unexpected end of file".into(), // Lexer errors ErrorKind::AbruptClosingOfEmptyComment => "Abrupt closing of empty comment".into(), ErrorKind::AbruptDoctypePublicIdentifier => "Abrupt doctype public identifier".into(), ErrorKind::AbruptDoctypeSystemIdentifier => "Abrupt doctype system identifier".into(), ErrorKind::ControlCharacterInInputStream => "Control character in input stream".into(), ErrorKind::EndTagWithAttributes => "End tag with attributes".into(), ErrorKind::ShortTagWithAttributes => "Short tag with attributes".into(), ErrorKind::DuplicateAttribute => "Duplicate attribute".into(), ErrorKind::EndTagWithTrailingSolidus => "End tag with trailing solidus".into(), ErrorKind::EofBeforeTagName => "Eof before tag name".into(), ErrorKind::EofInCdata => "Eof in cdata".into(), ErrorKind::EofInComment => "Eof in comment".into(), ErrorKind::EofInDoctype => "Eof in doctype".into(), ErrorKind::EofInTag => "Eof in tag".into(), ErrorKind::EofInProcessingInstruction => "Eof in processing instruction".into(), ErrorKind::IncorrectlyClosedComment => "Incorrectly closed comment".into(), ErrorKind::IncorrectlyOpenedComment => "Incorrectly opened comment".into(), ErrorKind::InvalidCharacterSequenceAfterDoctypeName => { "Invalid character sequence after doctype name".into() } ErrorKind::InvalidFirstCharacterOfTagName => { "Invalid first character of tag name".into() } ErrorKind::InvalidCharacterOfProcessingInstruction => { "Invalid character of processing instruction".into() } ErrorKind::InvalidCharacterInTag => "Invalid character in tag".into(), ErrorKind::InvalidEntityCharacter => "Invalid entity character".into(), ErrorKind::MissingDoctypeName => "Missing doctype name".into(), ErrorKind::MissingDoctypePublicIdentifier => "Missing doctype public identifier".into(), ErrorKind::MissingQuoteBeforeDoctypePublicIdentifier => { "Missing quote before doctype public identifier".into() } ErrorKind::MissingQuoteBeforeDoctypeSystemIdentifier => { "Missing quote before doctype system identifier".into() } ErrorKind::MissingSemicolonAfterCharacterReference => { "Missing semicolon after character reference".into() } ErrorKind::MissingWhitespaceAfterDoctypePublicKeyword => { "Missing whitespace after doctype public keyword".into() } ErrorKind::MissingWhitespaceAfterDoctypeSystemKeyword => { "Missing whitespace after doctype system keyword".into() } ErrorKind::MissingWhitespaceBeforeDoctypeName => { "Missing whitespace before doctype name".into() } ErrorKind::MissingWhitespaceBetweenDoctypePublicAndSystemIdentifiers => { "Missing whitespace between doctype public and system identifiers".into() } ErrorKind::MissingEndTagName => "Missing end tag name".into(), ErrorKind::MissingQuoteBeforeAttributeValue => { "Missing quote before attribute value".into() } ErrorKind::MissingEqualAfterAttributeName => { "Missing equal after attribute name".into() } ErrorKind::MissingSpaceBetweenAttributes => "Missing space between attributes".into(), ErrorKind::NestedComment => "Nested comment".into(), ErrorKind::DoubleHyphenWithInComment => "Double hyper within comment".into(), ErrorKind::NoncharacterInInputStream => "Noncharacter in input stream".into(), ErrorKind::SurrogateInInputStream => "Surrogate in input stream".into(), ErrorKind::SurrogateCharacterReference => "Surrogate character reference".into(), ErrorKind::UnexpectedCharacterAfterDoctypeSystemIdentifier => { "Unexpected character after doctype system identifier".into() } ErrorKind::UnexpectedColonBeforeAttributeName => { "Unexpected colon before attribute name".into() } ErrorKind::UnexpectedSolidusInTag => "Unexpected solidus in tag".into(), ErrorKind::NoTargetNameInProcessingInstruction => "No target name".into(), ErrorKind::MissingWhitespaceBeforeQuestionInProcessingInstruction => { "Missing whitespace before '?'".into() } ErrorKind::UnescapedCharacterInAttributeValue(c) => { format!("Unescaped \"{}\" not allowed in attribute values", c).into() } // Parser errors ErrorKind::UnexpectedTokenInStartPhase => "Unexpected token in start phase".into(), ErrorKind::UnexpectedTokenInMainPhase => "Unexpected token in main phase".into(), ErrorKind::UnexpectedTokenInEndPhase => "Unexpected token in end phase".into(), ErrorKind::UnexpectedEofInStartPhase => "Unexpected end of file in start phase".into(), ErrorKind::UnexpectedEofInMainPhase => "Unexpected end of file in main phase".into(), ErrorKind::OpeningAndEndingTagMismatch => "Opening and ending tag mismatch".into(), ErrorKind::UnexpectedCharacter => { "Unexpected character, only whitespace character allowed".into() } } } pub fn to_diagnostics<'a>(&self, handler: &'a Handler) -> DiagnosticBuilder<'a> { handler.struct_span_err(self.inner.0, &self.message()) } } #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum ErrorKind { Eof, // Lexer errors AbruptClosingOfEmptyComment, AbruptDoctypePublicIdentifier, AbruptDoctypeSystemIdentifier, ControlCharacterInInputStream, EndTagWithAttributes, ShortTagWithAttributes, DuplicateAttribute, EndTagWithTrailingSolidus, EofBeforeTagName, EofInCdata, EofInComment, EofInDoctype, EofInTag, EofInProcessingInstruction, IncorrectlyClosedComment, IncorrectlyOpenedComment, InvalidCharacterSequenceAfterDoctypeName, InvalidFirstCharacterOfTagName, InvalidCharacterOfProcessingInstruction, InvalidCharacterInTag, InvalidEntityCharacter, MissingDoctypeName, MissingDoctypePublicIdentifier, MissingQuoteBeforeDoctypePublicIdentifier, MissingQuoteBeforeDoctypeSystemIdentifier, MissingSemicolonAfterCharacterReference, MissingWhitespaceAfterDoctypePublicKeyword, MissingWhitespaceAfterDoctypeSystemKeyword, MissingWhitespaceBeforeDoctypeName, MissingWhitespaceBetweenDoctypePublicAndSystemIdentifiers, MissingEndTagName, MissingQuoteBeforeAttributeValue, MissingEqualAfterAttributeName, MissingSpaceBetweenAttributes, NestedComment, DoubleHyphenWithInComment, NoncharacterInInputStream, SurrogateInInputStream, SurrogateCharacterReference, UnexpectedCharacterAfterDoctypeSystemIdentifier, UnexpectedColonBeforeAttributeName, UnexpectedSolidusInTag, NoTargetNameInProcessingInstruction, MissingWhitespaceBeforeQuestionInProcessingInstruction, UnescapedCharacterInAttributeValue(char), // Parser errors UnexpectedTokenInStartPhase, UnexpectedTokenInMainPhase, UnexpectedTokenInEndPhase, UnexpectedEofInStartPhase, UnexpectedEofInMainPhase, OpeningAndEndingTagMismatch, UnexpectedCharacter, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/lexer/mod.rs
Rust
use std::{collections::VecDeque, mem::take}; use rustc_hash::FxHashSet; use swc_atoms::Atom; use swc_common::{input::Input, BytePos, Span}; use swc_xml_ast::{AttributeToken, Token, TokenAndSpan}; use crate::{ error::{Error, ErrorKind}, parser::input::ParserInput, }; #[derive(Debug, Clone)] pub enum State { Data, CharacterReferenceInData, Pi, PiTarget, PiTargetQuestion, PiTargetAfter, PiData, PiEnd, MarkupDeclaration, CommentStart, CommentStartDash, Comment, CommentLessThanSign, CommentLessThanSignBang, CommentLessThanSignBangDash, CommentLessThanSignBangDashDash, CommentEndDash, CommentEnd, CommentEndBang, Cdata, CdataBracket, CdataEnd, TagOpen, EndTagOpen, TagName, EmptyTag, TagAttributeNameBefore, TagAttributeName, TagAttributeNameAfter, TagAttributeValueBefore, TagAttributeValueDoubleQuoted, TagAttributeValueSingleQuoted, TagAttributeValueUnquoted, TagAttributeValueAfter, CharacterReferenceInAttributeValue, BogusComment, Doctype, BeforeDoctypeName, DoctypeName, AfterDoctypeName, AfterDoctypePublicKeyword, AfterDoctypeSystemKeyword, BeforeDoctypeSystemIdentifier, BeforeDoctypePublicIdentifier, DoctypePublicIdentifierSingleQuoted, DoctypePublicIdentifierDoubleQuoted, AfterDoctypePublicIdentifier, BetweenDoctypePublicAndSystemIdentifiers, DoctypeSystemIdentifierSingleQuoted, DoctypeSystemIdentifierDoubleQuoted, AfterDoctypeSystemIdentifier, DoctypeTypeInternalSubSet, BogusDoctype, } // TODO implement `raw` for all tokens #[derive(PartialEq, Eq, Clone, Debug)] struct Doctype { name: Option<String>, public_id: Option<String>, system_id: Option<String>, } #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] enum TagKind { Start, End, Empty, } #[derive(PartialEq, Eq, Clone, Debug)] struct Tag { kind: TagKind, tag_name: String, attributes: Vec<Attribute>, } #[derive(PartialEq, Eq, Clone, Debug)] struct Attribute { span: Span, name: String, raw_name: Option<String>, value: Option<String>, raw_value: Option<String>, } #[derive(PartialEq, Eq, Clone, Debug)] struct Comment { data: String, raw: String, } #[derive(PartialEq, Eq, Clone, Debug)] struct ProcessingInstruction { target: String, data: String, } #[derive(PartialEq, Eq, Clone, Debug)] struct Cdata { data: String, raw: String, } pub(crate) type LexResult<T> = Result<T, ErrorKind>; pub struct Lexer<I> where I: Input, { input: I, cur: Option<char>, cur_pos: BytePos, last_token_pos: BytePos, finished: bool, state: State, return_state: Option<State>, errors: Vec<Error>, additional_allowed_character: Option<char>, pending_tokens: VecDeque<TokenAndSpan>, doctype_raw: Option<String>, current_doctype_token: Option<Doctype>, current_comment_token: Option<Comment>, current_processing_instruction: Option<ProcessingInstruction>, current_tag_token: Option<Tag>, current_cdata_token: Option<Cdata>, attribute_start_position: Option<BytePos>, } impl<I> Lexer<I> where I: Input, { pub fn new(input: I) -> Self { let start_pos = input.last_pos(); let mut lexer = Lexer { input, cur: None, cur_pos: start_pos, last_token_pos: start_pos, finished: false, state: State::Data, return_state: None, errors: Vec::new(), additional_allowed_character: None, pending_tokens: VecDeque::new(), doctype_raw: None, current_doctype_token: None, current_comment_token: None, current_processing_instruction: None, current_tag_token: None, current_cdata_token: None, attribute_start_position: None, }; // A leading Byte Order Mark (BOM) causes the character encoding argument to be // ignored and will itself be skipped. if lexer.input.is_at_start() && lexer.input.cur() == Some('\u{feff}') { unsafe { // Safety: cur() is Some('\u{feff}') lexer.input.bump(); } } lexer } } impl<I: Input> Iterator for Lexer<I> { type Item = TokenAndSpan; fn next(&mut self) -> Option<Self::Item> { let token_and_span = self.read_token_and_span(); match token_and_span { Ok(token_and_span) => { return Some(token_and_span); } Err(..) => { return None; } } } } impl<I> ParserInput for Lexer<I> where I: Input, { fn start_pos(&mut self) -> swc_common::BytePos { self.input.cur_pos() } fn last_pos(&mut self) -> swc_common::BytePos { self.input.last_pos() } fn take_errors(&mut self) -> Vec<Error> { take(&mut self.errors) } } impl<I> Lexer<I> where I: Input, { #[inline(always)] fn next(&mut self) -> Option<char> { self.input.cur() } // Any occurrences of surrogates are surrogate-in-input-stream parse errors. Any // occurrences of noncharacters are noncharacter-in-input-stream parse errors // and any occurrences of controls other than ASCII whitespace and U+0000 NULL // characters are control-character-in-input-stream parse errors. // // Postpone validation for each character for perf reasons and do it in // `anything else` #[inline(always)] fn validate_input_stream_character(&mut self, c: char) { let code = c as u32; if (0xd800..=0xdfff).contains(&code) { self.emit_error(ErrorKind::SurrogateInInputStream); } else if code != 0x00 && is_control(code) { self.emit_error(ErrorKind::ControlCharacterInInputStream); } else if is_noncharacter(code) { self.emit_error(ErrorKind::NoncharacterInInputStream); } } #[inline(always)] fn consume(&mut self) { self.cur = self.input.cur(); self.cur_pos = self.input.cur_pos(); if self.cur.is_some() { unsafe { // Safety: cur() is Some(c) self.input.bump(); } } } #[inline(always)] fn reconsume(&mut self) { unsafe { // Safety: We got cur_pos from self.input self.input.reset_to(self.cur_pos); } } #[inline(always)] fn reconsume_in_state(&mut self, state: State) { self.state = state; self.reconsume(); } #[inline(always)] fn consume_next_char(&mut self) -> Option<char> { // The next input character is the first character in the input stream that has // not yet been consumed or explicitly ignored by the requirements in this // section. Initially, the next input character is the first character in the // input. The current input character is the last character to have been // consumed. let c = self.next(); self.consume(); c } #[cold] fn emit_error(&mut self, kind: ErrorKind) { self.errors.push(Error::new( Span::new(self.cur_pos, self.input.cur_pos()), kind, )); } #[inline(always)] fn emit_token(&mut self, token: Token) { let cur_pos = self.input.cur_pos(); let span = Span::new(self.last_token_pos, cur_pos); self.last_token_pos = cur_pos; self.pending_tokens.push_back(TokenAndSpan { span, token }); } fn consume_character_reference(&mut self) -> Option<(char, String)> { let cur_pos = self.input.cur_pos(); let anything_else = |lexer: &mut Lexer<I>| { lexer.emit_error(ErrorKind::InvalidEntityCharacter); lexer.cur_pos = cur_pos; unsafe { // Safety: We got cur_post from self.input lexer.input.reset_to(cur_pos); } }; // This section defines how to consume a character reference, optionally with an // additional allowed character, which, if specified where the algorithm is // invoked, adds a character to the list of characters that cause there to not // be a character reference. // // This definition is used when parsing character in text and in attributes. // // The behavior depends on identity of next character (the one immediately after // the U+0026 AMPERSAND character), as follows: match self.consume_next_char() { // The additional allowed character if there is one // Not a character reference. No characters are consumed and nothing is returned (This // is not an error, either). Some(c) if self.additional_allowed_character == Some(c) => { self.emit_error(ErrorKind::InvalidEntityCharacter); self.cur_pos = cur_pos; unsafe { // Safety: We got cur_post from self.input self.input.reset_to(cur_pos); } } Some('l') => match self.consume_next_char() { Some('t') => { match self.consume_next_char() { Some(';') => {} _ => { self.emit_error(ErrorKind::MissingSemicolonAfterCharacterReference); } } return Some(('<', String::from("&lt;"))); } _ => { anything_else(self); } }, Some('g') => match self.consume_next_char() { Some('t') => { match self.consume_next_char() { Some(';') => {} _ => { self.emit_error(ErrorKind::MissingSemicolonAfterCharacterReference); } } return Some(('>', String::from("&gt;"))); } _ => { anything_else(self); } }, Some('q') => match self.consume_next_char() { Some('u') => match self.consume_next_char() { Some('o') => match self.consume_next_char() { Some('t') => { match self.consume_next_char() { Some(';') => {} _ => { self.emit_error( ErrorKind::MissingSemicolonAfterCharacterReference, ); } } return Some(('"', String::from("&quot;"))); } _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, Some('a') => match self.consume_next_char() { Some('p') => match self.consume_next_char() { Some('o') => match self.consume_next_char() { Some('s') => { match self.consume_next_char() { Some(';') => {} _ => { self.emit_error( ErrorKind::MissingSemicolonAfterCharacterReference, ); } } return Some(('\'', String::from("&apos;"))); } _ => { anything_else(self); } }, _ => { anything_else(self); } }, Some('m') => match self.consume_next_char() { Some('p') => { match self.consume_next_char() { Some(';') => {} _ => { self.emit_error(ErrorKind::MissingSemicolonAfterCharacterReference); } } return Some(('&', String::from("&amp;"))); } _ => { anything_else(self); } }, _ => { anything_else(self); } }, Some('#') => { let mut base = 10; let mut characters = Vec::new(); let mut has_semicolon = false; match self.consume_next_char() { Some('x' | 'X') => { base = 16; while let Some(c) = &self.consume_next_char() { if !c.is_ascii_hexdigit() { if *c == ';' { has_semicolon = true; } break; } if c.is_ascii_digit() { characters.push(*c as u32 - 0x30); } else if is_upper_hex_digit(*c) { characters.push(*c as u32 - 0x37); } else if is_lower_hex_digit(*c) { characters.push(*c as u32 - 0x57); } } } Some(c) if c.is_ascii_digit() => { characters.push(c as u32 - 0x30); while let Some(c) = &self.consume_next_char() { if !c.is_ascii_digit() { if *c == ';' { has_semicolon = true; } break; } characters.push(*c as u32 - 0x30); } } _ => {} } if characters.is_empty() { // TODO self.cur_pos = cur_pos; unsafe { // Safety: We got cur_post from self.input self.input.reset_to(cur_pos); } return None; } if !has_semicolon { self.emit_error(ErrorKind::MissingSemicolonAfterCharacterReference); } let cr = { let mut i: u32 = 0; let mut overflowed = false; for value in characters { if !overflowed { if let Some(result) = i.checked_mul(base as u32) { i = result; if let Some(result) = i.checked_add(value) { i = result; } else { i = 0x110000; overflowed = true; } } else { i = 0x110000; overflowed = true; } } } i }; if is_surrogate(cr) { self.emit_error(ErrorKind::SurrogateCharacterReference); return Some((char::REPLACEMENT_CHARACTER, String::from("empty"))); } let c = match char::from_u32(cr) { Some(c) => c, _ => { unreachable!(); } }; return Some((c, String::from("empty"))); } _ => { anything_else(self); } } None } fn create_doctype_token(&mut self, name_c: Option<char>) { let mut new_name = None; if let Some(name_c) = name_c { let mut name = String::with_capacity(4); name.push(name_c); new_name = Some(name); } self.current_doctype_token = Some(Doctype { name: new_name, public_id: None, system_id: None, }); } fn append_raw_to_doctype_token(&mut self, c: char) { if let Some(doctype_raw) = &mut self.doctype_raw { let is_cr = c == '\r'; if is_cr { let mut raw = String::with_capacity(2); raw.push(c); if self.input.cur() == Some('\n') { unsafe { // Safety: cur() is Some('\n') self.input.bump(); } raw.push('\n'); } doctype_raw.push_str(&raw); } else { doctype_raw.push(c); } } } fn append_to_doctype_token( &mut self, name: Option<char>, public_id: Option<char>, system_id: Option<char>, ) { if let Some(ref mut token) = self.current_doctype_token { if let Some(name) = name { if let Doctype { name: Some(old_name), .. } = token { old_name.push(name); } } if let Some(public_id) = public_id { if let Doctype { public_id: Some(old_public_id), .. } = token { old_public_id.push(public_id); } } if let Some(system_id) = system_id { if let Doctype { system_id: Some(old_system_id), .. } = token { old_system_id.push(system_id); } } } } fn set_doctype_token_public_id(&mut self) { if let Some(Doctype { public_id, .. }) = &mut self.current_doctype_token { // The Longest public id is `-//softquad software//dtd hotmetal pro // 6.0::19990601::extensions to html 4.0//` *public_id = Some(String::with_capacity(78)); } } fn set_doctype_token_system_id(&mut self) { if let Some(Doctype { system_id, .. }) = &mut self.current_doctype_token { // The Longest system id is `http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd` *system_id = Some(String::with_capacity(58)); } } fn emit_doctype_token(&mut self) { let current_doctype_token = self.current_doctype_token.take().unwrap(); let raw = match self.doctype_raw.take() { Some(raw) => raw, _ => { unreachable!(); } }; let token = Token::Doctype { name: current_doctype_token.name.map(Atom::from), public_id: current_doctype_token.public_id.map(Atom::from), system_id: current_doctype_token.system_id.map(Atom::from), raw: Some(Atom::from(raw)), }; self.emit_token(token); } fn create_tag_token(&mut self, kind: TagKind) { self.current_tag_token = Some(Tag { kind, // Maximum known html tags are `blockquote` and `figcaption` tag_name: String::with_capacity(10), attributes: Vec::with_capacity(255), }); } fn append_to_tag_token_name(&mut self, c: char) { if let Some(Tag { tag_name, .. }) = &mut self.current_tag_token { tag_name.push(c); } } fn start_new_attribute(&mut self, c: Option<char>) { if let Some(Tag { attributes, .. }) = &mut self.current_tag_token { // The longest known HTML attribute is "allowpaymentrequest" for "iframe". let mut name = String::with_capacity(19); let mut raw_name = String::with_capacity(19); if let Some(c) = c { name.push(c); raw_name.push(c); }; attributes.push(Attribute { span: Default::default(), name, raw_name: Some(raw_name), value: None, raw_value: None, }); self.attribute_start_position = Some(self.cur_pos); } } fn append_to_attribute( &mut self, name: Option<(char, char)>, value: Option<(bool, Option<char>, Option<char>)>, ) { if let Some(Tag { attributes, .. }) = &mut self.current_tag_token { if let Some(attribute) = attributes.last_mut() { if let Some(name) = name { attribute.name.push(name.0); if let Some(raw_name) = &mut attribute.raw_name { raw_name.push(name.1); } } if let Some(value) = value { if let Some(c) = value.1 { if let Some(old_value) = &mut attribute.value { old_value.push(c); } else { let mut new_value = String::with_capacity(255); new_value.push(c); attribute.value = Some(new_value); } } if let Some(c) = value.2 { // Quote for attribute was found, so we set empty value by default if value.0 && attribute.value.is_none() { attribute.value = Some(String::with_capacity(255)); } if let Some(raw_value) = &mut attribute.raw_value { raw_value.push(c); } else { let mut raw_new_value = String::with_capacity(255); raw_new_value.push(c); attribute.raw_value = Some(raw_new_value); } } } } } } fn append_to_attribute_with_entity(&mut self, value: Option<(Option<char>, Option<&str>)>) { if let Some(Tag { attributes, .. }) = &mut self.current_tag_token { if let Some(attribute) = attributes.last_mut() { if let Some(value) = value { if let Some(c) = value.0 { if let Some(old_value) = &mut attribute.value { old_value.push(c); } else { let mut new_value = String::with_capacity(255); new_value.push(c); attribute.value = Some(new_value); } } if let Some(c) = value.1 { if let Some(raw_value) = &mut attribute.raw_value { raw_value.push_str(c); } else { let mut raw_new_value = String::with_capacity(255); raw_new_value.push_str(c); attribute.raw_value = Some(raw_new_value); } } } } } } fn update_attribute_span(&mut self) { if let Some(attribute_start_position) = self.attribute_start_position { if let Some(Tag { ref mut attributes, .. }) = self.current_tag_token { if let Some(last) = attributes.last_mut() { last.span = Span::new(attribute_start_position, self.cur_pos); } } } } fn set_tag_to_empty_tag(&mut self) { if let Some(Tag { kind, .. }) = &mut self.current_tag_token { *kind = TagKind::Empty; } } fn emit_tag_token(&mut self, kind: Option<TagKind>) { if let Some(mut current_tag_token) = self.current_tag_token.take() { if let Some(kind) = kind { current_tag_token.kind = kind; } let mut already_seen: FxHashSet<Atom> = Default::default(); let attributes = current_tag_token .attributes .drain(..) .map(|attribute| { let name = Atom::from(attribute.name); if already_seen.contains(&name) { self.errors .push(Error::new(attribute.span, ErrorKind::DuplicateAttribute)); } already_seen.insert(name.clone()); AttributeToken { span: attribute.span, name, raw_name: attribute.raw_name.map(Atom::from), value: attribute.value.map(Atom::from), raw_value: attribute.raw_value.map(Atom::from), } }) .collect(); match current_tag_token.kind { TagKind::Start => { let start_tag_token = Token::StartTag { tag_name: current_tag_token.tag_name.into(), attributes, }; self.emit_token(start_tag_token); } TagKind::End => { if !current_tag_token.attributes.is_empty() { self.emit_error(ErrorKind::EndTagWithAttributes); } let end_tag_token = Token::EndTag { tag_name: current_tag_token.tag_name.into(), attributes, }; self.emit_token(end_tag_token); } TagKind::Empty => { let empty_tag = Token::EmptyTag { tag_name: current_tag_token.tag_name.into(), attributes, }; self.emit_token(empty_tag); } } } } fn create_comment_token(&mut self, new_data: Option<String>, raw_start: &str) { let mut data = String::with_capacity(32); let mut raw = String::with_capacity(38); raw.push_str(raw_start); if let Some(new_data) = new_data { data.push_str(&new_data); raw.push_str(&new_data); }; self.current_comment_token = Some(Comment { data, raw }); } fn append_to_comment_token(&mut self, c: char, raw_c: char) { if let Some(Comment { data, raw }) = &mut self.current_comment_token { data.push(c); raw.push(raw_c); } } fn handle_raw_and_append_to_comment_token(&mut self, c: char) { if let Some(Comment { data, raw }) = &mut self.current_comment_token { let is_cr = c == '\r'; if is_cr { let mut raw_c = String::with_capacity(2); raw_c.push(c); if self.input.cur() == Some('\n') { unsafe { // Safety: cur() is Some('\n') self.input.bump(); } raw_c.push('\n'); } data.push('\n'); raw.push_str(&raw_c); } else { data.push(c); raw.push(c); } } } fn emit_comment_token(&mut self, raw_end: Option<&str>) { let mut comment = self.current_comment_token.take().unwrap(); if let Some(raw_end) = raw_end { comment.raw.push_str(raw_end); } self.emit_token(Token::Comment { data: comment.data.into(), raw: comment.raw.into(), }); } fn create_cdata_token(&mut self) { let data = String::new(); let raw = String::with_capacity(12); self.current_cdata_token = Some(Cdata { data, raw }); } fn append_to_cdata_token(&mut self, c: Option<char>, raw_c: Option<char>) { if let Some(Cdata { data, raw }) = &mut self.current_cdata_token { if let Some(c) = c { data.push(c); } if let Some(raw_c) = raw_c { raw.push(raw_c); } } } fn emit_cdata_token(&mut self) { let cdata = self.current_cdata_token.take().unwrap(); self.emit_token(Token::Cdata { data: cdata.data.into(), raw: cdata.raw.into(), }); } fn handle_raw_and_emit_character_token(&mut self, c: char) { let is_cr = c == '\r'; if is_cr { let mut raw = String::with_capacity(2); raw.push(c); if self.input.cur() == Some('\n') { unsafe { // Safety: cur() is Some('\n') self.input.bump(); } raw.push('\n'); } self.emit_token(Token::Character { value: '\n', raw: Some(raw.into()), }); } else { self.emit_token(Token::Character { value: c, raw: Some(String::from(c).into()), }); } } fn create_processing_instruction_token(&mut self) { self.current_processing_instruction = Some(ProcessingInstruction { target: String::with_capacity(3), data: String::with_capacity(255), }); } fn set_processing_instruction_token(&mut self, target_c: Option<char>, data_c: Option<char>) { if let Some(ProcessingInstruction { target, data, .. }) = &mut self.current_processing_instruction { if let Some(target_c) = target_c { target.push(target_c); } if let Some(data_c) = data_c { data.push(data_c); } } } fn emit_current_processing_instruction(&mut self) { let processing_instruction = self.current_processing_instruction.take().unwrap(); let token = Token::ProcessingInstruction { target: processing_instruction.target.into(), data: processing_instruction.data.into(), }; self.emit_token(token); } #[inline(always)] fn emit_character_token(&mut self, value: (char, char)) { self.emit_token(Token::Character { value: value.0, raw: Some(String::from(value.1).into()), }); } #[inline(always)] fn emit_character_token_with_entity(&mut self, c: char, raw: &str) { self.emit_token(Token::Character { value: c, raw: Some(raw.into()), }); } fn read_token_and_span(&mut self) -> LexResult<TokenAndSpan> { if self.finished { return Err(ErrorKind::Eof); } else { while self.pending_tokens.is_empty() { self.run()?; } } let token_and_span = self.pending_tokens.pop_front().unwrap(); match token_and_span.token { Token::Eof => { self.finished = true; return Err(ErrorKind::Eof); } _ => { return Ok(token_and_span); } } } fn run(&mut self) -> LexResult<()> { match self.state { State::Data => { // Consume the next input character: match self.consume_next_char() { // U+0026 AMPERSAND (&) // Switch to character reference in data state. Some('&') => { self.state = State::CharacterReferenceInData; } // U+003C LESSER-THAN SIGN (<) // Switch to the tag open state. Some('<') => { self.state = State::TagOpen; } // EOF // Emit an end-of-file token. None => { self.emit_token(Token::Eof); return Ok(()); } // Anything else // Emit the current input character as character. Stay in this state. Some(c) => { self.validate_input_stream_character(c); self.handle_raw_and_emit_character_token(c); } } } State::CharacterReferenceInData => { // Switch to the data state. // Attempt to consume a character reference. // // If nothing is returned emit a U+0026 AMPERSAND character (&) token. // // Otherwise, emit character tokens that were returned. self.state = State::Data; let character_reference = self.consume_character_reference(); if let Some((c, raw)) = character_reference { self.emit_character_token_with_entity(c, &raw); } else { self.emit_character_token(('&', '&')); } } State::Pi => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+0020 SPACE // EOF // Parse error. // Switch to the pi target after state. Some(c) if is_whitespace(c) => { self.emit_error(ErrorKind::InvalidCharacterOfProcessingInstruction); self.create_processing_instruction_token(); self.state = State::PiTargetAfter; } None => { self.emit_error(ErrorKind::EofInProcessingInstruction); self.create_processing_instruction_token(); self.emit_current_processing_instruction(); self.reconsume_in_state(State::Data); } // U+003F QUESTION MARK(?) // Emit error // Reprocess the current input character in the pi end state (recovery mode). Some('?') => { self.emit_error(ErrorKind::NoTargetNameInProcessingInstruction); self.create_processing_instruction_token(); self.state = State::PiEnd; } Some(c) => { self.validate_input_stream_character(c); self.create_processing_instruction_token(); self.set_processing_instruction_token(Some(c), None); self.state = State::PiTarget; } } } State::PiTarget => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+0020 SPACE // Switch to the pi target state. Some(c) if is_whitespace(c) => { self.state = State::PiTargetAfter; } // EOF // Parse error. Emit the current processing instruction token and then reprocess // the current input character in the data state. None => { self.emit_error(ErrorKind::EofInProcessingInstruction); self.emit_current_processing_instruction(); self.reconsume_in_state(State::Data); } // U+003F QUESTION MARK(?) // Switch to the pi target question. Some('?') => { self.state = State::PiTargetQuestion; } // Anything else // Append the current input character to the processing instruction target and // stay in the current state. Some(c) => { self.validate_input_stream_character(c); self.set_processing_instruction_token(Some(c), None); } } } State::PiTargetQuestion => { // Consume the next input character: match self.consume_next_char() { // U+003E GREATER-THAN SIGN (>) Some('>') => { self.reconsume_in_state(State::PiEnd); } _ => { self.errors.push(Error::new( Span::new(self.cur_pos - BytePos(1), self.input.cur_pos() - BytePos(1)), ErrorKind::MissingWhitespaceBeforeQuestionInProcessingInstruction, )); self.set_processing_instruction_token(None, Some('?')); self.reconsume_in_state(State::PiData); } } } State::PiTargetAfter => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (Tab) // U+000A LINE FEED (LF) // U+0020 SPACE (Space) // Stay in the current state. Some(c) if is_whitespace(c) => { self.skip_next_lf(c); } // Anything else // Reprocess the current input character in the pi data state. _ => { self.reconsume_in_state(State::PiData); } } } State::PiData => { // Consume the next input character: match self.consume_next_char() { // U+003F QUESTION MARK(?) // Switch to the pi after state. Some('?') => { self.state = State::PiEnd; } // EOF // Parse error. Emit the current processing instruction token and then reprocess // the current input character in the data state. None => { self.emit_error(ErrorKind::EofInProcessingInstruction); self.emit_current_processing_instruction(); self.reconsume_in_state(State::Data); } // Anything else // Append the current input character to the pi’s data and stay in the current // state. Some(c) => { self.validate_input_stream_character(c); self.set_processing_instruction_token(None, Some(c)); } } } State::PiEnd => { // Consume the next input character: match self.consume_next_char() { // U+003E GREATER-THAN SIGN (>) // Emit the current token and then switch to the data state. Some('>') => { self.emit_current_processing_instruction(); self.state = State::Data; } // EOF // Parse error. Emit the current processing instruction token and then reprocess // the current input character in the data state. None => { self.emit_error(ErrorKind::EofInProcessingInstruction); self.emit_current_processing_instruction(); self.reconsume_in_state(State::Data); } // Anything else // Reprocess the current input character in the pi data state. _ => { self.set_processing_instruction_token(None, Some('?')); self.reconsume_in_state(State::PiData); } } } State::MarkupDeclaration => { let cur_pos = self.input.cur_pos(); let anything_else = |lexer: &mut Lexer<I>| { lexer.emit_error(ErrorKind::IncorrectlyOpenedComment); lexer.create_comment_token(None, "<!"); lexer.state = State::BogusComment; lexer.cur_pos = cur_pos; // We don't validate input here because we reset position unsafe { // Safety: cur_pos is in the range of input lexer.input.reset_to(cur_pos); } }; // If the next few characters are: match self.consume_next_char() { // Two U+002D HYPEN-MINUS characters (-) // Consume those two characters, create a comment token whose data is the empty // string and switch to comment start state. Some('-') => match self.consume_next_char() { Some('-') => { self.create_comment_token(None, "<!--"); self.state = State::CommentStart; } _ => { anything_else(self); } }, // ASCII case-insensitive match for word "DOCTYPE" // Consume those characters and switch to Doctype state Some(d @ 'd' | d @ 'D') => match self.consume_next_char() { Some(o @ 'o' | o @ 'O') => match self.consume_next_char() { Some(c @ 'c' | c @ 'C') => match self.consume_next_char() { Some(t @ 't' | t @ 'T') => match self.consume_next_char() { Some(y @ 'y' | y @ 'Y') => match self.consume_next_char() { Some(p @ 'p' | p @ 'P') => match self.consume_next_char() { Some(e @ 'e' | e @ 'E') => { self.state = State::Doctype; let mut raw_keyword = String::with_capacity(9); raw_keyword.push('<'); raw_keyword.push('!'); raw_keyword.push(d); raw_keyword.push(o); raw_keyword.push(c); raw_keyword.push(t); raw_keyword.push(y); raw_keyword.push(p); raw_keyword.push(e); self.doctype_raw = Some(raw_keyword); } _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, // Exact match for word "[CDATA[" with a (the five uppercase letters "CDATA" // with a U+005B LEFT SQUARE BRACKET character before and after) // Consume those characters and switch to CDATA state Some('[') => match self.consume_next_char() { Some(c @ 'C') => match self.consume_next_char() { Some(d @ 'D') => match self.consume_next_char() { Some(a1 @ 'A') => match self.consume_next_char() { Some(t @ 'T') => match self.consume_next_char() { Some(a2 @ 'A') => match self.consume_next_char() { Some('[') => { self.create_cdata_token(); self.append_to_cdata_token(None, Some('<')); self.append_to_cdata_token(None, Some('!')); self.append_to_cdata_token(None, Some('[')); self.append_to_cdata_token(None, Some(c)); self.append_to_cdata_token(None, Some(d)); self.append_to_cdata_token(None, Some(a1)); self.append_to_cdata_token(None, Some(t)); self.append_to_cdata_token(None, Some(a2)); self.append_to_cdata_token(None, Some('[')); self.state = State::Cdata; } _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, _ => { anything_else(self); } }, // Anything else // Emit an error. Create a comment token whose data is an empty string. Switch // to bogus comment state (don’t consume any characters) _ => { anything_else(self); } } } State::CommentStart => { // Consume the next input character: match self.consume_next_char() { // U+002D HYPHEN-MINUS (-) // Switch to the comment start dash state. Some('-') => { self.state = State::CommentStartDash; } // U+003E GREATER-THAN SIGN (>) // This is an abrupt-closing-of-empty-comment parse error. Switch to the // data state. Emit the current comment token. Some('>') => { self.emit_error(ErrorKind::AbruptClosingOfEmptyComment); self.state = State::Data; self.emit_comment_token(Some(">")); } // Anything else // Reconsume in the comment state. _ => { self.reconsume_in_state(State::Comment); } } } State::CommentStartDash => { // Consume the next input character: match self.consume_next_char() { // U+002D HYPHEN-MINUS (-) // Switch to the comment end state. Some('-') => { self.state = State::CommentEnd; } // U+003E GREATER-THAN SIGN (>) // This is an abrupt-closing-of-empty-comment parse error. Switch to the // data state. Emit the current comment token. Some('>') => { self.emit_error(ErrorKind::AbruptClosingOfEmptyComment); self.state = State::Data; self.emit_comment_token(Some("->")); } // EOF // This is an eof-in-comment parse error. Emit the current comment token. // Emit an end-of-file token. None => { self.emit_error(ErrorKind::EofInComment); self.emit_comment_token(None); self.emit_token(Token::Eof); return Ok(()); } // Anything else // Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. // Reconsume in the comment state. _ => { self.append_to_comment_token('-', '-'); self.reconsume_in_state(State::Comment); } } } State::Comment => { // Consume the next input character: match self.consume_next_char() { // U+003C LESS-THAN SIGN (<) // Append the current input character to the comment token's data. Switch to // the comment less-than sign state. Some(c @ '<') => { self.append_to_comment_token(c, c); self.state = State::CommentLessThanSign; } // U+002D HYPHEN-MINUS (-) // Switch to the comment end dash state. Some('-') => { self.state = State::CommentEndDash; } // EOF // This is an eof-in-comment parse error. Emit the current comment token. // Emit an end-of-file token. None => { self.emit_error(ErrorKind::EofInComment); self.emit_comment_token(None); self.emit_token(Token::Eof); return Ok(()); } // Anything else // Append the current input character to the comment token's data. Some(c) => { self.validate_input_stream_character(c); self.handle_raw_and_append_to_comment_token(c); } } } // https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-state State::CommentLessThanSign => { // Consume the next input character: match self.consume_next_char() { // U+0021 EXCLAMATION MARK (!) // Append the current input character to the comment token's data. Switch to // the comment less-than sign bang state. Some(c @ '!') => { self.append_to_comment_token(c, c); self.state = State::CommentLessThanSignBang; } // U+003C LESS-THAN SIGN (<) // Append the current input character to the comment token's data. Some(c @ '<') => { self.append_to_comment_token(c, c); } // Anything else // Reconsume in the comment state. _ => { self.reconsume_in_state(State::Comment); } } } // https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-bang-state State::CommentLessThanSignBang => { // Consume the next input character: match self.consume_next_char() { // U+002D HYPHEN-MINUS (-) // Switch to the comment less-than sign bang dash state. Some('-') => { self.state = State::CommentLessThanSignBangDash; } // Anything else // Reconsume in the comment state. _ => { self.reconsume_in_state(State::Comment); } } } // https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-bang-dash-state State::CommentLessThanSignBangDash => { // Consume the next input character: match self.consume_next_char() { // U+002D HYPHEN-MINUS (-) // Switch to the comment less-than sign bang dash dash state. Some('-') => { self.state = State::CommentLessThanSignBangDashDash; } // Anything else // Reconsume in the comment end dash state. _ => { self.reconsume_in_state(State::CommentEndDash); } } } // https://html.spec.whatwg.org/multipage/parsing.html#comment-less-than-sign-bang-dash-dash-state State::CommentLessThanSignBangDashDash => { // Consume the next input character: match self.consume_next_char() { // U+003E GREATER-THAN SIGN (>) // EOF // Reconsume in the comment end state. Some('>') | None => { self.reconsume_in_state(State::CommentEnd); } // Anything else // This is a nested-comment parse error. Reconsume in the comment end state. _ => { self.emit_error(ErrorKind::NestedComment); self.reconsume_in_state(State::CommentEnd); } } } // https://html.spec.whatwg.org/multipage/parsing.html#comment-end-dash-state State::CommentEndDash => { // Consume the next input character: match self.consume_next_char() { // U+002D HYPHEN-MINUS (-) // Switch to the comment end state. Some('-') => { self.state = State::CommentEnd; } // EOF // This is an eof-in-comment parse error. Emit the current comment token. // Emit an end-of-file token. None => { self.emit_error(ErrorKind::EofInComment); self.emit_comment_token(None); self.emit_token(Token::Eof); return Ok(()); } // Anything else // Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. // Reconsume in the comment state. _ => { self.append_to_comment_token('-', '-'); self.reconsume_in_state(State::Comment); } } } // https://html.spec.whatwg.org/multipage/parsing.html#comment-end-state State::CommentEnd => { // Consume the next input character: match self.consume_next_char() { // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Emit the current comment token. Some('>') => { self.state = State::Data; self.emit_comment_token(Some("-->")); } // U+0021 EXCLAMATION MARK (!) // Switch to the comment end bang state. Some('!') => { self.state = State::CommentEndBang; } // U+002D HYPHEN-MINUS (-) // Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. Some(c @ '-') => { self.append_to_comment_token(c, c); self.emit_error(ErrorKind::DoubleHyphenWithInComment); } // EOF // This is an eof-in-comment parse error. Emit the current comment token. // Emit an end-of-file token. None => { self.emit_error(ErrorKind::EofInComment); self.emit_comment_token(None); self.emit_token(Token::Eof); return Ok(()); } // Anything else // Append two U+002D (-) characters and the current input character to the // comment token’s data. Reconsume in the comment state. _ => { self.append_to_comment_token('-', '-'); self.append_to_comment_token('-', '-'); self.reconsume_in_state(State::Comment); } } } // https://html.spec.whatwg.org/multipage/parsing.html#comment-end-bang-state State::CommentEndBang => { // Consume the next input character: match self.consume_next_char() { // U+002D HYPHEN-MINUS (-) // Append a U+002D HYPHEN-MINUS character (-) and U+0021 EXCLAMATION MARK // character(!) to the comment token’s data. Switch to the comment end dash // state. Some('-') => { self.append_to_comment_token('-', '-'); self.append_to_comment_token('!', '!'); self.state = State::CommentEndDash; } // U+003E GREATER-THAN SIGN (>) // Parse error. Switch to the data state.Emit the comment token. Some('>') => { self.emit_error(ErrorKind::IncorrectlyClosedComment); self.state = State::Data; self.emit_comment_token(Some(">")); } // EOF // Parse error. Emit the comment token. Emit an end-of-file token. None => { self.emit_error(ErrorKind::EofInComment); self.emit_comment_token(None); self.emit_token(Token::Eof); return Ok(()); } // Anything else // Anything else // Append two U+002D (-) characters and U+0021 EXCLAMATION MARK character(!) to // the comment token’s data. Reconsume in the comment state. _ => { self.append_to_comment_token('-', '-'); self.append_to_comment_token('-', '-'); self.append_to_comment_token('!', '!'); self.reconsume_in_state(State::Comment); } } } State::Cdata => { // Consume the next input character: match self.consume_next_char() { // U+005D RIGHT SQUARE BRACKET (]) // Switch to the CDATA bracket state. Some(']') => { self.state = State::CdataBracket; } // EOF // Parse error. Reprocess the current input character in the data state. None => { self.emit_error(ErrorKind::EofInCdata); self.reconsume_in_state(State::Data); } // Anything else // Append the current input character to the cdata dta. Stay in the current // state. Some(c) => { self.validate_input_stream_character(c); self.append_to_cdata_token(Some(c), Some(c)); } } } State::CdataBracket => { // Consume the next input character: match self.consume_next_char() { // U+005D RIGHT SQUARE BRACKET (]) // Switch to the CDATA end state. Some(']') => { self.state = State::CdataEnd; } // EOF // Parse error. Reconsume the current input character in the data state. None => { self.emit_error(ErrorKind::EofInCdata); self.reconsume_in_state(State::Data); } // Anything else // Emit a U+005D RIGHT SQUARE BRACKET character token. Reconsume in the // CDATA section state. Some(c) => { self.append_to_cdata_token(Some(']'), Some(']')); self.append_to_cdata_token(Some(c), Some(c)); self.state = State::Cdata; } } } State::CdataEnd => { // Consume the next input character: match self.consume_next_char() { // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Some('>') => { self.append_to_cdata_token(None, Some(']')); self.append_to_cdata_token(None, Some(']')); self.append_to_cdata_token(None, Some('>')); self.emit_cdata_token(); self.state = State::Data; } // U+005D RIGHT SQUARE BRACKET (]) // Emit the current input character as character token. Stay in the current // state. Some(c @ ']') => { self.append_to_cdata_token(Some(c), Some(c)); } // EOF // Parse error. Reconsume the current input character in the data state. None => { self.emit_error(ErrorKind::EofInCdata); self.reconsume_in_state(State::Data); } // Anything else // Emit two U+005D RIGHT SQUARE BRACKET (]) characters as character tokens and // also emit the current input character as character token. Switch to the CDATA // state. Some(c) => { self.append_to_cdata_token(Some(']'), Some(']')); self.append_to_cdata_token(Some(']'), Some(']')); self.append_to_cdata_token(Some(c), Some(c)); self.state = State::Cdata; } } } State::TagOpen => { // Consume the next input character: match self.consume_next_char() { // U+002F SOLIDUS (/) // Switch to the end tag open state. Some('/') => { self.state = State::EndTagOpen; } // U+0021 EXCLAMATION MARK (!) // Switch to the markup declaration open state. Some('!') => { self.state = State::MarkupDeclaration; } // U+003F QUESTION MARK(?) // Switch to the pi state. Some('?') => { self.state = State::Pi; } // Name start character // Create a new tag token and set its name to the input character, then switch // to the tag name state. Some(c) if is_name_start_char(c) => { self.create_tag_token(TagKind::Start); self.reconsume_in_state(State::TagName); } // EOF // This is an eof-before-tag-name parse error. Emit a U+003C LESS-THAN SIGN // character token and an end-of-file token. None => { self.emit_error(ErrorKind::EofBeforeTagName); self.emit_character_token(('<', '<')); self.emit_token(Token::Eof); return Ok(()); } // Anything else // This is an invalid-first-character-of-tag-name parse error. Emit a U+003C // LESS-THAN SIGN character token. Reconsume in the data state. _ => { self.emit_error(ErrorKind::InvalidFirstCharacterOfTagName); self.emit_character_token(('<', '<')); self.reconsume_in_state(State::Data); } } } State::EndTagOpen => { // Consume the next input character: match self.consume_next_char() { // ASCII alpha // Create a new end tag token, set its tag name to the empty string. // Reconsume in the tag name state. Some(c) if is_name_char(c) => { self.create_tag_token(TagKind::End); self.reconsume_in_state(State::TagName); } // U+003E GREATER-THAN SIGN (>) // This is a missing-end-tag-name parse error. Switch to the data state. Some('>') => { self.emit_error(ErrorKind::MissingEndTagName); self.state = State::Data; } // EOF // This is an eof-before-tag-name parse error. Emit a U+003C LESS-THAN SIGN // character token, a U+002F SOLIDUS character token and an end-of-file // token. None => { self.emit_error(ErrorKind::EofBeforeTagName); self.emit_character_token(('<', '<')); self.emit_character_token(('/', '/')); self.emit_token(Token::Eof); return Ok(()); } // Anything else // This is an invalid-first-character-of-tag-name parse error. Create a // comment token whose data is the empty string. Reconsume in the bogus // comment state. _ => { self.emit_error(ErrorKind::InvalidFirstCharacterOfTagName); self.emit_character_token(('<', '<')); self.emit_character_token(('/', '/')); self.reconsume_in_state(State::BogusComment); } } } State::TagName => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (Tab) // U+000A LINE FEED (LF) // U+0020 SPACE (Space) // Switch to the before attribute name state. Some(c) if is_whitespace(c) => { self.skip_next_lf(c); self.state = State::TagAttributeNameBefore; } // U+002F SOLIDUS (/) // Set current tag to empty tag. Switch to the empty tag state. Some('/') => { self.set_tag_to_empty_tag(); self.state = State::EmptyTag; } // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Emit the current tag token. Some('>') => { self.state = State::Data; self.emit_tag_token(None); } // EOF // This is an eof-in-tag parse error. Emit an end-of-file token. None => { self.emit_error(ErrorKind::EofInTag); self.emit_tag_token(None); return Ok(()); } // Name character // Append the current input character to the tag name and stay in the current // state. Some(c) if is_name_char(c) => { self.validate_input_stream_character(c); self.append_to_tag_token_name(c); } // Anything else // Parse error. Append the current input character to the tag name and stay in // the current state. Some(c) => { self.emit_error(ErrorKind::InvalidCharacterInTag); self.validate_input_stream_character(c); self.append_to_tag_token_name(c); } } } State::EmptyTag => { // Consume the next input character: match self.consume_next_char() { // U+003E GREATER-THAN SIGN (>) // Emit the current tag token as empty tag token and then switch to the data // state. Some('>') => { self.emit_tag_token(Some(TagKind::Empty)); self.state = State::Data; } // Anything else // Parse error. Reprocess the current input character in the tag attribute name // before state. _ => { self.emit_error(ErrorKind::UnexpectedSolidusInTag); self.reconsume_in_state(State::TagAttributeNameBefore); } } } State::TagAttributeNameBefore => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.skip_next_lf(c); } // U+003E GREATER-THAN SIGN(>) // Emit the current token and then switch to the data state. Some('>') => { self.emit_tag_token(None); self.state = State::Data; } // U+002F SOLIDUS (/) // Set current tag to empty tag. Switch to the empty tag state. Some('/') => { self.set_tag_to_empty_tag(); self.state = State::EmptyTag; } // U+003A COLON (:) // Parse error. Stay in the current state. Some(':') => { self.emit_error(ErrorKind::UnexpectedColonBeforeAttributeName); } // EOF // Parse error. Emit the current token and then reprocess the current input // character in the data state. None => { self.emit_error(ErrorKind::EofBeforeTagName); self.emit_tag_token(None); self.reconsume_in_state(State::Data); } // Anything else // Start a new attribute in the current tag token. Set that attribute’s name to // the current input character and its value to the empty string and then switch // to the tag attribute name state. _ => { self.start_new_attribute(None); self.reconsume_in_state(State::TagAttributeName); } } } State::TagAttributeName => { // Consume the next input character: match self.consume_next_char() { // U+003D EQUALS SIGN (=) // Switch to the before attribute value state. Some('=') => { self.state = State::TagAttributeValueBefore; } // U+003E GREATER-THEN SIGN (>) // Emit the current token as start tag token. Switch to the data state. Some('>') => { self.emit_error(ErrorKind::MissingEqualAfterAttributeName); self.emit_tag_token(None); self.state = State::Data; } // U+0009 CHARACTER TABULATION (Tab) // U+000A LINE FEED (LF) // U+0020 SPACE (Space) // Switch to the tag attribute name after state. Some(c) if is_whitespace(c) => { self.update_attribute_span(); self.skip_next_lf(c); self.reconsume_in_state(State::TagAttributeNameAfter); } // U+002F SOLIDUS (/) // Set current tag to empty tag. Switch to the empty tag state. Some('/') => { self.emit_error(ErrorKind::MissingEqualAfterAttributeName); self.set_tag_to_empty_tag(); self.state = State::EmptyTag; } // EOF // Parse error. Emit the current token as start tag token and then reprocess the // current input character in the data state. None => { self.emit_error(ErrorKind::EofInTag); self.emit_tag_token(Some(TagKind::Start)); self.reconsume_in_state(State::Data); } // Anything else // Append the current input character to the current attribute's name. Some(c) => { self.validate_input_stream_character(c); self.append_to_attribute(Some((c, c)), None); } } // When the user agent leaves the attribute name state (and // before emitting the tag token, if appropriate), the // complete attribute's name must be compared to the other // attributes on the same token; if there is already an // attribute on the token with the exact same name, then // this is a duplicate-attribute parse error and the new // attribute must be removed from the token. // // We postpone it when we will emit current tag token } State::TagAttributeNameAfter => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.skip_next_lf(c); } // U+003D EQUALS SIGN(=) // Switch to the tag attribute value before state. Some('=') => { self.state = State::TagAttributeValueBefore; } // U+003E GREATER-THEN SIGN(>) // Emit the current token and then switch to the data state. Some('>') => { self.emit_tag_token(None); self.state = State::Data; } // U+002F SOLIDUS (/) // Set current tag to empty tag. Switch to the empty tag state. Some('/') => { self.set_tag_to_empty_tag(); self.state = State::EmptyTag; } // EOF // Parse error. Emit the current token and then reprocess the current input // character in the data state. None => { self.emit_error(ErrorKind::EofInTag); self.emit_tag_token(None); self.reconsume_in_state(State::Data); } // Anything else // Start a new attribute in the current tag token. Set that attribute’s name to // the current input character and its value to the empty string and then switch // to the tag attribute name state. Some(c) => { self.emit_error(ErrorKind::MissingEqualAfterAttributeName); self.validate_input_stream_character(c); self.start_new_attribute(Some(c)); self.state = State::TagAttributeName; } } } State::TagAttributeValueBefore => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.skip_next_lf(c); } // U+0022 QUOTATION MARK (") // Switch to the attribute value (double-quoted) state. Some(c @ '"') => { self.append_to_attribute(None, Some((true, None, Some(c)))); self.state = State::TagAttributeValueDoubleQuoted; } // U+0027 APOSTROPHE (') // Switch to the attribute value (single-quoted) state. Some(c @ '\'') => { self.append_to_attribute(None, Some((true, None, Some(c)))); self.state = State::TagAttributeValueSingleQuoted; } // U+003E GREATER-THAN SIGN(>) // Emit the current token and then switch to the data state. Some('>') => { self.emit_tag_token(None); self.state = State::Data; } // EOF // Parse error. Emit the current token and then reprocess the current input // character in the data state. None => { self.emit_error(ErrorKind::EofInTag); self.emit_tag_token(None); self.reconsume_in_state(State::Data); } // Anything else // Append the current input character to the current attribute’s value and then // switch to the tag attribute value unquoted state. Some(c) => { self.emit_error(ErrorKind::MissingQuoteBeforeAttributeValue); self.validate_input_stream_character(c); self.append_to_attribute(None, Some((true, Some(c), Some(c)))); self.state = State::TagAttributeValueUnquoted; } } } State::TagAttributeValueDoubleQuoted => { // Consume the next input character: match self.consume_next_char() { // U+0022 QUOTATION MARK (") // Switch to the tag attribute name before state. // We set value to support empty attributes (i.e. `attr=""`) Some(c @ '"') => { self.append_to_attribute(None, Some((false, None, Some(c)))); self.state = State::TagAttributeValueAfter; } // U+0026 AMPERSAND (&) // Switch to character reference in attribute value state, with the additional // allowed character being U+0022 QUOTATION MARK("). Some('&') => { self.return_state = Some(self.state.clone()); self.state = State::CharacterReferenceInAttributeValue; self.additional_allowed_character = Some('"'); } // (<) Some(c @ '<') => { self.emit_error(ErrorKind::UnescapedCharacterInAttributeValue('<')); self.append_to_attribute(None, Some((false, Some(c), Some(c)))); } // EOF // Parse error. Emit the current token and then reprocess the current input // character in the data state. None => { self.emit_error(ErrorKind::EofInTag); self.emit_tag_token(None); self.reconsume_in_state(State::Data); } // Anything else // Append the input character to the current attribute’s value. Stay in the // current state. Some(c) => { self.validate_input_stream_character(c); self.append_to_attribute(None, Some((false, Some(c), Some(c)))); } } } State::TagAttributeValueSingleQuoted => { // Consume the next input character: match self.consume_next_char() { // U+0022 APOSTROPHE (') // Switch to the tag attribute name before state. // We set value to support empty attributes (i.e. `attr=''`) Some(c @ '\'') => { self.append_to_attribute(None, Some((false, None, Some(c)))); self.state = State::TagAttributeValueAfter; } // U+0026 AMPERSAND (&) // Switch to character reference in attribute value state, with the additional // allowed character being APOSTROPHE ('). Some('&') => { self.return_state = Some(self.state.clone()); self.state = State::CharacterReferenceInAttributeValue; self.additional_allowed_character = Some('\''); } // (<) Some(c @ '<') => { self.emit_error(ErrorKind::UnescapedCharacterInAttributeValue('<')); self.append_to_attribute(None, Some((false, Some(c), Some(c)))); } // EOF // Parse error. Emit the current token and then reprocess the current input // character in the data state. None => { self.emit_error(ErrorKind::EofInTag); self.emit_tag_token(None); self.reconsume_in_state(State::Data); } // Anything else // Append the current input character to the current attribute's value. Some(c) => { self.validate_input_stream_character(c); self.append_to_attribute(None, Some((false, Some(c), Some(c)))); } } } State::TagAttributeValueUnquoted => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (Tab) // U+000A LINE FEED (LF) // U+0020 SPACE (Space) // Switch to the before attribute name state. Some(c) if is_whitespace(c) => { self.update_attribute_span(); self.skip_next_lf(c); self.state = State::TagAttributeValueAfter; } // U+0026 AMPERSAND (&) // Set the return state to the attribute value (unquoted) state. Switch to // the character reference state. Some('&') => { self.return_state = Some(self.state.clone()); self.state = State::CharacterReferenceInAttributeValue; self.additional_allowed_character = Some('>'); } // (<) Some(c @ '<') => { self.emit_error(ErrorKind::UnescapedCharacterInAttributeValue('<')); self.append_to_attribute(None, Some((false, Some(c), Some(c)))); } // U+003E GREATER-THAN SIGN (>) // Emit the current token as start tag token and then switch to the data state. Some('>') => { self.update_attribute_span(); self.emit_tag_token(Some(TagKind::Start)); self.state = State::Data; } // EOF // Parse error. Emit the current token as start tag token and then reprocess the // current input character in the data state. None => { self.emit_error(ErrorKind::EofInTag); self.update_attribute_span(); self.emit_tag_token(Some(TagKind::Start)); self.reconsume_in_state(State::Data); } // Anything else // Append the input character to the current attribute’s value. Stay in the // current state. Some(c) => { self.validate_input_stream_character(c); self.append_to_attribute(None, Some((false, Some(c), Some(c)))); } } } State::TagAttributeValueAfter => match self.consume_next_char() { Some(c) if is_whitespace(c) => { self.reconsume_in_state(State::TagAttributeNameBefore); } Some('>') | Some('/') => { self.reconsume_in_state(State::TagAttributeNameBefore); } None => { self.emit_error(ErrorKind::EofInTag); self.update_attribute_span(); self.emit_tag_token(Some(TagKind::Start)); self.reconsume_in_state(State::Data); } _ => { self.emit_error(ErrorKind::MissingSpaceBetweenAttributes); self.reconsume_in_state(State::TagAttributeNameBefore); } }, State::CharacterReferenceInAttributeValue => { // Attempt to consume a character reference. // // If nothing is returned, append a U+0026 AMPERSAND (&) character to current // attribute’s value. // // Otherwise append returned character tokens to current attribute’s value. // // Finally, switch back to attribute value state that switched to this state. let character_reference = self.consume_character_reference(); if let Some((c, raw)) = character_reference { self.append_to_attribute_with_entity(Some((Some(c), Some(&raw)))); } else { self.append_to_attribute(None, Some((false, Some('&'), Some('&')))); } if let Some(return_state) = &self.return_state { self.state = return_state.clone(); } } State::BogusComment => { // Consume every character up to the first U+003E GREATER-THAN SIGN (>) or EOF, // whichever comes first. Emit a comment token whose data is the concatenation // of all those consumed characters. Then consume the next input character and // switch to the data state reprocessing the EOF character if that was the // character consumed. match self.consume_next_char() { // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Emit the current comment token. Some('>') => { self.emit_comment_token(Some(">")); self.state = State::Data; } // EOF // Emit the comment. Emit an end-of-file token. None => { self.emit_comment_token(None); self.state = State::Data; self.reconsume(); } // Anything else // Append the current input character to the comment token's data. Some(c) => { self.validate_input_stream_character(c); self.handle_raw_and_append_to_comment_token(c); } } } State::Doctype => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Switch to the before DOCTYPE name state. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); self.state = State::BeforeDoctypeName; } // EOF // Parse error. Switch to data state. Create new Doctype token. Emit Doctype // token. Reconsume the EOF character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.create_doctype_token(None); self.emit_doctype_token(); self.reconsume(); } // Anything else // This is a missing-whitespace-before-doctype-name parse error. Reconsume // in the before DOCTYPE name state. _ => { self.emit_error(ErrorKind::MissingWhitespaceBeforeDoctypeName); self.reconsume_in_state(State::BeforeDoctypeName); } } } State::BeforeDoctypeName => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); } // Uppercase ASCII letter // Create a new DOCTYPE token. Set the token name to lowercase version of the // current input character. Switch to the DOCTYPE name state. Some(c) if is_ascii_upper_alpha(c) => { self.append_raw_to_doctype_token(c); self.create_doctype_token(Some(c.to_ascii_lowercase())); self.state = State::DoctypeName; } // U+003E GREATER-THAN SIGN (>) // This is a missing-doctype-name parse error. Create a new DOCTYPE token. // Set its force-quirks flag to on. Switch to the data state. Emit the // current token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingDoctypeName); self.create_doctype_token(None); self.emit_doctype_token(); self.state = State::Data; } // EOF // Parse error. Switch to data state. Create new Doctype token. Emit Doctype // token. Reconsume the EOF character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.create_doctype_token(None); self.emit_doctype_token(); self.reconsume(); } // Anything else // Create new DOCTYPE token. Set the token’s name to current input character. // Switch to DOCTYPE name state. Some(c) => { self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); self.create_doctype_token(Some(c)); self.state = State::DoctypeName; } } } State::DoctypeName => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Switch to the after DOCTYPE name state. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); self.state = State::AfterDoctypeName; } // ASCII upper alpha // Append the lowercase version of the current input character (add 0x0020 // to the character's code point) to the current DOCTYPE token's name. Some(c) if is_ascii_upper_alpha(c) => { self.append_raw_to_doctype_token(c); self.append_to_doctype_token(Some(c.to_ascii_lowercase()), None, None); } // U+003E GREATER-THAN SIGN (>) // Emit token. Switch to data state. Some('>') => { self.emit_doctype_token(); self.state = State::Data; } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Append the current input character to the current DOCTYPE token's name. Some(c) => { self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); self.append_to_doctype_token(Some(c), None, None); } } } State::AfterDoctypeName => { let cur_pos = self.input.cur_pos(); // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); } // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Emit the current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.state = State::Data; self.emit_doctype_token(); } // U+005B LEFT SQUARE BRACKET ([) // Switch to the doctype internal subset state. Some(c @ '[') => { self.append_raw_to_doctype_token(c); self.state = State::DoctypeTypeInternalSubSet; } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // If the six characters starting from the current input character are an // ASCII case-insensitive match for the word "PUBLIC", then consume those // characters and switch to the after DOCTYPE public keyword state. // // Otherwise, if the six characters starting from the current input // character are an ASCII case-insensitive match for the word "SYSTEM", then // consume those characters and switch to the after DOCTYPE system keyword // state. // // Otherwise, this is an invalid-character-sequence-after-doctype-name parse // error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume // in the bogus DOCTYPE state. Some(c) => { let mut first_six_chars = String::with_capacity(6); first_six_chars.push(c); for _ in 0..5 { match self.consume_next_char() { Some(c) => { first_six_chars.push(c); } _ => { break; } } } match &*first_six_chars.to_lowercase() { "public" => { self.state = State::AfterDoctypePublicKeyword; if let Some(doctype_raw) = &mut self.doctype_raw { doctype_raw.push_str(&first_six_chars); } } "system" => { self.state = State::AfterDoctypeSystemKeyword; if let Some(doctype_raw) = &mut self.doctype_raw { doctype_raw.push_str(&first_six_chars); } } _ => { self.cur_pos = cur_pos; unsafe { // Safety: We got cur_pos from self.input.cur_pos() self.input.reset_to(cur_pos); } self.emit_error( ErrorKind::InvalidCharacterSequenceAfterDoctypeName, ); self.reconsume_in_state(State::BogusDoctype); } } } } } State::AfterDoctypePublicKeyword => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (Tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE (Space) // Switch to the before DOCTYPE public identifier state. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); self.state = State::BeforeDoctypePublicIdentifier; } // U+0022 QUOTATION MARK (") // This is a missing-whitespace-after-doctype-public-keyword parse error. // Set the current DOCTYPE token's public identifier to the empty string // (not missing), then switch to the DOCTYPE public identifier // (double-quoted) state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingWhitespaceAfterDoctypePublicKeyword); self.set_doctype_token_public_id(); self.state = State::DoctypePublicIdentifierDoubleQuoted; } // U+0027 APOSTROPHE (') // This is a missing-whitespace-after-doctype-public-keyword parse error. // Set the current DOCTYPE token's public identifier to the empty string // (not missing), then switch to the DOCTYPE public identifier // (single-quoted) state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingWhitespaceAfterDoctypePublicKeyword); self.set_doctype_token_public_id(); self.state = State::DoctypePublicIdentifierSingleQuoted; } // U+003E GREATER-THAN SIGN (>) // This is a missing-doctype-public-identifier parse error. Set the current // DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit // the current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingWhitespaceAfterDoctypePublicKeyword); self.set_doctype_token_public_id(); self.state = State::DoctypePublicIdentifierSingleQuoted; } // EOF // Parse error. Switch to the data state. Emit that DOCTYPE token. Reconsume the // EOF character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume() } // Anything else // Parse error. Switch to the bogus DOCTYPE state. Emit that DOCTYPE token. // Reconsume the EOF character. _ => { self.emit_error(ErrorKind::MissingQuoteBeforeDoctypePublicIdentifier); self.reconsume_in_state(State::BogusDoctype); self.emit_doctype_token(); self.reconsume() } } } State::AfterDoctypeSystemKeyword => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Switch to the before DOCTYPE system identifier state. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); self.state = State::BeforeDoctypeSystemIdentifier; } // U+0022 QUOTATION MARK (") // This is a missing-whitespace-after-doctype-system-keyword parse error. // Set the current DOCTYPE token's system identifier to the empty string // (not missing), then switch to the DOCTYPE system identifier // (double-quoted) state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingWhitespaceAfterDoctypeSystemKeyword); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierDoubleQuoted; } // U+0027 APOSTROPHE (') // This is a missing-whitespace-after-doctype-system-keyword parse error. // Set the current DOCTYPE token's system identifier to the empty string // (not missing), then switch to the DOCTYPE system identifier // (single-quoted) state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingWhitespaceAfterDoctypeSystemKeyword); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierSingleQuoted; } // U+003E GREATER-THAN SIGN(>) // Parse error. Set the DOCTYPE token’s public identifier current DOCTYPE token // to the empty string (not missing), then switch to the DOCTYPE system // identifier (single-quoted) state. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingWhitespaceAfterDoctypeSystemKeyword); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierSingleQuoted; } // EOF // Parse error. Switch to the data state. Emit that DOCTYPE token. Reconsume the // EOF character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume() } // Anything else // Parse error. Switch to the bogus DOCTYPE state. Some(c) => { self.validate_input_stream_character(c); self.emit_error(ErrorKind::MissingQuoteBeforeDoctypeSystemIdentifier); self.state = State::BogusComment } } } State::BeforeDoctypeSystemIdentifier => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); } // U+0022 QUOTATION MARK (") // Set the current DOCTYPE token's system identifier to the empty string // (not missing), then switch to the DOCTYPE system identifier // (double-quoted) state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierDoubleQuoted; } // U+0027 APOSTROPHE (') // Set the current DOCTYPE token's system identifier to the empty string // (not missing), then switch to the DOCTYPE system identifier // (single-quoted) state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierSingleQuoted; } // U+003E GREATER-THAN SIGN (>) // This is a missing-doctype-system-identifier parse error. Set the current // DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit // the current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Parse error. Switch to the bogus DOCTYPE state. Some(c) => { self.validate_input_stream_character(c); self.emit_error(ErrorKind::MissingQuoteBeforeDoctypeSystemIdentifier); self.state = State::BogusDoctype; } } } State::BeforeDoctypePublicIdentifier => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); } // U+0022 QUOTATION MARK (") // Set the current DOCTYPE token's public identifier to the empty string // (not missing), then switch to the DOCTYPE public identifier // (double-quoted) state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.set_doctype_token_public_id(); self.state = State::DoctypePublicIdentifierDoubleQuoted; } // U+0027 APOSTROPHE (') // Set the current DOCTYPE token's public identifier to the empty string // (not missing), then switch to the DOCTYPE public identifier // (single-quoted) state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.set_doctype_token_public_id(); self.state = State::DoctypePublicIdentifierSingleQuoted; } // U+003E GREATER-THAN SIGN(>) // Parse error. Switch to data state. Emit current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::MissingDoctypePublicIdentifier); self.state = State::Data; self.emit_doctype_token(); } // EOF // This is an eof-in-doctype parse error. Set the current DOCTYPE token's // force-quirks flag to on. Emit the current DOCTYPE token. Emit an // end-of-file token. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Parse error. Switch to the bogus DOCTYPE state. Some(c) => { self.validate_input_stream_character(c); self.emit_error(ErrorKind::MissingQuoteBeforeDoctypeSystemIdentifier); self.state = State::BogusDoctype; } } } State::DoctypePublicIdentifierSingleQuoted => { // Consume the next input character: match self.consume_next_char() { // U+0027 APOSTROPHE (') // Switch to the after DOCTYPE public identifier state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.state = State::AfterDoctypePublicIdentifier; } // U+003E GREATER-THAN SIGN(>) // Parse error. Switch to data state. Emit current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::AbruptDoctypePublicIdentifier); self.state = State::Data; self.emit_doctype_token(); } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Append the current input character to the current DOCTYPE token’s public // identifier. Some(c) => { self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); self.append_to_doctype_token(None, Some(c), None); } } } State::DoctypePublicIdentifierDoubleQuoted => { // Consume the next input character: match self.consume_next_char() { // U+0022 QUOTATION MARK (") // Switch to the after DOCTYPE public identifier state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.state = State::AfterDoctypePublicIdentifier; } // U+003E GREATER-THAN SIGN(>) // Parse error. Switch to data state. Emit current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::AbruptDoctypePublicIdentifier); self.state = State::Data; self.emit_doctype_token(); } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Append the current input character to the current DOCTYPE token’s public // identifier. Some(c) => { self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); self.append_to_doctype_token(None, Some(c), None); } } } State::AfterDoctypePublicIdentifier => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Switch to the between DOCTYPE public and system identifiers state. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); self.state = State::BetweenDoctypePublicAndSystemIdentifiers; } // U+0027 APOSTROPHE (') // Parse error. Set the DOCTYPE token’s system identifier to the empty string // (not missing) then switch to the DOCTYPE system identifier (single-quoted) // state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.emit_error( ErrorKind::MissingWhitespaceBetweenDoctypePublicAndSystemIdentifiers, ); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierSingleQuoted; } // U+0022 QUOTATION MARK (") // Parse error. Set the DOCTYPE token’s system identifier to the empty string // (not missing) then switch to the DOCTYPE system identifier (double-quoted) // state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.emit_error( ErrorKind::MissingWhitespaceBetweenDoctypePublicAndSystemIdentifiers, ); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierDoubleQuoted; } // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Emit the current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.state = State::Data; self.emit_doctype_token(); } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Parse error. Switch to bogus DOCTYPE state. Some(c) => { self.validate_input_stream_character(c); self.emit_error(ErrorKind::MissingQuoteBeforeDoctypeSystemIdentifier); self.state = State::BogusComment; } } } State::BetweenDoctypePublicAndSystemIdentifiers => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); } // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Emit the current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.state = State::Data; self.emit_doctype_token(); } // U+0027 APOSTROPHE(') // Set the DOCTYPE token’s system identifier to the empty string (not missing) // then switch to the DOCTYPE system identifier (single-quoted) state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierSingleQuoted; } // U+0022 QUOTATION MARK(") // Set the DOCTYPE token’s system identifier to the empty string (not missing) // then switch to the DOCTYPE system identifier (double-quoted) state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.set_doctype_token_system_id(); self.state = State::DoctypeSystemIdentifierDoubleQuoted; } // EOF // This is an eof-in-doctype parse error. Set the current DOCTYPE token's // force-quirks flag to on. Emit the current DOCTYPE token. Emit an // end-of-file token. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Parse error. Switch to Bogus DOCTYPE state. Some(c) => { self.validate_input_stream_character(c); self.emit_error(ErrorKind::MissingQuoteBeforeDoctypeSystemIdentifier); self.state = State::BogusDoctype; } } } State::DoctypeSystemIdentifierSingleQuoted => { // Consume the next input character: match self.consume_next_char() { // U+0027 APOSTROPHE (') // Switch to the after DOCTYPE system identifier state. Some(c @ '\'') => { self.append_raw_to_doctype_token(c); self.state = State::AfterDoctypeSystemIdentifier; } // U+003E GREATER-THAN SIGN (>) // Parse error. Switch to data state. Emit current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::AbruptDoctypeSystemIdentifier); self.state = State::Data; self.emit_doctype_token(); } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Append the current input character to the current DOCTYPE token's system // identifier. Some(c) => { self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); self.append_to_doctype_token(None, None, Some(c)); } } } State::DoctypeSystemIdentifierDoubleQuoted => { // Consume the next input character: match self.consume_next_char() { // U+0027 APOSTROPHE (') // Switch to the after DOCTYPE system identifier state. Some(c @ '"') => { self.append_raw_to_doctype_token(c); self.state = State::AfterDoctypeSystemIdentifier; } // U+003E GREATER-THAN SIGN (>) // Parse error. Switch to data state. Emit current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.emit_error(ErrorKind::AbruptDoctypeSystemIdentifier); self.state = State::Data; self.emit_doctype_token(); } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Append the current input character to the current DOCTYPE token's system // identifier. Some(c) => { self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); self.append_to_doctype_token(None, None, Some(c)); } } } State::AfterDoctypeSystemIdentifier => { // Consume the next input character: match self.consume_next_char() { // U+0009 CHARACTER TABULATION (tab) // U+000A LINE FEED (LF) // U+000C FORM FEED (FF) // U+0020 SPACE // Ignore the character. Some(c) if is_whitespace(c) => { self.append_raw_to_doctype_token(c); } // U+003E GREATER-THAN SIGN (>) // Switch to the data state. Emit the current DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.state = State::Data; self.emit_doctype_token(); } // U+005B LEFT SQUARE BRACKET ([) // Switch to the doctype internal subset state. Some(c @ '[') => { self.append_raw_to_doctype_token(c); self.state = State::DoctypeTypeInternalSubSet; } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Parse error. Switch to Bogus DOCTYPE state. Some(c) => { self.validate_input_stream_character(c); self.emit_error(ErrorKind::UnexpectedCharacterAfterDoctypeSystemIdentifier); self.state = State::BogusDoctype; } } } State::DoctypeTypeInternalSubSet => { // Consume the next input character: match self.consume_next_char() { // U+005D RIGHT SQUARE BRACKET (]) // Switch to the CDATA bracket state. Some(c @ ']') => { self.append_raw_to_doctype_token(c); self.state = State::AfterDoctypeName; } // EOF // Parse error. Switch to the data state. Emit DOCTYPE token. Reconsume the EOF // character. None => { self.emit_error(ErrorKind::EofInDoctype); self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Append the current input character to the current DOCTYPE token's system // identifier. Some(c) => { // TODO improve parse legacy declarations self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); } } } State::BogusDoctype => { // Consume the next input character: match self.consume_next_char() { // U+003E GREATER-THAN SIGN(>) // Switch to data state. Emit DOCTYPE token. Some(c @ '>') => { self.append_raw_to_doctype_token(c); self.state = State::Data; self.emit_doctype_token(); } // EOF // Switch to the data state. Emit DOCTYPE token. Reconsume the EOF character. None => { self.state = State::Data; self.emit_doctype_token(); self.reconsume(); } // Anything else // Ignore the character. Some(c) => { self.validate_input_stream_character(c); self.append_raw_to_doctype_token(c); } } } } Ok(()) } #[inline(always)] fn skip_next_lf(&mut self, c: char) { if c == '\r' && self.input.cur() == Some('\n') { unsafe { // Safety: cur() is Some('\n') self.input.bump(); } } } } // S ::= // (#x20 | #x9 | #xD | #xA)+ #[inline(always)] fn is_whitespace(c: char) -> bool { matches!(c, '\x20' | '\x09' | '\x0d' | '\x0a') } #[inline(always)] fn is_control(c: u32) -> bool { matches!(c, c @ 0x00..=0x1f | c @ 0x7f..=0x9f if !matches!(c, 0x09 | 0x0a | 0x0c | 0x0d | 0x20)) } #[inline(always)] fn is_surrogate(c: u32) -> bool { matches!(c, 0xd800..=0xdfff) } // A noncharacter is a code point that is in the range U+FDD0 to U+FDEF, // inclusive, or U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, U+2FFFF, U+3FFFE, // U+3FFFF, U+4FFFE, U+4FFFF, U+5FFFE, U+5FFFF, U+6FFFE, U+6FFFF, U+7FFFE, // U+7FFFF, U+8FFFE, U+8FFFF, U+9FFFE, U+9FFFF, U+AFFFE, U+AFFFF, U+BFFFE, // U+BFFFF, U+CFFFE, U+CFFFF, U+DFFFE, U+DFFFF, U+EFFFE, U+EFFFF, U+FFFFE, // U+FFFFF, U+10FFFE, or U+10FFFF. #[inline(always)] fn is_noncharacter(c: u32) -> bool { matches!( c, 0xfdd0 ..=0xfdef | 0xfffe | 0xffff | 0x1fffe | 0x1ffff | 0x2fffe | 0x2ffff | 0x3fffe | 0x3ffff | 0x4fffe | 0x4ffff | 0x5fffe | 0x5ffff | 0x6fffe | 0x6ffff | 0x7fffe | 0x7ffff | 0x8fffe | 0x8ffff | 0x9fffe | 0x9ffff | 0xafffe | 0xaffff | 0xbfffe | 0xbffff | 0xcfffe | 0xcffff | 0xdfffe | 0xdffff | 0xefffe | 0xeffff | 0xffffe | 0xfffff | 0x10fffe | 0x10ffff, ) } #[inline(always)] fn is_ascii_upper_alpha(c: char) -> bool { c.is_ascii_uppercase() } #[inline(always)] fn is_upper_hex_digit(c: char) -> bool { matches!(c, '0'..='9' | 'A'..='F') } #[inline(always)] fn is_lower_hex_digit(c: char) -> bool { matches!(c, '0'..='9' | 'a'..='f') } // NameStartChar ::= // ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | // [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | // [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | // [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] #[inline(always)] fn is_name_start_char(c: char) -> bool { match c { ':' | 'A'..='Z' | '_' | 'a'..='z' => true, _ if matches!(c as u32, 0xc0..=0xd6 | 0xd8..=0x2ff | 0x370..=0x37d | 0x37f..=0x1fff | 0x200c..=0x200d | 0x2070..=0x218f | 0x2c00..=0x2fef | 0x3001..=0xd7ff | 0xf900..=0xfdcf | 0xfdf0..=0xfffd | 0x10000..=0xeffff) => { true } _ => false, } } // NameChar ::= // NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | // [#x203F-#x2040] #[inline(always)] fn is_name_char(c: char) -> bool { match c { '-' | '.' | '0'..='9' => true, _ if matches!(c as u32, 0xb7 | 0x0300..=0x036f | 0x203f..=0x2040) => true, _ if is_name_start_char(c) => true, _ => false, } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/lib.rs
Rust
#![cfg_attr(docsrs, feature(doc_cfg))] #![deny(unused_must_use)] #![deny(clippy::all)] #![allow(clippy::needless_return)] #![allow(clippy::nonminimal_bool)] #![allow(clippy::wrong_self_convention)] use swc_common::{input::StringInput, SourceFile}; use swc_xml_ast::Document; use crate::{ error::Error, lexer::Lexer, parser::{PResult, Parser, ParserConfig}, }; pub mod error; pub mod lexer; pub mod parser; /// Parse a given file as `Document`. /// /// If there are syntax errors but if it was recoverable, it will be appended to /// `errors`. pub fn parse_file_as_document( fm: &SourceFile, config: ParserConfig, errors: &mut Vec<Error>, ) -> PResult<Document> { let lexer = Lexer::new(StringInput::from(fm)); let mut parser = Parser::new(lexer, config); let result = parser.parse_document(); errors.extend(parser.take_errors()); result }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/parser/input.rs
Rust
use std::{fmt::Debug, mem::take}; use swc_common::{BytePos, Span}; use swc_xml_ast::{Token, TokenAndSpan}; use super::PResult; use crate::error::Error; pub trait ParserInput: Iterator<Item = TokenAndSpan> { fn start_pos(&mut self) -> BytePos; fn last_pos(&mut self) -> BytePos; fn take_errors(&mut self) -> Vec<Error>; } #[derive(Debug)] pub(super) struct Buffer<I> where I: ParserInput, { cur: Option<TokenAndSpan>, input: I, } impl<I> Buffer<I> where I: ParserInput, { pub fn new(input: I) -> Self { Buffer { cur: None, input } } /// Last start position pub fn start_pos(&mut self) -> PResult<BytePos> { Ok(self.input.start_pos()) } /// Last end position pub fn last_pos(&mut self) -> PResult<BytePos> { Ok(self.input.last_pos()) } pub fn cur_span(&mut self) -> PResult<Span> { if self.cur.is_none() { self.bump_inner()?; } Ok(self.cur.as_ref().map(|cur| cur.span).unwrap_or_default()) } pub fn cur(&mut self) -> PResult<Option<&Token>> { if self.cur.is_none() { self.bump_inner()?; } Ok(self.cur.as_ref().map(|v| &v.token)) } #[track_caller] pub fn bump(&mut self) -> PResult<Option<TokenAndSpan>> { debug_assert!( self.cur.is_some(), "bump() is called without checking current token" ); let token = self.cur.take(); Ok(token) } fn bump_inner(&mut self) -> PResult<()> { self.cur = None; if self.cur.is_none() { let result = self.input.next(); if let Some(result) = result { self.cur = Some(result); } else { return Ok(()); } } Ok(()) } pub fn take_errors(&mut self) -> Vec<Error> { take(&mut self.input.take_errors()) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/parser/macros.rs
Rust
macro_rules! span { ($parser:expr, $start:expr) => {{ let last_pos = $parser.input.last_pos()?; swc_common::Span::new($start, last_pos) }}; } macro_rules! bump { ($parser:expr) => { $parser.input.bump()?.unwrap().token }; } macro_rules! get_tag_name { ($node:expr) => {{ match &$node.data { crate::parser::Data::Element { tag_name, .. } => tag_name.as_ref(), _ => { unreachable!(); } } }}; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/parser/mod.rs
Rust
use std::{cell::RefCell, mem, rc::Rc}; use node::*; use open_elements_stack::*; use swc_common::{Span, DUMMY_SP}; use swc_xml_ast::*; use self::input::{Buffer, ParserInput}; use crate::error::{Error, ErrorKind}; #[macro_use] mod macros; pub mod input; mod node; mod open_elements_stack; pub type PResult<T> = Result<T, Error>; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ParserConfig {} #[derive(Debug, Default)] pub enum Phase { #[default] StartPhase, MainPhase, EndPhase, } pub struct Parser<I> where I: ParserInput, { #[allow(dead_code)] config: ParserConfig, input: Buffer<I>, stopped: bool, document: Option<RcNode>, open_elements_stack: OpenElementsStack, errors: Vec<Error>, phase: Phase, } impl<I> Parser<I> where I: ParserInput, { pub fn new(input: I, config: ParserConfig) -> Self { Parser { config, input: Buffer::new(input), stopped: false, document: None, open_elements_stack: OpenElementsStack::new(), errors: Default::default(), phase: Phase::default(), } } pub fn dump_cur(&mut self) -> String { format!("{:?}", self.input.cur()) } pub fn take_errors(&mut self) -> Vec<Error> { mem::take(&mut self.errors) } pub fn parse_document(&mut self) -> PResult<Document> { let start = self.input.cur_span()?; self.document = Some(self.create_document()); self.run()?; let document = &mut self.document.take().unwrap(); let nodes = document.children.take(); let mut children = Vec::with_capacity(nodes.len()); for node in nodes { children.push(self.node_to_child(node)); } let last = self.input.last_pos()?; Ok(Document { span: Span::new(start.lo(), last), children, }) } fn create_document(&self) -> RcNode { Node::new(Data::Document, DUMMY_SP) } #[allow(clippy::only_used_in_recursion)] fn get_deep_end_span(&mut self, children: &[Child]) -> Option<Span> { match children.last() { Some(Child::DocumentType(DocumentType { span, .. })) => Some(*span), Some(Child::Element(Element { span, children, .. })) => { if span.is_dummy() { return self.get_deep_end_span(children); } Some(*span) } Some(Child::Comment(Comment { span, .. })) => Some(*span), Some(Child::Text(Text { span, .. })) => Some(*span), _ => None, } } fn node_to_child(&mut self, node: RcNode) -> Child { let start_span = node.start_span.take(); match node.data.clone() { Data::DocumentType { name, public_id, system_id, raw, } => Child::DocumentType(DocumentType { span: start_span, name, public_id, system_id, raw, }), Data::Element { tag_name, attributes, } => { let nodes = node.children.take(); let mut new_children = Vec::with_capacity(nodes.len()); for node in nodes { new_children.push(self.node_to_child(node)); } let attributes = attributes.take(); let span = if start_span.is_dummy() { start_span } else { let end_span = match node.end_span.take() { Some(end_span) if !end_span.is_dummy() => end_span, _ => match self.get_deep_end_span(&new_children) { Some(end_span) => end_span, _ => start_span, }, }; Span::new(start_span.lo(), end_span.hi()) }; Child::Element(Element { span, tag_name, attributes, children: new_children, }) } Data::Text { data, raw } => { let span = if let Some(end_span) = node.end_span.take() { swc_common::Span::new(start_span.lo(), end_span.hi()) } else { start_span }; Child::Text(Text { span, data: data.take().into(), raw: Some(raw.take().into()), }) } Data::Comment { data, raw } => Child::Comment(Comment { span: start_span, data, raw, }), Data::ProcessingInstruction { target, data } => { Child::ProcessingInstruction(ProcessingInstruction { span: start_span, target, data, }) } Data::CdataSection { data, raw } => Child::CdataSection(CdataSection { span: start_span, data, raw, }), _ => { unreachable!(); } } } fn run(&mut self) -> PResult<()> { while !self.stopped { let mut token_and_info = match self.input.cur()? { Some(_) => { let span = self.input.cur_span()?; let token = bump!(self); TokenAndInfo { span: span!(self, span.lo()), acknowledged: false, token, } } None => { let start_pos = self.input.start_pos()?; let last_pos = self.input.last_pos()?; TokenAndInfo { span: Span::new(start_pos, last_pos), acknowledged: false, token: Token::Eof, } } }; // Re-emit errors from tokenizer for error in self.input.take_errors() { let (span, kind) = *error.into_inner(); self.errors.push(Error::new(span, kind)); } self.tree_construction_dispatcher(&mut token_and_info)?; } Ok(()) } fn tree_construction_dispatcher(&mut self, token_and_info: &mut TokenAndInfo) -> PResult<()> { self.process_token(token_and_info, None) } fn process_token( &mut self, token_and_info: &mut TokenAndInfo, phase: Option<Phase>, ) -> PResult<()> { let phase = match &phase { Some(phase) => phase, _ => &self.phase, }; match phase { Phase::StartPhase => match &token_and_info.token { Token::StartTag { .. } => { let element = self.create_element_for_token(token_and_info.clone()); self.append_node(self.document.as_ref().unwrap(), element.clone()); self.open_elements_stack.items.push(element); self.phase = Phase::MainPhase; } Token::EmptyTag { .. } => { let element = self.create_element_for_token(token_and_info.clone()); self.append_node(self.document.as_ref().unwrap(), element); self.phase = Phase::EndPhase; } Token::Comment { .. } => { self.append_comment_to_doc(token_and_info)?; } Token::ProcessingInstruction { .. } => { self.append_processing_instruction_to_doc(token_and_info)?; } Token::Cdata { .. } => { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedTokenInStartPhase, )); self.append_cdata_to_doc(token_and_info)?; } Token::Character { value, .. } => { if !is_whitespace(*value) { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedCharacter, )); } } Token::Eof => { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedEofInStartPhase, )); self.process_token(token_and_info, Some(Phase::EndPhase))?; } Token::Doctype { .. } => { let document_type = self.create_document_type_for_token(token_and_info); self.append_node(self.document.as_ref().unwrap(), document_type); } _ => { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedTokenInStartPhase, )); } }, Phase::MainPhase => match &token_and_info.token { Token::Character { .. } => { self.append_character_to_current_element(token_and_info)?; } Token::StartTag { .. } => { let element = self.create_element_for_token(token_and_info.clone()); self.append_node(self.get_current_element(), element.clone()); self.open_elements_stack.items.push(element); } Token::EmptyTag { .. } => { let element = self.create_element_for_token(token_and_info.clone()); self.append_node(self.get_current_element(), element); } Token::EndTag { tag_name, .. } => { if get_tag_name!(self.get_current_element()) != tag_name { self.errors.push(Error::new( token_and_info.span, ErrorKind::OpeningAndEndingTagMismatch, )); } let is_closed = self .open_elements_stack .items .iter() .rev() .any(|node| get_tag_name!(node) == tag_name); if is_closed { let popped = self .open_elements_stack .pop_until_tag_name_popped(&[tag_name]); self.update_end_tag_span(popped.as_ref(), token_and_info.span); } if self.open_elements_stack.items.is_empty() { self.phase = Phase::EndPhase; } } Token::Comment { .. } => { let comment = self.create_comment(token_and_info); self.append_node(self.get_current_element(), comment); } Token::ProcessingInstruction { .. } => { let processing_instruction = self.create_processing_instruction(token_and_info); self.append_node(self.get_current_element(), processing_instruction); } Token::Cdata { .. } => { let cdata = self.create_cdata_section(token_and_info); self.append_node(self.get_current_element(), cdata); } Token::Eof => { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedEofInMainPhase, )); self.process_token(token_and_info, Some(Phase::EndPhase))?; } _ => { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedTokenInMainPhase, )); } }, Phase::EndPhase => match &token_and_info.token { Token::Comment { .. } => { self.append_comment_to_doc(token_and_info)?; } Token::ProcessingInstruction { .. } => { self.append_processing_instruction_to_doc(token_and_info)?; } Token::Cdata { .. } => { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedTokenInEndPhase, )); self.append_cdata_to_doc(token_and_info)?; } Token::Character { value, .. } => { if !is_whitespace(*value) { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedCharacter, )); } } Token::Eof => { self.stopped = true; } _ => { self.errors.push(Error::new( token_and_info.span, ErrorKind::UnexpectedTokenInEndPhase, )); } }, } Ok(()) } fn append_node(&self, parent: &RcNode, child: RcNode) { let previous_parent = child.parent.replace(Some(Rc::downgrade(parent))); // Invariant: child cannot have existing parent assert!(previous_parent.is_none()); parent.children.borrow_mut().push(child); } fn get_current_element(&self) -> &RcNode { self.open_elements_stack .items .last() .expect("no current element") } fn create_document_type_for_token(&self, token_and_info: &mut TokenAndInfo) -> RcNode { let (name, public_id, system_id, raw) = match &token_and_info.token { Token::Doctype { name, public_id, system_id, raw, } => ( name.clone(), public_id.clone(), system_id.clone(), raw.clone(), ), _ => { unreachable!() } }; Node::new( Data::DocumentType { name, public_id, system_id, raw, }, token_and_info.span, ) } fn create_element_for_token(&self, token_and_info: TokenAndInfo) -> RcNode { let element = match token_and_info.token { Token::StartTag { tag_name, attributes, .. } | Token::EndTag { tag_name, attributes, .. } | Token::EmptyTag { tag_name, attributes, .. } => { let attributes = attributes .into_iter() .map(|attribute_token| Attribute { span: attribute_token.span, namespace: None, prefix: None, name: attribute_token.name, raw_name: attribute_token.raw_name, value: attribute_token.value, raw_value: attribute_token.raw_value, }) .collect(); Data::Element { tag_name, attributes: RefCell::new(attributes), } } _ => { unreachable!(); } }; Node::new(element, token_and_info.span) } fn append_character_to_current_element( &mut self, token_and_info: &mut TokenAndInfo, ) -> PResult<()> { if let Some(last) = self.open_elements_stack.items.last() { let children = last.children.borrow(); if let Some(last) = children.last() { if let Data::Text { data, raw: raw_data, } = &last.data { match &token_and_info.token { Token::Character { value: c, raw: raw_c, } => { data.borrow_mut().push(*c); if let Some(raw_c) = raw_c { raw_data.borrow_mut().push_str(raw_c); } } _ => { unreachable!(); } } let mut span = last.end_span.borrow_mut(); *span = Some(token_and_info.span); return Ok(()); } } } let (data, raw) = match &token_and_info.token { Token::Character { value: c, raw: raw_c, } => { let mut data = String::with_capacity(255); data.push(*c); let mut raw = String::with_capacity(255); if let Some(raw_c) = raw_c { raw.push_str(raw_c); } (RefCell::new(data), RefCell::new(raw)) } _ => { unreachable!() } }; let text = Node::new(Data::Text { data, raw }, token_and_info.span); self.append_node(self.get_current_element(), text); Ok(()) } fn create_comment(&self, token_and_info: &mut TokenAndInfo) -> RcNode { let (data, raw) = match &token_and_info.token { Token::Comment { data, raw } => (data.clone(), Some(raw.clone())), _ => { unreachable!() } }; Node::new(Data::Comment { data, raw }, token_and_info.span) } fn append_comment_to_doc(&mut self, token_and_info: &mut TokenAndInfo) -> PResult<()> { let comment = self.create_comment(token_and_info); self.append_node(self.document.as_ref().unwrap(), comment); Ok(()) } fn create_processing_instruction(&self, token_and_info: &mut TokenAndInfo) -> RcNode { let (target, data) = match &token_and_info.token { Token::ProcessingInstruction { target, data } => (target.clone(), data.clone()), _ => { unreachable!() } }; Node::new( Data::ProcessingInstruction { target, data }, token_and_info.span, ) } fn append_processing_instruction_to_doc( &mut self, token_and_info: &mut TokenAndInfo, ) -> PResult<()> { let child = self.create_processing_instruction(token_and_info); self.append_node(self.document.as_ref().unwrap(), child); Ok(()) } fn create_cdata_section(&self, token_and_info: &mut TokenAndInfo) -> RcNode { let (data, raw) = match &token_and_info.token { Token::Cdata { data, raw } => (data.clone(), Some(raw.clone())), _ => { unreachable!() } }; Node::new(Data::CdataSection { data, raw }, token_and_info.span) } fn append_cdata_to_doc(&mut self, token_and_info: &mut TokenAndInfo) -> PResult<()> { let child = self.create_cdata_section(token_and_info); self.append_node(self.document.as_ref().unwrap(), child); Ok(()) } fn update_end_tag_span(&self, node: Option<&RcNode>, span: Span) { if let Some(node) = node { if node.start_span.borrow().is_dummy() { return; } let mut end_tag_span = node.end_span.borrow_mut(); *end_tag_span = Some(span); } } } fn is_whitespace(c: char) -> bool { matches!(c, '\t' | '\r' | '\n' | '\x0C' | ' ') }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/parser/node.rs
Rust
#![allow(dead_code)] use std::{ cell::{Cell, RefCell}, fmt, mem, rc::{Rc, Weak}, }; use swc_atoms::Atom; use swc_common::Span; use swc_xml_ast::*; #[derive(Debug, Clone)] pub struct TokenAndInfo { pub span: Span, pub acknowledged: bool, pub token: Token, } #[derive(Debug, Clone)] pub enum Data { Document, DocumentType { name: Option<Atom>, public_id: Option<Atom>, system_id: Option<Atom>, raw: Option<Atom>, }, Element { tag_name: Atom, attributes: RefCell<Vec<Attribute>>, }, Text { data: RefCell<String>, raw: RefCell<String>, }, ProcessingInstruction { target: Atom, data: Atom, }, CdataSection { data: Atom, raw: Option<Atom>, }, Comment { data: Atom, raw: Option<Atom>, }, } pub struct Node { pub parent: Cell<Option<WeakNode>>, pub children: RefCell<Vec<RcNode>>, pub data: Data, pub start_span: RefCell<Span>, pub end_span: RefCell<Option<Span>>, } impl Node { /// Create a new node from its contents pub fn new(data: Data, span: Span) -> Rc<Self> { Rc::new(Node { parent: Cell::new(None), children: RefCell::new(Vec::new()), start_span: RefCell::new(span), end_span: RefCell::new(None), data, }) } } impl Drop for Node { fn drop(&mut self) { let mut nodes = mem::take(&mut *self.children.borrow_mut()); while let Some(node) = nodes.pop() { let children = mem::take(&mut *node.children.borrow_mut()); nodes.extend(children); } } } impl fmt::Debug for Node { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Node") .field("data", &self.data) .field("children", &self.children) .finish() } } pub type RcNode = Rc<Node>; type WeakNode = Weak<Node>;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/src/parser/open_elements_stack.rs
Rust
use crate::parser::RcNode; pub struct OpenElementsStack { pub items: Vec<RcNode>, } impl OpenElementsStack { pub fn new() -> Self { OpenElementsStack { items: Vec::with_capacity(16), } } pub fn pop_until_tag_name_popped(&mut self, tag_name: &[&str]) -> Option<RcNode> { while let Some(node) = self.items.pop() { if tag_name.contains(&get_tag_name!(node)) { return Some(node); } } None } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_parser/tests/fixture.rs
Rust
#![deny(warnings)] #![allow(clippy::if_same_then_else)] #![allow(clippy::needless_update)] #![allow(clippy::redundant_clone)] #![allow(clippy::while_let_on_iterator)] use std::path::PathBuf; use swc_common::{errors::Handler, input::SourceFileInput, Spanned}; use swc_xml_ast::*; use swc_xml_parser::{ lexer::Lexer, parser::{PResult, Parser, ParserConfig}, }; use swc_xml_visit::{Visit, VisitMut, VisitMutWith, VisitWith}; use testing::NormalizedOutput; fn document_test(input: PathBuf, config: ParserConfig) { testing::run_test2(false, |cm, handler| { let json_path = input.parent().unwrap().join("output.json"); let fm = cm.load_file(&input).unwrap(); let lexer = Lexer::new(SourceFileInput::from(&*fm)); let mut parser = Parser::new(lexer, config); let document: PResult<Document> = parser.parse_document(); let errors = parser.take_errors(); for err in &errors { err.to_diagnostics(&handler).emit(); } if !errors.is_empty() { return Err(()); } match document { Ok(document) => { let actual_json = serde_json::to_string_pretty(&document) .map(NormalizedOutput::from) .expect("failed to serialize document"); actual_json.compare_to_file(json_path).unwrap(); Ok(()) } Err(err) => { let mut d = err.to_diagnostics(&handler); d.note(&format!("current token = {}", parser.dump_cur())); d.emit(); Err(()) } } }) .unwrap(); } fn document_recovery_test(input: PathBuf, config: ParserConfig) { let stderr_path = input.parent().unwrap().join("output.swc-stderr"); let mut recovered = false; let stderr = testing::run_test2(false, |cm, handler| { // Type annotation if false { return Ok(()); } let json_path = input.parent().unwrap().join("output.json"); let fm = cm.load_file(&input).unwrap(); let lexer = Lexer::new(SourceFileInput::from(&*fm)); let mut parser = Parser::new(lexer, config); let document: PResult<Document> = parser.parse_document(); let errors = parser.take_errors(); for err in &errors { err.to_diagnostics(&handler).emit(); } if !errors.is_empty() { recovered = true; } match document { Ok(document) => { let actual_json = serde_json::to_string_pretty(&document) .map(NormalizedOutput::from) .expect("failed to serialize document"); actual_json.compare_to_file(json_path).unwrap(); Err(()) } Err(err) => { let mut d = err.to_diagnostics(&handler); d.note(&format!("current token = {}", parser.dump_cur())); d.emit(); Err(()) } } }) .unwrap_err(); if !recovered { panic!( "Parser should emit errors (recover mode), but parser parsed everything successfully \ {}", stderr ); } stderr.compare_to_file(stderr_path).unwrap(); } fn document_span_visualizer(input: PathBuf, config: ParserConfig) { let dir = input.parent().unwrap().to_path_buf(); let output = testing::run_test2(false, |cm, handler| { // Type annotation if false { return Ok(()); } let fm = cm.load_file(&input).unwrap(); let lexer = Lexer::new(SourceFileInput::from(&*fm)); let mut parser = Parser::new(lexer, config); let document: PResult<Document> = parser.parse_document(); match document { Ok(document) => { document.visit_with(&mut SpanVisualizer { handler: &handler }); Err(()) } Err(err) => { let mut d = err.to_diagnostics(&handler); d.note(&format!("current token = {}", parser.dump_cur())); d.emit(); panic!(); } } }) .unwrap_err(); output.compare_to_file(dir.join("span.swc-stderr")).unwrap(); } fn document_dom_visualizer(input: PathBuf, config: ParserConfig) { let dir = input.parent().unwrap().to_path_buf(); testing::run_test2(false, |cm, handler| { // Type annotation if false { return Ok(()); } let fm = cm.load_file(&input).unwrap(); let lexer = Lexer::new(SourceFileInput::from(&*fm)); let mut parser = Parser::new(lexer, config); let document: PResult<Document> = parser.parse_document(); match document { Ok(mut document) => { let mut dom_buf = String::new(); document.visit_mut_with(&mut DomVisualizer { dom_buf: &mut dom_buf, indent: 0, }); NormalizedOutput::from(dom_buf) .compare_to_file(dir.join("dom.txt")) .unwrap(); Ok(()) } Err(err) => { let mut d = err.to_diagnostics(&handler); d.note(&format!("current token = {}", parser.dump_cur())); d.emit(); panic!(); } } }) .unwrap(); } struct SpanVisualizer<'a> { handler: &'a Handler, } macro_rules! mtd { ($T:ty,$name:ident) => { fn $name(&mut self, n: &$T) { let span = n.span(); self.handler.struct_span_err(span, stringify!($T)).emit(); n.visit_children_with(self); } }; } impl Visit for SpanVisualizer<'_> { mtd!(Document, visit_document); mtd!(Child, visit_child); mtd!(DocumentType, visit_document_type); mtd!(Element, visit_element); mtd!(Attribute, visit_attribute); mtd!(Text, visit_text); mtd!(ProcessingInstruction, visit_processing_instruction); mtd!(Comment, visit_comment); } struct DomVisualizer<'a> { dom_buf: &'a mut String, indent: usize, } impl DomVisualizer<'_> { fn get_ident(&self) -> String { let mut indent = String::new(); indent.push_str("| "); indent.push_str(&" ".repeat(self.indent)); indent } } impl VisitMut for DomVisualizer<'_> { fn visit_mut_document_type(&mut self, n: &mut DocumentType) { let mut document_type = String::new(); document_type.push_str(&self.get_ident()); document_type.push_str("<!DOCTYPE "); if let Some(name) = &n.name { document_type.push_str(name); } if let Some(public_id) = &n.public_id { document_type.push(' '); document_type.push('"'); document_type.push_str(public_id); document_type.push('"'); if let Some(system_id) = &n.system_id { document_type.push(' '); document_type.push('"'); document_type.push_str(system_id); document_type.push('"'); } else { document_type.push(' '); document_type.push('"'); document_type.push('"'); } } else if let Some(system_id) = &n.system_id { document_type.push(' '); document_type.push('"'); document_type.push('"'); document_type.push(' '); document_type.push('"'); document_type.push_str(system_id); document_type.push('"'); } document_type.push('>'); document_type.push('\n'); self.dom_buf.push_str(&document_type); n.visit_mut_children_with(self); } fn visit_mut_element(&mut self, n: &mut Element) { let mut element = String::new(); element.push_str(&self.get_ident()); element.push('<'); element.push_str(&n.tag_name); element.push('>'); element.push('\n'); n.attributes .sort_by(|a, b| a.name.partial_cmp(&b.name).unwrap()); self.dom_buf.push_str(&element); let old_indent = self.indent; self.indent += 1; n.visit_mut_children_with(self); self.indent = old_indent; } fn visit_mut_attribute(&mut self, n: &mut Attribute) { let mut attribute = String::new(); attribute.push_str(&self.get_ident()); if let Some(prefix) = &n.prefix { attribute.push_str(prefix); attribute.push(' '); } attribute.push_str(&n.name); attribute.push('='); attribute.push('"'); if let Some(value) = &n.value { attribute.push_str(value); } attribute.push('"'); attribute.push('\n'); self.dom_buf.push_str(&attribute); n.visit_mut_children_with(self); } fn visit_mut_text(&mut self, n: &mut Text) { let mut text = String::new(); text.push_str(&self.get_ident()); text.push('"'); text.push_str(&n.data); text.push('"'); text.push('\n'); self.dom_buf.push_str(&text); n.visit_mut_children_with(self); } fn visit_mut_comment(&mut self, n: &mut Comment) { let mut comment = String::new(); comment.push_str(&self.get_ident()); comment.push_str("<!-- "); comment.push_str(&n.data); comment.push_str(" -->"); comment.push('\n'); self.dom_buf.push_str(&comment); n.visit_mut_children_with(self); } fn visit_mut_processing_instruction(&mut self, n: &mut ProcessingInstruction) { let mut processing_instruction = String::new(); processing_instruction.push_str("<?"); processing_instruction.push_str(&n.target); processing_instruction.push(' '); processing_instruction.push_str(&n.data); processing_instruction.push('>'); processing_instruction.push('\n'); self.dom_buf.push_str(&processing_instruction); n.visit_mut_children_with(self); } } #[testing::fixture("tests/fixture/**/*.xml")] fn pass(input: PathBuf) { document_test(input, Default::default()) } #[testing::fixture("tests/recovery/**/*.xml")] fn recovery(input: PathBuf) { document_recovery_test(input, Default::default()) } #[testing::fixture("tests/fixture/**/*.xml")] #[testing::fixture("tests/recovery/**/*.xml")] fn span_visualizer(input: PathBuf) { document_span_visualizer(input, Default::default()) } #[testing::fixture("tests/fixture/**/*.xml")] #[testing::fixture("tests/recovery/**/*.xml")] fn dom_visualizer(input: PathBuf) { document_dom_visualizer(input, Default::default()) } // TODO tests from xml5lib-tests
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_visit/src/generated.rs
Rust
#![doc = r" This file is generated by `tools/generate-code`. DO NOT MODIFY."] #![allow(unused_variables)] #![allow(clippy::all)] pub use ::swc_visit::All; use swc_xml_ast::*; #[doc = r" A visitor trait for traversing the AST."] pub trait Visit { #[doc = "Visit a node of type `swc_atoms :: Atom`.\n\nBy default, this method calls \ [`swc_atoms :: Atom::visit_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_atom(&mut self, node: &swc_atoms::Atom) { <swc_atoms::Atom as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Attribute`.\n\nBy default, this method calls \ [`Attribute::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_attribute(&mut self, node: &Attribute) { <Attribute as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `AttributeToken`.\n\nBy default, this method calls \ [`AttributeToken::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_attribute_token(&mut self, node: &AttributeToken) { <AttributeToken as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Vec < AttributeToken >`.\n\nBy default, this method calls [`Vec \ < AttributeToken >::visit_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_attribute_tokens(&mut self, node: &[AttributeToken]) { <[AttributeToken] as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Vec < Attribute >`.\n\nBy default, this method calls [`Vec < \ Attribute >::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_attributes(&mut self, node: &[Attribute]) { <[Attribute] as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `CdataSection`.\n\nBy default, this method calls \ [`CdataSection::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_cdata_section(&mut self, node: &CdataSection) { <CdataSection as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Child`.\n\nBy default, this method calls \ [`Child::visit_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn visit_child(&mut self, node: &Child) { <Child as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Vec < Child >`.\n\nBy default, this method calls [`Vec < Child \ >::visit_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn visit_childs(&mut self, node: &[Child]) { <[Child] as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Comment`.\n\nBy default, this method calls \ [`Comment::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_comment(&mut self, node: &Comment) { <Comment as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Document`.\n\nBy default, this method calls \ [`Document::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_document(&mut self, node: &Document) { <Document as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `DocumentMode`.\n\nBy default, this method calls \ [`DocumentMode::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_document_mode(&mut self, node: &DocumentMode) { <DocumentMode as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `DocumentType`.\n\nBy default, this method calls \ [`DocumentType::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_document_type(&mut self, node: &DocumentType) { <DocumentType as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Element`.\n\nBy default, this method calls \ [`Element::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_element(&mut self, node: &Element) { <Element as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Namespace`.\n\nBy default, this method calls \ [`Namespace::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_namespace(&mut self, node: &Namespace) { <Namespace as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Option < swc_atoms :: Atom >`.\n\nBy default, this method calls \ [`Option < swc_atoms :: Atom >::visit_children_with`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_opt_atom(&mut self, node: &Option<swc_atoms::Atom>) { <Option<swc_atoms::Atom> as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Option < Namespace >`.\n\nBy default, this method calls \ [`Option < Namespace >::visit_children_with`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_opt_namespace(&mut self, node: &Option<Namespace>) { <Option<Namespace> as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `ProcessingInstruction`.\n\nBy default, this method calls \ [`ProcessingInstruction::visit_children_with`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_processing_instruction(&mut self, node: &ProcessingInstruction) { <ProcessingInstruction as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `swc_common :: Span`.\n\nBy default, this method calls \ [`swc_common :: Span::visit_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_span(&mut self, node: &swc_common::Span) { <swc_common::Span as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Text`.\n\nBy default, this method calls \ [`Text::visit_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn visit_text(&mut self, node: &Text) { <Text as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `Token`.\n\nBy default, this method calls \ [`Token::visit_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn visit_token(&mut self, node: &Token) { <Token as VisitWith<Self>>::visit_children_with(node, self) } #[doc = "Visit a node of type `TokenAndSpan`.\n\nBy default, this method calls \ [`TokenAndSpan::visit_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_token_and_span(&mut self, node: &TokenAndSpan) { <TokenAndSpan as VisitWith<Self>>::visit_children_with(node, self) } } impl<V> Visit for &mut V where V: ?Sized + Visit, { #[inline] fn visit_atom(&mut self, node: &swc_atoms::Atom) { <V as Visit>::visit_atom(&mut **self, node) } #[inline] fn visit_attribute(&mut self, node: &Attribute) { <V as Visit>::visit_attribute(&mut **self, node) } #[inline] fn visit_attribute_token(&mut self, node: &AttributeToken) { <V as Visit>::visit_attribute_token(&mut **self, node) } #[inline] fn visit_attribute_tokens(&mut self, node: &[AttributeToken]) { <V as Visit>::visit_attribute_tokens(&mut **self, node) } #[inline] fn visit_attributes(&mut self, node: &[Attribute]) { <V as Visit>::visit_attributes(&mut **self, node) } #[inline] fn visit_cdata_section(&mut self, node: &CdataSection) { <V as Visit>::visit_cdata_section(&mut **self, node) } #[inline] fn visit_child(&mut self, node: &Child) { <V as Visit>::visit_child(&mut **self, node) } #[inline] fn visit_childs(&mut self, node: &[Child]) { <V as Visit>::visit_childs(&mut **self, node) } #[inline] fn visit_comment(&mut self, node: &Comment) { <V as Visit>::visit_comment(&mut **self, node) } #[inline] fn visit_document(&mut self, node: &Document) { <V as Visit>::visit_document(&mut **self, node) } #[inline] fn visit_document_mode(&mut self, node: &DocumentMode) { <V as Visit>::visit_document_mode(&mut **self, node) } #[inline] fn visit_document_type(&mut self, node: &DocumentType) { <V as Visit>::visit_document_type(&mut **self, node) } #[inline] fn visit_element(&mut self, node: &Element) { <V as Visit>::visit_element(&mut **self, node) } #[inline] fn visit_namespace(&mut self, node: &Namespace) { <V as Visit>::visit_namespace(&mut **self, node) } #[inline] fn visit_opt_atom(&mut self, node: &Option<swc_atoms::Atom>) { <V as Visit>::visit_opt_atom(&mut **self, node) } #[inline] fn visit_opt_namespace(&mut self, node: &Option<Namespace>) { <V as Visit>::visit_opt_namespace(&mut **self, node) } #[inline] fn visit_processing_instruction(&mut self, node: &ProcessingInstruction) { <V as Visit>::visit_processing_instruction(&mut **self, node) } #[inline] fn visit_span(&mut self, node: &swc_common::Span) { <V as Visit>::visit_span(&mut **self, node) } #[inline] fn visit_text(&mut self, node: &Text) { <V as Visit>::visit_text(&mut **self, node) } #[inline] fn visit_token(&mut self, node: &Token) { <V as Visit>::visit_token(&mut **self, node) } #[inline] fn visit_token_and_span(&mut self, node: &TokenAndSpan) { <V as Visit>::visit_token_and_span(&mut **self, node) } } impl<V> Visit for Box<V> where V: ?Sized + Visit, { #[inline] fn visit_atom(&mut self, node: &swc_atoms::Atom) { <V as Visit>::visit_atom(&mut **self, node) } #[inline] fn visit_attribute(&mut self, node: &Attribute) { <V as Visit>::visit_attribute(&mut **self, node) } #[inline] fn visit_attribute_token(&mut self, node: &AttributeToken) { <V as Visit>::visit_attribute_token(&mut **self, node) } #[inline] fn visit_attribute_tokens(&mut self, node: &[AttributeToken]) { <V as Visit>::visit_attribute_tokens(&mut **self, node) } #[inline] fn visit_attributes(&mut self, node: &[Attribute]) { <V as Visit>::visit_attributes(&mut **self, node) } #[inline] fn visit_cdata_section(&mut self, node: &CdataSection) { <V as Visit>::visit_cdata_section(&mut **self, node) } #[inline] fn visit_child(&mut self, node: &Child) { <V as Visit>::visit_child(&mut **self, node) } #[inline] fn visit_childs(&mut self, node: &[Child]) { <V as Visit>::visit_childs(&mut **self, node) } #[inline] fn visit_comment(&mut self, node: &Comment) { <V as Visit>::visit_comment(&mut **self, node) } #[inline] fn visit_document(&mut self, node: &Document) { <V as Visit>::visit_document(&mut **self, node) } #[inline] fn visit_document_mode(&mut self, node: &DocumentMode) { <V as Visit>::visit_document_mode(&mut **self, node) } #[inline] fn visit_document_type(&mut self, node: &DocumentType) { <V as Visit>::visit_document_type(&mut **self, node) } #[inline] fn visit_element(&mut self, node: &Element) { <V as Visit>::visit_element(&mut **self, node) } #[inline] fn visit_namespace(&mut self, node: &Namespace) { <V as Visit>::visit_namespace(&mut **self, node) } #[inline] fn visit_opt_atom(&mut self, node: &Option<swc_atoms::Atom>) { <V as Visit>::visit_opt_atom(&mut **self, node) } #[inline] fn visit_opt_namespace(&mut self, node: &Option<Namespace>) { <V as Visit>::visit_opt_namespace(&mut **self, node) } #[inline] fn visit_processing_instruction(&mut self, node: &ProcessingInstruction) { <V as Visit>::visit_processing_instruction(&mut **self, node) } #[inline] fn visit_span(&mut self, node: &swc_common::Span) { <V as Visit>::visit_span(&mut **self, node) } #[inline] fn visit_text(&mut self, node: &Text) { <V as Visit>::visit_text(&mut **self, node) } #[inline] fn visit_token(&mut self, node: &Token) { <V as Visit>::visit_token(&mut **self, node) } #[inline] fn visit_token_and_span(&mut self, node: &TokenAndSpan) { <V as Visit>::visit_token_and_span(&mut **self, node) } } impl<A, B> Visit for ::swc_visit::Either<A, B> where A: Visit, B: Visit, { #[inline] fn visit_atom(&mut self, node: &swc_atoms::Atom) { match self { swc_visit::Either::Left(visitor) => Visit::visit_atom(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_atom(visitor, node), } } #[inline] fn visit_attribute(&mut self, node: &Attribute) { match self { swc_visit::Either::Left(visitor) => Visit::visit_attribute(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_attribute(visitor, node), } } #[inline] fn visit_attribute_token(&mut self, node: &AttributeToken) { match self { swc_visit::Either::Left(visitor) => Visit::visit_attribute_token(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_attribute_token(visitor, node), } } #[inline] fn visit_attribute_tokens(&mut self, node: &[AttributeToken]) { match self { swc_visit::Either::Left(visitor) => Visit::visit_attribute_tokens(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_attribute_tokens(visitor, node), } } #[inline] fn visit_attributes(&mut self, node: &[Attribute]) { match self { swc_visit::Either::Left(visitor) => Visit::visit_attributes(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_attributes(visitor, node), } } #[inline] fn visit_cdata_section(&mut self, node: &CdataSection) { match self { swc_visit::Either::Left(visitor) => Visit::visit_cdata_section(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_cdata_section(visitor, node), } } #[inline] fn visit_child(&mut self, node: &Child) { match self { swc_visit::Either::Left(visitor) => Visit::visit_child(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_child(visitor, node), } } #[inline] fn visit_childs(&mut self, node: &[Child]) { match self { swc_visit::Either::Left(visitor) => Visit::visit_childs(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_childs(visitor, node), } } #[inline] fn visit_comment(&mut self, node: &Comment) { match self { swc_visit::Either::Left(visitor) => Visit::visit_comment(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_comment(visitor, node), } } #[inline] fn visit_document(&mut self, node: &Document) { match self { swc_visit::Either::Left(visitor) => Visit::visit_document(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_document(visitor, node), } } #[inline] fn visit_document_mode(&mut self, node: &DocumentMode) { match self { swc_visit::Either::Left(visitor) => Visit::visit_document_mode(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_document_mode(visitor, node), } } #[inline] fn visit_document_type(&mut self, node: &DocumentType) { match self { swc_visit::Either::Left(visitor) => Visit::visit_document_type(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_document_type(visitor, node), } } #[inline] fn visit_element(&mut self, node: &Element) { match self { swc_visit::Either::Left(visitor) => Visit::visit_element(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_element(visitor, node), } } #[inline] fn visit_namespace(&mut self, node: &Namespace) { match self { swc_visit::Either::Left(visitor) => Visit::visit_namespace(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_namespace(visitor, node), } } #[inline] fn visit_opt_atom(&mut self, node: &Option<swc_atoms::Atom>) { match self { swc_visit::Either::Left(visitor) => Visit::visit_opt_atom(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_opt_atom(visitor, node), } } #[inline] fn visit_opt_namespace(&mut self, node: &Option<Namespace>) { match self { swc_visit::Either::Left(visitor) => Visit::visit_opt_namespace(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_opt_namespace(visitor, node), } } #[inline] fn visit_processing_instruction(&mut self, node: &ProcessingInstruction) { match self { swc_visit::Either::Left(visitor) => Visit::visit_processing_instruction(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_processing_instruction(visitor, node), } } #[inline] fn visit_span(&mut self, node: &swc_common::Span) { match self { swc_visit::Either::Left(visitor) => Visit::visit_span(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_span(visitor, node), } } #[inline] fn visit_text(&mut self, node: &Text) { match self { swc_visit::Either::Left(visitor) => Visit::visit_text(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_text(visitor, node), } } #[inline] fn visit_token(&mut self, node: &Token) { match self { swc_visit::Either::Left(visitor) => Visit::visit_token(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_token(visitor, node), } } #[inline] fn visit_token_and_span(&mut self, node: &TokenAndSpan) { match self { swc_visit::Either::Left(visitor) => Visit::visit_token_and_span(visitor, node), swc_visit::Either::Right(visitor) => Visit::visit_token_and_span(visitor, node), } } } impl<V> Visit for ::swc_visit::Optional<V> where V: Visit, { #[inline] fn visit_atom(&mut self, node: &swc_atoms::Atom) { if self.enabled { <V as Visit>::visit_atom(&mut self.visitor, node) } else { } } #[inline] fn visit_attribute(&mut self, node: &Attribute) { if self.enabled { <V as Visit>::visit_attribute(&mut self.visitor, node) } else { } } #[inline] fn visit_attribute_token(&mut self, node: &AttributeToken) { if self.enabled { <V as Visit>::visit_attribute_token(&mut self.visitor, node) } else { } } #[inline] fn visit_attribute_tokens(&mut self, node: &[AttributeToken]) { if self.enabled { <V as Visit>::visit_attribute_tokens(&mut self.visitor, node) } else { } } #[inline] fn visit_attributes(&mut self, node: &[Attribute]) { if self.enabled { <V as Visit>::visit_attributes(&mut self.visitor, node) } else { } } #[inline] fn visit_cdata_section(&mut self, node: &CdataSection) { if self.enabled { <V as Visit>::visit_cdata_section(&mut self.visitor, node) } else { } } #[inline] fn visit_child(&mut self, node: &Child) { if self.enabled { <V as Visit>::visit_child(&mut self.visitor, node) } else { } } #[inline] fn visit_childs(&mut self, node: &[Child]) { if self.enabled { <V as Visit>::visit_childs(&mut self.visitor, node) } else { } } #[inline] fn visit_comment(&mut self, node: &Comment) { if self.enabled { <V as Visit>::visit_comment(&mut self.visitor, node) } else { } } #[inline] fn visit_document(&mut self, node: &Document) { if self.enabled { <V as Visit>::visit_document(&mut self.visitor, node) } else { } } #[inline] fn visit_document_mode(&mut self, node: &DocumentMode) { if self.enabled { <V as Visit>::visit_document_mode(&mut self.visitor, node) } else { } } #[inline] fn visit_document_type(&mut self, node: &DocumentType) { if self.enabled { <V as Visit>::visit_document_type(&mut self.visitor, node) } else { } } #[inline] fn visit_element(&mut self, node: &Element) { if self.enabled { <V as Visit>::visit_element(&mut self.visitor, node) } else { } } #[inline] fn visit_namespace(&mut self, node: &Namespace) { if self.enabled { <V as Visit>::visit_namespace(&mut self.visitor, node) } else { } } #[inline] fn visit_opt_atom(&mut self, node: &Option<swc_atoms::Atom>) { if self.enabled { <V as Visit>::visit_opt_atom(&mut self.visitor, node) } else { } } #[inline] fn visit_opt_namespace(&mut self, node: &Option<Namespace>) { if self.enabled { <V as Visit>::visit_opt_namespace(&mut self.visitor, node) } else { } } #[inline] fn visit_processing_instruction(&mut self, node: &ProcessingInstruction) { if self.enabled { <V as Visit>::visit_processing_instruction(&mut self.visitor, node) } else { } } #[inline] fn visit_span(&mut self, node: &swc_common::Span) { if self.enabled { <V as Visit>::visit_span(&mut self.visitor, node) } else { } } #[inline] fn visit_text(&mut self, node: &Text) { if self.enabled { <V as Visit>::visit_text(&mut self.visitor, node) } else { } } #[inline] fn visit_token(&mut self, node: &Token) { if self.enabled { <V as Visit>::visit_token(&mut self.visitor, node) } else { } } #[inline] fn visit_token_and_span(&mut self, node: &TokenAndSpan) { if self.enabled { <V as Visit>::visit_token_and_span(&mut self.visitor, node) } else { } } } #[doc = r" A trait implemented for types that can be visited using a visitor."] pub trait VisitWith<V: ?Sized + Visit> { #[doc = r" Calls a visitor method (visitor.fold_xxx) with self."] fn visit_with(&self, visitor: &mut V); #[doc = r" Visit children nodes of `self`` with `visitor`."] fn visit_children_with(&self, visitor: &mut V); } impl<V: ?Sized + Visit> VisitWith<V> for Attribute { #[doc = "Calls [Visit`::visit_attribute`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_attribute(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <Option<Namespace> as VisitWith<V>>::visit_with(namespace, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(prefix, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw_name, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(value, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw_value, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for AttributeToken { #[doc = "Calls [Visit`::visit_attribute_token`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_attribute_token(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { AttributeToken { span, name, raw_name, value, raw_value, } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw_name, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(value, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw_value, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for CdataSection { #[doc = "Calls [Visit`::visit_cdata_section`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_cdata_section(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { CdataSection { span, data, raw } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(data, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for Child { #[doc = "Calls [Visit`::visit_child`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_child(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Child::DocumentType { 0: _field_0 } => { <DocumentType as VisitWith<V>>::visit_with(_field_0, visitor); } Child::Element { 0: _field_0 } => { <Element as VisitWith<V>>::visit_with(_field_0, visitor); } Child::Text { 0: _field_0 } => { <Text as VisitWith<V>>::visit_with(_field_0, visitor); } Child::CdataSection { 0: _field_0 } => { <CdataSection as VisitWith<V>>::visit_with(_field_0, visitor); } Child::Comment { 0: _field_0 } => { <Comment as VisitWith<V>>::visit_with(_field_0, visitor); } Child::ProcessingInstruction { 0: _field_0 } => { <ProcessingInstruction as VisitWith<V>>::visit_with(_field_0, visitor); } } } } impl<V: ?Sized + Visit> VisitWith<V> for Comment { #[doc = "Calls [Visit`::visit_comment`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_comment(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Comment { span, data, raw } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(data, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for Document { #[doc = "Calls [Visit`::visit_document`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_document(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Document { span, children } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <Vec<Child> as VisitWith<V>>::visit_with(children, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for DocumentMode { #[doc = "Calls [Visit`::visit_document_mode`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_document_mode(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { DocumentMode::NoQuirks => {} DocumentMode::LimitedQuirks => {} DocumentMode::Quirks => {} } } } impl<V: ?Sized + Visit> VisitWith<V> for DocumentType { #[doc = "Calls [Visit`::visit_document_type`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_document_type(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { DocumentType { span, name, public_id, system_id, raw, } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(public_id, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(system_id, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for Element { #[doc = "Calls [Visit`::visit_element`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_element(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Element { span, tag_name, attributes, children, } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(tag_name, visitor) }; { <Vec<Attribute> as VisitWith<V>>::visit_with(attributes, visitor) }; { <Vec<Child> as VisitWith<V>>::visit_with(children, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for Namespace { #[doc = "Calls [Visit`::visit_namespace`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_namespace(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Namespace::HTML => {} Namespace::MATHML => {} Namespace::SVG => {} Namespace::XLINK => {} Namespace::XML => {} Namespace::XMLNS => {} } } } impl<V: ?Sized + Visit> VisitWith<V> for ProcessingInstruction { #[doc = "Calls [Visit`::visit_processing_instruction`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_processing_instruction(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { ProcessingInstruction { span, target, data } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(target, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(data, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for Text { #[doc = "Calls [Visit`::visit_text`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_text(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Text { span, data, raw } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(data, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for Token { #[doc = "Calls [Visit`::visit_token`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_token(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { Token::Doctype { name, public_id, system_id, raw, } => { { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(public_id, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(system_id, visitor) }; { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw, visitor) }; } Token::StartTag { tag_name, attributes, } => { { <swc_atoms::Atom as VisitWith<V>>::visit_with(tag_name, visitor) }; { <Vec<AttributeToken> as VisitWith<V>>::visit_with(attributes, visitor) }; } Token::EndTag { tag_name, attributes, } => { { <swc_atoms::Atom as VisitWith<V>>::visit_with(tag_name, visitor) }; { <Vec<AttributeToken> as VisitWith<V>>::visit_with(attributes, visitor) }; } Token::EmptyTag { tag_name, attributes, } => { { <swc_atoms::Atom as VisitWith<V>>::visit_with(tag_name, visitor) }; { <Vec<AttributeToken> as VisitWith<V>>::visit_with(attributes, visitor) }; } Token::Comment { data, raw } => { { <swc_atoms::Atom as VisitWith<V>>::visit_with(data, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(raw, visitor) }; } Token::Character { value, raw } => { { <Option<swc_atoms::Atom> as VisitWith<V>>::visit_with(raw, visitor) }; } Token::ProcessingInstruction { target, data } => { { <swc_atoms::Atom as VisitWith<V>>::visit_with(target, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(data, visitor) }; } Token::Cdata { data, raw } => { { <swc_atoms::Atom as VisitWith<V>>::visit_with(data, visitor) }; { <swc_atoms::Atom as VisitWith<V>>::visit_with(raw, visitor) }; } Token::Eof => {} } } } impl<V: ?Sized + Visit> VisitWith<V> for TokenAndSpan { #[doc = "Calls [Visit`::visit_token_and_span`] with `self`."] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_token_and_span(visitor, self) } fn visit_children_with(&self, visitor: &mut V) { match self { TokenAndSpan { span, token } => { { <swc_common::Span as VisitWith<V>>::visit_with(span, visitor) }; { <Token as VisitWith<V>>::visit_with(token, visitor) }; } } } } impl<V: ?Sized + Visit> VisitWith<V> for swc_atoms::Atom { #[doc = "Calls [Visit`::visit_atom`] with `self`. (Extra impl)"] #[inline] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_atom(visitor, self) } #[inline] fn visit_children_with(&self, visitor: &mut V) { {} } } impl<V: ?Sized + Visit> VisitWith<V> for [AttributeToken] { #[doc = "Calls [Visit`::visit_attribute_tokens`] with `self`. (Extra impl)"] #[inline] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_attribute_tokens(visitor, self) } #[inline] fn visit_children_with(&self, visitor: &mut V) { self.iter() .for_each(|item| <AttributeToken as VisitWith<V>>::visit_with(item, visitor)) } } impl<V: ?Sized + Visit> VisitWith<V> for [Attribute] { #[doc = "Calls [Visit`::visit_attributes`] with `self`. (Extra impl)"] #[inline] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_attributes(visitor, self) } #[inline] fn visit_children_with(&self, visitor: &mut V) { self.iter() .for_each(|item| <Attribute as VisitWith<V>>::visit_with(item, visitor)) } } impl<V: ?Sized + Visit> VisitWith<V> for [Child] { #[doc = "Calls [Visit`::visit_childs`] with `self`. (Extra impl)"] #[inline] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_childs(visitor, self) } #[inline] fn visit_children_with(&self, visitor: &mut V) { self.iter() .for_each(|item| <Child as VisitWith<V>>::visit_with(item, visitor)) } } impl<V: ?Sized + Visit> VisitWith<V> for Option<swc_atoms::Atom> { #[doc = "Calls [Visit`::visit_opt_atom`] with `self`. (Extra impl)"] #[inline] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_opt_atom(visitor, self) } #[inline] fn visit_children_with(&self, visitor: &mut V) { match self { Some(inner) => <swc_atoms::Atom as VisitWith<V>>::visit_with(inner, visitor), None => {} } } } impl<V: ?Sized + Visit> VisitWith<V> for Option<Namespace> { #[doc = "Calls [Visit`::visit_opt_namespace`] with `self`. (Extra impl)"] #[inline] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_opt_namespace(visitor, self) } #[inline] fn visit_children_with(&self, visitor: &mut V) { match self { Some(inner) => <Namespace as VisitWith<V>>::visit_with(inner, visitor), None => {} } } } impl<V: ?Sized + Visit> VisitWith<V> for swc_common::Span { #[doc = "Calls [Visit`::visit_span`] with `self`. (Extra impl)"] #[inline] fn visit_with(&self, visitor: &mut V) { <V as Visit>::visit_span(visitor, self) } #[inline] fn visit_children_with(&self, visitor: &mut V) { {} } } impl<V, T> VisitWith<V> for std::boxed::Box<T> where V: ?Sized + Visit, T: VisitWith<V>, { #[inline] fn visit_with(&self, visitor: &mut V) { let v = <T as VisitWith<V>>::visit_with(&**self, visitor); v } #[inline] fn visit_children_with(&self, visitor: &mut V) { let v = <T as VisitWith<V>>::visit_children_with(&**self, visitor); v } } impl<V, T> VisitWith<V> for std::vec::Vec<T> where V: ?Sized + Visit, [T]: VisitWith<V>, { #[inline] fn visit_with(&self, visitor: &mut V) { let v = <[T] as VisitWith<V>>::visit_with(self, visitor); v } #[inline] fn visit_children_with(&self, visitor: &mut V) { let v = <[T] as VisitWith<V>>::visit_children_with(self, visitor); v } } #[doc = r" A visitor trait for traversing the AST."] #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] pub trait VisitAstPath { #[doc = "Visit a node of type `swc_atoms :: Atom`.\n\nBy default, this method calls \ [`swc_atoms :: Atom::visit_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_atom<'ast: 'r, 'r>( &mut self, node: &'ast swc_atoms::Atom, __ast_path: &mut AstNodePath<'r>, ) { <swc_atoms::Atom as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Attribute`.\n\nBy default, this method calls \ [`Attribute::visit_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_attribute<'ast: 'r, 'r>( &mut self, node: &'ast Attribute, __ast_path: &mut AstNodePath<'r>, ) { <Attribute as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `AttributeToken`.\n\nBy default, this method calls \ [`AttributeToken::visit_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_attribute_token<'ast: 'r, 'r>( &mut self, node: &'ast AttributeToken, __ast_path: &mut AstNodePath<'r>, ) { <AttributeToken as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Vec < AttributeToken >`.\n\nBy default, this method calls [`Vec \ < AttributeToken >::visit_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_attribute_tokens<'ast: 'r, 'r>( &mut self, node: &'ast [AttributeToken], __ast_path: &mut AstNodePath<'r>, ) { <[AttributeToken] as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Vec < Attribute >`.\n\nBy default, this method calls [`Vec < \ Attribute >::visit_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_attributes<'ast: 'r, 'r>( &mut self, node: &'ast [Attribute], __ast_path: &mut AstNodePath<'r>, ) { <[Attribute] as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `CdataSection`.\n\nBy default, this method calls \ [`CdataSection::visit_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_cdata_section<'ast: 'r, 'r>( &mut self, node: &'ast CdataSection, __ast_path: &mut AstNodePath<'r>, ) { <CdataSection as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Child`.\n\nBy default, this method calls \ [`Child::visit_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_child<'ast: 'r, 'r>(&mut self, node: &'ast Child, __ast_path: &mut AstNodePath<'r>) { <Child as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Vec < Child >`.\n\nBy default, this method calls [`Vec < Child \ >::visit_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_childs<'ast: 'r, 'r>( &mut self, node: &'ast [Child], __ast_path: &mut AstNodePath<'r>, ) { <[Child] as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Comment`.\n\nBy default, this method calls \ [`Comment::visit_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_comment<'ast: 'r, 'r>( &mut self, node: &'ast Comment, __ast_path: &mut AstNodePath<'r>, ) { <Comment as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Document`.\n\nBy default, this method calls \ [`Document::visit_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_document<'ast: 'r, 'r>( &mut self, node: &'ast Document, __ast_path: &mut AstNodePath<'r>, ) { <Document as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `DocumentMode`.\n\nBy default, this method calls \ [`DocumentMode::visit_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_document_mode<'ast: 'r, 'r>( &mut self, node: &'ast DocumentMode, __ast_path: &mut AstNodePath<'r>, ) { <DocumentMode as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `DocumentType`.\n\nBy default, this method calls \ [`DocumentType::visit_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_document_type<'ast: 'r, 'r>( &mut self, node: &'ast DocumentType, __ast_path: &mut AstNodePath<'r>, ) { <DocumentType as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Element`.\n\nBy default, this method calls \ [`Element::visit_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_element<'ast: 'r, 'r>( &mut self, node: &'ast Element, __ast_path: &mut AstNodePath<'r>, ) { <Element as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Namespace`.\n\nBy default, this method calls \ [`Namespace::visit_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Namespace, __ast_path: &mut AstNodePath<'r>, ) { <Namespace as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Option < swc_atoms :: Atom >`.\n\nBy default, this method calls \ [`Option < swc_atoms :: Atom >::visit_children_with_ast_path`]. If you want to \ recurse, you need to call it manually."] #[inline] fn visit_opt_atom<'ast: 'r, 'r>( &mut self, node: &'ast Option<swc_atoms::Atom>, __ast_path: &mut AstNodePath<'r>, ) { <Option<swc_atoms::Atom> as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Option < Namespace >`.\n\nBy default, this method calls \ [`Option < Namespace >::visit_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_opt_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Option<Namespace>, __ast_path: &mut AstNodePath<'r>, ) { <Option<Namespace> as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `ProcessingInstruction`.\n\nBy default, this method calls \ [`ProcessingInstruction::visit_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_processing_instruction<'ast: 'r, 'r>( &mut self, node: &'ast ProcessingInstruction, __ast_path: &mut AstNodePath<'r>, ) { <ProcessingInstruction as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `swc_common :: Span`.\n\nBy default, this method calls \ [`swc_common :: Span::visit_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_span<'ast: 'r, 'r>( &mut self, node: &'ast swc_common::Span, __ast_path: &mut AstNodePath<'r>, ) { <swc_common::Span as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Text`.\n\nBy default, this method calls \ [`Text::visit_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_text<'ast: 'r, 'r>(&mut self, node: &'ast Text, __ast_path: &mut AstNodePath<'r>) { <Text as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Token`.\n\nBy default, this method calls \ [`Token::visit_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_token<'ast: 'r, 'r>(&mut self, node: &'ast Token, __ast_path: &mut AstNodePath<'r>) { <Token as VisitWithAstPath<Self>>::visit_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `TokenAndSpan`.\n\nBy default, this method calls \ [`TokenAndSpan::visit_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_token_and_span<'ast: 'r, 'r>( &mut self, node: &'ast TokenAndSpan, __ast_path: &mut AstNodePath<'r>, ) { <TokenAndSpan as VisitWithAstPath<Self>>::visit_children_with_ast_path( node, self, __ast_path, ) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> VisitAstPath for &mut V where V: ?Sized + VisitAstPath, { #[inline] fn visit_atom<'ast: 'r, 'r>( &mut self, node: &'ast swc_atoms::Atom, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_atom(&mut **self, node, __ast_path) } #[inline] fn visit_attribute<'ast: 'r, 'r>( &mut self, node: &'ast Attribute, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute(&mut **self, node, __ast_path) } #[inline] fn visit_attribute_token<'ast: 'r, 'r>( &mut self, node: &'ast AttributeToken, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute_token(&mut **self, node, __ast_path) } #[inline] fn visit_attribute_tokens<'ast: 'r, 'r>( &mut self, node: &'ast [AttributeToken], __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute_tokens(&mut **self, node, __ast_path) } #[inline] fn visit_attributes<'ast: 'r, 'r>( &mut self, node: &'ast [Attribute], __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attributes(&mut **self, node, __ast_path) } #[inline] fn visit_cdata_section<'ast: 'r, 'r>( &mut self, node: &'ast CdataSection, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_cdata_section(&mut **self, node, __ast_path) } #[inline] fn visit_child<'ast: 'r, 'r>(&mut self, node: &'ast Child, __ast_path: &mut AstNodePath<'r>) { <V as VisitAstPath>::visit_child(&mut **self, node, __ast_path) } #[inline] fn visit_childs<'ast: 'r, 'r>( &mut self, node: &'ast [Child], __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_childs(&mut **self, node, __ast_path) } #[inline] fn visit_comment<'ast: 'r, 'r>( &mut self, node: &'ast Comment, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_comment(&mut **self, node, __ast_path) } #[inline] fn visit_document<'ast: 'r, 'r>( &mut self, node: &'ast Document, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document(&mut **self, node, __ast_path) } #[inline] fn visit_document_mode<'ast: 'r, 'r>( &mut self, node: &'ast DocumentMode, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document_mode(&mut **self, node, __ast_path) } #[inline] fn visit_document_type<'ast: 'r, 'r>( &mut self, node: &'ast DocumentType, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document_type(&mut **self, node, __ast_path) } #[inline] fn visit_element<'ast: 'r, 'r>( &mut self, node: &'ast Element, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_element(&mut **self, node, __ast_path) } #[inline] fn visit_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Namespace, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_opt_atom<'ast: 'r, 'r>( &mut self, node: &'ast Option<swc_atoms::Atom>, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_opt_atom(&mut **self, node, __ast_path) } #[inline] fn visit_opt_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Option<Namespace>, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_opt_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_processing_instruction<'ast: 'r, 'r>( &mut self, node: &'ast ProcessingInstruction, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_processing_instruction(&mut **self, node, __ast_path) } #[inline] fn visit_span<'ast: 'r, 'r>( &mut self, node: &'ast swc_common::Span, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_span(&mut **self, node, __ast_path) } #[inline] fn visit_text<'ast: 'r, 'r>(&mut self, node: &'ast Text, __ast_path: &mut AstNodePath<'r>) { <V as VisitAstPath>::visit_text(&mut **self, node, __ast_path) } #[inline] fn visit_token<'ast: 'r, 'r>(&mut self, node: &'ast Token, __ast_path: &mut AstNodePath<'r>) { <V as VisitAstPath>::visit_token(&mut **self, node, __ast_path) } #[inline] fn visit_token_and_span<'ast: 'r, 'r>( &mut self, node: &'ast TokenAndSpan, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_token_and_span(&mut **self, node, __ast_path) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> VisitAstPath for Box<V> where V: ?Sized + VisitAstPath, { #[inline] fn visit_atom<'ast: 'r, 'r>( &mut self, node: &'ast swc_atoms::Atom, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_atom(&mut **self, node, __ast_path) } #[inline] fn visit_attribute<'ast: 'r, 'r>( &mut self, node: &'ast Attribute, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute(&mut **self, node, __ast_path) } #[inline] fn visit_attribute_token<'ast: 'r, 'r>( &mut self, node: &'ast AttributeToken, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute_token(&mut **self, node, __ast_path) } #[inline] fn visit_attribute_tokens<'ast: 'r, 'r>( &mut self, node: &'ast [AttributeToken], __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute_tokens(&mut **self, node, __ast_path) } #[inline] fn visit_attributes<'ast: 'r, 'r>( &mut self, node: &'ast [Attribute], __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attributes(&mut **self, node, __ast_path) } #[inline] fn visit_cdata_section<'ast: 'r, 'r>( &mut self, node: &'ast CdataSection, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_cdata_section(&mut **self, node, __ast_path) } #[inline] fn visit_child<'ast: 'r, 'r>(&mut self, node: &'ast Child, __ast_path: &mut AstNodePath<'r>) { <V as VisitAstPath>::visit_child(&mut **self, node, __ast_path) } #[inline] fn visit_childs<'ast: 'r, 'r>( &mut self, node: &'ast [Child], __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_childs(&mut **self, node, __ast_path) } #[inline] fn visit_comment<'ast: 'r, 'r>( &mut self, node: &'ast Comment, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_comment(&mut **self, node, __ast_path) } #[inline] fn visit_document<'ast: 'r, 'r>( &mut self, node: &'ast Document, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document(&mut **self, node, __ast_path) } #[inline] fn visit_document_mode<'ast: 'r, 'r>( &mut self, node: &'ast DocumentMode, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document_mode(&mut **self, node, __ast_path) } #[inline] fn visit_document_type<'ast: 'r, 'r>( &mut self, node: &'ast DocumentType, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document_type(&mut **self, node, __ast_path) } #[inline] fn visit_element<'ast: 'r, 'r>( &mut self, node: &'ast Element, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_element(&mut **self, node, __ast_path) } #[inline] fn visit_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Namespace, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_opt_atom<'ast: 'r, 'r>( &mut self, node: &'ast Option<swc_atoms::Atom>, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_opt_atom(&mut **self, node, __ast_path) } #[inline] fn visit_opt_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Option<Namespace>, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_opt_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_processing_instruction<'ast: 'r, 'r>( &mut self, node: &'ast ProcessingInstruction, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_processing_instruction(&mut **self, node, __ast_path) } #[inline] fn visit_span<'ast: 'r, 'r>( &mut self, node: &'ast swc_common::Span, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_span(&mut **self, node, __ast_path) } #[inline] fn visit_text<'ast: 'r, 'r>(&mut self, node: &'ast Text, __ast_path: &mut AstNodePath<'r>) { <V as VisitAstPath>::visit_text(&mut **self, node, __ast_path) } #[inline] fn visit_token<'ast: 'r, 'r>(&mut self, node: &'ast Token, __ast_path: &mut AstNodePath<'r>) { <V as VisitAstPath>::visit_token(&mut **self, node, __ast_path) } #[inline] fn visit_token_and_span<'ast: 'r, 'r>( &mut self, node: &'ast TokenAndSpan, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_token_and_span(&mut **self, node, __ast_path) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<A, B> VisitAstPath for ::swc_visit::Either<A, B> where A: VisitAstPath, B: VisitAstPath, { #[inline] fn visit_atom<'ast: 'r, 'r>( &mut self, node: &'ast swc_atoms::Atom, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => VisitAstPath::visit_atom(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => { VisitAstPath::visit_atom(visitor, node, __ast_path) } } } #[inline] fn visit_attribute<'ast: 'r, 'r>( &mut self, node: &'ast Attribute, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_attribute(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_attribute(visitor, node, __ast_path) } } } #[inline] fn visit_attribute_token<'ast: 'r, 'r>( &mut self, node: &'ast AttributeToken, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_attribute_token(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_attribute_token(visitor, node, __ast_path) } } } #[inline] fn visit_attribute_tokens<'ast: 'r, 'r>( &mut self, node: &'ast [AttributeToken], __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_attribute_tokens(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_attribute_tokens(visitor, node, __ast_path) } } } #[inline] fn visit_attributes<'ast: 'r, 'r>( &mut self, node: &'ast [Attribute], __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_attributes(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_attributes(visitor, node, __ast_path) } } } #[inline] fn visit_cdata_section<'ast: 'r, 'r>( &mut self, node: &'ast CdataSection, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_cdata_section(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_cdata_section(visitor, node, __ast_path) } } } #[inline] fn visit_child<'ast: 'r, 'r>(&mut self, node: &'ast Child, __ast_path: &mut AstNodePath<'r>) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_child(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_child(visitor, node, __ast_path) } } } #[inline] fn visit_childs<'ast: 'r, 'r>( &mut self, node: &'ast [Child], __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_childs(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_childs(visitor, node, __ast_path) } } } #[inline] fn visit_comment<'ast: 'r, 'r>( &mut self, node: &'ast Comment, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_comment(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_comment(visitor, node, __ast_path) } } } #[inline] fn visit_document<'ast: 'r, 'r>( &mut self, node: &'ast Document, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_document(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_document(visitor, node, __ast_path) } } } #[inline] fn visit_document_mode<'ast: 'r, 'r>( &mut self, node: &'ast DocumentMode, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_document_mode(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_document_mode(visitor, node, __ast_path) } } } #[inline] fn visit_document_type<'ast: 'r, 'r>( &mut self, node: &'ast DocumentType, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_document_type(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_document_type(visitor, node, __ast_path) } } } #[inline] fn visit_element<'ast: 'r, 'r>( &mut self, node: &'ast Element, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_element(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_element(visitor, node, __ast_path) } } } #[inline] fn visit_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Namespace, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_namespace(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_namespace(visitor, node, __ast_path) } } } #[inline] fn visit_opt_atom<'ast: 'r, 'r>( &mut self, node: &'ast Option<swc_atoms::Atom>, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_opt_atom(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_opt_atom(visitor, node, __ast_path) } } } #[inline] fn visit_opt_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Option<Namespace>, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_opt_namespace(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_opt_namespace(visitor, node, __ast_path) } } } #[inline] fn visit_processing_instruction<'ast: 'r, 'r>( &mut self, node: &'ast ProcessingInstruction, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_processing_instruction(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_processing_instruction(visitor, node, __ast_path) } } } #[inline] fn visit_span<'ast: 'r, 'r>( &mut self, node: &'ast swc_common::Span, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => VisitAstPath::visit_span(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => { VisitAstPath::visit_span(visitor, node, __ast_path) } } } #[inline] fn visit_text<'ast: 'r, 'r>(&mut self, node: &'ast Text, __ast_path: &mut AstNodePath<'r>) { match self { swc_visit::Either::Left(visitor) => VisitAstPath::visit_text(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => { VisitAstPath::visit_text(visitor, node, __ast_path) } } } #[inline] fn visit_token<'ast: 'r, 'r>(&mut self, node: &'ast Token, __ast_path: &mut AstNodePath<'r>) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_token(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_token(visitor, node, __ast_path) } } } #[inline] fn visit_token_and_span<'ast: 'r, 'r>( &mut self, node: &'ast TokenAndSpan, __ast_path: &mut AstNodePath<'r>, ) { match self { swc_visit::Either::Left(visitor) => { VisitAstPath::visit_token_and_span(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitAstPath::visit_token_and_span(visitor, node, __ast_path) } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> VisitAstPath for ::swc_visit::Optional<V> where V: VisitAstPath, { #[inline] fn visit_atom<'ast: 'r, 'r>( &mut self, node: &'ast swc_atoms::Atom, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_atom(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_attribute<'ast: 'r, 'r>( &mut self, node: &'ast Attribute, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_attribute(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_attribute_token<'ast: 'r, 'r>( &mut self, node: &'ast AttributeToken, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_attribute_token(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_attribute_tokens<'ast: 'r, 'r>( &mut self, node: &'ast [AttributeToken], __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_attribute_tokens(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_attributes<'ast: 'r, 'r>( &mut self, node: &'ast [Attribute], __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_attributes(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_cdata_section<'ast: 'r, 'r>( &mut self, node: &'ast CdataSection, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_cdata_section(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_child<'ast: 'r, 'r>(&mut self, node: &'ast Child, __ast_path: &mut AstNodePath<'r>) { if self.enabled { <V as VisitAstPath>::visit_child(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_childs<'ast: 'r, 'r>( &mut self, node: &'ast [Child], __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_childs(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_comment<'ast: 'r, 'r>( &mut self, node: &'ast Comment, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_comment(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_document<'ast: 'r, 'r>( &mut self, node: &'ast Document, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_document(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_document_mode<'ast: 'r, 'r>( &mut self, node: &'ast DocumentMode, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_document_mode(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_document_type<'ast: 'r, 'r>( &mut self, node: &'ast DocumentType, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_document_type(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_element<'ast: 'r, 'r>( &mut self, node: &'ast Element, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_element(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Namespace, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_namespace(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_opt_atom<'ast: 'r, 'r>( &mut self, node: &'ast Option<swc_atoms::Atom>, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_opt_atom(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_opt_namespace<'ast: 'r, 'r>( &mut self, node: &'ast Option<Namespace>, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_opt_namespace(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_processing_instruction<'ast: 'r, 'r>( &mut self, node: &'ast ProcessingInstruction, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_processing_instruction(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_span<'ast: 'r, 'r>( &mut self, node: &'ast swc_common::Span, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_span(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_text<'ast: 'r, 'r>(&mut self, node: &'ast Text, __ast_path: &mut AstNodePath<'r>) { if self.enabled { <V as VisitAstPath>::visit_text(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_token<'ast: 'r, 'r>(&mut self, node: &'ast Token, __ast_path: &mut AstNodePath<'r>) { if self.enabled { <V as VisitAstPath>::visit_token(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_token_and_span<'ast: 'r, 'r>( &mut self, node: &'ast TokenAndSpan, __ast_path: &mut AstNodePath<'r>, ) { if self.enabled { <V as VisitAstPath>::visit_token_and_span(&mut self.visitor, node, __ast_path) } else { } } } #[doc = r" A trait implemented for types that can be visited using a visitor."] #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] pub trait VisitWithAstPath<V: ?Sized + VisitAstPath> { #[doc = r" Calls a visitor method (visitor.fold_xxx) with self."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ); #[doc = r" Visit children nodes of `self`` with `visitor`."] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ); } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Attribute { #[doc = "Calls [VisitAstPath`::visit_attribute`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Attribute( self, self::fields::AttributeField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Attribute( self, self::fields::AttributeField::Namespace, )); <Option<Namespace> as VisitWithAstPath<V>>::visit_with_ast_path( namespace, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Attribute( self, self::fields::AttributeField::Prefix, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( prefix, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Attribute( self, self::fields::AttributeField::Name, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Attribute( self, self::fields::AttributeField::RawName, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Attribute( self, self::fields::AttributeField::Value, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( value, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Attribute( self, self::fields::AttributeField::RawValue, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw_value, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for AttributeToken { #[doc = "Calls [VisitAstPath`::visit_attribute_token`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute_token(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { AttributeToken { span, name, raw_name, value, raw_value, } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::AttributeToken( self, self::fields::AttributeTokenField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::AttributeToken( self, self::fields::AttributeTokenField::Name, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::AttributeToken( self, self::fields::AttributeTokenField::RawName, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::AttributeToken( self, self::fields::AttributeTokenField::Value, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( value, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::AttributeToken( self, self::fields::AttributeTokenField::RawValue, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw_value, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for CdataSection { #[doc = "Calls [VisitAstPath`::visit_cdata_section`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_cdata_section(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { CdataSection { span, data, raw } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::CdataSection( self, self::fields::CdataSectionField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::CdataSection( self, self::fields::CdataSectionField::Data, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::CdataSection( self, self::fields::CdataSectionField::Raw, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Child { #[doc = "Calls [VisitAstPath`::visit_child`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_child(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Child::DocumentType { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Child( self, self::fields::ChildField::DocumentType, )); <DocumentType as VisitWithAstPath<V>>::visit_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::Element { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Child( self, self::fields::ChildField::Element, )); <Element as VisitWithAstPath<V>>::visit_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::Text { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Child( self, self::fields::ChildField::Text, )); <Text as VisitWithAstPath<V>>::visit_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::CdataSection { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Child( self, self::fields::ChildField::CdataSection, )); <CdataSection as VisitWithAstPath<V>>::visit_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::Comment { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Child( self, self::fields::ChildField::Comment, )); <Comment as VisitWithAstPath<V>>::visit_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::ProcessingInstruction { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Child( self, self::fields::ChildField::ProcessingInstruction, )); <ProcessingInstruction as VisitWithAstPath<V>>::visit_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Comment { #[doc = "Calls [VisitAstPath`::visit_comment`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_comment(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Comment { span, data, raw } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Comment( self, self::fields::CommentField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Comment( self, self::fields::CommentField::Data, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Comment( self, self::fields::CommentField::Raw, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Document { #[doc = "Calls [VisitAstPath`::visit_document`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Document { span, children } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Document( self, self::fields::DocumentField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Document( self, self::fields::DocumentField::Children(usize::MAX), )); <Vec<Child> as VisitWithAstPath<V>>::visit_with_ast_path( children, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for DocumentMode { #[doc = "Calls [VisitAstPath`::visit_document_mode`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document_mode(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { DocumentMode::NoQuirks => {} DocumentMode::LimitedQuirks => {} DocumentMode::Quirks => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for DocumentType { #[doc = "Calls [VisitAstPath`::visit_document_type`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_document_type(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { DocumentType { span, name, public_id, system_id, raw, } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::DocumentType( self, self::fields::DocumentTypeField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::DocumentType( self, self::fields::DocumentTypeField::Name, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::DocumentType( self, self::fields::DocumentTypeField::PublicId, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( public_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::DocumentType( self, self::fields::DocumentTypeField::SystemId, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( system_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::DocumentType( self, self::fields::DocumentTypeField::Raw, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Element { #[doc = "Calls [VisitAstPath`::visit_element`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_element(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Element { span, tag_name, attributes, children, } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Element( self, self::fields::ElementField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Element( self, self::fields::ElementField::TagName, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Element( self, self::fields::ElementField::Attributes(usize::MAX), )); <Vec<Attribute> as VisitWithAstPath<V>>::visit_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Element( self, self::fields::ElementField::Children(usize::MAX), )); <Vec<Child> as VisitWithAstPath<V>>::visit_with_ast_path( children, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Namespace { #[doc = "Calls [VisitAstPath`::visit_namespace`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_namespace(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Namespace::HTML => {} Namespace::MATHML => {} Namespace::SVG => {} Namespace::XLINK => {} Namespace::XML => {} Namespace::XMLNS => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for ProcessingInstruction { #[doc = "Calls [VisitAstPath`::visit_processing_instruction`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_processing_instruction(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { ProcessingInstruction { span, target, data } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::ProcessingInstruction( self, self::fields::ProcessingInstructionField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::ProcessingInstruction( self, self::fields::ProcessingInstructionField::Target, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( target, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::ProcessingInstruction( self, self::fields::ProcessingInstructionField::Data, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( data, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Text { #[doc = "Calls [VisitAstPath`::visit_text`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_text(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Text { span, data, raw } => { { let mut __ast_path = __ast_path .with_guard(AstParentNodeRef::Text(self, self::fields::TextField::Span)); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentNodeRef::Text(self, self::fields::TextField::Data)); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentNodeRef::Text(self, self::fields::TextField::Raw)); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Token { #[doc = "Calls [VisitAstPath`::visit_token`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_token(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Token::Doctype { name, public_id, system_id, raw, } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Doctype, )); { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Name, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::PublicId, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( public_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::SystemId, )); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( system_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentNodeRef::Token(self, self::fields::TokenField::Raw)); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::StartTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::StartTag, )); { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::TagName, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as VisitWithAstPath<V>>::visit_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; } Token::EndTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::EndTag, )); { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::TagName, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as VisitWithAstPath<V>>::visit_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; } Token::EmptyTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::EmptyTag, )); { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::TagName, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as VisitWithAstPath<V>>::visit_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; } Token::Comment { data, raw } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Comment, )); { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Data, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentNodeRef::Token(self, self::fields::TokenField::Raw)); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::Character { value, raw } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Character, )); { let mut __ast_path = __ast_path .with_guard(AstParentNodeRef::Token(self, self::fields::TokenField::Raw)); <Option<swc_atoms::Atom> as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::ProcessingInstruction { target, data } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::ProcessingInstruction, )); { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Target, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( target, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Data, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( data, visitor, &mut *__ast_path, ) }; } Token::Cdata { data, raw } => { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Cdata, )); { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::Token( self, self::fields::TokenField::Data, )); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentNodeRef::Token(self, self::fields::TokenField::Raw)); <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::Eof => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for TokenAndSpan { #[doc = "Calls [VisitAstPath`::visit_token_and_span`] with `self`."] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_token_and_span(visitor, self, __ast_path) } fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { TokenAndSpan { span, token } => { { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::TokenAndSpan( self, self::fields::TokenAndSpanField::Span, )); <swc_common::Span as VisitWithAstPath<V>>::visit_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentNodeRef::TokenAndSpan( self, self::fields::TokenAndSpanField::Token, )); <Token as VisitWithAstPath<V>>::visit_with_ast_path( token, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for swc_atoms::Atom { #[doc = "Calls [VisitAstPath`::visit_atom`] with `self`. (Extra impl)"] #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_atom(visitor, self, __ast_path) } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { {} } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for [AttributeToken] { #[doc = "Calls [VisitAstPath`::visit_attribute_tokens`] with `self`. (Extra impl)"] #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attribute_tokens(visitor, self, __ast_path) } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { self.iter().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <AttributeToken as VisitWithAstPath<V>>::visit_with_ast_path( item, visitor, &mut *__ast_path, ) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for [Attribute] { #[doc = "Calls [VisitAstPath`::visit_attributes`] with `self`. (Extra impl)"] #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_attributes(visitor, self, __ast_path) } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { self.iter().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <Attribute as VisitWithAstPath<V>>::visit_with_ast_path(item, visitor, &mut *__ast_path) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for [Child] { #[doc = "Calls [VisitAstPath`::visit_childs`] with `self`. (Extra impl)"] #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_childs(visitor, self, __ast_path) } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { self.iter().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <Child as VisitWithAstPath<V>>::visit_with_ast_path(item, visitor, &mut *__ast_path) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Option<swc_atoms::Atom> { #[doc = "Calls [VisitAstPath`::visit_opt_atom`] with `self`. (Extra impl)"] #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_opt_atom(visitor, self, __ast_path) } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Some(inner) => <swc_atoms::Atom as VisitWithAstPath<V>>::visit_with_ast_path( inner, visitor, __ast_path, ), None => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for Option<Namespace> { #[doc = "Calls [VisitAstPath`::visit_opt_namespace`] with `self`. (Extra impl)"] #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_opt_namespace(visitor, self, __ast_path) } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { match self { Some(inner) => { <Namespace as VisitWithAstPath<V>>::visit_with_ast_path(inner, visitor, __ast_path) } None => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitAstPath> VisitWithAstPath<V> for swc_common::Span { #[doc = "Calls [VisitAstPath`::visit_span`] with `self`. (Extra impl)"] #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { <V as VisitAstPath>::visit_span(visitor, self, __ast_path) } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { {} } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V, T> VisitWithAstPath<V> for std::boxed::Box<T> where V: ?Sized + VisitAstPath, T: VisitWithAstPath<V>, { #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { let v = <T as VisitWithAstPath<V>>::visit_with_ast_path(&**self, visitor, __ast_path); v } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { let v = <T as VisitWithAstPath<V>>::visit_children_with_ast_path(&**self, visitor, __ast_path); v } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V, T> VisitWithAstPath<V> for std::vec::Vec<T> where V: ?Sized + VisitAstPath, [T]: VisitWithAstPath<V>, { #[inline] fn visit_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { let v = <[T] as VisitWithAstPath<V>>::visit_with_ast_path(self, visitor, __ast_path); v } #[inline] fn visit_children_with_ast_path<'ast: 'r, 'r>( &'ast self, visitor: &mut V, __ast_path: &mut AstNodePath<'r>, ) { let v = <[T] as VisitWithAstPath<V>>::visit_children_with_ast_path(self, visitor, __ast_path); v } } #[doc = r" A visitor trait for traversing the AST."] pub trait VisitMut { #[doc = "Visit a node of type `swc_atoms :: Atom`.\n\nBy default, this method calls \ [`swc_atoms :: Atom::visit_mut_children_with`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom) { <swc_atoms::Atom as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Attribute`.\n\nBy default, this method calls \ [`Attribute::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute) { <Attribute as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `AttributeToken`.\n\nBy default, this method calls \ [`AttributeToken::visit_mut_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_attribute_token(&mut self, node: &mut AttributeToken) { <AttributeToken as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Vec < AttributeToken >`.\n\nBy default, this method calls [`Vec \ < AttributeToken >::visit_mut_children_with`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_attribute_tokens(&mut self, node: &mut Vec<AttributeToken>) { <Vec<AttributeToken> as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Vec < Attribute >`.\n\nBy default, this method calls [`Vec < \ Attribute >::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>) { <Vec<Attribute> as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `CdataSection`.\n\nBy default, this method calls \ [`CdataSection::visit_mut_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection) { <CdataSection as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Child`.\n\nBy default, this method calls \ [`Child::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_child(&mut self, node: &mut Child) { <Child as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Vec < Child >`.\n\nBy default, this method calls [`Vec < Child \ >::visit_mut_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>) { <Vec<Child> as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Comment`.\n\nBy default, this method calls \ [`Comment::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_comment(&mut self, node: &mut Comment) { <Comment as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Document`.\n\nBy default, this method calls \ [`Document::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_document(&mut self, node: &mut Document) { <Document as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `DocumentMode`.\n\nBy default, this method calls \ [`DocumentMode::visit_mut_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode) { <DocumentMode as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `DocumentType`.\n\nBy default, this method calls \ [`DocumentType::visit_mut_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType) { <DocumentType as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Element`.\n\nBy default, this method calls \ [`Element::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_element(&mut self, node: &mut Element) { <Element as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Namespace`.\n\nBy default, this method calls \ [`Namespace::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace) { <Namespace as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Option < swc_atoms :: Atom >`.\n\nBy default, this method calls \ [`Option < swc_atoms :: Atom >::visit_mut_children_with`]. If you want to recurse, \ you need to call it manually."] #[inline] fn visit_mut_opt_atom(&mut self, node: &mut Option<swc_atoms::Atom>) { <Option<swc_atoms::Atom> as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Option < Namespace >`.\n\nBy default, this method calls \ [`Option < Namespace >::visit_mut_children_with`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_mut_opt_namespace(&mut self, node: &mut Option<Namespace>) { <Option<Namespace> as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `ProcessingInstruction`.\n\nBy default, this method calls \ [`ProcessingInstruction::visit_mut_children_with`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_mut_processing_instruction(&mut self, node: &mut ProcessingInstruction) { <ProcessingInstruction as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `swc_common :: Span`.\n\nBy default, this method calls \ [`swc_common :: Span::visit_mut_children_with`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span) { <swc_common::Span as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Text`.\n\nBy default, this method calls \ [`Text::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_text(&mut self, node: &mut Text) { <Text as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `Token`.\n\nBy default, this method calls \ [`Token::visit_mut_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_token(&mut self, node: &mut Token) { <Token as VisitMutWith<Self>>::visit_mut_children_with(node, self) } #[doc = "Visit a node of type `TokenAndSpan`.\n\nBy default, this method calls \ [`TokenAndSpan::visit_mut_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan) { <TokenAndSpan as VisitMutWith<Self>>::visit_mut_children_with(node, self) } } impl<V> VisitMut for &mut V where V: ?Sized + VisitMut, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom) { <V as VisitMut>::visit_mut_atom(&mut **self, node) } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute) { <V as VisitMut>::visit_mut_attribute(&mut **self, node) } #[inline] fn visit_mut_attribute_token(&mut self, node: &mut AttributeToken) { <V as VisitMut>::visit_mut_attribute_token(&mut **self, node) } #[inline] fn visit_mut_attribute_tokens(&mut self, node: &mut Vec<AttributeToken>) { <V as VisitMut>::visit_mut_attribute_tokens(&mut **self, node) } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>) { <V as VisitMut>::visit_mut_attributes(&mut **self, node) } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection) { <V as VisitMut>::visit_mut_cdata_section(&mut **self, node) } #[inline] fn visit_mut_child(&mut self, node: &mut Child) { <V as VisitMut>::visit_mut_child(&mut **self, node) } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>) { <V as VisitMut>::visit_mut_childs(&mut **self, node) } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment) { <V as VisitMut>::visit_mut_comment(&mut **self, node) } #[inline] fn visit_mut_document(&mut self, node: &mut Document) { <V as VisitMut>::visit_mut_document(&mut **self, node) } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode) { <V as VisitMut>::visit_mut_document_mode(&mut **self, node) } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType) { <V as VisitMut>::visit_mut_document_type(&mut **self, node) } #[inline] fn visit_mut_element(&mut self, node: &mut Element) { <V as VisitMut>::visit_mut_element(&mut **self, node) } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace) { <V as VisitMut>::visit_mut_namespace(&mut **self, node) } #[inline] fn visit_mut_opt_atom(&mut self, node: &mut Option<swc_atoms::Atom>) { <V as VisitMut>::visit_mut_opt_atom(&mut **self, node) } #[inline] fn visit_mut_opt_namespace(&mut self, node: &mut Option<Namespace>) { <V as VisitMut>::visit_mut_opt_namespace(&mut **self, node) } #[inline] fn visit_mut_processing_instruction(&mut self, node: &mut ProcessingInstruction) { <V as VisitMut>::visit_mut_processing_instruction(&mut **self, node) } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span) { <V as VisitMut>::visit_mut_span(&mut **self, node) } #[inline] fn visit_mut_text(&mut self, node: &mut Text) { <V as VisitMut>::visit_mut_text(&mut **self, node) } #[inline] fn visit_mut_token(&mut self, node: &mut Token) { <V as VisitMut>::visit_mut_token(&mut **self, node) } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan) { <V as VisitMut>::visit_mut_token_and_span(&mut **self, node) } } impl<V> VisitMut for Box<V> where V: ?Sized + VisitMut, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom) { <V as VisitMut>::visit_mut_atom(&mut **self, node) } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute) { <V as VisitMut>::visit_mut_attribute(&mut **self, node) } #[inline] fn visit_mut_attribute_token(&mut self, node: &mut AttributeToken) { <V as VisitMut>::visit_mut_attribute_token(&mut **self, node) } #[inline] fn visit_mut_attribute_tokens(&mut self, node: &mut Vec<AttributeToken>) { <V as VisitMut>::visit_mut_attribute_tokens(&mut **self, node) } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>) { <V as VisitMut>::visit_mut_attributes(&mut **self, node) } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection) { <V as VisitMut>::visit_mut_cdata_section(&mut **self, node) } #[inline] fn visit_mut_child(&mut self, node: &mut Child) { <V as VisitMut>::visit_mut_child(&mut **self, node) } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>) { <V as VisitMut>::visit_mut_childs(&mut **self, node) } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment) { <V as VisitMut>::visit_mut_comment(&mut **self, node) } #[inline] fn visit_mut_document(&mut self, node: &mut Document) { <V as VisitMut>::visit_mut_document(&mut **self, node) } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode) { <V as VisitMut>::visit_mut_document_mode(&mut **self, node) } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType) { <V as VisitMut>::visit_mut_document_type(&mut **self, node) } #[inline] fn visit_mut_element(&mut self, node: &mut Element) { <V as VisitMut>::visit_mut_element(&mut **self, node) } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace) { <V as VisitMut>::visit_mut_namespace(&mut **self, node) } #[inline] fn visit_mut_opt_atom(&mut self, node: &mut Option<swc_atoms::Atom>) { <V as VisitMut>::visit_mut_opt_atom(&mut **self, node) } #[inline] fn visit_mut_opt_namespace(&mut self, node: &mut Option<Namespace>) { <V as VisitMut>::visit_mut_opt_namespace(&mut **self, node) } #[inline] fn visit_mut_processing_instruction(&mut self, node: &mut ProcessingInstruction) { <V as VisitMut>::visit_mut_processing_instruction(&mut **self, node) } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span) { <V as VisitMut>::visit_mut_span(&mut **self, node) } #[inline] fn visit_mut_text(&mut self, node: &mut Text) { <V as VisitMut>::visit_mut_text(&mut **self, node) } #[inline] fn visit_mut_token(&mut self, node: &mut Token) { <V as VisitMut>::visit_mut_token(&mut **self, node) } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan) { <V as VisitMut>::visit_mut_token_and_span(&mut **self, node) } } impl<A, B> VisitMut for ::swc_visit::Either<A, B> where A: VisitMut, B: VisitMut, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_atom(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_atom(visitor, node), } } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_attribute(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_attribute(visitor, node), } } #[inline] fn visit_mut_attribute_token(&mut self, node: &mut AttributeToken) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_attribute_token(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_attribute_token(visitor, node), } } #[inline] fn visit_mut_attribute_tokens(&mut self, node: &mut Vec<AttributeToken>) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_attribute_tokens(visitor, node), swc_visit::Either::Right(visitor) => { VisitMut::visit_mut_attribute_tokens(visitor, node) } } } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_attributes(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_attributes(visitor, node), } } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_cdata_section(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_cdata_section(visitor, node), } } #[inline] fn visit_mut_child(&mut self, node: &mut Child) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_child(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_child(visitor, node), } } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_childs(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_childs(visitor, node), } } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_comment(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_comment(visitor, node), } } #[inline] fn visit_mut_document(&mut self, node: &mut Document) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_document(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_document(visitor, node), } } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_document_mode(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_document_mode(visitor, node), } } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_document_type(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_document_type(visitor, node), } } #[inline] fn visit_mut_element(&mut self, node: &mut Element) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_element(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_element(visitor, node), } } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_namespace(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_namespace(visitor, node), } } #[inline] fn visit_mut_opt_atom(&mut self, node: &mut Option<swc_atoms::Atom>) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_opt_atom(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_opt_atom(visitor, node), } } #[inline] fn visit_mut_opt_namespace(&mut self, node: &mut Option<Namespace>) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_opt_namespace(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_opt_namespace(visitor, node), } } #[inline] fn visit_mut_processing_instruction(&mut self, node: &mut ProcessingInstruction) { match self { swc_visit::Either::Left(visitor) => { VisitMut::visit_mut_processing_instruction(visitor, node) } swc_visit::Either::Right(visitor) => { VisitMut::visit_mut_processing_instruction(visitor, node) } } } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_span(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_span(visitor, node), } } #[inline] fn visit_mut_text(&mut self, node: &mut Text) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_text(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_text(visitor, node), } } #[inline] fn visit_mut_token(&mut self, node: &mut Token) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_token(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_token(visitor, node), } } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan) { match self { swc_visit::Either::Left(visitor) => VisitMut::visit_mut_token_and_span(visitor, node), swc_visit::Either::Right(visitor) => VisitMut::visit_mut_token_and_span(visitor, node), } } } impl<V> VisitMut for ::swc_visit::Optional<V> where V: VisitMut, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom) { if self.enabled { <V as VisitMut>::visit_mut_atom(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute) { if self.enabled { <V as VisitMut>::visit_mut_attribute(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_attribute_token(&mut self, node: &mut AttributeToken) { if self.enabled { <V as VisitMut>::visit_mut_attribute_token(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_attribute_tokens(&mut self, node: &mut Vec<AttributeToken>) { if self.enabled { <V as VisitMut>::visit_mut_attribute_tokens(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>) { if self.enabled { <V as VisitMut>::visit_mut_attributes(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection) { if self.enabled { <V as VisitMut>::visit_mut_cdata_section(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_child(&mut self, node: &mut Child) { if self.enabled { <V as VisitMut>::visit_mut_child(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>) { if self.enabled { <V as VisitMut>::visit_mut_childs(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment) { if self.enabled { <V as VisitMut>::visit_mut_comment(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_document(&mut self, node: &mut Document) { if self.enabled { <V as VisitMut>::visit_mut_document(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode) { if self.enabled { <V as VisitMut>::visit_mut_document_mode(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType) { if self.enabled { <V as VisitMut>::visit_mut_document_type(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_element(&mut self, node: &mut Element) { if self.enabled { <V as VisitMut>::visit_mut_element(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace) { if self.enabled { <V as VisitMut>::visit_mut_namespace(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_opt_atom(&mut self, node: &mut Option<swc_atoms::Atom>) { if self.enabled { <V as VisitMut>::visit_mut_opt_atom(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_opt_namespace(&mut self, node: &mut Option<Namespace>) { if self.enabled { <V as VisitMut>::visit_mut_opt_namespace(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_processing_instruction(&mut self, node: &mut ProcessingInstruction) { if self.enabled { <V as VisitMut>::visit_mut_processing_instruction(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span) { if self.enabled { <V as VisitMut>::visit_mut_span(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_text(&mut self, node: &mut Text) { if self.enabled { <V as VisitMut>::visit_mut_text(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_token(&mut self, node: &mut Token) { if self.enabled { <V as VisitMut>::visit_mut_token(&mut self.visitor, node) } else { } } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan) { if self.enabled { <V as VisitMut>::visit_mut_token_and_span(&mut self.visitor, node) } else { } } } #[doc = r" A trait implemented for types that can be visited using a visitor."] pub trait VisitMutWith<V: ?Sized + VisitMut> { #[doc = r" Calls a visitor method (visitor.fold_xxx) with self."] fn visit_mut_with(&mut self, visitor: &mut V); #[doc = r" Visit children nodes of `self`` with `visitor`."] fn visit_mut_children_with(&mut self, visitor: &mut V); } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Attribute { #[doc = "Calls [VisitMut`::visit_mut_attribute`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_attribute(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <Option<Namespace> as VisitMutWith<V>>::visit_mut_with(namespace, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(prefix, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw_name, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(value, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw_value, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for AttributeToken { #[doc = "Calls [VisitMut`::visit_mut_attribute_token`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_attribute_token(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { AttributeToken { span, name, raw_name, value, raw_value, } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw_name, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(value, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw_value, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for CdataSection { #[doc = "Calls [VisitMut`::visit_mut_cdata_section`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_cdata_section(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { CdataSection { span, data, raw } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(data, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Child { #[doc = "Calls [VisitMut`::visit_mut_child`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_child(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Child::DocumentType { 0: _field_0 } => { <DocumentType as VisitMutWith<V>>::visit_mut_with(_field_0, visitor); } Child::Element { 0: _field_0 } => { <Element as VisitMutWith<V>>::visit_mut_with(_field_0, visitor); } Child::Text { 0: _field_0 } => { <Text as VisitMutWith<V>>::visit_mut_with(_field_0, visitor); } Child::CdataSection { 0: _field_0 } => { <CdataSection as VisitMutWith<V>>::visit_mut_with(_field_0, visitor); } Child::Comment { 0: _field_0 } => { <Comment as VisitMutWith<V>>::visit_mut_with(_field_0, visitor); } Child::ProcessingInstruction { 0: _field_0 } => { <ProcessingInstruction as VisitMutWith<V>>::visit_mut_with(_field_0, visitor); } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Comment { #[doc = "Calls [VisitMut`::visit_mut_comment`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_comment(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Comment { span, data, raw } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(data, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Document { #[doc = "Calls [VisitMut`::visit_mut_document`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_document(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Document { span, children } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <Vec<Child> as VisitMutWith<V>>::visit_mut_with(children, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for DocumentMode { #[doc = "Calls [VisitMut`::visit_mut_document_mode`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_document_mode(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { DocumentMode::NoQuirks => {} DocumentMode::LimitedQuirks => {} DocumentMode::Quirks => {} } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for DocumentType { #[doc = "Calls [VisitMut`::visit_mut_document_type`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_document_type(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { DocumentType { span, name, public_id, system_id, raw, } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(public_id, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(system_id, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Element { #[doc = "Calls [VisitMut`::visit_mut_element`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_element(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Element { span, tag_name, attributes, children, } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(tag_name, visitor) }; { <Vec<Attribute> as VisitMutWith<V>>::visit_mut_with(attributes, visitor) }; { <Vec<Child> as VisitMutWith<V>>::visit_mut_with(children, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Namespace { #[doc = "Calls [VisitMut`::visit_mut_namespace`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_namespace(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Namespace::HTML => {} Namespace::MATHML => {} Namespace::SVG => {} Namespace::XLINK => {} Namespace::XML => {} Namespace::XMLNS => {} } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for ProcessingInstruction { #[doc = "Calls [VisitMut`::visit_mut_processing_instruction`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_processing_instruction(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { ProcessingInstruction { span, target, data } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(target, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(data, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Text { #[doc = "Calls [VisitMut`::visit_mut_text`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_text(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Text { span, data, raw } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(data, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Token { #[doc = "Calls [VisitMut`::visit_mut_token`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_token(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Token::Doctype { name, public_id, system_id, raw, } => { { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(name, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(public_id, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(system_id, visitor) }; { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } Token::StartTag { tag_name, attributes, } => { { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(tag_name, visitor) }; { <Vec<AttributeToken> as VisitMutWith<V>>::visit_mut_with(attributes, visitor) }; } Token::EndTag { tag_name, attributes, } => { { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(tag_name, visitor) }; { <Vec<AttributeToken> as VisitMutWith<V>>::visit_mut_with(attributes, visitor) }; } Token::EmptyTag { tag_name, attributes, } => { { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(tag_name, visitor) }; { <Vec<AttributeToken> as VisitMutWith<V>>::visit_mut_with(attributes, visitor) }; } Token::Comment { data, raw } => { { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(data, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } Token::Character { value, raw } => { { <Option<swc_atoms::Atom> as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } Token::ProcessingInstruction { target, data } => { { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(target, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(data, visitor) }; } Token::Cdata { data, raw } => { { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(data, visitor) }; { <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(raw, visitor) }; } Token::Eof => {} } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for TokenAndSpan { #[doc = "Calls [VisitMut`::visit_mut_token_and_span`] with `self`."] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_token_and_span(visitor, self) } fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { TokenAndSpan { span, token } => { { <swc_common::Span as VisitMutWith<V>>::visit_mut_with(span, visitor) }; { <Token as VisitMutWith<V>>::visit_mut_with(token, visitor) }; } } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for swc_atoms::Atom { #[doc = "Calls [VisitMut`::visit_mut_atom`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_atom(visitor, self) } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { {} } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Vec<AttributeToken> { #[doc = "Calls [VisitMut`::visit_mut_attribute_tokens`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_attribute_tokens(visitor, self) } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { self.iter_mut() .for_each(|item| <AttributeToken as VisitMutWith<V>>::visit_mut_with(item, visitor)) } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Vec<Attribute> { #[doc = "Calls [VisitMut`::visit_mut_attributes`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_attributes(visitor, self) } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { self.iter_mut() .for_each(|item| <Attribute as VisitMutWith<V>>::visit_mut_with(item, visitor)) } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Vec<Child> { #[doc = "Calls [VisitMut`::visit_mut_childs`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_childs(visitor, self) } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { self.iter_mut() .for_each(|item| <Child as VisitMutWith<V>>::visit_mut_with(item, visitor)) } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Option<swc_atoms::Atom> { #[doc = "Calls [VisitMut`::visit_mut_opt_atom`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_opt_atom(visitor, self) } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Some(inner) => <swc_atoms::Atom as VisitMutWith<V>>::visit_mut_with(inner, visitor), None => {} } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for Option<Namespace> { #[doc = "Calls [VisitMut`::visit_mut_opt_namespace`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_opt_namespace(visitor, self) } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { match self { Some(inner) => <Namespace as VisitMutWith<V>>::visit_mut_with(inner, visitor), None => {} } } } impl<V: ?Sized + VisitMut> VisitMutWith<V> for swc_common::Span { #[doc = "Calls [VisitMut`::visit_mut_span`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { <V as VisitMut>::visit_mut_span(visitor, self) } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { {} } } impl<V, T> VisitMutWith<V> for std::boxed::Box<T> where V: ?Sized + VisitMut, T: VisitMutWith<V>, { #[inline] fn visit_mut_with(&mut self, visitor: &mut V) { let v = <T as VisitMutWith<V>>::visit_mut_with(&mut **self, visitor); v } #[inline] fn visit_mut_children_with(&mut self, visitor: &mut V) { let v = <T as VisitMutWith<V>>::visit_mut_children_with(&mut **self, visitor); v } } #[doc = r" A visitor trait for traversing the AST."] #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] pub trait VisitMutAstPath { #[doc = "Visit a node of type `swc_atoms :: Atom`.\n\nBy default, this method calls \ [`swc_atoms :: Atom::visit_mut_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom, __ast_path: &mut AstKindPath) { <swc_atoms::Atom as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Attribute`.\n\nBy default, this method calls \ [`Attribute::visit_mut_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute, __ast_path: &mut AstKindPath) { <Attribute as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `AttributeToken`.\n\nBy default, this method calls \ [`AttributeToken::visit_mut_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_mut_attribute_token( &mut self, node: &mut AttributeToken, __ast_path: &mut AstKindPath, ) { <AttributeToken as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Vec < AttributeToken >`.\n\nBy default, this method calls [`Vec \ < AttributeToken >::visit_mut_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_mut_attribute_tokens( &mut self, node: &mut Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) { <Vec<AttributeToken> as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Vec < Attribute >`.\n\nBy default, this method calls [`Vec < \ Attribute >::visit_mut_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>, __ast_path: &mut AstKindPath) { <Vec<Attribute> as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `CdataSection`.\n\nBy default, this method calls \ [`CdataSection::visit_mut_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection, __ast_path: &mut AstKindPath) { <CdataSection as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Child`.\n\nBy default, this method calls \ [`Child::visit_mut_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_child(&mut self, node: &mut Child, __ast_path: &mut AstKindPath) { <Child as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Vec < Child >`.\n\nBy default, this method calls [`Vec < Child \ >::visit_mut_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>, __ast_path: &mut AstKindPath) { <Vec<Child> as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Comment`.\n\nBy default, this method calls \ [`Comment::visit_mut_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_comment(&mut self, node: &mut Comment, __ast_path: &mut AstKindPath) { <Comment as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Document`.\n\nBy default, this method calls \ [`Document::visit_mut_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_document(&mut self, node: &mut Document, __ast_path: &mut AstKindPath) { <Document as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `DocumentMode`.\n\nBy default, this method calls \ [`DocumentMode::visit_mut_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode, __ast_path: &mut AstKindPath) { <DocumentMode as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `DocumentType`.\n\nBy default, this method calls \ [`DocumentType::visit_mut_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType, __ast_path: &mut AstKindPath) { <DocumentType as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Element`.\n\nBy default, this method calls \ [`Element::visit_mut_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_element(&mut self, node: &mut Element, __ast_path: &mut AstKindPath) { <Element as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Namespace`.\n\nBy default, this method calls \ [`Namespace::visit_mut_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace, __ast_path: &mut AstKindPath) { <Namespace as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Option < swc_atoms :: Atom >`.\n\nBy default, this method calls \ [`Option < swc_atoms :: Atom >::visit_mut_children_with_ast_path`]. If you want to \ recurse, you need to call it manually."] #[inline] fn visit_mut_opt_atom( &mut self, node: &mut Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) { <Option<swc_atoms::Atom> as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Option < Namespace >`.\n\nBy default, this method calls \ [`Option < Namespace >::visit_mut_children_with_ast_path`]. If you want to recurse, \ you need to call it manually."] #[inline] fn visit_mut_opt_namespace( &mut self, node: &mut Option<Namespace>, __ast_path: &mut AstKindPath, ) { <Option<Namespace> as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `ProcessingInstruction`.\n\nBy default, this method calls \ [`ProcessingInstruction::visit_mut_children_with_ast_path`]. If you want to recurse, \ you need to call it manually."] #[inline] fn visit_mut_processing_instruction( &mut self, node: &mut ProcessingInstruction, __ast_path: &mut AstKindPath, ) { <ProcessingInstruction as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `swc_common :: Span`.\n\nBy default, this method calls \ [`swc_common :: Span::visit_mut_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span, __ast_path: &mut AstKindPath) { <swc_common::Span as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Text`.\n\nBy default, this method calls \ [`Text::visit_mut_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_text(&mut self, node: &mut Text, __ast_path: &mut AstKindPath) { <Text as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Token`.\n\nBy default, this method calls \ [`Token::visit_mut_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn visit_mut_token(&mut self, node: &mut Token, __ast_path: &mut AstKindPath) { <Token as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `TokenAndSpan`.\n\nBy default, this method calls \ [`TokenAndSpan::visit_mut_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan, __ast_path: &mut AstKindPath) { <TokenAndSpan as VisitMutWithAstPath<Self>>::visit_mut_children_with_ast_path( node, self, __ast_path, ) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> VisitMutAstPath for &mut V where V: ?Sized + VisitMutAstPath, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_atom(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attribute(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attribute_token( &mut self, node: &mut AttributeToken, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_attribute_token(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attribute_tokens( &mut self, node: &mut Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_attribute_tokens(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attributes(&mut **self, node, __ast_path) } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_cdata_section(&mut **self, node, __ast_path) } #[inline] fn visit_mut_child(&mut self, node: &mut Child, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_child(&mut **self, node, __ast_path) } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_childs(&mut **self, node, __ast_path) } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_comment(&mut **self, node, __ast_path) } #[inline] fn visit_mut_document(&mut self, node: &mut Document, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document(&mut **self, node, __ast_path) } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document_mode(&mut **self, node, __ast_path) } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document_type(&mut **self, node, __ast_path) } #[inline] fn visit_mut_element(&mut self, node: &mut Element, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_element(&mut **self, node, __ast_path) } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_mut_opt_atom( &mut self, node: &mut Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_opt_atom(&mut **self, node, __ast_path) } #[inline] fn visit_mut_opt_namespace( &mut self, node: &mut Option<Namespace>, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_opt_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_mut_processing_instruction( &mut self, node: &mut ProcessingInstruction, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_processing_instruction(&mut **self, node, __ast_path) } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_span(&mut **self, node, __ast_path) } #[inline] fn visit_mut_text(&mut self, node: &mut Text, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_text(&mut **self, node, __ast_path) } #[inline] fn visit_mut_token(&mut self, node: &mut Token, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_token(&mut **self, node, __ast_path) } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_token_and_span(&mut **self, node, __ast_path) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> VisitMutAstPath for Box<V> where V: ?Sized + VisitMutAstPath, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_atom(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attribute(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attribute_token( &mut self, node: &mut AttributeToken, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_attribute_token(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attribute_tokens( &mut self, node: &mut Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_attribute_tokens(&mut **self, node, __ast_path) } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attributes(&mut **self, node, __ast_path) } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_cdata_section(&mut **self, node, __ast_path) } #[inline] fn visit_mut_child(&mut self, node: &mut Child, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_child(&mut **self, node, __ast_path) } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_childs(&mut **self, node, __ast_path) } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_comment(&mut **self, node, __ast_path) } #[inline] fn visit_mut_document(&mut self, node: &mut Document, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document(&mut **self, node, __ast_path) } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document_mode(&mut **self, node, __ast_path) } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document_type(&mut **self, node, __ast_path) } #[inline] fn visit_mut_element(&mut self, node: &mut Element, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_element(&mut **self, node, __ast_path) } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_mut_opt_atom( &mut self, node: &mut Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_opt_atom(&mut **self, node, __ast_path) } #[inline] fn visit_mut_opt_namespace( &mut self, node: &mut Option<Namespace>, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_opt_namespace(&mut **self, node, __ast_path) } #[inline] fn visit_mut_processing_instruction( &mut self, node: &mut ProcessingInstruction, __ast_path: &mut AstKindPath, ) { <V as VisitMutAstPath>::visit_mut_processing_instruction(&mut **self, node, __ast_path) } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_span(&mut **self, node, __ast_path) } #[inline] fn visit_mut_text(&mut self, node: &mut Text, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_text(&mut **self, node, __ast_path) } #[inline] fn visit_mut_token(&mut self, node: &mut Token, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_token(&mut **self, node, __ast_path) } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_token_and_span(&mut **self, node, __ast_path) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<A, B> VisitMutAstPath for ::swc_visit::Either<A, B> where A: VisitMutAstPath, B: VisitMutAstPath, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_atom(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_atom(visitor, node, __ast_path) } } } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_attribute(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_attribute(visitor, node, __ast_path) } } } #[inline] fn visit_mut_attribute_token( &mut self, node: &mut AttributeToken, __ast_path: &mut AstKindPath, ) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_attribute_token(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_attribute_token(visitor, node, __ast_path) } } } #[inline] fn visit_mut_attribute_tokens( &mut self, node: &mut Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_attribute_tokens(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_attribute_tokens(visitor, node, __ast_path) } } } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_attributes(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_attributes(visitor, node, __ast_path) } } } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_cdata_section(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_cdata_section(visitor, node, __ast_path) } } } #[inline] fn visit_mut_child(&mut self, node: &mut Child, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_child(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_child(visitor, node, __ast_path) } } } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_childs(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_childs(visitor, node, __ast_path) } } } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_comment(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_comment(visitor, node, __ast_path) } } } #[inline] fn visit_mut_document(&mut self, node: &mut Document, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_document(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_document(visitor, node, __ast_path) } } } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_document_mode(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_document_mode(visitor, node, __ast_path) } } } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_document_type(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_document_type(visitor, node, __ast_path) } } } #[inline] fn visit_mut_element(&mut self, node: &mut Element, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_element(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_element(visitor, node, __ast_path) } } } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_namespace(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_namespace(visitor, node, __ast_path) } } } #[inline] fn visit_mut_opt_atom( &mut self, node: &mut Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_opt_atom(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_opt_atom(visitor, node, __ast_path) } } } #[inline] fn visit_mut_opt_namespace( &mut self, node: &mut Option<Namespace>, __ast_path: &mut AstKindPath, ) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_opt_namespace(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_opt_namespace(visitor, node, __ast_path) } } } #[inline] fn visit_mut_processing_instruction( &mut self, node: &mut ProcessingInstruction, __ast_path: &mut AstKindPath, ) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_processing_instruction(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_processing_instruction(visitor, node, __ast_path) } } } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_span(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_span(visitor, node, __ast_path) } } } #[inline] fn visit_mut_text(&mut self, node: &mut Text, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_text(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_text(visitor, node, __ast_path) } } } #[inline] fn visit_mut_token(&mut self, node: &mut Token, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_token(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_token(visitor, node, __ast_path) } } } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan, __ast_path: &mut AstKindPath) { match self { swc_visit::Either::Left(visitor) => { VisitMutAstPath::visit_mut_token_and_span(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { VisitMutAstPath::visit_mut_token_and_span(visitor, node, __ast_path) } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> VisitMutAstPath for ::swc_visit::Optional<V> where V: VisitMutAstPath, { #[inline] fn visit_mut_atom(&mut self, node: &mut swc_atoms::Atom, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_atom(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_attribute(&mut self, node: &mut Attribute, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_attribute(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_attribute_token( &mut self, node: &mut AttributeToken, __ast_path: &mut AstKindPath, ) { if self.enabled { <V as VisitMutAstPath>::visit_mut_attribute_token(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_attribute_tokens( &mut self, node: &mut Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) { if self.enabled { <V as VisitMutAstPath>::visit_mut_attribute_tokens(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_attributes(&mut self, node: &mut Vec<Attribute>, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_attributes(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_cdata_section(&mut self, node: &mut CdataSection, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_cdata_section(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_child(&mut self, node: &mut Child, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_child(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_childs(&mut self, node: &mut Vec<Child>, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_childs(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_comment(&mut self, node: &mut Comment, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_comment(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_document(&mut self, node: &mut Document, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_document(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_document_mode(&mut self, node: &mut DocumentMode, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_document_mode(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_document_type(&mut self, node: &mut DocumentType, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_document_type(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_element(&mut self, node: &mut Element, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_element(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_namespace(&mut self, node: &mut Namespace, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_namespace(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_opt_atom( &mut self, node: &mut Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) { if self.enabled { <V as VisitMutAstPath>::visit_mut_opt_atom(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_opt_namespace( &mut self, node: &mut Option<Namespace>, __ast_path: &mut AstKindPath, ) { if self.enabled { <V as VisitMutAstPath>::visit_mut_opt_namespace(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_processing_instruction( &mut self, node: &mut ProcessingInstruction, __ast_path: &mut AstKindPath, ) { if self.enabled { <V as VisitMutAstPath>::visit_mut_processing_instruction( &mut self.visitor, node, __ast_path, ) } else { } } #[inline] fn visit_mut_span(&mut self, node: &mut swc_common::Span, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_span(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_text(&mut self, node: &mut Text, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_text(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_token(&mut self, node: &mut Token, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_token(&mut self.visitor, node, __ast_path) } else { } } #[inline] fn visit_mut_token_and_span(&mut self, node: &mut TokenAndSpan, __ast_path: &mut AstKindPath) { if self.enabled { <V as VisitMutAstPath>::visit_mut_token_and_span(&mut self.visitor, node, __ast_path) } else { } } } #[doc = r" A trait implemented for types that can be visited using a visitor."] #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] pub trait VisitMutWithAstPath<V: ?Sized + VisitMutAstPath> { #[doc = r" Calls a visitor method (visitor.fold_xxx) with self."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath); #[doc = r" Visit children nodes of `self`` with `visitor`."] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath); } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Attribute { #[doc = "Calls [VisitMutAstPath`::visit_mut_attribute`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attribute(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } => { { let mut __ast_path = __ast_path .with_guard(AstParentKind::Attribute(self::fields::AttributeField::Span)); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::Namespace, )); <Option<Namespace> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( namespace, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::Prefix, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( prefix, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentKind::Attribute(self::fields::AttributeField::Name)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::RawName, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::Value, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( value, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::RawValue, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw_value, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for AttributeToken { #[doc = "Calls [VisitMutAstPath`::visit_mut_attribute_token`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attribute_token(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { AttributeToken { span, name, raw_name, value, raw_value, } => { { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::Span, )); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::Name, )); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::RawName, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::Value, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( value, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::RawValue, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw_value, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for CdataSection { #[doc = "Calls [VisitMutAstPath`::visit_mut_cdata_section`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_cdata_section(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { CdataSection { span, data, raw } => { { let mut __ast_path = __ast_path.with_guard(AstParentKind::CdataSection( self::fields::CdataSectionField::Span, )); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::CdataSection( self::fields::CdataSectionField::Data, )); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::CdataSection( self::fields::CdataSectionField::Raw, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Child { #[doc = "Calls [VisitMutAstPath`::visit_mut_child`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_child(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Child::DocumentType { 0: _field_0 } => { let mut __ast_path = __ast_path .with_guard(AstParentKind::Child(self::fields::ChildField::DocumentType)); <DocumentType as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::Element { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child(self::fields::ChildField::Element)); <Element as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::Text { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child(self::fields::ChildField::Text)); <Text as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::CdataSection { 0: _field_0 } => { let mut __ast_path = __ast_path .with_guard(AstParentKind::Child(self::fields::ChildField::CdataSection)); <CdataSection as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::Comment { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child(self::fields::ChildField::Comment)); <Comment as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } Child::ProcessingInstruction { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child( self::fields::ChildField::ProcessingInstruction, )); <ProcessingInstruction as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( _field_0, visitor, &mut *__ast_path, ); } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Comment { #[doc = "Calls [VisitMutAstPath`::visit_mut_comment`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_comment(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Comment { span, data, raw } => { { let mut __ast_path = __ast_path .with_guard(AstParentKind::Comment(self::fields::CommentField::Span)); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentKind::Comment(self::fields::CommentField::Data)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentKind::Comment(self::fields::CommentField::Raw)); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Document { #[doc = "Calls [VisitMutAstPath`::visit_mut_document`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Document { span, children } => { { let mut __ast_path = __ast_path .with_guard(AstParentKind::Document(self::fields::DocumentField::Span)); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Document( self::fields::DocumentField::Children(usize::MAX), )); <Vec<Child> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( children, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for DocumentMode { #[doc = "Calls [VisitMutAstPath`::visit_mut_document_mode`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document_mode(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { DocumentMode::NoQuirks => {} DocumentMode::LimitedQuirks => {} DocumentMode::Quirks => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for DocumentType { #[doc = "Calls [VisitMutAstPath`::visit_mut_document_type`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_document_type(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { DocumentType { span, name, public_id, system_id, raw, } => { { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::Span, )); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::Name, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::PublicId, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( public_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::SystemId, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( system_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::Raw, )); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Element { #[doc = "Calls [VisitMutAstPath`::visit_mut_element`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_element(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Element { span, tag_name, attributes, children, } => { { let mut __ast_path = __ast_path .with_guard(AstParentKind::Element(self::fields::ElementField::Span)); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentKind::Element(self::fields::ElementField::TagName)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Element( self::fields::ElementField::Attributes(usize::MAX), )); <Vec<Attribute> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Element( self::fields::ElementField::Children(usize::MAX), )); <Vec<Child> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( children, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Namespace { #[doc = "Calls [VisitMutAstPath`::visit_mut_namespace`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_namespace(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Namespace::HTML => {} Namespace::MATHML => {} Namespace::SVG => {} Namespace::XLINK => {} Namespace::XML => {} Namespace::XMLNS => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for ProcessingInstruction { #[doc = "Calls [VisitMutAstPath`::visit_mut_processing_instruction`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_processing_instruction(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { ProcessingInstruction { span, target, data } => { { let mut __ast_path = __ast_path.with_guard(AstParentKind::ProcessingInstruction( self::fields::ProcessingInstructionField::Span, )); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::ProcessingInstruction( self::fields::ProcessingInstructionField::Target, )); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( target, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::ProcessingInstruction( self::fields::ProcessingInstructionField::Data, )); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( data, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Text { #[doc = "Calls [VisitMutAstPath`::visit_mut_text`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_text(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Text { span, data, raw } => { { let mut __ast_path = __ast_path.with_guard(AstParentKind::Text(self::fields::TextField::Span)); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Text(self::fields::TextField::Data)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Text(self::fields::TextField::Raw)); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Token { #[doc = "Calls [VisitMutAstPath`::visit_mut_token`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_token(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Token::Doctype { name, public_id, system_id, raw, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Doctype)); { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Name)); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::PublicId)); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( public_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::SystemId)); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( system_id, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::StartTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::StartTag)); { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::TagName)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; } Token::EndTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::EndTag)); { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::TagName)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; } Token::EmptyTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::EmptyTag)); { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::TagName)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; } Token::Comment { data, raw } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Comment)); { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Data)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::Character { value, raw } => { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::Character)); { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <Option<swc_atoms::Atom> as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::ProcessingInstruction { target, data } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::ProcessingInstruction, )); { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::Target)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( target, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Data)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( data, visitor, &mut *__ast_path, ) }; } Token::Cdata { data, raw } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Cdata)); { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Data)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( data, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( raw, visitor, &mut *__ast_path, ) }; } Token::Eof => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for TokenAndSpan { #[doc = "Calls [VisitMutAstPath`::visit_mut_token_and_span`] with `self`."] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_token_and_span(visitor, self, __ast_path) } fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { TokenAndSpan { span, token } => { { let mut __ast_path = __ast_path.with_guard(AstParentKind::TokenAndSpan( self::fields::TokenAndSpanField::Span, )); <swc_common::Span as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( span, visitor, &mut *__ast_path, ) }; { let mut __ast_path = __ast_path.with_guard(AstParentKind::TokenAndSpan( self::fields::TokenAndSpanField::Token, )); <Token as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( token, visitor, &mut *__ast_path, ) }; } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for swc_atoms::Atom { #[doc = "Calls [VisitMutAstPath`::visit_mut_atom`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_atom(visitor, self, __ast_path) } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { {} } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Vec<AttributeToken> { #[doc = "Calls [VisitMutAstPath`::visit_mut_attribute_tokens`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attribute_tokens(visitor, self, __ast_path) } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { self.iter_mut().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <AttributeToken as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( item, visitor, &mut *__ast_path, ) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Vec<Attribute> { #[doc = "Calls [VisitMutAstPath`::visit_mut_attributes`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_attributes(visitor, self, __ast_path) } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { self.iter_mut().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <Attribute as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( item, visitor, &mut *__ast_path, ) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Vec<Child> { #[doc = "Calls [VisitMutAstPath`::visit_mut_childs`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_childs(visitor, self, __ast_path) } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { self.iter_mut().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <Child as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( item, visitor, &mut *__ast_path, ) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Option<swc_atoms::Atom> { #[doc = "Calls [VisitMutAstPath`::visit_mut_opt_atom`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_opt_atom(visitor, self, __ast_path) } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Some(inner) => <swc_atoms::Atom as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( inner, visitor, __ast_path, ), None => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for Option<Namespace> { #[doc = "Calls [VisitMutAstPath`::visit_mut_opt_namespace`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_opt_namespace(visitor, self, __ast_path) } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { match self { Some(inner) => <Namespace as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( inner, visitor, __ast_path, ), None => {} } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + VisitMutAstPath> VisitMutWithAstPath<V> for swc_common::Span { #[doc = "Calls [VisitMutAstPath`::visit_mut_span`] with `self`. (Extra impl)"] #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { <V as VisitMutAstPath>::visit_mut_span(visitor, self, __ast_path) } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { {} } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V, T> VisitMutWithAstPath<V> for std::boxed::Box<T> where V: ?Sized + VisitMutAstPath, T: VisitMutWithAstPath<V>, { #[inline] fn visit_mut_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { let v = <T as VisitMutWithAstPath<V>>::visit_mut_with_ast_path( &mut **self, visitor, __ast_path, ); v } #[inline] fn visit_mut_children_with_ast_path(&mut self, visitor: &mut V, __ast_path: &mut AstKindPath) { let v = <T as VisitMutWithAstPath<V>>::visit_mut_children_with_ast_path( &mut **self, visitor, __ast_path, ); v } } #[doc = r" A visitor trait for traversing the AST."] pub trait Fold { #[doc = "Visit a node of type `swc_atoms :: Atom`.\n\nBy default, this method calls \ [`swc_atoms :: Atom::fold_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn fold_atom(&mut self, node: swc_atoms::Atom) -> swc_atoms::Atom { <swc_atoms::Atom as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Attribute`.\n\nBy default, this method calls \ [`Attribute::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_attribute(&mut self, node: Attribute) -> Attribute { <Attribute as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `AttributeToken`.\n\nBy default, this method calls \ [`AttributeToken::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_attribute_token(&mut self, node: AttributeToken) -> AttributeToken { <AttributeToken as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Vec < AttributeToken >`.\n\nBy default, this method calls [`Vec \ < AttributeToken >::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_attribute_tokens(&mut self, node: Vec<AttributeToken>) -> Vec<AttributeToken> { <Vec<AttributeToken> as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Vec < Attribute >`.\n\nBy default, this method calls [`Vec < \ Attribute >::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_attributes(&mut self, node: Vec<Attribute>) -> Vec<Attribute> { <Vec<Attribute> as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `CdataSection`.\n\nBy default, this method calls \ [`CdataSection::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_cdata_section(&mut self, node: CdataSection) -> CdataSection { <CdataSection as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Child`.\n\nBy default, this method calls \ [`Child::fold_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn fold_child(&mut self, node: Child) -> Child { <Child as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Vec < Child >`.\n\nBy default, this method calls [`Vec < Child \ >::fold_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn fold_childs(&mut self, node: Vec<Child>) -> Vec<Child> { <Vec<Child> as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Comment`.\n\nBy default, this method calls \ [`Comment::fold_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn fold_comment(&mut self, node: Comment) -> Comment { <Comment as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Document`.\n\nBy default, this method calls \ [`Document::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_document(&mut self, node: Document) -> Document { <Document as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `DocumentMode`.\n\nBy default, this method calls \ [`DocumentMode::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_document_mode(&mut self, node: DocumentMode) -> DocumentMode { <DocumentMode as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `DocumentType`.\n\nBy default, this method calls \ [`DocumentType::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_document_type(&mut self, node: DocumentType) -> DocumentType { <DocumentType as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Element`.\n\nBy default, this method calls \ [`Element::fold_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn fold_element(&mut self, node: Element) -> Element { <Element as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Namespace`.\n\nBy default, this method calls \ [`Namespace::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_namespace(&mut self, node: Namespace) -> Namespace { <Namespace as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Option < swc_atoms :: Atom >`.\n\nBy default, this method calls \ [`Option < swc_atoms :: Atom >::fold_children_with`]. If you want to recurse, you \ need to call it manually."] #[inline] fn fold_opt_atom(&mut self, node: Option<swc_atoms::Atom>) -> Option<swc_atoms::Atom> { <Option<swc_atoms::Atom> as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Option < Namespace >`.\n\nBy default, this method calls \ [`Option < Namespace >::fold_children_with`]. If you want to recurse, you need to \ call it manually."] #[inline] fn fold_opt_namespace(&mut self, node: Option<Namespace>) -> Option<Namespace> { <Option<Namespace> as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `ProcessingInstruction`.\n\nBy default, this method calls \ [`ProcessingInstruction::fold_children_with`]. If you want to recurse, you need to \ call it manually."] #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, ) -> ProcessingInstruction { <ProcessingInstruction as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `swc_common :: Span`.\n\nBy default, this method calls \ [`swc_common :: Span::fold_children_with`]. If you want to recurse, you need to call \ it manually."] #[inline] fn fold_span(&mut self, node: swc_common::Span) -> swc_common::Span { <swc_common::Span as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Text`.\n\nBy default, this method calls \ [`Text::fold_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn fold_text(&mut self, node: Text) -> Text { <Text as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `Token`.\n\nBy default, this method calls \ [`Token::fold_children_with`]. If you want to recurse, you need to call it manually."] #[inline] fn fold_token(&mut self, node: Token) -> Token { <Token as FoldWith<Self>>::fold_children_with(node, self) } #[doc = "Visit a node of type `TokenAndSpan`.\n\nBy default, this method calls \ [`TokenAndSpan::fold_children_with`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_token_and_span(&mut self, node: TokenAndSpan) -> TokenAndSpan { <TokenAndSpan as FoldWith<Self>>::fold_children_with(node, self) } } impl<V> Fold for &mut V where V: ?Sized + Fold, { #[inline] fn fold_atom(&mut self, node: swc_atoms::Atom) -> swc_atoms::Atom { <V as Fold>::fold_atom(&mut **self, node) } #[inline] fn fold_attribute(&mut self, node: Attribute) -> Attribute { <V as Fold>::fold_attribute(&mut **self, node) } #[inline] fn fold_attribute_token(&mut self, node: AttributeToken) -> AttributeToken { <V as Fold>::fold_attribute_token(&mut **self, node) } #[inline] fn fold_attribute_tokens(&mut self, node: Vec<AttributeToken>) -> Vec<AttributeToken> { <V as Fold>::fold_attribute_tokens(&mut **self, node) } #[inline] fn fold_attributes(&mut self, node: Vec<Attribute>) -> Vec<Attribute> { <V as Fold>::fold_attributes(&mut **self, node) } #[inline] fn fold_cdata_section(&mut self, node: CdataSection) -> CdataSection { <V as Fold>::fold_cdata_section(&mut **self, node) } #[inline] fn fold_child(&mut self, node: Child) -> Child { <V as Fold>::fold_child(&mut **self, node) } #[inline] fn fold_childs(&mut self, node: Vec<Child>) -> Vec<Child> { <V as Fold>::fold_childs(&mut **self, node) } #[inline] fn fold_comment(&mut self, node: Comment) -> Comment { <V as Fold>::fold_comment(&mut **self, node) } #[inline] fn fold_document(&mut self, node: Document) -> Document { <V as Fold>::fold_document(&mut **self, node) } #[inline] fn fold_document_mode(&mut self, node: DocumentMode) -> DocumentMode { <V as Fold>::fold_document_mode(&mut **self, node) } #[inline] fn fold_document_type(&mut self, node: DocumentType) -> DocumentType { <V as Fold>::fold_document_type(&mut **self, node) } #[inline] fn fold_element(&mut self, node: Element) -> Element { <V as Fold>::fold_element(&mut **self, node) } #[inline] fn fold_namespace(&mut self, node: Namespace) -> Namespace { <V as Fold>::fold_namespace(&mut **self, node) } #[inline] fn fold_opt_atom(&mut self, node: Option<swc_atoms::Atom>) -> Option<swc_atoms::Atom> { <V as Fold>::fold_opt_atom(&mut **self, node) } #[inline] fn fold_opt_namespace(&mut self, node: Option<Namespace>) -> Option<Namespace> { <V as Fold>::fold_opt_namespace(&mut **self, node) } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, ) -> ProcessingInstruction { <V as Fold>::fold_processing_instruction(&mut **self, node) } #[inline] fn fold_span(&mut self, node: swc_common::Span) -> swc_common::Span { <V as Fold>::fold_span(&mut **self, node) } #[inline] fn fold_text(&mut self, node: Text) -> Text { <V as Fold>::fold_text(&mut **self, node) } #[inline] fn fold_token(&mut self, node: Token) -> Token { <V as Fold>::fold_token(&mut **self, node) } #[inline] fn fold_token_and_span(&mut self, node: TokenAndSpan) -> TokenAndSpan { <V as Fold>::fold_token_and_span(&mut **self, node) } } impl<V> Fold for Box<V> where V: ?Sized + Fold, { #[inline] fn fold_atom(&mut self, node: swc_atoms::Atom) -> swc_atoms::Atom { <V as Fold>::fold_atom(&mut **self, node) } #[inline] fn fold_attribute(&mut self, node: Attribute) -> Attribute { <V as Fold>::fold_attribute(&mut **self, node) } #[inline] fn fold_attribute_token(&mut self, node: AttributeToken) -> AttributeToken { <V as Fold>::fold_attribute_token(&mut **self, node) } #[inline] fn fold_attribute_tokens(&mut self, node: Vec<AttributeToken>) -> Vec<AttributeToken> { <V as Fold>::fold_attribute_tokens(&mut **self, node) } #[inline] fn fold_attributes(&mut self, node: Vec<Attribute>) -> Vec<Attribute> { <V as Fold>::fold_attributes(&mut **self, node) } #[inline] fn fold_cdata_section(&mut self, node: CdataSection) -> CdataSection { <V as Fold>::fold_cdata_section(&mut **self, node) } #[inline] fn fold_child(&mut self, node: Child) -> Child { <V as Fold>::fold_child(&mut **self, node) } #[inline] fn fold_childs(&mut self, node: Vec<Child>) -> Vec<Child> { <V as Fold>::fold_childs(&mut **self, node) } #[inline] fn fold_comment(&mut self, node: Comment) -> Comment { <V as Fold>::fold_comment(&mut **self, node) } #[inline] fn fold_document(&mut self, node: Document) -> Document { <V as Fold>::fold_document(&mut **self, node) } #[inline] fn fold_document_mode(&mut self, node: DocumentMode) -> DocumentMode { <V as Fold>::fold_document_mode(&mut **self, node) } #[inline] fn fold_document_type(&mut self, node: DocumentType) -> DocumentType { <V as Fold>::fold_document_type(&mut **self, node) } #[inline] fn fold_element(&mut self, node: Element) -> Element { <V as Fold>::fold_element(&mut **self, node) } #[inline] fn fold_namespace(&mut self, node: Namespace) -> Namespace { <V as Fold>::fold_namespace(&mut **self, node) } #[inline] fn fold_opt_atom(&mut self, node: Option<swc_atoms::Atom>) -> Option<swc_atoms::Atom> { <V as Fold>::fold_opt_atom(&mut **self, node) } #[inline] fn fold_opt_namespace(&mut self, node: Option<Namespace>) -> Option<Namespace> { <V as Fold>::fold_opt_namespace(&mut **self, node) } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, ) -> ProcessingInstruction { <V as Fold>::fold_processing_instruction(&mut **self, node) } #[inline] fn fold_span(&mut self, node: swc_common::Span) -> swc_common::Span { <V as Fold>::fold_span(&mut **self, node) } #[inline] fn fold_text(&mut self, node: Text) -> Text { <V as Fold>::fold_text(&mut **self, node) } #[inline] fn fold_token(&mut self, node: Token) -> Token { <V as Fold>::fold_token(&mut **self, node) } #[inline] fn fold_token_and_span(&mut self, node: TokenAndSpan) -> TokenAndSpan { <V as Fold>::fold_token_and_span(&mut **self, node) } } impl<A, B> Fold for ::swc_visit::Either<A, B> where A: Fold, B: Fold, { #[inline] fn fold_atom(&mut self, node: swc_atoms::Atom) -> swc_atoms::Atom { match self { swc_visit::Either::Left(visitor) => Fold::fold_atom(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_atom(visitor, node), } } #[inline] fn fold_attribute(&mut self, node: Attribute) -> Attribute { match self { swc_visit::Either::Left(visitor) => Fold::fold_attribute(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_attribute(visitor, node), } } #[inline] fn fold_attribute_token(&mut self, node: AttributeToken) -> AttributeToken { match self { swc_visit::Either::Left(visitor) => Fold::fold_attribute_token(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_attribute_token(visitor, node), } } #[inline] fn fold_attribute_tokens(&mut self, node: Vec<AttributeToken>) -> Vec<AttributeToken> { match self { swc_visit::Either::Left(visitor) => Fold::fold_attribute_tokens(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_attribute_tokens(visitor, node), } } #[inline] fn fold_attributes(&mut self, node: Vec<Attribute>) -> Vec<Attribute> { match self { swc_visit::Either::Left(visitor) => Fold::fold_attributes(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_attributes(visitor, node), } } #[inline] fn fold_cdata_section(&mut self, node: CdataSection) -> CdataSection { match self { swc_visit::Either::Left(visitor) => Fold::fold_cdata_section(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_cdata_section(visitor, node), } } #[inline] fn fold_child(&mut self, node: Child) -> Child { match self { swc_visit::Either::Left(visitor) => Fold::fold_child(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_child(visitor, node), } } #[inline] fn fold_childs(&mut self, node: Vec<Child>) -> Vec<Child> { match self { swc_visit::Either::Left(visitor) => Fold::fold_childs(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_childs(visitor, node), } } #[inline] fn fold_comment(&mut self, node: Comment) -> Comment { match self { swc_visit::Either::Left(visitor) => Fold::fold_comment(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_comment(visitor, node), } } #[inline] fn fold_document(&mut self, node: Document) -> Document { match self { swc_visit::Either::Left(visitor) => Fold::fold_document(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_document(visitor, node), } } #[inline] fn fold_document_mode(&mut self, node: DocumentMode) -> DocumentMode { match self { swc_visit::Either::Left(visitor) => Fold::fold_document_mode(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_document_mode(visitor, node), } } #[inline] fn fold_document_type(&mut self, node: DocumentType) -> DocumentType { match self { swc_visit::Either::Left(visitor) => Fold::fold_document_type(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_document_type(visitor, node), } } #[inline] fn fold_element(&mut self, node: Element) -> Element { match self { swc_visit::Either::Left(visitor) => Fold::fold_element(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_element(visitor, node), } } #[inline] fn fold_namespace(&mut self, node: Namespace) -> Namespace { match self { swc_visit::Either::Left(visitor) => Fold::fold_namespace(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_namespace(visitor, node), } } #[inline] fn fold_opt_atom(&mut self, node: Option<swc_atoms::Atom>) -> Option<swc_atoms::Atom> { match self { swc_visit::Either::Left(visitor) => Fold::fold_opt_atom(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_opt_atom(visitor, node), } } #[inline] fn fold_opt_namespace(&mut self, node: Option<Namespace>) -> Option<Namespace> { match self { swc_visit::Either::Left(visitor) => Fold::fold_opt_namespace(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_opt_namespace(visitor, node), } } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, ) -> ProcessingInstruction { match self { swc_visit::Either::Left(visitor) => Fold::fold_processing_instruction(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_processing_instruction(visitor, node), } } #[inline] fn fold_span(&mut self, node: swc_common::Span) -> swc_common::Span { match self { swc_visit::Either::Left(visitor) => Fold::fold_span(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_span(visitor, node), } } #[inline] fn fold_text(&mut self, node: Text) -> Text { match self { swc_visit::Either::Left(visitor) => Fold::fold_text(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_text(visitor, node), } } #[inline] fn fold_token(&mut self, node: Token) -> Token { match self { swc_visit::Either::Left(visitor) => Fold::fold_token(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_token(visitor, node), } } #[inline] fn fold_token_and_span(&mut self, node: TokenAndSpan) -> TokenAndSpan { match self { swc_visit::Either::Left(visitor) => Fold::fold_token_and_span(visitor, node), swc_visit::Either::Right(visitor) => Fold::fold_token_and_span(visitor, node), } } } impl<V> Fold for ::swc_visit::Optional<V> where V: Fold, { #[inline] fn fold_atom(&mut self, node: swc_atoms::Atom) -> swc_atoms::Atom { if self.enabled { <V as Fold>::fold_atom(&mut self.visitor, node) } else { node } } #[inline] fn fold_attribute(&mut self, node: Attribute) -> Attribute { if self.enabled { <V as Fold>::fold_attribute(&mut self.visitor, node) } else { node } } #[inline] fn fold_attribute_token(&mut self, node: AttributeToken) -> AttributeToken { if self.enabled { <V as Fold>::fold_attribute_token(&mut self.visitor, node) } else { node } } #[inline] fn fold_attribute_tokens(&mut self, node: Vec<AttributeToken>) -> Vec<AttributeToken> { if self.enabled { <V as Fold>::fold_attribute_tokens(&mut self.visitor, node) } else { node } } #[inline] fn fold_attributes(&mut self, node: Vec<Attribute>) -> Vec<Attribute> { if self.enabled { <V as Fold>::fold_attributes(&mut self.visitor, node) } else { node } } #[inline] fn fold_cdata_section(&mut self, node: CdataSection) -> CdataSection { if self.enabled { <V as Fold>::fold_cdata_section(&mut self.visitor, node) } else { node } } #[inline] fn fold_child(&mut self, node: Child) -> Child { if self.enabled { <V as Fold>::fold_child(&mut self.visitor, node) } else { node } } #[inline] fn fold_childs(&mut self, node: Vec<Child>) -> Vec<Child> { if self.enabled { <V as Fold>::fold_childs(&mut self.visitor, node) } else { node } } #[inline] fn fold_comment(&mut self, node: Comment) -> Comment { if self.enabled { <V as Fold>::fold_comment(&mut self.visitor, node) } else { node } } #[inline] fn fold_document(&mut self, node: Document) -> Document { if self.enabled { <V as Fold>::fold_document(&mut self.visitor, node) } else { node } } #[inline] fn fold_document_mode(&mut self, node: DocumentMode) -> DocumentMode { if self.enabled { <V as Fold>::fold_document_mode(&mut self.visitor, node) } else { node } } #[inline] fn fold_document_type(&mut self, node: DocumentType) -> DocumentType { if self.enabled { <V as Fold>::fold_document_type(&mut self.visitor, node) } else { node } } #[inline] fn fold_element(&mut self, node: Element) -> Element { if self.enabled { <V as Fold>::fold_element(&mut self.visitor, node) } else { node } } #[inline] fn fold_namespace(&mut self, node: Namespace) -> Namespace { if self.enabled { <V as Fold>::fold_namespace(&mut self.visitor, node) } else { node } } #[inline] fn fold_opt_atom(&mut self, node: Option<swc_atoms::Atom>) -> Option<swc_atoms::Atom> { if self.enabled { <V as Fold>::fold_opt_atom(&mut self.visitor, node) } else { node } } #[inline] fn fold_opt_namespace(&mut self, node: Option<Namespace>) -> Option<Namespace> { if self.enabled { <V as Fold>::fold_opt_namespace(&mut self.visitor, node) } else { node } } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, ) -> ProcessingInstruction { if self.enabled { <V as Fold>::fold_processing_instruction(&mut self.visitor, node) } else { node } } #[inline] fn fold_span(&mut self, node: swc_common::Span) -> swc_common::Span { if self.enabled { <V as Fold>::fold_span(&mut self.visitor, node) } else { node } } #[inline] fn fold_text(&mut self, node: Text) -> Text { if self.enabled { <V as Fold>::fold_text(&mut self.visitor, node) } else { node } } #[inline] fn fold_token(&mut self, node: Token) -> Token { if self.enabled { <V as Fold>::fold_token(&mut self.visitor, node) } else { node } } #[inline] fn fold_token_and_span(&mut self, node: TokenAndSpan) -> TokenAndSpan { if self.enabled { <V as Fold>::fold_token_and_span(&mut self.visitor, node) } else { node } } } #[doc = r" A trait implemented for types that can be visited using a visitor."] pub trait FoldWith<V: ?Sized + Fold> { #[doc = r" Calls a visitor method (visitor.fold_xxx) with self."] fn fold_with(self, visitor: &mut V) -> Self; #[doc = r" Visit children nodes of `self`` with `visitor`."] fn fold_children_with(self, visitor: &mut V) -> Self; } impl<V: ?Sized + Fold> FoldWith<V> for Attribute { #[doc = "Calls [Fold`::fold_attribute`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_attribute(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let namespace = { <Option<Namespace> as FoldWith<V>>::fold_with(namespace, visitor) }; let prefix = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(prefix, visitor) }; let name = { <swc_atoms::Atom as FoldWith<V>>::fold_with(name, visitor) }; let raw_name = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw_name, visitor) }; let value = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(value, visitor) }; let raw_value = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw_value, visitor) }; Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } } } } } impl<V: ?Sized + Fold> FoldWith<V> for AttributeToken { #[doc = "Calls [Fold`::fold_attribute_token`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_attribute_token(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { AttributeToken { span, name, raw_name, value, raw_value, } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let name = { <swc_atoms::Atom as FoldWith<V>>::fold_with(name, visitor) }; let raw_name = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw_name, visitor) }; let value = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(value, visitor) }; let raw_value = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw_value, visitor) }; AttributeToken { span, name, raw_name, value, raw_value, } } } } } impl<V: ?Sized + Fold> FoldWith<V> for CdataSection { #[doc = "Calls [Fold`::fold_cdata_section`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_cdata_section(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { CdataSection { span, data, raw } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let data = { <swc_atoms::Atom as FoldWith<V>>::fold_with(data, visitor) }; let raw = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw, visitor) }; CdataSection { span, data, raw } } } } } impl<V: ?Sized + Fold> FoldWith<V> for Child { #[doc = "Calls [Fold`::fold_child`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_child(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Child::DocumentType { 0: _field_0 } => { let _field_0 = <DocumentType as FoldWith<V>>::fold_with(_field_0, visitor); Child::DocumentType { 0: _field_0 } } Child::Element { 0: _field_0 } => { let _field_0 = <Element as FoldWith<V>>::fold_with(_field_0, visitor); Child::Element { 0: _field_0 } } Child::Text { 0: _field_0 } => { let _field_0 = <Text as FoldWith<V>>::fold_with(_field_0, visitor); Child::Text { 0: _field_0 } } Child::CdataSection { 0: _field_0 } => { let _field_0 = <CdataSection as FoldWith<V>>::fold_with(_field_0, visitor); Child::CdataSection { 0: _field_0 } } Child::Comment { 0: _field_0 } => { let _field_0 = <Comment as FoldWith<V>>::fold_with(_field_0, visitor); Child::Comment { 0: _field_0 } } Child::ProcessingInstruction { 0: _field_0 } => { let _field_0 = <ProcessingInstruction as FoldWith<V>>::fold_with(_field_0, visitor); Child::ProcessingInstruction { 0: _field_0 } } } } } impl<V: ?Sized + Fold> FoldWith<V> for Comment { #[doc = "Calls [Fold`::fold_comment`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_comment(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Comment { span, data, raw } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let data = { <swc_atoms::Atom as FoldWith<V>>::fold_with(data, visitor) }; let raw = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw, visitor) }; Comment { span, data, raw } } } } } impl<V: ?Sized + Fold> FoldWith<V> for Document { #[doc = "Calls [Fold`::fold_document`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_document(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Document { span, children } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let children = { <Vec<Child> as FoldWith<V>>::fold_with(children, visitor) }; Document { span, children } } } } } impl<V: ?Sized + Fold> FoldWith<V> for DocumentMode { #[doc = "Calls [Fold`::fold_document_mode`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_document_mode(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { DocumentMode::NoQuirks => DocumentMode::NoQuirks, DocumentMode::LimitedQuirks => DocumentMode::LimitedQuirks, DocumentMode::Quirks => DocumentMode::Quirks, } } } impl<V: ?Sized + Fold> FoldWith<V> for DocumentType { #[doc = "Calls [Fold`::fold_document_type`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_document_type(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { DocumentType { span, name, public_id, system_id, raw, } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let name = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(name, visitor) }; let public_id = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(public_id, visitor) }; let system_id = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(system_id, visitor) }; let raw = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw, visitor) }; DocumentType { span, name, public_id, system_id, raw, } } } } } impl<V: ?Sized + Fold> FoldWith<V> for Element { #[doc = "Calls [Fold`::fold_element`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_element(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Element { span, tag_name, attributes, children, } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let tag_name = { <swc_atoms::Atom as FoldWith<V>>::fold_with(tag_name, visitor) }; let attributes = { <Vec<Attribute> as FoldWith<V>>::fold_with(attributes, visitor) }; let children = { <Vec<Child> as FoldWith<V>>::fold_with(children, visitor) }; Element { span, tag_name, attributes, children, } } } } } impl<V: ?Sized + Fold> FoldWith<V> for Namespace { #[doc = "Calls [Fold`::fold_namespace`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_namespace(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Namespace::HTML => Namespace::HTML, Namespace::MATHML => Namespace::MATHML, Namespace::SVG => Namespace::SVG, Namespace::XLINK => Namespace::XLINK, Namespace::XML => Namespace::XML, Namespace::XMLNS => Namespace::XMLNS, } } } impl<V: ?Sized + Fold> FoldWith<V> for ProcessingInstruction { #[doc = "Calls [Fold`::fold_processing_instruction`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_processing_instruction(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { ProcessingInstruction { span, target, data } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let target = { <swc_atoms::Atom as FoldWith<V>>::fold_with(target, visitor) }; let data = { <swc_atoms::Atom as FoldWith<V>>::fold_with(data, visitor) }; ProcessingInstruction { span, target, data } } } } } impl<V: ?Sized + Fold> FoldWith<V> for Text { #[doc = "Calls [Fold`::fold_text`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_text(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Text { span, data, raw } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let data = { <swc_atoms::Atom as FoldWith<V>>::fold_with(data, visitor) }; let raw = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw, visitor) }; Text { span, data, raw } } } } } impl<V: ?Sized + Fold> FoldWith<V> for Token { #[doc = "Calls [Fold`::fold_token`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_token(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { Token::Doctype { name, public_id, system_id, raw, } => { let name = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(name, visitor) }; let public_id = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(public_id, visitor) }; let system_id = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(system_id, visitor) }; let raw = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw, visitor) }; Token::Doctype { name, public_id, system_id, raw, } } Token::StartTag { tag_name, attributes, } => { let tag_name = { <swc_atoms::Atom as FoldWith<V>>::fold_with(tag_name, visitor) }; let attributes = { <Vec<AttributeToken> as FoldWith<V>>::fold_with(attributes, visitor) }; Token::StartTag { tag_name, attributes, } } Token::EndTag { tag_name, attributes, } => { let tag_name = { <swc_atoms::Atom as FoldWith<V>>::fold_with(tag_name, visitor) }; let attributes = { <Vec<AttributeToken> as FoldWith<V>>::fold_with(attributes, visitor) }; Token::EndTag { tag_name, attributes, } } Token::EmptyTag { tag_name, attributes, } => { let tag_name = { <swc_atoms::Atom as FoldWith<V>>::fold_with(tag_name, visitor) }; let attributes = { <Vec<AttributeToken> as FoldWith<V>>::fold_with(attributes, visitor) }; Token::EmptyTag { tag_name, attributes, } } Token::Comment { data, raw } => { let data = { <swc_atoms::Atom as FoldWith<V>>::fold_with(data, visitor) }; let raw = { <swc_atoms::Atom as FoldWith<V>>::fold_with(raw, visitor) }; Token::Comment { data, raw } } Token::Character { value, raw } => { let raw = { <Option<swc_atoms::Atom> as FoldWith<V>>::fold_with(raw, visitor) }; Token::Character { value, raw } } Token::ProcessingInstruction { target, data } => { let target = { <swc_atoms::Atom as FoldWith<V>>::fold_with(target, visitor) }; let data = { <swc_atoms::Atom as FoldWith<V>>::fold_with(data, visitor) }; Token::ProcessingInstruction { target, data } } Token::Cdata { data, raw } => { let data = { <swc_atoms::Atom as FoldWith<V>>::fold_with(data, visitor) }; let raw = { <swc_atoms::Atom as FoldWith<V>>::fold_with(raw, visitor) }; Token::Cdata { data, raw } } Token::Eof => Token::Eof, } } } impl<V: ?Sized + Fold> FoldWith<V> for TokenAndSpan { #[doc = "Calls [Fold`::fold_token_and_span`] with `self`."] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_token_and_span(visitor, self) } fn fold_children_with(self, visitor: &mut V) -> Self { match self { TokenAndSpan { span, token } => { let span = { <swc_common::Span as FoldWith<V>>::fold_with(span, visitor) }; let token = { <Token as FoldWith<V>>::fold_with(token, visitor) }; TokenAndSpan { span, token } } } } } impl<V: ?Sized + Fold> FoldWith<V> for swc_atoms::Atom { #[doc = "Calls [Fold`::fold_atom`] with `self`. (Extra impl)"] #[inline] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_atom(visitor, self) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { self } } impl<V: ?Sized + Fold> FoldWith<V> for Vec<AttributeToken> { #[doc = "Calls [Fold`::fold_attribute_tokens`] with `self`. (Extra impl)"] #[inline] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_attribute_tokens(visitor, self) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { swc_visit::util::move_map::MoveMap::move_map(self, |item| { <AttributeToken as FoldWith<V>>::fold_with(item, visitor) }) } } impl<V: ?Sized + Fold> FoldWith<V> for Vec<Attribute> { #[doc = "Calls [Fold`::fold_attributes`] with `self`. (Extra impl)"] #[inline] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_attributes(visitor, self) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { swc_visit::util::move_map::MoveMap::move_map(self, |item| { <Attribute as FoldWith<V>>::fold_with(item, visitor) }) } } impl<V: ?Sized + Fold> FoldWith<V> for Vec<Child> { #[doc = "Calls [Fold`::fold_childs`] with `self`. (Extra impl)"] #[inline] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_childs(visitor, self) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { swc_visit::util::move_map::MoveMap::move_map(self, |item| { <Child as FoldWith<V>>::fold_with(item, visitor) }) } } impl<V: ?Sized + Fold> FoldWith<V> for Option<swc_atoms::Atom> { #[doc = "Calls [Fold`::fold_opt_atom`] with `self`. (Extra impl)"] #[inline] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_opt_atom(visitor, self) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { self.map(|inner| <swc_atoms::Atom as FoldWith<V>>::fold_with(inner, visitor)) } } impl<V: ?Sized + Fold> FoldWith<V> for Option<Namespace> { #[doc = "Calls [Fold`::fold_opt_namespace`] with `self`. (Extra impl)"] #[inline] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_opt_namespace(visitor, self) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { self.map(|inner| <Namespace as FoldWith<V>>::fold_with(inner, visitor)) } } impl<V: ?Sized + Fold> FoldWith<V> for swc_common::Span { #[doc = "Calls [Fold`::fold_span`] with `self`. (Extra impl)"] #[inline] fn fold_with(self, visitor: &mut V) -> Self { <V as Fold>::fold_span(visitor, self) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { self } } impl<V, T> FoldWith<V> for std::boxed::Box<T> where V: ?Sized + Fold, T: FoldWith<V>, { #[inline] fn fold_with(self, visitor: &mut V) -> Self { swc_visit::util::map::Map::map(self, |inner| <T as FoldWith<V>>::fold_with(inner, visitor)) } #[inline] fn fold_children_with(self, visitor: &mut V) -> Self { swc_visit::util::map::Map::map(self, |inner| { <T as FoldWith<V>>::fold_children_with(inner, visitor) }) } } #[doc = r" A visitor trait for traversing the AST."] #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] pub trait FoldAstPath { #[doc = "Visit a node of type `swc_atoms :: Atom`.\n\nBy default, this method calls \ [`swc_atoms :: Atom::fold_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn fold_atom( &mut self, node: swc_atoms::Atom, __ast_path: &mut AstKindPath, ) -> swc_atoms::Atom { <swc_atoms::Atom as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Attribute`.\n\nBy default, this method calls \ [`Attribute::fold_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn fold_attribute(&mut self, node: Attribute, __ast_path: &mut AstKindPath) -> Attribute { <Attribute as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `AttributeToken`.\n\nBy default, this method calls \ [`AttributeToken::fold_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn fold_attribute_token( &mut self, node: AttributeToken, __ast_path: &mut AstKindPath, ) -> AttributeToken { <AttributeToken as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Vec < AttributeToken >`.\n\nBy default, this method calls [`Vec \ < AttributeToken >::fold_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn fold_attribute_tokens( &mut self, node: Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) -> Vec<AttributeToken> { <Vec<AttributeToken> as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Vec < Attribute >`.\n\nBy default, this method calls [`Vec < \ Attribute >::fold_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn fold_attributes( &mut self, node: Vec<Attribute>, __ast_path: &mut AstKindPath, ) -> Vec<Attribute> { <Vec<Attribute> as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `CdataSection`.\n\nBy default, this method calls \ [`CdataSection::fold_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn fold_cdata_section( &mut self, node: CdataSection, __ast_path: &mut AstKindPath, ) -> CdataSection { <CdataSection as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Child`.\n\nBy default, this method calls \ [`Child::fold_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_child(&mut self, node: Child, __ast_path: &mut AstKindPath) -> Child { <Child as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Vec < Child >`.\n\nBy default, this method calls [`Vec < Child \ >::fold_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_childs(&mut self, node: Vec<Child>, __ast_path: &mut AstKindPath) -> Vec<Child> { <Vec<Child> as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Comment`.\n\nBy default, this method calls \ [`Comment::fold_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_comment(&mut self, node: Comment, __ast_path: &mut AstKindPath) -> Comment { <Comment as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Document`.\n\nBy default, this method calls \ [`Document::fold_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn fold_document(&mut self, node: Document, __ast_path: &mut AstKindPath) -> Document { <Document as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `DocumentMode`.\n\nBy default, this method calls \ [`DocumentMode::fold_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn fold_document_mode( &mut self, node: DocumentMode, __ast_path: &mut AstKindPath, ) -> DocumentMode { <DocumentMode as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `DocumentType`.\n\nBy default, this method calls \ [`DocumentType::fold_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn fold_document_type( &mut self, node: DocumentType, __ast_path: &mut AstKindPath, ) -> DocumentType { <DocumentType as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Element`.\n\nBy default, this method calls \ [`Element::fold_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_element(&mut self, node: Element, __ast_path: &mut AstKindPath) -> Element { <Element as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Namespace`.\n\nBy default, this method calls \ [`Namespace::fold_children_with_ast_path`]. If you want to recurse, you need to call \ it manually."] #[inline] fn fold_namespace(&mut self, node: Namespace, __ast_path: &mut AstKindPath) -> Namespace { <Namespace as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Option < swc_atoms :: Atom >`.\n\nBy default, this method calls \ [`Option < swc_atoms :: Atom >::fold_children_with_ast_path`]. If you want to \ recurse, you need to call it manually."] #[inline] fn fold_opt_atom( &mut self, node: Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) -> Option<swc_atoms::Atom> { <Option<swc_atoms::Atom> as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Option < Namespace >`.\n\nBy default, this method calls \ [`Option < Namespace >::fold_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn fold_opt_namespace( &mut self, node: Option<Namespace>, __ast_path: &mut AstKindPath, ) -> Option<Namespace> { <Option<Namespace> as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `ProcessingInstruction`.\n\nBy default, this method calls \ [`ProcessingInstruction::fold_children_with_ast_path`]. If you want to recurse, you \ need to call it manually."] #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, __ast_path: &mut AstKindPath, ) -> ProcessingInstruction { <ProcessingInstruction as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `swc_common :: Span`.\n\nBy default, this method calls \ [`swc_common :: Span::fold_children_with_ast_path`]. If you want to recurse, you need \ to call it manually."] #[inline] fn fold_span( &mut self, node: swc_common::Span, __ast_path: &mut AstKindPath, ) -> swc_common::Span { <swc_common::Span as FoldWithAstPath<Self>>::fold_children_with_ast_path( node, self, __ast_path, ) } #[doc = "Visit a node of type `Text`.\n\nBy default, this method calls \ [`Text::fold_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_text(&mut self, node: Text, __ast_path: &mut AstKindPath) -> Text { <Text as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `Token`.\n\nBy default, this method calls \ [`Token::fold_children_with_ast_path`]. If you want to recurse, you need to call it \ manually."] #[inline] fn fold_token(&mut self, node: Token, __ast_path: &mut AstKindPath) -> Token { <Token as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } #[doc = "Visit a node of type `TokenAndSpan`.\n\nBy default, this method calls \ [`TokenAndSpan::fold_children_with_ast_path`]. If you want to recurse, you need to \ call it manually."] #[inline] fn fold_token_and_span( &mut self, node: TokenAndSpan, __ast_path: &mut AstKindPath, ) -> TokenAndSpan { <TokenAndSpan as FoldWithAstPath<Self>>::fold_children_with_ast_path(node, self, __ast_path) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> FoldAstPath for &mut V where V: ?Sized + FoldAstPath, { #[inline] fn fold_atom( &mut self, node: swc_atoms::Atom, __ast_path: &mut AstKindPath, ) -> swc_atoms::Atom { <V as FoldAstPath>::fold_atom(&mut **self, node, __ast_path) } #[inline] fn fold_attribute(&mut self, node: Attribute, __ast_path: &mut AstKindPath) -> Attribute { <V as FoldAstPath>::fold_attribute(&mut **self, node, __ast_path) } #[inline] fn fold_attribute_token( &mut self, node: AttributeToken, __ast_path: &mut AstKindPath, ) -> AttributeToken { <V as FoldAstPath>::fold_attribute_token(&mut **self, node, __ast_path) } #[inline] fn fold_attribute_tokens( &mut self, node: Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) -> Vec<AttributeToken> { <V as FoldAstPath>::fold_attribute_tokens(&mut **self, node, __ast_path) } #[inline] fn fold_attributes( &mut self, node: Vec<Attribute>, __ast_path: &mut AstKindPath, ) -> Vec<Attribute> { <V as FoldAstPath>::fold_attributes(&mut **self, node, __ast_path) } #[inline] fn fold_cdata_section( &mut self, node: CdataSection, __ast_path: &mut AstKindPath, ) -> CdataSection { <V as FoldAstPath>::fold_cdata_section(&mut **self, node, __ast_path) } #[inline] fn fold_child(&mut self, node: Child, __ast_path: &mut AstKindPath) -> Child { <V as FoldAstPath>::fold_child(&mut **self, node, __ast_path) } #[inline] fn fold_childs(&mut self, node: Vec<Child>, __ast_path: &mut AstKindPath) -> Vec<Child> { <V as FoldAstPath>::fold_childs(&mut **self, node, __ast_path) } #[inline] fn fold_comment(&mut self, node: Comment, __ast_path: &mut AstKindPath) -> Comment { <V as FoldAstPath>::fold_comment(&mut **self, node, __ast_path) } #[inline] fn fold_document(&mut self, node: Document, __ast_path: &mut AstKindPath) -> Document { <V as FoldAstPath>::fold_document(&mut **self, node, __ast_path) } #[inline] fn fold_document_mode( &mut self, node: DocumentMode, __ast_path: &mut AstKindPath, ) -> DocumentMode { <V as FoldAstPath>::fold_document_mode(&mut **self, node, __ast_path) } #[inline] fn fold_document_type( &mut self, node: DocumentType, __ast_path: &mut AstKindPath, ) -> DocumentType { <V as FoldAstPath>::fold_document_type(&mut **self, node, __ast_path) } #[inline] fn fold_element(&mut self, node: Element, __ast_path: &mut AstKindPath) -> Element { <V as FoldAstPath>::fold_element(&mut **self, node, __ast_path) } #[inline] fn fold_namespace(&mut self, node: Namespace, __ast_path: &mut AstKindPath) -> Namespace { <V as FoldAstPath>::fold_namespace(&mut **self, node, __ast_path) } #[inline] fn fold_opt_atom( &mut self, node: Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) -> Option<swc_atoms::Atom> { <V as FoldAstPath>::fold_opt_atom(&mut **self, node, __ast_path) } #[inline] fn fold_opt_namespace( &mut self, node: Option<Namespace>, __ast_path: &mut AstKindPath, ) -> Option<Namespace> { <V as FoldAstPath>::fold_opt_namespace(&mut **self, node, __ast_path) } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, __ast_path: &mut AstKindPath, ) -> ProcessingInstruction { <V as FoldAstPath>::fold_processing_instruction(&mut **self, node, __ast_path) } #[inline] fn fold_span( &mut self, node: swc_common::Span, __ast_path: &mut AstKindPath, ) -> swc_common::Span { <V as FoldAstPath>::fold_span(&mut **self, node, __ast_path) } #[inline] fn fold_text(&mut self, node: Text, __ast_path: &mut AstKindPath) -> Text { <V as FoldAstPath>::fold_text(&mut **self, node, __ast_path) } #[inline] fn fold_token(&mut self, node: Token, __ast_path: &mut AstKindPath) -> Token { <V as FoldAstPath>::fold_token(&mut **self, node, __ast_path) } #[inline] fn fold_token_and_span( &mut self, node: TokenAndSpan, __ast_path: &mut AstKindPath, ) -> TokenAndSpan { <V as FoldAstPath>::fold_token_and_span(&mut **self, node, __ast_path) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> FoldAstPath for Box<V> where V: ?Sized + FoldAstPath, { #[inline] fn fold_atom( &mut self, node: swc_atoms::Atom, __ast_path: &mut AstKindPath, ) -> swc_atoms::Atom { <V as FoldAstPath>::fold_atom(&mut **self, node, __ast_path) } #[inline] fn fold_attribute(&mut self, node: Attribute, __ast_path: &mut AstKindPath) -> Attribute { <V as FoldAstPath>::fold_attribute(&mut **self, node, __ast_path) } #[inline] fn fold_attribute_token( &mut self, node: AttributeToken, __ast_path: &mut AstKindPath, ) -> AttributeToken { <V as FoldAstPath>::fold_attribute_token(&mut **self, node, __ast_path) } #[inline] fn fold_attribute_tokens( &mut self, node: Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) -> Vec<AttributeToken> { <V as FoldAstPath>::fold_attribute_tokens(&mut **self, node, __ast_path) } #[inline] fn fold_attributes( &mut self, node: Vec<Attribute>, __ast_path: &mut AstKindPath, ) -> Vec<Attribute> { <V as FoldAstPath>::fold_attributes(&mut **self, node, __ast_path) } #[inline] fn fold_cdata_section( &mut self, node: CdataSection, __ast_path: &mut AstKindPath, ) -> CdataSection { <V as FoldAstPath>::fold_cdata_section(&mut **self, node, __ast_path) } #[inline] fn fold_child(&mut self, node: Child, __ast_path: &mut AstKindPath) -> Child { <V as FoldAstPath>::fold_child(&mut **self, node, __ast_path) } #[inline] fn fold_childs(&mut self, node: Vec<Child>, __ast_path: &mut AstKindPath) -> Vec<Child> { <V as FoldAstPath>::fold_childs(&mut **self, node, __ast_path) } #[inline] fn fold_comment(&mut self, node: Comment, __ast_path: &mut AstKindPath) -> Comment { <V as FoldAstPath>::fold_comment(&mut **self, node, __ast_path) } #[inline] fn fold_document(&mut self, node: Document, __ast_path: &mut AstKindPath) -> Document { <V as FoldAstPath>::fold_document(&mut **self, node, __ast_path) } #[inline] fn fold_document_mode( &mut self, node: DocumentMode, __ast_path: &mut AstKindPath, ) -> DocumentMode { <V as FoldAstPath>::fold_document_mode(&mut **self, node, __ast_path) } #[inline] fn fold_document_type( &mut self, node: DocumentType, __ast_path: &mut AstKindPath, ) -> DocumentType { <V as FoldAstPath>::fold_document_type(&mut **self, node, __ast_path) } #[inline] fn fold_element(&mut self, node: Element, __ast_path: &mut AstKindPath) -> Element { <V as FoldAstPath>::fold_element(&mut **self, node, __ast_path) } #[inline] fn fold_namespace(&mut self, node: Namespace, __ast_path: &mut AstKindPath) -> Namespace { <V as FoldAstPath>::fold_namespace(&mut **self, node, __ast_path) } #[inline] fn fold_opt_atom( &mut self, node: Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) -> Option<swc_atoms::Atom> { <V as FoldAstPath>::fold_opt_atom(&mut **self, node, __ast_path) } #[inline] fn fold_opt_namespace( &mut self, node: Option<Namespace>, __ast_path: &mut AstKindPath, ) -> Option<Namespace> { <V as FoldAstPath>::fold_opt_namespace(&mut **self, node, __ast_path) } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, __ast_path: &mut AstKindPath, ) -> ProcessingInstruction { <V as FoldAstPath>::fold_processing_instruction(&mut **self, node, __ast_path) } #[inline] fn fold_span( &mut self, node: swc_common::Span, __ast_path: &mut AstKindPath, ) -> swc_common::Span { <V as FoldAstPath>::fold_span(&mut **self, node, __ast_path) } #[inline] fn fold_text(&mut self, node: Text, __ast_path: &mut AstKindPath) -> Text { <V as FoldAstPath>::fold_text(&mut **self, node, __ast_path) } #[inline] fn fold_token(&mut self, node: Token, __ast_path: &mut AstKindPath) -> Token { <V as FoldAstPath>::fold_token(&mut **self, node, __ast_path) } #[inline] fn fold_token_and_span( &mut self, node: TokenAndSpan, __ast_path: &mut AstKindPath, ) -> TokenAndSpan { <V as FoldAstPath>::fold_token_and_span(&mut **self, node, __ast_path) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<A, B> FoldAstPath for ::swc_visit::Either<A, B> where A: FoldAstPath, B: FoldAstPath, { #[inline] fn fold_atom( &mut self, node: swc_atoms::Atom, __ast_path: &mut AstKindPath, ) -> swc_atoms::Atom { match self { swc_visit::Either::Left(visitor) => FoldAstPath::fold_atom(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => FoldAstPath::fold_atom(visitor, node, __ast_path), } } #[inline] fn fold_attribute(&mut self, node: Attribute, __ast_path: &mut AstKindPath) -> Attribute { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_attribute(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_attribute(visitor, node, __ast_path) } } } #[inline] fn fold_attribute_token( &mut self, node: AttributeToken, __ast_path: &mut AstKindPath, ) -> AttributeToken { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_attribute_token(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_attribute_token(visitor, node, __ast_path) } } } #[inline] fn fold_attribute_tokens( &mut self, node: Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) -> Vec<AttributeToken> { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_attribute_tokens(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_attribute_tokens(visitor, node, __ast_path) } } } #[inline] fn fold_attributes( &mut self, node: Vec<Attribute>, __ast_path: &mut AstKindPath, ) -> Vec<Attribute> { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_attributes(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_attributes(visitor, node, __ast_path) } } } #[inline] fn fold_cdata_section( &mut self, node: CdataSection, __ast_path: &mut AstKindPath, ) -> CdataSection { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_cdata_section(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_cdata_section(visitor, node, __ast_path) } } } #[inline] fn fold_child(&mut self, node: Child, __ast_path: &mut AstKindPath) -> Child { match self { swc_visit::Either::Left(visitor) => FoldAstPath::fold_child(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => FoldAstPath::fold_child(visitor, node, __ast_path), } } #[inline] fn fold_childs(&mut self, node: Vec<Child>, __ast_path: &mut AstKindPath) -> Vec<Child> { match self { swc_visit::Either::Left(visitor) => FoldAstPath::fold_childs(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => { FoldAstPath::fold_childs(visitor, node, __ast_path) } } } #[inline] fn fold_comment(&mut self, node: Comment, __ast_path: &mut AstKindPath) -> Comment { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_comment(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_comment(visitor, node, __ast_path) } } } #[inline] fn fold_document(&mut self, node: Document, __ast_path: &mut AstKindPath) -> Document { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_document(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_document(visitor, node, __ast_path) } } } #[inline] fn fold_document_mode( &mut self, node: DocumentMode, __ast_path: &mut AstKindPath, ) -> DocumentMode { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_document_mode(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_document_mode(visitor, node, __ast_path) } } } #[inline] fn fold_document_type( &mut self, node: DocumentType, __ast_path: &mut AstKindPath, ) -> DocumentType { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_document_type(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_document_type(visitor, node, __ast_path) } } } #[inline] fn fold_element(&mut self, node: Element, __ast_path: &mut AstKindPath) -> Element { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_element(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_element(visitor, node, __ast_path) } } } #[inline] fn fold_namespace(&mut self, node: Namespace, __ast_path: &mut AstKindPath) -> Namespace { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_namespace(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_namespace(visitor, node, __ast_path) } } } #[inline] fn fold_opt_atom( &mut self, node: Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) -> Option<swc_atoms::Atom> { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_opt_atom(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_opt_atom(visitor, node, __ast_path) } } } #[inline] fn fold_opt_namespace( &mut self, node: Option<Namespace>, __ast_path: &mut AstKindPath, ) -> Option<Namespace> { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_opt_namespace(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_opt_namespace(visitor, node, __ast_path) } } } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, __ast_path: &mut AstKindPath, ) -> ProcessingInstruction { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_processing_instruction(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_processing_instruction(visitor, node, __ast_path) } } } #[inline] fn fold_span( &mut self, node: swc_common::Span, __ast_path: &mut AstKindPath, ) -> swc_common::Span { match self { swc_visit::Either::Left(visitor) => FoldAstPath::fold_span(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => FoldAstPath::fold_span(visitor, node, __ast_path), } } #[inline] fn fold_text(&mut self, node: Text, __ast_path: &mut AstKindPath) -> Text { match self { swc_visit::Either::Left(visitor) => FoldAstPath::fold_text(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => FoldAstPath::fold_text(visitor, node, __ast_path), } } #[inline] fn fold_token(&mut self, node: Token, __ast_path: &mut AstKindPath) -> Token { match self { swc_visit::Either::Left(visitor) => FoldAstPath::fold_token(visitor, node, __ast_path), swc_visit::Either::Right(visitor) => FoldAstPath::fold_token(visitor, node, __ast_path), } } #[inline] fn fold_token_and_span( &mut self, node: TokenAndSpan, __ast_path: &mut AstKindPath, ) -> TokenAndSpan { match self { swc_visit::Either::Left(visitor) => { FoldAstPath::fold_token_and_span(visitor, node, __ast_path) } swc_visit::Either::Right(visitor) => { FoldAstPath::fold_token_and_span(visitor, node, __ast_path) } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V> FoldAstPath for ::swc_visit::Optional<V> where V: FoldAstPath, { #[inline] fn fold_atom( &mut self, node: swc_atoms::Atom, __ast_path: &mut AstKindPath, ) -> swc_atoms::Atom { if self.enabled { <V as FoldAstPath>::fold_atom(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_attribute(&mut self, node: Attribute, __ast_path: &mut AstKindPath) -> Attribute { if self.enabled { <V as FoldAstPath>::fold_attribute(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_attribute_token( &mut self, node: AttributeToken, __ast_path: &mut AstKindPath, ) -> AttributeToken { if self.enabled { <V as FoldAstPath>::fold_attribute_token(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_attribute_tokens( &mut self, node: Vec<AttributeToken>, __ast_path: &mut AstKindPath, ) -> Vec<AttributeToken> { if self.enabled { <V as FoldAstPath>::fold_attribute_tokens(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_attributes( &mut self, node: Vec<Attribute>, __ast_path: &mut AstKindPath, ) -> Vec<Attribute> { if self.enabled { <V as FoldAstPath>::fold_attributes(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_cdata_section( &mut self, node: CdataSection, __ast_path: &mut AstKindPath, ) -> CdataSection { if self.enabled { <V as FoldAstPath>::fold_cdata_section(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_child(&mut self, node: Child, __ast_path: &mut AstKindPath) -> Child { if self.enabled { <V as FoldAstPath>::fold_child(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_childs(&mut self, node: Vec<Child>, __ast_path: &mut AstKindPath) -> Vec<Child> { if self.enabled { <V as FoldAstPath>::fold_childs(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_comment(&mut self, node: Comment, __ast_path: &mut AstKindPath) -> Comment { if self.enabled { <V as FoldAstPath>::fold_comment(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_document(&mut self, node: Document, __ast_path: &mut AstKindPath) -> Document { if self.enabled { <V as FoldAstPath>::fold_document(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_document_mode( &mut self, node: DocumentMode, __ast_path: &mut AstKindPath, ) -> DocumentMode { if self.enabled { <V as FoldAstPath>::fold_document_mode(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_document_type( &mut self, node: DocumentType, __ast_path: &mut AstKindPath, ) -> DocumentType { if self.enabled { <V as FoldAstPath>::fold_document_type(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_element(&mut self, node: Element, __ast_path: &mut AstKindPath) -> Element { if self.enabled { <V as FoldAstPath>::fold_element(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_namespace(&mut self, node: Namespace, __ast_path: &mut AstKindPath) -> Namespace { if self.enabled { <V as FoldAstPath>::fold_namespace(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_opt_atom( &mut self, node: Option<swc_atoms::Atom>, __ast_path: &mut AstKindPath, ) -> Option<swc_atoms::Atom> { if self.enabled { <V as FoldAstPath>::fold_opt_atom(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_opt_namespace( &mut self, node: Option<Namespace>, __ast_path: &mut AstKindPath, ) -> Option<Namespace> { if self.enabled { <V as FoldAstPath>::fold_opt_namespace(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_processing_instruction( &mut self, node: ProcessingInstruction, __ast_path: &mut AstKindPath, ) -> ProcessingInstruction { if self.enabled { <V as FoldAstPath>::fold_processing_instruction(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_span( &mut self, node: swc_common::Span, __ast_path: &mut AstKindPath, ) -> swc_common::Span { if self.enabled { <V as FoldAstPath>::fold_span(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_text(&mut self, node: Text, __ast_path: &mut AstKindPath) -> Text { if self.enabled { <V as FoldAstPath>::fold_text(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_token(&mut self, node: Token, __ast_path: &mut AstKindPath) -> Token { if self.enabled { <V as FoldAstPath>::fold_token(&mut self.visitor, node, __ast_path) } else { node } } #[inline] fn fold_token_and_span( &mut self, node: TokenAndSpan, __ast_path: &mut AstKindPath, ) -> TokenAndSpan { if self.enabled { <V as FoldAstPath>::fold_token_and_span(&mut self.visitor, node, __ast_path) } else { node } } } #[doc = r" A trait implemented for types that can be visited using a visitor."] #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] pub trait FoldWithAstPath<V: ?Sized + FoldAstPath> { #[doc = r" Calls a visitor method (visitor.fold_xxx) with self."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self; #[doc = r" Visit children nodes of `self`` with `visitor`."] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self; } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Attribute { #[doc = "Calls [FoldAstPath`::fold_attribute`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_attribute(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } => { let span = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Attribute(self::fields::AttributeField::Span)); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let namespace = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::Namespace, )); <Option<Namespace> as FoldWithAstPath<V>>::fold_with_ast_path( namespace, visitor, &mut *__ast_path, ) }; let prefix = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::Prefix, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( prefix, visitor, &mut *__ast_path, ) }; let name = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Attribute(self::fields::AttributeField::Name)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( name, visitor, &mut *__ast_path, ) }; let raw_name = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::RawName, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw_name, visitor, &mut *__ast_path, ) }; let value = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::Value, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( value, visitor, &mut *__ast_path, ) }; let raw_value = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Attribute( self::fields::AttributeField::RawValue, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw_value, visitor, &mut *__ast_path, ) }; Attribute { span, namespace, prefix, name, raw_name, value, raw_value, } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for AttributeToken { #[doc = "Calls [FoldAstPath`::fold_attribute_token`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_attribute_token(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { AttributeToken { span, name, raw_name, value, raw_value, } => { let span = { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::Span, )); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let name = { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::Name, )); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( name, visitor, &mut *__ast_path, ) }; let raw_name = { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::RawName, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw_name, visitor, &mut *__ast_path, ) }; let value = { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::Value, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( value, visitor, &mut *__ast_path, ) }; let raw_value = { let mut __ast_path = __ast_path.with_guard(AstParentKind::AttributeToken( self::fields::AttributeTokenField::RawValue, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw_value, visitor, &mut *__ast_path, ) }; AttributeToken { span, name, raw_name, value, raw_value, } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for CdataSection { #[doc = "Calls [FoldAstPath`::fold_cdata_section`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_cdata_section(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { CdataSection { span, data, raw } => { let span = { let mut __ast_path = __ast_path.with_guard(AstParentKind::CdataSection( self::fields::CdataSectionField::Span, )); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let data = { let mut __ast_path = __ast_path.with_guard(AstParentKind::CdataSection( self::fields::CdataSectionField::Data, )); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( data, visitor, &mut *__ast_path, ) }; let raw = { let mut __ast_path = __ast_path.with_guard(AstParentKind::CdataSection( self::fields::CdataSectionField::Raw, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; CdataSection { span, data, raw } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Child { #[doc = "Calls [FoldAstPath`::fold_child`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_child(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Child::DocumentType { 0: _field_0 } => { let mut __ast_path = __ast_path .with_guard(AstParentKind::Child(self::fields::ChildField::DocumentType)); let _field_0 = <DocumentType as FoldWithAstPath<V>>::fold_with_ast_path( _field_0, visitor, &mut *__ast_path, ); Child::DocumentType { 0: _field_0 } } Child::Element { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child(self::fields::ChildField::Element)); let _field_0 = <Element as FoldWithAstPath<V>>::fold_with_ast_path( _field_0, visitor, &mut *__ast_path, ); Child::Element { 0: _field_0 } } Child::Text { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child(self::fields::ChildField::Text)); let _field_0 = <Text as FoldWithAstPath<V>>::fold_with_ast_path( _field_0, visitor, &mut *__ast_path, ); Child::Text { 0: _field_0 } } Child::CdataSection { 0: _field_0 } => { let mut __ast_path = __ast_path .with_guard(AstParentKind::Child(self::fields::ChildField::CdataSection)); let _field_0 = <CdataSection as FoldWithAstPath<V>>::fold_with_ast_path( _field_0, visitor, &mut *__ast_path, ); Child::CdataSection { 0: _field_0 } } Child::Comment { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child(self::fields::ChildField::Comment)); let _field_0 = <Comment as FoldWithAstPath<V>>::fold_with_ast_path( _field_0, visitor, &mut *__ast_path, ); Child::Comment { 0: _field_0 } } Child::ProcessingInstruction { 0: _field_0 } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Child( self::fields::ChildField::ProcessingInstruction, )); let _field_0 = <ProcessingInstruction as FoldWithAstPath<V>>::fold_with_ast_path( _field_0, visitor, &mut *__ast_path, ); Child::ProcessingInstruction { 0: _field_0 } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Comment { #[doc = "Calls [FoldAstPath`::fold_comment`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_comment(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Comment { span, data, raw } => { let span = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Comment(self::fields::CommentField::Span)); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let data = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Comment(self::fields::CommentField::Data)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( data, visitor, &mut *__ast_path, ) }; let raw = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Comment(self::fields::CommentField::Raw)); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; Comment { span, data, raw } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Document { #[doc = "Calls [FoldAstPath`::fold_document`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_document(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Document { span, children } => { let span = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Document(self::fields::DocumentField::Span)); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let children = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Document( self::fields::DocumentField::Children(usize::MAX), )); <Vec<Child> as FoldWithAstPath<V>>::fold_with_ast_path( children, visitor, &mut *__ast_path, ) }; Document { span, children } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for DocumentMode { #[doc = "Calls [FoldAstPath`::fold_document_mode`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_document_mode(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { DocumentMode::NoQuirks => DocumentMode::NoQuirks, DocumentMode::LimitedQuirks => DocumentMode::LimitedQuirks, DocumentMode::Quirks => DocumentMode::Quirks, } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for DocumentType { #[doc = "Calls [FoldAstPath`::fold_document_type`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_document_type(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { DocumentType { span, name, public_id, system_id, raw, } => { let span = { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::Span, )); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let name = { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::Name, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( name, visitor, &mut *__ast_path, ) }; let public_id = { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::PublicId, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( public_id, visitor, &mut *__ast_path, ) }; let system_id = { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::SystemId, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( system_id, visitor, &mut *__ast_path, ) }; let raw = { let mut __ast_path = __ast_path.with_guard(AstParentKind::DocumentType( self::fields::DocumentTypeField::Raw, )); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; DocumentType { span, name, public_id, system_id, raw, } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Element { #[doc = "Calls [FoldAstPath`::fold_element`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_element(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Element { span, tag_name, attributes, children, } => { let span = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Element(self::fields::ElementField::Span)); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let tag_name = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Element(self::fields::ElementField::TagName)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; let attributes = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Element( self::fields::ElementField::Attributes(usize::MAX), )); <Vec<Attribute> as FoldWithAstPath<V>>::fold_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; let children = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Element( self::fields::ElementField::Children(usize::MAX), )); <Vec<Child> as FoldWithAstPath<V>>::fold_with_ast_path( children, visitor, &mut *__ast_path, ) }; Element { span, tag_name, attributes, children, } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Namespace { #[doc = "Calls [FoldAstPath`::fold_namespace`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_namespace(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Namespace::HTML => Namespace::HTML, Namespace::MATHML => Namespace::MATHML, Namespace::SVG => Namespace::SVG, Namespace::XLINK => Namespace::XLINK, Namespace::XML => Namespace::XML, Namespace::XMLNS => Namespace::XMLNS, } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for ProcessingInstruction { #[doc = "Calls [FoldAstPath`::fold_processing_instruction`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_processing_instruction(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { ProcessingInstruction { span, target, data } => { let span = { let mut __ast_path = __ast_path.with_guard(AstParentKind::ProcessingInstruction( self::fields::ProcessingInstructionField::Span, )); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let target = { let mut __ast_path = __ast_path.with_guard(AstParentKind::ProcessingInstruction( self::fields::ProcessingInstructionField::Target, )); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( target, visitor, &mut *__ast_path, ) }; let data = { let mut __ast_path = __ast_path.with_guard(AstParentKind::ProcessingInstruction( self::fields::ProcessingInstructionField::Data, )); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( data, visitor, &mut *__ast_path, ) }; ProcessingInstruction { span, target, data } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Text { #[doc = "Calls [FoldAstPath`::fold_text`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_text(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Text { span, data, raw } => { let span = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Text(self::fields::TextField::Span)); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let data = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Text(self::fields::TextField::Data)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( data, visitor, &mut *__ast_path, ) }; let raw = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Text(self::fields::TextField::Raw)); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; Text { span, data, raw } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Token { #[doc = "Calls [FoldAstPath`::fold_token`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_token(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { Token::Doctype { name, public_id, system_id, raw, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Doctype)); let name = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Name)); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( name, visitor, &mut *__ast_path, ) }; let public_id = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::PublicId)); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( public_id, visitor, &mut *__ast_path, ) }; let system_id = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::SystemId)); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( system_id, visitor, &mut *__ast_path, ) }; let raw = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; Token::Doctype { name, public_id, system_id, raw, } } Token::StartTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::StartTag)); let tag_name = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::TagName)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; let attributes = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as FoldWithAstPath<V>>::fold_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; Token::StartTag { tag_name, attributes, } } Token::EndTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::EndTag)); let tag_name = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::TagName)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; let attributes = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as FoldWithAstPath<V>>::fold_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; Token::EndTag { tag_name, attributes, } } Token::EmptyTag { tag_name, attributes, } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::EmptyTag)); let tag_name = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::TagName)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( tag_name, visitor, &mut *__ast_path, ) }; let attributes = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::Attributes(usize::MAX), )); <Vec<AttributeToken> as FoldWithAstPath<V>>::fold_with_ast_path( attributes, visitor, &mut *__ast_path, ) }; Token::EmptyTag { tag_name, attributes, } } Token::Comment { data, raw } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Comment)); let data = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Data)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( data, visitor, &mut *__ast_path, ) }; let raw = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; Token::Comment { data, raw } } Token::Character { value, raw } => { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::Character)); let raw = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <Option<swc_atoms::Atom> as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; Token::Character { value, raw } } Token::ProcessingInstruction { target, data } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token( self::fields::TokenField::ProcessingInstruction, )); let target = { let mut __ast_path = __ast_path .with_guard(AstParentKind::Token(self::fields::TokenField::Target)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( target, visitor, &mut *__ast_path, ) }; let data = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Data)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( data, visitor, &mut *__ast_path, ) }; Token::ProcessingInstruction { target, data } } Token::Cdata { data, raw } => { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Cdata)); let data = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Data)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( data, visitor, &mut *__ast_path, ) }; let raw = { let mut __ast_path = __ast_path.with_guard(AstParentKind::Token(self::fields::TokenField::Raw)); <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path( raw, visitor, &mut *__ast_path, ) }; Token::Cdata { data, raw } } Token::Eof => Token::Eof, } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for TokenAndSpan { #[doc = "Calls [FoldAstPath`::fold_token_and_span`] with `self`."] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_token_and_span(visitor, self, __ast_path) } fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { match self { TokenAndSpan { span, token } => { let span = { let mut __ast_path = __ast_path.with_guard(AstParentKind::TokenAndSpan( self::fields::TokenAndSpanField::Span, )); <swc_common::Span as FoldWithAstPath<V>>::fold_with_ast_path( span, visitor, &mut *__ast_path, ) }; let token = { let mut __ast_path = __ast_path.with_guard(AstParentKind::TokenAndSpan( self::fields::TokenAndSpanField::Token, )); <Token as FoldWithAstPath<V>>::fold_with_ast_path( token, visitor, &mut *__ast_path, ) }; TokenAndSpan { span, token } } } } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for swc_atoms::Atom { #[doc = "Calls [FoldAstPath`::fold_atom`] with `self`. (Extra impl)"] #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_atom(visitor, self, __ast_path) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { self } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Vec<AttributeToken> { #[doc = "Calls [FoldAstPath`::fold_attribute_tokens`] with `self`. (Extra impl)"] #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_attribute_tokens(visitor, self, __ast_path) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { self.into_iter() .enumerate() .map(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <AttributeToken as FoldWithAstPath<V>>::fold_with_ast_path( item, visitor, &mut *__ast_path, ) }) .collect() } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Vec<Attribute> { #[doc = "Calls [FoldAstPath`::fold_attributes`] with `self`. (Extra impl)"] #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_attributes(visitor, self, __ast_path) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { self.into_iter() .enumerate() .map(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <Attribute as FoldWithAstPath<V>>::fold_with_ast_path( item, visitor, &mut *__ast_path, ) }) .collect() } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Vec<Child> { #[doc = "Calls [FoldAstPath`::fold_childs`] with `self`. (Extra impl)"] #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_childs(visitor, self, __ast_path) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { self.into_iter() .enumerate() .map(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <Child as FoldWithAstPath<V>>::fold_with_ast_path(item, visitor, &mut *__ast_path) }) .collect() } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Option<swc_atoms::Atom> { #[doc = "Calls [FoldAstPath`::fold_opt_atom`] with `self`. (Extra impl)"] #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_opt_atom(visitor, self, __ast_path) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { self.map(|inner| { <swc_atoms::Atom as FoldWithAstPath<V>>::fold_with_ast_path(inner, visitor, __ast_path) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for Option<Namespace> { #[doc = "Calls [FoldAstPath`::fold_opt_namespace`] with `self`. (Extra impl)"] #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_opt_namespace(visitor, self, __ast_path) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { self.map(|inner| { <Namespace as FoldWithAstPath<V>>::fold_with_ast_path(inner, visitor, __ast_path) }) } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V: ?Sized + FoldAstPath> FoldWithAstPath<V> for swc_common::Span { #[doc = "Calls [FoldAstPath`::fold_span`] with `self`. (Extra impl)"] #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { <V as FoldAstPath>::fold_span(visitor, self, __ast_path) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { self } } #[cfg(any(docsrs, feature = "path"))] #[cfg_attr(docsrs, doc(cfg(feature = "path")))] impl<V, T> FoldWithAstPath<V> for std::boxed::Box<T> where V: ?Sized + FoldAstPath, T: FoldWithAstPath<V>, { #[inline] fn fold_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { swc_visit::util::map::Map::map(self, |inner| { <T as FoldWithAstPath<V>>::fold_with_ast_path(inner, visitor, __ast_path) }) } #[inline] fn fold_children_with_ast_path(self, visitor: &mut V, __ast_path: &mut AstKindPath) -> Self { swc_visit::util::map::Map::map(self, |inner| { <T as FoldWithAstPath<V>>::fold_children_with_ast_path(inner, visitor, __ast_path) }) } } #[cfg(any(docsrs, feature = "path"))] pub type AstKindPath = swc_visit::AstKindPath<AstParentKind>; #[cfg(any(docsrs, feature = "path"))] pub type AstNodePath<'ast> = swc_visit::AstNodePath<AstParentNodeRef<'ast>>; #[cfg(any(docsrs, feature = "path"))] pub mod fields { use swc_xml_ast::*; #[inline(always)] fn assert_initial_index(idx: usize, index: usize) { #[cfg(debug_assertions)] if !(idx == usize::MAX || index == usize::MAX) { { panic!("Should be usize::MAX"); } } } impl AttributeField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum AttributeField { #[doc = "Represents [`Attribute::span`]"] Span, #[doc = "Represents [`Attribute::namespace`]"] Namespace, #[doc = "Represents [`Attribute::prefix`]"] Prefix, #[doc = "Represents [`Attribute::name`]"] Name, #[doc = "Represents [`Attribute::raw_name`]"] RawName, #[doc = "Represents [`Attribute::value`]"] Value, #[doc = "Represents [`Attribute::raw_value`]"] RawValue, } impl AttributeTokenField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum AttributeTokenField { #[doc = "Represents [`AttributeToken::span`]"] Span, #[doc = "Represents [`AttributeToken::name`]"] Name, #[doc = "Represents [`AttributeToken::raw_name`]"] RawName, #[doc = "Represents [`AttributeToken::value`]"] Value, #[doc = "Represents [`AttributeToken::raw_value`]"] RawValue, } impl CdataSectionField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum CdataSectionField { #[doc = "Represents [`CdataSection::span`]"] Span, #[doc = "Represents [`CdataSection::data`]"] Data, #[doc = "Represents [`CdataSection::raw`]"] Raw, } impl ChildField { #[inline(always)] pub(crate) fn set_index(&mut self, _: usize) { swc_visit::wrong_ast_path(); } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum ChildField { #[doc = "Represents [`Child::DocumentType`]"] DocumentType, #[doc = "Represents [`Child::Element`]"] Element, #[doc = "Represents [`Child::Text`]"] Text, #[doc = "Represents [`Child::CdataSection`]"] CdataSection, #[doc = "Represents [`Child::Comment`]"] Comment, #[doc = "Represents [`Child::ProcessingInstruction`]"] ProcessingInstruction, } impl CommentField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum CommentField { #[doc = "Represents [`Comment::span`]"] Span, #[doc = "Represents [`Comment::data`]"] Data, #[doc = "Represents [`Comment::raw`]"] Raw, } impl DocumentField { pub(crate) fn set_index(&mut self, index: usize) { match self { Self::Children(idx) => { assert_initial_index(*idx, index); *idx = index; } _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum DocumentField { #[doc = "Represents [`Document::span`]"] Span, #[doc = "Represents [`Document::children`]"] Children(usize), } impl DocumentModeField { #[inline(always)] pub(crate) fn set_index(&mut self, _: usize) { swc_visit::wrong_ast_path(); } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum DocumentModeField { #[doc = "Represents [`DocumentMode::NoQuirks`]"] NoQuirks, #[doc = "Represents [`DocumentMode::LimitedQuirks`]"] LimitedQuirks, #[doc = "Represents [`DocumentMode::Quirks`]"] Quirks, } impl DocumentTypeField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum DocumentTypeField { #[doc = "Represents [`DocumentType::span`]"] Span, #[doc = "Represents [`DocumentType::name`]"] Name, #[doc = "Represents [`DocumentType::public_id`]"] PublicId, #[doc = "Represents [`DocumentType::system_id`]"] SystemId, #[doc = "Represents [`DocumentType::raw`]"] Raw, } impl ElementField { pub(crate) fn set_index(&mut self, index: usize) { match self { Self::Attributes(idx) => { assert_initial_index(*idx, index); *idx = index; } Self::Children(idx) => { assert_initial_index(*idx, index); *idx = index; } _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum ElementField { #[doc = "Represents [`Element::span`]"] Span, #[doc = "Represents [`Element::tag_name`]"] TagName, #[doc = "Represents [`Element::attributes`]"] Attributes(usize), #[doc = "Represents [`Element::children`]"] Children(usize), } impl NamespaceField { #[inline(always)] pub(crate) fn set_index(&mut self, _: usize) { swc_visit::wrong_ast_path(); } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum NamespaceField { #[doc = "Represents [`Namespace::HTML`]"] Html, #[doc = "Represents [`Namespace::MATHML`]"] Mathml, #[doc = "Represents [`Namespace::SVG`]"] Svg, #[doc = "Represents [`Namespace::XLINK`]"] Xlink, #[doc = "Represents [`Namespace::XML`]"] Xml, #[doc = "Represents [`Namespace::XMLNS`]"] Xmlns, } impl ProcessingInstructionField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum ProcessingInstructionField { #[doc = "Represents [`ProcessingInstruction::span`]"] Span, #[doc = "Represents [`ProcessingInstruction::target`]"] Target, #[doc = "Represents [`ProcessingInstruction::data`]"] Data, } impl TextField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum TextField { #[doc = "Represents [`Text::span`]"] Span, #[doc = "Represents [`Text::data`]"] Data, #[doc = "Represents [`Text::raw`]"] Raw, } impl TokenField { #[inline(always)] pub(crate) fn set_index(&mut self, _: usize) { swc_visit::wrong_ast_path(); } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum TokenField { #[doc = "Represents [`Token::Doctype`]"] Doctype, #[doc = "Represents [`Token::StartTag`]"] StartTag, #[doc = "Represents [`Token::EndTag`]"] EndTag, #[doc = "Represents [`Token::EmptyTag`]"] EmptyTag, #[doc = "Represents [`Token::Comment`]"] Comment, #[doc = "Represents [`Token::Character`]"] Character, #[doc = "Represents [`Token::ProcessingInstruction`]"] ProcessingInstruction, #[doc = "Represents [`Token::Cdata`]"] Cdata, #[doc = "Represents [`Token::Eof`]"] Eof, } impl TokenAndSpanField { pub(crate) fn set_index(&mut self, index: usize) { match self { _ => swc_visit::wrong_ast_path(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum TokenAndSpanField { #[doc = "Represents [`TokenAndSpan::span`]"] Span, #[doc = "Represents [`TokenAndSpan::token`]"] Token, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum AstParentKind { Attribute(AttributeField), AttributeToken(AttributeTokenField), CdataSection(CdataSectionField), Child(ChildField), Comment(CommentField), Document(DocumentField), DocumentMode(DocumentModeField), DocumentType(DocumentTypeField), Element(ElementField), Namespace(NamespaceField), ProcessingInstruction(ProcessingInstructionField), Text(TextField), Token(TokenField), TokenAndSpan(TokenAndSpanField), } impl ::swc_visit::ParentKind for AstParentKind { #[inline] fn set_index(&mut self, index: usize) { match self { Self::Attribute(v) => v.set_index(index), Self::AttributeToken(v) => v.set_index(index), Self::CdataSection(v) => v.set_index(index), Self::Child(v) => v.set_index(index), Self::Comment(v) => v.set_index(index), Self::Document(v) => v.set_index(index), Self::DocumentMode(v) => v.set_index(index), Self::DocumentType(v) => v.set_index(index), Self::Element(v) => v.set_index(index), Self::Namespace(v) => v.set_index(index), Self::ProcessingInstruction(v) => v.set_index(index), Self::Text(v) => v.set_index(index), Self::Token(v) => v.set_index(index), Self::TokenAndSpan(v) => v.set_index(index), } } } #[derive(Debug, Clone, Copy)] pub enum AstParentNodeRef<'ast> { Attribute(&'ast Attribute, AttributeField), AttributeToken(&'ast AttributeToken, AttributeTokenField), CdataSection(&'ast CdataSection, CdataSectionField), Child(&'ast Child, ChildField), Comment(&'ast Comment, CommentField), Document(&'ast Document, DocumentField), DocumentMode(&'ast DocumentMode, DocumentModeField), DocumentType(&'ast DocumentType, DocumentTypeField), Element(&'ast Element, ElementField), Namespace(&'ast Namespace, NamespaceField), ProcessingInstruction(&'ast ProcessingInstruction, ProcessingInstructionField), Text(&'ast Text, TextField), Token(&'ast Token, TokenField), TokenAndSpan(&'ast TokenAndSpan, TokenAndSpanField), } impl<'ast> ::swc_visit::NodeRef for AstParentNodeRef<'ast> { type ParentKind = AstParentKind; #[inline(always)] fn kind(&self) -> AstParentKind { self.kind() } fn set_index(&mut self, index: usize) { match self { Self::Attribute(_, __field_kind) => __field_kind.set_index(index), Self::AttributeToken(_, __field_kind) => __field_kind.set_index(index), Self::CdataSection(_, __field_kind) => __field_kind.set_index(index), Self::Child(_, __field_kind) => __field_kind.set_index(index), Self::Comment(_, __field_kind) => __field_kind.set_index(index), Self::Document(_, __field_kind) => __field_kind.set_index(index), Self::DocumentMode(_, __field_kind) => __field_kind.set_index(index), Self::DocumentType(_, __field_kind) => __field_kind.set_index(index), Self::Element(_, __field_kind) => __field_kind.set_index(index), Self::Namespace(_, __field_kind) => __field_kind.set_index(index), Self::ProcessingInstruction(_, __field_kind) => __field_kind.set_index(index), Self::Text(_, __field_kind) => __field_kind.set_index(index), Self::Token(_, __field_kind) => __field_kind.set_index(index), Self::TokenAndSpan(_, __field_kind) => __field_kind.set_index(index), } } } #[cfg(any(docsrs, feature = "path"))] impl<'ast> AstParentNodeRef<'ast> { #[inline] pub fn kind(&self) -> AstParentKind { match self { Self::Attribute(_, __field_kind) => AstParentKind::Attribute(*__field_kind), Self::AttributeToken(_, __field_kind) => { AstParentKind::AttributeToken(*__field_kind) } Self::CdataSection(_, __field_kind) => AstParentKind::CdataSection(*__field_kind), Self::Child(_, __field_kind) => AstParentKind::Child(*__field_kind), Self::Comment(_, __field_kind) => AstParentKind::Comment(*__field_kind), Self::Document(_, __field_kind) => AstParentKind::Document(*__field_kind), Self::DocumentMode(_, __field_kind) => AstParentKind::DocumentMode(*__field_kind), Self::DocumentType(_, __field_kind) => AstParentKind::DocumentType(*__field_kind), Self::Element(_, __field_kind) => AstParentKind::Element(*__field_kind), Self::Namespace(_, __field_kind) => AstParentKind::Namespace(*__field_kind), Self::ProcessingInstruction(_, __field_kind) => { AstParentKind::ProcessingInstruction(*__field_kind) } Self::Text(_, __field_kind) => AstParentKind::Text(*__field_kind), Self::Token(_, __field_kind) => AstParentKind::Token(*__field_kind), Self::TokenAndSpan(_, __field_kind) => AstParentKind::TokenAndSpan(*__field_kind), } } } } impl<'ast> From<&'ast Attribute> for NodeRef<'ast> { fn from(node: &'ast Attribute) -> Self { NodeRef::Attribute(node) } } impl<'ast> From<&'ast AttributeToken> for NodeRef<'ast> { fn from(node: &'ast AttributeToken) -> Self { NodeRef::AttributeToken(node) } } impl<'ast> From<&'ast CdataSection> for NodeRef<'ast> { fn from(node: &'ast CdataSection) -> Self { NodeRef::CdataSection(node) } } impl<'ast> From<&'ast Child> for NodeRef<'ast> { fn from(node: &'ast Child) -> Self { NodeRef::Child(node) } } impl<'ast> From<&'ast Comment> for NodeRef<'ast> { fn from(node: &'ast Comment) -> Self { NodeRef::Comment(node) } } impl<'ast> From<&'ast Document> for NodeRef<'ast> { fn from(node: &'ast Document) -> Self { NodeRef::Document(node) } } impl<'ast> From<&'ast DocumentMode> for NodeRef<'ast> { fn from(node: &'ast DocumentMode) -> Self { NodeRef::DocumentMode(node) } } impl<'ast> From<&'ast DocumentType> for NodeRef<'ast> { fn from(node: &'ast DocumentType) -> Self { NodeRef::DocumentType(node) } } impl<'ast> From<&'ast Element> for NodeRef<'ast> { fn from(node: &'ast Element) -> Self { NodeRef::Element(node) } } impl<'ast> From<&'ast Namespace> for NodeRef<'ast> { fn from(node: &'ast Namespace) -> Self { NodeRef::Namespace(node) } } impl<'ast> From<&'ast ProcessingInstruction> for NodeRef<'ast> { fn from(node: &'ast ProcessingInstruction) -> Self { NodeRef::ProcessingInstruction(node) } } impl<'ast> From<&'ast Text> for NodeRef<'ast> { fn from(node: &'ast Text) -> Self { NodeRef::Text(node) } } impl<'ast> From<&'ast Token> for NodeRef<'ast> { fn from(node: &'ast Token) -> Self { NodeRef::Token(node) } } impl<'ast> From<&'ast TokenAndSpan> for NodeRef<'ast> { fn from(node: &'ast TokenAndSpan) -> Self { NodeRef::TokenAndSpan(node) } } #[derive(Debug, Clone, Copy)] pub enum NodeRef<'ast> { Attribute(&'ast Attribute), AttributeToken(&'ast AttributeToken), CdataSection(&'ast CdataSection), Child(&'ast Child), Comment(&'ast Comment), Document(&'ast Document), DocumentMode(&'ast DocumentMode), DocumentType(&'ast DocumentType), Element(&'ast Element), Namespace(&'ast Namespace), ProcessingInstruction(&'ast ProcessingInstruction), Text(&'ast Text), Token(&'ast Token), TokenAndSpan(&'ast TokenAndSpan), } impl<'ast> NodeRef<'ast> { #[doc = r" This is not a part of semver-stable API. It is experimental and subject to change."] #[allow(unreachable_patterns)] pub fn experimental_raw_children<'a>(&'a self) -> Box<dyn 'a + Iterator<Item = NodeRef<'ast>>> { match self { NodeRef::Attribute(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>().chain( node.namespace .iter() .flat_map(|item| ::std::iter::once(NodeRef::Namespace(&item))), ); Box::new(iterator) } NodeRef::AttributeToken(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>(); Box::new(iterator) } NodeRef::CdataSection(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>(); Box::new(iterator) } NodeRef::Child(node) => match node { Child::DocumentType(v0) => Box::new(::std::iter::once(NodeRef::DocumentType(v0))), Child::Element(v0) => Box::new(::std::iter::once(NodeRef::Element(v0))), Child::Text(v0) => Box::new(::std::iter::once(NodeRef::Text(v0))), Child::CdataSection(v0) => Box::new(::std::iter::once(NodeRef::CdataSection(v0))), Child::Comment(v0) => Box::new(::std::iter::once(NodeRef::Comment(v0))), Child::ProcessingInstruction(v0) => { Box::new(::std::iter::once(NodeRef::ProcessingInstruction(v0))) } _ => Box::new(::std::iter::empty::<NodeRef<'ast>>()), }, NodeRef::Comment(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>(); Box::new(iterator) } NodeRef::Document(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>().chain( node.children .iter() .flat_map(|item| ::std::iter::once(NodeRef::Child(&item))), ); Box::new(iterator) } NodeRef::DocumentMode(node) => match node { _ => Box::new(::std::iter::empty::<NodeRef<'ast>>()), }, NodeRef::DocumentType(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>(); Box::new(iterator) } NodeRef::Element(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>() .chain( node.attributes .iter() .flat_map(|item| ::std::iter::once(NodeRef::Attribute(&item))), ) .chain( node.children .iter() .flat_map(|item| ::std::iter::once(NodeRef::Child(&item))), ); Box::new(iterator) } NodeRef::Namespace(node) => match node { _ => Box::new(::std::iter::empty::<NodeRef<'ast>>()), }, NodeRef::ProcessingInstruction(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>(); Box::new(iterator) } NodeRef::Text(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>(); Box::new(iterator) } NodeRef::Token(node) => match node { _ => Box::new(::std::iter::empty::<NodeRef<'ast>>()), }, NodeRef::TokenAndSpan(node) => { let iterator = ::std::iter::empty::<NodeRef<'ast>>() .chain(::std::iter::once(NodeRef::Token(&node.token))); Box::new(iterator) } } } } impl<'ast> NodeRef<'ast> { #[doc = r" Visit all nodes in self in preorder."] #[doc = r""] #[doc = r" This is not a part of semver-stable API. It is"] #[doc = r" experimental and subject to change."] pub fn experimental_traverse(&'ast self) -> Box<dyn 'ast + Iterator<Item = NodeRef<'ast>>> { let mut queue = std::collections::VecDeque::<NodeRef<'ast>>::new(); queue.push_back(*self); Box::new(std::iter::from_fn(move || { let node: NodeRef<'ast> = queue.pop_front()?; { let children = node.experimental_raw_children(); queue.extend(children); } Some(node) })) } } #[cfg(any(docsrs, feature = "path"))] pub use self::fields::{AstParentKind, AstParentNodeRef};
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_xml_visit/src/lib.rs
Rust
#![cfg_attr(docsrs, feature(doc_cfg))] #![deny(clippy::all)] #![allow(clippy::ptr_arg)] pub use crate::generated::*; mod generated;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/diag_errors.rs
Rust
use std::sync::RwLock; use swc_common::{ errors::{Diagnostic, DiagnosticBuilder, Emitter, Handler, HandlerFlags, SourceMapperDyn}, sync::Lrc, }; /// Creates a new handler for testing. pub(crate) fn new_handler( _: Lrc<SourceMapperDyn>, treat_err_as_bug: bool, ) -> (Handler, BufferedError) { let e = BufferedError::default(); let handler = Handler::with_emitter_and_flags( Box::new(e.clone()), HandlerFlags { treat_err_as_bug, can_emit_warnings: true, ..Default::default() }, ); (handler, e) } #[derive(Clone, Default)] pub(crate) struct BufferedError(Lrc<RwLock<Vec<Diagnostic>>>); impl Emitter for BufferedError { fn emit(&mut self, db: &DiagnosticBuilder) { self.0.write().unwrap().push((**db).clone()); } } impl From<BufferedError> for Vec<Diagnostic> { fn from(buf: BufferedError) -> Self { let s = buf.0.read().unwrap(); s.clone() } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/errors/mod.rs
Rust
use swc_common::errors::{DiagnosticBuilder, Emitter}; pub(crate) mod stderr; pub(crate) fn multi_emitter(a: Box<dyn Emitter>, b: Box<dyn Emitter>) -> Box<dyn Emitter> { Box::new(MultiEmitter { a, b }) } struct MultiEmitter { a: Box<dyn Emitter>, b: Box<dyn Emitter>, } impl Emitter for MultiEmitter { fn emit(&mut self, db: &DiagnosticBuilder<'_>) { self.a.emit(db); self.b.emit(db); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/errors/stderr.rs
Rust
use std::fmt; use swc_common::{ errors::{DiagnosticBuilder, Emitter}, sync::Lrc, SourceMap, }; use swc_error_reporters::{GraphicalReportHandler, PrettyEmitter, PrettyEmitterConfig}; use tracing::{info, metadata::LevelFilter, Level}; /// This emitter is controlled by the env var `RUST_LOG`. /// /// This emitter will print to stderr if the logging level is higher than or /// equal to `debug` pub(crate) fn stderr_emitter(cm: Lrc<SourceMap>) -> Box<dyn Emitter> { if LevelFilter::current() > Level::INFO { info!("Diagnostics will be printed to stderr as logging level is trace or debug"); let reporter = GraphicalReportHandler::default(); let emitter = PrettyEmitter::new( cm, Box::new(TestStderr), reporter, PrettyEmitterConfig { skip_filename: false, }, ); Box::new(emitter) } else { Box::new(NoopEmitter) } } struct TestStderr; impl fmt::Write for TestStderr { fn write_str(&mut self, s: &str) -> fmt::Result { eprint!("{}", s); Ok(()) } } struct NoopEmitter; impl Emitter for NoopEmitter { fn emit(&mut self, _: &DiagnosticBuilder<'_>) {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/json.rs
Rust
use serde_json::Value; fn normalize_value_recursively(v: &mut Value, normalize: &mut dyn FnMut(&str, &mut Value)) { match v { Value::Array(arr) => { for v in arr { normalize_value_recursively(v, normalize); } } Value::Object(obj) => { for (k, v) in obj.iter_mut() { normalize(k, v); } for (_, v) in obj.iter_mut() { normalize_value_recursively(v, normalize); } } _ => {} } } /// Remove common properties, recursively. You can optionally normalize more by /// passing a closure. /// /// Closure takes `(key, value)`. /// /// Returns `true` if `actual` and `expected` are equal. pub fn diff_json_value( a: &mut Value, b: &mut Value, normalize: &mut dyn FnMut(&str, &mut Value), ) -> bool { normalize_value_recursively(a, normalize); normalize_value_recursively(b, normalize); remove_common(a, b) } fn remove_common(a: &mut Value, b: &mut Value) -> bool { if *a == *b { return true; } match (&mut *a, &mut *b) { (Value::Object(a), Value::Object(b)) => { if a.is_empty() && b.is_empty() { return true; } a.retain(|key, a_v| { if let Some(b_v) = b.get_mut(key) { if remove_common(a_v, b_v) { // Remove from both b.remove(key); return false; } } else { // Remove if a.foo is null and b does not have foo if a_v == &Value::Null { return false; } } // Preserve by default true }); b.retain(|key, b_v| { // Remove if b.foo is null and a does not have foo if b_v == &Value::Null && !a.contains_key(key) { return false; } // Preserve by default true }); } (Value::Array(a), Value::Array(b)) => { if a.len() == b.len() { for (a_v, b_v) in a.iter_mut().zip(b.iter_mut()) { remove_common(a_v, b_v); } } } _ => {} } false }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/lib.rs
Rust
use std::{ env, fmt::{self, Debug, Display, Formatter}, fs::{create_dir_all, rename, File}, io::Write, path::{Component, Path, PathBuf}, process::Command, str::FromStr, sync::RwLock, thread, }; use difference::Changeset; use once_cell::sync::Lazy; pub use pretty_assertions::{assert_eq, assert_ne}; use regex::Regex; use rustc_hash::FxHashMap; use swc_common::{ errors::{Diagnostic, Handler, HANDLER}, sync::Lrc, FilePathMapping, SourceMap, }; pub use testing_macros::fixture; use tracing_subscriber::EnvFilter; pub use self::output::{NormalizedOutput, StdErr, StdOut, TestOutput}; mod errors; pub mod json; #[macro_use] mod macros; mod diag_errors; mod output; mod paths; mod string_errors; /// Configures logger #[must_use] pub fn init() -> tracing::subscriber::DefaultGuard { let log_env = env::var("RUST_LOG").unwrap_or_else(|_| "debug".to_string()); let logger = tracing_subscriber::FmtSubscriber::builder() .without_time() .with_target(false) .with_ansi(true) .with_env_filter(EnvFilter::from_str(&log_env).unwrap()) .with_test_writer() .pretty() .finish(); tracing::subscriber::set_default(logger) } pub fn find_executable(name: &str) -> Option<PathBuf> { static CACHE: Lazy<RwLock<FxHashMap<String, PathBuf>>> = Lazy::new(Default::default); { let locked = CACHE.read().unwrap(); if let Some(cached) = locked.get(name) { return Some(cached.clone()); } } let mut path = env::var_os("PATH").and_then(|paths| { env::split_paths(&paths) .filter_map(|dir| { let full_path = dir.join(name); if full_path.is_file() { Some(full_path) } else { None } }) .next() }); if path.is_none() { // Run yarn bin $name path = Command::new("yarn") .arg("bin") .arg(name) .output() .ok() .and_then(|output| { if output.status.success() { let path = String::from_utf8(output.stdout).ok()?; let path = path.trim(); let path = PathBuf::from(path); if path.is_file() { return Some(path); } } None }); } if let Some(path) = path.clone() { let mut locked = CACHE.write().unwrap(); locked.insert(name.to_string(), path); } path } /// Run test and print errors. pub fn run_test<F, Ret>(treat_err_as_bug: bool, op: F) -> Result<Ret, StdErr> where F: FnOnce(Lrc<SourceMap>, &Handler) -> Result<Ret, ()>, { let _log = init(); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let (handler, errors) = self::string_errors::new_handler(cm.clone(), treat_err_as_bug); let result = swc_common::GLOBALS.set(&swc_common::Globals::new(), || { HANDLER.set(&handler, || op(cm, &handler)) }); match result { Ok(res) => Ok(res), Err(()) => Err(errors.into()), } } /// Run test and print errors. pub fn run_test2<F, Ret>(treat_err_as_bug: bool, op: F) -> Result<Ret, StdErr> where F: FnOnce(Lrc<SourceMap>, Handler) -> Result<Ret, ()>, { let _log = init(); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let (handler, errors) = self::string_errors::new_handler(cm.clone(), treat_err_as_bug); let result = swc_common::GLOBALS.set(&swc_common::Globals::new(), || op(cm, handler)); match result { Ok(res) => Ok(res), Err(()) => Err(errors.into()), } } pub struct Tester { pub cm: Lrc<SourceMap>, pub globals: swc_common::Globals, treat_err_as_bug: bool, } impl Tester { #[allow(clippy::new_without_default)] pub fn new() -> Self { Tester { cm: Lrc::new(SourceMap::new(FilePathMapping::empty())), globals: swc_common::Globals::new(), treat_err_as_bug: false, } } pub fn no_error(mut self) -> Self { self.treat_err_as_bug = true; self } /// Run test and print errors. pub fn print_errors<F, Ret>(&self, op: F) -> Result<Ret, StdErr> where F: FnOnce(Lrc<SourceMap>, Handler) -> Result<Ret, ()>, { let _log = init(); let (handler, errors) = self::string_errors::new_handler(self.cm.clone(), self.treat_err_as_bug); let result = swc_common::GLOBALS.set(&self.globals, || op(self.cm.clone(), handler)); match result { Ok(res) => Ok(res), Err(()) => Err(errors.into()), } } /// Run test and collect errors. pub fn errors<F, Ret>(&self, op: F) -> Result<Ret, Vec<Diagnostic>> where F: FnOnce(Lrc<SourceMap>, Handler) -> Result<Ret, ()>, { let _log = init(); let (handler, errors) = self::diag_errors::new_handler(self.cm.clone(), self.treat_err_as_bug); let result = swc_common::GLOBALS.set(&self.globals, || op(self.cm.clone(), handler)); let mut errs: Vec<_> = errors.into(); errs.sort_by_key(|d| { let span = d.span.primary_span().unwrap(); let cp = self.cm.lookup_char_pos(span.lo()); let line = cp.line; let column = cp.col.0 + 1; line * 10000 + column }); match result { Ok(res) => Ok(res), Err(()) => Err(errs), } } } fn write_to_file(path: &Path, content: &str) { File::create(path) .unwrap_or_else(|err| { panic!( "failed to create file ({}) for writing data of the failed assertion: {}", path.display(), err ) }) .write_all(content.as_bytes()) .expect("failed to write data of the failed assertion") } pub fn print_left_right(left: &dyn Debug, right: &dyn Debug) -> String { fn print(t: &dyn Debug) -> String { let s = format!("{:#?}", t); // Replace 'Span { lo: BytePos(0), hi: BytePos(0), ctxt: #0 }' with '_' let s = { static RE: Lazy<Regex> = Lazy::new(|| Regex::new("Span \\{[\\a-zA-Z0#:\\(\\)]*\\}").unwrap()); &RE } .replace_all(&s, "_"); // Remove 'span: _,' let s = { static RE: Lazy<Regex> = Lazy::new(|| Regex::new("span: _[,]?\\s*").unwrap()); &RE } .replace_all(&s, ""); s.into() } let (left, right) = (print(left), print(right)); let cur = thread::current(); let test_name = cur .name() .expect("rustc sets test name as the name of thread"); // ./target/debug/tests/${test_name}/ let target_dir = { let mut buf = paths::test_results_dir().to_path_buf(); for m in test_name.split("::") { buf.push(m) } create_dir_all(&buf).unwrap_or_else(|err| { panic!( "failed to create directory ({}) for writing data of the failed assertion: {}", buf.display(), err ) }); buf }; write_to_file(&target_dir.join("left"), &left); write_to_file(&target_dir.join("right"), &right); format!( "----- {}\n left:\n{}\n right:\n{}", test_name, left, right ) } #[macro_export] macro_rules! assert_eq_ignore_span { ($l:expr, $r:expr) => {{ println!("{}", module_path!()); let (l, r) = ($crate::drop_span($l), $crate::drop_span($r)); if l != r { panic!("assertion failed\n{}", $crate::print_left_right(&l, &r)); } }}; } pub fn diff(l: &str, r: &str) -> String { let cs = Changeset::new(l, r, "\n"); format!("{}", cs) } /// Used for assertions. /// /// Prints string without escaping special characters on failure. #[derive(PartialEq, Eq)] pub struct DebugUsingDisplay<'a>(pub &'a str); impl Debug for DebugUsingDisplay<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(self.0, f) } } /// Rename `foo/.bar/exec.js` => `foo/bar/exec.js` pub fn unignore_fixture(fixture_path: &Path) { if fixture_path.components().all(|c| { !matches!(c, Component::Normal(..)) || !c.as_os_str().to_string_lossy().starts_with('.') }) { return; } // let mut new_path = PathBuf::new(); for c in fixture_path.components() { if let Component::Normal(s) = c { if let Some(s) = s.to_string_lossy().strip_prefix('.') { new_path.push(s); continue; } } new_path.push(c); } create_dir_all(new_path.parent().unwrap()).expect("failed to create parent dir"); rename(fixture_path, &new_path).expect("failed to rename"); } pub static CARGO_TARGET_DIR: Lazy<PathBuf> = Lazy::new(|| { cargo_metadata::MetadataCommand::new() .no_deps() .exec() .unwrap() .target_directory .into() }); pub static CARGO_WORKSPACE_ROOT: Lazy<PathBuf> = Lazy::new(|| { cargo_metadata::MetadataCommand::new() .no_deps() .exec() .unwrap() .workspace_root .into() });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/macros.rs
Rust
#[allow(unused_macros)] macro_rules! try_panic { ($e:expr) => {{ $e.unwrap_or_else(|err| { panic!("{} failed with {}", stringify!($e), err); }) }}; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/output.rs
Rust
use std::{ env, fmt, fs::{self, create_dir_all, File}, io::Read, ops::Deref, path::Path, }; use serde::Serialize; use tracing::debug; use crate::paths; #[must_use] pub struct TestOutput<R> { /// Errors produced by `swc_common::error::Handler`. pub errors: StdErr, pub result: R, } pub type StdErr = NormalizedOutput; #[derive(Debug, Clone, Hash)] pub struct Diff { pub actual: NormalizedOutput, /// Output stored in file. pub expected: NormalizedOutput, } /// Normalized stdout/stderr. /// /// # Normalization /// /// See https://github.com/rust-lang/rust/blob/b224fc84e3/src/test/COMPILER_TESTS.md#normalization /// /// - The `CARGO_MANIFEST_DIR` directory is replaced with `$DIR`. /// - All backslashes (\) within same line as `$DIR` are converted to forward /// slashes (/) (for Windows) - All CR LF newlines are converted to LF /// /// - `normalize-stdout` is not implemented (yet?). #[derive(Clone, Ord, PartialOrd, PartialEq, Eq, Default, Hash)] pub struct NormalizedOutput(String); impl fmt::Display for NormalizedOutput { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl fmt::Debug for NormalizedOutput { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } fn normalize_input(input: String, skip_last_newline: bool) -> String { let manifest_dirs = [ adjust_canonicalization(paths::manifest_dir()), paths::manifest_dir().to_string_lossy().to_string(), ] .into_iter() .flat_map(|dir| [dir.replace('\\', "\\\\"), dir.replace('\\', "/"), dir]) .collect::<Vec<_>>(); let input = input.replace("\r\n", "\n"); let mut buf = String::new(); for line in input.lines() { if manifest_dirs.iter().any(|dir| line.contains(&**dir)) { let mut s = line.to_string(); for dir in &manifest_dirs { s = s.replace(&**dir, "$DIR"); } s = s.replace("\\\\", "\\").replace('\\', "/"); let s = if cfg!(target_os = "windows") { s.replace("//?/$DIR", "$DIR").replace("/?/$DIR", "$DIR") } else { s }; buf.push_str(&s) } else { buf.push_str(line); } buf.push('\n'); } if skip_last_newline && !matches!(input.chars().last(), Some('\n')) { buf.truncate(buf.len() - 1); } buf } impl NormalizedOutput { pub fn new_raw(s: String) -> Self { if s.is_empty() { return NormalizedOutput(s); } NormalizedOutput(normalize_input(s, true)) } pub fn compare_json_to_file<T>(actual: &T, path: &Path) where T: Serialize, { let actual_value = serde_json::to_value(actual).expect("failed to serialize the actual value to json"); if let Ok(expected) = fs::read_to_string(path) { let expected_value = serde_json::from_str::<serde_json::Value>(&expected) .expect("failed to deserialize the expected value from json"); if expected_value == actual_value { return; } } let actual_json_string = serde_json::to_string_pretty(&actual_value) .expect("failed to serialize the actual value to json"); let _ = NormalizedOutput::from(actual_json_string).compare_to_file(path); } /// If output differs, prints actual stdout/stderr to /// `CARGO_MANIFEST_DIR/target/swc-test-results/ui/$rel_path` where /// `$rel_path`: `path.strip_prefix(CARGO_MANIFEST_DIR)` pub fn compare_to_file<P>(self, path: P) -> Result<(), Diff> where P: AsRef<Path>, { let path = path.as_ref(); let path = path.canonicalize().unwrap_or_else(|err| { debug!( "compare_to_file: failed to canonicalize outfile path `{}`: {:?}", path.display(), err ); path.to_path_buf() }); let expected: NormalizedOutput = NormalizedOutput( File::open(&path) .map(|mut file| { let mut buf = String::new(); file.read_to_string(&mut buf).unwrap(); buf }) .unwrap_or_else(|_| { // If xxx.stderr file does not exist, stderr should be empty. String::new() }) .replace("\r\n", "\n"), ); if expected == self { return Ok(()); } debug!("Comparing output to {}", path.display()); create_dir_all(path.parent().unwrap()).expect("failed to run `mkdir -p`"); let update = std::env::var("UPDATE").unwrap_or_default() == "1"; if update { crate::write_to_file(&path, &self.0); debug!("Updating file {}", path.display()); return Ok(()); } if !update && self.0.lines().count() <= 5 { assert_eq!(expected, self, "Actual:\n{}", self); } let diff = Diff { expected, actual: self, }; if env::var("DIFF").unwrap_or_default() == "0" { assert_eq!(diff.expected, diff.actual, "Actual:\n{}", diff.actual); } else { pretty_assertions::assert_eq!(diff.expected, diff.actual, "Actual:\n{}", diff.actual); } // Actually unreachable. Err(diff) } } impl From<String> for NormalizedOutput { fn from(s: String) -> Self { if s.is_empty() { return NormalizedOutput(s); } NormalizedOutput(normalize_input(s, false)) } } impl Deref for NormalizedOutput { type Target = str; fn deref(&self) -> &str { &self.0 } } pub type StdOut = NormalizedOutput; impl<R> TestOutput<Option<R>> { /// Expects **`result`** to be `None` and **`errors`** to be match content /// of `${path}.stderr`. pub fn expect_err(self, _path: &Path) {} } #[cfg(not(target_os = "windows"))] fn adjust_canonicalization<P: AsRef<Path>>(p: P) -> String { p.as_ref().display().to_string() } #[cfg(target_os = "windows")] fn adjust_canonicalization<P: AsRef<Path>>(p: P) -> String { const VERBATIM_PREFIX: &str = r#"\\?\"#; let p = p.as_ref().display().to_string(); if let Some(stripped) = p.strip_prefix(VERBATIM_PREFIX) { stripped.to_string() } else { p } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/paths.rs
Rust
use std::{env, path::PathBuf, sync::Arc}; use once_cell::sync::Lazy; pub fn manifest_dir() -> PathBuf { env::var("CARGO_MANIFEST_DIR") .map(PathBuf::from) .map(|p| { p.canonicalize() .expect("failed to canonicalize `CARGO_MANIFEST_DIR`") }) .unwrap_or_else(|err| panic!("failed to read `CARGO_MANIFEST_DIR`: {}", err)) } /// This directory is per-crate. pub fn test_results_dir() -> Arc<PathBuf> { fn detect() -> PathBuf { manifest_dir().join("target").join("swc-test-results") } static DIR: Lazy<Arc<PathBuf>> = Lazy::new(|| Arc::new(detect())); DIR.clone() }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing/src/string_errors.rs
Rust
use std::{ fmt, io::{self, Write}, sync::{Arc, RwLock}, }; use swc_common::{ errors::{Handler, HandlerFlags}, sync::Lrc, SourceMap, }; use swc_error_reporters::{ GraphicalReportHandler, GraphicalTheme, PrettyEmitter, PrettyEmitterConfig, }; use super::StdErr; use crate::errors::{multi_emitter, stderr::stderr_emitter}; /// Creates a new handler for testing. pub(crate) fn new_handler(cm: Lrc<SourceMap>, treat_err_as_bug: bool) -> (Handler, BufferedError) { let buf: BufferedError = Default::default(); let emitter = PrettyEmitter::new( cm.clone(), Box::new(buf.clone()), GraphicalReportHandler::default().with_theme(GraphicalTheme::none()), PrettyEmitterConfig { skip_filename: false, }, ); let emitter = multi_emitter(Box::new(emitter), stderr_emitter(cm)); let handler = Handler::with_emitter_and_flags( emitter, HandlerFlags { treat_err_as_bug, ..Default::default() }, ); (handler, buf) } #[derive(Clone, Default)] pub(crate) struct BufferedError(Arc<RwLock<Vec<u8>>>); impl Write for BufferedError { fn write(&mut self, d: &[u8]) -> io::Result<usize> { self.0.write().unwrap().write(d) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl From<BufferedError> for StdErr { fn from(buf: BufferedError) -> Self { let s = buf.0.read().unwrap(); let s: String = String::from_utf8_lossy(&s).into(); s.into() } } impl fmt::Write for BufferedError { fn write_str(&mut self, s: &str) -> fmt::Result { self.write(s.as_bytes()).map_err(|_| fmt::Error)?; Ok(()) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing_macros/src/fixture.rs
Rust
use std::{ env, path::{Component, PathBuf}, }; use anyhow::{Context, Error}; use glob::glob; use once_cell::sync::Lazy; use proc_macro2::{Span, TokenStream}; use quote::quote; use regex::Regex; use relative_path::RelativePath; use syn::{ parse::{Parse, ParseStream}, parse2, punctuated::Punctuated, Ident, LitStr, Meta, Token, }; pub struct Config { pattern: String, exclude_patterns: Vec<Regex>, } impl Parse for Config { fn parse(input: ParseStream) -> syn::Result<Self> { fn update(c: &mut Config, meta: Meta) { if let Meta::List(list) = &meta { if list .path .get_ident() .map(|i| *i == "exclude") .unwrap_or(false) { // macro_rules! fail { () => {{ fail!("invalid input to the attribute") }}; ($inner:expr) => {{ panic!( "{}\nnote: exclude() expects one or more comma-separated regular \ expressions, like exclude(\".*\\\\.d\\\\.ts\") or \ exclude(\".*\\\\.d\\\\.ts\", \".*\\\\.tsx\")", $inner ) }}; } if list.tokens.is_empty() { fail!("empty exclude()") } let input = parse2::<InputParen>(list.tokens.clone()) .expect("failed to parse token as `InputParen`"); for lit in input.input { c.exclude_patterns .push(Regex::new(&lit.value()).unwrap_or_else(|err| { fail!(format!("failed to parse regex: {}\n{}", lit.value(), err)) })); } return; } } let expected = r#"#[fixture("fixture/**/*.ts", exclude("*\.d\.ts"))]"#; unimplemented!( "Expected something like {}\nGot wrong meta tag: {:?}", expected, meta, ) } let pattern: LitStr = input.parse()?; let pattern = pattern.value(); let mut config = Self { pattern, exclude_patterns: Vec::new(), }; let comma: Option<Token![,]> = input.parse()?; if comma.is_some() { let meta: Meta = input.parse()?; update(&mut config, meta); } Ok(config) } } pub fn expand(callee: &Ident, attr: Config) -> Result<Vec<TokenStream>, Error> { let base_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect( "#[fixture] requires CARGO_MANIFEST_DIR because it's relative to cargo manifest directory", )); let resolved_path = RelativePath::new(&attr.pattern).to_path(&base_dir); let pattern = resolved_path.to_string_lossy(); let paths = glob(&pattern).with_context(|| format!("glob failed for whole path: `{}`", pattern))?; let mut test_fns = Vec::new(); // Allow only alphanumeric and underscore characters for the test_name. static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[^A-Za-z0-9_]").unwrap()); 'add: for path in paths { let path = path.with_context(|| "glob failed for file".to_string())?; let abs_path = path .canonicalize() .with_context(|| format!("failed to canonicalize {}", path.display()))?; let path_for_name = path.strip_prefix(&base_dir).with_context(|| { format!( "Failed to strip prefix `{}` from `{}`", base_dir.display(), path.display() ) })?; let path_str = path.to_string_lossy(); // Skip excluded files for pattern in &attr.exclude_patterns { if pattern.is_match(&path_str) { continue 'add; } if cfg!(target_os = "windows") && pattern.is_match(&path_str.replace('\\', "/")) { continue 'add; } } let ignored = path.components().any(|c| match c { Component::Normal(s) => s.to_string_lossy().starts_with('.'), _ => false, }); let test_name = format!( "{}_{}", callee, RE.replace_all( path_for_name .to_string_lossy() .replace(['\\', '/'], "__") .as_str(), "_", ) ) .replace("___", "__"); let test_ident = Ident::new(&test_name, Span::call_site()); let ignored_attr = if ignored { quote!(#[ignore]) } else { quote!() }; let path_str = abs_path.to_string_lossy(); let f = quote!( #[test] #[inline(never)] #[doc(hidden)] #[allow(non_snake_case)] #ignored_attr fn #test_ident() { eprintln!("Input: {}", #path_str); #callee(::std::path::PathBuf::from(#path_str)); } ); test_fns.push(f); } if test_fns.is_empty() { panic!("No test found") } Ok(test_fns) } struct InputParen { input: Punctuated<LitStr, Token![,]>, } impl Parse for InputParen { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self { input: input.call(Punctuated::parse_terminated)?, }) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing_macros/src/lib.rs
Rust
use proc_macro::TokenStream; use quote::{quote, ToTokens}; use syn::ItemFn; mod fixture; /// Create tests from files. /// /// **NOTE: Path should be relative to the directory of `Cargo.toml` file**. /// This is limitation of current proc macro api. /// /// # Why /// /// If you create test dynamically, running a specific test become very /// cumbersome. /// /// For example, if you use `test` crate with nightly, you can't use `cargo test /// foo` to run tests with name containing `foo`. Instead, you have to implement /// your own ignoring logic /// /// /// # Usage /// /// If you want to load all typescript files from `pass` /// /// ```rust,ignore /// /// #[fixture("pass/**/*.{ts,tsx}")] /// fn pass(file: PathBuf) { /// // test by reading file /// } /// ``` /// /// # Return value /// /// The function is allowed to return `Result` on error. If it's the case /// /// /// ## Ignoring a test /// /// If the path to the file contains a component starts with `.` (dot), it will /// be ignore. This convention is widely used in many projects (including other /// languages), as a file or a directory starting with `.` means hidden file in /// unix system. /// /// Note that they are added as a test `#[ignore]`, so you can use /// `cargo test -- --ignored` or `cargo test -- --include-ignored` to run those /// tests. /// /// /// # Roadmap /// /// - Support async function #[proc_macro_attribute] pub fn fixture(attr: TokenStream, item: TokenStream) -> TokenStream { let item: ItemFn = syn::parse(item).expect("failed to parse input as a function item"); if cfg!(feature = "rust-analyzer") { return quote!( #[allow(unused)] #item ) .into(); } let config: self::fixture::Config = syn::parse(attr).expect("failed to parse input passed to #[fixture]"); let cases = self::fixture::expand(&item.sig.ident, config).unwrap(); let mut output = proc_macro2::TokenStream::new(); for case in cases { case.to_tokens(&mut output); } item.to_tokens(&mut output); output.into() }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/testing_macros/tests/test.rs
Rust
#![deny(unused)] use std::path::PathBuf; use testing_macros::fixture; #[fixture("tests/simple/*.ts")] fn simple(_path: PathBuf) {} #[fixture("tests/ignore/**/*.ts")] fn ignored(_path: PathBuf) {} #[fixture("tests/simple/**/*.ts")] #[fixture("tests/simple/**/*.tsx")] fn multiple(_path: PathBuf) {} #[fixture("tests/simple/**/*", exclude(".*\\.tsx", ".*.d\\.ts"))] fn exclude(_path: PathBuf) {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/bench-node.sh
Shell
#!/usr/bin/env bash set -eu echo "Binary load time" hyperfine --warmup 10 --runs 5 'node ./node-swc/benches/load.mjs' echo "Load + minify antd, all core" hyperfine --warmup 5 --runs 5 "node ./node-swc/benches/minify.mjs $PWD/crates/swc_ecma_minifier/benches/full/antd.js" echo "Load + minify antd, 2 core" hyperfine --warmup 5 --runs 5 "RAYON_NUM_THREADS=2 node ./node-swc/benches/minify.mjs $PWD/crates/swc_ecma_minifier/benches/full/antd.js"
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/bench/build-crate.sh
Shell
#!/usr/bin/env bash set -eu crate=$1 # If crate has feature 'concurrent', build it with feature if [[ $(./scripts/cargo/list-features.sh $crate) == *"concurrent"* ]]; then echo "Building $crate with feature 'concurrent'" cargo codspeed build -p $crate --features concurrent else echo "Building $crate" cargo codspeed build -p $crate fi
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/bench/list-crates-with-bench.sh
Shell
#!/usr/bin/env bash set -eu WS_CRATES=$(./scripts/cargo/get-workspace-crates-json.sh) echo "$WS_CRATES" | jq -r -c '[.[] | select(.targets[] | .kind | contains(["bench"])) | .name] | sort | unique' | jq -r -c '[.[] | select(. != "swc_plugin_runner" and . != "swc_allocator" and . != "swc")]'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/bisect/list-commits.sh
Shell
#!/usr/bin/env bash set -eu commits=$(git rev-list --ancestry-path $1...$2) # Filter out commits made by `swc-bot` filtered_commits=$(echo "$commits" | while read -r commit; do author=$(git show -s --format='%an' "$commit") if [[ "$author" != "SWC Bot" ]]; then echo "$commit" fi done) # Print the filtered commits in `$hash: $title` format echo "$filtered_commits" | while read -r commit; do title=$(git show -s --format='%s' "$commit") echo "$commit: $title" done
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cargo/get-crates-with-benchmark.sh
Shell
#!/usr/bin/env bash set -eu cargo metadata --format-version 1 --no-deps \ | jq -r -j '[.packages[] | select(.source == null and .name != "xtask") | .name]' \ | tr -d '\012\015'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cargo/get-crates.sh
Shell
#!/usr/bin/env bash set -eu cargo metadata --format-version 1 --no-deps | jq -r -j '[.packages[] | select(.source == null and .name != "xtask") | .name]' | tr -d '\012\015'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cargo/get-workspace-crates-json.sh
Shell
#!/usr/bin/env bash set -eu cargo metadata --format-version 1 --no-deps | jq -r -j '[.packages[] | select(.source == null and .name != "xtask")]'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cargo/list-crates.sh
Shell
#!/usr/bin/env bash set -eu # Prints json for workspace crates cargo metadata --format-version 1 | jq -r '.packages[] | select(.source == null)'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cargo/list-features.sh
Shell
#!/usr/bin/env bash set -eu # Prints json for workspace crates cargo metadata --format-version 1 | jq -r '.packages[] | select(.source == null and .name == "'$1'") | .features'
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cargo/patch-section.sh
Shell
#!/usr/bin/env bash set -eu SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) function toLine { # >&2 echo "toLine: $@" arr=(${1//,/ }) # >&2 echo "arr: ${arr[0]} ${arr[1]}" dir="$(dirname ${arr[1]})" echo "${arr[0]} = { path = '$dir' }" } export -f toLine $SCRIPT_DIR/list-crates.sh | jq '[.name, .manifest_path] | @csv' -r | xargs -I {} bash -c 'toLine "$@"' _ {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cargo/print-pulblished-files.sh
Shell
#!/usr/bin/env bash set -eu SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) crates=$(\ cargo metadata --format-version 1 \ | jq -r '.workspace_members[]' \ | cut -f1 -d" " \ | sort \ ) for crate in $crates do cargo publish -p $crate --dry-run --no-verify -v || true done
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cli.sh
Shell
#!/usr/bin/env bash set -eu cargo install --offline --debug --path cli
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/cli_upload_gh_release.sh
Shell
#!/bin/sh cd ./packages/core/ # Naive substitution to napi artifacts for the cli binary. for filename in artifacts_cli/* do echo "Trying to upload $filename" BINDING_NAME=${filename#*.} BINDING_ABI=${BINDING_NAME%%.*} CLI_BINARY_PATH=${filename%%.*} if [ -f "$CLI_BINARY_PATH" ]; then chmod +x $CLI_BINARY_PATH gh release upload $RELEASE_VERSION $CLI_BINARY_PATH elif [ -f "$CLI_BINARY_PATH.exe" ]; then gh release upload $RELEASE_VERSION $CLI_BINARY_PATH.exe fi done
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/doc.sh
Shell
#!/bin/sh BASEDIR=$(dirname "$0") RUSTDOC="$BASEDIR/rustdoc.sh" cargo doc $@
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/git-diff.sh
Shell
#!/usr/bin/env bash # # Used to generate `swc-bump` set -eu git diff --name-only HEAD upstream/main | grep -E '^crates/' | sed -e "s/^crates\///" | sed 's/\/.*//' | uniq
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/github/get-all-crates.sh
Shell
#!/usr/bin/env bash set -eu function prepend() { while read line; do echo "${1}${line}"; done; } cargo metadata --format-version 1 \ | jq -r '.workspace_members[]' \ | cut -f1 -d" " \ | sort \ | prepend '- '
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/github/get-test-matrix.mjs
JavaScript
#!/usr/bin/env zx import * as path from 'node:path'; import * as fs from 'node:fs/promises'; import { parse, } from 'yaml' const scriptDir = __dirname; const repoRootDir = path.resolve(scriptDir, '../../'); const testsYmlPath = path.resolve(repoRootDir, 'tests.yml'); const testsYml = parse(await fs.readFile(testsYmlPath, 'utf8')); process.stderr.write(`Script dir: ${scriptDir}\n`); process.stderr.write(`Using tests.yml at ${testsYmlPath}\n`); const rawMetadata = await $`cargo metadata --format-version=1 --all-features --no-deps`; const metadata = JSON.parse(rawMetadata.stdout); const packages = metadata.packages.map(p => p.name).filter(name => name !== 'xtask'); process.stderr.write(`Crates: ${packages}\n`) process.stderr.write(`Test config: ${testsYml}\n`) const settings = []; for (const pkg of packages) { settings.push({ crate: pkg, os: 'ubuntu-latest', }); if (testsYml.os?.windows?.includes(pkg)) { settings.push({ crate: pkg, os: 'windows-latest', }); } if (testsYml.os?.macos?.includes(pkg)) { settings.push({ crate: pkg, os: 'macos-latest', }); } } const output = JSON.stringify(settings) console.log(output)
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/github/run-cargo-hack.sh
Shell
#!/usr/bin/env bash set -eu SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) crate=$1 echo "Running cargo hack for crate $crate" # yq query syntax is weird, so we have to use jq json_str="$(yq -o=json $SCRIPT_DIR/../../tests.yml)" if echo $json_str | jq -e ".check.\"$crate\"" > /dev/null; then check_commands=$(echo $json_str | jq -e -r ".check.\"$crate\" | .[]") while IFS= read -r line; do echo " Running '$line'" (cd "crates/$crate" && $line) done <<< "$check_commands" fi
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/github/test-concurrent.sh
Shell
#!/usr/bin/env bash set -eu echo "Checking if '$1' has feature 'concurrent'" # Get crates with feature named `concurrent` CRATES=$(./scripts/cargo/list-crates.sh | \ jq -r 'select(.features.concurrent != null) | .name') if [[ "swc" == "$1" ]]; then echo "Skipping swc itself" exit 0 fi if [[ $CRATES == *"$1"* ]]; then cargo test --color always -p $1 --all-targets --features "$1/concurrent" fi
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/link.sh
Shell
#!/usr/bin/env bash set -eu yarn run build:dev yarn link (cd swr && yarn run build)
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/publish.sh
Shell
#!/usr/bin/env bash set -eu SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) git pull || true yarn version="$1" swc_core_version="$(cargo tree -i -p swc_core --depth 0 | awk '{print $2}')" echo "Publishing $version with swc_core $swc_core_version" # Update swc_core (cd ./bindings && ../scripts/update-all-swc-crates.sh || true) # Update version (cd ./packages/core && npm version "$version" --no-git-tag-version --allow-same-version || true) (cd ./packages/html && npm version "$version" --no-git-tag-version --allow-same-version || true) (cd ./packages/minifier && npm version "$version" --no-git-tag-version --allow-same-version || true) (cd ./bindings && cargo set-version $version -p binding_core_wasm -p binding_minifier_wasm -p binding_typescript_wasm) (cd ./bindings && cargo set-version --bump patch -p swc_cli) # Commmit and tag git add -A git commit -am "chore: Publish \`$version\` with \`swc_core\` \`$swc_core_version\`" git tag -a -m "swc_core $swc_core_version" "v$version" # Update changelog yarn changelog git add -A || true git commit -m 'chore: Update changelog' || true # Publish packages git push git@github.com:swc-project/swc.git --no-verify git push git@github.com:swc-project/swc.git --no-verify --tags
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/repo/count-files.sh
Shell
#!/usr/bin/env bash # # This script counts the number of files per each directory. # # set -eu find . -type d -empty -delete find . -maxdepth 3 -mindepth 1 -type d | while read dir; do if [[ $dir == ./.git* ]]; then continue fi if git check-ignore "$dir" > /dev/null ; then # echo "Ignoring $dir" continue fi echo "Directory: $dir" echo "Dir: $(find $dir -type d | wc -l)" echo "File: $(find $dir -type f | wc -l)" done
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/repo/profile-git.sh
Shell
#!/usr/bin/env zsh set -eu find . -type d -empty -delete export GIT_TRACE2_PERF_BRIEF=true export GIT_TRACE2_PERF=/tmp/git-perf rm -f $GIT_TRACE2_PERF time git status -z -u # time git status -uno # git add -A cat $GIT_TRACE2_PERF
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/setup-env.sh
Shell
#!/usr/bin/env bash set -eu NODE_PLATFORM_NAME=$(node -e "console.log(require('os').platform())") (cd scripts/npm/core-$NODE_PLATFORM_NAME && npm link) npm link @swc/core-$NODE_PLATFORM_NAME
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/sourcemap/decode.js
JavaScript
// Copied from https://gist.github.com/bengourley/c3c62e41c9b579ecc1d51e9d9eb8b9d2 // // This program reads a sourcemap from stdin // and replaces the "mappings" property with // human readable content. It writes the output // to stdout. // // 1. install the dependencies: // npm i concat-stream vlq // // 2. optional: install jq for pretty printing json // // 3. run the command like so: // // cat my-source-map.js.map | node decode | jq . // const concat = require("concat-stream"); const vlq = require("./vlq"); const formatMappings = (mappings, sources, names) => { const vlqState = [0, 0, 0, 0, 0]; return mappings.split(";").reduce((accum, line, i) => { accum[i + 1] = formatLine(line, vlqState, sources, names); vlqState[0] = 0; return accum; }, {}); }; const formatLine = (line, state, sources, names) => { const segs = line.split(","); return segs.map((seg) => { if (!seg) return ""; const decoded = vlq.decode(seg); for (var i = 0; i < 5; i++) { state[i] = typeof decoded[i] === "number" ? state[i] + decoded[i] : state[i]; } return formatSegment(...state.concat([sources, names])); }); }; const formatSegment = ( col, source, sourceLine, sourceCol, name, sources, names ) => `${col + 1} => ${sources[source]} ${sourceLine + 1}:${sourceCol + 1}${ names[name] ? ` ${names[name]}` : `` }`; process.stdin.pipe( concat((json) => { const map = JSON.parse(json); process.stdout.write( JSON.stringify({ ...map, mappings: formatMappings(map.mappings, map.sources, map.names), }) ); }) );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/sourcemap/vlq.js
JavaScript
(function (global, factory) { typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : ((global = typeof globalThis !== "undefined" ? globalThis : global || self), factory((global.vlq = {}))); })(this, function (exports) { "use strict"; /** @type {Record<string, number>} */ let char_to_integer = {}; /** @type {Record<number, string>} */ let integer_to_char = {}; "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" .split("") .forEach(function (char, i) { char_to_integer[char] = i; integer_to_char[i] = char; }); /** @param {string} string */ function decode(string) { /** @type {number[]} */ let result = []; let shift = 0; let value = 0; for (let i = 0; i < string.length; i += 1) { let integer = char_to_integer[string[i]]; if (integer === undefined) { throw new Error("Invalid character (" + string[i] + ")"); } const has_continuation_bit = integer & 32; integer &= 31; value += integer << shift; if (has_continuation_bit) { shift += 5; } else { const should_negate = value & 1; value >>>= 1; if (should_negate) { result.push(value === 0 ? -0x80000000 : -value); } else { result.push(value); } // reset value = shift = 0; } } return result; } /** @param {number | number[]} value */ function encode(value) { if (typeof value === "number") { return encode_integer(value); } let result = ""; for (let i = 0; i < value.length; i += 1) { result += encode_integer(value[i]); } return result; } /** @param {number} num */ function encode_integer(num) { let result = ""; if (num < 0) { num = (-num << 1) | 1; } else { num <<= 1; } do { let clamped = num & 31; num >>>= 5; if (num > 0) { clamped |= 32; } result += integer_to_char[clamped]; } while (num > 0); return result; } exports.decode = decode; exports.encode = encode; Object.defineProperty(exports, "__esModule", { value: true }); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/test.sh
Shell
#!/usr/bin/env bash set -eux yarn run build:dev yarn run tsc # yarn test npm link mkdir -p tests/integration/three-js swc tests/integration/three-js/repo/ -d tests/integration/three-js/build/ (cd tests/integration/three-js/build/test && qunit -r failonlyreporter unit/three.source.unit.js)
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/update-all-swc-crates.sh
Shell
#!/usr/bin/env bash set -eu echo "Listing all swc crates" swc_crates=$(cargo metadata --format-version=1 --all-features | jq '.packages .[] | select(.repository == "https://github.com/swc-project/swc.git" or .repository == "https://github.com/swc-project/plugins.git") | .name' -r) swc_deps=$(cargo metadata --format-version=1 --all-features | jq '.packages .[] | select(.repository == "https://github.com/swc-project/swc.git" or .repository == "https://github.com/swc-project/plugins.git") | .name+"@"+.version' -r) command="cargo update" for crate in $swc_deps; do command="$command -p $crate" done echo "Running: $command" eval $command all_direct_deps=$(cargo metadata --format-version=1 --all-features | jq -r '.packages[] | select(.source == null) | .dependencies .[] .name' -r) direct_swc_deps=$(comm -12 <(echo "$swc_crates" | sort) <(echo "$all_direct_deps" | sort)) command="cargo upgrade --incompatible --recursive false" for crate in $direct_swc_deps; do command="$command -p $crate" done echo "Running: $command" eval $command
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/update-all.sh
Shell
#!/usr/bin/env bash set -u export UPDATE=1 export DIFF=0 function crate() { until cargo test -p $1 --no-fail-fast do git add -A git commit -m 'Update test refs' done git add -A git commit -m 'Update test refs' } crate swc crate swc_ecma_codegen crate swc_ecma_parser crate swc_bundler crate swc_node_bundler crate swc_ecma_transforms_react git push -u origin "$(git rev-parse --abbrev-ref HEAD)" --no-verify
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
scripts/update_fallback_dependencies.js
JavaScript
// For some native targets, we'll make `@swc/wasm` as dependency to ensure it can gracefully fallback // While we migrate native builds into `@swc/wasm`. const path = require("path"); const fs = require("fs"); const targets = [ "freebsd-x64", "win32-ia32-msvc", "linux-arm-gnueabihf", "android-arm64", "win32-arm64-msvc", "android-arm-eabi", ]; (async () => { for (const target of targets) { const pkgPath = path.resolve(__dirname, "npm", target, "package.json"); const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8")); const { version } = pkg; pkg.dependencies = { "@swc/wasm": version, }; fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)); } })().catch((err) => { console.error("Failed to update dependencies", err); });
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
tools/generate-code/src/generators/mod.rs
Rust
pub mod visitor;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
tools/generate-code/src/generators/visitor.rs
Rust
use std::collections::HashSet; use inflector::Inflector; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use swc_cached::regex::CachedRegex; use syn::{ parse_quote, Arm, Attribute, Expr, Field, Fields, File, GenericArgument, Ident, Item, Lit, LitInt, Path, PathArguments, Stmt, TraitItem, Type, }; pub fn generate(crate_name: &Ident, node_types: &[&Item], excluded_types: &[String]) -> File { let mut output = File { shebang: None, attrs: Vec::new(), items: Vec::new(), }; let mut all_types = all_field_types(node_types).into_iter().collect::<Vec<_>>(); if !excluded_types.is_empty() { all_types.retain(|ty| { !excluded_types .iter() .any(|type_name| ty.contains_type(type_name)) }); } all_types.sort_by_cached_key(|v| v.method_name()); let mut typedefs = HashSet::new(); for node_type in node_types { match node_type { Item::Enum(data) => { typedefs.insert(FieldType::Normal(data.ident.to_string())); } Item::Struct(data) => { typedefs.insert(FieldType::Normal(data.ident.to_string())); } _ => {} } } let field_only_types = { let mut all = all_types.clone(); all.retain(|ty| !typedefs.contains(ty)); all }; output.attrs.push(parse_quote!( //! This file is generated by `tools/generate-code`. DO NOT MODIFY. )); output.attrs.push(parse_quote!( #![allow(unused_variables)] )); output.attrs.push(parse_quote!( #![allow(clippy::all)] )); output.items.push(parse_quote!( use #crate_name::*; )); output.items.push(parse_quote!( pub use ::swc_visit::All; )); for &kind in [TraitKind::Visit, TraitKind::VisitMut, TraitKind::Fold].iter() { for &variant in [Variant::Normal, Variant::AstPath].iter() { let g = Generator { kind, variant, excluded_types, }; output.items.extend(g.declare_visit_trait(&all_types)); output.items.extend(g.declare_visit_with_trait()); output .items .extend(g.implement_visit_with_for_node_types(node_types)); output .items .extend(g.implement_visit_with_for_non_node_types(&field_only_types)); output .items .extend(g.implement_visit_with_for_generic_types()); } } output.items.push(parse_quote!( #[cfg(any(docsrs, feature = "path"))] pub type AstKindPath = swc_visit::AstKindPath<AstParentKind>; )); output.items.push(parse_quote!( #[cfg(any(docsrs, feature = "path"))] pub type AstNodePath<'ast> = swc_visit::AstNodePath<AstParentNodeRef<'ast>>; )); output.items.extend(define_fields(crate_name, node_types)); output } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] enum FieldType { Normal(String), Generic(String, Box<FieldType>), } impl ToTokens for FieldType { fn to_tokens(&self, tokens: &mut TokenStream) { match self { FieldType::Normal(name) => { let parsed: Path = syn::parse_str(name).expect("failed to parse path"); parsed.to_tokens(tokens); } FieldType::Generic(name, ty) => { let name = Ident::new(name, Span::call_site()); let ty = &**ty; quote!(#name<#ty>).to_tokens(tokens); } } } } impl FieldType { pub fn method_name(&self) -> String { match self { FieldType::Normal(name) => name.split("::").last().unwrap().to_snake_case(), FieldType::Generic(name, ty) => match &**name { "Option" => format!("opt_{}", ty.method_name()), "Vec" => { // Vec<Option<Foo>> => opt_vec_foo match &**ty { FieldType::Generic(name, ty) if name == "Option" => { return format!("opt_vec_{}s", ty.method_name()) } _ => {} } format!("{}s", ty.method_name()) } "Box" => ty.method_name(), _ => todo!("method_name for generic type: {}", name), }, } } fn contains_type(&self, type_name: &str) -> bool { let regex = CachedRegex::new(type_name).expect("failed to create regex"); match self { FieldType::Normal(name) => regex.is_match(name), FieldType::Generic(name, ty) => regex.is_match(name) || ty.contains_type(type_name), } } } fn all_field_types(node_types: &[&Item]) -> HashSet<FieldType> { let mut all_types = HashSet::new(); for ty in node_types { let type_name = match ty { Item::Enum(data) => data.ident.to_string(), Item::Struct(data) => data.ident.to_string(), _ => continue, }; all_types.insert(FieldType::Normal(type_name)); match ty { Item::Enum(data) => { for variant in &data.variants { for field in &variant.fields { let ty = &field.ty; all_types.extend(all_types_in_ty(ty)); } } } Item::Struct(data) => { for field in &data.fields { let ty = &field.ty; all_types.extend(all_types_in_ty(ty)); } } _ => continue, } } all_types } fn to_field_ty(ty: &Type) -> Option<FieldType> { if let Some(ty) = extract_vec(ty) { return to_field_ty(ty).map(|ty| FieldType::Generic("Vec".into(), Box::new(ty))); } if let Some(ty) = extract_generic("Box", ty) { return to_field_ty(ty).map(|ty| FieldType::Generic("Box".into(), Box::new(ty))); } if let Some(ty) = extract_generic("Option", ty) { return to_field_ty(ty).map(|ty| FieldType::Generic("Option".into(), Box::new(ty))); } match ty { Type::Path(p) => { let last = p.path.segments.last().unwrap(); if last.arguments.is_empty() { let i = &last.ident; if i == "bool" || i == "char" || i == "f32" || i == "f64" || i == "i8" || i == "i16" || i == "i32" || i == "i64" || i == "i128" || i == "isize" || i == "str" || i == "u8" || i == "u16" || i == "u32" || i == "u64" || i == "u128" || i == "usize" { return None; } return Some(FieldType::Normal(quote!(#p).to_string())); } todo!("to_field_ty: {:?}", ty) } _ => todo!("to_field_ty"), } } fn all_types_in_ty(ty: &Type) -> Vec<FieldType> { if let Some(ty) = extract_vec(ty) { let mut types = all_types_in_ty(ty); types.extend(to_field_ty(ty).map(|ty| FieldType::Generic("Vec".into(), Box::new(ty)))); return types; } if let Some(ty) = extract_generic("Box", ty) { let mut types = all_types_in_ty(ty); types.extend(to_field_ty(ty).map(|ty| FieldType::Generic("Box".into(), Box::new(ty)))); return types; } if let Some(ty) = extract_generic("Option", ty) { let mut types = all_types_in_ty(ty); types.extend(to_field_ty(ty).map(|ty| FieldType::Generic("Option".into(), Box::new(ty)))); return types; } to_field_ty(ty).into_iter().collect() } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum TraitKind { Visit, VisitMut, Fold, } impl TraitKind { pub fn method_prefix(self) -> &'static str { match self { TraitKind::Visit => "visit", TraitKind::VisitMut => "visit_mut", TraitKind::Fold => "fold", } } pub fn trait_prefix(self) -> &'static str { match self { TraitKind::Visit => "Visit", TraitKind::VisitMut => "VisitMut", TraitKind::Fold => "Fold", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Variant { Normal, AstPath, } impl Variant { pub fn method_suffix(self, is_visitor_method: bool) -> &'static str { if self == Variant::Normal || is_visitor_method { "" } else { "_ast_path" } } } struct Generator<'a> { kind: TraitKind, variant: Variant, excluded_types: &'a [String], } impl Generator<'_> { fn should_skip(&self, ty: &Type) -> bool { if let Some(ty) = extract_generic("Box", ty) { return self.should_skip(ty); } if let Some(ty) = extract_generic("Vec", ty) { return self.should_skip(ty); } if let Some(ty) = extract_generic("Option", ty) { return self.should_skip(ty); } let ty = to_field_ty(ty); match ty { Some(ty) => { for excluded_type in self.excluded_types { if ty.contains_type(excluded_type) { return true; } } } None => return true, } false } fn method_lifetime(&self) -> TokenStream { match self.kind { TraitKind::Visit => match self.variant { Variant::Normal => quote!(), Variant::AstPath => quote!(<'ast: 'r, 'r>), }, TraitKind::VisitMut => quote!(), TraitKind::Fold => quote!(), } } fn parameter_type_token(&self, ty: TokenStream) -> TokenStream { match self.kind { TraitKind::Visit => match self.variant { Variant::Normal => quote!(&#ty), Variant::AstPath => quote!(&'ast #ty), }, TraitKind::VisitMut => quote!(&mut #ty), TraitKind::Fold => ty, } } /// This includes `->` fn return_type_token(&self, ty: TokenStream) -> TokenStream { match self.kind { TraitKind::Visit => quote!(), TraitKind::VisitMut => quote!(), TraitKind::Fold => quote!(-> #ty), } } fn arg_extra_token(&self) -> TokenStream { match self.variant { Variant::Normal => quote!(), Variant::AstPath => quote!(, __ast_path), } } fn param_extra_token(&self) -> TokenStream { match self.variant { Variant::Normal => quote!(), Variant::AstPath => match self.kind { TraitKind::Visit => { quote!(, __ast_path: &mut AstNodePath<'r>) } TraitKind::VisitMut | TraitKind::Fold => quote!(, __ast_path: &mut AstKindPath), }, } } fn trait_name(&self, with: bool) -> Ident { let name = self.kind.trait_prefix(); let name = if with { format!("{}With", name) } else { name.to_string() }; match self.variant { Variant::Normal => Ident::new(&name, Span::call_site()), Variant::AstPath => Ident::new(&format!("{}AstPath", name), Span::call_site()), } } fn base_trait_attrs(&self) -> Vec<Attribute> { let mut attrs = Vec::new(); if self.variant == Variant::AstPath { attrs.push(parse_quote!(#[cfg(any(docsrs, feature = "path"))])); attrs.push(parse_quote!(#[cfg_attr(docsrs, doc(cfg(feature = "path")))])); } attrs } fn declare_visit_trait(&self, all_types: &[FieldType]) -> Vec<Item> { let mut items = Vec::<Item>::new(); let lifetime = self.method_lifetime(); let ast_path_arg = self.arg_extra_token(); let ast_path_params = self.param_extra_token(); let with_trait_name = self.trait_name(true); let trait_name = self.trait_name(false); let attrs = self.base_trait_attrs(); let mut trait_methods = Vec::<TraitItem>::new(); let mut either_impl_methods = Vec::<TraitItem>::new(); let mut optional_impl_methods = Vec::<TraitItem>::new(); let mut ptr_impl_methods = Vec::<TraitItem>::new(); for ty in all_types { if let FieldType::Generic(name, ..) = &ty { if name == "Box" { continue; } } let type_name = quote!(#ty); let return_type = self.return_type_token(quote!(#type_name)); let node_type = self.node_type_for_visitor_method(ty); let type_param = self.parameter_type_token(quote!(#node_type)); let visit_method_name = Ident::new( &format!( "{}_{}{}", self.kind.method_prefix(), ty.method_name(), self.variant.method_suffix(true) ), Span::call_site(), ); let visit_with_children_name = Ident::new( &format!( "{}_children_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let recurse_doc = "If you want to recurse, you need to call it manually."; let method_doc = doc(&format!( "Visit a node of type `{}`.\n\nBy default, this method calls \ [`{type_name}::{visit_with_children_name}`]. {recurse_doc}", type_name )); trait_methods.push(parse_quote!( #method_doc #[inline] fn #visit_method_name #lifetime (&mut self, node: #type_param #ast_path_params) #return_type { <#node_type as #with_trait_name<Self>>::#visit_with_children_name(node, self #ast_path_arg) } )); either_impl_methods.push(parse_quote!( #[inline] fn #visit_method_name #lifetime (&mut self, node: #type_param #ast_path_params) #return_type { match self { swc_visit::Either::Left(visitor) => { #trait_name::#visit_method_name(visitor, node #ast_path_arg) } swc_visit::Either::Right(visitor) => { #trait_name::#visit_method_name(visitor, node #ast_path_arg) } } } )); let else_block = if self.kind == TraitKind::Fold { quote!(node) } else { quote!() }; optional_impl_methods.push(parse_quote!( #[inline] fn #visit_method_name #lifetime (&mut self, node: #type_param #ast_path_params) #return_type { if self.enabled { <V as #trait_name>::#visit_method_name(&mut self.visitor, node #ast_path_arg) } else { #else_block } } )); ptr_impl_methods.push(parse_quote!( #[inline] fn #visit_method_name #lifetime (&mut self, node: #type_param #ast_path_params) #return_type { <V as #trait_name>::#visit_method_name(&mut **self, node #ast_path_arg) } )); } items.push(parse_quote! { /// A visitor trait for traversing the AST. #(#attrs)* pub trait #trait_name { #(#trait_methods)* } }); // &mut V items.push(parse_quote! { #(#attrs)* impl<V> #trait_name for &mut V where V: ?Sized + #trait_name { #(#ptr_impl_methods)* } }); // Box<V> items.push(parse_quote! { #(#attrs)* impl<V> #trait_name for Box<V> where V: ?Sized + #trait_name { #(#ptr_impl_methods)* } }); // ::swc_visit::Either<A, B> items.push(parse_quote! { #(#attrs)* impl<A, B> #trait_name for ::swc_visit::Either<A, B> where A: #trait_name, B: #trait_name, { #(#either_impl_methods)* } }); // ::swc_visit::Optional<V> items.push(parse_quote! { #(#attrs)* impl<V> #trait_name for ::swc_visit::Optional<V> where V: #trait_name, { #(#optional_impl_methods)* } }); items } fn declare_visit_with_trait(&self) -> Vec<Item> { let visitor_trait_name = self.trait_name(false); let trait_name = self.trait_name(true); let attrs = self.base_trait_attrs(); let mut visit_with_trait_methods: Vec<TraitItem> = Vec::new(); { let lifetime = self.method_lifetime(); let ast_path_extra = self.param_extra_token(); let return_type = self.return_type_token(quote!(Self)); let receiver = self.parameter_type_token(quote!(self)); let visit_with_name = Ident::new( &format!( "{}_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let visit_with_children_name = Ident::new( &format!( "{}_children_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); visit_with_trait_methods.push(parse_quote!( /// Calls a visitor method (visitor.fold_xxx) with self. fn #visit_with_name #lifetime (#receiver, visitor: &mut V #ast_path_extra) #return_type; )); visit_with_trait_methods.push(parse_quote!( /// Visit children nodes of `self`` with `visitor`. fn #visit_with_children_name #lifetime (#receiver, visitor: &mut V #ast_path_extra) #return_type; )); } let mut items: Vec<Item> = Vec::new(); items.push(parse_quote!( /// A trait implemented for types that can be visited using a visitor. #(#attrs)* pub trait #trait_name<V: ?Sized + #visitor_trait_name> { #(#visit_with_trait_methods)* } )); items } fn implement_visit_with_for_node_types(&self, node_types: &[&Item]) -> Vec<Item> { let visitor_trait_name = self.trait_name(false); let trait_name = self.trait_name(true); let attrs = self.base_trait_attrs(); let mut items: Vec<Item> = Vec::new(); for node_type in node_types { let type_name = match node_type { Item::Enum(data) => data.ident.clone(), Item::Struct(data) => data.ident.clone(), _ => continue, }; let lifetime = self.method_lifetime(); let ast_path_arg = self.arg_extra_token(); let ast_path_param = self.param_extra_token(); let return_type = self.return_type_token(quote!(Self)); let receiver = self.parameter_type_token(quote!(self)); let visit_with_name = Ident::new( &format!( "{}_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let visit_with_children_name = Ident::new( &format!( "{}_children_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let visit_method_name = Ident::new( &format!( "{}_{}{}", self.kind.method_prefix(), type_name.to_string().to_snake_case(), self.variant.method_suffix(true) ), Span::call_site(), ); let visit_with_doc = doc(&format!( "Calls [{visitor_trait_name}`::{}`] with `self`.", visit_method_name )); let default_body: Expr = match node_type { Item::Enum(data) => { let name = &data.ident; let mut match_arms = Vec::new(); for v in &data.variants { let variant_name = &v.ident; match_arms.push(self.default_visit_body( quote!(#name::#variant_name), name, Some(variant_name), &v.fields, )); } parse_quote!(match self { #(#match_arms)* }) } Item::Struct(data) => { let name = &data.ident; let arm = self.default_visit_body(quote!(#name), name, None, &data.fields); parse_quote!(match self { #arm }) } _ => continue, }; items.push(parse_quote!( #(#attrs)* impl<V: ?Sized + #visitor_trait_name> #trait_name<V> for #type_name { #visit_with_doc fn #visit_with_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { <V as #visitor_trait_name>::#visit_method_name(visitor, self #ast_path_arg) } fn #visit_with_children_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { #default_body } } )); } items } fn default_visit_body( &self, path: TokenStream, type_name: &Ident, enum_variant_name: Option<&Ident>, fields: &Fields, ) -> Arm { let ast_path_arg = match self.variant { Variant::Normal => quote!(), Variant::AstPath => quote!(, &mut *__ast_path), }; let with_visitor_trait_name = self.trait_name(true); let visit_with_name = Ident::new( &format!( "{}_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let fields_enum_name = Ident::new(&format!("{type_name}Field"), Span::call_site()); let enum_ast_path = match enum_variant_name { Some(variant_name) if self.variant == Variant::AstPath => { let field_variant = Ident::new( &variant_name.to_string().to_pascal_case(), Span::call_site(), ); match self.kind { TraitKind::Visit => Some(quote!( let mut __ast_path = __ast_path .with_guard( AstParentNodeRef::#type_name(self, self::fields::#fields_enum_name::#field_variant), ); )), _ => Some(quote!( let mut __ast_path = __ast_path .with_guard( AstParentKind::#type_name(self::fields::#fields_enum_name::#field_variant), ); )), } } _ => None, }; match fields { Fields::Named(n) => { let mut stmts: Vec<Stmt> = Vec::new(); let mut bindings = Vec::new(); let mut reconstruct = match self.kind { TraitKind::Visit | TraitKind::VisitMut => None, TraitKind::Fold => Some(Vec::<TokenStream>::new()), }; for field in &n.named { let field_name = field.ident.as_ref().unwrap(); let ty = &field.ty; bindings.push(field_name.clone()); let field_variant = Ident::new(&field_name.to_string().to_pascal_case(), Span::call_site()); let mut ast_path_guard_expr: Option<Stmt> = None; if self.variant == Variant::AstPath && !self.should_skip(ty) { let mut kind = quote!(self::fields::#fields_enum_name::#field_variant); if extract_vec(extract_generic("Option", ty).unwrap_or(ty)).is_some() { kind = quote!(#kind(usize::MAX)); } match self.kind { TraitKind::Visit => { ast_path_guard_expr = Some(parse_quote!( let mut __ast_path = __ast_path .with_guard( AstParentNodeRef::#type_name(self, #kind), ); )); } _ => { ast_path_guard_expr = Some(parse_quote!( let mut __ast_path = __ast_path .with_guard( AstParentKind::#type_name(#kind), ); )); } } } if let Some(reconstructor) = &mut reconstruct { if !self.should_skip(ty) { stmts.push(parse_quote!( let #field_name = { #ast_path_guard_expr <#ty as #with_visitor_trait_name<V>>::#visit_with_name(#field_name, visitor #ast_path_arg) }; )); } reconstructor.push(parse_quote!(#field_name)); } else if !self.should_skip(ty) { stmts.push(parse_quote!( { #ast_path_guard_expr <#ty as #with_visitor_trait_name<V>>::#visit_with_name(#field_name, visitor #ast_path_arg) }; )); } } match self.kind { TraitKind::Visit | TraitKind::VisitMut => { parse_quote!(#path { #(#bindings),* } => { #enum_ast_path; #(#stmts)* }) } TraitKind::Fold => { let reconstruct = reconstruct.unwrap(); parse_quote!(#path { #(#bindings),* } => { #enum_ast_path; #(#stmts)* #path { #(#reconstruct),* } }) } } } Fields::Unnamed(u) => { let mut stmts: Vec<Stmt> = Vec::new(); let mut bindings = Vec::<TokenStream>::new(); let mut reconstruct = match self.kind { TraitKind::Visit | TraitKind::VisitMut => None, TraitKind::Fold => Some(Vec::<TokenStream>::new()), }; for (idx, field) in u.unnamed.iter().enumerate() { let field_name = Ident::new(&format!("_field_{}", idx), Span::call_site()); let ty = &field.ty; let binding_idx = Lit::Int(LitInt::new(&idx.to_string(), Span::call_site())); bindings.push(parse_quote!(#binding_idx: #field_name)); if let Some(reconstructor) = &mut reconstruct { if !self.should_skip(ty) { stmts.push(parse_quote!( let #field_name = <#ty as #with_visitor_trait_name<V>>::#visit_with_name(#field_name, visitor #ast_path_arg); )); } reconstructor.push(parse_quote!(#binding_idx: #field_name)); } else if !self.should_skip(ty) { stmts.push(parse_quote!( <#ty as #with_visitor_trait_name<V>>::#visit_with_name(#field_name, visitor #ast_path_arg); )); } } match self.kind { TraitKind::Visit | TraitKind::VisitMut => { parse_quote!(#path { #(#bindings),* }=> { #enum_ast_path; #(#stmts)* }) } TraitKind::Fold => { let reconstruct = reconstruct.unwrap(); parse_quote!(#path { #(#bindings),* } => { #enum_ast_path; #(#stmts)* #path{#(#reconstruct),*} }) } } } Fields::Unit => match self.kind { TraitKind::Visit | TraitKind::VisitMut => { parse_quote!(#path => {}) } TraitKind::Fold => parse_quote!(#path => #path,), }, } } fn implement_visit_with_for_non_node_types(&self, non_leaf_types: &[FieldType]) -> Vec<Item> { let visitor_trait_name = self.trait_name(false); let visit_with_trait_name = self.trait_name(true); let attrs = self.base_trait_attrs(); let lifetime = self.method_lifetime(); let ast_path_arg = self.arg_extra_token(); let ast_path_param = self.param_extra_token(); let return_type = self.return_type_token(quote!(Self)); let receiver = self.parameter_type_token(quote!(self)); let mut items: Vec<Item> = Vec::new(); for node_type in non_leaf_types { let visit_with_name = Ident::new( &format!( "{}_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let visit_with_children_name = Ident::new( &format!( "{}_children_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let visit_method_name = Ident::new( &format!( "{}_{}{}", self.kind.method_prefix(), node_type.method_name(), self.variant.method_suffix(true) ), Span::call_site(), ); let visit_with_doc = doc(&format!( "Calls [{visitor_trait_name}`::{}`] with `self`. (Extra impl)", visit_method_name )); let default_body: Expr = match node_type { FieldType::Normal(..) => match self.kind { TraitKind::Visit => { parse_quote!({}) } TraitKind::VisitMut => { parse_quote!({}) } TraitKind::Fold => { parse_quote!(self) } }, FieldType::Generic(name, inner) => match &**name { "Vec" => { let inner = inner.as_ref(); let inner_ty = quote!(#inner); match (self.kind, self.variant) { (TraitKind::Visit, Variant::Normal) => { parse_quote!(self.iter().for_each(|item| { <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(item, visitor #ast_path_arg) })) } (TraitKind::Visit, Variant::AstPath) => { parse_quote!(self.iter().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(item, visitor, &mut *__ast_path) })) } (TraitKind::VisitMut, Variant::Normal) => { parse_quote!( self.iter_mut().for_each(|item| { <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(item, visitor #ast_path_arg) }) ) } (TraitKind::VisitMut, Variant::AstPath) => { parse_quote!( self.iter_mut().enumerate().for_each(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(item, visitor, &mut *__ast_path) }) ) } (TraitKind::Fold, Variant::Normal) => { parse_quote!( swc_visit::util::move_map::MoveMap::move_map(self, |item| { <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(item, visitor #ast_path_arg) }) ) } (TraitKind::Fold, Variant::AstPath) => { parse_quote!( self.into_iter().enumerate().map(|(__idx, item)| { let mut __ast_path = __ast_path.with_index_guard(__idx); <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(item, visitor, &mut *__ast_path) }).collect() ) } } } "Option" => { let inner = inner.as_ref(); let inner_ty = quote!(#inner); match self.kind { TraitKind::Visit => { parse_quote!( match self { Some(inner) => { <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(inner, visitor #ast_path_arg) } None => {} } ) } TraitKind::VisitMut => { parse_quote!( match self { Some(inner) => { <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(inner, visitor #ast_path_arg) } None => {} } ) } TraitKind::Fold => { parse_quote!( self.map(|inner| { <#inner_ty as #visit_with_trait_name<V>>::#visit_with_name(inner, visitor #ast_path_arg) }) ) } } } "Box" => continue, _ => unreachable!("unexpected generic type: {}", name), }, }; let target_type = self.node_type_for_visitor_method(node_type); items.push(parse_quote!( #(#attrs)* impl<V: ?Sized + #visitor_trait_name> #visit_with_trait_name<V> for #target_type { #visit_with_doc #[inline] fn #visit_with_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { <V as #visitor_trait_name>::#visit_method_name(visitor, self #ast_path_arg) } #[inline] fn #visit_with_children_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { #default_body } } )); } items } fn implement_visit_with_for_generic_types(&self) -> Vec<Item> { let visit_trait_name = self.trait_name(false); let visit_with_trait_name = self.trait_name(true); let lifetime = self.method_lifetime(); let ast_path_arg = self.arg_extra_token(); let ast_path_param = self.param_extra_token(); let return_type = self.return_type_token(quote!(Self)); let attrs = self.base_trait_attrs(); let receiver = self.parameter_type_token(quote!(self)); let visit_with_name = Ident::new( &format!( "{}_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let visit_with_children_name = Ident::new( &format!( "{}_children_with{}", self.kind.method_prefix(), self.variant.method_suffix(false) ), Span::call_site(), ); let mut items = Vec::<Item>::new(); { // Box<T> => T match self.kind { TraitKind::Fold => { items.push(parse_quote!( #(#attrs)* impl<V, T> #visit_with_trait_name<V> for std::boxed::Box<T> where V: ?Sized + #visit_trait_name, T: #visit_with_trait_name<V> { #[inline] fn #visit_with_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { swc_visit::util::map::Map::map(self, |inner| { <T as #visit_with_trait_name<V>>::#visit_with_name(inner, visitor #ast_path_arg) }) } #[inline] fn #visit_with_children_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { swc_visit::util::map::Map::map(self, |inner| { <T as #visit_with_trait_name<V>>::#visit_with_children_name(inner, visitor #ast_path_arg) }) } } )); } _ => { let deref_expr = match self.kind { TraitKind::Visit => { quote!(&**self) } TraitKind::VisitMut => { quote!(&mut **self) } TraitKind::Fold => { unreachable!() } }; let restore_expr = match self.kind { TraitKind::Visit => { quote!() } TraitKind::VisitMut => { quote!() } TraitKind::Fold => { unreachable!() } }; items.push(parse_quote!( #(#attrs)* impl<V, T> #visit_with_trait_name<V> for std::boxed::Box<T> where V: ?Sized + #visit_trait_name, T: #visit_with_trait_name<V> { #[inline] fn #visit_with_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { let v = <T as #visit_with_trait_name<V>>::#visit_with_name(#deref_expr, visitor #ast_path_arg); #restore_expr v } #[inline] fn #visit_with_children_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { let v = <T as #visit_with_trait_name<V>>::#visit_with_children_name(#deref_expr, visitor #ast_path_arg); #restore_expr v } } )); } } } if self.kind == TraitKind::Visit { // Vec<T> => [T] items.push(parse_quote!( #(#attrs)* impl<V, T> #visit_with_trait_name<V> for std::vec::Vec<T> where V: ?Sized + #visit_trait_name, [T]: #visit_with_trait_name<V> { #[inline] fn #visit_with_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { let v = <[T] as #visit_with_trait_name<V>>::#visit_with_name(self, visitor #ast_path_arg); v } #[inline] fn #visit_with_children_name #lifetime (#receiver, visitor: &mut V #ast_path_param) #return_type { let v = <[T] as #visit_with_trait_name<V>>::#visit_with_children_name(self, visitor #ast_path_arg); v } } )); } items } fn node_type_for_visitor_method(&self, node_type: &FieldType) -> TokenStream { match self.kind { TraitKind::Visit => match node_type { FieldType::Generic(name, inner) if name == "Vec" => { let inner_ty = quote!(#inner); quote!([#inner_ty]) } _ => quote!(#node_type), }, _ => quote!(#node_type), } } } fn doc(s: &str) -> Attribute { parse_quote!(#[doc = #s]) } fn field_variant(type_name: &Ident, field: &Field) -> Option<(TokenStream, Option<Arm>)> { if let Some(field_name) = &field.ident { let variant_name = Ident::new(&field_name.to_string().to_pascal_case(), Span::call_site()); let variant_doc = doc(&format!("Represents [`{type_name}::{field_name}`]")); if extract_vec(extract_generic("Option", &field.ty).unwrap_or(&field.ty)).is_some() { let v = quote!( #variant_doc #variant_name(usize) ); let arg = parse_quote!( Self::#variant_name(idx) => { assert_initial_index(*idx, index); *idx = index; }, ); return Some((v, Some(arg))); } return Some(( quote!( #variant_doc #variant_name ), None, )); } None } fn extract_vec(ty: &Type) -> Option<&Type> { extract_generic("Vec", ty) } fn extract_generic<'a>(name: &str, ty: &'a Type) -> Option<&'a Type> { if let Type::Path(p) = ty { let last = p.path.segments.last().unwrap(); if !last.arguments.is_empty() && last.ident == name { match &last.arguments { PathArguments::AngleBracketed(tps) => { let arg = tps.args.first().unwrap(); match arg { GenericArgument::Type(arg) => return Some(arg), _ => unimplemented!("generic parameter other than type"), } } _ => unimplemented!("Box() -> T or Box without a type parameter"), } } } if let Type::Reference(r) = ty { return extract_generic(name, &r.elem); } None } fn to_iter(e: TokenStream, ty: &Type, node_names: &[Ident]) -> Option<Expr> { if let Some(ty) = extract_vec(ty) { let inner_expr = to_iter(quote!(item), ty, node_names)?; return Some(parse_quote!(#e.iter().flat_map(|item| #inner_expr))); } if let Some(ty) = extract_generic("Option", ty) { let inner_expr = to_iter(quote!(item), ty, node_names)?; return Some(parse_quote!(#e.iter().flat_map(|item| #inner_expr))); } if let Some(ty) = extract_generic("Box", ty) { let inner_expr = to_iter(quote!(item), ty, node_names)?; return Some(parse_quote!({ let item = &*#e; #inner_expr })); } if let Type::Path(p) = ty { let ty = &p.path.segments.last().unwrap().ident; if node_names.contains(ty) { return Some(parse_quote!(::std::iter::once(NodeRef::#ty(&#e)))); } None } else { todo!("to_iter for {:?}", ty); } } fn define_fields(crate_name: &Ident, node_types: &[&Item]) -> Vec<Item> { let mut items = Vec::<Item>::new(); let mut kind_enum_members = Vec::new(); let mut parent_enum_members = Vec::new(); let mut node_ref_enum_members = Vec::new(); let mut kind_set_index_arms = Vec::<Arm>::new(); let mut node_ref_set_index_arms = Vec::<Arm>::new(); let mut node_ref_kind_arms = Vec::<Arm>::new(); let mut node_ref_iter_next_arms = Vec::<Arm>::new(); let node_names = node_types .iter() .filter_map(|ty| match ty { Item::Enum(data) => Some(data.ident.clone()), Item::Struct(data) => Some(data.ident.clone()), _ => None, }) .collect::<Vec<_>>(); let is_node_ref_raw = |ty: &Type| match ty { Type::Path(p) => node_names.contains(&p.path.segments.last().unwrap().ident), _ => false, }; let is_node_ref = |ty: &Type| { if let Some(ty) = extract_generic("Box", ty) { return is_node_ref_raw(ty); } is_node_ref_raw(ty) }; { let mut defs = Vec::<Item>::new(); defs.push(parse_quote!( use #crate_name::*; )); defs.push(parse_quote!( #[inline(always)] fn assert_initial_index(idx: usize, index: usize) { #[cfg(debug_assertions)] if !(idx == usize::MAX || index == usize::MAX) { { panic!("Should be usize::MAX"); } } } )); for ty in node_types { let type_name = match ty { Item::Enum(data) => data.ident.clone(), Item::Struct(data) => data.ident.clone(), _ => continue, }; let fields_enum_name = Ident::new(&format!("{type_name}Field"), Span::call_site()); let mut variants = Vec::new(); kind_set_index_arms.push(parse_quote!( Self::#type_name(v) => v.set_index(index), )); node_ref_kind_arms.push(parse_quote!( Self::#type_name(_, __field_kind) => AstParentKind::#type_name(*__field_kind), )); node_ref_set_index_arms.push(parse_quote!( Self::#type_name(_, __field_kind) => __field_kind.set_index(index), )); match ty { Item::Enum(data) => { for variant in &data.variants { let orig_ident = &variant.ident; let variant_name = Ident::new( &variant.ident.to_string().to_pascal_case(), Span::call_site(), ); let variant_doc = doc(&format!("Represents [`{type_name}::{orig_ident}`]")); variants.push(quote!( #variant_doc #variant_name )); } kind_enum_members.push(quote!( #type_name(#fields_enum_name) )); parent_enum_members.push(quote!( #type_name(&'ast #type_name, #fields_enum_name) )); node_ref_enum_members.push(quote!( #type_name(&'ast #type_name) )); items.push(parse_quote!( impl<'ast> From<&'ast #type_name> for NodeRef<'ast> { fn from(node: &'ast #type_name) -> Self { NodeRef::#type_name(node) } } )); { let mut arms = Vec::<Arm>::new(); for variant in &data.variants { let variant_name = &variant.ident; // TODO: Support all kinds of fields if variant.fields.len() != 1 { continue; } for f in variant.fields.iter().filter(|f| is_node_ref(&f.ty)) { let mut ty = &f.ty; if let Some(inner) = extract_generic("Box", ty) { ty = inner; } arms.push(parse_quote!( #type_name::#variant_name(v0) => { Box::new(::std::iter::once(NodeRef::#ty(v0))) }, )); } } node_ref_iter_next_arms.push(parse_quote!( NodeRef::#type_name(node) => { match node { #(#arms)* _ => Box::new(::std::iter::empty::<NodeRef<'ast>>()) } } )); } defs.push(parse_quote!( impl #fields_enum_name { #[inline(always)] pub(crate) fn set_index(&mut self, _: usize) { swc_visit::wrong_ast_path(); } } )); } Item::Struct(data) => { let mut set_index_arms = Vec::<Arm>::new(); for field in &data.fields { let opt = field_variant(&type_name, field); let opt = match opt { Some(v) => v, None => continue, }; variants.push(opt.0); set_index_arms.extend(opt.1); } kind_enum_members.push(quote!( #type_name(#fields_enum_name) )); parent_enum_members.push(quote!( #type_name(&'ast #type_name, #fields_enum_name) )); node_ref_enum_members.push(quote!( #type_name(&'ast #type_name) )); items.push(parse_quote!( impl<'ast> From<&'ast #type_name> for NodeRef<'ast> { fn from(node: &'ast #type_name) -> Self { NodeRef::#type_name(node) } } )); { let mut iter: Expr = parse_quote!(::std::iter::empty::<NodeRef<'ast>>()); match &data.fields { Fields::Named(fields) => { for f in fields.named.iter() { let ident = &f.ident; let iter_expr = to_iter(quote!(node.#ident), &f.ty, &node_names); if let Some(iter_expr) = iter_expr { iter = parse_quote!(#iter.chain(#iter_expr)); } } } Fields::Unnamed(_fields) => { // TODO: Support unnamed fields } Fields::Unit => {} } node_ref_iter_next_arms.push(parse_quote!( NodeRef::#type_name(node) => { let iterator = #iter; Box::new(iterator) } )); } defs.push(parse_quote!( impl #fields_enum_name { pub(crate) fn set_index(&mut self, index: usize) { match self { #(#set_index_arms)* _ => { swc_visit::wrong_ast_path() } } } } )); } _ => continue, } defs.push(parse_quote!( #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum #fields_enum_name { #(#variants),* } )) } { defs.push(parse_quote!( #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] pub enum AstParentKind { #(#kind_enum_members),* } )); defs.push(parse_quote!( impl ::swc_visit::ParentKind for AstParentKind { #[inline] fn set_index(&mut self, index: usize) { match self { #(#kind_set_index_arms)* } } } )); } { defs.push(parse_quote!( #[derive(Debug, Clone, Copy)] pub enum AstParentNodeRef<'ast> { #(#parent_enum_members),* } )); items.push(parse_quote!( #[derive(Debug, Clone, Copy)] pub enum NodeRef<'ast> { #(#node_ref_enum_members),* } )); defs.push(parse_quote!( impl<'ast> ::swc_visit::NodeRef for AstParentNodeRef<'ast> { type ParentKind = AstParentKind; #[inline(always)] fn kind(&self) -> AstParentKind { self.kind() } fn set_index(&mut self, index: usize) { match self { #(#node_ref_set_index_arms)* } } } )); defs.push(parse_quote!( #[cfg(any(docsrs, feature = "path"))] impl<'ast> AstParentNodeRef<'ast> { #[inline] pub fn kind(&self) -> AstParentKind { match self { #(#node_ref_kind_arms)* } } } )); items.push(parse_quote!( impl<'ast> NodeRef<'ast> { /// This is not a part of semver-stable API. It is experimental and subject to change. #[allow(unreachable_patterns)] pub fn experimental_raw_children<'a>(&'a self) -> Box<dyn 'a + Iterator<Item = NodeRef<'ast>>> { match self { #(#node_ref_iter_next_arms)* } } } )); items.push(parse_quote!( impl<'ast> NodeRef<'ast> { /// Visit all nodes in self in preorder. /// /// This is not a part of semver-stable API. It is /// experimental and subject to change. pub fn experimental_traverse( &'ast self, ) -> Box<dyn 'ast + Iterator<Item = NodeRef<'ast>>> { let mut queue = std::collections::VecDeque::<NodeRef<'ast>>::new(); queue.push_back(*self); Box::new(std::iter::from_fn(move || { let node: NodeRef<'ast> = queue.pop_front()?; { let children = node.experimental_raw_children(); queue.extend(children); } Some(node) })) } } )); } items.insert( 0, parse_quote!( #[cfg(any(docsrs, feature = "path"))] pub mod fields { #(#defs)* } ), ); items.push(parse_quote!( #[cfg(any(docsrs, feature = "path"))] pub use self::fields::{AstParentKind, AstParentNodeRef}; )); } items }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
tools/generate-code/src/main.rs
Rust
#![allow(clippy::only_used_in_recursion)] use std::path::{Path, PathBuf}; use anyhow::{bail, Context, Result}; use clap::Parser; use proc_macro2::Span; use swc_cached::regex::CachedRegex; use syn::{Ident, Item}; use crate::types::qualify_types; mod generators; mod types; #[derive(Debug, Parser)] struct CliArgs { /// The directory containing the crate to generate the visitor for. #[clap(short = 'i', long)] input_dir: PathBuf, /// The file for the generated visitor code. #[clap(short = 'o', long)] output: PathBuf, /// The list of types to exclude from the generated visitor. #[clap(long)] exclude: Vec<String>, } fn main() -> Result<()> { let CliArgs { input_dir, output, exclude, } = CliArgs::parse(); run_visitor_codegen(&input_dir, &output, &exclude)?; Ok(()) } fn run_visitor_codegen(input_dir: &Path, output: &Path, excluded_types: &[String]) -> Result<()> { let crate_name = Ident::new( input_dir.file_name().unwrap().to_str().unwrap(), Span::call_site(), ); let input_dir = input_dir .canonicalize() .context("faield to canonicalize input directory")? .join("src"); eprintln!("Generating visitor for crate in directory: {:?}", input_dir); let input_files = collect_input_files(&input_dir)?; eprintln!("Found {} input files", input_files.len()); eprintln!("Generating visitor in directory: {:?}", output); let inputs = input_files .iter() .map(|file| { parse_rust_file(file).with_context(|| format!("failed to parse file: {:?}", file)) }) .map(|res| res.map(qualify_types)) .collect::<Result<Vec<_>>>()?; let mut all_type_defs = inputs.iter().flat_map(get_type_defs).collect::<Vec<_>>(); all_type_defs.retain(|type_def| { let ident = match type_def { Item::Struct(data) => &data.ident, Item::Enum(data) => &data.ident, _ => return false, }; for type_name in excluded_types { let regex = CachedRegex::new(type_name).expect("failed to create regex"); if regex.is_match(&ident.to_string()) { return false; } } true }); all_type_defs.sort_by_key(|item| match item { Item::Enum(data) => Some(data.ident.clone()), Item::Struct(data) => Some(data.ident.clone()), _ => None, }); let file = generators::visitor::generate(&crate_name, &all_type_defs, excluded_types); let output_content = quote::quote!(#file).to_string(); let original = std::fs::read_to_string(output).ok(); std::fs::write(output, output_content).context("failed to write the output file")?; eprintln!("Generated visitor code in file: {:?}", output); run_cargo_fmt(output)?; if std::env::var("CI").is_ok_and(|v| v != "1") { if let Some(original) = original { let output = std::fs::read_to_string(output).context("failed to read the output file")?; if original != output { bail!( "The generated code is not up to date. Please run `cargo codegen` and commit \ the changes." ); } } } Ok(()) } #[test] fn test_ecmascript() { run_visitor_codegen( Path::new("../../crates/swc_ecma_ast"), Path::new("../../crates/swc_ecma_visit/src/generated.rs"), &[ "Align64".into(), "EncodeBigInt".into(), "EsVersion".into(), "FnPass".into(), ], ) .unwrap(); } #[test] fn test_ecmascript_std() { run_visitor_codegen( Path::new("../../crates/swc_ecma_ast"), Path::new("../../crates/swc_ecma_visit_std/src/generated.rs"), &[ "Align64".into(), "EncodeBigInt".into(), "EsVersion".into(), "FnPass".into(), "Accessibility".into(), "^Ts.*".into(), ], ) .unwrap(); } #[test] fn test_css() { run_visitor_codegen( Path::new("../../crates/swc_css_ast"), Path::new("../../crates/swc_css_visit/src/generated.rs"), &[], ) .unwrap(); } #[test] fn test_html() { run_visitor_codegen( Path::new("../../crates/swc_html_ast"), Path::new("../../crates/swc_html_visit/src/generated.rs"), &[], ) .unwrap(); } #[test] fn test_xml() { run_visitor_codegen( Path::new("../../crates/swc_xml_ast"), Path::new("../../crates/swc_xml_visit/src/generated.rs"), &[], ) .unwrap(); } fn get_type_defs(file: &syn::File) -> Vec<&Item> { let mut type_defs = Vec::new(); for item in &file.items { match item { Item::Struct(_) | Item::Enum(_) => { type_defs.push(item); } _ => {} } } type_defs } fn parse_rust_file(file: &Path) -> Result<syn::File> { let content = std::fs::read_to_string(file).context("failed to read the input file")?; let syntax = syn::parse_file(&content).context("failed to parse the input file using syn")?; Ok(syntax) } fn collect_input_files(input_dir: &Path) -> Result<Vec<PathBuf>> { Ok(walkdir::WalkDir::new(input_dir) .into_iter() .filter_map(|entry| entry.ok()) .filter(|entry| entry.file_type().is_file()) .map(|entry| entry.path().to_path_buf()) .collect()) } fn run_cargo_fmt(file: &Path) -> Result<()> { let file = file.canonicalize().context("failed to canonicalize file")?; let mut cmd = std::process::Command::new("cargo"); cmd.arg("fmt").arg("--").arg(file); eprintln!("Running: {:?}", cmd); let status = cmd.status().context("failed to run cargo fmt")?; if !status.success() { bail!("cargo fmt failed with status: {:?}", status); } Ok(()) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
tools/generate-code/src/types.rs
Rust
use std::collections::HashMap; use syn::{ parse_quote, visit_mut::{visit_file_mut, VisitMut}, File, Ident, ItemUse, Path, PathSegment, TypePath, UseTree, }; pub fn qualify_types(mut file: File) -> File { let use_items = collect_use_items(&file); let mut map = HashMap::new(); for item in use_items { // e.g. use swc_allocator::boxed::Box; // becomes `Box: "swc_allocator::boxed::Box"` in the map. for_each_use_item(&[], &item.tree, &mut |local_name, path| { map.insert(local_name.to_string(), path); }); } map.entry("Option".into()) .or_insert_with(|| parse_quote!(::std::option::Option)); map.entry("Box".into()) .or_insert_with(|| parse_quote!(::std::boxed::Box)); map.entry("Vec".into()) .or_insert_with(|| parse_quote!(::std::vec::Vec)); visit_file_mut(&mut Folder { map }, &mut file); file } fn for_each_use_item(path: &[Ident], tree: &UseTree, op: &mut impl FnMut(Ident, Path)) { match tree { UseTree::Path(p) => { if p.ident == "self" || p.ident == "super" || p.ident == "crate" { return; } let mut path = path.to_vec(); path.push(p.ident.clone()); for_each_use_item(&path, &p.tree, op); } UseTree::Name(name) => { let mut path = path.to_vec(); path.push(name.ident.clone()); op( name.ident.clone(), Path { leading_colon: None, segments: path.into_iter().map(PathSegment::from).collect(), }, ); } UseTree::Rename(..) => {} UseTree::Glob(_) => {} UseTree::Group(g) => { for item in &g.items { for_each_use_item(path, item, op); } } } } fn collect_use_items(file: &File) -> Vec<ItemUse> { let mut use_items = Vec::new(); for item in &file.items { if let syn::Item::Use(item_use) = item { use_items.push(item_use.clone()); } } use_items } struct Folder { /// e.g. `("Box", "std::boxed::Box")` map: HashMap<String, Path>, } impl VisitMut for Folder { fn visit_type_path_mut(&mut self, i: &mut TypePath) { if let Some(id) = i.path.get_ident() { if let Some(path) = self.map.get(&id.to_string()) { i.path = path.clone(); } } syn::visit_mut::visit_type_path_mut(self, i); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
tools/swc-releaser/src/main.rs
Rust
use std::{ collections::{hash_map::Entry, HashMap}, env, path::{Path, PathBuf}, process::Command, }; use anyhow::{Context, Result}; use cargo_metadata::{semver::Version, DependencyKind}; use changesets::ChangeType; use clap::{Parser, Subcommand}; use indexmap::IndexSet; use petgraph::{prelude::DiGraphMap, Direction}; #[derive(Debug, Parser)] struct CliArgs { #[clap(long)] pub dry_run: bool, #[clap(subcommand)] pub cmd: Cmd, } #[derive(Debug, Subcommand)] enum Cmd { Bump, } fn main() -> Result<()> { let CliArgs { dry_run, cmd } = CliArgs::parse(); let workspace_dir = env::var("CARGO_WORKSPACE_DIR") .map(PathBuf::from) .context("CARGO_WORKSPACE_DIR is not set")?; match cmd { Cmd::Bump => { run_bump(&workspace_dir, dry_run)?; } } Ok(()) } fn run_bump(workspace_dir: &Path, dry_run: bool) -> Result<()> { let changeset_dir = workspace_dir.join(".changeset"); let changeset = changesets::ChangeSet::from_directory(&changeset_dir) .context("failed to load changeset")?; if changeset.releases.is_empty() { eprintln!("No changeset found"); return Ok(()); } let (versions, graph) = get_data()?; let mut new_versions = VersionMap::new(); let mut worker = Bump { versions: &versions, graph: &graph, new_versions: &mut new_versions, }; for (pkg_name, release) in changeset.releases { let is_breaking = worker .is_breaking(pkg_name.as_str(), release.change_type()) .with_context(|| format!("failed to check if package {} is breaking", pkg_name))?; worker .bump_crate(pkg_name.as_str(), release.change_type(), is_breaking) .with_context(|| format!("failed to bump package {}", pkg_name))?; } for (pkg_name, version) in new_versions { run_cargo_set_version(&pkg_name, &version, dry_run) .with_context(|| format!("failed to set version for {}", pkg_name))?; } { eprintln!("Removing changeset files... "); if !dry_run { std::fs::remove_dir_all(&changeset_dir).context("failed to remove changeset files")?; } } { // Update changelog update_changelog().with_context(|| "failed to update changelog")?; } git_commit(dry_run).context("failed to commit")?; git_tag_core(dry_run).context("failed to tag core")?; Ok(()) } fn run_cargo_set_version(pkg_name: &str, version: &Version, dry_run: bool) -> Result<()> { let mut cmd = Command::new("cargo"); cmd.arg("set-version") .arg("-p") .arg(pkg_name) .arg(version.to_string()); eprintln!("Running {:?}", cmd); if dry_run { return Ok(()); } cmd.status().context("failed to run cargo set-version")?; Ok(()) } fn get_swc_core_version() -> Result<String> { let md = cargo_metadata::MetadataCommand::new() .no_deps() .exec() .expect("failed to run cargo metadata"); md.packages .iter() .find(|p| p.name == "swc_core") .map(|p| p.version.to_string()) .context("failed to find swc_core") } fn git_commit(dry_run: bool) -> Result<()> { let core_ver = get_swc_core_version()?; let mut cmd = Command::new("git"); cmd.arg("commit").arg("-am").arg(format!( "chore: Publish crates with `swc_core` `v{}`", core_ver )); eprintln!("Running {:?}", cmd); if dry_run { return Ok(()); } cmd.status().context("failed to run git commit")?; Ok(()) } fn git_tag_core(dry_run: bool) -> Result<()> { let core_ver = get_swc_core_version()?; let mut cmd = Command::new("git"); cmd.arg("tag").arg(format!("swc_core@v{}", core_ver)); eprintln!("Running {:?}", cmd); if dry_run { return Ok(()); } cmd.status().context("failed to run git tag")?; Ok(()) } struct Bump<'a> { /// Original versions versions: &'a VersionMap, /// Dependency graph graph: &'a InternedGraph, new_versions: &'a mut VersionMap, } impl Bump<'_> { fn is_breaking(&self, pkg_name: &str, change_type: Option<&ChangeType>) -> Result<bool> { let original_version = self .versions .get(pkg_name) .context(format!("failed to find original version for {}", pkg_name))?; Ok(match change_type { Some(ChangeType::Major) => true, Some(ChangeType::Minor) => original_version.major == 0, Some(ChangeType::Patch) => false, Some(ChangeType::Custom(label)) => { if label == "breaking" { true } else { panic!("unknown custom change type: {}", label) } } None => false, }) } fn bump_crate( &mut self, pkg_name: &str, change_type: Option<&ChangeType>, is_breaking: bool, ) -> Result<()> { eprintln!("Bumping crate: {}", pkg_name); let original_version = self .versions .get(pkg_name) .context(format!("failed to find original version for {}", pkg_name))?; let mut new_version = original_version.clone(); match change_type { Some(ChangeType::Patch) => { new_version.patch += 1; } Some(ChangeType::Minor) => { new_version.minor += 1; new_version.patch = 0; } Some(ChangeType::Major) => { new_version.major += 1; new_version.minor = 0; new_version.patch = 0; } Some(ChangeType::Custom(label)) => { if label == "breaking" { if original_version.major == 0 { new_version.minor += 1; new_version.patch = 0; } else { new_version.major += 1; new_version.minor = 0; new_version.patch = 0; } } else { panic!("unknown custom change type: {}", label) } } None => { if is_breaking { if original_version.major == 0 { new_version.minor += 1; new_version.patch = 0; } else { new_version.major += 1; new_version.minor = 0; new_version.patch = 0; } } else { new_version.patch += 1; } } }; match self.new_versions.entry(pkg_name.to_string()) { Entry::Vacant(v) => { v.insert(new_version); } Entry::Occupied(mut o) => { o.insert(new_version.max(o.get().clone())); } } if is_breaking { // Iterate over dependants let a = self.graph.node(pkg_name); for dep in self.graph.g.neighbors_directed(a, Direction::Incoming) { let dep_name = &*self.graph.ix[dep]; eprintln!("Bumping dependant crate: {}", dep_name); self.bump_crate(dep_name, None, true)?; } } Ok(()) } } fn update_changelog() -> Result<()> { // Run `yarn changelog` let mut cmd = Command::new("yarn"); cmd.arg("changelog"); eprintln!("Running {:?}", cmd); cmd.status().context("failed to run yarn changelog")?; Ok(()) } type VersionMap = HashMap<String, Version>; #[derive(Debug, Default)] struct InternedGraph { ix: IndexSet<String>, g: DiGraphMap<usize, ()>, } impl InternedGraph { fn add_node(&mut self, name: String) -> usize { self.ix.get_index_of(&name).unwrap_or_else(|| { let ix = self.ix.len(); self.ix.insert_full(name); ix }) as _ } fn node(&self, name: &str) -> usize { self.ix.get_index_of(name).unwrap_or_else(|| { panic!("unknown node: {}", name); }) } } fn get_data() -> Result<(VersionMap, InternedGraph)> { let md = cargo_metadata::MetadataCommand::new() .exec() .expect("failed to run cargo metadata"); let workspace_packages = md .workspace_packages() .into_iter() .filter(|p| p.publish != Some(vec![])) .map(|p| p.name.clone()) .collect::<Vec<_>>(); let mut graph = InternedGraph::default(); let mut versions = VersionMap::new(); for pkg in md.workspace_packages() { versions.insert(pkg.name.clone(), pkg.version.clone()); } for pkg in md.workspace_packages() { for dep in &pkg.dependencies { if dep.kind != DependencyKind::Normal { continue; } if workspace_packages.contains(&dep.name) { let from = graph.add_node(pkg.name.clone()); let to = graph.add_node(dep.name.clone()); if from == to { continue; } graph.g.add_edge(from, to, ()); } } } Ok((versions, graph)) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/bench.rs
Rust
use std::process::Command; use anyhow::Result; use clap::Args; use crate::util::{repository_root, run_cmd}; /// Run one or more benchmarks #[derive(Debug, Args)] pub(super) struct BenchCmd { #[clap(long, short = 'p')] package: String, /// Build benchmarks in debug mode. #[clap(long)] debug: bool, /// Template to use while instrumenting #[clap(short = 't')] template: Option<String>, #[clap(long)] no_lib: bool, #[clap(long)] benches: bool, #[clap(long)] bench: Option<String>, /// Instrument using https://github.com/dudykr/ddt #[clap(long)] instrument: bool, /// Instrument using https://github.com/mstange/samply #[clap(long)] samply: bool, #[clap(long)] features: Vec<String>, args: Vec<String>, } impl BenchCmd { pub fn run(self) -> Result<()> { let mut cmd = self.build_cmd()?; cmd.env("RUST_LOG", "off"); cmd.env("CARGO_PROFILE_RELEASE_DEBUG", "true"); cmd.env("CARGO_PROFILE_BENCH_DEBUG", "true"); run_cmd(&mut cmd) } fn build_cmd(&self) -> Result<Command> { let mut cmd = if self.samply { // ddt profile instruments cargo -t time let mut cmd = Command::new("ddt"); cmd.arg("profile").arg("samply").arg("cargo"); if !self.debug { cmd.arg("--release"); } cmd } else if self.instrument { // ddt profile instruments cargo -t time let mut cmd = Command::new("ddt"); cmd.arg("profile").arg("instruments").arg("cargo"); cmd.arg("-t") .arg(self.template.as_deref().unwrap_or("time")); if !self.debug { cmd.arg("--release"); } cmd } else { let mut cmd = Command::new("cargo"); cmd.arg("bench"); if self.debug { cmd.arg("--debug"); } cmd }; cmd.arg("--package").arg(&self.package); if self.benches { cmd.arg("--benches"); } if let Some(b) = &self.bench { cmd.arg("--bench").arg(b); } for f in self.features.iter() { cmd.arg("--features").arg(f); } if self.samply || self.instrument { cmd.arg("--").arg("--bench").args(&self.args); } else { cmd.arg("--").args(&self.args); } // TODO: This should use cargo metadata cmd.current_dir(repository_root()?.join("crates").join(&self.package)); Ok(cmd) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/clean.rs
Rust
use std::path::Path; use anyhow::Result; use clap::Args; use walkdir::WalkDir; use crate::util::{repository_root, run_cmd}; /// Clean cargo target directories #[derive(Debug, Args)] pub(super) struct CleanCmd {} impl CleanCmd { pub fn run(self) -> Result<()> { let root_dir = repository_root()?; run_cargo_clean(&root_dir.join("bindings"))?; for entry in WalkDir::new( root_dir .join("crates") .join("swc_plugin_runner") .join("tests"), ) { let entry = entry?; if entry.file_name().to_string_lossy() == "Cargo.tomm" { run_cargo_clean(entry.path().parent().unwrap())?; } } // This should be last due to `xtask` itself run_cargo_clean(&root_dir)?; Ok(()) } } fn run_cargo_clean(dir: &Path) -> Result<()> { run_cmd( std::process::Command::new("cargo") .arg("clean") .current_dir(dir), ) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/es/minifier.rs
Rust
use anyhow::Result; use clap::{Args, Subcommand}; #[derive(Debug, Args)] pub(super) struct MinifierCmd { #[clap(subcommand)] cmd: Cmd, } impl MinifierCmd { pub fn run(self) -> Result<()> { match self.cmd {} } } #[derive(Debug, Subcommand)] enum Cmd {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/es/mod.rs
Rust
use anyhow::Result; use clap::{Args, Subcommand}; use self::minifier::MinifierCmd; mod minifier; /// Commands for ECMAScript crates. #[derive(Debug, Args)] pub(super) struct EsCmd { #[clap(subcommand)] cmd: Cmd, } impl EsCmd { pub fn run(self) -> Result<()> { match self.cmd { Cmd::Minifier(cmd) => cmd.run(), } } } #[derive(Debug, Subcommand)] enum Cmd { Minifier(MinifierCmd), }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/git/mod.rs
Rust
use anyhow::Result; use clap::{Args, Subcommand}; use self::reduce::ReduceCmd; mod reduce; #[derive(Debug, Args)] pub(super) struct GitCmd { #[clap(subcommand)] cmd: Inner, } #[derive(Debug, Subcommand)] enum Inner { Reduce(ReduceCmd), } impl GitCmd { pub fn run(self) -> Result<()> { match self.cmd { Inner::Reduce(cmd) => cmd.run(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/git/reduce/core_ver.rs
Rust
use anyhow::Result; use clap::Args; use crate::util::get_commit_for_core_version; /// Reduce the difference of the versions of `swc_core`s to the list of commits /// and pull requests. #[derive(Debug, Args)] pub(super) struct CoreVerCmd { from: String, to: String, } impl CoreVerCmd { pub fn run(self) -> Result<()> { let from_commit = get_commit_for_core_version(&self.from, false)?; let to_commit = get_commit_for_core_version(&self.to, true)?; eprintln!( "GitHub diff: https://github.com/swc-project/swc/compare/{from_commit}...{to_commit}" ); Ok(()) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/git/reduce/mod.rs
Rust
use anyhow::Result; use clap::{Args, Subcommand}; use self::core_ver::CoreVerCmd; mod core_ver; #[derive(Debug, Args)] pub(super) struct ReduceCmd { #[clap(subcommand)] cmd: Inner, } #[derive(Debug, Subcommand)] enum Inner { CoreVer(CoreVerCmd), } impl ReduceCmd { pub fn run(self) -> Result<()> { match self.cmd { Inner::CoreVer(cmd) => cmd.run(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/main.rs
Rust
use anyhow::Result; use clap::{Parser, Subcommand}; use npm::NpmCmd; use crate::{bench::BenchCmd, clean::CleanCmd, es::EsCmd, git::GitCmd}; mod bench; mod clean; mod es; mod git; mod npm; mod util; #[derive(Debug, Parser)] struct CliArgs { #[clap(subcommand)] cmd: Cmd, } #[derive(Debug, Subcommand)] enum Cmd { Es(EsCmd), Bench(BenchCmd), Git(GitCmd), Npm(NpmCmd), Clean(CleanCmd), } fn main() -> Result<()> { let args = CliArgs::parse(); match args.cmd { Cmd::Es(c) => c.run(), Cmd::Bench(c) => c.run(), Cmd::Git(c) => c.run(), Cmd::Npm(c) => c.run(), Cmd::Clean(c) => c.run(), } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/npm/mod.rs
Rust
use anyhow::Result; use clap::{Args, Subcommand}; use self::nightly::NightlyCmd; mod nightly; mod util; #[derive(Debug, Args)] pub(super) struct NpmCmd { #[clap(subcommand)] cmd: Inner, } #[derive(Debug, Subcommand)] enum Inner { Nightly(NightlyCmd), } impl NpmCmd { pub fn run(self) -> Result<()> { match self.cmd { Inner::Nightly(c) => c.run(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/npm/nightly.rs
Rust
use std::process::{Command, Stdio}; use anyhow::{ensure, Context, Result}; use chrono::Utc; use clap::Args; use semver::{Prerelease, Version}; use crate::{ npm::util::{bump_swc_cli, set_version}, util::{repository_root, wrap}, }; #[derive(Debug, Args)] pub(super) struct NightlyCmd {} impl NightlyCmd { pub fn run(self) -> Result<()> { wrap(|| { let date = Utc::now().format("%Y%m%d").to_string(); let root_pkg_json = repository_root()?.join("./packages/core/package.json"); let content = serde_json::from_reader::<_, serde_json::Value>( std::fs::File::open(root_pkg_json) .context("failed to open ./packages/core/package.json")?, )?; let prev_version = Version::parse(content["version"].as_str().unwrap())?; let version = find_first_nightly(&prev_version, &date)?; println!("Publishing nightly version {}", version); set_version(&version).context("failed to set version")?; bump_swc_cli().context("failed to bump swc-cli")?; // ./scripts/publish.sh $version let status = Command::new("sh") .arg("./scripts/publish.sh") .arg(format!("{}", version)) .status() .context("failed to publish")?; ensure!(status.success(), "failed to publish"); Ok(()) }) .context("failed to publish nightly version") } } fn find_first_nightly(prev_version: &semver::Version, date: &str) -> Result<Version> { let mut ver = prev_version.clone(); if prev_version.pre.is_empty() { ver.patch += 1; } for i in 1.. { ver.pre = Prerelease::new(&format!("nightly-{}.{}", date, i))?; if ver <= *prev_version { continue; } let tag = format!("v{}", ver); let output = Command::new("git") .arg("tag") .arg("-l") .stderr(Stdio::inherit()) .output() .context("git tag -l failed") .map(|v| v.stdout) .and_then(|s| String::from_utf8(s).context("git tag -l returned non-utf8"))?; if !output.contains(&tag) { return Ok(ver); } } unreachable!("failed to find a free nightly version") }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/npm/util.rs
Rust
use std::process::{Command, Stdio}; use anyhow::{Context, Result}; use semver::Version; use crate::util::{repository_root, wrap}; pub fn set_version(version: &Version) -> Result<()> { wrap(|| { let mut c = Command::new("npm"); c.current_dir(repository_root()?).stderr(Stdio::inherit()); c.arg("version") .arg(version.to_string()) .arg("--no-git-tag-version") .arg("--allow-same-version"); c.status()?; Ok(()) }) .with_context(|| format!("failed to set version of @swc/core to v{}", version))?; wrap(|| { let mut c = Command::new("npm"); c.current_dir(repository_root()?.join("packages").join("minifier")) .stderr(Stdio::inherit()); c.arg("version") .arg(version.to_string()) .arg("--no-git-tag-version") .arg("--allow-same-version"); c.status()?; Ok(()) }) .with_context(|| format!("failed to set version of @swc/minifier to v{}", version))?; wrap(|| { let mut c = Command::new("cargo"); c.current_dir(repository_root()?.join("bindings")) .stderr(Stdio::inherit()); c.arg("set-version") .arg(version.to_string()) .arg("-p") .arg("binding_core_wasm") .arg("-p") .arg("binding_minifier_wasm"); c.status()?; Ok(()) }) .with_context(|| format!("failed to set version of Wasm packages to v{}", version))?; Ok(()) } pub fn bump_swc_cli() -> Result<()> { let mut c = Command::new("cargo"); c.current_dir(repository_root()?.join("bindings")) .stderr(Stdio::inherit()); c.arg("set-version") .arg("--bump") .arg("patch") .arg("-p") .arg("swc_cli"); c.status()?; Ok(()) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
xtask/src/util/mod.rs
Rust
use std::{ env, path::{Path, PathBuf}, process::{Command, Stdio}, }; use anyhow::{bail, Context, Result}; use serde_derive::Deserialize; pub fn wrap<F, Ret>(op: F) -> Result<Ret> where F: FnOnce() -> Result<Ret>, { op() } pub fn repository_root() -> Result<PathBuf> { let dir = env::var("CARGO_MANIFEST_DIR").context("failed to get manifest dir")?; Ok(Path::new(&*dir).parent().unwrap().to_path_buf()) } pub fn run_cmd(cmd: &mut Command) -> Result<()> { eprintln!("Running {:?}", *cmd); cmd.stdin(Stdio::inherit()); let status = cmd.status()?; if !status.success() { anyhow::bail!("Failed to run cargo command"); } Ok(()) } pub fn get_commit_for_core_version(version: &str, last: bool) -> Result<String> { wrap(|| { eprintln!("Getting commit for swc_core@v{}", version); // We need to get the list of commits and pull requests which changed the // version of swc_core. let git_rev_list = Command::new("git") .current_dir(repository_root()?) .arg("rev-list") .arg("--branches") .arg("main") .arg("--") .arg("Cargo.lock") .stderr(Stdio::inherit()) .output() .context("failed to spwan git rev-list")?; let git_rev_list = String::from_utf8(git_rev_list.stdout).context("git rev-list output is not utf8")?; let git_grep_output = Command::new("git") .current_dir(repository_root()?) .arg("grep") .arg(format!("version = \"{}\"", version)) .args(git_rev_list.lines()) .arg("--") .arg("Cargo.lock") .stderr(Stdio::piped()) // .stdin(Stdio::from(git_rev_list.stdout.unwrap())) .output() .context("failed to execute git grep")?; // git grep returns all commits with the version string with the format, so we // need to check if it's the version of swc_core let output = String::from_utf8(git_grep_output.stdout).context("git grep output is not utf8")?; let line_count = output.lines().count(); if line_count == 0 { bail!("swc_core@v{} is not found in the repository", version); } let iter: Box<dyn Iterator<Item = &str>> = if last { Box::new(output.lines().rev()) } else { Box::new(output.lines()) }; for line in iter { let commit = line.split(':').next().unwrap().to_string(); let commit_version = get_version_of_swc_core_of_commit(&commit)?; if Some(version) == commit_version.as_deref() { eprintln!("\tFound commit for swc_core@v{}: https://github.com/swc-project/swc/commits/{}", version, commit); return Ok(commit); } } bail!("swc_core@v{} is not found in the repository", version); }) .with_context(|| format!("failed to get the commit for swc_core@v{}", version)) } /// Read the version of swc_core from `Cargo.lock` pub fn get_version_of_swc_core_of_commit(commit: &str) -> Result<Option<String>> { wrap(|| { let output = Command::new("git") .current_dir(repository_root()?) .arg("show") .arg(format!("{}:Cargo.lock", commit)) .stderr(Stdio::inherit()) .output() .context("failed to spwan git show")?; let output_toml = String::from_utf8(output.stdout).context("git show output is not utf8")?; let content = toml::from_str::<CargoLockfile>(&output_toml).context("failed to parse Cargo.lock")?; for pkg in content.package { if pkg.name == "swc_core" { return Ok(Some(pkg.version)); } } Ok(None) }) .with_context(|| format!("failed to get the version of swc_core of {}", commit)) } #[derive(Debug, Deserialize)] struct CargoLockfile { package: Vec<LockfilePkg>, } #[derive(Debug, Deserialize)] struct LockfilePkg { name: String, version: String, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
src/bitset/bitvec.rs
Rust
//! A bit-set from the [`bitvec`] crate. use bitvec::{prelude::Lsb0, store::BitStore}; use crate::{ bitset::BitSet, pointer::{ArcFamily, RcFamily, RefFamily}, }; pub use ::bitvec::{self, vec::BitVec}; impl BitSet for BitVec { fn empty(size: usize) -> Self { bitvec::bitvec![usize, Lsb0; 0; size] } fn contains(&self, index: usize) -> bool { self[index] } fn insert(&mut self, index: usize) -> bool { let contained = self[index]; self.set(index, true); !contained } fn remove(&mut self, index: usize) -> bool { let contained = self[index]; self.set(index, false); contained } fn iter(&self) -> impl Iterator<Item = usize> { self.iter_ones() } fn len(&self) -> usize { self.count_ones() } fn union(&mut self, other: &Self) { *self |= other; } fn intersect(&mut self, other: &Self) { *self &= other; } fn invert(&mut self) { // Inline defn of Not::not bc it assumes ownership of the BitVec for elem in self.as_raw_mut_slice() { elem.store_value(!elem.load_value()); } } fn clear(&mut self) { for elem in self.as_raw_mut_slice() { elem.store_value(0); } } fn subtract(&mut self, other: &Self) { let mut other_copy = other.clone(); other_copy.invert(); self.intersect(&other_copy); } fn insert_all(&mut self) { self.fill(true); } fn copy_from(&mut self, other: &Self) { self.copy_from_bitslice(other); } } /// [`IndexSet`](crate::set::IndexSet) specialized to the [`BitVec`] implementation with the [`RcFamily`]. pub type RcIndexSet<T> = crate::set::IndexSet<'static, T, BitVec, RcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the [`BitVec`] implementation with the [`ArcFamily`]. pub type ArcIndexSet<T> = crate::set::IndexSet<'static, T, BitVec, ArcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the [`BitVec`] implementation with the [`RefFamily`]. pub type RefIndexSet<'a, T> = crate::set::IndexSet<'a, T, BitVec, RefFamily<'a>>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`BitVec`] implementation with the [`RcFamily`]. pub type RcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, BitVec, RcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`BitVec`] implementation with the [`ArcFamily`]. pub type ArcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, BitVec, ArcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`BitVec`] implementation with the [`RefFamily`]. pub type RefIndexMatrix<'a, R, C> = crate::matrix::IndexMatrix<'a, R, C, BitVec, RefFamily<'a>>; #[test] fn test_bitvec() { crate::test_utils::impl_test::<BitVec>(); }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/bitset/mod.rs
Rust
//! Abstraction over bit-set implementations. /// Interface for bit-set implementations. /// /// Implement this trait if you want to provide a custom bit-set /// beneath the indexical abstractions. pub trait BitSet: Clone + PartialEq { /// Constructs a new bit-set with a domain of size `size`. fn empty(size: usize) -> Self; /// Sets `index` to 1, returning true if `self` changed. fn insert(&mut self, index: usize) -> bool; /// Sets `index` to 0, returning true if `self` changed. fn remove(&mut self, index: usize) -> bool; /// Returns true if `index` is 1. fn contains(&self, index: usize) -> bool; /// Returns an iterator over all the indices of ones in the bit-set. fn iter(&self) -> impl Iterator<Item = usize>; /// Returns the number of ones in the bit-set. fn len(&self) -> usize; /// Returns true if there are no ones in the bit-set. fn is_empty(&self) -> bool { self.len() == 0 } // Note: we have the `_changed` methods separated out because // if you don't care about the return value, then it's just extra // computation w/ some APIs like bitvec. /// Adds all ones from `other` to `self`. fn union(&mut self, other: &Self); /// Adds all ones from `other` to `self`, returning true if `self` changed. fn union_changed(&mut self, other: &Self) -> bool { let n = self.len(); self.union(other); n != self.len() } /// Removes all ones in `self` not in `other`. fn intersect(&mut self, other: &Self); /// Removes all ones in `self` not in `other`, returning true if `self` changed. fn intersect_changed(&mut self, other: &Self) -> bool { let n = self.len(); self.intersect(other); n != self.len() } /// Removes all ones from `other` in `self`. fn subtract(&mut self, other: &Self); /// Removes all ones from `other` in `self`, returning true if `self` changed. fn subtract_changed(&mut self, other: &Self) -> bool { let n = self.len(); self.intersect(other); n != self.len() } /// Flips all bits in `self`. fn invert(&mut self); /// Sets all bits to 0. fn clear(&mut self); /// Adds every element of the domain to `self`. fn insert_all(&mut self); /// Returns true if all ones in `other` are a one in `self`. fn superset(&self, other: &Self) -> bool { let orig_len = self.len(); // TODO: can we avoid this clone? let mut self_copy = self.clone(); self_copy.union(other); orig_len == self_copy.len() } /// Copies `other` into `self`. Must have the same lengths. fn copy_from(&mut self, other: &Self); } #[cfg(feature = "bitvec")] pub mod bitvec; #[cfg(feature = "rustc")] pub mod rustc; #[cfg(feature = "simd")] pub mod simd; #[cfg(feature = "roaring")] pub mod roaring;
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/bitset/roaring.rs
Rust
#![allow(clippy::cast_possible_truncation)] //! A bit-set based on [`RoaringBitmap`]. //! //! If you want roaring's SIMD support, add `roaring-simd` to //! your indexical feature list. pub use roaring::{self, RoaringBitmap}; use crate::{ bitset::BitSet, pointer::{ArcFamily, RcFamily, RefFamily}, }; /// Wrapper around a [`RoaringBitmap`] that includes the domain size. #[derive(PartialEq, Clone)] pub struct RoaringSet { set: RoaringBitmap, size: usize, } fn to_usize(i: u32) -> usize { i as usize } impl BitSet for RoaringSet { fn empty(size: usize) -> Self { RoaringSet { set: RoaringBitmap::new(), size, } } fn insert(&mut self, index: usize) -> bool { self.set.insert(index as u32) } fn remove(&mut self, index: usize) -> bool { self.set.remove(index as u32) } fn contains(&self, index: usize) -> bool { self.set.contains(index as u32) } fn iter(&self) -> impl Iterator<Item = usize> { self.set.iter().map(to_usize) } fn len(&self) -> usize { self.set.len() as usize } fn union(&mut self, other: &Self) { self.set |= &other.set; } fn intersect(&mut self, other: &Self) { self.set &= &other.set; } fn subtract(&mut self, other: &Self) { self.set -= &other.set; } fn invert(&mut self) { for i in 0..self.size { if self.set.contains(i as u32) { self.set.remove(i as u32); } else { self.set.insert(i as u32); } } } fn clear(&mut self) { self.set.clear(); } fn insert_all(&mut self) { self.set.insert_range(0..(self.size as u32)); } fn copy_from(&mut self, other: &Self) { self.set.clone_from(&other.set); } } /// [`IndexSet`](crate::set::IndexSet) specialized to the [`RoaringSet`] implementation with the [`RcFamily`]. pub type RcIndexSet<T> = crate::set::IndexSet<'static, T, RoaringSet, RcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the [`RoaringSet`] implementation with the [`ArcFamily`]. pub type ArcIndexSet<T> = crate::set::IndexSet<'static, T, RoaringSet, ArcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the [`RoaringSet`] implementation with the [`RefFamily`]. pub type RefIndexSet<'a, T> = crate::set::IndexSet<'a, T, RoaringSet, RefFamily<'a>>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`RoaringSet`] implementation with the [`RcFamily`]. pub type RcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, RoaringSet, RcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`RoaringSet`] implementation with the [`ArcFamily`]. pub type ArcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, RoaringSet, ArcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`RoaringSet`] implementation with the [`RefFamily`]. pub type RefIndexMatrix<'a, R, C> = crate::matrix::IndexMatrix<'a, R, C, RoaringSet, RefFamily<'a>>; #[test] fn test_roaring() { crate::test_utils::impl_test::<RoaringSet>(); }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/bitset/rustc.rs
Rust
//! The Rust compiler's [`BitSet`](https://doc.rust-lang.org/beta/nightly-rustc/rustc_index/bit_set/struct.BitSet.html). extern crate rustc_driver; pub extern crate rustc_index; extern crate rustc_mir_dataflow; use crate::{ IndexedValue, bitset::BitSet, pointer::{ArcFamily, PointerFamily, RcFamily, RefFamily}, }; use rustc_mir_dataflow::JoinSemiLattice; use std::hash::Hash; pub use rustc_index::bit_set::{ChunkedBitSet, DenseBitSet, MixedBitIter, MixedBitSet}; /// A bitset specialized to `usize` indices. pub type RustcBitSet = MixedBitSet<usize>; impl BitSet for RustcBitSet { fn empty(size: usize) -> Self { RustcBitSet::new_empty(size) } fn contains(&self, index: usize) -> bool { self.contains(index) } fn insert(&mut self, index: usize) -> bool { self.insert(index) } fn remove(&mut self, index: usize) -> bool { self.remove(index) } fn iter(&self) -> impl Iterator<Item = usize> { self.iter() } fn intersect(&mut self, other: &Self) { self.intersect_changed(other); } fn intersect_changed(&mut self, other: &Self) -> bool { // TODO: this code should be removed once the corresponding implementation // has been added to rustc match (self, other) { (MixedBitSet::Large(self_large), MixedBitSet::Large(other_large)) => { ChunkedBitSet::intersect(self_large, other_large) } (MixedBitSet::Small(self_small), MixedBitSet::Small(other_small)) => { DenseBitSet::intersect(self_small, other_small) } _ => panic!("Mismatched domains"), } } fn len(&self) -> usize { self.iter().count() } fn union(&mut self, other: &Self) { self.union_changed(other); } fn union_changed(&mut self, other: &Self) -> bool { self.union(other) } fn subtract(&mut self, other: &Self) { self.subtract_changed(other); } fn subtract_changed(&mut self, other: &Self) -> bool { self.subtract(other) } fn clear(&mut self) { self.clear(); } fn invert(&mut self) { let mut inverted = RustcBitSet::new_empty(self.domain_size()); inverted.insert_all(); inverted.subtract(self); *self = inverted; } fn insert_all(&mut self) { self.insert_all(); } fn copy_from(&mut self, other: &Self) { self.clone_from(other); } } /// [`IndexSet`](crate::set::IndexSet) specialized to the `bit_set::BitSet` implementation with the [`RcFamily`]. pub type RcIndexSet<T> = crate::set::IndexSet<'static, T, RustcBitSet, RcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the `bit_set::BitSet` implementation with the [`ArcFamily`]. pub type ArcIndexSet<T> = crate::set::IndexSet<'static, T, RustcBitSet, ArcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the `bit_set::BitSet` implementation with the [`RefFamily`]. pub type RefIndexSet<'a, T> = crate::set::IndexSet<'a, T, RustcBitSet, RefFamily<'a>>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the `bit_set::BitSet` implementation with the [`RcFamily`]. pub type RcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, RustcBitSet, RcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the `bit_set::BitSet` implementation with the [`ArcFamily`]. pub type ArcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, RustcBitSet, ArcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the `bit_set::BitSet` implementation with the [`RefFamily`]. pub type RefIndexMatrix<'a, R, C> = crate::matrix::IndexMatrix<'a, R, C, RustcBitSet, RefFamily<'a>>; impl<'a, T, S, P> JoinSemiLattice for crate::set::IndexSet<'a, T, S, P> where T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { fn join(&mut self, other: &Self) -> bool { self.union_changed(other) } } impl<'a, R, C, S, P> JoinSemiLattice for crate::matrix::IndexMatrix<'a, R, C, S, P> where R: PartialEq + Eq + Hash + Clone, C: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { fn join(&mut self, other: &Self) -> bool { let mut changed = false; for (row, col) in &other.matrix { changed |= self.ensure_row(row.clone()).union_changed(col); } changed } } #[test] fn test_rustc_bitset() { crate::test_utils::impl_test::<RustcBitSet>(); }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/bitset/simd.rs
Rust
#![allow(clippy::cast_possible_truncation)] //! A custom SIMD-accelerated bit-set. //! //! Implementation is largely derived from the `bitsvec` crate: <https://github.com/psiace/bitsvec> //! //! The main difference is I made a much more efficient iterator that computes the indices //! of the 1-bits. //! //! **WARNING:** this module makes liberal use of unsafe code and has not been thoroughly vetted, //! so use it at your own risk. use crate::{ bitset::BitSet, pointer::{ArcFamily, RcFamily, RefFamily}, }; use std::{ mem::size_of, ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXorAssign, Not}, simd::{LaneCount, Simd, SimdElement, SupportedLaneCount}, slice, }; /// Capabilities of an element that represent a SIMD lane pub trait SimdSetElement: SimdElement + BitOr<Output = Self> + BitAnd<Output = Self> + Not<Output = Self> + BitOrAssign + BitXorAssign + BitAndAssign + PartialEq + 'static { /// The `0` value. const ZERO: Self; /// The `1` value. const ONE: Self; /// The largest value. const MAX: Self; /// Efficient bit-shift-left. /// /// # Safety /// `rhs < size_of::<Self>()` #[must_use] unsafe fn unchecked_shl(self, rhs: u32) -> Self; /// Efficient bit-shift-right. /// /// # Safety /// `rhs < size_of::<Self>()` #[must_use] unsafe fn unchecked_shr(self, rhs: u32) -> Self; /// The number of zeros before the first 1 bit, counting from LSB. fn trailing_zeros(self) -> u32; /// The number of 1 bits in the element. fn count_ones(self) -> u32; } macro_rules! simd_set_element_impl { ($n:ty) => { impl SimdSetElement for $n { const ZERO: Self = 0; const ONE: Self = 1; const MAX: Self = Self::MAX; unsafe fn unchecked_shl(self, rhs: u32) -> Self { unsafe { <$n>::unchecked_shl(self, rhs) } } unsafe fn unchecked_shr(self, rhs: u32) -> Self { unsafe { <$n>::unchecked_shr(self, rhs) } } fn trailing_zeros(self) -> u32 { <$n>::trailing_zeros(self) } fn count_ones(self) -> u32 { <$n>::count_ones(self) } } }; } simd_set_element_impl!(u8); simd_set_element_impl!(u16); simd_set_element_impl!(u32); simd_set_element_impl!(u64); /// A dense bit-set with SIMD-accelerated operations. #[derive(PartialEq, Clone)] pub struct SimdBitset<T, const N: usize> where T: SimdSetElement, LaneCount<N>: SupportedLaneCount, { chunks: Vec<Simd<T, N>>, nbits: usize, } impl<T: SimdSetElement, const N: usize> SimdBitset<T, N> where LaneCount<N>: SupportedLaneCount, { const fn chunk_size() -> usize { Self::lane_size() * N } const fn lane_size() -> usize { size_of::<T>() * 8 } const fn coords(index: usize) -> (usize, usize, u32) { let (chunk, index) = (index / Self::chunk_size(), index % Self::chunk_size()); let (lane, index) = (index / Self::lane_size(), index % Self::lane_size()); (chunk, lane, index as u32) } fn get(&self, chunk_idx: usize, lane_idx: usize, bit: u32) -> bool { debug_assert!(chunk_idx < self.chunks.len()); debug_assert!(lane_idx < N); debug_assert!(bit < Self::lane_size() as u32); unsafe { let chunk = self.chunks.get_unchecked(chunk_idx); let lane = chunk.as_array().get_unchecked(lane_idx); lane.unchecked_shr(bit) & T::ONE == T::ONE } } fn zip_mut(&mut self, other: &Self, mut op: impl FnMut(&mut Simd<T, N>, &Simd<T, N>)) { debug_assert!(other.chunks.len() == self.chunks.len()); let mut dst = self.chunks.as_mut_ptr(); let mut src = other.chunks.as_ptr(); unsafe { let dst_end = dst.add(self.chunks.len()); while dst != dst_end { op(&mut *dst, &*src); dst = dst.add(1); src = src.add(1); } } } } /// Iterator over the 1-bits of a [`SimdBitset`]. pub struct SimdSetIter<'a, T, const N: usize> where T: SimdSetElement, LaneCount<N>: SupportedLaneCount, { set: &'a SimdBitset<T, N>, index: usize, chunk_iter: slice::Iter<'a, Simd<T, N>>, lane_iter: slice::Iter<'a, T>, lane: T, } impl<'a, T, const N: usize> SimdSetIter<'a, T, N> where T: SimdSetElement, LaneCount<N>: SupportedLaneCount, { fn new(set: &'a SimdBitset<T, N>) -> Self { let mut chunk_iter = set.chunks.iter(); let chunk = chunk_iter.next().unwrap(); let mut lane_iter = chunk.as_array().iter(); let lane = *lane_iter.next().unwrap(); SimdSetIter { set, index: 0, chunk_iter, lane_iter, lane, } } } impl<T, const N: usize> Iterator for SimdSetIter<'_, T, N> where T: SimdSetElement, LaneCount<N>: SupportedLaneCount, { type Item = usize; fn next(&mut self) -> Option<Self::Item> { if self.index >= self.set.nbits { return None; } let lane_size = SimdBitset::<T, N>::lane_size() as u32; while self.lane == T::ZERO { self.index += lane_size as usize; let zero_simd = Simd::splat(T::ZERO); let chunk_size = lane_size as usize * N; match self.lane_iter.next() { Some(lane) => { self.lane = *lane; } None => loop { match self.chunk_iter.next() { Some(chunk) => { if *chunk == zero_simd { self.index += chunk_size; continue; } self.lane_iter = chunk.as_array().iter(); self.lane = *self.lane_iter.next().unwrap(); break; } None => return None, } }, } } let zeros = self.lane.trailing_zeros(); let idx = self.index + zeros as usize; self.lane ^= unsafe { T::ONE.unchecked_shl(zeros) }; if idx >= self.set.nbits { self.index = self.set.nbits; return None; } Some(idx) } } impl<T: SimdSetElement, const N: usize> BitSet for SimdBitset<T, N> where LaneCount<N>: SupportedLaneCount, Simd<T, N>: for<'a> BitOr<&'a Simd<T, N>, Output = Simd<T, N>>, Simd<T, N>: for<'a> BitAnd<&'a Simd<T, N>, Output = Simd<T, N>>, { fn empty(nbits: usize) -> Self { let n_chunks = nbits.div_ceil(Self::chunk_size()); SimdBitset { chunks: vec![Simd::from([T::ZERO; N]); n_chunks], nbits, } } fn insert(&mut self, index: usize) -> bool { let (chunk_idx, lane_idx, bit) = Self::coords(index); debug_assert!(chunk_idx < self.chunks.len()); debug_assert!(lane_idx < N); debug_assert!(bit < Self::lane_size() as u32); unsafe { let chunk = self.chunks.get_unchecked_mut(chunk_idx); let lane = chunk.as_mut_array().get_unchecked_mut(lane_idx); *lane |= T::ONE.unchecked_shl(bit); } true } fn remove(&mut self, index: usize) -> bool { let (chunk_idx, lane_idx, bit) = Self::coords(index); debug_assert!(chunk_idx < self.chunks.len()); debug_assert!(lane_idx < N); debug_assert!(bit < Self::lane_size() as u32); unsafe { let chunk = self.chunks.get_unchecked_mut(chunk_idx); let lane = chunk.as_mut_array().get_unchecked_mut(lane_idx); *lane &= T::ZERO.unchecked_shl(bit); } true } fn contains(&self, index: usize) -> bool { let (chunk_idx, lane_idx, bit) = Self::coords(index); self.get(chunk_idx, lane_idx, bit) } fn iter(&self) -> impl Iterator<Item = usize> { SimdSetIter::new(self) } fn len(&self) -> usize { let mut n = 0; for chunk in &self.chunks { for lane in chunk.as_array() { n += lane.count_ones(); } } n as usize } fn union(&mut self, other: &Self) { self.zip_mut(other, |dst, src| *dst |= src); } fn intersect(&mut self, other: &Self) { self.zip_mut(other, |dst, src| *dst &= src); } fn subtract(&mut self, other: &Self) { let mut other = other.clone(); other.invert(); self.intersect(&other); } fn invert(&mut self) { for chunk in &mut self.chunks { for lane in chunk.as_mut_array() { *lane = !*lane; } } } fn clear(&mut self) { for chunk in &mut self.chunks { for lane in chunk.as_mut_array() { *lane = T::ZERO; } } } fn insert_all(&mut self) { for chunk in &mut self.chunks { for lane in chunk.as_mut_array() { *lane = T::MAX; } } } fn copy_from(&mut self, other: &Self) { self.zip_mut(other, |dst, src| *dst = *src); } } /// [`IndexSet`](crate::set::IndexSet) specialized to the [`SimdBitset`] implementation with the [`RcFamily`]. pub type RcIndexSet<T> = crate::set::IndexSet<'static, T, SimdBitset<u64, 4>, RcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the [`SimdBitset`] implementation with the [`ArcFamily`]. pub type ArcIndexSet<T> = crate::set::IndexSet<'static, T, SimdBitset<u64, 4>, ArcFamily>; /// [`IndexSet`](crate::set::IndexSet) specialized to the [`SimdBitset`] implementation with the [`RefFamily`]. pub type RefIndexSet<'a, T> = crate::set::IndexSet<'a, T, SimdBitset<u64, 4>, RefFamily<'a>>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`SimdBitset`] implementation with the [`RcFamily`]. pub type RcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, SimdBitset<u64, 4>, RcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`SimdBitset`] implementation with the [`ArcFamily`]. pub type ArcIndexMatrix<R, C> = crate::matrix::IndexMatrix<'static, R, C, SimdBitset<u64, 4>, ArcFamily>; /// [`IndexMatrix`](crate::matrix::IndexMatrix) specialized to the [`SimdBitset`] implementation with the [`RefFamily`]. pub type RefIndexMatrix<'a, R, C> = crate::matrix::IndexMatrix<'a, R, C, SimdBitset<u64, 4>, RefFamily<'a>>; #[test] fn test_simd_bitset() { const N: usize = 64 * 7 + 63; let mut bitset = SimdBitset::<u64, 4>::empty(N); for i in 0..N { bitset.clear(); for j in 0..i { bitset.insert(j); } assert_eq!( bitset.iter().collect::<Vec<_>>(), (0..i).collect::<Vec<_>>() ); assert_eq!(bitset.len(), i); } crate::test_utils::impl_test::<SimdBitset<u64, 4>>(); }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/domain.rs
Rust
use index_vec::{Idx, IndexVec}; use rustc_hash::FxHashMap; use std::fmt; use crate::IndexedValue; /// An indexed collection of objects. /// /// Contains a reverse-mapping from `T` to `T::Index` for efficient lookups of indices. #[derive(Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct IndexedDomain<T: IndexedValue> { domain: IndexVec<T::Index, T>, #[cfg_attr(feature = "serde", serde(skip))] reverse_map: FxHashMap<T, T::Index>, } #[cfg(feature = "serde")] impl<'de, T: IndexedValue + serde::Deserialize<'de>> serde::Deserialize<'de> for IndexedDomain<T> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { #[derive(serde::Deserialize)] struct IndexedDomain2<T: IndexedValue> { domain: IndexVec<T::Index, T>, } let domain = IndexedDomain2::<T>::deserialize(deserializer)?; let reverse_map = domain .domain .iter_enumerated() .map(|(idx, value)| (value.clone(), idx)) .collect(); Ok(IndexedDomain { domain: domain.domain, reverse_map, }) } } impl<T: IndexedValue> IndexedDomain<T> { /// Creates an empty domain, #[must_use] pub fn new() -> Self { IndexedDomain { domain: IndexVec::new(), reverse_map: FxHashMap::default(), } } /// Gets the object corresponding to `index`. /// /// Panics if `index` is not within the domain. pub fn value(&self, index: T::Index) -> &T { &self.domain[index] } /// Gets the index corresponding to `value`. /// /// Panics if `value` is not within the domain. pub fn index(&self, value: &T) -> T::Index { self.reverse_map[value] } /// Returns true if `value` is contained in the domain. pub fn contains_value(&self, value: &T) -> bool { self.reverse_map.contains_key(value) } /// Returns true if `index` is contained in the domain. pub fn contains_index(&self, index: T::Index) -> bool { index.index() < self.domain.len() } /// Adds `value` to the domain, returning its new index. pub fn insert(&mut self, value: T) -> T::Index { let idx = self.domain.push(value.clone()); self.reverse_map.insert(value, idx); idx } /// Returns immutable access to the underlying indexed vector. #[must_use] pub fn as_vec(&self) -> &IndexVec<T::Index, T> { &self.domain } /// Returns the number of elements in the domain. #[must_use] pub fn len(&self) -> usize { self.domain.len() } /// Returns true if the domain is empty. #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Similar to [`IndexedDomain::index`], except it adds `value` /// to the domain if it does not exist yet. pub fn ensure(&mut self, value: &T) -> T::Index { if self.contains_value(value) { self.index(value) } else { self.insert(value.clone()) } } /// Returns an iterator over all elements of the domain. #[must_use] pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + ExactSizeIterator<Item = &T> { self.domain.iter() } /// Returns an iterator over all indices of the domain. pub fn indices( &self, ) -> impl DoubleEndedIterator<Item = T::Index> + ExactSizeIterator<Item = T::Index> { // Re-implementing `indices` because profiling suggests that // the IndexVec impl is not getting inlined for some reason?? (0..self.domain.len()).map(T::Index::from_usize) } /// Returns an iterator over all pairs of indices and elements of the domain. #[must_use] pub fn iter_enumerated( &self, ) -> impl DoubleEndedIterator<Item = (T::Index, &T)> + ExactSizeIterator<Item = (T::Index, &T)> { self.domain.iter_enumerated() } } impl<T: IndexedValue> Default for IndexedDomain<T> { fn default() -> Self { IndexedDomain::new() } } impl<T: IndexedValue> From<IndexVec<T::Index, T>> for IndexedDomain<T> { /// Creates a new domain from an indexed vector. /// /// Consider using the [`FromIterator`] implementation if you don't want to manually construct /// an [`IndexVec`] object. fn from(domain: IndexVec<T::Index, T>) -> Self { let reverse_map = domain .iter_enumerated() .map(|(idx, value)| (value.clone(), idx)) .collect(); IndexedDomain { domain, reverse_map, } } } impl<T: IndexedValue> FromIterator<T> for IndexedDomain<T> { fn from_iter<Iter: IntoIterator<Item = T>>(iter: Iter) -> Self { let domain = iter.into_iter().collect::<IndexVec<T::Index, T>>(); IndexedDomain::from(domain) } } impl<T: IndexedValue + fmt::Debug> fmt::Debug for IndexedDomain<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.domain.fmt(f) } } #[test] fn test_domain() { fn mk(s: &str) -> String { s.to_string() } let d = IndexedDomain::from_iter([mk("a"), mk("b")]); let a = d.index(&mk("a")); let b = d.index(&mk("b")); assert_eq!(d.value(a), "a"); assert_eq!(d.value(b), "b"); assert!(d.contains_value(&mk("a"))); assert!(!d.contains_value(&mk("c"))); assert_eq!(d.len(), 2); assert_eq!(d.iter().collect::<Vec<_>>(), vec!["a", "b"]); }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/lib.rs
Rust
#![doc = include_str!("../README.md")] //! ## Design //! The key idea is that the [`IndexedDomain`] is shared pervasively //! across all Indexical types. All types can then use the [`IndexedDomain`] to convert between indexes and objects, usually via the [`ToIndex`] trait. //! //! [`IndexSet`](set::IndexSet) and [`IndexMatrix`](matrix::IndexMatrix) are generic with respect to two things: //! 1. **The choice of bit-set implementation.** By default, Indexical includes the [`bitvec`] crate and re-exports the [`bitset::bitvec`] module from root. //! You can provide your own bit-set implementation via the [`bitset::BitSet`] trait. //! 2. **The choice of domain pointer.** By default, Indexical uses the [`Rc`](std::rc::Rc) pointer via the [`RcFamily`](pointer::RcFamily) type. //! You can choose to use the [`ArcFamily`](pointer::ArcFamily) if you need concurrency, or the [`RefFamily`](pointer::RefFamily) if you want to avoid reference-counting. #![cfg_attr(feature = "rustc", feature(rustc_private))] #![cfg_attr(feature = "simd", feature(portable_simd, unchecked_shifts))] #![warn(missing_docs, clippy::pedantic)] use self::pointer::PointerFamily; use index_vec::Idx; use std::hash::Hash; pub mod bitset; mod domain; pub mod map; pub mod matrix; pub mod pointer; pub mod set; #[cfg(test)] mod test_utils; pub mod vec; #[doc(hidden)] pub use index_vec as _index_vec; #[cfg(all( feature = "bitvec", not(any(feature = "rustc", feature = "simd", feature = "roaring")) ))] pub use bitset::bitvec::{ ArcIndexMatrix, ArcIndexSet, RcIndexMatrix, RcIndexSet, RefIndexMatrix, RefIndexSet, }; #[cfg(all( feature = "roaring", not(any(feature = "rustc", feature = "simd", feature = "bitvec")) ))] pub use bitset::roaring::{ ArcIndexMatrix, ArcIndexSet, RcIndexMatrix, RcIndexSet, RefIndexMatrix, RefIndexSet, }; #[cfg(all( feature = "rustc", not(any(feature = "bitvec", feature = "simd", feature = "roaring")) ))] pub use bitset::rustc::{ ArcIndexMatrix, ArcIndexSet, RcIndexMatrix, RcIndexSet, RefIndexMatrix, RefIndexSet, }; #[cfg(all( feature = "simd", not(any(feature = "bitvec", feature = "rustc", feature = "roaring")) ))] pub use bitset::simd::{ ArcIndexMatrix, ArcIndexSet, RcIndexMatrix, RcIndexSet, RefIndexMatrix, RefIndexSet, }; pub use domain::IndexedDomain; pub use vec::{ArcIndexVec, RcIndexVec, RefIndexVec}; /// Coherence hack for the `ToIndex` trait. pub struct MarkerOwned; /// Coherence hack for the `ToIndex` trait. pub struct MarkerRef; /// Coherence hack for the `ToIndex` trait. pub struct MarkerIndex; /// Implicit conversions from elements to indexes. /// Commonly used in the [`IndexSet`](set::IndexSet) and [`IndexMatrix`](matrix::IndexMatrix) interfaces. /// /// Note that we cannot use the [`Into`] trait because this conversion requires /// the [`IndexedDomain`] as input. /// /// The `M` type parameter is a coherence hack to ensure the blanket implementations /// do not conflict. pub trait ToIndex<T: IndexedValue, M> { /// Converts `self` to an index over `T`. fn to_index(self, domain: &IndexedDomain<T>) -> T::Index; } impl<T: IndexedValue> ToIndex<T, MarkerOwned> for T { fn to_index(self, domain: &IndexedDomain<T>) -> T::Index { domain.index(&self) } } impl<T: IndexedValue> ToIndex<T, MarkerRef> for &T { fn to_index(self, domain: &IndexedDomain<T>) -> T::Index { domain.index(self) } } impl<T: IndexedValue> ToIndex<T, MarkerIndex> for T::Index { fn to_index(self, _domain: &IndexedDomain<T>) -> T::Index { self } } /// Links a type to its index. /// /// Should be automatically implemented by the [`define_index_type`] macro. pub trait IndexedValue: Clone + PartialEq + Eq + Hash { /// The index for `Self`. type Index: Idx; } /// Creates a new index type and associates it with an object type. /// /// This is a thin wrapper around [`index_vec::define_index_type`]. The only /// modification is the `for $TYPE` syntax that generates the [`IndexedValue`] /// implementation. #[macro_export] macro_rules! define_index_type { ( $(#[$attrs:meta])* $v:vis struct $type:ident for $target:ident $(<$($l:lifetime),*>)? = $raw:ident; $($CONFIG_NAME:ident = $value:expr;)* $(;)? ) => { $crate::_index_vec::define_index_type! { $(#[$attrs])* $v struct $type = $raw; $($CONFIG_NAME = $value;)* } impl $(<$($l),*>)? $crate::IndexedValue for $target $(<$($l),*>)? { type Index = $type; } } } /// Generic interface for converting iterators into indexical collections. pub trait FromIndexicalIterator<'a, T: IndexedValue + 'a, P: PointerFamily<'a>, M, A>: Sized { /// Converts an iterator into a collection within the given domain. fn from_indexical_iter( iter: impl Iterator<Item = A>, domain: &P::Pointer<IndexedDomain<T>>, ) -> Self; } /// Extension trait that adds `collect_indexical` to all iterators. pub trait IndexicalIteratorExt<'a, T: IndexedValue + 'a, P: PointerFamily<'a>, M>: Iterator + Sized { /// Like [`Iterator::collect`], except also takes as input a `domain`. fn collect_indexical<B>(self, domain: &P::Pointer<IndexedDomain<T>>) -> B where B: FromIndexicalIterator<'a, T, P, M, Self::Item>, { FromIndexicalIterator::from_indexical_iter(self, domain) } } impl<'a, I: Iterator, T: IndexedValue + 'a, P: PointerFamily<'a>, M> IndexicalIteratorExt<'a, T, P, M> for I { }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/map.rs
Rust
//! Map-like collections for indexed keys. use std::{ collections::hash_map, ops::{Index, IndexMut}, }; use rustc_hash::FxHashMap; use crate::{ FromIndexicalIterator, IndexedDomain, IndexedValue, ToIndex, pointer::{ArcFamily, PointerFamily, RcFamily, RefFamily}, vec::IndexVec, }; /// A mapping from indexed keys to values, implemented sparsely with a hash map. /// /// This is more memory-efficient than the [`DenseIndexMap`] with a small /// number of keys. pub struct SparseIndexMap<'a, K: IndexedValue + 'a, V, P: PointerFamily<'a>> { map: FxHashMap<K::Index, V>, domain: P::Pointer<IndexedDomain<K>>, } /// [`SparseIndexMap`] specialized to the [`RcFamily`]. pub type SparseRcIndexMap<K, V> = SparseIndexMap<'static, K, V, RcFamily>; /// [`SparseIndexMap`] specialized to the [`ArcFamily`]. pub type SparseArcIndexMap<K, V> = SparseIndexMap<'static, K, V, ArcFamily>; /// [`SparseIndexMap`] specialized to the [`RefFamily`]. pub type SparseRefIndexMap<'a, K, V> = SparseIndexMap<'a, K, V, RefFamily<'a>>; impl<'a, K, V, P> SparseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, { /// Constructs an empty map within the given domain. pub fn new(domain: &P::Pointer<IndexedDomain<K>>) -> Self { SparseIndexMap { map: FxHashMap::default(), domain: domain.clone(), } } /// Returns an immutable reference to a value for a given key if it exists. pub fn get<M>(&self, key: impl ToIndex<K, M>) -> Option<&V> { let idx = key.to_index(&self.domain); self.map.get(&idx) } /// Returns a mutable reference to a value for a given key if it exists. pub fn get_mut<M>(&mut self, key: impl ToIndex<K, M>) -> Option<&mut V> { let idx = key.to_index(&self.domain); self.map.get_mut(&idx) } /// Returns a reference to a value for a given key. /// /// # Safety /// This function has undefined behavior if `key` is not in `self`. pub unsafe fn get_unchecked<M>(&self, key: impl ToIndex<K, M>) -> &V { let idx = key.to_index(&self.domain); unsafe { self.map.get(&idx).unwrap_unchecked() } } /// Returns a mutable reference to a value for a given key. /// /// # Safety /// This function has undefined behavior if `key` is not in `self`. pub unsafe fn get_unchecked_mut<M>(&mut self, key: impl ToIndex<K, M>) -> &mut V { let idx = key.to_index(&self.domain); unsafe { self.map.get_mut(&idx).unwrap_unchecked() } } /// Inserts the key/value pair into `self`. pub fn insert<M>(&mut self, key: impl ToIndex<K, M>, value: V) { let idx = key.to_index(&self.domain); self.map.insert(idx, value); } /// Returns an iterator over the values of the map. pub fn values(&self) -> impl ExactSizeIterator<Item = &V> { self.map.values() } /// Returns a mutable entry into the map for the given key. pub fn entry<M>(&mut self, key: impl ToIndex<K, M>) -> hash_map::Entry<'_, K::Index, V> { let idx = key.to_index(&self.domain); self.map.entry(idx) } /// Returns the number of entries in the map. pub fn len(&self) -> usize { self.map.len() } /// Returns true if the map has no elements. pub fn is_empty(&self) -> bool { self.map.is_empty() } /// Returns an iterator over pairs of keys and values in the map. pub fn iter(&self) -> hash_map::Iter<'_, K::Index, V> { self.map.iter() } } impl<'a, K, V, P> PartialEq for SparseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, V: PartialEq, { fn eq(&self, other: &Self) -> bool { self.map == other.map } } impl<'a, K, V, P> Eq for SparseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, V: Eq, { } impl<'a, K, V, P> Index<K::Index> for SparseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, { type Output = V; fn index(&self, index: K::Index) -> &Self::Output { self.get(index).unwrap() } } impl<'a, K, V, P> IndexMut<K::Index> for SparseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, { fn index_mut(&mut self, index: K::Index) -> &mut Self::Output { self.get_mut(index).unwrap() } } impl<'a, K, V, P, M, U> FromIndexicalIterator<'a, K, P, M, (U, V)> for SparseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, U: ToIndex<K, M>, { fn from_indexical_iter( iter: impl Iterator<Item = (U, V)>, domain: &P::Pointer<IndexedDomain<K>>, ) -> Self { let map = iter .map(|(u, v)| (u.to_index(domain), v)) .collect::<FxHashMap<_, _>>(); SparseIndexMap { map, domain: domain.clone(), } } } impl<'a, 'b, K, V, P> IntoIterator for &'b SparseIndexMap<'a, K, V, P> where K: IndexedValue + 'a + 'b, V: 'b, P: PointerFamily<'a>, { type Item = (&'b K::Index, &'b V); type IntoIter = hash_map::Iter<'b, K::Index, V>; fn into_iter(self) -> Self::IntoIter { self.iter() } } /// A mapping from indexed keys to values, implemented densely with a vector. /// /// This is more time-efficient than the [`SparseIndexMap`] for lookup, /// but it consumes more memory for missing elements. pub struct DenseIndexMap<'a, K: IndexedValue + 'a, V, P: PointerFamily<'a>>( IndexVec<'a, K, Option<V>, P>, ); /// [`DenseIndexMap`] specialized to the [`RcFamily`]. pub type DenseRcIndexMap<K, V> = DenseIndexMap<'static, K, V, RcFamily>; /// [`DenseIndexMap`] specialized to the [`ArcFamily`]. pub type DenseArcIndexMap<K, V> = DenseIndexMap<'static, K, V, ArcFamily>; /// [`DenseIndexMap`] specialized to the [`RefFamily`]. pub type DenseRefIndexMap<'a, K, V> = DenseIndexMap<'a, K, V, RefFamily<'a>>; impl<'a, K, V, P> DenseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, { /// Constructs a new map with an initial element of `mk_elem(i)` for each `i` in `domain`. pub fn new(domain: &P::Pointer<IndexedDomain<K>>) -> Self { Self(IndexVec::from_fn(|_| None, domain)) } /// Returns an immutable reference to a value for a given key if it exists. pub fn get<M>(&self, idx: impl ToIndex<K, M>) -> Option<&V> { self.0.get(idx).as_ref() } /// Returns a mutable reference to a value for a given key if it exists. pub fn get_mut<M>(&mut self, idx: impl ToIndex<K, M>) -> Option<&mut V> { self.0.get_mut(idx).as_mut() } /// Returns a reference to a value for a given key. /// /// # Safety /// This function has undefined behavior if `key` is not in `self`. pub unsafe fn get_unchecked<M>(&self, idx: impl ToIndex<K, M>) -> &V { unsafe { self.get(idx).unwrap_unchecked() } } /// Returns a mutable reference to a value for a given key. /// /// # Safety /// This function has undefined behavior if `key` is not in `self`. pub unsafe fn get_unchecked_mut<M>(&mut self, idx: impl ToIndex<K, M>) -> &mut V { unsafe { self.get_mut(idx).unwrap_unchecked() } } /// Inserts the key/value pair into `self`. pub fn insert<M>(&mut self, idx: impl ToIndex<K, M>, value: V) { let idx = idx.to_index(&self.0.domain); self.0[idx] = Some(value); } /// Returns an iterator over the values of the map. pub fn values(&self) -> impl Iterator<Item = &V> { self.0.iter().filter_map(Option::as_ref) } } impl<'a, K, V, P> Index<K::Index> for DenseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, { type Output = V; fn index(&self, index: K::Index) -> &Self::Output { self.get(index).unwrap() } } impl<'a, K, V, P> IndexMut<K::Index> for DenseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, { fn index_mut(&mut self, index: K::Index) -> &mut Self::Output { self.get_mut(index).unwrap() } } impl<'a, K, V, P, M, U> FromIndexicalIterator<'a, K, P, M, (U, V)> for DenseIndexMap<'a, K, V, P> where K: IndexedValue + 'a, P: PointerFamily<'a>, U: ToIndex<K, M>, { fn from_indexical_iter( iter: impl Iterator<Item = (U, V)>, domain: &P::Pointer<IndexedDomain<K>>, ) -> Self { let mut map = DenseIndexMap::new(domain); for (u, v) in iter { map.insert(u, v); } map } }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/matrix.rs
Rust
//! An unordered collections of pairs `(R, C)`, implemented with a sparse bit-matrix. #![allow(clippy::needless_pass_by_value)] use rustc_hash::FxHashMap; use std::{fmt, hash::Hash}; use crate::{ IndexedDomain, IndexedValue, ToIndex, bitset::BitSet, pointer::PointerFamily, set::IndexSet, }; /// An unordered collections of pairs `(R, C)`, implemented with a sparse bit-matrix. /// /// "Sparse" means "hash map from rows to bit-sets of columns". Subsequently, only column types `C` must be indexed, /// while row types `R` only need be hashable. pub struct IndexMatrix<'a, R, C: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>> { pub(crate) matrix: FxHashMap<R, IndexSet<'a, C, S, P>>, empty_set: IndexSet<'a, C, S, P>, col_domain: P::Pointer<IndexedDomain<C>>, } impl<'a, R, C, S, P> IndexMatrix<'a, R, C, S, P> where R: PartialEq + Eq + Hash + Clone, C: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { /// Creates an empty matrix. pub fn new(col_domain: &P::Pointer<IndexedDomain<C>>) -> Self { IndexMatrix { matrix: FxHashMap::default(), empty_set: IndexSet::new(col_domain), col_domain: col_domain.clone(), } } pub(crate) fn ensure_row(&mut self, row: R) -> &mut IndexSet<'a, C, S, P> { self.matrix .entry(row) .or_insert_with(|| self.empty_set.clone()) } /// Inserts a pair `(row, col)` into the matrix, returning true if `self` changed. pub fn insert<M>(&mut self, row: R, col: impl ToIndex<C, M>) -> bool { let col = col.to_index(&self.col_domain); self.ensure_row(row).insert(col) } /// Adds all elements of `from` into the row `into`. pub fn union_into_row(&mut self, into: R, from: &IndexSet<'a, C, S, P>) -> bool { self.ensure_row(into).union_changed(from) } /// Adds all elements from the row `from` into the row `into`. pub fn union_rows(&mut self, from: R, to: R) -> bool { if from == to { return false; } self.ensure_row(from.clone()); self.ensure_row(to.clone()); // SAFETY: `from` != `to` therefore this is a disjoint mutable borrow let [Some(from), Some(to)] = (unsafe { self.matrix.get_disjoint_unchecked_mut([&from, &to]) }) else { unreachable!() }; to.union_changed(from) } /// Returns an iterator over the elements in `row`. pub fn row(&self, row: &R) -> impl Iterator<Item = &C> { self.matrix.get(row).into_iter().flat_map(IndexSet::iter) } /// Returns an iterator over all rows in the matrix. pub fn rows(&self) -> impl ExactSizeIterator<Item = (&R, &IndexSet<'a, C, S, P>)> { self.matrix.iter() } /// Returns the [`IndexSet`] for a particular `row`. pub fn row_set(&self, row: &R) -> &IndexSet<'a, C, S, P> { self.matrix.get(row).unwrap_or(&self.empty_set) } /// Clears all the elements from the `row`. pub fn clear_row(&mut self, row: &R) { self.matrix.remove(row); } /// Returns the [`IndexedDomain`] for the column type. pub fn col_domain(&self) -> &P::Pointer<IndexedDomain<C>> { &self.col_domain } } impl<'a, R, C, S, P> IndexMatrix<'a, R, C, S, P> where R: PartialEq + Eq + Hash + Clone + 'a, C: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { // R = Local // C = Allocation /// Transposes the matrix, assuming the row type is also indexed. pub fn transpose<T, M>( &self, row_domain: &P::Pointer<IndexedDomain<T>>, ) -> IndexMatrix<'a, C::Index, T, S, P> where T: IndexedValue + 'a, R: ToIndex<T, M>, { let mut mtx = IndexMatrix::new(row_domain); for (row, cols) in self.rows() { for col in cols.indices() { mtx.insert(col, row.clone()); } } mtx } } impl<'a, R, C, S, P> PartialEq for IndexMatrix<'a, R, C, S, P> where R: PartialEq + Eq + Hash + Clone, C: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { fn eq(&self, other: &Self) -> bool { self.matrix == other.matrix } } impl<'a, R, C, S, P> Eq for IndexMatrix<'a, R, C, S, P> where R: PartialEq + Eq + Hash + Clone, C: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { } impl<'a, R, C, S, P> Clone for IndexMatrix<'a, R, C, S, P> where R: PartialEq + Eq + Hash + Clone, C: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { fn clone(&self) -> Self { Self { matrix: self.matrix.clone(), empty_set: self.empty_set.clone(), col_domain: self.col_domain.clone(), } } fn clone_from(&mut self, source: &Self) { for col in self.matrix.values_mut() { col.clear(); } for (row, col) in &source.matrix { self.ensure_row(row.clone()).clone_from(col); } self.empty_set.clone_from(&source.empty_set); self.col_domain.clone_from(&source.col_domain); } } impl<'a, R, C, S, P> fmt::Debug for IndexMatrix<'a, R, C, S, P> where R: PartialEq + Eq + Hash + Clone + fmt::Debug, C: IndexedValue + fmt::Debug + 'a, S: BitSet, P: PointerFamily<'a>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map().entries(self.rows()).finish() } } #[cfg(test)] mod test { use crate::{IndexedDomain, test_utils::TestIndexMatrix}; use std::rc::Rc; fn mk(s: &str) -> String { s.to_string() } #[test] fn test_indexmatrix() { let col_domain = Rc::new(IndexedDomain::from_iter([mk("a"), mk("b"), mk("c")])); let mut mtx = TestIndexMatrix::new(&col_domain); mtx.insert(0, mk("b")); mtx.insert(1, mk("c")); assert_eq!(mtx.row(&0).collect::<Vec<_>>(), vec!["b"]); assert_eq!(mtx.row(&1).collect::<Vec<_>>(), vec!["c"]); assert!(mtx.union_rows(0, 1)); assert_eq!(mtx.row(&1).collect::<Vec<_>>(), vec!["b", "c"]); } }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/pointer.rs
Rust
//! Abstraction over smart pointers. use std::marker::PhantomData; use std::ops::Deref; use std::rc::Rc; use std::sync::Arc; /// Abstraction over smart pointers. /// /// Used so to make the indexical data structures generic with respect /// to choice of `Rc` or `Arc` (or your own clonable smart pointer!). pub trait PointerFamily<'a> { /// Pointer type for a given family. type Pointer<T: 'a>: Deref<Target = T> + Clone; } /// Family of [`Arc`] pointers. pub struct ArcFamily; impl<'a> PointerFamily<'a> for ArcFamily { type Pointer<T: 'a> = Arc<T>; } /// Family of [`Rc`] pointers. pub struct RcFamily; impl<'a> PointerFamily<'a> for RcFamily { type Pointer<T: 'a> = Rc<T>; } /// Family of `&`-references. pub struct RefFamily<'a>(PhantomData<&'a ()>); impl<'a> PointerFamily<'a> for RefFamily<'a> { type Pointer<T: 'a> = &'a T; }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/set.rs
Rust
//! An unordered collections of `T`s, implemented with a bit-set. use std::{borrow::Borrow, fmt}; use index_vec::Idx; use crate::{ FromIndexicalIterator, IndexedDomain, IndexedValue, ToIndex, bitset::BitSet, pointer::PointerFamily, }; /// An unordered collections of `T`s, implemented with a bit-set. pub struct IndexSet<'a, T: IndexedValue + 'a, S, P: PointerFamily<'a>> { set: S, domain: P::Pointer<IndexedDomain<T>>, } impl<'a, T, S, P> IndexSet<'a, T, S, P> where T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { /// Creates an empty index set. pub fn new(domain: &P::Pointer<IndexedDomain<T>>) -> Self { IndexSet { set: S::empty(domain.len()), domain: domain.clone(), } } /// Returns an iterator over all the indices contained in `self`. pub fn indices(&self) -> impl Iterator<Item = T::Index> { self.set.iter().map(T::Index::from_usize) } /// Returns an iterator over all the objects contained in `self`. pub fn iter(&self) -> impl Iterator<Item = &T> { self.indices().map(move |idx| self.domain.value(idx)) } /// Returns an iterator over the pairs of indices and objects contained in `self`. pub fn iter_enumerated(&self) -> impl Iterator<Item = (T::Index, &T)> { self.indices().map(move |idx| (idx, self.domain.value(idx))) } /// Returns true if `index` is contained in `self`. pub fn contains<M>(&self, index: impl ToIndex<T, M>) -> bool { let elem = index.to_index(&self.domain); self.set.contains(elem.index()) } /// Returns the number of elements in `self`. pub fn len(&self) -> usize { self.set.len() } /// Return true if `self` has no elements. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns true if every element in `other` is also in `self`. pub fn is_superset(&self, other: &IndexSet<'a, T, S, P>) -> bool { self.set.superset(&other.set) } /// Adds the element `elt` to `self`, returning true if `self` changed. pub fn insert<M>(&mut self, elt: impl ToIndex<T, M>) -> bool { let elt = elt.to_index(&self.domain); self.set.insert(elt.index()) } /// Removes the element `elt` from `self`, returning true if `self` changed. pub fn remove<M>(&mut self, elt: impl ToIndex<T, M>) -> bool { let elt = elt.to_index(&self.domain); self.set.remove(elt.index()) } /// Adds each element of `other` to `self`. pub fn union(&mut self, other: &IndexSet<'a, T, S, P>) { self.set.union(&other.set); } /// Adds each element of `other` to `self`, returning true if `self` changed. pub fn union_changed(&mut self, other: &IndexSet<'a, T, S, P>) -> bool { self.set.union_changed(&other.set) } /// Removes every element of `other` from `self`. pub fn subtract(&mut self, other: &IndexSet<'a, T, S, P>) { self.set.subtract(&other.set); } /// Removes every element of `other` from `self`, returning true if `self` changed. pub fn subtract_changed(&mut self, other: &IndexSet<'a, T, S, P>) -> bool { self.set.subtract_changed(&other.set) } /// Removes every element of `self` not in `other`. pub fn intersect(&mut self, other: &IndexSet<'a, T, S, P>) { self.set.intersect(&other.set); } /// Removes every element of `self` not in `other`, returning true if `self` changed. pub fn intersect_changed(&mut self, other: &IndexSet<'a, T, S, P>) -> bool { self.set.intersect_changed(&other.set) } /// Adds every element of the domain to `self`. pub fn insert_all(&mut self) { self.set.insert_all(); } /// Removes every element from `self`. pub fn clear(&mut self) { self.set.clear(); } /// Returns a reference to the inner set. pub fn inner(&self) -> &S { &self.set } } impl<'a, T, S, P> fmt::Debug for IndexSet<'a, T, S, P> where T: IndexedValue + fmt::Debug + 'a, S: BitSet, P: PointerFamily<'a>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_set().entries(self.iter()).finish() } } impl<'a, T, S, P> PartialEq for IndexSet<'a, T, S, P> where T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { fn eq(&self, other: &Self) -> bool { self.set == other.set } } impl<'a, T, S, P> Eq for IndexSet<'a, T, S, P> where T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { } impl<'a, T, S, P> Clone for IndexSet<'a, T, S, P> where T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, { fn clone(&self) -> Self { IndexSet { set: self.set.clone(), domain: self.domain.clone(), } } fn clone_from(&mut self, source: &Self) { self.set.copy_from(&source.set); self.domain = source.domain.clone(); } } impl<'a, T, U, S, M, P> FromIndexicalIterator<'a, T, P, M, U> for IndexSet<'a, T, S, P> where T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, U: ToIndex<T, M>, { fn from_indexical_iter( iter: impl Iterator<Item = U>, domain: &P::Pointer<IndexedDomain<T>>, ) -> Self { let mut set = IndexSet::new(domain); for s in iter { set.insert(s); } set } } /// Iterator extension trait for [`IndexSet`]. pub trait IndexSetIteratorExt< 'a, T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, U: Borrow<IndexSet<'a, T, S, P>>, >: Iterator<Item = U> + Sized { /// Returns the union of the input index sets. fn union_indexical(self, domain: &P::Pointer<IndexedDomain<T>>) -> IndexSet<'a, T, S, P> { let mut set = IndexSet::new(domain); for other in self { set.union(other.borrow()); } set } } impl<'a, I, T, S, P, U> IndexSetIteratorExt<'a, T, S, P, U> for I where T: IndexedValue + 'a, S: BitSet, P: PointerFamily<'a>, U: Borrow<IndexSet<'a, T, S, P>>, I: Iterator<Item = U> + Sized, { } #[cfg(test)] mod test { use crate::{IndexedDomain, IndexicalIteratorExt, test_utils::TestIndexSet}; use std::rc::Rc; fn mk(s: &str) -> String { s.to_string() } #[test] fn test_indexset() { let d = Rc::new(IndexedDomain::from_iter([mk("a"), mk("b"), mk("c")])); let mut s = TestIndexSet::new(&d); s.insert(mk("a")); let b = d.index(&mk("b")); s.insert(b); assert!(s.contains(mk("a"))); assert!(s.contains(mk("b"))); assert_eq!(s.len(), 2); assert_eq!( [mk("a"), mk("b")] .into_iter() .collect_indexical::<TestIndexSet<_>>(&d), s ); assert_eq!(format!("{s:?}"), r#"{"a", "b"}"#) } #[cfg(feature = "bitvec")] #[test] fn test_indexset_reffamily() { let d = &IndexedDomain::from_iter([mk("a"), mk("b"), mk("c")]); let mut s = crate::bitset::bitvec::RefIndexSet::new(&d); s.insert(mk("a")); assert!(s.contains(mk("a"))); let s2 = s.clone(); assert!(std::ptr::eq(s.domain, s2.domain)); } }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University
src/test_utils.rs
Rust
use crate::{bitset::BitSet, define_index_type}; define_index_type! { pub struct StrIdx for String = u32; } pub type TestIndexSet<T> = crate::bitset::bitvec::RcIndexSet<T>; pub type TestIndexMatrix<R, C> = crate::bitset::bitvec::RcIndexMatrix<R, C>; pub fn impl_test<T: BitSet>() { let mut bv = T::empty(10); assert!(!bv.contains(0)); bv.insert(0); bv.insert(5); assert!(bv.contains(0)); assert!(bv.contains(5)); assert!(!bv.contains(1)); assert_eq!(bv.iter().collect::<Vec<_>>(), vec![0, 5]); assert_eq!(bv.len(), 2); let mut bv2 = T::empty(10); bv2.insert(5); assert!(bv.superset(&bv2)); bv2.insert(1); assert!(!bv.superset(&bv2)); assert!(bv.intersect_changed(&bv2)); assert!(!bv.intersect_changed(&bv2)); assert_eq!(bv.iter().collect::<Vec<_>>(), vec![5]); let mut bv = T::empty(64 * 4 + 1); bv.insert(64 * 4); assert!(!bv.contains(64 * 4 - 1)); assert!(bv.contains(64 * 4)); let mut bv = T::empty(10); bv.insert(0); bv.insert(1); let mut bv2 = T::empty(10); bv2.insert(0); bv.subtract(&bv2); assert_eq!(bv.iter().collect::<Vec<_>>(), vec![1]); bv.invert(); assert_eq!( bv.iter().collect::<Vec<_>>(), vec![0, 2, 3, 4, 5, 6, 7, 8, 9] ); bv.clear(); assert!(!bv.contains(0)); assert_eq!(bv.iter().collect::<Vec<_>>(), Vec::<usize>::new()); let mut bv = T::empty(10); bv.insert(0); assert!(bv.contains(0)); bv.remove(0); assert!(!bv.contains(0)); }
willcrichton/indexical
56
Human-friendly indexed collections
Rust
willcrichton
Will Crichton
Brown University