repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/tree.rs
rust/rope/src/tree.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A general b-tree structure suitable for ropes and the like. use std::cmp::{min, Ordering}; use std::marker::PhantomData; use std::sync::Arc; use crate::interval::{Interval, IntervalBounds}; const MIN_CHILDREN: usize = 4; const MAX_CHILDREN: usize = 8; pub trait NodeInfo: Clone { /// The type of the leaf. /// /// A given `NodeInfo` is for exactly one type of leaf. That is why /// the leaf type is an associated type rather than a type parameter. type L: Leaf; /// An operator that combines info from two subtrees. It is intended /// (but not strictly enforced) that this operator be associative and /// obey an identity property. In mathematical terms, the accumulate /// method is the operation of a monoid. fn accumulate(&mut self, other: &Self); /// A mapping from a leaf into the info type. It is intended (but /// not strictly enforced) that applying the accumulate method to /// the info derived from two leaves gives the same result as /// deriving the info from the concatenation of the two leaves. In /// mathematical terms, the compute_info method is a monoid /// homomorphism. fn compute_info(_: &Self::L) -> Self; /// The identity of the monoid. Need not be implemented because it /// can be computed from the leaf default. /// /// This is here to demonstrate that this is a monoid. fn identity() -> Self { Self::compute_info(&Self::L::default()) } /// The interval covered by the first `len` base units of this node. The /// default impl is sufficient for most types, but interval trees may need /// to override it. fn interval(&self, len: usize) -> Interval { Interval::new(0, len) } } /// A trait indicating the default metric of a NodeInfo. /// /// Adds quality of life functions to /// Node\<N\>, where N is a DefaultMetric. /// For example, [Node\<DefaultMetric\>.count](struct.Node.html#method.count). pub trait DefaultMetric: NodeInfo { type DefaultMetric: Metric<Self>; } /// A trait for the leaves of trees of type [Node](struct.Node.html). /// /// Two leafs can be concatenated using `push_maybe_split`. pub trait Leaf: Sized + Clone + Default { /// Measurement of leaf in base units. /// A 'base unit' refers to the smallest discrete unit /// by which a given concrete type can be indexed. /// Concretely, for Rust's String type the base unit is the byte. fn len(&self) -> usize; /// Generally a minimum size requirement for leaves. fn is_ok_child(&self) -> bool; /// Combine the part `other` denoted by the `Interval` `iv` into `self`, /// optionly splitting off a new `Leaf` if `self` would have become too big. /// Returns either `None` if no splitting was needed, or `Some(rest)` if /// `rest` was split off. /// /// Interval is in "base units". Generally implements a maximum size. /// /// # Invariants: /// - If one or the other input is empty, then no split. /// - If either input satisfies `is_ok_child`, then, on return, `self` /// satisfies this, as does the optional split. fn push_maybe_split(&mut self, other: &Self, iv: Interval) -> Option<Self>; /// Same meaning as push_maybe_split starting from an empty /// leaf, but maybe can be implemented more efficiently? /// // TODO: remove if it doesn't pull its weight fn subseq(&self, iv: Interval) -> Self { let mut result = Self::default(); if result.push_maybe_split(self, iv).is_some() { panic!("unexpected split"); } result } } /// A b-tree node storing leaves at the bottom, and with info /// retained at each node. It is implemented with atomic reference counting /// and copy-on-write semantics, so an immutable clone is a very cheap /// operation, and nodes can be shared across threads. Even so, it is /// designed to be updated in place, with efficiency similar to a mutable /// data structure, using uniqueness of reference count to detect when /// this operation is safe. /// /// When the leaf is a string, this is a rope data structure (a persistent /// rope in functional programming jargon). However, it is not restricted /// to strings, and it is expected to be the basis for a number of data /// structures useful for text processing. #[derive(Clone)] pub struct Node<N: NodeInfo>(Arc<NodeBody<N>>); #[derive(Clone)] struct NodeBody<N: NodeInfo> { height: usize, len: usize, info: N, val: NodeVal<N>, } #[derive(Clone)] enum NodeVal<N: NodeInfo> { Leaf(N::L), Internal(Vec<Node<N>>), } // also consider making Metric a newtype for usize, so type system can // help separate metrics /// A trait for quickly processing attributes of a /// [NodeInfo](struct.NodeInfo.html). /// /// For the conceptual background see the /// [blog post, Rope science, part 2: metrics](https://github.com/google/xi-editor/blob/master/docs/docs/rope_science_02.md). pub trait Metric<N: NodeInfo> { /// Return the size of the /// [NodeInfo::L](trait.NodeInfo.html#associatedtype.L), as measured by this /// metric. /// /// The usize argument is the total size/length of the node, in base units. /// /// # Examples /// For the [LinesMetric](../rope/struct.LinesMetric.html), this gives the number of /// lines in string contained in the leaf. For the /// [BaseMetric](../rope/struct.BaseMetric.html), this gives the size of the string /// in uft8 code units, that is, bytes. /// fn measure(info: &N, len: usize) -> usize; /// Returns the smallest offset, in base units, for an offset in measured units. /// /// # Invariants: /// /// - `from_base_units(to_base_units(x)) == x` is True for valid `x` fn to_base_units(l: &N::L, in_measured_units: usize) -> usize; /// Returns the smallest offset in measured units corresponding to an offset in base units. /// /// # Invariants: /// /// - `from_base_units(to_base_units(x)) == x` is True for valid `x` fn from_base_units(l: &N::L, in_base_units: usize) -> usize; /// Return whether the offset in base units is a boundary of this metric. /// If a boundary is at end of a leaf then this method must return true. /// However, a boundary at the beginning of a leaf is optional /// (the previous leaf will be queried). fn is_boundary(l: &N::L, offset: usize) -> bool; /// Returns the index of the boundary directly preceding offset, /// or None if no such boundary exists. Input and result are in base units. fn prev(l: &N::L, offset: usize) -> Option<usize>; /// Returns the index of the first boundary for which index > offset, /// or None if no such boundary exists. Input and result are in base units. fn next(l: &N::L, offset: usize) -> Option<usize>; /// Returns true if the measured units in this metric can span multiple /// leaves. As an example, in a metric that measures lines in a rope, a /// line may start in one leaf and end in another; however in a metric /// measuring bytes, storage of a single byte cannot extend across leaves. fn can_fragment() -> bool; } impl<N: NodeInfo> Node<N> { pub fn from_leaf(l: N::L) -> Node<N> { let len = l.len(); let info = N::compute_info(&l); Node(Arc::new(NodeBody { height: 0, len, info, val: NodeVal::Leaf(l) })) } /// Create a node from a vec of nodes. /// /// The input must satisfy the following balancing requirements: /// * The length of `nodes` must be <= MAX_CHILDREN and > 1. /// * All the nodes are the same height. /// * All the nodes must satisfy is_ok_child. fn from_nodes(nodes: Vec<Node<N>>) -> Node<N> { debug_assert!(nodes.len() > 1); debug_assert!(nodes.len() <= MAX_CHILDREN); let height = nodes[0].0.height + 1; let mut len = nodes[0].0.len; let mut info = nodes[0].0.info.clone(); debug_assert!(nodes[0].is_ok_child()); for child in &nodes[1..] { debug_assert_eq!(child.height() + 1, height); debug_assert!(child.is_ok_child()); len += child.0.len; info.accumulate(&child.0.info); } Node(Arc::new(NodeBody { height, len, info, val: NodeVal::Internal(nodes) })) } pub fn len(&self) -> usize { self.0.len } pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns `true` if these two `Node`s share the same underlying data. /// /// This is principally intended to be used by the druid crate, without needing /// to actually add a feature and implement druid's `Data` trait. pub fn ptr_eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } fn height(&self) -> usize { self.0.height } fn is_leaf(&self) -> bool { self.0.height == 0 } fn interval(&self) -> Interval { self.0.info.interval(self.0.len) } fn get_children(&self) -> &[Node<N>] { if let NodeVal::Internal(ref v) = self.0.val { v } else { panic!("get_children called on leaf node"); } } fn get_leaf(&self) -> &N::L { if let NodeVal::Leaf(ref l) = self.0.val { l } else { panic!("get_leaf called on internal node"); } } /// Call a callback with a mutable reference to a leaf. /// /// This clones the leaf if the reference is shared. It also recomputes /// length and info after the leaf is mutated. fn with_leaf_mut<T>(&mut self, f: impl FnOnce(&mut N::L) -> T) -> T { let inner = Arc::make_mut(&mut self.0); if let NodeVal::Leaf(ref mut l) = inner.val { let result = f(l); inner.len = l.len(); inner.info = N::compute_info(l); result } else { panic!("with_leaf_mut called on internal node"); } } fn is_ok_child(&self) -> bool { match self.0.val { NodeVal::Leaf(ref l) => l.is_ok_child(), NodeVal::Internal(ref nodes) => (nodes.len() >= MIN_CHILDREN), } } fn merge_nodes(children1: &[Node<N>], children2: &[Node<N>]) -> Node<N> { let n_children = children1.len() + children2.len(); if n_children <= MAX_CHILDREN { Node::from_nodes([children1, children2].concat()) } else { // Note: this leans left. Splitting at midpoint is also an option let splitpoint = min(MAX_CHILDREN, n_children - MIN_CHILDREN); let mut iter = children1.iter().chain(children2.iter()).cloned(); let left = iter.by_ref().take(splitpoint).collect(); let right = iter.collect(); let parent_nodes = vec![Node::from_nodes(left), Node::from_nodes(right)]; Node::from_nodes(parent_nodes) } } fn merge_leaves(mut rope1: Node<N>, rope2: Node<N>) -> Node<N> { debug_assert!(rope1.is_leaf() && rope2.is_leaf()); let both_ok = rope1.get_leaf().is_ok_child() && rope2.get_leaf().is_ok_child(); if both_ok { return Node::from_nodes(vec![rope1, rope2]); } match { let node1 = Arc::make_mut(&mut rope1.0); let leaf2 = rope2.get_leaf(); if let NodeVal::Leaf(ref mut leaf1) = node1.val { let leaf2_iv = Interval::new(0, leaf2.len()); let new = leaf1.push_maybe_split(leaf2, leaf2_iv); node1.len = leaf1.len(); node1.info = N::compute_info(leaf1); new } else { panic!("merge_leaves called on non-leaf"); } } { Some(new) => Node::from_nodes(vec![rope1, Node::from_leaf(new)]), None => rope1, } } pub fn concat(rope1: Node<N>, rope2: Node<N>) -> Node<N> { let h1 = rope1.height(); let h2 = rope2.height(); match h1.cmp(&h2) { Ordering::Less => { let children2 = rope2.get_children(); if h1 == h2 - 1 && rope1.is_ok_child() { return Node::merge_nodes(&[rope1], children2); } let newrope = Node::concat(rope1, children2[0].clone()); if newrope.height() == h2 - 1 { Node::merge_nodes(&[newrope], &children2[1..]) } else { Node::merge_nodes(newrope.get_children(), &children2[1..]) } } Ordering::Equal => { if rope1.is_ok_child() && rope2.is_ok_child() { return Node::from_nodes(vec![rope1, rope2]); } if h1 == 0 { return Node::merge_leaves(rope1, rope2); } Node::merge_nodes(rope1.get_children(), rope2.get_children()) } Ordering::Greater => { let children1 = rope1.get_children(); if h2 == h1 - 1 && rope2.is_ok_child() { return Node::merge_nodes(children1, &[rope2]); } let lastix = children1.len() - 1; let newrope = Node::concat(children1[lastix].clone(), rope2); if newrope.height() == h1 - 1 { Node::merge_nodes(&children1[..lastix], &[newrope]) } else { Node::merge_nodes(&children1[..lastix], newrope.get_children()) } } } } pub fn measure<M: Metric<N>>(&self) -> usize { M::measure(&self.0.info, self.0.len) } pub fn subseq<T: IntervalBounds>(&self, iv: T) -> Node<N> { let iv = iv.into_interval(self.len()); let mut b = TreeBuilder::new(); b.push_slice(self, iv); b.build() } pub fn edit<T, IV>(&mut self, iv: IV, new: T) where T: Into<Node<N>>, IV: IntervalBounds, { let mut b = TreeBuilder::new(); let iv = iv.into_interval(self.len()); let self_iv = self.interval(); b.push_slice(self, self_iv.prefix(iv)); b.push(new.into()); b.push_slice(self, self_iv.suffix(iv)); *self = b.build(); } // doesn't deal with endpoint, handle that specially if you need it pub fn convert_metrics<M1: Metric<N>, M2: Metric<N>>(&self, mut m1: usize) -> usize { if m1 == 0 { return 0; } // If M1 can fragment, then we must land on the leaf containing // the m1 boundary. Otherwise, we can land on the beginning of // the leaf immediately following the M1 boundary, which may be // more efficient. let m1_fudge = if M1::can_fragment() { 1 } else { 0 }; let mut m2 = 0; let mut node = self; while node.height() > 0 { for child in node.get_children() { let child_m1 = child.measure::<M1>(); if m1 < child_m1 + m1_fudge { node = child; break; } m2 += child.measure::<M2>(); m1 -= child_m1; } } let l = node.get_leaf(); let base = M1::to_base_units(l, m1); m2 + M2::from_base_units(l, base) } } impl<N: DefaultMetric> Node<N> { /// Measures the length of the text bounded by ``DefaultMetric::measure(offset)`` with another metric. /// /// # Examples /// ``` /// use crate::xi_rope::{Rope, LinesMetric}; /// /// // the default metric of Rope is BaseMetric (aka number of bytes) /// let my_rope = Rope::from("first line \n second line \n"); /// /// // count the number of lines in my_rope /// let num_lines = my_rope.count::<LinesMetric>(my_rope.len()); /// assert_eq!(2, num_lines); /// ``` pub fn count<M: Metric<N>>(&self, offset: usize) -> usize { self.convert_metrics::<N::DefaultMetric, M>(offset) } /// Measures the length of the text bounded by ``M::measure(offset)`` with the default metric. /// /// # Examples /// ``` /// use crate::xi_rope::{Rope, LinesMetric}; /// /// // the default metric of Rope is BaseMetric (aka number of bytes) /// let my_rope = Rope::from("first line \n second line \n"); /// /// // get the byte offset of the line at index 1 /// let byte_offset = my_rope.count_base_units::<LinesMetric>(1); /// assert_eq!(12, byte_offset); /// ``` pub fn count_base_units<M: Metric<N>>(&self, offset: usize) -> usize { self.convert_metrics::<M, N::DefaultMetric>(offset) } } impl<N: NodeInfo> Default for Node<N> { fn default() -> Node<N> { Node::from_leaf(N::L::default()) } } /// A builder for creating new trees. pub struct TreeBuilder<N: NodeInfo> { // A stack of partially built trees. These are kept in order of // strictly descending height, and all vectors have a length less // than MAX_CHILDREN and greater than zero. // // In addition, there is a balancing invariant: for each vector // of length greater than one, all elements satisfy `is_ok_child`. stack: Vec<Vec<Node<N>>>, } impl<N: NodeInfo> TreeBuilder<N> { /// A new, empty builder. pub fn new() -> TreeBuilder<N> { TreeBuilder { stack: Vec::new() } } /// Append a node to the tree being built. pub fn push(&mut self, mut n: Node<N>) { loop { let ord = if let Some(last) = self.stack.last() { last[0].height().cmp(&n.height()) } else { Ordering::Greater }; match ord { Ordering::Less => { n = Node::concat(self.pop(), n); } Ordering::Equal => { let tos = self.stack.last_mut().unwrap(); if tos.last().unwrap().is_ok_child() && n.is_ok_child() { tos.push(n); } else if n.height() == 0 { let iv = Interval::new(0, n.len()); let new_leaf = tos .last_mut() .unwrap() .with_leaf_mut(|l| l.push_maybe_split(n.get_leaf(), iv)); if let Some(new_leaf) = new_leaf { tos.push(Node::from_leaf(new_leaf)); } } else { let last = tos.pop().unwrap(); let children1 = last.get_children(); let children2 = n.get_children(); let n_children = children1.len() + children2.len(); if n_children <= MAX_CHILDREN { tos.push(Node::from_nodes([children1, children2].concat())); } else { // Note: this leans left. Splitting at midpoint is also an option let splitpoint = min(MAX_CHILDREN, n_children - MIN_CHILDREN); let mut iter = children1.iter().chain(children2.iter()).cloned(); let left = iter.by_ref().take(splitpoint).collect(); let right = iter.collect(); tos.push(Node::from_nodes(left)); tos.push(Node::from_nodes(right)); } } if tos.len() < MAX_CHILDREN { break; } n = self.pop() } Ordering::Greater => { self.stack.push(vec![n]); break; } } } } /// Push a subsequence of a rope. /// /// Pushes the subsequence of another tree `n` defined by the interval `iv` /// onto the builder. /// /// This is intended as an efficient operation. It is equivalent to taking /// the subsequence of `n` and pushing that, but attempts to minimize the /// allocation of intermediate results. pub fn push_slice(&mut self, n: &Node<N>, iv: Interval) { if iv.is_empty() { return; } if iv == n.interval() { self.push(n.clone()); return; } match n.0.val { NodeVal::Leaf(ref l) => { self.push_leaf_slice(l, iv); } NodeVal::Internal(ref v) => { let mut offset = 0; for child in v { if iv.is_before(offset) { break; } let child_iv = child.interval(); // easier just to use signed ints? let rec_iv = iv.intersect(child_iv.translate(offset)).translate_neg(offset); self.push_slice(child, rec_iv); offset += child.len(); } } } } /// Append a sequence of leaves. pub fn push_leaves(&mut self, leaves: impl IntoIterator<Item = N::L>) { for leaf in leaves.into_iter() { self.push(Node::from_leaf(leaf)); } } /// Append a single leaf. pub fn push_leaf(&mut self, l: N::L) { self.push(Node::from_leaf(l)) } /// Append a slice of a single leaf. pub fn push_leaf_slice(&mut self, l: &N::L, iv: Interval) { self.push(Node::from_leaf(l.subseq(iv))) } /// Build the final tree. /// /// The tree is the concatenation of all the nodes and leaves that have been pushed /// on the builder, in order. pub fn build(mut self) -> Node<N> { if self.stack.is_empty() { Node::from_leaf(N::L::default()) } else { let mut n = self.pop(); while !self.stack.is_empty() { n = Node::concat(self.pop(), n); } n } } /// Pop the last vec-of-nodes off the stack, resulting in a node. fn pop(&mut self) -> Node<N> { let nodes = self.stack.pop().unwrap(); if nodes.len() == 1 { nodes.into_iter().next().unwrap() } else { Node::from_nodes(nodes) } } } const CURSOR_CACHE_SIZE: usize = 4; /// A data structure for traversing boundaries in a tree. /// /// It is designed to be efficient both for random access and for iteration. The /// cursor itself is agnostic to which [`Metric`] is used to determine boundaries, but /// the methods to find boundaries are parametrized on the [`Metric`]. /// /// A cursor can be valid or invalid. It is always valid when created or after /// [`set`](#method.set) is called, and becomes invalid after [`prev`](#method.prev) /// or [`next`](#method.next) fails to find a boundary. /// /// [`Metric`]: struct.Metric.html pub struct Cursor<'a, N: 'a + NodeInfo> { /// The tree being traversed by this cursor. root: &'a Node<N>, /// The current position of the cursor. /// /// It is always less than or equal to the tree length. position: usize, /// The cache holds the tail of the path from the root to the current leaf. /// /// Each entry is a reference to the parent node and the index of the child. It /// is stored bottom-up; `cache[0]` is the parent of the leaf and the index of /// the leaf within that parent. /// /// The main motivation for this being a fixed-size array is to keep the cursor /// an allocation-free data structure. cache: [Option<(&'a Node<N>, usize)>; CURSOR_CACHE_SIZE], /// The leaf containing the current position, when the cursor is valid. /// /// The position is only at the end of the leaf when it is at the end of the tree. leaf: Option<&'a N::L>, /// The offset of `leaf` within the tree. offset_of_leaf: usize, } impl<'a, N: NodeInfo> Cursor<'a, N> { /// Create a new cursor at the given position. pub fn new(n: &'a Node<N>, position: usize) -> Cursor<'a, N> { let mut result = Cursor { root: n, position, cache: [None; CURSOR_CACHE_SIZE], leaf: None, offset_of_leaf: 0, }; result.descend(); result } /// The length of the tree. pub fn total_len(&self) -> usize { self.root.len() } /// Return a reference to the root node of the tree. pub fn root(&self) -> &'a Node<N> { self.root } /// Get the current leaf of the cursor. /// /// If the cursor is valid, returns the leaf containing the current position, /// and the offset of the current position within the leaf. That offset is equal /// to the leaf length only at the end, otherwise it is less than the leaf length. pub fn get_leaf(&self) -> Option<(&'a N::L, usize)> { self.leaf.map(|l| (l, self.position - self.offset_of_leaf)) } /// Set the position of the cursor. /// /// The cursor is valid after this call. /// /// Precondition: `position` is less than or equal to the length of the tree. pub fn set(&mut self, position: usize) { self.position = position; if let Some(l) = self.leaf { if self.position >= self.offset_of_leaf && self.position < self.offset_of_leaf + l.len() { return; } } // TODO: walk up tree to find leaf if nearby self.descend(); } /// Get the position of the cursor. pub fn pos(&self) -> usize { self.position } /// Determine whether the current position is a boundary. /// /// Note: the beginning and end of the tree may or may not be boundaries, depending on the /// metric. If the metric is not `can_fragment`, then they always are. pub fn is_boundary<M: Metric<N>>(&mut self) -> bool { if self.leaf.is_none() { // not at a valid position return false; } if self.position == self.offset_of_leaf && !M::can_fragment() { return true; } if self.position == 0 || self.position > self.offset_of_leaf { return M::is_boundary(self.leaf.unwrap(), self.position - self.offset_of_leaf); } // tricky case, at beginning of leaf, need to query end of previous // leaf; TODO: would be nice if we could do it another way that didn't // make the method &mut self. let l = self.prev_leaf().unwrap().0; let result = M::is_boundary(l, l.len()); let _ = self.next_leaf(); result } /// Moves the cursor to the previous boundary. /// /// When there is no previous boundary, returns `None` and the cursor becomes invalid. /// /// Return value: the position of the boundary, if it exists. pub fn prev<M: Metric<N>>(&mut self) -> Option<usize> { if self.position == 0 || self.leaf.is_none() { self.leaf = None; return None; } let orig_pos = self.position; let offset_in_leaf = orig_pos - self.offset_of_leaf; if offset_in_leaf > 0 { let l = self.leaf.unwrap(); if let Some(offset_in_leaf) = M::prev(l, offset_in_leaf) { self.position = self.offset_of_leaf + offset_in_leaf; return Some(self.position); } } // not in same leaf, need to scan backwards self.prev_leaf()?; if let Some(offset) = self.last_inside_leaf::<M>(orig_pos) { return Some(offset); } // Not found in previous leaf, find using measurement. let measure = self.measure_leaf::<M>(self.position); if measure == 0 { self.leaf = None; self.position = 0; return None; } self.descend_metric::<M>(measure); self.last_inside_leaf::<M>(orig_pos) } /// Moves the cursor to the next boundary. /// /// When there is no next boundary, returns `None` and the cursor becomes invalid. /// /// Return value: the position of the boundary, if it exists. pub fn next<M: Metric<N>>(&mut self) -> Option<usize> { if self.position >= self.root.len() || self.leaf.is_none() { self.leaf = None; return None; } if let Some(offset) = self.next_inside_leaf::<M>() { return Some(offset); } self.next_leaf()?; if let Some(offset) = self.next_inside_leaf::<M>() { return Some(offset); } // Leaf is 0-measure (otherwise would have already succeeded). let measure = self.measure_leaf::<M>(self.position); self.descend_metric::<M>(measure + 1); if let Some(offset) = self.next_inside_leaf::<M>() { return Some(offset); } // Not found, properly invalidate cursor. self.position = self.root.len(); self.leaf = None; None } /// Returns the current position if it is a boundary in this [`Metric`], /// else behaves like [`next`](#method.next). /// /// [`Metric`]: struct.Metric.html pub fn at_or_next<M: Metric<N>>(&mut self) -> Option<usize> { if self.is_boundary::<M>() { Some(self.pos()) } else { self.next::<M>() } } /// Returns the current position if it is a boundary in this [`Metric`], /// else behaves like [`prev`](#method.prev). /// /// [`Metric`]: struct.Metric.html pub fn at_or_prev<M: Metric<N>>(&mut self) -> Option<usize> { if self.is_boundary::<M>() { Some(self.pos()) } else { self.prev::<M>() } } /// Returns an iterator with this cursor over the given [`Metric`]. /// /// # Examples: /// /// ``` /// # use xi_rope::{Cursor, LinesMetric, Rope}; /// # /// let text: Rope = "one line\ntwo line\nred line\nblue".into(); /// let mut cursor = Cursor::new(&text, 0); /// let line_offsets = cursor.iter::<LinesMetric>().collect::<Vec<_>>(); /// assert_eq!(line_offsets, vec![9, 18, 27]); /// /// ``` /// [`Metric`]: struct.Metric.html pub fn iter<'c, M: Metric<N>>(&'c mut self) -> CursorIter<'c, 'a, N, M> { CursorIter { cursor: self, _metric: PhantomData } } /// Tries to find the last boundary in the leaf the cursor is currently in. /// /// If the last boundary is at the end of the leaf, it is only counted if /// it is less than `orig_pos`. #[inline] fn last_inside_leaf<M: Metric<N>>(&mut self, orig_pos: usize) -> Option<usize> { let l = self.leaf.expect("inconsistent, shouldn't get here"); let len = l.len(); if self.offset_of_leaf + len < orig_pos && M::is_boundary(l, len) { let _ = self.next_leaf(); return Some(self.position); } let offset_in_leaf = M::prev(l, len)?; self.position = self.offset_of_leaf + offset_in_leaf; Some(self.position) } /// Tries to find the next boundary in the leaf the cursor is currently in. #[inline] fn next_inside_leaf<M: Metric<N>>(&mut self) -> Option<usize> { let l = self.leaf.expect("inconsistent, shouldn't get here"); let offset_in_leaf = self.position - self.offset_of_leaf; let offset_in_leaf = M::next(l, offset_in_leaf)?; if offset_in_leaf == l.len() && self.offset_of_leaf + offset_in_leaf != self.root.len() { let _ = self.next_leaf(); } else { self.position = self.offset_of_leaf + offset_in_leaf; } Some(self.position) } /// Move to beginning of next leaf. /// /// Return value: same as [`get_leaf`](#method.get_leaf). pub fn next_leaf(&mut self) -> Option<(&'a N::L, usize)> { let leaf = self.leaf?; self.position = self.offset_of_leaf + leaf.len(); for i in 0..CURSOR_CACHE_SIZE {
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
true
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/find.rs
rust/rope/src/find.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Implementation of string finding in ropes. use std::cmp::min; use memchr::{memchr, memchr2, memchr3}; use crate::rope::BaseMetric; use crate::rope::LinesRaw; use crate::rope::RopeInfo; use crate::tree::Cursor; use regex::Regex; use std::borrow::Cow; use std::str; /// The result of a [`find`][find] operation. /// /// [find]: fn.find.html pub enum FindResult { /// The pattern was found at this position. Found(usize), /// The pattern was not found. NotFound, /// The cursor has been advanced by some amount. The pattern is not /// found before the new cursor, but may be at or beyond it. TryAgain, } /// A policy for case matching. There may be more choices in the future (for /// example, an even more forgiving mode that ignores accents, or possibly /// handling Unicode normalization). #[derive(Clone, Copy, PartialEq)] pub enum CaseMatching { /// Require an exact codepoint-for-codepoint match (implies case sensitivity). Exact, /// Case insensitive match. Guaranteed to work for the ASCII case, and /// reasonably well otherwise (it is currently defined in terms of the /// `to_lowercase` methods in the Rust standard library). CaseInsensitive, } /// Finds a pattern string in the rope referenced by the cursor, starting at /// the current location of the cursor (and finding the first match). Both /// case sensitive and case insensitive matching is provided, controlled by /// the `cm` parameter. The `regex` parameter controls whether the query /// should be considered as a regular expression. /// /// On success, the cursor is updated to immediately follow the found string. /// On failure, the cursor's position is indeterminate. /// /// Can panic if `pat` is empty. pub fn find( cursor: &mut Cursor<RopeInfo>, lines: &mut LinesRaw, cm: CaseMatching, pat: &str, regex: Option<&Regex>, ) -> Option<usize> { match find_progress(cursor, lines, cm, pat, usize::max_value(), regex) { FindResult::Found(start) => Some(start), FindResult::NotFound => None, FindResult::TryAgain => unreachable!("find_progress got stuck"), } } /// A variant of [`find`][find] that makes a bounded amount of progress, then either /// returns or suspends (returning `TryAgain`). /// /// The `num_steps` parameter controls the number of "steps" processed per /// call. The unit of "step" is not formally defined but is typically /// scanning one leaf (using a memchr-like scan) or testing one candidate /// when scanning produces a result. It should be empirically tuned for a /// balance between overhead and impact on interactive performance, but the /// exact value is probably not critical. /// /// [find]: fn.find.html pub fn find_progress( cursor: &mut Cursor<RopeInfo>, lines: &mut LinesRaw, cm: CaseMatching, pat: &str, num_steps: usize, regex: Option<&Regex>, ) -> FindResult { // empty search string if pat.is_empty() { return FindResult::NotFound; } match regex { Some(r) => find_progress_iter( cursor, lines, pat, |_| Some(0), |cursor, lines, pat| compare_cursor_regex(cursor, lines, pat, r), num_steps, ), None => { match cm { CaseMatching::Exact => { let b = pat.as_bytes()[0]; let scanner = |s: &str| memchr(b, s.as_bytes()); let matcher = compare_cursor_str; find_progress_iter(cursor, lines, pat, scanner, matcher, num_steps) } CaseMatching::CaseInsensitive => { let pat_lower = pat.to_lowercase(); let b = pat_lower.as_bytes()[0]; let matcher = compare_cursor_str_casei; if b == b'i' { // 0xC4 is first utf-8 byte of 'İ' let scanner = |s: &str| memchr3(b'i', b'I', 0xC4, s.as_bytes()); find_progress_iter(cursor, lines, &pat_lower, scanner, matcher, num_steps) } else if b == b'k' { // 0xE2 is first utf-8 byte of u+212A (kelvin sign) let scanner = |s: &str| memchr3(b'k', b'K', 0xE2, s.as_bytes()); find_progress_iter(cursor, lines, &pat_lower, scanner, matcher, num_steps) } else if (b'a'..=b'z').contains(&b) { let scanner = |s: &str| memchr2(b, b - 0x20, s.as_bytes()); find_progress_iter(cursor, lines, &pat_lower, scanner, matcher, num_steps) } else if b < 0x80 { let scanner = |s: &str| memchr(b, s.as_bytes()); find_progress_iter(cursor, lines, &pat_lower, scanner, matcher, num_steps) } else { let c = pat.chars().next().unwrap(); let scanner = |s: &str| scan_lowercase(c, s); find_progress_iter(cursor, lines, &pat_lower, scanner, matcher, num_steps) } } } } } } // Run the core repeatedly until there is a result, up to a certain number of steps. fn find_progress_iter( cursor: &mut Cursor<RopeInfo>, lines: &mut LinesRaw, pat: &str, scanner: impl Fn(&str) -> Option<usize>, matcher: impl Fn(&mut Cursor<RopeInfo>, &mut LinesRaw, &str) -> Option<usize>, num_steps: usize, ) -> FindResult { for _ in 0..num_steps { match find_core(cursor, lines, pat, &scanner, &matcher) { FindResult::TryAgain => (), result => return result, } } FindResult::TryAgain } // The core of the find algorithm. It takes a "scanner", which quickly // scans through a single leaf searching for some prefix of the pattern, // then a "matcher" which confirms that such a candidate actually matches // in the full rope. fn find_core( cursor: &mut Cursor<RopeInfo>, lines: &mut LinesRaw, pat: &str, scanner: impl Fn(&str) -> Option<usize>, matcher: impl Fn(&mut Cursor<RopeInfo>, &mut LinesRaw, &str) -> Option<usize>, ) -> FindResult { let orig_pos = cursor.pos(); // if cursor reached the end of the text then no match has been found if orig_pos == cursor.total_len() { return FindResult::NotFound; } if let Some((leaf, pos_in_leaf)) = cursor.get_leaf() { if let Some(off) = scanner(&leaf[pos_in_leaf..]) { let candidate_pos = orig_pos + off; cursor.set(candidate_pos); if let Some(actual_pos) = matcher(cursor, lines, pat) { return FindResult::Found(actual_pos); } } else { let _ = cursor.next_leaf(); } FindResult::TryAgain } else { FindResult::NotFound } } /// Compare whether the substring beginning at the current cursor location /// is equal to the provided string. Leaves the cursor at an indeterminate /// position on failure, but the end of the string on success. Returns the /// start position of the match. pub fn compare_cursor_str( cursor: &mut Cursor<RopeInfo>, _lines: &mut LinesRaw, mut pat: &str, ) -> Option<usize> { let start_position = cursor.pos(); if pat.is_empty() { return Some(start_position); } let success_pos = cursor.pos() + pat.len(); while let Some((leaf, pos_in_leaf)) = cursor.get_leaf() { let n = min(pat.len(), leaf.len() - pos_in_leaf); if leaf.as_bytes()[pos_in_leaf..pos_in_leaf + n] != pat.as_bytes()[..n] { cursor.set(start_position); cursor.next::<BaseMetric>(); return None; } pat = &pat[n..]; if pat.is_empty() { cursor.set(success_pos); return Some(start_position); } let _ = cursor.next_leaf(); } cursor.set(start_position); cursor.next::<BaseMetric>(); None } /// Like `compare_cursor_str` but case invariant (using to_lowercase() to /// normalize both strings before comparison). Returns the start position /// of the match. pub fn compare_cursor_str_casei( cursor: &mut Cursor<RopeInfo>, _lines: &mut LinesRaw, pat: &str, ) -> Option<usize> { let start_position = cursor.pos(); let mut pat_iter = pat.chars(); let mut c = pat_iter.next().unwrap(); loop { if let Some(rope_c) = cursor.next_codepoint() { for lc_c in rope_c.to_lowercase() { if c != lc_c { cursor.set(start_position); cursor.next::<BaseMetric>(); return None; } if let Some(next_c) = pat_iter.next() { c = next_c; } else { return Some(start_position); } } } else { // end of string before pattern is complete cursor.set(start_position); cursor.next::<BaseMetric>(); return None; } } } /// Compare whether the substring beginning at the cursor location matches /// the provided regular expression. The substring begins at the beginning /// of the start of the line. /// If the regular expression can match multiple lines then the entire text /// is consumed and matched against the regular expression. Otherwise only /// the current line is matched. Returns the start position of the match. pub fn compare_cursor_regex( cursor: &mut Cursor<RopeInfo>, lines: &mut LinesRaw, pat: &str, regex: &Regex, ) -> Option<usize> { let orig_position = cursor.pos(); if pat.is_empty() { return Some(orig_position); } let text: Cow<str>; if is_multiline_regex(pat) { // consume all of the text if regex is multi line matching text = Cow::Owned(lines.collect()); } else { match lines.next() { Some(line) => text = line, _ => return None, } } // match regex against text match regex.find(&text) { Some(mat) => { // calculate start position based on where the match starts let start_position = orig_position + mat.start(); // update cursor and set to end of match let end_position = orig_position + mat.end(); cursor.set(end_position); Some(start_position) } None => { cursor.set(orig_position + text.len()); None } } } /// Checks if a regular expression can match multiple lines. pub fn is_multiline_regex(regex: &str) -> bool { // regex characters that match line breaks // todo: currently multiline mode is ignored let multiline_indicators = vec![r"\n", r"\r", r"[[:space:]]"]; multiline_indicators.iter().any(|&i| regex.contains(i)) } /// Scan for a codepoint that, after conversion to lowercase, matches the probe. fn scan_lowercase(probe: char, s: &str) -> Option<usize> { for (i, c) in s.char_indices() { if c.to_lowercase().next().unwrap() == probe { return Some(i); } } None } #[cfg(test)] mod tests { use super::CaseMatching::{CaseInsensitive, Exact}; use super::*; use crate::rope::Rope; use crate::tree::Cursor; use regex::RegexBuilder; const REGEX_SIZE_LIMIT: usize = 1000000; #[test] fn find_small() { let a = Rope::from("Löwe 老虎 Léopard"); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(..); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", None), Some(0)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", None), Some(13)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Léopard", None), Some(13)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Léopard", None), None); c.set(0); // Note: these two characters both start with 0xE8 in utf-8 assert_eq!(find(&mut c, &mut raw_lines, Exact, "老虎", None), Some(6)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "老虎", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, Exact, "虎", None), Some(9)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "虎", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Tiger", None), None); } #[test] fn find_medium() { let mut s = String::new(); for _ in 0..4000 { s.push('x'); } s.push_str("Löwe 老虎 Léopard"); let a = Rope::from(&s); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", None), Some(4000)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", None), Some(4013)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Léopard", None), Some(4013)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Léopard", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, Exact, "老虎", None), Some(4006)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "老虎", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, Exact, "虎", None), Some(4009)); assert_eq!(find(&mut c, &mut raw_lines, Exact, "虎", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Tiger", None), None); } #[test] fn find_casei_small() { let a = Rope::from("Löwe 老虎 Léopard"); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "l", None), Some(0)); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "l", None), Some(13)); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "l", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "léopard", None), Some(13)); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "léopard", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "LÉOPARD", None), Some(13)); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "LÉOPARD", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "老虎", None), Some(6)); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "老虎", None), None); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "Tiger", None), None); } #[test] fn find_casei_ascii_nonalpha() { let a = Rope::from("![cfg(test)]"); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "(test)", None), Some(5)); c.set(0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "(TEST)", None), Some(5)); } #[test] fn find_casei_special() { let a = Rope::from("İ"); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "i̇", None), Some(0)); let a = Rope::from("i̇"); let mut c = Cursor::new(&a, 0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "İ", None), Some(0)); let a = Rope::from("\u{212A}"); let mut c = Cursor::new(&a, 0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "k", None), Some(0)); let a = Rope::from("k"); let mut c = Cursor::new(&a, 0); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "\u{212A}", None), Some(0)); } #[test] fn find_casei_0xc4() { let a = Rope::from("\u{0100}I"); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "i", None), Some(2)); } #[test] fn find_regex_small_casei() { let a = Rope::from("Löwe 老虎 Léopard\nSecond line"); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); let regex = RegexBuilder::new("L").size_limit(REGEX_SIZE_LIMIT).case_insensitive(true).build().ok(); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "L", regex.as_ref()), Some(0)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "L", regex.as_ref()), Some(13)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "L", regex.as_ref()), Some(29)); c.set(0); let regex = RegexBuilder::new("Léopard") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!( find(&mut c, &mut raw_lines, CaseInsensitive, "Léopard", regex.as_ref()), Some(13) ); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "Léopard", regex.as_ref()), None); c.set(0); let mut raw_lines = a.lines_raw(0..a.len()); let regex = RegexBuilder::new("老虎") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "老虎", regex.as_ref()), Some(6)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "老虎", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new("Tiger") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "Tiger", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new(".").size_limit(REGEX_SIZE_LIMIT).case_insensitive(true).build().ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, ".", regex.as_ref()), Some(0)); raw_lines = a.lines_raw(c.pos()..a.len()); let regex = RegexBuilder::new("\\s") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "\\s", regex.as_ref()), Some(5)); raw_lines = a.lines_raw(c.pos()..a.len()); let regex = RegexBuilder::new("\\sLéopard\n.*") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); assert_eq!( find(&mut c, &mut raw_lines, CaseInsensitive, "\\sLéopard\n.*", regex.as_ref()), Some(12) ); } #[test] fn find_regex_small() { let a = Rope::from("Löwe 老虎 Léopard\nSecond line"); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); let regex = RegexBuilder::new("L") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(false) .build() .ok(); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", regex.as_ref()), Some(0)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", regex.as_ref()), Some(13)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "L", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new("Léopard") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(false) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Léopard", regex.as_ref()), Some(13)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Léopard", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new("老虎") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(false) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "老虎", regex.as_ref()), Some(6)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "老虎", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new("Tiger") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(false) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, "Tiger", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new(".") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(false) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, Exact, ".", regex.as_ref()), Some(0)); raw_lines = a.lines_raw(c.pos()..a.len()); let regex = RegexBuilder::new("\\s") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(false) .build() .ok(); assert_eq!(find(&mut c, &mut raw_lines, Exact, "\\s", regex.as_ref()), Some(5)); raw_lines = a.lines_raw(c.pos()..a.len()); let regex = RegexBuilder::new("\\sLéopard\n.*") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(false) .build() .ok(); assert_eq!(find(&mut c, &mut raw_lines, Exact, "\\sLéopard\n.*", regex.as_ref()), Some(12)); } #[test] fn find_regex_medium() { let mut s = String::new(); for _ in 0..4000 { s.push('x'); } s.push_str("Löwe 老虎 Léopard\nSecond line"); let a = Rope::from(&s); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); let regex = RegexBuilder::new("L").size_limit(REGEX_SIZE_LIMIT).case_insensitive(true).build().ok(); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "L", regex.as_ref()), Some(4000)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "L", regex.as_ref()), Some(4013)); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "L", regex.as_ref()), Some(4029)); c.set(0); let mut raw_lines = a.lines_raw(0..a.len()); let regex = RegexBuilder::new("Léopard") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); assert_eq!( find(&mut c, &mut raw_lines, CaseInsensitive, "Léopard", regex.as_ref()), Some(4013) ); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "Léopard", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new("老虎") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!( find(&mut c, &mut raw_lines, CaseInsensitive, "老虎", regex.as_ref()), Some(4006) ); raw_lines = a.lines_raw(c.pos()..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "老虎", regex.as_ref()), None); c.set(0); let regex = RegexBuilder::new("Tiger") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); let mut raw_lines = a.lines_raw(0..a.len()); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, "Tiger", regex.as_ref()), None); c.set(0); let mut raw_lines = a.lines_raw(0..a.len()); let regex = RegexBuilder::new(".").size_limit(REGEX_SIZE_LIMIT).case_insensitive(true).build().ok(); assert_eq!(find(&mut c, &mut raw_lines, CaseInsensitive, ".", regex.as_ref()), Some(0)); raw_lines = a.lines_raw(c.pos()..a.len()); let regex = RegexBuilder::new("\\s") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); assert_eq!( find(&mut c, &mut raw_lines, CaseInsensitive, "\\s", regex.as_ref()), Some(4005) ); raw_lines = a.lines_raw(c.pos()..a.len()); let regex = RegexBuilder::new("\\sLéopard\n.*") .size_limit(REGEX_SIZE_LIMIT) .case_insensitive(true) .build() .ok(); assert_eq!( find(&mut c, &mut raw_lines, CaseInsensitive, "\\sLéopard\n.*", regex.as_ref()), Some(4012) ); } #[test] fn compare_cursor_regex_singleline() { let regex = Regex::new(r"^(\*+)(?: +(.*?))?[ \t]*$").unwrap(); let rope = Rope::from("** level 2 headline"); let mut c = Cursor::new(&rope, 0); let mut l = rope.lines_raw(c.pos()..rope.len()); assert!(compare_cursor_regex(&mut c, &mut l, regex.as_str(), &regex).is_some()); c.set(3); l = rope.lines_raw(c.pos()..rope.len()); assert!(compare_cursor_regex(&mut c, &mut l, regex.as_str(), &regex).is_none()); } #[test] fn compare_cursor_regex_multiline() { let regex = Regex::new( r"^[ \t]*:PROPERTIES:[ \t]*\n(?:[ \t]*:\S+:(?: .*)?[ \t]*\n)*?[ \t]*:END:[ \t]*\n", ) .unwrap(); // taken from http://doc.norang.ca/org-mode.html#DiaryForAppointments let s = "\ #+FILETAGS: PERSONAL\ \n* Appointments\ \n :PROPERTIES:\ \n :CATEGORY: Appt\ \n :ARCHIVE: %s_archive::* Appointments\ \n :END:\ \n** Holidays\ \n :PROPERTIES:\ \n :Category: Holiday\ \n :END:\ \n %%(org-calendar-holiday)\ \n** Some other Appointment\n"; let rope = Rope::from(s); let mut c = Cursor::new(&rope, 0); let mut l = rope.lines_raw(c.pos()..rope.len()); assert!(compare_cursor_regex(&mut c, &mut l, regex.as_str(), &regex).is_none()); // move to the next line after "* Appointments" c.set(36); l = rope.lines_raw(c.pos()..rope.len()); assert!(compare_cursor_regex(&mut c, &mut l, regex.as_str(), &regex).is_some()); assert_eq!(117, c.pos()); assert_eq!(Some('*'), c.next_codepoint()); // move to the next line after "** Holidays" c.set(129); l = rope.lines_raw(c.pos()..rope.len()); assert!(compare_cursor_regex(&mut c, &mut l, regex.as_str(), &regex).is_some()); c.next_codepoint(); c.next_codepoint(); c.next_codepoint(); assert_eq!(Some('%'), c.next_codepoint()); } #[test] fn compare_cursor_str_small() { let a = Rope::from("Löwe 老虎 Léopard"); let mut c = Cursor::new(&a, 0); let pat = "Löwe 老虎 Léopard"; let mut raw_lines = a.lines_raw(0..a.len()); assert!(compare_cursor_str(&mut c, &mut raw_lines, pat).is_some()); assert_eq!(c.pos(), pat.len()); c.set(0); let pat = "Löwe"; assert!(compare_cursor_str(&mut c, &mut raw_lines, pat).is_some()); assert_eq!(c.pos(), pat.len()); c.set(0); // Empty string is valid for compare_cursor_str (but not find) let pat = ""; assert!(compare_cursor_str(&mut c, &mut raw_lines, pat).is_some()); assert_eq!(c.pos(), pat.len()); c.set(0); assert!(compare_cursor_str(&mut c, &mut raw_lines, "Löwe 老虎 Léopardfoo").is_none()); } #[test] fn compare_cursor_str_medium() { let mut s = String::new(); for _ in 0..4000 { s.push('x'); } s.push_str("Löwe 老虎 Léopard"); let a = Rope::from(&s); let mut c = Cursor::new(&a, 0); let mut raw_lines = a.lines_raw(0..a.len()); assert!(compare_cursor_str(&mut c, &mut raw_lines, &s).is_some()); c.set(2000); assert!(compare_cursor_str(&mut c, &mut raw_lines, &s[2000..]).is_some()); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/spans.rs
rust/rope/src/spans.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A module for representing spans (in an interval tree), useful for rich text //! annotations. It is parameterized over a data type, so can be used for //! storing different annotations. use std::fmt; use std::marker::PhantomData; use std::mem; use crate::delta::{Delta, DeltaElement, Transformer}; use crate::interval::{Interval, IntervalBounds}; use crate::tree::{Cursor, Leaf, Node, NodeInfo, TreeBuilder}; const MIN_LEAF: usize = 32; const MAX_LEAF: usize = 64; pub type Spans<T> = Node<SpansInfo<T>>; #[derive(Clone)] pub struct Span<T: Clone> { iv: Interval, data: T, } #[derive(Clone)] pub struct SpansLeaf<T: Clone> { len: usize, // measured in base units spans: Vec<Span<T>>, } // It would be preferable to derive Default. // This would however require T to implement Default due to an issue in Rust. // See: https://github.com/rust-lang/rust/issues/26925 impl<T: Clone> Default for SpansLeaf<T> { fn default() -> Self { SpansLeaf { len: 0, spans: vec![] } } } #[derive(Clone)] pub struct SpansInfo<T> { n_spans: usize, iv: Interval, phantom: PhantomData<T>, } impl<T: Clone> Leaf for SpansLeaf<T> { fn len(&self) -> usize { self.len } fn is_ok_child(&self) -> bool { self.spans.len() >= MIN_LEAF } fn push_maybe_split(&mut self, other: &Self, iv: Interval) -> Option<Self> { let iv_start = iv.start(); for span in &other.spans { let span_iv = span.iv.intersect(iv).translate_neg(iv_start).translate(self.len); if !span_iv.is_empty() { self.spans.push(Span { iv: span_iv, data: span.data.clone() }); } } self.len += iv.size(); if self.spans.len() <= MAX_LEAF { None } else { let splitpoint = self.spans.len() / 2; // number of spans let splitpoint_units = self.spans[splitpoint].iv.start(); let mut new = self.spans.split_off(splitpoint); for span in &mut new { span.iv = span.iv.translate_neg(splitpoint_units); } let new_len = self.len - splitpoint_units; self.len = splitpoint_units; Some(SpansLeaf { len: new_len, spans: new }) } } } impl<T: Clone> NodeInfo for SpansInfo<T> { type L = SpansLeaf<T>; fn accumulate(&mut self, other: &Self) { self.n_spans += other.n_spans; self.iv = self.iv.union(other.iv); } fn compute_info(l: &SpansLeaf<T>) -> Self { let mut iv = Interval::new(0, 0); // should be Interval::default? for span in &l.spans { iv = iv.union(span.iv); } SpansInfo { n_spans: l.spans.len(), iv, phantom: PhantomData } } } pub struct SpansBuilder<T: Clone> { b: TreeBuilder<SpansInfo<T>>, leaf: SpansLeaf<T>, len: usize, total_len: usize, } impl<T: Clone> SpansBuilder<T> { pub fn new(total_len: usize) -> Self { SpansBuilder { b: TreeBuilder::new(), leaf: SpansLeaf::default(), len: 0, total_len } } // Precondition: spans must be added in nondecreasing start order. // Maybe take Span struct instead of separate iv, data args? pub fn add_span<IV: IntervalBounds>(&mut self, iv: IV, data: T) { let iv = iv.into_interval(self.total_len); if self.leaf.spans.len() == MAX_LEAF { let mut leaf = mem::take(&mut self.leaf); leaf.len = iv.start() - self.len; self.len = iv.start(); self.b.push(Node::from_leaf(leaf)); } self.leaf.spans.push(Span { iv: iv.translate_neg(self.len), data }) } // Would make slightly more implementation sense to take total_len as an argument // here, but that's not quite the usual builder pattern. pub fn build(mut self) -> Spans<T> { self.leaf.len = self.total_len - self.len; self.b.push(Node::from_leaf(self.leaf)); self.b.build() } } pub struct SpanIter<'a, T: 'a + Clone> { cursor: Cursor<'a, SpansInfo<T>>, ix: usize, } impl<T: Clone> Spans<T> { /// Perform operational transformation on a spans object intended to be edited into /// a sequence at the given offset. // Note: this implementation is not efficient for very large Spans objects, as it // traverses all spans linearly. A more sophisticated approach would be to traverse // the tree, and only delve into subtrees that are transformed. pub fn transform<N: NodeInfo>( &self, base_start: usize, base_end: usize, xform: &mut Transformer<N>, ) -> Self { // TODO: maybe should take base as an Interval and figure out "after" from that let new_start = xform.transform(base_start, false); let new_end = xform.transform(base_end, true); let mut builder = SpansBuilder::new(new_end - new_start); for (iv, data) in self.iter() { let start = xform.transform(iv.start() + base_start, false) - new_start; let end = xform.transform(iv.end() + base_start, false) - new_start; if start < end { let iv = Interval::new(start, end); // TODO: could imagine using a move iterator and avoiding clone, but it's not easy. builder.add_span(iv, data.clone()); } } builder.build() } /// Creates a new Spans instance by merging spans from `other` with `self`, /// using a closure to transform values. /// /// New spans are created from non-overlapping regions of existing spans, /// and by combining overlapping regions into new spans. In all cases, /// new values are generated by calling a closure that transforms the /// value of the existing span or spans. /// /// # Panics /// /// Panics if `self` and `other` have different lengths. /// pub fn merge<F, O>(&self, other: &Self, mut f: F) -> Spans<O> where F: FnMut(&T, Option<&T>) -> O, O: Clone, { //TODO: confirm that this is sensible behaviour assert_eq!(self.len(), other.len()); let mut sb = SpansBuilder::new(self.len()); // red/blue is just a better name than one/two or me/other let mut iter_red = self.iter(); let mut iter_blue = other.iter(); let mut next_red = iter_red.next(); let mut next_blue = iter_blue.next(); loop { // exit conditions: if next_red.is_none() && next_blue.is_none() { // all merged. break; } else if next_red.is_none() != next_blue.is_none() { // one side is exhausted; append remaining items from other side. let iter = if next_red.is_some() { iter_red } else { iter_blue }; // add this item let (iv, val) = next_red.or(next_blue).unwrap(); sb.add_span(iv, f(val, None)); for (iv, val) in iter { sb.add_span(iv, f(val, None)) } break; } // body: let (mut red_iv, red_val) = next_red.unwrap(); let (mut blue_iv, blue_val) = next_blue.unwrap(); if red_iv.intersect(blue_iv).is_empty() { // spans do not overlap. Add the leading span & advance that iter. if red_iv.is_before(blue_iv.start()) { sb.add_span(red_iv, f(red_val, None)); next_red = iter_red.next(); } else { sb.add_span(blue_iv, f(blue_val, None)); next_blue = iter_blue.next(); } continue; } assert!(!red_iv.intersect(blue_iv).is_empty()); // if these two spans do not share a start point, create a new span from // the prefix of the leading span. use std::cmp::Ordering; match red_iv.start().cmp(&blue_iv.start()) { Ordering::Less => { let iv = red_iv.prefix(blue_iv); sb.add_span(iv, f(red_val, None)); red_iv = red_iv.suffix(iv); } Ordering::Greater => { let iv = blue_iv.prefix(red_iv); sb.add_span(iv, f(blue_val, None)); blue_iv = blue_iv.suffix(iv); } Ordering::Equal => {} } assert!(red_iv.start() == blue_iv.start()); // create a new span by merging the overlapping regions. let iv = red_iv.intersect(blue_iv); assert!(!iv.is_empty()); sb.add_span(iv, f(red_val, Some(blue_val))); // if an old span was consumed by this new span, advance // else reuse remaining span (set next_red/blue) for the next loop iteration red_iv = red_iv.suffix(iv); blue_iv = blue_iv.suffix(iv); assert!(red_iv.is_empty() || blue_iv.is_empty()); if red_iv.is_empty() { next_red = iter_red.next(); } else { next_red = Some((red_iv, red_val)); } if blue_iv.is_empty() { next_blue = iter_blue.next(); } else { next_blue = Some((blue_iv, blue_val)); } } sb.build() } // possible future: an iterator that takes an interval, so results are the same as // taking a subseq on the spans object. Would require specialized Cursor. pub fn iter(&self) -> SpanIter<T> { SpanIter { cursor: Cursor::new(self, 0), ix: 0 } } /// Applies a generic delta to `self`, inserting empty spans for any /// added regions. /// /// This is intended to be used to keep spans up to date with a `Rope` /// as edits occur. pub fn apply_shape<M: NodeInfo>(&mut self, delta: &Delta<M>) { let mut b = TreeBuilder::new(); for elem in &delta.els { match *elem { DeltaElement::Copy(beg, end) => b.push(self.subseq(Interval::new(beg, end))), DeltaElement::Insert(ref n) => b.push(SpansBuilder::new(n.len()).build()), } } *self = b.build(); } /// Deletes all spans that intersect with `interval` and that come after. pub fn delete_after(&mut self, interval: Interval) { let mut builder = SpansBuilder::new(self.len()); for (iv, data) in self.iter() { // check if spans overlaps with interval if iv.intersect(interval).is_empty() { // keep the ones that are not overlapping builder.add_span(iv, data.clone()); } else { // all remaining spans are invalid break; } } *self = builder.build(); } } impl<T: Clone + fmt::Debug> fmt::Debug for Spans<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let strs = self.iter().map(|(iv, val)| format!("{}: {:?}", iv, val)).collect::<Vec<String>>(); write!(f, "len: {}\nspans:\n\t{}", self.len(), &strs.join("\n\t")) } } impl<'a, T: Clone> Iterator for SpanIter<'a, T> { type Item = (Interval, &'a T); fn next(&mut self) -> Option<(Interval, &'a T)> { if let Some((leaf, start_pos)) = self.cursor.get_leaf() { if leaf.spans.is_empty() { return None; } let leaf_start = self.cursor.pos() - start_pos; let span = &leaf.spans[self.ix]; self.ix += 1; if self.ix == leaf.spans.len() { let _ = self.cursor.next_leaf(); self.ix = 0; } return Some((span.iv.translate(leaf_start), &span.data)); } None } } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { // merging 1 1 1 1 1 1 1 1 1 16 // with 2 2 4 4 8 8 // == 3 3 5 5 1 1 9 9 1 16 let mut sb = SpansBuilder::new(10); sb.add_span(Interval::new(0, 9), 1u32); sb.add_span(Interval::new(9, 10), 16); let red = sb.build(); let mut sb = SpansBuilder::new(10); sb.add_span(Interval::new(0, 2), 2); sb.add_span(Interval::new(2, 4), 4); sb.add_span(Interval::new(6, 8), 8); let blue = sb.build(); let merged = red.merge(&blue, |r, b| b.map(|b| b + r).unwrap_or(*r)); let mut merged_iter = merged.iter(); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(0, 2)); assert_eq!(*val, 3); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(2, 4)); assert_eq!(*val, 5); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(4, 6)); assert_eq!(*val, 1); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(6, 8)); assert_eq!(*val, 9); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(8, 9)); assert_eq!(*val, 1); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(9, 10)); assert_eq!(*val, 16); assert!(merged_iter.next().is_none()); } #[test] fn test_merge_2() { // 1 1 1 4 4 // 2 2 2 2 8 9 let mut sb = SpansBuilder::new(9); sb.add_span(Interval::new(0, 3), 1); sb.add_span(Interval::new(4, 6), 4); let blue = sb.build(); let mut sb = SpansBuilder::new(9); sb.add_span(Interval::new(1, 5), 2); sb.add_span(Interval::new(7, 8), 8); sb.add_span(Interval::new(8, 9), 9); let red = sb.build(); let merged = red.merge(&blue, |r, b| b.map(|b| b + r).unwrap_or(*r)); let mut merged_iter = merged.iter(); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(0, 1)); assert_eq!(*val, 1); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(1, 3)); assert_eq!(*val, 3); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(3, 4)); assert_eq!(*val, 2); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(4, 5)); assert_eq!(*val, 6); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(5, 6)); assert_eq!(*val, 4); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(7, 8)); assert_eq!(*val, 8); let (iv, val) = merged_iter.next().unwrap(); assert_eq!(iv, Interval::new(8, 9)); assert_eq!(*val, 9); assert!(merged_iter.next().is_none()); } #[test] fn test_delete_after() { let mut sb = SpansBuilder::new(11); sb.add_span(Interval::new(1, 2), 2); sb.add_span(Interval::new(3, 5), 8); sb.add_span(Interval::new(6, 8), 9); sb.add_span(Interval::new(9, 10), 1); sb.add_span(Interval::new(10, 11), 1); let mut spans = sb.build(); spans.delete_after(Interval::new(4, 7)); assert_eq!(spans.iter().count(), 1); let (iv, val) = spans.iter().next().unwrap(); assert_eq!(iv, Interval::new(1, 2)); assert_eq!(*val, 2); } #[test] fn delete_after_big_at_start() { let mut sb = SpansBuilder::new(10); sb.add_span(0..10, 0); let mut spans = sb.build(); assert_eq!(spans.iter().count(), 1); spans.delete_after(Interval::new(1, 2)); assert_eq!(spans.iter().count(), 0); } #[test] fn delete_after_big_and_small() { let mut sb = SpansBuilder::new(10); sb.add_span(0..10, 0); sb.add_span(3..10, 1); let mut spans = sb.build(); assert_eq!(spans.iter().count(), 2); spans.delete_after(Interval::new(1, 2)); assert_eq!(spans.iter().count(), 0); } #[test] fn delete_after_empty() { let mut sb = SpansBuilder::new(10); sb.add_span(0..3, 0); let mut spans = sb.build(); assert_eq!(spans.iter().count(), 1); spans.delete_after(Interval::new(5, 7)); assert_eq!(spans.iter().count(), 1); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/breaks.rs
rust/rope/src/breaks.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A module for representing a set of breaks, typically used for //! storing the result of line breaking. use crate::interval::Interval; use crate::tree::{DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder}; use std::cmp::min; use std::mem; /// A set of indexes. A motivating use is storing line breaks. pub type Breaks = Node<BreaksInfo>; const MIN_LEAF: usize = 32; const MAX_LEAF: usize = 64; // Here the base units are arbitrary, but most commonly match the base units // of the rope storing the underlying string. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct BreaksLeaf { /// Length, in base units. len: usize, /// Indexes, represent as offsets from the start of the leaf. data: Vec<usize>, } /// The number of breaks. #[derive(Clone, Debug)] pub struct BreaksInfo(usize); impl Leaf for BreaksLeaf { fn len(&self) -> usize { self.len } fn is_ok_child(&self) -> bool { self.data.len() >= MIN_LEAF } fn push_maybe_split(&mut self, other: &BreaksLeaf, iv: Interval) -> Option<BreaksLeaf> { //eprintln!("push_maybe_split {:?} {:?} {}", self, other, iv); let (start, end) = iv.start_end(); for &v in &other.data { if start < v && v <= end { self.data.push(v - start + self.len); } } // the min with other.len() shouldn't be needed self.len += min(end, other.len()) - start; if self.data.len() <= MAX_LEAF { None } else { let splitpoint = self.data.len() / 2; // number of breaks let splitpoint_units = self.data[splitpoint - 1]; let mut new = self.data.split_off(splitpoint); for x in &mut new { *x -= splitpoint_units; } let new_len = self.len - splitpoint_units; self.len = splitpoint_units; Some(BreaksLeaf { len: new_len, data: new }) } } } impl NodeInfo for BreaksInfo { type L = BreaksLeaf; fn accumulate(&mut self, other: &Self) { self.0 += other.0; } fn compute_info(l: &BreaksLeaf) -> BreaksInfo { BreaksInfo(l.data.len()) } } impl DefaultMetric for BreaksInfo { type DefaultMetric = BreaksBaseMetric; } impl BreaksLeaf { /// Exposed for testing. #[doc(hidden)] pub fn get_data_cloned(&self) -> Vec<usize> { self.data.clone() } } #[derive(Copy, Clone)] pub struct BreaksMetric(()); impl Metric<BreaksInfo> for BreaksMetric { fn measure(info: &BreaksInfo, _: usize) -> usize { info.0 } fn to_base_units(l: &BreaksLeaf, in_measured_units: usize) -> usize { if in_measured_units > l.data.len() { l.len + 1 } else if in_measured_units == 0 { 0 } else { l.data[in_measured_units - 1] } } fn from_base_units(l: &BreaksLeaf, in_base_units: usize) -> usize { match l.data.binary_search(&in_base_units) { Ok(n) => n + 1, Err(n) => n, } } fn is_boundary(l: &BreaksLeaf, offset: usize) -> bool { l.data.binary_search(&offset).is_ok() } fn prev(l: &BreaksLeaf, offset: usize) -> Option<usize> { for i in 0..l.data.len() { if offset <= l.data[i] { if i == 0 { return None; } else { return Some(l.data[i - 1]); } } } l.data.last().cloned() } fn next(l: &BreaksLeaf, offset: usize) -> Option<usize> { let n = match l.data.binary_search(&offset) { Ok(n) => n + 1, Err(n) => n, }; if n == l.data.len() { None } else { Some(l.data[n]) } } fn can_fragment() -> bool { true } } #[derive(Copy, Clone)] pub struct BreaksBaseMetric(()); impl Metric<BreaksInfo> for BreaksBaseMetric { fn measure(_: &BreaksInfo, len: usize) -> usize { len } fn to_base_units(_: &BreaksLeaf, in_measured_units: usize) -> usize { in_measured_units } fn from_base_units(_: &BreaksLeaf, in_base_units: usize) -> usize { in_base_units } fn is_boundary(l: &BreaksLeaf, offset: usize) -> bool { BreaksMetric::is_boundary(l, offset) } fn prev(l: &BreaksLeaf, offset: usize) -> Option<usize> { BreaksMetric::prev(l, offset) } fn next(l: &BreaksLeaf, offset: usize) -> Option<usize> { BreaksMetric::next(l, offset) } fn can_fragment() -> bool { true } } // Additional functions specific to breaks impl Breaks { // a length with no break, useful in edit operations; for // other use cases, use the builder. pub fn new_no_break(len: usize) -> Breaks { let leaf = BreaksLeaf { len, data: vec![] }; Node::from_leaf(leaf) } } pub struct BreakBuilder { b: TreeBuilder<BreaksInfo>, leaf: BreaksLeaf, } impl Default for BreakBuilder { fn default() -> BreakBuilder { BreakBuilder { b: TreeBuilder::new(), leaf: BreaksLeaf::default() } } } impl BreakBuilder { pub fn new() -> BreakBuilder { BreakBuilder::default() } pub fn add_break(&mut self, len: usize) { if self.leaf.data.len() == MAX_LEAF { let leaf = mem::take(&mut self.leaf); self.b.push(Node::from_leaf(leaf)); } self.leaf.len += len; self.leaf.data.push(self.leaf.len); } pub fn add_no_break(&mut self, len: usize) { self.leaf.len += len; } pub fn build(mut self) -> Breaks { self.b.push(Node::from_leaf(self.leaf)); self.b.build() } } #[cfg(test)] mod tests { use crate::breaks::{BreakBuilder, BreaksInfo, BreaksLeaf, BreaksMetric}; use crate::interval::Interval; use crate::tree::{Cursor, Node}; fn gen(n: usize) -> Node<BreaksInfo> { let mut node = Node::default(); let mut b = BreakBuilder::new(); b.add_break(10); let testnode = b.build(); if n == 1 { return testnode; } for _ in 0..n { let len = node.len(); let empty_interval_at_end = Interval::new(len, len); node.edit(empty_interval_at_end, testnode.clone()); } node } #[test] fn empty() { let n = gen(0); assert_eq!(0, n.len()); } #[test] fn fromleaf() { let testnode = gen(1); assert_eq!(10, testnode.len()); } #[test] fn one() { let testleaf = BreaksLeaf { len: 10, data: vec![10] }; let testnode = Node::<BreaksInfo>::from_leaf(testleaf.clone()); assert_eq!(10, testnode.len()); let mut c = Cursor::new(&testnode, 0); assert_eq!(c.get_leaf().unwrap().0, &testleaf); assert_eq!(10, c.next::<BreaksMetric>().unwrap()); assert!(c.next::<BreaksMetric>().is_none()); c.set(0); assert!(!c.is_boundary::<BreaksMetric>()); c.set(1); assert!(!c.is_boundary::<BreaksMetric>()); c.set(10); assert!(c.is_boundary::<BreaksMetric>()); assert!(c.prev::<BreaksMetric>().is_none()); } #[test] fn concat() { let left = gen(1); let right = gen(1); let node = Node::concat(left, right); assert_eq!(node.len(), 20); let mut c = Cursor::new(&node, 0); assert_eq!(10, c.next::<BreaksMetric>().unwrap()); assert_eq!(20, c.next::<BreaksMetric>().unwrap()); assert!(c.next::<BreaksMetric>().is_none()); } #[test] fn larger() { let node = gen(100); assert_eq!(node.len(), 1000); } #[test] fn default_metric_test() { use super::BreaksBaseMetric; let breaks = gen(10); assert_eq!( breaks.convert_metrics::<BreaksBaseMetric, BreaksMetric>(5), breaks.count::<BreaksMetric>(5) ); assert_eq!( breaks.convert_metrics::<BreaksMetric, BreaksBaseMetric>(7), breaks.count_base_units::<BreaksMetric>(7) ); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/interval.rs
rust/rope/src/interval.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Closed-open intervals, and operations on them. //NOTE: intervals used to be more fancy, and could be open or closed on either //end. It may now be worth considering replacing intervals with Range<usize> or similar. use std::cmp::{max, min}; use std::fmt; use std::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; /// A fancy version of Range<usize>, representing a closed-open range; /// the interval [5, 7) is the set {5, 6}. /// /// It is an invariant that `start <= end`. An interval where `end < start` is /// considered empty. #[derive(Clone, Copy, PartialEq, Eq)] pub struct Interval { pub start: usize, pub end: usize, } impl Interval { /// Construct a new `Interval` representing the range [start..end). /// It is an invariant that `start <= end`. pub fn new(start: usize, end: usize) -> Interval { debug_assert!(start <= end); Interval { start, end } } #[deprecated(since = "0.3.0", note = "all intervals are now closed_open, use Interval::new")] pub fn new_closed_open(start: usize, end: usize) -> Interval { Self::new(start, end) } #[deprecated(since = "0.3.0", note = "all intervals are now closed_open")] pub fn new_open_closed(start: usize, end: usize) -> Interval { Self::new(start, end) } #[deprecated(since = "0.3.0", note = "all intervals are now closed_open")] pub fn new_closed_closed(start: usize, end: usize) -> Interval { Self::new(start, end) } #[deprecated(since = "0.3.0", note = "all intervals are now closed_open")] pub fn new_open_open(start: usize, end: usize) -> Interval { Self::new(start, end) } pub fn start(&self) -> usize { self.start } pub fn end(&self) -> usize { self.end } pub fn start_end(&self) -> (usize, usize) { (self.start, self.end) } // The following 3 methods define a trisection, exactly one is true. // (similar to std::cmp::Ordering, but "Equal" is not the same as "contains") /// the interval is before the point (the point is after the interval) pub fn is_before(&self, val: usize) -> bool { self.end <= val } /// the point is inside the interval pub fn contains(&self, val: usize) -> bool { self.start <= val && val < self.end } /// the interval is after the point (the point is before the interval) pub fn is_after(&self, val: usize) -> bool { self.start > val } pub fn is_empty(&self) -> bool { self.end <= self.start } // impl BitAnd would be completely valid for this pub fn intersect(&self, other: Interval) -> Interval { let start = max(self.start, other.start); let end = min(self.end, other.end); Interval { start, end: max(start, end) } } // smallest interval that encloses both inputs; if the inputs are // disjoint, then it fills in the hole. pub fn union(&self, other: Interval) -> Interval { if self.is_empty() { return other; } if other.is_empty() { return *self; } let start = min(self.start, other.start); let end = max(self.end, other.end); Interval { start, end } } // the first half of self - other pub fn prefix(&self, other: Interval) -> Interval { Interval { start: min(self.start, other.start), end: min(self.end, other.start) } } // the second half of self - other pub fn suffix(&self, other: Interval) -> Interval { Interval { start: max(self.start, other.end), end: max(self.end, other.end) } } // could impl Add trait, but that's probably too cute pub fn translate(&self, amount: usize) -> Interval { Interval { start: self.start + amount, end: self.end + amount } } // as above for Sub trait pub fn translate_neg(&self, amount: usize) -> Interval { debug_assert!(self.start >= amount); Interval { start: self.start - amount, end: self.end - amount } } // insensitive to open or closed ends, just the size of the interior pub fn size(&self) -> usize { self.end - self.start } } impl fmt::Display for Interval { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}, {})", self.start(), self.end()) } } impl fmt::Debug for Interval { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl From<Range<usize>> for Interval { fn from(src: Range<usize>) -> Interval { let Range { start, end } = src; Interval { start, end } } } impl From<RangeTo<usize>> for Interval { fn from(src: RangeTo<usize>) -> Interval { Interval::new(0, src.end) } } impl From<RangeInclusive<usize>> for Interval { fn from(src: RangeInclusive<usize>) -> Interval { Interval::new(*src.start(), src.end().saturating_add(1)) } } impl From<RangeToInclusive<usize>> for Interval { fn from(src: RangeToInclusive<usize>) -> Interval { Interval::new(0, src.end.saturating_add(1)) } } /// A trait for types that represent unbounded ranges; they need an explicit /// upper bound in order to be converted to `Interval`s. /// /// This exists so that some methods that use `Interval` under the hood can /// accept arguments like `..` or `10..`. /// /// This trait should only be used when the idea of taking all of something /// makes sense. pub trait IntervalBounds { fn into_interval(self, upper_bound: usize) -> Interval; } impl<T: Into<Interval>> IntervalBounds for T { fn into_interval(self, _upper_bound: usize) -> Interval { self.into() } } impl IntervalBounds for RangeFrom<usize> { fn into_interval(self, upper_bound: usize) -> Interval { Interval::new(self.start, upper_bound) } } impl IntervalBounds for RangeFull { fn into_interval(self, upper_bound: usize) -> Interval { Interval::new(0, upper_bound) } } #[cfg(test)] mod tests { use crate::interval::Interval; #[test] fn contains() { let i = Interval::new(2, 42); assert!(!i.contains(1)); assert!(i.contains(2)); assert!(i.contains(3)); assert!(i.contains(41)); assert!(!i.contains(42)); assert!(!i.contains(43)); } #[test] fn before() { let i = Interval::new(2, 42); assert!(!i.is_before(1)); assert!(!i.is_before(2)); assert!(!i.is_before(3)); assert!(!i.is_before(41)); assert!(i.is_before(42)); assert!(i.is_before(43)); } #[test] fn after() { let i = Interval::new(2, 42); assert!(i.is_after(1)); assert!(!i.is_after(2)); assert!(!i.is_after(3)); assert!(!i.is_after(41)); assert!(!i.is_after(42)); assert!(!i.is_after(43)); } #[test] fn translate() { let i = Interval::new(2, 42); assert_eq!(Interval::new(5, 45), i.translate(3)); assert_eq!(Interval::new(1, 41), i.translate_neg(1)); } #[test] fn empty() { assert!(Interval::new(0, 0).is_empty()); assert!(Interval::new(1, 1).is_empty()); assert!(!Interval::new(1, 2).is_empty()); } #[test] fn intersect() { assert_eq!(Interval::new(2, 3), Interval::new(1, 3).intersect(Interval::new(2, 4))); assert!(Interval::new(1, 2).intersect(Interval::new(2, 43)).is_empty()); } #[test] fn prefix() { assert_eq!(Interval::new(1, 2), Interval::new(1, 4).prefix(Interval::new(2, 3))); } #[test] fn suffix() { assert_eq!(Interval::new(3, 4), Interval::new(1, 4).suffix(Interval::new(2, 3))); } #[test] fn size() { assert_eq!(40, Interval::new(2, 42).size()); assert_eq!(0, Interval::new(1, 1).size()); assert_eq!(1, Interval::new(1, 2).size()); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/multiset.rs
rust/rope/src/multiset.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A data structure for representing multi-subsets of sequences (typically strings). use std::cmp; // These two imports are for the `apply` method only. use crate::interval::Interval; use crate::tree::{Node, NodeInfo, TreeBuilder}; use std::fmt; use std::slice; #[derive(Clone, PartialEq, Eq, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] struct Segment { len: usize, count: usize, } /// Represents a multi-subset of a string, that is a subset where elements can /// be included multiple times. This is represented as each element of the /// string having a "count" which is the number of times that element is /// included in the set. /// /// Internally, this is stored as a list of "segments" with a length and a count. #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Subset { /// Invariant, maintained by `SubsetBuilder`: all `Segment`s have non-zero /// length, and no `Segment` has the same count as the one before it. segments: Vec<Segment>, } #[derive(Default)] pub struct SubsetBuilder { segments: Vec<Segment>, total_len: usize, } impl SubsetBuilder { pub fn new() -> SubsetBuilder { SubsetBuilder::default() } /// Intended for use with `add_range` to ensure the total length of the /// `Subset` corresponds to the document length. pub fn pad_to_len(&mut self, total_len: usize) { if total_len > self.total_len { let cur_len = self.total_len; self.push_segment(total_len - cur_len, 0); } } /// Sets the count for a given range. This method must be called with a /// non-empty range with `begin` not before the largest range or segment added /// so far. Gaps will be filled with a 0-count segment. pub fn add_range(&mut self, begin: usize, end: usize, count: usize) { assert!(begin >= self.total_len, "ranges must be added in non-decreasing order"); // assert!(begin < end, "ranges added must be non-empty: [{},{})", begin, end); if begin >= end { return; } let len = end - begin; let cur_total_len = self.total_len; // add 0-count segment to fill any gap if begin > self.total_len { self.push_segment(begin - cur_total_len, 0); } self.push_segment(len, count); } /// Assign `count` to the next `len` elements in the string. /// Will panic if called with `len==0`. pub fn push_segment(&mut self, len: usize, count: usize) { assert!(len > 0, "can't push empty segment"); self.total_len += len; // merge into previous segment if possible if let Some(last) = self.segments.last_mut() { if last.count == count { last.len += len; return; } } self.segments.push(Segment { len, count }); } pub fn build(self) -> Subset { Subset { segments: self.segments } } } /// Determines which elements of a `Subset` a method applies to /// based on the count of the element. #[derive(Clone, Copy, Debug)] pub enum CountMatcher { Zero, NonZero, All, } impl CountMatcher { fn matches(self, seg: &Segment) -> bool { match self { CountMatcher::Zero => (seg.count == 0), CountMatcher::NonZero => (seg.count != 0), CountMatcher::All => true, } } } impl Subset { /// Creates an empty `Subset` of a string of length `len` pub fn new(len: usize) -> Subset { let mut sb = SubsetBuilder::new(); sb.pad_to_len(len); sb.build() } /// Mostly for testing. pub fn delete_from_string(&self, s: &str) -> String { let mut result = String::new(); for (b, e) in self.range_iter(CountMatcher::Zero) { result.push_str(&s[b..e]); } result } // Maybe Subset should be a pure data structure and this method should // be a method of Node. /// Builds a version of `s` with all the elements in this `Subset` deleted from it. pub fn delete_from<N: NodeInfo>(&self, s: &Node<N>) -> Node<N> { let mut b = TreeBuilder::new(); for (beg, end) in self.range_iter(CountMatcher::Zero) { b.push_slice(s, Interval::new(beg, end)); } b.build() } /// The length of the resulting sequence after deleting this subset. A /// convenience alias for `self.count(CountMatcher::Zero)` to reduce /// thinking about what that means in the cases where the length after /// delete is what you want to know. /// /// `self.delete_from_string(s).len() = self.len(s.len())` pub fn len_after_delete(&self) -> usize { self.count(CountMatcher::Zero) } /// Count the total length of all the segments matching `matcher`. pub fn count(&self, matcher: CountMatcher) -> usize { self.segments.iter().filter(|seg| matcher.matches(seg)).map(|seg| seg.len).sum() } /// Convenience alias for `self.count(CountMatcher::All)` pub fn len(&self) -> usize { self.count(CountMatcher::All) } /// Determine whether the subset is empty. /// In this case deleting it would do nothing. pub fn is_empty(&self) -> bool { (self.segments.is_empty()) || ((self.segments.len() == 1) && (self.segments[0].count == 0)) } /// Compute the union of two subsets. The count of an element in the /// result is the sum of the counts in the inputs. pub fn union(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count + zseg.b_count); } sb.build() } /// Compute the difference of two subsets. The count of an element in the /// result is the subtraction of the counts of other from self. pub fn subtract(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { assert!( zseg.a_count >= zseg.b_count, "can't subtract {} from {}", zseg.a_count, zseg.b_count ); sb.push_segment(zseg.len, zseg.a_count - zseg.b_count); } sb.build() } /// Compute the bitwise xor of two subsets, useful as a reversible /// difference. The count of an element in the result is the bitwise xor /// of the counts of the inputs. Unchanged segments will be 0. /// /// This works like set symmetric difference when all counts are 0 or 1 /// but it extends nicely to the case of larger counts. pub fn bitxor(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); for zseg in self.zip(other) { sb.push_segment(zseg.len, zseg.a_count ^ zseg.b_count); } sb.build() } /// Map the contents of `self` into the 0-regions of `other`. /// Precondition: `self.count(CountMatcher::All) == other.count(CountMatcher::Zero)` fn transform(&self, other: &Subset, union: bool) -> Subset { let mut sb = SubsetBuilder::new(); let mut seg_iter = self.segments.iter(); let mut cur_seg = Segment { len: 0, count: 0 }; for oseg in &other.segments { if oseg.count > 0 { sb.push_segment(oseg.len, if union { oseg.count } else { 0 }); } else { // fill 0-region with segments from self. let mut to_be_consumed = oseg.len; while to_be_consumed > 0 { if cur_seg.len == 0 { cur_seg = seg_iter .next() .expect("self must cover all 0-regions of other") .clone(); } // consume as much of the segment as possible and necessary let to_consume = cmp::min(cur_seg.len, to_be_consumed); sb.push_segment(to_consume, cur_seg.count); to_be_consumed -= to_consume; cur_seg.len -= to_consume; } } } assert_eq!(cur_seg.len, 0, "the 0-regions of other must be the size of self"); assert_eq!(seg_iter.next(), None, "the 0-regions of other must be the size of self"); sb.build() } /// Transform through coordinate transform represented by other. /// The equation satisfied is as follows: /// /// s1 = other.delete_from_string(s0) /// /// s2 = self.delete_from_string(s1) /// /// element in self.transform_expand(other).delete_from_string(s0) if (not in s1) or in s2 pub fn transform_expand(&self, other: &Subset) -> Subset { self.transform(other, false) } /// The same as taking transform_expand and then unioning with `other`. pub fn transform_union(&self, other: &Subset) -> Subset { self.transform(other, true) } /// Transform subset through other coordinate transform, shrinking. /// The following equation is satisfied: /// /// C = A.transform_expand(B) /// /// B.transform_shrink(C).delete_from_string(C.delete_from_string(s)) = /// A.delete_from_string(B.delete_from_string(s)) pub fn transform_shrink(&self, other: &Subset) -> Subset { let mut sb = SubsetBuilder::new(); // discard ZipSegments where the shrinking set has positive count for zseg in self.zip(other) { // TODO: should this actually do something like subtract counts? if zseg.b_count == 0 { sb.push_segment(zseg.len, zseg.a_count); } } sb.build() } /// Return an iterator over the ranges with a count matching the `matcher`. /// These will often be easier to work with than raw segments. pub fn range_iter(&self, matcher: CountMatcher) -> RangeIter { RangeIter { seg_iter: self.segments.iter(), consumed: 0, matcher } } /// Convenience alias for `self.range_iter(CountMatcher::Zero)`. /// Semantically iterates the ranges of the complement of this `Subset`. pub fn complement_iter(&self) -> RangeIter { self.range_iter(CountMatcher::Zero) } /// Return an iterator over `ZipSegment`s where each `ZipSegment` contains /// the count for both self and other in that range. The two `Subset`s /// must have the same total length. /// /// Each returned `ZipSegment` will differ in at least one count. pub fn zip<'a>(&'a self, other: &'a Subset) -> ZipIter<'a> { ZipIter { a_segs: self.segments.as_slice(), b_segs: other.segments.as_slice(), a_i: 0, b_i: 0, a_consumed: 0, b_consumed: 0, consumed: 0, } } /// Find the complement of this Subset. Every 0-count element will have a /// count of 1 and every non-zero element will have a count of 0. pub fn complement(&self) -> Subset { let mut sb = SubsetBuilder::new(); for seg in &self.segments { if seg.count == 0 { sb.push_segment(seg.len, 1); } else { sb.push_segment(seg.len, 0); } } sb.build() } /// Return a `Mapper` that can be use to map coordinates in the document to coordinates /// in this `Subset`, but only in non-decreasing order for performance reasons. pub fn mapper(&self, matcher: CountMatcher) -> Mapper { Mapper { range_iter: self.range_iter(matcher), last_i: 0, // indices only need to be in non-decreasing order, not increasing cur_range: (0, 0), // will immediately try to consume next range subset_amount_consumed: 0, } } } impl fmt::Debug for Subset { /// Use the alternate flag (`#`) to print a more compact representation /// where each character represents the count of one element: /// '-' is 0, '#' is 1, 2-9 are digits, `+` is >9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if f.alternate() { for s in &self.segments { let chr = if s.count == 0 { '-' } else if s.count == 1 { '#' } else if s.count <= 9 { ((s.count as u8) + b'0') as char } else { '+' }; for _ in 0..s.len { write!(f, "{}", chr)?; } } Ok(()) } else { f.debug_tuple("Subset").field(&self.segments).finish() } } } pub struct RangeIter<'a> { seg_iter: slice::Iter<'a, Segment>, pub consumed: usize, matcher: CountMatcher, } impl<'a> Iterator for RangeIter<'a> { type Item = (usize, usize); fn next(&mut self) -> Option<(usize, usize)> { for seg in &mut self.seg_iter { self.consumed += seg.len; if self.matcher.matches(seg) { return Some((self.consumed - seg.len, self.consumed)); } } None } } /// See `Subset::zip` pub struct ZipIter<'a> { a_segs: &'a [Segment], b_segs: &'a [Segment], a_i: usize, b_i: usize, a_consumed: usize, b_consumed: usize, pub consumed: usize, } /// See `Subset::zip` #[derive(Clone, Debug)] pub struct ZipSegment { len: usize, a_count: usize, b_count: usize, } impl<'a> Iterator for ZipIter<'a> { type Item = ZipSegment; /// Consume as far as possible from `self.consumed` until reaching a /// segment boundary in either `Subset`, and return the resulting /// `ZipSegment`. Will panic if it reaches the end of one `Subset` before /// the other, that is when they have different total length. fn next(&mut self) -> Option<ZipSegment> { match (self.a_segs.get(self.a_i), self.b_segs.get(self.b_i)) { (None, None) => None, (None, Some(_)) | (Some(_), None) => { panic!("can't zip Subsets of different base lengths.") } ( Some(&Segment { len: a_len, count: a_count }), Some(&Segment { len: b_len, count: b_count }), ) => { let len = match (a_len + self.a_consumed).cmp(&(b_len + self.b_consumed)) { cmp::Ordering::Equal => { self.a_consumed += a_len; self.a_i += 1; self.b_consumed += b_len; self.b_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Less => { self.a_consumed += a_len; self.a_i += 1; self.a_consumed - self.consumed } cmp::Ordering::Greater => { self.b_consumed += b_len; self.b_i += 1; self.b_consumed - self.consumed } }; self.consumed += len; Some(ZipSegment { len, a_count, b_count }) } } } } pub struct Mapper<'a> { range_iter: RangeIter<'a>, // Not actually necessary for computation, just for dynamic checking of invariant last_i: usize, cur_range: (usize, usize), pub subset_amount_consumed: usize, } impl<'a> Mapper<'a> { /// Map a coordinate in the document this subset corresponds to, to a /// coordinate in the subset matched by the `CountMatcher`. For example, /// if the Subset is a set of deletions and the matcher is /// `CountMatcher::NonZero`, this would map indices in the union string to /// indices in the tombstones string. /// /// Will return the closest coordinate in the subset if the index is not /// in the subset. If the coordinate is past the end of the subset it will /// return one more than the largest index in the subset (i.e the length). /// This behaviour is suitable for mapping closed-open intervals in a /// string to intervals in a subset of the string. /// /// In order to guarantee good performance, this method must be called /// with `i` values in non-decreasing order or it will panic. This allows /// the total cost to be O(n) where `n = max(calls,ranges)` over all times /// called on a single `Mapper`. pub fn doc_index_to_subset(&mut self, i: usize) -> usize { assert!( i >= self.last_i, "method must be called with i in non-decreasing order. i={}<{}=last_i", i, self.last_i ); self.last_i = i; while i >= self.cur_range.1 { self.subset_amount_consumed += self.cur_range.1 - self.cur_range.0; self.cur_range = match self.range_iter.next() { Some(range) => range, // past the end of the subset None => { // ensure we don't try to consume any more self.cur_range = (usize::max_value(), usize::max_value()); return self.subset_amount_consumed; } } } if i >= self.cur_range.0 { let dist_in_range = i - self.cur_range.0; dist_in_range + self.subset_amount_consumed } else { // not in the subset self.subset_amount_consumed } } } #[cfg(test)] mod tests { use crate::multiset::*; use crate::test_helpers::find_deletions; const TEST_STR: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; #[test] fn test_apply() { let mut sb = SubsetBuilder::new(); for &(b, e) in &[ (0, 1), (2, 4), (6, 11), (13, 14), (15, 18), (19, 23), (24, 26), (31, 32), (33, 35), (36, 37), (40, 44), (45, 48), (49, 51), (52, 57), (58, 59), ] { sb.add_range(b, e, 1); } sb.pad_to_len(TEST_STR.len()); let s = sb.build(); println!("{:?}", s); assert_eq!("145BCEINQRSTUWZbcdimpvxyz", s.delete_from_string(TEST_STR)); } #[test] fn trivial() { let s = SubsetBuilder::new().build(); assert!(s.is_empty()); } #[test] fn test_find_deletions() { let substr = "015ABDFHJOPQVYdfgloprsuvz"; let s = find_deletions(substr, TEST_STR); assert_eq!(substr, s.delete_from_string(TEST_STR)); assert!(!s.is_empty()) } #[test] fn test_complement() { let substr = "0456789DEFGHIJKLMNOPQRSTUVWXYZdefghijklmnopqrstuvw"; let s = find_deletions(substr, TEST_STR); let c = s.complement(); // deleting the complement of the deletions we found should yield the deletions assert_eq!("123ABCabcxyz", c.delete_from_string(TEST_STR)); } #[test] fn test_mapper() { let substr = "469ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwz"; let s = find_deletions(substr, TEST_STR); let mut m = s.mapper(CountMatcher::NonZero); // subset is {0123 5 78 xy} assert_eq!(0, m.doc_index_to_subset(0)); assert_eq!(2, m.doc_index_to_subset(2)); assert_eq!(2, m.doc_index_to_subset(2)); assert_eq!(3, m.doc_index_to_subset(3)); assert_eq!(4, m.doc_index_to_subset(4)); // not in subset assert_eq!(4, m.doc_index_to_subset(5)); assert_eq!(5, m.doc_index_to_subset(7)); assert_eq!(6, m.doc_index_to_subset(8)); assert_eq!(6, m.doc_index_to_subset(8)); assert_eq!(8, m.doc_index_to_subset(60)); assert_eq!(9, m.doc_index_to_subset(61)); // not in subset assert_eq!(9, m.doc_index_to_subset(62)); // not in subset } #[test] #[should_panic(expected = "non-decreasing")] fn test_mapper_requires_non_decreasing() { let substr = "469ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw"; let s = find_deletions(substr, TEST_STR); let mut m = s.mapper(CountMatcher::NonZero); m.doc_index_to_subset(0); m.doc_index_to_subset(2); m.doc_index_to_subset(1); } #[test] fn union() { let s1 = find_deletions("024AEGHJKNQTUWXYZabcfgikqrvy", TEST_STR); let s2 = find_deletions("14589DEFGIKMOPQRUXZabcdefglnpsuxyz", TEST_STR); assert_eq!("4EGKQUXZabcfgy", s1.union(&s2).delete_from_string(TEST_STR)); } fn transform_case(str1: &str, str2: &str, result: &str) { let s1 = find_deletions(str1, TEST_STR); let s2 = find_deletions(str2, str1); let s3 = s2.transform_expand(&s1); let str3 = s3.delete_from_string(TEST_STR); assert_eq!(result, str3); assert_eq!(str2, s1.transform_shrink(&s3).delete_from_string(&str3)); assert_eq!(str2, s2.transform_union(&s1).delete_from_string(TEST_STR)); } #[test] fn transform() { transform_case( "02345678BCDFGHKLNOPQRTUVXZbcefghjlmnopqrstwx", "027CDGKLOTUbcegopqrw", "01279ACDEGIJKLMOSTUWYabcdegikopqruvwyz", ); transform_case( "01234678DHIKLMNOPQRUWZbcdhjostvy", "136KLPQZvy", "13569ABCEFGJKLPQSTVXYZaefgiklmnpqruvwxyz", ); transform_case( "0125789BDEFIJKLMNPVXabdjmrstuwy", "12BIJVXjmrstu", "12346ABCGHIJOQRSTUVWXYZcefghijklmnopqrstuvxz", ); transform_case( "12456789ABCEFGJKLMNPQRSTUVXYadefghkrtwxz", "15ACEFGKLPRUVYdhrtx", "0135ACDEFGHIKLOPRUVWYZbcdhijlmnopqrstuvxy", ); transform_case( "0128ABCDEFGIJMNOPQXYZabcfgijkloqruvy", "2CEFGMZabijloruvy", "2345679CEFGHKLMRSTUVWZabdehijlmnoprstuvwxyz", ); transform_case( "01245689ABCDGJKLMPQSTWXYbcdfgjlmnosvy", "01245ABCDJLQSWXYgsv", "0123457ABCDEFHIJLNOQRSUVWXYZaeghikpqrstuvwxz", ); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/serde_impls.rs
rust/rope/src/serde_impls.rs
// Copyright 2019 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt; use std::str::FromStr; use serde::de::{self, Deserialize, Deserializer, Visitor}; use serde::ser::{Serialize, SerializeStruct, SerializeTupleVariant, Serializer}; use crate::tree::Node; use crate::{Delta, DeltaElement, Rope, RopeInfo}; impl Serialize for Rope { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&String::from(self)) } } impl<'de> Deserialize<'de> for Rope { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_str(RopeVisitor) } } struct RopeVisitor; impl<'de> Visitor<'de> for RopeVisitor { type Value = Rope; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a string") } fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> where E: de::Error, { Rope::from_str(s).map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self)) } } impl Serialize for DeltaElement<RopeInfo> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { DeltaElement::Copy(ref start, ref end) => { let mut el = serializer.serialize_tuple_variant("DeltaElement", 0, "copy", 2)?; el.serialize_field(start)?; el.serialize_field(end)?; el.end() } DeltaElement::Insert(ref node) => { serializer.serialize_newtype_variant("DeltaElement", 1, "insert", node) } } } } impl Serialize for Delta<RopeInfo> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut delta = serializer.serialize_struct("Delta", 2)?; delta.serialize_field("els", &self.els)?; delta.serialize_field("base_len", &self.base_len)?; delta.end() } } impl<'de> Deserialize<'de> for Delta<RopeInfo> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { // NOTE: we derive to an interim representation and then convert // that into our actual target. #[derive(Serialize, Deserialize)] #[serde(rename_all = "snake_case")] enum RopeDeltaElement_ { Copy(usize, usize), Insert(Node<RopeInfo>), } #[derive(Serialize, Deserialize)] struct RopeDelta_ { els: Vec<RopeDeltaElement_>, base_len: usize, } impl From<RopeDeltaElement_> for DeltaElement<RopeInfo> { fn from(elem: RopeDeltaElement_) -> DeltaElement<RopeInfo> { match elem { RopeDeltaElement_::Copy(start, end) => DeltaElement::Copy(start, end), RopeDeltaElement_::Insert(rope) => DeltaElement::Insert(rope), } } } impl From<RopeDelta_> for Delta<RopeInfo> { fn from(mut delta: RopeDelta_) -> Delta<RopeInfo> { Delta { els: delta.els.drain(..).map(DeltaElement::from).collect(), base_len: delta.base_len, } } } let d = RopeDelta_::deserialize(deserializer)?; Ok(Delta::from(d)) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/compare.rs
rust/rope/src/compare.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Fast comparison of rope regions, principally for diffing. use crate::rope::{BaseMetric, Rope, RopeInfo}; use crate::tree::Cursor; #[allow(dead_code)] const SSE_STRIDE: usize = 16; /// Given two 16-byte slices, returns a bitmask where the 1 bits indicate /// the positions of non-equal bytes. /// /// The least significant bit in the mask refers to the byte in position 0; /// that is, you read the mask right to left. /// /// # Examples /// /// ``` /// # use xi_rope::compare::sse_compare_mask; /// # if is_x86_feature_detected!("sse4.2") { /// let one = "aaaaaaaaaaaaaaaa"; /// let two = "aa3aaaaa9aaaEaaa"; /// let exp = "0001000100000100"; /// let mask = unsafe { sse_compare_mask(one.as_bytes(), two.as_bytes()) }; /// let result = format!("{:016b}", mask); /// assert_eq!(result.as_str(), exp); /// # } /// ``` /// #[allow(clippy::cast_ptr_alignment, clippy::unreadable_literal)] #[doc(hidden)] #[cfg(target_arch = "x86_64")] #[target_feature(enable = "sse4.2")] pub unsafe fn sse_compare_mask(one: &[u8], two: &[u8]) -> i32 { use std::arch::x86_64::*; // too lazy to figure out the bit-fiddly way to get this mask const HIGH_HALF_MASK: u32 = 0b11111111111111110000000000000000; debug_assert!(is_x86_feature_detected!("sse4.2")); let onev = _mm_loadu_si128(one.as_ptr() as *const _); let twov = _mm_loadu_si128(two.as_ptr() as *const _); let mask = _mm_cmpeq_epi8(onev, twov); (!_mm_movemask_epi8(mask)) ^ HIGH_HALF_MASK as i32 } #[allow(dead_code)] const AVX_STRIDE: usize = 32; /// Like above but with 32 byte slices #[allow(clippy::cast_ptr_alignment, clippy::unreadable_literal)] #[doc(hidden)] #[cfg(target_arch = "x86_64")] #[target_feature(enable = "avx2")] pub unsafe fn avx_compare_mask(one: &[u8], two: &[u8]) -> i32 { use std::arch::x86_64::*; let onev = _mm256_loadu_si256(one.as_ptr() as *const _); let twov = _mm256_loadu_si256(two.as_ptr() as *const _); let mask = _mm256_cmpeq_epi8(onev, twov); !_mm256_movemask_epi8(mask) } /// Returns the lowest `i` for which `one[i] != two[i]`, if one exists. pub fn ne_idx(one: &[u8], two: &[u8]) -> Option<usize> { #[cfg(target_arch = "x86_64")] { if is_x86_feature_detected!("avx2") { return unsafe { ne_idx_avx(one, two) }; } else if is_x86_feature_detected!("sse4.2") { return unsafe { ne_idx_sse(one, two) }; } } ne_idx_fallback(one, two) } /// Returns the lowest `i` such that `one[one.len()-i] != two[two.len()-i]`, /// if one exists. pub fn ne_idx_rev(one: &[u8], two: &[u8]) -> Option<usize> { #[cfg(target_arch = "x86_64")] { if is_x86_feature_detected!("sse4.2") { return unsafe { ne_idx_rev_sse(one, two) }; } } ne_idx_rev_fallback(one, two) } #[doc(hidden)] #[cfg(target_arch = "x86_64")] #[target_feature(enable = "avx2")] pub unsafe fn ne_idx_avx(one: &[u8], two: &[u8]) -> Option<usize> { let min_len = one.len().min(two.len()); let mut idx = 0; while idx < min_len { let stride_len = AVX_STRIDE.min(min_len - idx); let mask = avx_compare_mask( one.get_unchecked(idx..idx + stride_len), two.get_unchecked(idx..idx + stride_len), ); // at the end of the slice the mask might include garbage bytes, so // we ignore matches that are OOB if mask != 0 && idx + (mask.trailing_zeros() as usize) < min_len { return Some(idx + mask.trailing_zeros() as usize); } idx += AVX_STRIDE; } None } #[doc(hidden)] #[cfg(target_arch = "x86_64")] #[target_feature(enable = "sse4.2")] pub unsafe fn ne_idx_sse(one: &[u8], two: &[u8]) -> Option<usize> { let min_len = one.len().min(two.len()); let mut idx = 0; while idx < min_len { let stride_len = SSE_STRIDE.min(min_len - idx); let mask = sse_compare_mask( one.get_unchecked(idx..idx + stride_len), two.get_unchecked(idx..idx + stride_len), ); if mask != 0 && idx + (mask.trailing_zeros() as usize) < min_len { return Some(idx + mask.trailing_zeros() as usize); } idx += SSE_STRIDE; } None } #[doc(hidden)] #[cfg(target_arch = "x86_64")] #[target_feature(enable = "sse4.2")] pub unsafe fn ne_idx_rev_sse(one: &[u8], two: &[u8]) -> Option<usize> { let min_len = one.len().min(two.len()); let one = &one[one.len() - min_len..]; let two = &two[two.len() - min_len..]; debug_assert_eq!(one.len(), two.len()); let mut idx = min_len; loop { let mask = if idx < SSE_STRIDE { let mut one_buf: [u8; SSE_STRIDE] = [0; SSE_STRIDE]; let mut two_buf: [u8; SSE_STRIDE] = [0; SSE_STRIDE]; one_buf[SSE_STRIDE - idx..].copy_from_slice(&one[..idx]); two_buf[SSE_STRIDE - idx..].copy_from_slice(&two[..idx]); sse_compare_mask(&one_buf, &two_buf) } else { sse_compare_mask(&one[idx - SSE_STRIDE..idx], &two[idx - SSE_STRIDE..idx]) }; let i = mask.leading_zeros() as usize - SSE_STRIDE; if i != SSE_STRIDE { return Some(min_len - (idx - i)); } if idx < SSE_STRIDE { break; } idx -= SSE_STRIDE; } None } #[inline] #[allow(dead_code)] #[doc(hidden)] pub fn ne_idx_fallback(one: &[u8], two: &[u8]) -> Option<usize> { one.iter().zip(two.iter()).position(|(a, b)| a != b) } #[inline] #[allow(dead_code)] #[doc(hidden)] pub fn ne_idx_rev_fallback(one: &[u8], two: &[u8]) -> Option<usize> { one.iter().rev().zip(two.iter().rev()).position(|(a, b)| a != b) } /// Utility for efficiently comparing two ropes. pub struct RopeScanner<'a> { base: Cursor<'a, RopeInfo>, target: Cursor<'a, RopeInfo>, base_chunk: &'a str, target_chunk: &'a str, scanned: usize, } impl<'a> RopeScanner<'a> { pub fn new(base: &'a Rope, target: &'a Rope) -> Self { RopeScanner { base: Cursor::new(base, 0), target: Cursor::new(target, 0), base_chunk: "", target_chunk: "", scanned: 0, } } /// Starting from the two provided offsets in the corresponding ropes, /// Returns the distance, moving backwards, to the first non-equal codepoint. /// If no such position exists, returns the distance to the closest 0 offset. /// /// if `stop` is not None, the scan will stop at if it reaches this value. /// /// # Examples /// /// ``` /// # use xi_rope::compare::RopeScanner; /// # use xi_rope::Rope; /// /// let one = Rope::from("hiii"); /// let two = Rope::from("siii"); /// let mut scanner = RopeScanner::new(&one, &two); /// assert_eq!(scanner.find_ne_char_back(one.len(), two.len(), None), 3); /// assert_eq!(scanner.find_ne_char_back(one.len(), two.len(), 2), 2); /// ``` pub fn find_ne_char_back<T>(&mut self, base_off: usize, targ_off: usize, stop: T) -> usize where T: Into<Option<usize>>, { let stop = stop.into().unwrap_or(usize::max_value()); self.base.set(base_off); self.target.set(targ_off); self.scanned = 0; let (base_leaf, base_leaf_off) = self.base.get_leaf().unwrap(); let (target_leaf, target_leaf_off) = self.target.get_leaf().unwrap(); debug_assert!(self.target.is_boundary::<BaseMetric>()); debug_assert!(self.base.is_boundary::<BaseMetric>()); debug_assert!(base_leaf.is_char_boundary(base_leaf_off)); debug_assert!(target_leaf.is_char_boundary(target_leaf_off)); self.base_chunk = &base_leaf[..base_leaf_off]; self.target_chunk = &target_leaf[..target_leaf_off]; loop { if let Some(mut idx) = ne_idx_rev(self.base_chunk.as_bytes(), self.target_chunk.as_bytes()) { // find nearest codepoint boundary while idx > 1 && !self.base_chunk.is_char_boundary(self.base_chunk.len() - idx) { idx -= 1; } return stop.min(self.scanned + idx); } let scan_len = self.target_chunk.len().min(self.base_chunk.len()); self.base_chunk = &self.base_chunk[..self.base_chunk.len() - scan_len]; self.target_chunk = &self.target_chunk[..self.target_chunk.len() - scan_len]; self.scanned += scan_len; if stop <= self.scanned { break; } self.load_prev_chunk(); if self.base_chunk.is_empty() || self.target_chunk.is_empty() { break; } } stop.min(self.scanned) } /// Starting from the two provided offsets into the two ropes, returns /// the distance (in bytes) to the first non-equal codepoint. If no such /// position exists, returns the shortest distance to the end of a rope. /// /// This can be thought of as the length of the longest common substring /// between `base[base_off..]` and `target[targ_off..]`. /// /// if `stop` is not None, the scan will stop at if it reaches this value. /// /// # Examples /// /// ``` /// # use xi_rope::compare::RopeScanner; /// # use xi_rope::Rope; /// /// let one = Rope::from("uh-oh🙈"); /// let two = Rope::from("uh-oh🙉"); /// let mut scanner = RopeScanner::new(&one, &two); /// assert_eq!(scanner.find_ne_char(0, 0, None), 5); /// assert_eq!(scanner.find_ne_char(0, 0, 3), 3); /// ``` pub fn find_ne_char<T>(&mut self, base_off: usize, targ_off: usize, stop: T) -> usize where T: Into<Option<usize>>, { let stop = stop.into().unwrap_or(usize::max_value()); self.base.set(base_off); self.target.set(targ_off); self.scanned = 0; let (base_leaf, base_leaf_off) = self.base.get_leaf().unwrap(); let (target_leaf, target_leaf_off) = self.target.get_leaf().unwrap(); debug_assert!(base_leaf.is_char_boundary(base_leaf_off)); debug_assert!(target_leaf.is_char_boundary(target_leaf_off)); self.base_chunk = &base_leaf[base_leaf_off..]; self.target_chunk = &target_leaf[target_leaf_off..]; loop { if let Some(mut idx) = ne_idx(self.base_chunk.as_bytes(), self.target_chunk.as_bytes()) { while idx > 0 && !self.base_chunk.is_char_boundary(idx) { idx -= 1; } return stop.min(self.scanned + idx); } let scan_len = self.target_chunk.len().min(self.base_chunk.len()); self.base_chunk = &self.base_chunk[scan_len..]; self.target_chunk = &self.target_chunk[scan_len..]; debug_assert!(self.base_chunk.is_empty() || self.target_chunk.is_empty()); self.scanned += scan_len; if stop <= self.scanned { break; } self.load_next_chunk(); if self.base_chunk.is_empty() || self.target_chunk.is_empty() { break; } } stop.min(self.scanned) } /// Returns the positive offset from the start of the rope to the first /// non-equal byte, and the negative offset from the end of the rope to /// the first non-equal byte. /// /// The two offsets are guaranteed not to overlap; /// thus `sum(start_offset, end_offset) <= min(one.len(), two.len())`. /// /// # Examples /// /// ``` /// # use xi_rope::compare::RopeScanner; /// # use xi_rope::Rope; /// /// let one = Rope::from("123xxx12345"); /// let two = Rope::from("123ZZZ12345"); /// let mut scanner = RopeScanner::new(&one, &two); /// assert_eq!(scanner.find_min_diff_range(), (3, 5)); /// /// /// let one = Rope::from("friends"); /// let two = Rope::from("fiends"); /// let mut scanner = RopeScanner::new(&one, &two); /// assert_eq!(scanner.find_min_diff_range(), (1, 5)) /// ``` pub fn find_min_diff_range(&mut self) -> (usize, usize) { let b_end = self.base.total_len(); let t_end = self.target.total_len(); let start = self.find_ne_char(0, 0, None); // scanning from the end of the document, we should stop at whatever // offset we reached scanning from the start. let unscanned = b_end.min(t_end) - start; let end = match unscanned { 0 => 0, n => self.find_ne_char_back(b_end, t_end, n), }; (start, end) } fn load_prev_chunk(&mut self) { if self.base_chunk.is_empty() { if let Some(prev) = self.base.prev_leaf() { self.base_chunk = prev.0; } } if self.target_chunk.is_empty() { if let Some(prev) = self.target.prev_leaf() { self.target_chunk = prev.0; } } } fn load_next_chunk(&mut self) { if self.base_chunk.is_empty() { if let Some(next) = self.base.next_leaf() { self.base_chunk = next.0; } } if self.target_chunk.is_empty() { if let Some(next) = self.target.next_leaf() { self.target_chunk = next.0; } } } } #[cfg(test)] mod tests { use super::*; use std::iter; #[test] fn ne_len() { // we should only match up to the length of the shortest input let one = "aaaaaa"; let two = "aaaa"; let tre = "aaba"; let fur = ""; assert!(ne_idx_fallback(one.as_bytes(), two.as_bytes()).is_none()); assert_eq!(ne_idx_fallback(one.as_bytes(), tre.as_bytes()), Some(2)); assert_eq!(ne_idx_fallback(one.as_bytes(), fur.as_bytes()), None); } #[test] #[cfg(target_arch = "x86_64")] fn ne_len_simd() { // we should only match up to the length of the shortest input let one = "aaaaaa"; let two = "aaaa"; let tre = "aaba"; let fur = ""; unsafe { if is_x86_feature_detected!("sse4.2") { assert!(ne_idx_sse(one.as_bytes(), two.as_bytes()).is_none()); assert_eq!(ne_idx_sse(one.as_bytes(), tre.as_bytes()), Some(2)); assert_eq!(ne_idx_sse(one.as_bytes(), fur.as_bytes()), None); } if is_x86_feature_detected!("avx2") { assert!(ne_idx_avx(one.as_bytes(), two.as_bytes()).is_none()); assert_eq!(ne_idx_avx(one.as_bytes(), tre.as_bytes()), Some(2)); assert_eq!(ne_idx_avx(one.as_bytes(), fur.as_bytes()), None); } } } #[test] fn ne_len_rev() { let one = "aaaaaa"; let two = "aaaa"; let tre = "aaba"; let fur = ""; assert!(ne_idx_rev_fallback(one.as_bytes(), two.as_bytes()).is_none()); assert_eq!(ne_idx_rev_fallback(one.as_bytes(), tre.as_bytes()), Some(1)); assert_eq!(ne_idx_rev_fallback(one.as_bytes(), fur.as_bytes()), None); } #[test] #[cfg(target_arch = "x86_64")] fn ne_len_rev_sse() { if !is_x86_feature_detected!("sse4.2") { return; } let one = "aaaaaa"; let two = "aaaa"; let tre = "aaba"; let fur = ""; unsafe { assert!(ne_idx_rev_sse(one.as_bytes(), two.as_bytes()).is_none()); assert_eq!(ne_idx_rev_sse(one.as_bytes(), tre.as_bytes()), Some(1)); assert_eq!(ne_idx_rev_sse(one.as_bytes(), fur.as_bytes()), None); } } #[test] fn ne_rev_regression1() { let one: &[u8] = &[ 101, 119, 58, 58, 123, 83, 116, 121, 108, 101, 44, 32, 86, 105, 101, 119, 125, 59, 10, 10, ]; let two: &[u8] = &[ 101, 119, 58, 58, 123, 83, 101, 32, 118, 105, 101, 119, 58, 58, 86, 105, 101, 119, 59, 10, ]; assert_eq!(ne_idx_rev_fallback(one, two), Some(1)); #[cfg(target_arch = "x86_64")] { if is_x86_feature_detected!("sse4.2") { unsafe { assert_eq!(ne_idx_rev_sse(one, two), Some(1)); } } } } fn make_lines(n: usize) -> String { let mut s = String::with_capacity(n * 81); let line: String = iter::repeat('a').take(79).chain(iter::once('\n')).collect(); for _ in 0..n { s.push_str(&line); } s } #[test] fn scanner_forward_simple() { let rope = Rope::from("aaaaaaaaaaaaaaaa"); let chunk1 = Rope::from("aaaaaaaaaaaaaaaa"); let chunk2 = Rope::from("baaaaaaaaaaaaaaa"); let chunk3 = Rope::from("abaaaaaaaaaaaaaa"); let chunk4 = Rope::from("aaaaaabaaaaaaaaa"); { let mut scanner = RopeScanner::new(&rope, &chunk1); assert_eq!(scanner.find_ne_char(0, 0, None), 16); } { let mut scanner = RopeScanner::new(&rope, &chunk2); assert_eq!(scanner.find_ne_char(0, 0, None), 0); } { let mut scanner = RopeScanner::new(&rope, &chunk3); assert_eq!(scanner.find_ne_char(0, 0, None), 1); } { let mut scanner = RopeScanner::new(&rope, &chunk4); assert_eq!(scanner.find_ne_char(0, 0, None), 6); } } #[test] fn scanner_backward_simple() { let rope = Rope::from("aaaaaaaaaaaaaaaa"); let chunk1 = Rope::from("aaaaaaaaaaaaaaaa"); let chunk2 = Rope::from("aaaaaaaaaaaaaaba"); let chunk3 = Rope::from("aaaaaaaaaaaaaaab"); let chunk4 = Rope::from("aaaaaabaaaaaaaaa"); { let mut scanner = RopeScanner::new(&rope, &chunk1); assert_eq!(scanner.find_ne_char_back(rope.len(), chunk1.len(), None), 16); } { let mut scanner = RopeScanner::new(&rope, &chunk2); assert_eq!(scanner.find_ne_char_back(rope.len(), chunk2.len(), None), 1); } { let mut scanner = RopeScanner::new(&rope, &chunk3); assert_eq!(scanner.find_ne_char_back(rope.len(), chunk3.len(), None), 0); } { let mut scanner = RopeScanner::new(&rope, &chunk4); assert_eq!(scanner.find_ne_char_back(rope.len(), chunk4.len(), None), 9); } } #[test] fn scan_back_ne_lens() { let rope = Rope::from("aaaaaaaaaaaaaaaa"); let chunk1 = Rope::from("aaaaaaaaaaaaa"); let chunk2 = Rope::from("aaaaaaaaaaaaab"); { let mut scanner = RopeScanner::new(&rope, &chunk1); assert_eq!(scanner.find_ne_char_back(rope.len(), chunk1.len(), None), 13); } { let mut scanner = RopeScanner::new(&rope, &chunk2); assert_eq!(scanner.find_ne_char_back(rope.len(), chunk2.len(), None), 0); } } #[test] fn find_diff_range() { let one = Rope::from("aaaaaaaaa"); let two = Rope::from("baaaaaaab"); let mut scanner = RopeScanner::new(&one, &two); let (start, end) = scanner.find_min_diff_range(); assert_eq!((start, end), (0, 0)); let one = Rope::from("aaaaaaaaa"); let two = Rope::from("abaaaaaba"); let mut scanner = RopeScanner::new(&one, &two); let (start, end) = scanner.find_min_diff_range(); assert_eq!((start, end), (1, 1)); let one = Rope::from("XXX"); let two = Rope::from("XXX"); let mut scanner = RopeScanner::new(&one, &two); let (start, end) = scanner.find_min_diff_range(); assert_eq!((start, end), (3, 0)); } #[test] fn find_diff_range_ne_lens() { let one = Rope::from("this is a great bit of text"); let two = Rope::from("this is a great bit of text, with some bonus bytes"); let mut scanner = RopeScanner::new(&one, &two); let (start, end) = scanner.find_min_diff_range(); assert_eq!((start, end), (27, 0)); let one = Rope::from("this is a great bit of text"); let two = Rope::from("xtra bytes precede this is a great bit of text"); let mut scanner = RopeScanner::new(&one, &two); let (start, end) = scanner.find_min_diff_range(); assert_eq!((start, end), (0, 27)); } #[test] fn scanner_back() { let rope = Rope::from(make_lines(10)); let mut chunk = String::from("bbb"); chunk.push_str(&make_lines(5)); let targ = Rope::from(chunk); { let mut scanner = RopeScanner::new(&rope, &targ); let result = scanner.find_ne_char_back(rope.len(), targ.len(), None); assert_eq!(result, 400); } let mut targ = String::from(targ); targ.push('x'); targ.push('\n'); let targ = Rope::from(&targ); let mut scanner = RopeScanner::new(&rope, &targ); let result = scanner.find_ne_char_back(rope.len(), targ.len(), None); assert_eq!(result, 1); } #[test] fn find_forward_utf8() { // make sure we don't include the matching non-boundary bytes let one = Rope::from("aaaa🙈"); let two = Rope::from("aaaa🙉"); let mut scanner = RopeScanner::new(&one, &two); let result = scanner.find_ne_char(0, 0, None); assert_eq!(result, 4); } #[test] fn find_back_utf8() { let zer = Rope::from("baaaa"); let one = Rope::from("🍄aaaa"); // F0 9F 8D 84 61 61 61 61; let two = Rope::from("🙄aaaa"); // F0 9F 99 84 61 61 61 61; let tri = Rope::from("🝄aaaa"); // F0 AF 8D 84 61 61 61 61; let mut scanner = RopeScanner::new(&zer, &one); let result = scanner.find_ne_char_back(zer.len(), one.len(), None); assert_eq!(result, 4); let mut scanner = RopeScanner::new(&one, &two); let result = scanner.find_ne_char_back(one.len(), two.len(), None); assert_eq!(result, 4); let mut scanner = RopeScanner::new(&one, &tri); let result = scanner.find_ne_char_back(one.len(), tri.len(), None); assert_eq!(result, 4); } #[test] fn ne_idx_rev_utf8() { // there was a weird failure in `find_back_utf8` non_simd, drilling down: let zer = "baaaa"; let one = "🍄aaaa"; // F0 9F 8D 84 61 61 61 61; let two = "🙄aaaa"; // F0 9F 99 84 61 61 61 61; #[cfg(target_arch = "x86_64")] if is_x86_feature_detected!("sse4.2") { unsafe { assert_eq!(ne_idx_rev_sse(zer.as_bytes(), one.as_bytes()), Some(4)); assert_eq!(ne_idx_rev_sse(one.as_bytes(), two.as_bytes()), Some(5)); } } assert_eq!(ne_idx_rev_fallback(zer.as_bytes(), one.as_bytes()), Some(4)); assert_eq!(ne_idx_rev_fallback(one.as_bytes(), two.as_bytes()), Some(5)); } #[test] #[cfg(target_arch = "x86_64")] fn avx_mask() { if !is_x86_feature_detected!("avx2") { return; } let one = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; let two = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; let mask = unsafe { avx_compare_mask(one.as_bytes(), two.as_bytes()) }; assert_eq!(mask, 0); assert_eq!(mask.trailing_zeros(), 32); let two = "aaaaaaaa_aaaaaaaaaaaaaaaaaaaaaaa"; let mask = unsafe { avx_compare_mask(one.as_bytes(), two.as_bytes()) }; assert_eq!(mask.trailing_zeros(), 8); let two = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; let mask = unsafe { avx_compare_mask(one.as_bytes(), two.as_bytes()) }; assert_eq!(mask.trailing_zeros(), 0); } #[test] #[cfg(target_arch = "x86_64")] fn ne_avx() { if !is_x86_feature_detected!("avx2") { return; } let one = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; let two = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; unsafe { assert_eq!(ne_idx_avx(one.as_bytes(), two.as_bytes()), Some(0)); let two = "aaaaaaa_aaaaaaaaaaaaaaaaaaaaaaaa"; assert_eq!(ne_idx_avx(one.as_bytes(), two.as_bytes()), Some(7)); let two = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; assert_eq!(ne_idx_avx(one.as_bytes(), two.as_bytes()), None); let one = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; assert_eq!(ne_idx_avx(one.as_bytes(), one.as_bytes()), None); let two = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaaaaaaaaa"; assert_eq!(ne_idx_avx(one.as_bytes(), two.as_bytes()), Some(38)); let two = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_"; assert_eq!(ne_idx_avx(one.as_bytes(), two.as_bytes()), Some(63)); let one = "________________________________________"; let two = "______________________________________0_"; assert_eq!(ne_idx_avx(one.as_bytes(), two.as_bytes()), Some(38)); } } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/benches/diff.rs
rust/rope/benches/diff.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![feature(test)] extern crate test; extern crate xi_rope; use test::Bencher; use xi_rope::compare; use xi_rope::diff::{Diff, LineHashDiff}; use xi_rope::rope::{Rope, RopeDelta}; static EDITOR_STR: &str = include_str!("../../core-lib/src/editor.rs"); static VIEW_STR: &str = include_str!("../../core-lib/src/view.rs"); static INTERVAL_STR: &str = include_str!("../src/interval.rs"); static BREAKS_STR: &str = include_str!("../src/breaks.rs"); static BASE_STR: &str = "This adds FixedSizeAdler32, that has a size set at construction, and keeps bytes in a cyclic buffer of that size to be removed when it fills up. Current logic (and implementing Write) might be too much, since bytes will probably always be fed one by one anyway. Otherwise a faster way of removing a sequence might be needed (one by one is inefficient)."; static TARG_STR: &str = "This adds some function, I guess?, that has a size set at construction, and keeps bytes in a cyclic buffer of that size to be ground up and injested when it fills up. Currently my sense of smell (and the pain of implementing Write) might be too much, since bytes will probably always be fed one by one anyway. Otherwise crying might be needed (one by one is inefficient)."; fn make_test_data() -> (Vec<u8>, Vec<u8>) { let one = [EDITOR_STR, VIEW_STR, INTERVAL_STR, BREAKS_STR].concat().into_bytes(); let mut two = one.clone(); let idx = one.len() / 2; two[idx] = 0x02; (one, two) } #[bench] fn ne_idx_sw(b: &mut Bencher) { let (one, two) = make_test_data(); b.iter(|| { compare::ne_idx_fallback(&one, &one); compare::ne_idx_fallback(&one, &two); }) } #[bench] #[cfg(target_arch = "x86_64")] fn ne_idx_sse(b: &mut Bencher) { if !is_x86_feature_detected!("sse4.2") { return; } let (one, two) = make_test_data(); let mut x = 0; b.iter(|| { x += unsafe { compare::ne_idx_sse(&one, &one).unwrap_or_default() }; x += unsafe { compare::ne_idx_sse(&one, &two).unwrap_or_default() }; }) } #[bench] #[cfg(target_arch = "x86_64")] fn ne_idx_avx(b: &mut Bencher) { if !is_x86_feature_detected!("avx2") { return; } let (one, two) = make_test_data(); let mut dont_opt_me = 0; b.iter(|| { dont_opt_me += unsafe { compare::ne_idx_avx(&one, &two).unwrap_or_default() }; dont_opt_me += unsafe { compare::ne_idx_avx(&one, &one).unwrap_or_default() }; }) } #[bench] fn ne_idx_detect(b: &mut Bencher) { let (one, two) = make_test_data(); let mut dont_opt_me = 0; b.iter(|| { dont_opt_me += compare::ne_idx(&one, &two).unwrap_or_default(); dont_opt_me += compare::ne_idx(&one, &one).unwrap_or_default(); }) } #[bench] fn ne_idx_rev_sw(b: &mut Bencher) { let (one, two) = make_test_data(); let mut x = 0; b.iter(|| { x += compare::ne_idx_rev_fallback(&one, &one).unwrap_or_default(); x += compare::ne_idx_rev_fallback(&one, &two).unwrap_or_default(); }) } #[bench] #[cfg(target_arch = "x86_64")] fn ne_idx_rev_sse(b: &mut Bencher) { if !is_x86_feature_detected!("sse4.2") { return; } let (one, two) = make_test_data(); b.iter(|| unsafe { compare::ne_idx_rev_sse(&one, &one); compare::ne_idx_rev_sse(&one, &two); }) } #[bench] fn scanner(b: &mut Bencher) { let (one, two) = make_test_data(); let one = Rope::from(String::from_utf8(one).unwrap()); let two = Rope::from(String::from_utf8(two).unwrap()); let mut scanner = compare::RopeScanner::new(&one, &two); b.iter(|| { scanner.find_ne_char(0, 0, None); scanner.find_ne_char_back(one.len(), two.len(), None); }) } #[bench] fn hash_diff(b: &mut Bencher) { let one = BASE_STR.into(); let two = TARG_STR.into(); let mut delta: Option<RopeDelta> = None; b.iter(|| { delta = Some(LineHashDiff::compute_delta(&one, &two)); }); let _result = delta.unwrap().apply(&one); assert_eq!(String::from(_result), String::from(&two)); } #[bench] fn hash_diff_med(b: &mut Bencher) { let one = INTERVAL_STR.into(); let two = BREAKS_STR.into(); let mut delta: Option<RopeDelta> = None; b.iter(|| { delta = Some(LineHashDiff::compute_delta(&one, &two)); }); let _result = delta.unwrap().apply(&one); assert_eq!(String::from(_result), String::from(&two)); } #[bench] fn hash_diff_big(b: &mut Bencher) { let one = EDITOR_STR.into(); let two = VIEW_STR.into(); let mut delta: Option<RopeDelta> = None; b.iter(|| { delta = Some(LineHashDiff::compute_delta(&one, &two)); }); let _result = delta.unwrap().apply(&one); assert_eq!(String::from(_result), String::from(&two)); } #[bench] fn simple_insertion(b: &mut Bencher) { let one: Rope = ["start", EDITOR_STR, VIEW_STR, INTERVAL_STR, BREAKS_STR, "end"].concat().into(); let two = "startend".into(); let mut delta: Option<RopeDelta> = None; b.iter(|| { delta = Some(LineHashDiff::compute_delta(&one, &two)); }); let _result = delta.unwrap().apply(&one); assert_eq!(String::from(_result), String::from(&two)); } #[bench] fn simple_deletion(b: &mut Bencher) { let one: Rope = ["start", EDITOR_STR, VIEW_STR, INTERVAL_STR, BREAKS_STR, "end"].concat().into(); let two = "startend".into(); let mut delta: Option<RopeDelta> = None; b.iter(|| { delta = Some(LineHashDiff::compute_delta(&two, &one)); }); let _result = delta.unwrap().apply(&two); assert_eq!(String::from(_result), String::from(&one)); }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/benches/edit.rs
rust/rope/benches/edit.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![feature(test)] extern crate test; extern crate xi_rope; use test::Bencher; use xi_rope::rope::Rope; fn build_triangle(n: usize) -> String { let mut s = String::new(); let mut line = String::new(); for _ in 0..n { s += &line; s += "\n"; line += "a"; } s } fn build_short_lines(n: usize) -> String { let line = "match s.as_bytes()[minsplit - 1..splitpoint].iter().rposition(|&c| c == b'\n') {"; let mut s = String::new(); for _ in 0..n { s += line; } s } fn build_few_big_lines(size: usize) -> String { let mut s = String::with_capacity(size * 10 + 20); for _ in 0..10 { for _ in 0..size { s += "a"; } s += "\n"; } s } #[bench] fn benchmark_file_load_short_lines(b: &mut Bencher) { let text = build_short_lines(50_000); b.iter(|| { Rope::from(&text); }); } #[bench] fn benchmark_file_load_few_big_lines(b: &mut Bencher) { let text = build_few_big_lines(1_000_000); b.iter(|| { Rope::from(&text); }); } #[bench] fn benchmark_char_insertion_one_line_edit(b: &mut Bencher) { let mut text = Rope::from("b".repeat(100)); let mut offset = 100; b.iter(|| { text.edit(offset..=offset, "a"); offset += 1; }); } #[bench] fn benchmark_paste_into_line(b: &mut Bencher) { let mut text = Rope::from(build_short_lines(50_000)); let insertion = "a".repeat(50); let mut offset = 100; b.iter(|| { text.edit(offset..=offset, &insertion); offset += 150; }); } #[bench] fn benchmark_insert_newline(b: &mut Bencher) { let mut text = Rope::from(build_few_big_lines(1_000_000)); let mut offset = 1000; b.iter(|| { text.edit(offset..=offset, "\n"); offset += 1001; }); } #[bench] fn benchmark_overwrite_into_line(b: &mut Bencher) { let mut text = Rope::from(build_short_lines(50_000)); let mut offset = 100; let insertion = "a".repeat(50); b.iter(|| { // TODO: if the method runs too quickly, this may generate a fault // since there's an upper limit to how many times this can run. text.edit(offset..=offset + 20, &insertion); offset += 30; }); } #[bench] fn benchmark_triangle_concat_inplace(b: &mut Bencher) { let mut text = Rope::from(""); let insertion = build_triangle(3000); let insertion_len = insertion.len(); let mut offset = 0; b.iter(|| { text.edit(offset..=offset, &insertion); offset += insertion_len; }); } #[bench] fn real_world_editing_scenario(b: &mut Bencher) { b.iter(|| { let mut text = Rope::default(); let mut cursor = 0; for i in 1..10_000 { let s = if i % 80 == 0 { "\n" } else { "a" }; text.edit(cursor..cursor, s); if i % 123 == 0 { // periodically do some deletes text.edit(cursor - 5..cursor, ""); } // periodically move cursor: cursor = match i { 1000 => 200, 2000 => 1800, 3000 => 1000, 4000 => text.len() - 1, 5000 => 404, 6000 => 4444, 7000 => 6990, 8000 => 6990, 9000 => 100, n if n % 123 == 0 => cursor - 5, // the delete case _ => cursor + 1, }; } }) }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/benches/cursors.rs
rust/rope/benches/cursors.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![feature(test)] extern crate test; extern crate xi_rope; use test::Bencher; use xi_rope::rope::{LinesMetric, Rope}; use xi_rope::tree::*; fn run_down_rope(text: &Rope) { let mut cursor = Cursor::new(text, 0); while cursor.pos() < text.len() - 2 { cursor.next::<LinesMetric>(); } } fn build_triangle(n: usize) -> String { let mut s = String::new(); let mut line = String::new(); for _ in 0..n { s += &line; s += "\n"; line += "a"; } s } fn build_short_lines(n: usize) -> String { let line = "match s.as_bytes()[minsplit - 1..splitpoint].iter().rposition(|&c| c == b'\n') {"; let mut s = String::new(); for _ in 0..n { s += line; } s } fn build_few_big_lines(size: usize) -> String { let mut s = String::with_capacity(size * 10 + 20); for _ in 0..10 { for _ in 0..size { s += "a"; } s += "\n"; } s } #[bench] fn benchmark_triangle(b: &mut Bencher) { let text = Rope::from(build_triangle(50_000)); b.iter(|| run_down_rope(&text)); } #[bench] fn benchmark_short_lines(b: &mut Bencher) { let text = Rope::from(build_short_lines(1_000_000)); b.iter(|| run_down_rope(&text)); } #[bench] fn benchmark_few_big_lines(b: &mut Bencher) { let text = Rope::from(build_few_big_lines(1_000_000)); b.iter(|| run_down_rope(&text)); }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/examples/ropetoy.rs
rust/rope/examples/ropetoy.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Toy app for experimenting with ropes extern crate xi_rope; use xi_rope::Rope; fn main() { let mut a = Rope::from("hello."); a.edit(5..6, "!"); for i in 0..1000000 { let l = a.len(); a.edit(l..l, &(i.to_string() + "\n")); } let l = a.len(); for s in a.clone().iter_chunks(1000..3000) { println!("chunk {:?}", s); } a.edit(1000..l, ""); //a = a.subrange(0, 1000); println!("{:?}", String::from(a)); }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/src/main.rs
rust/src/main.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate log; extern crate chrono; extern crate fern; extern crate dirs; extern crate xi_core_lib; extern crate xi_rpc; use std::collections::HashMap; use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::process; use xi_core_lib::XiCore; use xi_rpc::RpcLoop; const XI_LOG_DIR: &str = "xi-core"; const XI_LOG_FILE: &str = "xi-core.log"; fn get_logging_directory_path<P: AsRef<Path>>(directory: P) -> Result<PathBuf, io::Error> { match dirs::data_local_dir() { Some(mut log_dir) => { log_dir.push(directory); Ok(log_dir) } None => Err(io::Error::new( io::ErrorKind::NotFound, "No standard logging directory known for this platform", )), } } /// This function tries to create the parent directories for a file /// /// It wraps around the `parent()` function of `Path` which returns an `Option<&Path>` and /// `fs::create_dir_all` which returns an `io::Result<()>`. /// /// This allows you to use `?`/`try!()` to create the dir and you recive the additional custom error for when `parent()` /// returns nothing. /// /// # Errors /// This can return an `io::Error` if `fs::create_dir_all` fails or if `parent()` returns `None`. /// See `Path`'s `parent()` function for more details. /// # Examples /// ``` /// use std::path::Path; /// use std::ffi::OsStr; /// /// let path_with_file = Path::new("/some/directory/then/file"); /// assert_eq!(Some(OsStr::new("file")), path_with_file.file_name()); /// assert_eq!(create_log_directory(path_with_file).is_ok(), true); /// /// let path_with_other_file = Path::new("/other_file"); /// assert_eq!(Some(OsStr::new("other_file")), path_with_other_file.file_name()); /// assert_eq!(create_log_directory(path_with_file).is_ok(), true); /// /// // Path that is just the root or prefix: /// let path_without_file = Path::new("/"); /// assert_eq!(None, path_without_file.file_name()); /// assert_eq!(create_log_directory(path_without_file).is_ok(), false); /// ``` fn create_log_directory(path_with_file: &Path) -> io::Result<()> { let log_dir = path_with_file.parent().ok_or_else(|| io::Error::new( io::ErrorKind::InvalidInput, format!( "Unable to get the parent of the following Path: {}, Your path should contain a file name", path_with_file.display(), ), ))?; fs::create_dir_all(log_dir)?; Ok(()) } fn setup_logging(logging_path: Option<&Path>) -> Result<(), fern::InitError> { let level_filter = match std::env::var("XI_LOG") { Ok(level) => match level.to_lowercase().as_ref() { "trace" => log::LevelFilter::Trace, "debug" => log::LevelFilter::Debug, _ => log::LevelFilter::Info, }, // Default to info Err(_) => log::LevelFilter::Info, }; let mut fern_dispatch = fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message, )) }) .level(level_filter) .chain(io::stderr()); if let Some(logging_file_path) = logging_path { create_log_directory(logging_file_path)?; fern_dispatch = fern_dispatch.chain(fern::log_file(logging_file_path)?); }; // Start fern fern_dispatch.apply()?; info!("Logging with fern is set up"); // Log details of the logging_file_path result using fern/log // Either logging the path fern is outputting to or the error from obtaining the path match logging_path { Some(logging_file_path) => info!("Writing logs to: {}", logging_file_path.display()), None => warn!("No path was supplied for the log file. Not saving logs to disk, falling back to just stderr"), } Ok(()) } fn generate_logging_path(logfile_config: LogfileConfig) -> Result<PathBuf, io::Error> { // Use the file name set in logfile_config or fallback to the default let logfile_file_name = match logfile_config.file { Some(file_name) => file_name, None => PathBuf::from(XI_LOG_FILE), }; if logfile_file_name.eq(Path::new("")) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "A blank file name was supplied")); }; // Use the directory name set in logfile_config or fallback to the default let logfile_directory_name = match logfile_config.directory { Some(dir) => dir, None => PathBuf::from(XI_LOG_DIR), }; let mut logging_directory_path = get_logging_directory_path(logfile_directory_name)?; // Add the file name & return the full path logging_directory_path.push(logfile_file_name); Ok(logging_directory_path) } fn get_flags() -> HashMap<String, Option<String>> { let mut flags: HashMap<String, Option<String>> = HashMap::new(); let flag_prefix = "-"; let mut args_iterator = std::env::args().peekable(); while let Some(arg) = args_iterator.next() { if arg.starts_with(flag_prefix) { let key = arg.trim_start_matches(flag_prefix).to_string(); // Check the next argument doesn't start with the flag prefix // map_or accounts for peek returning an Option let next_arg_not_a_flag: bool = args_iterator.peek().map_or(false, |val| !val.starts_with(flag_prefix)); if next_arg_not_a_flag { flags.insert(key, args_iterator.next()); } } } flags } struct EnvFlagConfig { env_name: &'static str, flag_name: &'static str, } /// Extracts a value from the flags and the env. /// /// In this order: `String` from the flags, then `String` from the env, then `None` fn extract_env_or_flag( flags: &HashMap<String, Option<String>>, conf: &EnvFlagConfig, ) -> Option<String> { flags.get(conf.flag_name).cloned().unwrap_or_else(|| std::env::var(conf.env_name).ok()) } struct LogfileConfig { directory: Option<PathBuf>, file: Option<PathBuf>, } fn generate_logfile_config(flags: &HashMap<String, Option<String>>) -> LogfileConfig { // If the key is set, get the Option within let log_dir_env_flag = EnvFlagConfig { env_name: "XI_LOG_DIR", flag_name: "log-dir" }; let log_file_env_flag = EnvFlagConfig { env_name: "XI_LOG_FILE", flag_name: "log-file" }; let log_dir_flag_option = extract_env_or_flag(flags, &log_dir_env_flag).map(PathBuf::from); let log_file_flag_option = extract_env_or_flag(flags, &log_file_env_flag).map(PathBuf::from); LogfileConfig { directory: log_dir_flag_option, file: log_file_flag_option } } fn main() { let mut state = XiCore::new(); let stdin = io::stdin(); let stdout = io::stdout(); let mut rpc_looper = RpcLoop::new(stdout); let flags = get_flags(); let logfile_config = generate_logfile_config(&flags); let logging_path_result = generate_logging_path(logfile_config); let logging_path = logging_path_result.as_ref().map(|p: &PathBuf| -> &Path { p.as_path() }).ok(); if let Err(e) = setup_logging(logging_path) { eprintln!("[ERROR] setup_logging returned error, logging not enabled: {:?}", e); } if let Err(e) = logging_path_result.as_ref() { warn!("Unable to generate the logging path to pass to set up: {}", e) } match rpc_looper.mainloop(|| stdin.lock(), &mut state) { Ok(_) => (), Err(err) => { error!("xi-core exited with error:\n{:?}", err); process::exit(1); } } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rpc/src/lib.rs
rust/rpc/src/lib.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic RPC handling (used for both front end and plugin communication). //! //! The RPC protocol is based on [JSON-RPC](http://www.jsonrpc.org/specification), //! but with some modifications. Unlike JSON-RPC 2.0, requests and notifications //! are allowed in both directions, rather than imposing client and server roles. //! Further, the batch form is not supported. //! //! Because these changes make the protocol not fully compliant with the spec, //! the `"jsonrpc"` member is omitted from request and response objects. #![allow(clippy::boxed_local, clippy::or_fun_call)] #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate crossbeam_utils; extern crate serde; extern crate xi_trace; #[macro_use] extern crate log; mod error; mod parse; pub mod test_utils; use std::cmp; use std::collections::{BTreeMap, BinaryHeap, VecDeque}; use std::io::{self, BufRead, Write}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::time::{Duration, Instant}; use serde::de::DeserializeOwned; use serde_json::Value; use xi_trace::{trace, trace_block, trace_block_payload, trace_payload}; pub use crate::error::{Error, ReadError, RemoteError}; use crate::parse::{Call, MessageReader, Response, RpcObject}; /// The maximum duration we will block on a reader before checking for an task. const MAX_IDLE_WAIT: Duration = Duration::from_millis(5); /// An interface to access the other side of the RPC channel. The main purpose /// is to send RPC requests and notifications to the peer. /// /// A single shared `RawPeer` exists for each `RpcLoop`; a reference can /// be taken with `RpcLoop::get_peer()`. /// /// In general, `RawPeer` shouldn't be used directly, but behind a pointer as /// the `Peer` trait object. pub struct RawPeer<W: Write + 'static>(Arc<RpcState<W>>); /// The `Peer` trait represents the interface for the other side of the RPC /// channel. It is intended to be used behind a pointer, a trait object. pub trait Peer: Send + 'static { /// Used to implement `clone` in an object-safe way. /// For an explanation on this approach, see /// [this thread](https://users.rust-lang.org/t/solved-is-it-possible-to-clone-a-boxed-trait-object/1714/6). fn box_clone(&self) -> Box<dyn Peer>; /// Sends a notification (asynchronous RPC) to the peer. fn send_rpc_notification(&self, method: &str, params: &Value); /// Sends a request asynchronously, and the supplied callback will /// be called when the response arrives. /// /// `Callback` is an alias for `FnOnce(Result<Value, Error>)`; it must /// be boxed because trait objects cannot use generic paramaters. fn send_rpc_request_async(&self, method: &str, params: &Value, f: Box<dyn Callback>); /// Sends a request (synchronous RPC) to the peer, and waits for the result. fn send_rpc_request(&self, method: &str, params: &Value) -> Result<Value, Error>; /// Determines whether an incoming request (or notification) is /// pending. This is intended to reduce latency for bulk operations /// done in the background. fn request_is_pending(&self) -> bool; /// Adds a token to the idle queue. When the runloop is idle and the /// queue is not empty, the handler's `idle` fn will be called /// with the earliest added token. fn schedule_idle(&self, token: usize); /// Like `schedule_idle`, with the guarantee that the handler's `idle` /// fn will not be called _before_ the provided `Instant`. /// /// # Note /// /// This is not intended as a high-fidelity timer. Regular RPC messages /// will always take priority over an idle task. fn schedule_timer(&self, after: Instant, token: usize); } /// The `Peer` trait object. pub type RpcPeer = Box<dyn Peer>; pub struct RpcCtx { peer: RpcPeer, } #[derive(Debug, Clone, Serialize, Deserialize)] /// An RPC command. /// /// This type is used as a placeholder in various places, and can be /// used by clients as a catchall type for implementing `MethodHandler`. pub struct RpcCall { pub method: String, pub params: Value, } /// A trait for types which can handle RPCs. /// /// Types which implement `MethodHandler` are also responsible for implementing /// `Parser`; `Parser` is provided when Self::Notification and Self::Request /// can be used with serde::DeserializeOwned. pub trait Handler { type Notification: DeserializeOwned; type Request: DeserializeOwned; fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification); fn handle_request(&mut self, ctx: &RpcCtx, rpc: Self::Request) -> Result<Value, RemoteError>; #[allow(unused_variables)] fn idle(&mut self, ctx: &RpcCtx, token: usize) {} } pub trait Callback: Send { fn call(self: Box<Self>, result: Result<Value, Error>); } impl<F: Send + FnOnce(Result<Value, Error>)> Callback for F { fn call(self: Box<F>, result: Result<Value, Error>) { (*self)(result) } } /// A helper type which shuts down the runloop if a panic occurs while /// handling an RPC. struct PanicGuard<'a, W: Write + 'static>(&'a RawPeer<W>); impl<'a, W: Write + 'static> Drop for PanicGuard<'a, W> { fn drop(&mut self) { if thread::panicking() { error!("panic guard hit, closing runloop"); self.0.disconnect(); } } } trait IdleProc: Send { fn call(self: Box<Self>, token: usize); } impl<F: Send + FnOnce(usize)> IdleProc for F { fn call(self: Box<F>, token: usize) { (*self)(token) } } enum ResponseHandler { Chan(mpsc::Sender<Result<Value, Error>>), Callback(Box<dyn Callback>), } impl ResponseHandler { fn invoke(self, result: Result<Value, Error>) { match self { ResponseHandler::Chan(tx) => { let _ = tx.send(result); } ResponseHandler::Callback(f) => f.call(result), } } } #[derive(Debug, PartialEq, Eq)] struct Timer { fire_after: Instant, token: usize, } struct RpcState<W: Write> { rx_queue: Mutex<VecDeque<Result<RpcObject, ReadError>>>, rx_cvar: Condvar, writer: Mutex<W>, id: AtomicUsize, pending: Mutex<BTreeMap<usize, ResponseHandler>>, idle_queue: Mutex<VecDeque<usize>>, timers: Mutex<BinaryHeap<Timer>>, needs_exit: AtomicBool, is_blocked: AtomicBool, } /// A structure holding the state of a main loop for handling RPC's. pub struct RpcLoop<W: Write + 'static> { reader: MessageReader, peer: RawPeer<W>, } impl<W: Write + Send> RpcLoop<W> { /// Creates a new `RpcLoop` with the given output stream (which is used for /// sending requests and notifications, as well as responses). pub fn new(writer: W) -> Self { let rpc_peer = RawPeer(Arc::new(RpcState { rx_queue: Mutex::new(VecDeque::new()), rx_cvar: Condvar::new(), writer: Mutex::new(writer), id: AtomicUsize::new(0), pending: Mutex::new(BTreeMap::new()), idle_queue: Mutex::new(VecDeque::new()), timers: Mutex::new(BinaryHeap::new()), needs_exit: AtomicBool::new(false), is_blocked: AtomicBool::new(false), })); RpcLoop { reader: MessageReader::default(), peer: rpc_peer } } /// Gets a reference to the peer. pub fn get_raw_peer(&self) -> RawPeer<W> { self.peer.clone() } /// Starts the event loop, reading lines from the reader until EOF, /// or an error occurs. /// /// Returns `Ok()` in the EOF case, otherwise returns the /// underlying `ReadError`. /// /// # Note: /// The reader is supplied via a closure, as basically a workaround /// so that the reader doesn't have to be `Send`. Internally, the /// main loop starts a separate thread for I/O, and at startup that /// thread calls the given closure. /// /// Calls to the handler happen on the caller's thread. /// /// Calls to the handler are guaranteed to preserve the order as /// they appear on on the channel. At the moment, there is no way /// for there to be more than one incoming request to be outstanding. pub fn mainloop<R, RF, H>(&mut self, rf: RF, handler: &mut H) -> Result<(), ReadError> where R: BufRead, RF: Send + FnOnce() -> R, H: Handler, { let exit = crossbeam_utils::thread::scope(|scope| { let peer = self.get_raw_peer(); peer.reset_needs_exit(); let ctx = RpcCtx { peer: Box::new(peer.clone()) }; scope.spawn(move |_| { let mut stream = rf(); loop { // The main thread cannot return while this thread is active; // when the main thread wants to exit it sets this flag. if self.peer.needs_exit() { trace("read loop exit", &["rpc"]); break; } let json = match self.reader.next(&mut stream) { Ok(json) => json, Err(err) => { if self.peer.0.is_blocked.load(Ordering::Acquire) { error!("failed to parse response json: {}", err); self.peer.disconnect(); } self.peer.put_rx(Err(err)); break; } }; if json.is_response() { let id = json.get_id().unwrap(); let _resp = trace_block_payload("read loop response", &["rpc"], format!("{}", id)); match json.into_response() { Ok(resp) => { let resp = resp.map_err(Error::from); self.peer.handle_response(id, resp); } Err(msg) => { error!("failed to parse response: {}", msg); self.peer.handle_response(id, Err(Error::InvalidResponse)); } } } else { self.peer.put_rx(Ok(json)); } } }); loop { let _guard = PanicGuard(&peer); let read_result = next_read(&peer, handler, &ctx); let _trace = trace_block("main got msg", &["rpc"]); let json = match read_result { Ok(json) => json, Err(err) => { trace_payload("main loop err", &["rpc"], err.to_string()); // finish idle work before disconnecting; // this is mostly useful for integration tests. if let Some(idle_token) = peer.try_get_idle() { handler.idle(&ctx, idle_token); } peer.disconnect(); return err; } }; let method = json.get_method().map(String::from); match json.into_rpc::<H::Notification, H::Request>() { Ok(Call::Request(id, cmd)) => { let _t = trace_block_payload("handle request", &["rpc"], method.unwrap()); let result = handler.handle_request(&ctx, cmd); peer.respond(result, id); } Ok(Call::Notification(cmd)) => { let _t = trace_block_payload("handle notif", &["rpc"], method.unwrap()); handler.handle_notification(&ctx, cmd); } Ok(Call::InvalidRequest(id, err)) => peer.respond(Err(err), id), Err(err) => { trace_payload("read loop exit", &["rpc"], err.to_string()); peer.disconnect(); return ReadError::UnknownRequest(err); } } } }) .unwrap(); if exit.is_disconnect() { Ok(()) } else { Err(exit) } } } /// Returns the next read result, checking for idle work when no /// result is available. fn next_read<W, H>(peer: &RawPeer<W>, handler: &mut H, ctx: &RpcCtx) -> Result<RpcObject, ReadError> where W: Write + Send, H: Handler, { loop { if let Some(result) = peer.try_get_rx() { return result; } // handle timers before general idle work let time_to_next_timer = match peer.check_timers() { Some(Ok(token)) => { do_idle(handler, ctx, token); continue; } Some(Err(duration)) => Some(duration), None => None, }; if let Some(idle_token) = peer.try_get_idle() { do_idle(handler, ctx, idle_token); continue; } // we don't want to block indefinitely if there's no current idle work, // because idle work could be scheduled from another thread. let idle_timeout = time_to_next_timer.unwrap_or(MAX_IDLE_WAIT).min(MAX_IDLE_WAIT); if let Some(result) = peer.get_rx_timeout(idle_timeout) { return result; } } } fn do_idle<H: Handler>(handler: &mut H, ctx: &RpcCtx, token: usize) { let _trace = trace_block_payload("do_idle", &["rpc"], format!("token: {}", token)); handler.idle(ctx, token); } impl RpcCtx { pub fn get_peer(&self) -> &RpcPeer { &self.peer } /// Schedule the idle handler to be run when there are no requests pending. pub fn schedule_idle(&self, token: usize) { self.peer.schedule_idle(token) } } impl<W: Write + Send + 'static> Peer for RawPeer<W> { fn box_clone(&self) -> Box<dyn Peer> { Box::new((*self).clone()) } fn send_rpc_notification(&self, method: &str, params: &Value) { let _trace = trace_block_payload("send notif", &["rpc"], method.to_owned()); if let Err(e) = self.send(&json!({ "method": method, "params": params, })) { error!("send error on send_rpc_notification method {}: {}", method, e); } } fn send_rpc_request_async(&self, method: &str, params: &Value, f: Box<dyn Callback>) { let _trace = trace_block_payload("send req async", &["rpc"], method.to_owned()); self.send_rpc_request_common(method, params, ResponseHandler::Callback(f)); } fn send_rpc_request(&self, method: &str, params: &Value) -> Result<Value, Error> { let _trace = trace_block_payload("send req sync", &["rpc"], method.to_owned()); self.0.is_blocked.store(true, Ordering::Release); let (tx, rx) = mpsc::channel(); self.send_rpc_request_common(method, params, ResponseHandler::Chan(tx)); rx.recv().unwrap_or(Err(Error::PeerDisconnect)) } fn request_is_pending(&self) -> bool { let queue = self.0.rx_queue.lock().unwrap(); !queue.is_empty() } fn schedule_idle(&self, token: usize) { self.0.idle_queue.lock().unwrap().push_back(token); } fn schedule_timer(&self, after: Instant, token: usize) { self.0.timers.lock().unwrap().push(Timer { fire_after: after, token }); } } impl<W: Write> RawPeer<W> { fn send(&self, v: &Value) -> Result<(), io::Error> { let _trace = trace_block("send", &["rpc"]); let mut s = serde_json::to_string(v).unwrap(); s.push('\n'); self.0.writer.lock().unwrap().write_all(s.as_bytes()) // Technically, maybe we should flush here, but doesn't seem to be required. } fn respond(&self, result: Response, id: u64) { let mut response = json!({ "id": id }); match result { Ok(result) => response["result"] = result, Err(error) => response["error"] = json!(error), }; if let Err(e) = self.send(&response) { error!("error {} sending response to RPC {:?}", e, id); } } fn send_rpc_request_common(&self, method: &str, params: &Value, rh: ResponseHandler) { let id = self.0.id.fetch_add(1, Ordering::Relaxed); { let mut pending = self.0.pending.lock().unwrap(); pending.insert(id, rh); } if let Err(e) = self.send(&json!({ "id": id, "method": method, "params": params, })) { let mut pending = self.0.pending.lock().unwrap(); if let Some(rh) = pending.remove(&id) { rh.invoke(Err(Error::Io(e))); } } } fn handle_response(&self, id: u64, resp: Result<Value, Error>) { let id = id as usize; let handler = { let mut pending = self.0.pending.lock().unwrap(); pending.remove(&id) }; match handler { Some(responsehandler) => responsehandler.invoke(resp), None => warn!("id {} not found in pending", id), } } /// Get a message from the receive queue if available. fn try_get_rx(&self) -> Option<Result<RpcObject, ReadError>> { let mut queue = self.0.rx_queue.lock().unwrap(); queue.pop_front() } /// Get a message from the receive queue, waiting for at most `Duration` /// and returning `None` if no message is available. fn get_rx_timeout(&self, dur: Duration) -> Option<Result<RpcObject, ReadError>> { let mut queue = self.0.rx_queue.lock().unwrap(); let result = self.0.rx_cvar.wait_timeout(queue, dur).unwrap(); queue = result.0; queue.pop_front() } /// Adds a message to the receive queue. The message should only /// be `None` if the read thread is exiting. fn put_rx(&self, json: Result<RpcObject, ReadError>) { let mut queue = self.0.rx_queue.lock().unwrap(); queue.push_back(json); self.0.rx_cvar.notify_one(); } fn try_get_idle(&self) -> Option<usize> { self.0.idle_queue.lock().unwrap().pop_front() } /// Checks status of the most imminent timer. If that timer has expired, /// returns `Some(Ok(_))`, with the corresponding token. /// If a timer exists but has not expired, returns `Some(Err(_))`, /// with the error value being the `Duration` until the timer is ready. /// Returns `None` if no timers are registered. fn check_timers(&self) -> Option<Result<usize, Duration>> { let mut timers = self.0.timers.lock().unwrap(); match timers.peek() { None => return None, Some(t) => { let now = Instant::now(); if t.fire_after > now { return Some(Err(t.fire_after - now)); } } } Some(Ok(timers.pop().unwrap().token)) } /// send disconnect error to pending requests. fn disconnect(&self) { let mut pending = self.0.pending.lock().unwrap(); let ids = pending.keys().cloned().collect::<Vec<_>>(); for id in &ids { let callback = pending.remove(id).unwrap(); callback.invoke(Err(Error::PeerDisconnect)); } self.0.needs_exit.store(true, Ordering::Relaxed); } /// Returns `true` if an error has occured in the main thread. fn needs_exit(&self) -> bool { self.0.needs_exit.load(Ordering::Relaxed) } fn reset_needs_exit(&self) { self.0.needs_exit.store(false, Ordering::SeqCst); } } impl Clone for Box<dyn Peer> { fn clone(&self) -> Box<dyn Peer> { self.box_clone() } } impl<W: Write> Clone for RawPeer<W> { fn clone(&self) -> Self { RawPeer(self.0.clone()) } } //NOTE: for our timers to work with Rust's BinaryHeap we want to reverse //the default comparison; smaller `Instant`'s are considered 'greater'. impl Ord for Timer { fn cmp(&self, other: &Timer) -> cmp::Ordering { other.fire_after.cmp(&self.fire_after) } } impl PartialOrd for Timer { fn partial_cmp(&self, other: &Timer) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_notif() { let reader = MessageReader::default(); let json = reader.parse(r#"{"method": "hi", "params": {"words": "plz"}}"#).unwrap(); assert!(!json.is_response()); let rpc = json.into_rpc::<Value, Value>().unwrap(); match rpc { Call::Notification(_) => (), _ => panic!("parse failed"), } } #[test] fn test_parse_req() { let reader = MessageReader::default(); let json = reader.parse(r#"{"id": 5, "method": "hi", "params": {"words": "plz"}}"#).unwrap(); assert!(!json.is_response()); let rpc = json.into_rpc::<Value, Value>().unwrap(); match rpc { Call::Request(..) => (), _ => panic!("parse failed"), } } #[test] fn test_parse_bad_json() { // missing "" around params let reader = MessageReader::default(); let json = reader.parse(r#"{"id": 5, "method": "hi", params: {"words": "plz"}}"#).err().unwrap(); match json { ReadError::Json(..) => (), _ => panic!("parse failed"), } // not an object let json = reader.parse(r#"[5, "hi", {"arg": "val"}]"#).err().unwrap(); match json { ReadError::NotObject => (), _ => panic!("parse failed"), } } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rpc/src/parse.rs
rust/rpc/src/parse.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Parsing of raw JSON messages into RPC objects. use std::io::BufRead; use serde::de::DeserializeOwned; use serde_json::{Error as JsonError, Value}; use crate::error::{ReadError, RemoteError}; /// A unique identifier attached to request RPCs. type RequestId = u64; /// An RPC response, received from the peer. pub type Response = Result<Value, RemoteError>; /// Reads and parses RPC messages from a stream, maintaining an /// internal buffer. #[derive(Debug, Default)] pub struct MessageReader(String); /// An internal type used during initial JSON parsing. /// /// Wraps an arbitrary JSON object, which may be any valid or invalid /// RPC message. This allows initial parsing and response handling to /// occur on the read thread. If the message looks like a request, it /// is passed to the main thread for handling. #[derive(Debug, Clone)] pub struct RpcObject(pub Value); #[derive(Debug, Clone, PartialEq)] /// An RPC call, which may be either a notification or a request. pub enum Call<N, R> { /// An id and an RPC Request Request(RequestId, R), /// An RPC Notification Notification(N), /// A malformed request: the request contained an id, but could /// not be parsed. The client will receive an error. InvalidRequest(RequestId, RemoteError), } impl MessageReader { /// Attempts to read the next line from the stream and parse it as /// an RPC object. /// /// # Errors /// /// This function will return an error if there is an underlying /// I/O error, if the stream is closed, or if the message is not /// a valid JSON object. pub fn next<R: BufRead>(&mut self, reader: &mut R) -> Result<RpcObject, ReadError> { self.0.clear(); let _ = reader.read_line(&mut self.0)?; if self.0.is_empty() { Err(ReadError::Disconnect) } else { self.parse(&self.0) } } /// Attempts to parse a &str as an RPC Object. /// /// This should not be called directly unless you are writing tests. #[doc(hidden)] pub fn parse(&self, s: &str) -> Result<RpcObject, ReadError> { let _trace = xi_trace::trace_block("parse", &["rpc"]); let val = serde_json::from_str::<Value>(s)?; if !val.is_object() { Err(ReadError::NotObject) } else { Ok(val.into()) } } } impl RpcObject { /// Returns the 'id' of the underlying object, if present. pub fn get_id(&self) -> Option<RequestId> { self.0.get("id").and_then(Value::as_u64) } /// Returns the 'method' field of the underlying object, if present. pub fn get_method(&self) -> Option<&str> { self.0.get("method").and_then(Value::as_str) } /// Returns `true` if this object looks like an RPC response; /// that is, if it has an 'id' field and does _not_ have a 'method' /// field. pub fn is_response(&self) -> bool { self.0.get("id").is_some() && self.0.get("method").is_none() } /// Attempts to convert the underlying `Value` into an RPC response /// object, and returns the result. /// /// The caller is expected to verify that the object is a response /// before calling this method. /// /// # Errors /// /// If the `Value` is not a well formed response object, this will /// return a `String` containing an error message. The caller should /// print this message and exit. pub fn into_response(mut self) -> Result<Response, String> { let _ = self.get_id().ok_or("Response requires 'id' field.".to_string())?; if self.0.get("result").is_some() == self.0.get("error").is_some() { return Err("RPC response must contain exactly one of\ 'error' or 'result' fields." .into()); } let result = self.0.as_object_mut().and_then(|obj| obj.remove("result")); match result { Some(r) => Ok(Ok(r)), None => { let error = self.0.as_object_mut().and_then(|obj| obj.remove("error")).unwrap(); match serde_json::from_value::<RemoteError>(error) { Ok(e) => Ok(Err(e)), Err(e) => Err(format!("Error handling response: {:?}", e)), } } } } /// Attempts to convert the underlying `Value` into either an RPC /// notification or request. /// /// # Errors /// /// Returns a `serde_json::Error` if the `Value` cannot be converted /// to one of the expected types. pub fn into_rpc<N, R>(self) -> Result<Call<N, R>, JsonError> where N: DeserializeOwned, R: DeserializeOwned, { let id = self.get_id(); match id { Some(id) => match serde_json::from_value::<R>(self.0) { Ok(resp) => Ok(Call::Request(id, resp)), Err(err) => Ok(Call::InvalidRequest(id, err.into())), }, None => { let result = serde_json::from_value::<N>(self.0)?; Ok(Call::Notification(result)) } } } } impl From<Value> for RpcObject { fn from(v: Value) -> RpcObject { RpcObject(v) } } #[cfg(test)] mod tests { use super::*; #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "snake_case")] #[serde(tag = "method", content = "params")] enum TestR { NewView { file_path: Option<String> }, OldView { file_path: usize }, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "snake_case")] #[serde(tag = "method", content = "params")] enum TestN { CloseView { view_id: String }, Save { view_id: String, file_path: String }, } #[test] fn request_success() { let json = r#"{"id":0,"method":"new_view","params":{}}"#; let p: RpcObject = serde_json::from_str::<Value>(json).unwrap().into(); assert!(!p.is_response()); let req = p.into_rpc::<TestN, TestR>().unwrap(); assert_eq!(req, Call::Request(0, TestR::NewView { file_path: None })); } #[test] fn request_failure() { // method does not exist let json = r#"{"id":0,"method":"new_truth","params":{}}"#; let p: RpcObject = serde_json::from_str::<Value>(json).unwrap().into(); let req = p.into_rpc::<TestN, TestR>().unwrap(); let is_ok = matches!(req, Call::InvalidRequest(0, _)); if !is_ok { panic!("{:?}", req); } } #[test] fn notif_with_id() { // method is a notification, should not have ID let json = r#"{"id":0,"method":"close_view","params":{"view_id": "view-id-1"}}"#; let p: RpcObject = serde_json::from_str::<Value>(json).unwrap().into(); let req = p.into_rpc::<TestN, TestR>().unwrap(); let is_ok = matches!(req, Call::InvalidRequest(0, _)); if !is_ok { panic!("{:?}", req); } } #[test] fn test_resp_err() { let json = r#"{"id":5,"error":{"code":420, "message":"chill out"}}"#; let p: RpcObject = serde_json::from_str::<Value>(json).unwrap().into(); assert!(p.is_response()); let resp = p.into_response().unwrap(); assert_eq!(resp, Err(RemoteError::custom(420, "chill out", None))); } #[test] fn test_resp_result() { let json = r#"{"id":5,"result":"success!"}"#; let p: RpcObject = serde_json::from_str::<Value>(json).unwrap().into(); assert!(p.is_response()); let resp = p.into_response().unwrap(); assert_eq!(resp, Ok(json!("success!"))); } #[test] fn test_err() { let json = r#"{"code": -32600, "message": "Invalid Request"}"#; let e = serde_json::from_str::<RemoteError>(json).unwrap(); assert_eq!(e, RemoteError::InvalidRequest(None)); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rpc/src/test_utils.rs
rust/rpc/src/test_utils.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Types and helpers used for testing. use std::io::{self, Cursor, Write}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::time::{Duration, Instant}; use serde_json::{self, Value}; use super::{Callback, Error, MessageReader, Peer, ReadError, Response, RpcObject}; /// Wraps an instance of `mpsc::Sender`, implementing `Write`. /// /// This lets the tx side of an mpsc::channel serve as the destination /// stream for an RPC loop. pub struct DummyWriter(Sender<String>); /// Wraps an instance of `mpsc::Receiver`, providing convenience methods /// for parsing received messages. pub struct DummyReader(MessageReader, Receiver<String>); /// An Peer that doesn't do anything. #[derive(Debug, Clone)] pub struct DummyPeer; /// Returns a `(DummyWriter, DummyReader)` pair. pub fn test_channel() -> (DummyWriter, DummyReader) { let (tx, rx) = channel(); (DummyWriter(tx), DummyReader(MessageReader::default(), rx)) } /// Given a string type, returns a `Cursor<Vec<u8>>`, which implements /// `BufRead`. pub fn make_reader<S: AsRef<str>>(s: S) -> Cursor<Vec<u8>> { Cursor::new(s.as_ref().as_bytes().to_vec()) } impl DummyReader { /// Attempts to read a message, returning `None` if the wait exceeds /// `timeout`. /// /// This method makes no assumptions about the contents of the /// message, and does no error handling. pub fn next_timeout(&mut self, timeout: Duration) -> Option<Result<RpcObject, ReadError>> { self.1.recv_timeout(timeout).ok().map(|s| self.0.parse(&s)) } /// Reads and parses a response object. /// /// # Panics /// /// Panics if a non-response message is received, or if no message /// is received after a reasonable time. pub fn expect_response(&mut self) -> Response { let raw = self.next_timeout(Duration::from_secs(1)).expect("response should be received"); let val = raw.as_ref().ok().map(|v| serde_json::to_string(&v.0)); let resp = raw.map_err(|e| e.to_string()).and_then(|r| r.into_response()); match resp { Err(msg) => panic!("Bad response: {:?}. {}", val, msg), Ok(resp) => resp, } } pub fn expect_object(&mut self) -> RpcObject { self.next_timeout(Duration::from_secs(1)).expect("expected object").unwrap() } pub fn expect_rpc(&mut self, method: &str) -> RpcObject { let obj = self .next_timeout(Duration::from_secs(1)) .unwrap_or_else(|| panic!("expected rpc \"{}\"", method)) .unwrap(); assert_eq!(obj.get_method(), Some(method)); obj } pub fn expect_nothing(&mut self) { if let Some(thing) = self.next_timeout(Duration::from_millis(500)) { panic!("unexpected something {:?}", thing); } } } impl Write for DummyWriter { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let s = String::from_utf8(buf.to_vec()).unwrap(); self.0 .send(s) .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err))) .map(|_| buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl Peer for DummyPeer { fn box_clone(&self) -> Box<dyn Peer> { Box::new(self.clone()) } fn send_rpc_notification(&self, _method: &str, _params: &Value) {} fn send_rpc_request_async(&self, _method: &str, _params: &Value, f: Box<dyn Callback>) { f.call(Ok("dummy peer".into())) } fn send_rpc_request(&self, _method: &str, _params: &Value) -> Result<Value, Error> { Ok("dummy peer".into()) } fn request_is_pending(&self) -> bool { false } fn schedule_idle(&self, _token: usize) {} fn schedule_timer(&self, _time: Instant, _token: usize) {} }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rpc/src/error.rs
rust/rpc/src/error.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt; use std::io; use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; use serde_json::{Error as JsonError, Value}; /// The possible error outcomes when attempting to send a message. #[derive(Debug)] pub enum Error { /// An IO error occurred on the underlying communication channel. Io(io::Error), /// The peer returned an error. RemoteError(RemoteError), /// The peer closed the connection. PeerDisconnect, /// The peer sent a response containing the id, but was malformed. InvalidResponse, } /// The possible error outcomes when attempting to read a message. #[derive(Debug)] pub enum ReadError { /// An error occurred in the underlying stream Io(io::Error), /// The message was not valid JSON. Json(JsonError), /// The message was not a JSON object. NotObject, /// The the method and params were not recognized by the handler. UnknownRequest(JsonError), /// The peer closed the connection. Disconnect, } /// Errors that can be received from the other side of the RPC channel. /// /// This type is intended to go over the wire. And by convention /// should `Serialize` as a JSON object with "code", "message", /// and optionally "data" fields. /// /// The xi RPC protocol defines one error: `RemoteError::InvalidRequest`, /// represented by error code `-32600`; however codes in the range /// `-32700 ... -32000` (inclusive) are reserved for compatability with /// the JSON-RPC spec. /// /// # Examples /// /// An invalid request: /// /// ``` /// # extern crate xi_rpc; /// # extern crate serde_json; /// use xi_rpc::RemoteError; /// use serde_json::Value; /// /// let json = r#"{ /// "code": -32600, /// "message": "Invalid request", /// "data": "Additional details" /// }"#; /// /// let err = serde_json::from_str::<RemoteError>(&json).unwrap(); /// assert_eq!(err, /// RemoteError::InvalidRequest( /// Some(Value::String("Additional details".into())))); /// ``` /// /// A custom error: /// /// ``` /// # extern crate xi_rpc; /// # extern crate serde_json; /// use xi_rpc::RemoteError; /// use serde_json::Value; /// /// let json = r#"{ /// "code": 404, /// "message": "Not Found" /// }"#; /// /// let err = serde_json::from_str::<RemoteError>(&json).unwrap(); /// assert_eq!(err, RemoteError::custom(404, "Not Found", None)); /// ``` #[derive(Debug, Clone, PartialEq)] pub enum RemoteError { /// The JSON was valid, but was not a correctly formed request. /// /// This Error is used internally, and should not be returned by /// clients. InvalidRequest(Option<Value>), /// A custom error, defined by the client. Custom { code: i64, message: String, data: Option<Value> }, /// An error that cannot be represented by an error object. /// /// This error is intended to accommodate clients that return arbitrary /// error values. It should not be used for new errors. Unknown(Value), } impl RemoteError { /// Creates a new custom error. pub fn custom<S, V>(code: i64, message: S, data: V) -> Self where S: AsRef<str>, V: Into<Option<Value>>, { let message = message.as_ref().into(); let data = data.into(); RemoteError::Custom { code, message, data } } } impl ReadError { /// Returns `true` iff this is the `ReadError::Disconnect` variant. pub fn is_disconnect(&self) -> bool { matches!(*self, ReadError::Disconnect) } } impl fmt::Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ReadError::Io(ref err) => write!(f, "I/O Error: {:?}", err), ReadError::Json(ref err) => write!(f, "JSON Error: {:?}", err), ReadError::NotObject => write!(f, "JSON message was not an object."), ReadError::UnknownRequest(ref err) => write!(f, "Unknown request: {:?}", err), ReadError::Disconnect => write!(f, "Peer closed the connection."), } } } impl From<JsonError> for ReadError { fn from(err: JsonError) -> ReadError { ReadError::Json(err) } } impl From<io::Error> for ReadError { fn from(err: io::Error) -> ReadError { ReadError::Io(err) } } impl From<JsonError> for RemoteError { fn from(err: JsonError) -> RemoteError { RemoteError::InvalidRequest(Some(json!(err.to_string()))) } } impl From<RemoteError> for Error { fn from(err: RemoteError) -> Error { Error::RemoteError(err) } } #[derive(Deserialize, Serialize)] struct ErrorHelper { code: i64, message: String, #[serde(skip_serializing_if = "Option::is_none")] data: Option<Value>, } impl<'de> Deserialize<'de> for RemoteError { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let v = Value::deserialize(deserializer)?; let resp = match ErrorHelper::deserialize(&v) { Ok(resp) => resp, Err(_) => return Ok(RemoteError::Unknown(v)), }; Ok(match resp.code { -32600 => RemoteError::InvalidRequest(resp.data), _ => RemoteError::Custom { code: resp.code, message: resp.message, data: resp.data }, }) } } impl Serialize for RemoteError { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let (code, message, data) = match *self { RemoteError::InvalidRequest(ref d) => (-32600, "Invalid request", d), RemoteError::Custom { code, ref message, ref data } => (code, message.as_ref(), data), RemoteError::Unknown(_) => panic!( "The 'Unknown' error variant is \ not intended for client use." ), }; let message = message.to_owned(); let data = data.to_owned(); let err = ErrorHelper { code, message, data }; err.serialize(serializer) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rpc/tests/integration.rs
rust/rpc/tests/integration.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate serde_json; extern crate xi_rpc; use std::io; use std::time::Duration; use serde_json::Value; use xi_rpc::test_utils::{make_reader, test_channel}; use xi_rpc::{Handler, ReadError, RemoteError, RpcCall, RpcCtx, RpcLoop}; /// Handler that responds to requests with whatever params they sent. pub struct EchoHandler; #[allow(unused)] impl Handler for EchoHandler { type Notification = RpcCall; type Request = RpcCall; fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) {} fn handle_request(&mut self, ctx: &RpcCtx, rpc: Self::Request) -> Result<Value, RemoteError> { Ok(rpc.params) } } #[test] fn test_recv_notif() { // we should not reply to a well formed notification let mut handler = EchoHandler; let (tx, mut rx) = test_channel(); let mut rpc_looper = RpcLoop::new(tx); let r = make_reader(r#"{"method": "hullo", "params": {"words": "plz"}}"#); assert!(rpc_looper.mainloop(|| r, &mut handler).is_ok()); let resp = rx.next_timeout(Duration::from_millis(100)); assert!(resp.is_none()); } #[test] fn test_recv_resp() { // we should reply to a well formed request let mut handler = EchoHandler; let (tx, mut rx) = test_channel(); let mut rpc_looper = RpcLoop::new(tx); let r = make_reader(r#"{"id": 1, "method": "hullo", "params": {"words": "plz"}}"#); assert!(rpc_looper.mainloop(|| r, &mut handler).is_ok()); let resp = rx.expect_response().unwrap(); assert_eq!(resp["words"], json!("plz")); // do it again let r = make_reader(r#"{"id": 0, "method": "hullo", "params": {"words": "yay"}}"#); assert!(rpc_looper.mainloop(|| r, &mut handler).is_ok()); let resp = rx.expect_response().unwrap(); assert_eq!(resp["words"], json!("yay")); } #[test] fn test_recv_error() { // a malformed request containing an ID should receive an error let mut handler = EchoHandler; let (tx, mut rx) = test_channel(); let mut rpc_looper = RpcLoop::new(tx); let r = make_reader(r#"{"id": 0, "method": "hullo","args": {"args": "should", "be": "params"}}"#); assert!(rpc_looper.mainloop(|| r, &mut handler).is_ok()); let resp = rx.expect_response(); assert!(resp.is_err(), "{:?}", resp); } #[test] fn test_bad_json_err() { // malformed json should cause the runloop to return an error. let mut handler = EchoHandler; let mut rpc_looper = RpcLoop::new(io::sink()); let r = make_reader(r#"this is not valid json"#); let exit = rpc_looper.mainloop(|| r, &mut handler); match exit { Err(ReadError::Json(_)) => (), Err(err) => panic!("Incorrect error: {:?}", err), Ok(()) => panic!("Expected an error"), } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rpc/examples/try_chan.rs
rust/rpc/examples/try_chan.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A simple test program for evaluating the speed of cross-thread communications. extern crate xi_rpc; use std::sync::mpsc; use std::thread; /* use xi_rpc::chan::Chan; pub fn test_chan() { let n_iter = 1000000; let chan1 = Chan::new(); let chan1s = chan1.clone(); let chan2 = Chan::new(); let chan2s = chan2.clone(); let thread1 = thread::spawn(move|| { for _ in 0..n_iter { chan2s.try_send(chan1.recv()); } }); let thread2 = thread::spawn(move|| { for _ in 0..n_iter { chan1s.try_send(42); let _ = chan2.recv(); } }); let _ = thread1.join(); let _ = thread2.join(); } */ pub fn test_mpsc() { let n_iter = 1000000; let (chan1s, chan1) = mpsc::channel(); let (chan2s, chan2) = mpsc::channel(); let thread1 = thread::spawn(move || { for _ in 0..n_iter { chan2s.send(chan1.recv()).unwrap(); } }); let thread2 = thread::spawn(move || { for _ in 0..n_iter { chan1s.send(42).unwrap(); let _ = chan2.recv(); } }); let _ = thread1.join(); let _ = thread2.join(); } pub fn main() { test_mpsc() }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/trace/src/lib.rs
rust/trace/src/lib.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![cfg_attr(feature = "benchmarks", feature(test))] #![allow(clippy::identity_op, clippy::new_without_default, clippy::trivially_copy_pass_by_ref)] #[macro_use] extern crate lazy_static; extern crate time; #[macro_use] extern crate serde_derive; extern crate serde; #[macro_use] extern crate log; extern crate libc; #[cfg(feature = "benchmarks")] extern crate test; #[cfg(any(test, feature = "json_payload", feature = "chroma_trace_dump"))] #[cfg_attr(any(test), macro_use)] extern crate serde_json; mod fixed_lifo_deque; mod sys_pid; mod sys_tid; #[cfg(feature = "chrome_trace_event")] pub mod chrome_trace_dump; use crate::fixed_lifo_deque::FixedLifoDeque; use std::borrow::Cow; use std::cmp; use std::collections::HashMap; use std::fmt; use std::fs; use std::hash::{Hash, Hasher}; use std::mem::size_of; use std::path::Path; use std::string::ToString; use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::sync::Mutex; pub type StrCow = Cow<'static, str>; #[derive(Clone, Debug)] pub enum CategoriesT { StaticArray(&'static [&'static str]), DynamicArray(Vec<String>), } trait StringArrayEq<Rhs: ?Sized = Self> { fn arr_eq(&self, other: &Rhs) -> bool; } impl StringArrayEq<[&'static str]> for Vec<String> { fn arr_eq(&self, other: &[&'static str]) -> bool { if self.len() != other.len() { return false; } for i in 0..self.len() { if self[i] != other[i] { return false; } } true } } impl StringArrayEq<Vec<String>> for &'static [&'static str] { fn arr_eq(&self, other: &Vec<String>) -> bool { if self.len() != other.len() { return false; } for i in 0..self.len() { if self[i] != other[i] { return false; } } true } } impl PartialEq for CategoriesT { fn eq(&self, other: &CategoriesT) -> bool { match *self { CategoriesT::StaticArray(ref self_arr) => match *other { CategoriesT::StaticArray(ref other_arr) => self_arr.eq(other_arr), CategoriesT::DynamicArray(ref other_arr) => self_arr.arr_eq(other_arr), }, CategoriesT::DynamicArray(ref self_arr) => match *other { CategoriesT::StaticArray(other_arr) => self_arr.arr_eq(other_arr), CategoriesT::DynamicArray(ref other_arr) => self_arr.eq(other_arr), }, } } } impl Eq for CategoriesT {} impl serde::Serialize for CategoriesT { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.join(",").serialize(serializer) } } impl<'de> serde::Deserialize<'de> for CategoriesT { fn deserialize<D>(deserializer: D) -> Result<CategoriesT, D::Error> where D: serde::Deserializer<'de>, { use serde::de::Visitor; struct CategoriesTVisitor; impl<'de> Visitor<'de> for CategoriesTVisitor { type Value = CategoriesT; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("comma-separated strings") } fn visit_str<E>(self, v: &str) -> Result<CategoriesT, E> where E: serde::de::Error, { let categories = v.split(',').map(ToString::to_string).collect(); Ok(CategoriesT::DynamicArray(categories)) } } deserializer.deserialize_str(CategoriesTVisitor) } } impl CategoriesT { pub fn join(&self, sep: &str) -> String { match *self { CategoriesT::StaticArray(arr) => arr.join(sep), CategoriesT::DynamicArray(ref vec) => vec.join(sep), } } } macro_rules! categories_from_constant_array { ($num_args: expr) => { impl From<&'static [&'static str; $num_args]> for CategoriesT { fn from(c: &'static [&'static str; $num_args]) -> CategoriesT { CategoriesT::StaticArray(c) } } }; } categories_from_constant_array!(0); categories_from_constant_array!(1); categories_from_constant_array!(2); categories_from_constant_array!(3); categories_from_constant_array!(4); categories_from_constant_array!(5); categories_from_constant_array!(6); categories_from_constant_array!(7); categories_from_constant_array!(8); categories_from_constant_array!(9); categories_from_constant_array!(10); impl From<Vec<String>> for CategoriesT { fn from(c: Vec<String>) -> CategoriesT { CategoriesT::DynamicArray(c) } } #[cfg(not(feature = "json_payload"))] pub type TracePayloadT = StrCow; #[cfg(feature = "json_payload")] pub type TracePayloadT = serde_json::Value; /// How tracing should be configured. #[derive(Copy, Clone)] pub struct Config { sample_limit_count: usize, } impl Config { /// The maximum number of bytes the tracing data should take up. This limit /// won't be exceeded by the underlying storage itself (i.e. rounds down). pub fn with_limit_bytes(size: usize) -> Self { Self::with_limit_count(size / size_of::<Sample>()) } /// The maximum number of entries the tracing data should allow. Total /// storage allocated will be limit * size_of<Sample> pub fn with_limit_count(limit: usize) -> Self { Self { sample_limit_count: limit } } /// The default amount of storage to allocate for tracing. Currently 1 MB. pub fn default() -> Self { // 1 MB Self::with_limit_bytes(1 * 1024 * 1024) } /// The maximum amount of space the tracing data will take up. This does /// not account for any overhead of storing the data itself (i.e. pointer to /// the heap, counters, etc); just the data itself. pub fn max_size_in_bytes(self) -> usize { self.sample_limit_count * size_of::<Sample>() } /// The maximum number of samples that should be stored. pub fn max_samples(self) -> usize { self.sample_limit_count } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SampleEventType { DurationBegin, DurationEnd, CompleteDuration, Instant, AsyncStart, AsyncInstant, AsyncEnd, FlowStart, FlowInstant, FlowEnd, ObjectCreated, ObjectSnapshot, ObjectDestroyed, Metadata, } impl SampleEventType { // TODO(vlovich): Replace all of this with serde flatten + rename once // https://github.com/serde-rs/serde/issues/1189 is fixed. #[inline] fn into_chrome_id(self) -> char { match self { SampleEventType::DurationBegin => 'B', SampleEventType::DurationEnd => 'E', SampleEventType::CompleteDuration => 'X', SampleEventType::Instant => 'i', SampleEventType::AsyncStart => 'b', SampleEventType::AsyncInstant => 'n', SampleEventType::AsyncEnd => 'e', SampleEventType::FlowStart => 's', SampleEventType::FlowInstant => 't', SampleEventType::FlowEnd => 'f', SampleEventType::ObjectCreated => 'N', SampleEventType::ObjectSnapshot => 'O', SampleEventType::ObjectDestroyed => 'D', SampleEventType::Metadata => 'M', } } #[inline] fn from_chrome_id(symbol: char) -> Self { match symbol { 'B' => SampleEventType::DurationBegin, 'E' => SampleEventType::DurationEnd, 'X' => SampleEventType::CompleteDuration, 'i' => SampleEventType::Instant, 'b' => SampleEventType::AsyncStart, 'n' => SampleEventType::AsyncInstant, 'e' => SampleEventType::AsyncEnd, 's' => SampleEventType::FlowStart, 't' => SampleEventType::FlowInstant, 'f' => SampleEventType::FlowEnd, 'N' => SampleEventType::ObjectCreated, 'O' => SampleEventType::ObjectSnapshot, 'D' => SampleEventType::ObjectDestroyed, 'M' => SampleEventType::Metadata, _ => panic!("Unexpected chrome sample type '{}'", symbol), } } } #[derive(Clone, Debug, PartialEq, Eq)] enum MetadataType { ProcessName { name: String, }, #[allow(dead_code)] ProcessLabels { labels: String, }, #[allow(dead_code)] ProcessSortIndex { sort_index: i32, }, ThreadName { name: String, }, #[allow(dead_code)] ThreadSortIndex { sort_index: i32, }, } impl MetadataType { fn sample_name(&self) -> &'static str { match *self { MetadataType::ProcessName { .. } => "process_name", MetadataType::ProcessLabels { .. } => "process_labels", MetadataType::ProcessSortIndex { .. } => "process_sort_index", MetadataType::ThreadName { .. } => "thread_name", MetadataType::ThreadSortIndex { .. } => "thread_sort_index", } } fn consume(self) -> (Option<String>, Option<i32>) { match self { MetadataType::ProcessName { name } => (Some(name), None), MetadataType::ThreadName { name } => (Some(name), None), MetadataType::ProcessSortIndex { sort_index } => (None, Some(sort_index)), MetadataType::ThreadSortIndex { sort_index } => (None, Some(sort_index)), MetadataType::ProcessLabels { .. } => (None, None), } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct SampleArgs { /// An arbitrary payload to associate with the sample. The type is /// controlled by features (default string). #[serde(rename = "xi_payload")] #[serde(skip_serializing_if = "Option::is_none")] pub payload: Option<TracePayloadT>, /// The name to associate with the pid/tid. Whether it's associated with /// the pid or the tid depends on the name of the event /// via process_name/thread_name respectively. #[serde(rename = "name")] #[serde(skip_serializing_if = "Option::is_none")] pub metadata_name: Option<StrCow>, /// Sorting priority between processes/threads in the view. #[serde(rename = "sort_index")] #[serde(skip_serializing_if = "Option::is_none")] pub metadata_sort_index: Option<i32>, } #[inline] fn ns_to_us(ns: u64) -> u64 { ns / 1000 } //NOTE: serde requires this to take a reference fn serialize_event_type<S>(ph: &SampleEventType, s: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { s.serialize_char(ph.into_chrome_id()) } fn deserialize_event_type<'de, D>(d: D) -> Result<SampleEventType, D::Error> where D: serde::Deserializer<'de>, { serde::Deserialize::deserialize(d).map(SampleEventType::from_chrome_id) } /// Stores the relevant data about a sample for later serialization. /// The payload associated with any sample is by default a string but may be /// configured via the `json_payload` feature (there is an /// associated performance hit across the board for turning it on). #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Sample { /// The name of the event to be shown. pub name: StrCow, /// List of categories the event applies to. #[serde(rename = "cat")] #[serde(skip_serializing_if = "Option::is_none")] pub categories: Option<CategoriesT>, /// When was the sample started. #[serde(rename = "ts")] pub timestamp_us: u64, /// What kind of sample this is. #[serde(rename = "ph")] #[serde(serialize_with = "serialize_event_type")] #[serde(deserialize_with = "deserialize_event_type")] pub event_type: SampleEventType, #[serde(rename = "dur")] #[serde(skip_serializing_if = "Option::is_none")] pub duration_us: Option<u64>, /// The process the sample was captured in. pub pid: u64, /// The thread the sample was captured on. Omitted for Metadata events that /// want to set the process name (if provided then sets the thread name). pub tid: u64, #[serde(skip_serializing)] pub thread_name: Option<StrCow>, #[serde(skip_serializing_if = "Option::is_none")] pub args: Option<SampleArgs>, } fn to_cow_str<S>(s: S) -> StrCow where S: Into<StrCow>, { s.into() } impl Sample { fn thread_name() -> Option<StrCow> { let thread = std::thread::current(); thread.name().map(|s| to_cow_str((*s).to_string())) } /// Constructs a Begin or End sample. Should not be used directly. Instead /// should be constructed via SampleGuard. pub fn new_duration_marker<S, C>( name: S, categories: C, payload: Option<TracePayloadT>, event_type: SampleEventType, ) -> Self where S: Into<StrCow>, C: Into<CategoriesT>, { Self { name: name.into(), categories: Some(categories.into()), timestamp_us: ns_to_us(time::precise_time_ns()), event_type, duration_us: None, tid: sys_tid::current_tid().unwrap(), thread_name: Sample::thread_name(), pid: sys_pid::current_pid(), args: Some(SampleArgs { payload, metadata_name: None, metadata_sort_index: None }), } } /// Constructs a Duration sample. For use via xi_trace::closure. pub fn new_duration<S, C>( name: S, categories: C, payload: Option<TracePayloadT>, start_ns: u64, duration_ns: u64, ) -> Self where S: Into<StrCow>, C: Into<CategoriesT>, { Self { name: name.into(), categories: Some(categories.into()), timestamp_us: ns_to_us(start_ns), event_type: SampleEventType::CompleteDuration, duration_us: Some(ns_to_us(duration_ns)), tid: sys_tid::current_tid().unwrap(), thread_name: Sample::thread_name(), pid: sys_pid::current_pid(), args: Some(SampleArgs { payload, metadata_name: None, metadata_sort_index: None }), } } /// Constructs an instantaneous sample. pub fn new_instant<S, C>(name: S, categories: C, payload: Option<TracePayloadT>) -> Self where S: Into<StrCow>, C: Into<CategoriesT>, { Self { name: name.into(), categories: Some(categories.into()), timestamp_us: ns_to_us(time::precise_time_ns()), event_type: SampleEventType::Instant, duration_us: None, tid: sys_tid::current_tid().unwrap(), thread_name: Sample::thread_name(), pid: sys_pid::current_pid(), args: Some(SampleArgs { payload, metadata_name: None, metadata_sort_index: None }), } } fn new_metadata(timestamp_ns: u64, meta: MetadataType, tid: u64) -> Self { let sample_name = to_cow_str(meta.sample_name()); let (metadata_name, sort_index) = meta.consume(); Self { name: sample_name, categories: None, timestamp_us: ns_to_us(timestamp_ns), event_type: SampleEventType::Metadata, duration_us: None, tid, thread_name: None, pid: sys_pid::current_pid(), args: Some(SampleArgs { payload: None, metadata_name: metadata_name.map(Cow::Owned), metadata_sort_index: sort_index, }), } } } impl PartialEq for Sample { fn eq(&self, other: &Sample) -> bool { self.timestamp_us == other.timestamp_us && self.name == other.name && self.categories == other.categories && self.pid == other.pid && self.tid == other.tid && self.event_type == other.event_type && self.args == other.args } } impl Eq for Sample {} impl PartialOrd for Sample { fn partial_cmp(&self, other: &Sample) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for Sample { fn cmp(&self, other: &Sample) -> cmp::Ordering { self.timestamp_us.cmp(&other.timestamp_us) } } impl Hash for Sample { fn hash<H: Hasher>(&self, state: &mut H) { (self.pid, self.timestamp_us).hash(state); } } #[must_use] pub struct SampleGuard<'a> { sample: Option<Sample>, trace: Option<&'a Trace>, } impl<'a> SampleGuard<'a> { #[inline] pub fn new_disabled() -> Self { Self { sample: None, trace: None } } #[inline] fn new<S, C>(trace: &'a Trace, name: S, categories: C, payload: Option<TracePayloadT>) -> Self where S: Into<StrCow>, C: Into<CategoriesT>, { // TODO(vlovich): optimize this path to use the Complete event type // rather than emitting an explicit start/stop to reduce the size of // the generated JSON. let guard = Self { sample: Some(Sample::new_duration_marker( name, categories, payload, SampleEventType::DurationBegin, )), trace: Some(trace), }; trace.record(guard.sample.as_ref().unwrap().clone()); guard } } impl<'a> Drop for SampleGuard<'a> { fn drop(&mut self) { if let Some(ref mut trace) = self.trace { let mut sample = self.sample.take().unwrap(); sample.timestamp_us = ns_to_us(time::precise_time_ns()); sample.event_type = SampleEventType::DurationEnd; trace.record(sample); } } } /// Returns the file name of the EXE if possible, otherwise the full path, or /// None if an irrecoverable error occured. fn exe_name() -> Option<String> { match std::env::current_exe() { Ok(exe_name) => match exe_name.file_name() { Some(filename) => filename.to_str().map(ToString::to_string), None => { let full_path = exe_name.into_os_string(); let full_path_str = full_path.into_string(); match full_path_str { Ok(s) => Some(s), Err(e) => { warn!("Failed to get string representation: {:?}", e); None } } } }, Err(ref e) => { warn!("Failed to get path to current exe: {:?}", e); None } } } /// Stores the tracing data. pub struct Trace { enabled: AtomicBool, samples: Mutex<FixedLifoDeque<Sample>>, } impl Trace { pub fn disabled() -> Self { Self { enabled: AtomicBool::new(false), samples: Mutex::new(FixedLifoDeque::new()) } } pub fn enabled(config: Config) -> Self { Self { enabled: AtomicBool::new(true), samples: Mutex::new(FixedLifoDeque::with_limit(config.max_samples())), } } pub fn disable(&self) { let mut all_samples = self.samples.lock().unwrap(); all_samples.reset_limit(0); self.enabled.store(false, AtomicOrdering::Relaxed); } #[inline] pub fn enable(&self) { self.enable_config(Config::default()); } pub fn enable_config(&self, config: Config) { let mut all_samples = self.samples.lock().unwrap(); all_samples.reset_limit(config.max_samples()); self.enabled.store(true, AtomicOrdering::Relaxed); } /// Generally racy since the underlying storage might be mutated in a separate thread. /// Exposed for unit tests. pub fn get_samples_count(&self) -> usize { self.samples.lock().unwrap().len() } /// Exposed for unit tests only. pub fn get_samples_limit(&self) -> usize { self.samples.lock().unwrap().limit() } #[inline] pub(crate) fn record(&self, sample: Sample) { let mut all_samples = self.samples.lock().unwrap(); all_samples.push_back(sample); } pub fn is_enabled(&self) -> bool { self.enabled.load(AtomicOrdering::Relaxed) } pub fn instant<S, C>(&self, name: S, categories: C) where S: Into<StrCow>, C: Into<CategoriesT>, { if self.is_enabled() { self.record(Sample::new_instant(name, categories, None)); } } pub fn instant_payload<S, C, P>(&self, name: S, categories: C, payload: P) where S: Into<StrCow>, C: Into<CategoriesT>, P: Into<TracePayloadT>, { if self.is_enabled() { self.record(Sample::new_instant(name, categories, Some(payload.into()))); } } pub fn block<S, C>(&self, name: S, categories: C) -> SampleGuard where S: Into<StrCow>, C: Into<CategoriesT>, { if !self.is_enabled() { SampleGuard::new_disabled() } else { SampleGuard::new(self, name, categories, None) } } pub fn block_payload<S, C, P>(&self, name: S, categories: C, payload: P) -> SampleGuard where S: Into<StrCow>, C: Into<CategoriesT>, P: Into<TracePayloadT>, { if !self.is_enabled() { SampleGuard::new_disabled() } else { SampleGuard::new(self, name, categories, Some(payload.into())) } } pub fn closure<S, C, F, R>(&self, name: S, categories: C, closure: F) -> R where S: Into<StrCow>, C: Into<CategoriesT>, F: FnOnce() -> R, { // TODO: simplify this through the use of scopeguard crate let start = time::precise_time_ns(); let result = closure(); let end = time::precise_time_ns(); if self.is_enabled() { self.record(Sample::new_duration(name, categories, None, start, end - start)); } result } pub fn closure_payload<S, C, P, F, R>( &self, name: S, categories: C, closure: F, payload: P, ) -> R where S: Into<StrCow>, C: Into<CategoriesT>, P: Into<TracePayloadT>, F: FnOnce() -> R, { // TODO: simplify this through the use of scopeguard crate let start = time::precise_time_ns(); let result = closure(); let end = time::precise_time_ns(); if self.is_enabled() { self.record(Sample::new_duration( name, categories, Some(payload.into()), start, end - start, )); } result } pub fn samples_cloned_unsorted(&self) -> Vec<Sample> { let all_samples = self.samples.lock().unwrap(); if all_samples.is_empty() { return Vec::with_capacity(0); } let mut as_vec = Vec::with_capacity(all_samples.len() + 10); let first_sample_timestamp = all_samples.front().map_or(0, |s| s.timestamp_us); let tid = all_samples.front().map_or_else(|| sys_tid::current_tid().unwrap(), |s| s.tid); if let Some(exe_name) = exe_name() { as_vec.push(Sample::new_metadata( first_sample_timestamp, MetadataType::ProcessName { name: exe_name }, tid, )); } let mut thread_names: HashMap<u64, StrCow> = HashMap::new(); for sample in all_samples.iter() { if let Some(ref thread_name) = sample.thread_name { let previous_name = thread_names.insert(sample.tid, thread_name.clone()); if previous_name.is_none() || previous_name.unwrap() != *thread_name { as_vec.push(Sample::new_metadata( first_sample_timestamp, MetadataType::ThreadName { name: thread_name.to_string() }, sample.tid, )); } } } as_vec.extend(all_samples.iter().cloned()); as_vec } #[inline] pub fn samples_cloned_sorted(&self) -> Vec<Sample> { let mut samples = self.samples_cloned_unsorted(); samples.sort_unstable(); samples } pub fn save<P: AsRef<Path>>( &self, path: P, sort: bool, ) -> Result<(), chrome_trace_dump::Error> { let traces = if sort { samples_cloned_sorted() } else { samples_cloned_unsorted() }; let path: &Path = path.as_ref(); if path.exists() { return Err(chrome_trace_dump::Error::already_exists()); } let mut trace_file = fs::File::create(&path)?; chrome_trace_dump::serialize(&traces, &mut trace_file) } } lazy_static! { static ref TRACE: Trace = Trace::disabled(); } /// Enable tracing with the default configuration. See Config::default. /// Tracing is disabled initially on program launch. #[inline] pub fn enable_tracing() { TRACE.enable(); } /// Enable tracing with a specific configuration. Tracing is disabled initially /// on program launch. #[inline] pub fn enable_tracing_with_config(config: Config) { TRACE.enable_config(config); } /// Disable tracing. This clears all trace data (& frees the memory). #[inline] pub fn disable_tracing() { TRACE.disable(); } /// Is tracing enabled. Technically doesn't guarantee any samples will be /// stored as tracing could still be enabled but set with a limit of 0. #[inline] pub fn is_enabled() -> bool { TRACE.is_enabled() } /// Create an instantaneous sample without any payload. This is the lowest /// overhead tracing routine available. /// /// # Performance /// The `json_payload` feature makes this ~1.3-~1.5x slower. /// See `trace_payload` for a more complete discussion. /// /// # Arguments /// /// * `name` - A string that provides some meaningful name to this sample. /// Usage of static strings is encouraged for best performance to avoid copies. /// However, anything that can be converted into a Cow string can be passed as /// an argument. /// /// * `categories` - A static array of static strings that tags the samples in /// some way. /// /// # Examples /// /// ``` /// xi_trace::trace("something happened", &["rpc", "response"]); /// ``` #[inline] pub fn trace<S, C>(name: S, categories: C) where S: Into<StrCow>, C: Into<CategoriesT>, { TRACE.instant(name, categories); } /// Create an instantaneous sample with a payload. The type the payload /// conforms to is currently determined by the feature this library is compiled /// with. By default, the type is string-like just like name. If compiled with /// the `json_payload` then a `serde_json::Value` is expected and the library /// acquires a dependency on the `serde_json` crate. /// /// # Performance /// A static string has the lowest overhead as no copies are necessary, roughly /// equivalent performance to a regular trace. A string that needs to be copied /// first can make it ~1.7x slower than a regular trace. /// /// When compiling with `json_payload`, this is ~2.1x slower than a string that /// needs to be copied (or ~4.5x slower than a static string) /// /// # Arguments /// /// * `name` - A string that provides some meaningful name to this sample. /// Usage of static strings is encouraged for best performance to avoid copies. /// However, anything that can be converted into a Cow string can be passed as /// an argument. /// /// * `categories` - A static array of static strings that tags the samples in /// some way. /// /// # Examples /// /// ``` /// xi_trace::trace_payload("something happened", &["rpc", "response"], "a note about this"); /// ``` /// /// With `json_payload` feature: /// /// ```rust,ignore /// xi_trace::trace_payload("my event", &["rpc", "response"], json!({"key": "value"})); /// ``` #[inline] pub fn trace_payload<S, C, P>(name: S, categories: C, payload: P) where S: Into<StrCow>, C: Into<CategoriesT>, P: Into<TracePayloadT>, { TRACE.instant_payload(name, categories, payload); } /// Creates a duration sample. The sample is finalized (end_ns set) when the /// returned value is dropped. `trace_closure` may be prettier to read. /// /// # Performance /// See `trace_payload` for a more complete discussion. /// /// # Arguments /// /// * `name` - A string that provides some meaningful name to this sample. /// Usage of static strings is encouraged for best performance to avoid copies. /// However, anything that can be converted into a Cow string can be passed as /// an argument. /// /// * `categories` - A static array of static strings that tags the samples in /// some way. /// /// # Returns /// A guard that when dropped will update the Sample with the timestamp & then /// record it. /// /// # Examples /// /// ``` /// fn something_expensive() { /// } /// /// fn something_else_expensive() { /// } /// /// let trace_guard = xi_trace::trace_block("something_expensive", &["rpc", "request"]); /// something_expensive(); /// std::mem::drop(trace_guard); // finalize explicitly if /// /// { /// let _guard = xi_trace::trace_block("something_else_expensive", &["rpc", "response"]); /// something_else_expensive(); /// } /// ``` #[inline] pub fn trace_block<'a, S, C>(name: S, categories: C) -> SampleGuard<'a> where S: Into<StrCow>, C: Into<CategoriesT>, { TRACE.block(name, categories) } /// See `trace_block` for how the block works and `trace_payload` for a /// discussion on payload. #[inline] pub fn trace_block_payload<'a, S, C, P>(name: S, categories: C, payload: P) -> SampleGuard<'a> where S: Into<StrCow>, C: Into<CategoriesT>, P: Into<TracePayloadT>, { TRACE.block_payload(name, categories, payload) } /// Creates a duration sample that measures how long the closure took to execute. /// /// # Performance /// See `trace_payload` for a more complete discussion. /// /// # Arguments /// /// * `name` - A string that provides some meaningful name to this sample. /// Usage of static strings is encouraged for best performance to avoid copies. /// However, anything that can be converted into a Cow string can be passed as /// an argument. /// /// * `categories` - A static array of static strings that tags the samples in /// some way. /// /// # Returns /// The result of the closure. /// /// # Examples /// /// ``` /// fn something_expensive() -> u32 { /// 0 /// } /// /// fn something_else_expensive(value: u32) { /// } /// /// let result = xi_trace::trace_closure("something_expensive", &["rpc", "request"], || { /// something_expensive() /// }); /// xi_trace::trace_closure("something_else_expensive", &["rpc", "response"], || { /// something_else_expensive(result); /// }); /// ``` #[inline] pub fn trace_closure<S, C, F, R>(name: S, categories: C, closure: F) -> R where S: Into<StrCow>, C: Into<CategoriesT>, F: FnOnce() -> R, { TRACE.closure(name, categories, closure) } /// See `trace_closure` for how the closure works and `trace_payload` for a /// discussion on payload. #[inline] pub fn trace_closure_payload<S, C, P, F, R>(name: S, categories: C, closure: F, payload: P) -> R where S: Into<StrCow>, C: Into<CategoriesT>, P: Into<TracePayloadT>, F: FnOnce() -> R, { TRACE.closure_payload(name, categories, closure, payload) } #[inline] pub fn samples_len() -> usize { TRACE.get_samples_count() } /// Returns all the samples collected so far. There is no guarantee that the /// samples are ordered chronologically for several reasons: /// /// 1. Samples that span sections of code may be inserted on end instead of /// beginning. /// 2. Performance optimizations might have per-thread buffers. Keeping all /// that sorted would be prohibitively expensive. /// 3. You may not care about them always being sorted if you're merging samples /// from multiple distributed sources (i.e. you want to sort the merged result /// rather than just this processe's samples). #[inline] pub fn samples_cloned_unsorted() -> Vec<Sample> { TRACE.samples_cloned_unsorted() } /// Returns all the samples collected so far ordered chronologically by /// creation. Roughly corresponds to start_ns but instead there's a
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
true
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/trace/src/sys_tid.rs
rust/trace/src/sys_tid.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[cfg(any(target_os = "macos", target_os = "ios"))] #[inline] pub fn current_tid() -> Result<u64, libc::c_int> { #[link(name = "pthread")] extern "C" { fn pthread_threadid_np(thread: libc::pthread_t, thread_id: *mut u64) -> libc::c_int; } unsafe { let mut tid = 0; let err = pthread_threadid_np(0, &mut tid); match err { 0 => Ok(tid), _ => Err(err), } } } #[cfg(target_os = "fuchsia")] #[inline] pub fn current_tid() -> Result<u64, libc::c_int> { // TODO: fill in for fuchsia. This is the native C API but maybe there are // rust-specific bindings already. /* extern { fn thrd_get_zx_handle(thread: thrd_t) -> zx_handle_t; fn thrd_current() -> thrd_t; } Ok(thrd_get_zx_handle(thrd_current()) as u64) */ Ok(0) } #[cfg(any(target_os = "linux", target_os = "android"))] #[inline] pub fn current_tid() -> Result<u64, libc::c_int> { unsafe { Ok(libc::syscall(libc::SYS_gettid) as u64) } } // TODO: maybe use https://github.com/alexcrichton/cfg-if to simplify this? // pthread-based fallback #[cfg(all( target_family = "unix", not(any( target_os = "macos", target_os = "ios", target_os = "linux", target_os = "android", target_os = "fuchsia" )) ))] pub fn current_tid() -> Result<u64, libc::c_int> { unsafe { Ok(libc::pthread_self() as u64) } } #[cfg(target_os = "windows")] #[inline] pub fn current_tid() -> Result<u64, libc::c_int> { extern "C" { fn GetCurrentThreadId() -> libc::c_ulong; } unsafe { Ok(u64::from(GetCurrentThreadId())) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/trace/src/fixed_lifo_deque.rs
rust/trace/src/fixed_lifo_deque.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::cmp::{self, Ordering}; use std::collections::vec_deque::{Drain, IntoIter, Iter, IterMut, VecDeque}; use std::hash::{Hash, Hasher}; use std::ops::{Index, IndexMut, RangeBounds}; /// Provides fixed size ring buffer that overwrites elements in FIFO order on /// insertion when full. API provided is similar to VecDeque & uses a VecDeque /// internally. One distinction is that only append-like insertion is allowed. /// This means that insert & push_front are not allowed. The reasoning is that /// there is ambiguity on how such functions should operate since it would be /// pretty impossible to maintain a FIFO ordering. /// /// All operations that would cause growth beyond the limit drop the appropriate /// number of elements from the front. For example, on a full buffer push_front /// replaces the first element. /// /// The removal of elements on operation that would cause excess beyond the /// limit happens first to make sure the space is available in the underlying /// VecDeque, thus guaranteeing O(1) operations always. #[derive(Clone, Debug)] pub struct FixedLifoDeque<T> { storage: VecDeque<T>, limit: usize, } impl<T> FixedLifoDeque<T> { /// Constructs a ring buffer that will reject all insertions as no-ops. /// This also construct the underlying VecDeque with_capacity(0) which /// in the current stdlib implementation allocates 2 Ts. #[inline] pub fn new() -> Self { FixedLifoDeque::with_limit(0) } /// Constructs a fixed size ring buffer with the given number of elements. /// Attempts to insert more than this number of elements will cause excess /// elements to first be evicted in FIFO order (i.e. from the front). pub fn with_limit(n: usize) -> Self { FixedLifoDeque { storage: VecDeque::with_capacity(n), limit: n } } /// This sets a new limit on the container. Excess elements are dropped in /// FIFO order. The new capacity is reset to the requested limit which will /// likely result in re-allocation + copies/clones even if the limit /// shrinks. pub fn reset_limit(&mut self, n: usize) { if n < self.limit { let overflow = self.limit - n; self.drop_excess_for_inserting(overflow); } self.limit = n; self.storage.reserve_exact(n); self.storage.shrink_to_fit(); debug_assert!(self.storage.len() <= self.limit); } /// Returns the current limit this ring buffer is configured with. #[inline] pub fn limit(&self) -> usize { self.limit } #[inline] pub fn get(&self, index: usize) -> Option<&T> { self.storage.get(index) } #[inline] pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { self.storage.get_mut(index) } #[inline] pub fn swap(&mut self, i: usize, j: usize) { self.storage.swap(i, j); } #[inline] pub fn capacity(&self) -> usize { self.limit } #[inline] pub fn iter(&self) -> Iter<T> { self.storage.iter() } #[inline] pub fn iter_mut(&mut self) -> IterMut<T> { self.storage.iter_mut() } /// Returns a tuple of 2 slices that represents the ring buffer. [0] is the /// beginning of the buffer to the physical end of the array or the last /// element (whichever comes first). [1] is the continuation of [0] if the /// ring buffer has wrapped the contiguous storage. #[inline] pub fn as_slices(&self) -> (&[T], &[T]) { self.storage.as_slices() } #[inline] pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) { self.storage.as_mut_slices() } #[inline] pub fn len(&self) -> usize { self.storage.len() } #[inline] pub fn is_empty(&self) -> bool { self.storage.is_empty() } #[inline] pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeBounds<usize>, { self.storage.drain(range) } #[inline] pub fn clear(&mut self) { self.storage.clear(); } #[inline] pub fn contains(&self, x: &T) -> bool where T: PartialEq<T>, { self.storage.contains(x) } #[inline] pub fn front(&self) -> Option<&T> { self.storage.front() } #[inline] pub fn front_mut(&mut self) -> Option<&mut T> { self.storage.front_mut() } #[inline] pub fn back(&self) -> Option<&T> { self.storage.back() } #[inline] pub fn back_mut(&mut self) -> Option<&mut T> { self.storage.back_mut() } #[inline] fn drop_excess_for_inserting(&mut self, n_to_be_inserted: usize) { if self.storage.len() + n_to_be_inserted > self.limit { let overflow = self.storage.len().min(self.storage.len() + n_to_be_inserted - self.limit); self.storage.drain(..overflow); } } /// Always an O(1) operation. Memory is never reclaimed. #[inline] pub fn pop_front(&mut self) -> Option<T> { self.storage.pop_front() } /// Always an O(1) operation. If the number of elements is at the limit, /// the element at the front is overwritten. /// /// Post condition: The number of elements is <= limit pub fn push_back(&mut self, value: T) { self.drop_excess_for_inserting(1); self.storage.push_back(value); // For when limit == 0 self.drop_excess_for_inserting(0); } /// Always an O(1) operation. Memory is never reclaimed. #[inline] pub fn pop_back(&mut self) -> Option<T> { self.storage.pop_back() } #[inline] pub fn swap_remove_back(&mut self, index: usize) -> Option<T> { self.storage.swap_remove_back(index) } #[inline] pub fn swap_remove_front(&mut self, index: usize) -> Option<T> { self.storage.swap_remove_front(index) } /// Always an O(1) operation. #[inline] pub fn remove(&mut self, index: usize) -> Option<T> { self.storage.remove(index) } pub fn split_off(&mut self, at: usize) -> FixedLifoDeque<T> { FixedLifoDeque { storage: self.storage.split_off(at), limit: self.limit } } /// Always an O(m) operation where m is the length of `other'. pub fn append(&mut self, other: &mut VecDeque<T>) { self.drop_excess_for_inserting(other.len()); self.storage.append(other); // For when limit == 0 self.drop_excess_for_inserting(0); } #[inline] pub fn retain<F>(&mut self, f: F) where F: FnMut(&T) -> bool, { self.storage.retain(f); } } impl<T: Clone> FixedLifoDeque<T> { /// Resizes a fixed queue. This doesn't change the limit so the resize is /// capped to the limit. Additionally, resizing drops the elements from the /// front unlike with a regular VecDeque. pub fn resize(&mut self, new_len: usize, value: T) { if new_len < self.len() { let to_drop = self.len() - new_len; self.storage.drain(..to_drop); } else { self.storage.resize(cmp::min(self.limit, new_len), value); } } } impl<A: PartialEq> PartialEq for FixedLifoDeque<A> { #[inline] fn eq(&self, other: &FixedLifoDeque<A>) -> bool { self.storage == other.storage } } impl<A: Eq> Eq for FixedLifoDeque<A> {} impl<A: PartialOrd> PartialOrd for FixedLifoDeque<A> { #[inline] fn partial_cmp(&self, other: &FixedLifoDeque<A>) -> Option<Ordering> { self.storage.partial_cmp(&other.storage) } } impl<A: Ord> Ord for FixedLifoDeque<A> { #[inline] fn cmp(&self, other: &FixedLifoDeque<A>) -> Ordering { self.storage.cmp(&other.storage) } } impl<A: Hash> Hash for FixedLifoDeque<A> { #[inline] fn hash<H: Hasher>(&self, state: &mut H) { self.storage.hash(state); } } impl<A> Index<usize> for FixedLifoDeque<A> { type Output = A; #[inline] fn index(&self, index: usize) -> &A { &self.storage[index] } } impl<A> IndexMut<usize> for FixedLifoDeque<A> { #[inline] fn index_mut(&mut self, index: usize) -> &mut A { &mut self.storage[index] } } impl<T> IntoIterator for FixedLifoDeque<T> { type Item = T; type IntoIter = IntoIter<T>; /// Consumes the list into a front-to-back iterator yielding elements by /// value. #[inline] fn into_iter(self) -> IntoIter<T> { self.storage.into_iter() } } impl<'a, T> IntoIterator for &'a FixedLifoDeque<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; #[inline] fn into_iter(self) -> Iter<'a, T> { self.storage.iter() } } impl<'a, T> IntoIterator for &'a mut FixedLifoDeque<T> { type Item = &'a mut T; type IntoIter = IterMut<'a, T>; #[inline] fn into_iter(self) -> IterMut<'a, T> { self.storage.iter_mut() } } impl<A> Extend<A> for FixedLifoDeque<A> { fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) { for elt in iter { self.push_back(elt); } } } impl<'a, T: 'a + Copy> Extend<&'a T> for FixedLifoDeque<T> { fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } #[cfg(test)] mod tests { use super::*; #[cfg(feature = "benchmarks")] use test::Bencher; #[test] fn test_basic_insertions() { let mut tester = FixedLifoDeque::with_limit(3); assert_eq!(tester.len(), 0); assert_eq!(tester.capacity(), 3); assert_eq!(tester.front(), None); assert_eq!(tester.back(), None); tester.push_back(1); assert_eq!(tester.len(), 1); assert_eq!(tester.front(), Some(1).as_ref()); assert_eq!(tester.back(), Some(1).as_ref()); tester.push_back(2); assert_eq!(tester.len(), 2); assert_eq!(tester.front(), Some(1).as_ref()); assert_eq!(tester.back(), Some(2).as_ref()); tester.push_back(3); tester.push_back(4); assert_eq!(tester.len(), 3); assert_eq!(tester.front(), Some(2).as_ref()); assert_eq!(tester.back(), Some(4).as_ref()); assert_eq!(tester[0], 2); assert_eq!(tester[1], 3); assert_eq!(tester[2], 4); } #[cfg(feature = "benchmarks")] #[bench] fn bench_push_back(b: &mut Bencher) { let mut q = FixedLifoDeque::with_limit(10); b.iter(|| q.push_back(5)); } #[cfg(feature = "benchmarks")] #[bench] fn bench_deletion_from_empty(b: &mut Bencher) { let mut q = FixedLifoDeque::<u32>::with_limit(10000); b.iter(|| q.pop_front()); } #[cfg(feature = "benchmarks")] #[bench] fn bench_deletion_from_non_empty(b: &mut Bencher) { let mut q = FixedLifoDeque::with_limit(1000000); for i in 0..q.limit() { q.push_back(i); } b.iter(|| q.pop_front()); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/trace/src/sys_pid.rs
rust/trace/src/sys_pid.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[cfg(all(target_family = "unix", not(target_os = "fuchsia")))] #[inline] pub fn current_pid() -> u64 { extern "C" { fn getpid() -> libc::pid_t; } unsafe { getpid() as u64 } } #[cfg(target_os = "fuchsia")] pub fn current_pid() -> u64 { // TODO: implement for fuchsia (does getpid work?) 0 } #[cfg(target_family = "windows")] #[inline] pub fn current_pid() -> u64 { extern "C" { fn GetCurrentProcessId() -> libc::c_ulong; } unsafe { u64::from(GetCurrentProcessId()) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/trace/src/chrome_trace_dump.rs
rust/trace/src/chrome_trace_dump.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![allow( clippy::if_same_then_else, clippy::needless_bool, clippy::needless_pass_by_value, clippy::ptr_arg )] #[cfg(all(test, feature = "benchmarks"))] extern crate test; use std::io::{Error as IOError, ErrorKind as IOErrorKind, Read, Write}; use super::Sample; #[derive(Debug)] pub enum Error { Io(IOError), Json(serde_json::Error), DecodingFormat(String), } impl From<IOError> for Error { fn from(e: IOError) -> Error { Error::Io(e) } } impl From<serde_json::Error> for Error { fn from(e: serde_json::Error) -> Error { Error::Json(e) } } impl From<String> for Error { fn from(e: String) -> Error { Error::DecodingFormat(e) } } impl Error { pub fn already_exists() -> Error { Error::Io(IOError::from(IOErrorKind::AlreadyExists)) } } #[derive(Clone, Debug, Deserialize)] #[serde(untagged)] enum ChromeTraceArrayEntries { Array(Vec<Sample>), } /// This serializes the samples into the [Chrome trace event format](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiJlZmDguXYAhUD4GMKHVmEDqIQFggpMAA&url=https%3A%2F%2Fdocs.google.com%2Fdocument%2Fd%2F1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU%2Fpreview&usg=AOvVaw0tBFlVbDVBikdzLqgrWK3g). /// /// # Arguments /// `samples` - Something that can be converted into an iterator of sample /// references. /// `format` - Which trace format to save the data in. There are four total /// formats described in the document. /// `output` - Where to write the serialized result. /// /// # Returns /// A `Result<(), Error>` that indicates if serialization was successful or the /// details of any error that occured. /// /// # Examples /// ```no_run /// # use xi_trace::chrome_trace_dump::serialize; /// let samples = xi_trace::samples_cloned_sorted(); /// let mut serialized = Vec::<u8>::new(); /// serialize(&samples, &mut serialized); /// ``` pub fn serialize<W>(samples: &Vec<Sample>, output: W) -> Result<(), Error> where W: Write, { serde_json::to_writer(output, samples).map_err(Error::Json) } pub fn to_value(samples: &Vec<Sample>) -> Result<serde_json::Value, Error> { serde_json::to_value(samples).map_err(Error::Json) } pub fn decode(samples: serde_json::Value) -> Result<Vec<Sample>, Error> { serde_json::from_value(samples).map_err(Error::Json) } pub fn deserialize<R>(input: R) -> Result<Vec<Sample>, Error> where R: Read, { serde_json::from_reader(input).map_err(Error::Json) } #[cfg(test)] mod tests { use super::*; #[cfg(feature = "json_payload")] use crate::TracePayloadT; #[cfg(feature = "benchmarks")] use test::Bencher; #[cfg(not(feature = "json_payload"))] fn to_payload(value: &'static str) -> &'static str { value } #[cfg(feature = "json_payload")] fn to_payload(value: &'static str) -> TracePayloadT { json!({ "test": value }) } #[cfg(feature = "chrome_trace_event")] #[test] fn test_chrome_trace_serialization() { use super::super::*; let trace = Trace::enabled(Config::with_limit_count(10)); trace.instant("sample1", &["test", "chrome"]); trace.instant_payload("sample2", &["test", "chrome"], to_payload("payload 2")); trace.instant_payload("sample3", &["test", "chrome"], to_payload("payload 3")); trace.closure_payload( "sample4", &["test", "chrome"], || { let _guard = trace.block("sample5", &["test,chrome"]); }, to_payload("payload 4"), ); let samples = trace.samples_cloned_unsorted(); let mut serialized = Vec::<u8>::new(); let result = serialize(&samples, &mut serialized); assert!(result.is_ok(), "{:?}", result); let decoded_result: Vec<serde_json::Value> = serde_json::from_slice(&serialized).unwrap(); assert_eq!(decoded_result.len(), 8); assert_eq!(decoded_result[0]["name"].as_str().unwrap(), "process_name"); assert_eq!(decoded_result[1]["name"].as_str().unwrap(), "thread_name"); for i in 2..5 { assert_eq!(decoded_result[i]["name"].as_str().unwrap(), samples[i].name); assert_eq!(decoded_result[i]["cat"].as_str().unwrap(), "test,chrome"); assert_eq!(decoded_result[i]["ph"].as_str().unwrap(), "i"); assert_eq!(decoded_result[i]["ts"], samples[i].timestamp_us); let nth_sample = &samples[i]; let nth_args = nth_sample.args.as_ref().unwrap(); assert_eq!(decoded_result[i]["args"]["xi_payload"], json!(nth_args.payload.as_ref())); } assert_eq!(decoded_result[5]["ph"], "B"); assert_eq!(decoded_result[6]["ph"], "E"); assert_eq!(decoded_result[7]["ph"], "X"); } #[cfg(feature = "chrome_trace_event")] #[test] fn test_chrome_trace_deserialization() { use super::super::*; let trace = Trace::enabled(Config::with_limit_count(10)); trace.instant("sample1", &["test", "chrome"]); trace.instant_payload("sample2", &["test", "chrome"], to_payload("payload 2")); trace.instant_payload("sample3", &["test", "chrome"], to_payload("payload 3")); trace.closure_payload("sample4", &["test", "chrome"], || (), to_payload("payload 4")); let samples = trace.samples_cloned_unsorted(); let mut serialized = Vec::<u8>::new(); let result = serialize(&samples, &mut serialized); assert!(result.is_ok(), "{:?}", result); let deserialized_samples = deserialize(serialized.as_slice()).unwrap(); assert_eq!(deserialized_samples, samples); } #[cfg(all(feature = "chrome_trace_event", feature = "benchmarks"))] #[bench] fn bench_chrome_trace_serialization_one_element(b: &mut Bencher) { use super::*; let mut serialized = Vec::<u8>::new(); let samples = vec![super::Sample::new_instant("trace1", &["benchmark", "test"], None)]; b.iter(|| { serialized.clear(); serialize(&samples, &mut serialized).unwrap(); }); } #[cfg(all(feature = "chrome_trace_event", feature = "benchmarks"))] #[bench] fn bench_chrome_trace_serialization_multiple_elements(b: &mut Bencher) { use super::super::*; use super::*; let mut serialized = Vec::<u8>::new(); let samples = vec![ Sample::new_instant("trace1", &["benchmark", "test"], None), Sample::new_instant("trace2", &["benchmark"], None), Sample::new_duration("trace3", &["benchmark"], Some(to_payload("some payload")), 0, 0), Sample::new_instant("trace4", &["benchmark"], None), ]; b.iter(|| { serialized.clear(); serialize(&samples, &mut serialized).unwrap(); }); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/lib.rs
rust/experimental/lang/src/lib.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Library export for benchmarking and testing purposes. // At the moment, we only export the peg module; this may expand. pub mod peg;
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/parser.rs
rust/experimental/lang/src/parser.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::statestack::State; use crate::ScopeId; /// Trait for abstracting over text parsing and [Scope] extraction pub trait Parser { fn has_offset(&mut self) -> bool; fn set_scope_offset(&mut self, offset: u32); fn get_all_scopes(&self) -> Vec<Vec<String>>; fn get_scope_id_for_state(&self, state: State) -> ScopeId; fn parse(&mut self, text: &str, state: State) -> (usize, State, usize, State); }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/peg.rs
rust/experimental/lang/src/peg.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Simple parser expression generator use std::char::from_u32; use std::ops; pub trait Peg { fn p(&self, s: &[u8]) -> Option<usize>; } impl<F: Fn(&[u8]) -> Option<usize>> Peg for F { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self(s) } } pub struct OneByte<F>(pub F); impl<F: Fn(u8) -> bool> Peg for OneByte<F> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { if s.is_empty() || !self.0(s[0]) { None } else { Some(1) } } } impl Peg for u8 { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { OneByte(|b| b == *self).p(s) } } pub struct OneChar<F>(pub F); fn decode_utf8(s: &[u8]) -> Option<(char, usize)> { if s.is_empty() { return None; } let b = s[0]; if b < 0x80 { return Some((b as char, 1)); } else if (0xc2..=0xe0).contains(&b) && s.len() >= 2 { let b2 = s[1]; if (b2 as i8) > -0x40 { return None; } let cp = (u32::from(b) << 6) + u32::from(b2) - 0x3080; return from_u32(cp).map(|ch| (ch, 2)); } else if (0xe0..=0xf0).contains(&b) && s.len() >= 3 { let b2 = s[1]; let b3 = s[2]; if (b2 as i8) > -0x40 || (b3 as i8) > -0x40 { return None; } let cp = (u32::from(b) << 12) + (u32::from(b2) << 6) + u32::from(b3) - 0xe2080; if cp < 0x800 { return None; } // overlong encoding return from_u32(cp).map(|ch| (ch, 3)); } else if (0xf0..=0xf5).contains(&b) && s.len() >= 4 { let b2 = s[1]; let b3 = s[2]; let b4 = s[3]; if (b2 as i8) > -0x40 || (b3 as i8) > -0x40 || (b4 as i8) > -0x40 { return None; } let cp = (u32::from(b) << 18) + (u32::from(b2) << 12) + (u32::from(b3) << 6) + u32::from(b4) - 0x03c8_2080; if cp < 0x10000 { return None; } // overlong encoding return from_u32(cp).map(|ch| (ch, 4)); } None } impl<F: Fn(char) -> bool> Peg for OneChar<F> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { if let Some((ch, len)) = decode_utf8(s) { if self.0(ch) { return Some(len); } } None } } // split out into a separate function to help inlining heuristics; even so, // prefer to use bytes even though they're not quite as ergonomic fn char_helper(s: &[u8], c: char) -> Option<usize> { OneChar(|x| x == c).p(s) } impl Peg for char { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { let c = *self; if c <= '\x7f' { (c as u8).p(s) } else { char_helper(s, c) } } } // byte ranges, including inclusive variants /// Use Inclusive(a..b) to indicate an inclusive range. When a...b syntax becomes /// stable, we'll get rid of this and switch to that. pub struct Inclusive<T>(pub T); impl Peg for ops::Range<u8> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { OneByte(|x| x >= self.start && x < self.end).p(s) } } impl Peg for Inclusive<ops::Range<u8>> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { OneByte(|x| x >= self.0.start && x <= self.0.end).p(s) } } // Note: char ranges are also possible, but probably not commonly used, and inefficient impl<'a> Peg for &'a [u8] { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { let len = self.len(); if s.len() >= len && &s[..len] == *self { Some(len) } else { None } } } impl<'a> Peg for &'a str { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.as_bytes().p(s) } } impl<P1: Peg, P2: Peg> Peg for (P1, P2) { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).and_then(|len1| self.1.p(&s[len1..]).map(|len2| len1 + len2)) } } impl<P1: Peg, P2: Peg, P3: Peg> Peg for (P1, P2, P3) { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).and_then(|len1| { self.1 .p(&s[len1..]) .and_then(|len2| self.2.p(&s[len1 + len2..]).map(|len3| len1 + len2 + len3)) }) } } macro_rules! impl_tuple { ( $( $p:ident $ix:ident ),* ) => { impl< $( $p : Peg ),* > Peg for ( $( $p ),* ) { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { let ( $( ref $ix ),* ) = *self; let mut i = 0; $( if let Some(len) = $ix.p(&s[i..]) { i += len; } else { return None; } )* Some(i) } } } } impl_tuple!(P1 p1, P2 p2, P3 p3, P4 p4); /// Choice from two heterogeneous alternatives. pub struct Alt<P1, P2>(pub P1, pub P2); impl<P1: Peg, P2: Peg> Peg for Alt<P1, P2> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).or_else(|| self.1.p(s)) } } /// Choice from three heterogeneous alternatives. pub struct Alt3<P1, P2, P3>(pub P1, pub P2, pub P3); impl<P1: Peg, P2: Peg, P3: Peg> Peg for Alt3<P1, P2, P3> { #[inline(always)] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).or_else(|| self.1.p(s).or_else(|| self.2.p(s))) } } /// Choice from a homogenous slice of parsers. pub struct OneOf<'a, P: 'a>(pub &'a [P]); impl<'a, P: Peg> Peg for OneOf<'a, P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { for p in self.0.iter() { if let Some(len) = p.p(s) { return Some(len); } } None } } /// Repetition with a minimum and maximum (inclusive) bound pub struct Repeat<P, R>(pub P, pub R); impl<P: Peg> Peg for Repeat<P, usize> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, reps) = *self; let mut i = 0; let mut count = 0; while count < reps { if let Some(len) = p.p(&s[i..]) { i += len; count += 1; } else { break; } } Some(i) } } impl<P: Peg> Peg for Repeat<P, ops::Range<usize>> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, ops::Range { start, end }) = *self; let mut i = 0; let mut count = 0; while count + 1 < end { if let Some(len) = p.p(&s[i..]) { i += len; count += 1; } else { break; } } if count >= start { Some(i) } else { None } } } impl<P: Peg> Peg for Repeat<P, ops::RangeFrom<usize>> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, ops::RangeFrom { start }) = *self; let mut i = 0; let mut count = 0; while let Some(len) = p.p(&s[i..]) { i += len; count += 1; } if count >= start { Some(i) } else { None } } } impl<P: Peg> Peg for Repeat<P, ops::RangeFull> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { ZeroOrMore(Ref(&self.0)).p(s) } } impl<P: Peg> Peg for Repeat<P, ops::RangeTo<usize>> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let Repeat(ref p, ops::RangeTo { end }) = *self; Repeat(Ref(p), 0..end).p(s) } } pub struct Optional<P>(pub P); impl<P: Peg> Peg for Optional<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s).or(Some(0)) } } #[allow(dead_code)] // not used by rust lang, but used in tests pub struct OneOrMore<P>(pub P); impl<P: Peg> Peg for OneOrMore<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { Repeat(Ref(&self.0), 1..).p(s) } } pub struct ZeroOrMore<P>(pub P); impl<P: Peg> Peg for ZeroOrMore<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { let mut i = 0; while let Some(len) = self.0.p(&s[i..]) { i += len; } Some(i) } } /// Fail to match if the arg matches, otherwise match empty. pub struct FailIf<P>(pub P); impl<P: Peg> Peg for FailIf<P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { match self.0.p(s) { Some(_) => None, None => Some(0), } } } /// A wrapper to use whenever you have a reference to a Peg object pub struct Ref<'a, P: 'a>(pub &'a P); impl<'a, P: Peg> Peg for Ref<'a, P> { #[inline] fn p(&self, s: &[u8]) -> Option<usize> { self.0.p(s) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/main.rs
rust/experimental/lang/src/main.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A language syntax coloring and indentation plugin for xi-editor. extern crate xi_core_lib; extern crate xi_plugin_lib; extern crate xi_rope; extern crate xi_trace; use std::{collections::HashMap, env, path::Path}; use crate::language::{plaintext::PlaintextParser, rust::RustParser}; use crate::parser::Parser; use crate::statestack::State; use xi_core_lib::{plugins::rpc::ScopeSpan, ConfigTable, LanguageId, ViewId}; use xi_plugin_lib::{mainloop, Cache, Plugin, StateCache, View}; use xi_rope::RopeDelta; use xi_trace::{trace, trace_block, trace_payload}; mod language; mod parser; mod peg; mod statestack; const LINES_PER_RPC: usize = 50; type ScopeId = u32; struct LangPlugin { view_states: HashMap<ViewId, ViewState>, } impl LangPlugin { fn new() -> LangPlugin { LangPlugin { view_states: HashMap::new() } } } impl Plugin for LangPlugin { type Cache = StateCache<State>; fn update( &mut self, view: &mut View<Self::Cache>, _delta: Option<&RopeDelta>, _edit_type: String, _author: String, ) { view.schedule_idle(); } fn did_save(&mut self, view: &mut View<Self::Cache>, _old_path: Option<&Path>) { let view_id = view.get_id(); if let Some(view_state) = self.view_states.get_mut(&view_id) { view_state.do_highlighting(view); } } fn did_close(&mut self, view: &View<Self::Cache>) { let view_id = view.get_id(); self.view_states.remove(&view_id); } fn new_view(&mut self, view: &mut View<Self::Cache>) { let view_id = view.get_id(); let mut view_state = ViewState::new(); view_state.do_highlighting(view); self.view_states.insert(view_id, view_state); } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn language_changed( &mut self, view: &mut View<<Self as Plugin>::Cache>, _old_lang: LanguageId, ) { let view_id = view.get_id(); if let Some(view_state) = self.view_states.get_mut(&view_id) { view_state.do_highlighting(view); } } fn idle(&mut self, view: &mut View<Self::Cache>) { let view_id = view.get_id(); if let Some(view_state) = self.view_states.get_mut(&view_id) { for _ in 0..LINES_PER_RPC { if !view_state.highlight_one_line(view) { view_state.flush_spans(view); return; } if view.request_is_pending() { trace("yielding for request", &["experimental-lang"]); break; } } view_state.flush_spans(view); view.schedule_idle(); } } } struct ViewState { current_language: LanguageId, parser: Box<dyn Parser>, offset: usize, initial_state: State, spans_start: usize, spans: Vec<ScopeSpan>, scope_offset: u32, } impl ViewState { fn new() -> ViewState { ViewState { current_language: LanguageId::from("Plain Text"), parser: Box::new(PlaintextParser::new()), offset: 0, initial_state: State::default(), spans_start: 0, spans: Vec::new(), scope_offset: 0, } } fn do_highlighting(&mut self, view: &mut View<StateCache<State>>) { self.offset = 0; self.spans_start = 0; self.initial_state = State::default(); self.spans = Vec::new(); view.get_cache().clear(); if view.get_language_id() != &self.current_language { let parser: Box<dyn Parser> = match view.get_language_id().as_ref() { "Rust" => Box::new(RustParser::new()), "Plain Text" => Box::new(PlaintextParser::new()), language_id => { trace_payload( "unsupported language", &["experimental-lang"], format!("language id: {}", language_id), ); Box::new(PlaintextParser::new()) } }; self.current_language = view.get_language_id().clone(); self.parser = parser; } let scopes = self.parser.get_all_scopes(); view.add_scopes(&scopes); if !self.parser.has_offset() { self.parser.set_scope_offset(self.scope_offset); self.scope_offset += scopes.len() as u32; } view.schedule_idle(); } fn highlight_one_line(&mut self, view: &mut View<StateCache<State>>) -> bool { if let Some(line_num) = view.get_frontier() { let (line_num, offset, _state) = view.get_prev(line_num); if offset != self.offset { self.flush_spans(view); self.offset = offset; self.spans_start = offset; } let new_frontier = match view.get_line(line_num) { Ok("") => None, Ok(line) => { let new_state = self.compute_syntax(line); self.offset += line.len(); if line.as_bytes().last() == Some(&b'\n') { Some((new_state, line_num + 1)) } else { None } } Err(_) => None, }; let mut converged = false; if let Some((ref new_state, new_line_num)) = new_frontier { if let Some(old_state) = view.get(new_line_num) { converged = old_state == new_state; } } if !converged { if let Some((new_state, new_line_num)) = new_frontier { view.set(new_line_num, new_state); view.update_frontier(new_line_num); return true; } } view.close_frontier(); } false } fn compute_syntax(&mut self, line: &str) -> State { let _guard = trace_block("ExperimentalLang::compute_syntax", &["experimental-lang"]); let mut i = 0; let mut state = self.initial_state; while i < line.len() { let (prevlen, s0, len, s1) = self.parser.parse(&line[i..], state); if prevlen > 0 { // TODO: maybe make an iterator to avoid this duplication let scope_id = self.parser.get_scope_id_for_state(self.initial_state); let start = self.offset - self.spans_start + i; let end = start + prevlen; let span = ScopeSpan { start, end, scope_id }; self.spans.push(span); i += prevlen; } let scope_id = self.parser.get_scope_id_for_state(s0); let start = self.offset - self.spans_start + i; let end = start + len; let span = ScopeSpan { start, end, scope_id }; self.spans.push(span); i += len; state = s1; } state } fn flush_spans(&mut self, view: &mut View<StateCache<State>>) { if self.spans_start != self.offset { trace_payload( "flushing spans", &["experimental-lang"], format!("flushing spans: {:?}", self.spans), ); view.update_spans(self.spans_start, self.offset - self.spans_start, &self.spans); self.spans.clear(); } self.spans_start = self.offset; } } fn main() { if let Some(ref s) = env::args().nth(1) { if s == "test" { language::rust::test(); return; } } let mut plugin = LangPlugin::new(); mainloop(&mut plugin).unwrap() }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/statestack.rs
rust/experimental/lang/src/statestack.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::{collections::HashMap, hash::Hash}; /// An entire state stack is represented as a single integer. #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct State(usize); struct Entry<T> { tos: T, prev: State, } /// All states are interpreted in a context. pub struct Context<T> { // oddly enough, this is 1-based, as state 0 doesn't have an entry. entries: Vec<Entry<T>>, next: HashMap<(State, T), State>, } impl<T: Clone + Hash + Eq> Context<T> { pub fn new() -> Context<T> { Context { entries: Vec::new(), next: HashMap::new() } } fn entry(&self, s: State) -> Option<&Entry<T>> { if s.0 == 0 { None } else { Some(&self.entries[s.0 - 1]) } } /// The top of the stack for the given state. pub fn tos(&self, s: State) -> Option<T> { self.entry(s).map(|entry| entry.tos.clone()) } pub fn pop(&self, s: State) -> Option<State> { self.entry(s).map(|entry| entry.prev) } pub fn push(&mut self, s: State, el: T) -> State { let entries = &mut self.entries; *self.next.entry((s, el.clone())).or_insert_with(|| { entries.push(Entry { tos: el, prev: s }); State(entries.len()) }) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/language/rust.rs
rust/experimental/lang/src/language/rust.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Rust language syntax analysis and highlighting. use std::io::{stdin, Read}; use crate::parser::Parser; use crate::peg::*; use crate::statestack::{Context, State}; use crate::ScopeId; /// See [this](https://github.com/sublimehq/Packages/blob/master/Rust/Rust.sublime-syntax) /// for reference. static ALL_SCOPES: &[&[&str]] = &[ &["source.rust"], &["source.rust", "string.quoted.double.rust"], &["source.rust", "string.quoted.single.rust"], &["source.rust", "comment.line.double-slash.rust"], &["source.rust", "constant.character.escape.rust"], &["source.rust", "constant.numeric.decimal.rust"], &["source.rust", "invalid.illegal.rust"], &["source.rust", "keyword.operator.rust"], &["source.rust", "keyword.operator.arithmetic.rust"], &["source.rust", "entity.name.type.rust"], ]; #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub enum StateEl { Source, StrQuote, CharQuote, Comment, // One for each /* CharConst, NumericLiteral, Invalid, Keyword, Operator, PrimType, //RawStrHash, // One for each hash in a raw string //Block, // One for each { //Bracket, // One for each [ //Paren, // One for each ( // generics etc } impl StateEl { pub fn scope_id(&self) -> ScopeId { match self { StateEl::Source => 0, StateEl::StrQuote => 1, StateEl::CharQuote => 2, StateEl::Comment => 3, StateEl::CharConst => 4, StateEl::NumericLiteral => 5, StateEl::Invalid => 6, StateEl::Keyword => 7, StateEl::Operator => 8, StateEl::PrimType => 9, } } } // sorted for easy binary searching const RUST_KEYWORDS: &[&[u8]] = &[ b"Self", b"abstract", b"alignof", b"as", b"become", b"box", b"break", b"const", b"continue", b"crate", b"default", b"do", b"else", b"enum", b"extern", b"false", b"final", b"fn", b"for", b"if", b"impl", b"in", b"let", b"loop", b"macro", b"match", b"mod", b"move", b"mut", b"offsetof", b"override", b"priv", b"proc", b"pub", b"pure", b"ref", b"return", b"self", b"sizeof", b"static", b"struct", b"super", b"trait", b"true", b"type", b"typeof", b"union", b"unsafe", b"unsized", b"use", b"virtual", b"where", b"while", b"yield", ]; // sorted for easy binary searching const RUST_PRIM_TYPES: &[&[u8]] = &[ b"bool", b"char", b"f32", b"f64", b"i128", b"i16", b"i32", b"i64", b"i8", b"isize", b"str", b"u128", b"u16", b"u32", b"u64", b"u8", b"usize", ]; const RUST_OPERATORS: &[&[u8]] = &[ b"!", b"%=", b"%", b"&=", b"&&", b"&", b"*=", b"*", b"+=", b"+", b"-=", b"-", b"/=", b"/", b"<<=", b"<<", b">>=", b">>", b"^=", b"^", b"|=", b"||", b"|", b"==", b"=", b"..", b"=>", b"<=", b"<", b">=", b">", ]; pub struct RustParser { scope_offset: Option<u32>, ctx: Context<StateEl>, } impl RustParser { pub fn new() -> RustParser { RustParser { scope_offset: None, ctx: Context::new() } } fn quoted_str(&mut self, t: &[u8], state: State) -> (usize, State, usize, State) { let mut i = 0; while i < t.len() { let b = t[i]; if b == b'"' { return (0, state, i + 1, self.ctx.pop(state).unwrap()); } else if b == b'\\' { if let Some(len) = escape.p(&t[i..]) { return (i, self.ctx.push(state, StateEl::CharConst), len, state); } else if let Some(len) = (FailIf(OneOf(b"\r\nbu")), OneChar(|_| true)).p(&t[i + 1..]) { return (i + 1, self.ctx.push(state, StateEl::Invalid), len, state); } } i += 1; } (0, state, i, state) } } impl Parser for RustParser { fn has_offset(&mut self) -> bool { self.scope_offset.is_some() } fn set_scope_offset(&mut self, offset: u32) { if !self.has_offset() { self.scope_offset = Some(offset) } } fn get_all_scopes(&self) -> Vec<Vec<String>> { ALL_SCOPES .iter() .map(|stack| stack.iter().map(|s| (*s).to_string()).collect::<Vec<_>>()) .collect() } fn get_scope_id_for_state(&self, state: State) -> ScopeId { let offset = self.scope_offset.unwrap_or_default(); if let Some(element) = self.ctx.tos(state) { element.scope_id() + offset } else { offset } } fn parse(&mut self, text: &str, mut state: State) -> (usize, State, usize, State) { let t = text.as_bytes(); match self.ctx.tos(state) { Some(StateEl::Comment) => { for i in 0..t.len() { if let Some(len) = "/*".p(&t[i..]) { state = self.ctx.push(state, StateEl::Comment); return (i, state, len, state); } else if let Some(len) = "*/".p(&t[i..]) { return (0, state, i + len, self.ctx.pop(state).unwrap()); } } return (0, state, t.len(), state); } Some(StateEl::StrQuote) => return self.quoted_str(t, state), _ => (), } let mut i = 0; while i < t.len() { let b = t[i]; if let Some(len) = "/*".p(&t[i..]) { state = self.ctx.push(state, StateEl::Comment); return (i, state, len, state); } else if "//".p(&t[i..]).is_some() { return (i, self.ctx.push(state, StateEl::Comment), t.len(), state); } else if let Some(len) = numeric_literal.p(&t[i..]) { return (i, self.ctx.push(state, StateEl::NumericLiteral), len, state); } else if b == b'"' { state = self.ctx.push(state, StateEl::StrQuote); return (i, state, 1, state); } else if let Some(len) = char_literal.p(&t[i..]) { return (i, self.ctx.push(state, StateEl::CharQuote), len, state); } else if let Some(len) = OneOf(RUST_OPERATORS).p(&t[i..]) { return (i, self.ctx.push(state, StateEl::Operator), len, state); } else if let Some(len) = ident.p(&t[i..]) { if RUST_KEYWORDS.binary_search(&&t[i..i + len]).is_ok() { return (i, self.ctx.push(state, StateEl::Keyword), len, state); } else if RUST_PRIM_TYPES.binary_search(&&t[i..i + len]).is_ok() { return (i, self.ctx.push(state, StateEl::PrimType), len, state); } else { i += len; continue; } } else if let Some(len) = whitespace.p(&t[i..]) { return (i, self.ctx.push(state, StateEl::Source), len, state); } i += 1; } (0, self.ctx.push(state, StateEl::Source), t.len(), state) } } fn is_digit(c: u8) -> bool { (b'0'..=b'9').contains(&c) } fn is_hex_digit(c: u8) -> bool { (b'0'..=b'9').contains(&c) || (b'a'..=b'f').contains(&c) || (b'A'..=b'F').contains(&c) } // Note: will have to rework this if we want to support non-ASCII identifiers fn is_ident_start(c: u8) -> bool { (b'A'..=b'Z').contains(&c) || (b'a'..=b'z').contains(&c) || c == b'_' } fn is_ident_continue(c: u8) -> bool { is_ident_start(c) || is_digit(c) } fn ident(s: &[u8]) -> Option<usize> { (OneByte(is_ident_start), ZeroOrMore(OneByte(is_ident_continue))).p(s) } // sequence of decimal digits with optional separator fn raw_numeric(s: &[u8]) -> Option<usize> { (OneByte(is_digit), ZeroOrMore(Alt(b'_', OneByte(is_digit)))).p(s) } fn int_suffix(s: &[u8]) -> Option<usize> { (Alt(b'u', b'i'), OneOf(&["8", "16", "32", "64", "128", "size"])).p(s) } // At least one P with any number of SEP mixed in. Note: this is also an example // of composing combinators to make a new combinator. struct OneOrMoreWithSep<P, SEP>(P, SEP); impl<P: Peg, SEP: Peg> Peg for OneOrMoreWithSep<P, SEP> { fn p(&self, s: &[u8]) -> Option<usize> { let OneOrMoreWithSep(ref p, ref sep) = *self; (ZeroOrMore(Ref(sep)), Ref(p), ZeroOrMore(Alt(Ref(p), Ref(sep)))).p(s) } } fn positive_nondecimal(s: &[u8]) -> Option<usize> { ( b'0', Alt3( (b'x', OneOrMoreWithSep(OneByte(is_hex_digit), b'_')), (b'o', OneOrMoreWithSep(Inclusive(b'0'..b'7'), b'_')), (b'b', OneOrMoreWithSep(Alt(b'0', b'1'), b'_')), ), Optional(int_suffix), ) .p(s) } fn positive_decimal(s: &[u8]) -> Option<usize> { ( raw_numeric, Alt( int_suffix, ( Optional((b'.', FailIf(OneByte(is_ident_start)), Optional(raw_numeric))), Optional((Alt(b'e', b'E'), Optional(Alt(b'+', b'-')), raw_numeric)), Optional(Alt("f32", "f64")), ), ), ) .p(s) } fn numeric_literal(s: &[u8]) -> Option<usize> { (Optional(b'-'), Alt(positive_nondecimal, positive_decimal)).p(s) } fn escape(s: &[u8]) -> Option<usize> { ( b'\\', Alt3( OneOf(b"\\\'\"0nrt"), (b'x', Repeat(OneByte(is_hex_digit), 2)), ("u{", Repeat(OneByte(is_hex_digit), 1..7), b'}'), ), ) .p(s) } fn char_literal(s: &[u8]) -> Option<usize> { (b'\'', Alt(OneChar(|c| c != '\\' && c != '\''), escape), b'\'').p(s) } // Parser for an arbitrary number of whitespace characters // Reference: https://en.cppreference.com/w/cpp/string/byte/isspace fn whitespace(s: &[u8]) -> Option<usize> { // 0x0B -> \v // 0x0C -> \f (OneOrMore(OneOf(&[b' ', b'\t', b'\n', b'\r', 0x0B, 0x0C]))).p(s) } // A simple stdio based harness for testing. pub fn test() { let mut buf = String::new(); let _ = stdin().read_to_string(&mut buf).unwrap(); let mut c = RustParser::new(); let mut state = State::default(); for line in buf.lines() { let mut i = 0; while i < line.len() { let (prevlen, s0, len, s1) = c.parse(&line[i..], state); if prevlen > 0 { println!("{}: {:?}", &line[i..i + prevlen], state); i += prevlen; } println!("{}: {:?}", &line[i..i + len], s0); i += len; state = s1; } } } #[cfg(test)] mod tests { use super::numeric_literal; #[test] fn numeric_literals() { assert_eq!(Some(1), numeric_literal(b"2.f64")); assert_eq!(Some(6), numeric_literal(b"2.0f64")); assert_eq!(Some(1), numeric_literal(b"2._f64")); assert_eq!(Some(1), numeric_literal(b"2._0f64")); assert_eq!(Some(5), numeric_literal(b"1_2__")); assert_eq!(Some(7), numeric_literal(b"1_2__u8")); assert_eq!(Some(9), numeric_literal(b"1_2__u128")); assert_eq!(None, numeric_literal(b"_1_")); assert_eq!(Some(4), numeric_literal(b"0xff")); assert_eq!(Some(4), numeric_literal(b"0o6789")); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/language/mod.rs
rust/experimental/lang/src/language/mod.rs
pub mod plaintext; pub mod rust;
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/src/language/plaintext.rs
rust/experimental/lang/src/language/plaintext.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::parser::Parser; use crate::statestack::{Context, State}; use crate::ScopeId; const PLAINTEXT_SOURCE_SCOPE: &[&str] = &["source.plaintext"]; pub struct PlaintextParser { scope_offset: Option<u32>, ctx: Context<()>, } impl PlaintextParser { pub fn new() -> PlaintextParser { PlaintextParser { scope_offset: None, ctx: Context::new() } } } impl Parser for PlaintextParser { fn has_offset(&mut self) -> bool { self.scope_offset.is_some() } fn set_scope_offset(&mut self, offset: u32) { if !self.has_offset() { self.scope_offset = Some(offset) } } fn get_all_scopes(&self) -> Vec<Vec<String>> { vec![PLAINTEXT_SOURCE_SCOPE.iter().map(|it| (*it).to_string()).collect()] } fn get_scope_id_for_state(&self, _state: State) -> ScopeId { self.scope_offset.unwrap_or_default() } fn parse(&mut self, text: &str, state: State) -> (usize, State, usize, State) { (0, self.ctx.push(state, ()), text.as_bytes().len(), state) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/experimental/lang/benches/peg_tests.rs
rust/experimental/lang/benches/peg_tests.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Benchmarks of PEG parsing libraries #![feature(test)] /// Run as: /// ``` /// run nightly cargo bench --features "nom regex pom" /// ``` use std::env; extern crate xi_lang; #[cfg(test)] extern crate test; #[cfg(feature = "pom")] extern crate pom; #[cfg(feature = "regex")] extern crate regex; #[cfg(feature = "nom")] #[macro_use] extern crate nom; #[cfg(feature = "combine")] extern crate combine; const TEST_STR: &str = "1.2345e56"; #[cfg(all(test, feature = "pom"))] mod pom_benches { use super::{test, TEST_STR}; use pom::parser::{one_of, sym}; use pom::{DataInput, Parser}; use test::Bencher; fn pom_number() -> Parser<u8, usize> { let integer = one_of(b"123456789") - one_of(b"0123456789").repeat(0..) | sym(b'0'); let frac = sym(b'.') + one_of(b"0123456789").repeat(1..); let exp = one_of(b"eE") + one_of(b"+-").opt() + one_of(b"0123456789").repeat(1..); let number = sym(b'-').opt() + integer + frac.opt() + exp.opt(); number.pos() } #[bench] fn bench_pom(b: &mut Bencher) { let parser = pom_number(); b.iter(|| { let mut buf = DataInput::new(test::black_box(TEST_STR.as_bytes())); parser.parse(&mut buf) }) } } #[cfg(all(test, feature = "regex"))] mod regex_benches { use super::{test, TEST_STR}; use regex::Regex; use test::Bencher; #[bench] fn bench_regex(b: &mut Bencher) { let re = Regex::new(r"^(0|[1-9][0-9]*)(\.[0-9]+)?([eE]([+-])?[0-9]+)?").unwrap(); b.iter(|| re.find(test::black_box(TEST_STR))) } } #[cfg(all(test, feature = "nom"))] mod nom_benches { use super::{test, TEST_STR}; use nom::digit; use test::Bencher; named!(digits<()>, fold_many1!(digit, (), |_, _| ())); named!( nom_num<()>, do_parse!( opt!(char!('-')) >> alt!(map!(char!('0'), |_| ()) | digits) >> opt!(do_parse!(char!('.') >> digits >> ())) >> opt!(do_parse!( alt!(char!('e') | char!('E')) >> opt!(alt!(char!('+') | char!('-'))) >> digits >> () )) >> () ) ); #[cfg(feature = "nom")] #[bench] fn bench_nom(b: &mut Bencher) { b.iter(|| nom_num(test::black_box(TEST_STR.as_bytes()))) } } #[cfg(all(test, feature = "combine"))] mod combine_benches { use super::{is_digit, test, TEST_STR}; use combine::range::take_while1; use combine::*; use test::Bencher; fn my_number(s: &[u8]) -> ParseResult<(), &[u8]> { ( token(b'-').map(Some).or(value(None)), token(b'0').map(|_| &b"0"[..]).or(take_while1(is_digit)), optional((token(b'.'), take_while1(is_digit))), optional(( token(b'e').or(token(b'E')), token(b'-').map(Some).or(token(b'+').map(Some)).or(value(None)), take_while1(is_digit), )), ) .map(|_| ()) .parse_stream(s) } #[bench] fn bench_combine(b: &mut Bencher) { assert_eq!(parser(my_number).parse(TEST_STR.as_bytes()), Ok(((), &b""[..]))); b.iter(|| parser(my_number).parse(test::black_box(TEST_STR.as_bytes()))) } } use xi_lang::peg::{Alt, OneByte, OneOrMore, Optional, Peg}; fn is_digit(c: u8) -> bool { (b'0'..=b'9').contains(&c) } fn my_number(s: &[u8]) -> Option<usize> { ( Optional('-'), Alt('0', OneOrMore(OneByte(is_digit))), Optional(('.', OneOrMore(OneByte(is_digit)))), Optional((Alt('e', 'E'), Optional(Alt('-', '+')), OneOrMore(OneByte(is_digit)))), ) .p(s) } fn main() { if let Some(s) = env::args().nth(1) { println!("my: {:?}", my_number(s.as_bytes())); /* let mut buf = DataInput::new(s.as_bytes()); println!("pom: {:?}", pom_number().parse(&mut buf)); let re = Regex::new(r"^(0|[1-9][0-9]*)(\.[0-9]+)?([eE]([+-])?[0-9]+)?").unwrap(); println!("regex: {:?}", re.find(&s)); println!("nom: {:?}", nom_num(s.as_bytes())); */ } } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[bench] fn bench_my_peg(b: &mut Bencher) { b.iter(|| my_number(test::black_box(TEST_STR.as_bytes()))) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/sample-plugin/src/main.rs
rust/sample-plugin/src/main.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A sample plugin, intended as an illustration and a template for plugin //! developers. extern crate xi_core_lib as xi_core; extern crate xi_plugin_lib; extern crate xi_rope; use std::path::Path; use crate::xi_core::ConfigTable; use xi_plugin_lib::{mainloop, ChunkCache, Error, Plugin, View}; use xi_rope::delta::Builder as EditBuilder; use xi_rope::interval::Interval; use xi_rope::rope::RopeDelta; /// A type that implements the `Plugin` trait, and interacts with xi-core. /// /// Currently, this plugin has a single noteworthy behaviour, /// intended to demonstrate how to edit a document; when the plugin is active, /// and the user inserts an exclamation mark, the plugin will capitalize the /// preceding word. struct SamplePlugin; //NOTE: implementing the `Plugin` trait is the sole requirement of a plugin. // For more documentation, see `rust/plugin-lib` in this repo. impl Plugin for SamplePlugin { type Cache = ChunkCache; fn new_view(&mut self, view: &mut View<Self::Cache>) { eprintln!("new view {}", view.get_id()); } fn did_close(&mut self, view: &View<Self::Cache>) { eprintln!("close view {}", view.get_id()); } fn did_save(&mut self, view: &mut View<Self::Cache>, _old: Option<&Path>) { eprintln!("saved view {}", view.get_id()); } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, _edit_type: String, _author: String, ) { //NOTE: example simple conditional edit. If this delta is //an insert of a single '!', we capitalize the preceding word. if let Some(delta) = delta { let (iv, _) = delta.summary(); let text: String = delta.as_simple_insert().map(String::from).unwrap_or_default(); if text == "!" { let _ = self.capitalize_word(view, iv.end()); } } } } impl SamplePlugin { /// Uppercases the word preceding `end_offset`. fn capitalize_word(&self, view: &mut View<ChunkCache>, end_offset: usize) -> Result<(), Error> { //NOTE: this makes it clear to me that we need a better API for edits let line_nb = view.line_of_offset(end_offset)?; let line_start = view.offset_of_line(line_nb)?; let mut cur_utf8_ix = 0; let mut word_start = 0; for c in view.get_line(line_nb)?.chars() { if c.is_whitespace() { word_start = cur_utf8_ix; } cur_utf8_ix += c.len_utf8(); if line_start + cur_utf8_ix == end_offset { break; } } let new_text = view.get_line(line_nb)?[word_start..end_offset - line_start].to_uppercase(); let buf_size = view.get_buf_size(); let mut builder = EditBuilder::new(buf_size); let iv = Interval::new(line_start + word_start, end_offset); builder.replace(iv, new_text.into()); view.edit(builder.build(), 0, false, true, "sample".into()); Ok(()) } } fn main() { let mut plugin = SamplePlugin; mainloop(&mut plugin).unwrap(); }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/plugin-lib/src/lib.rs
rust/plugin-lib/src/lib.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The library base for implementing xi-editor plugins. extern crate xi_core_lib as xi_core; extern crate xi_rope; extern crate xi_rpc; extern crate xi_trace; #[macro_use] extern crate serde_json; extern crate bytecount; extern crate memchr; extern crate rand; extern crate serde; #[macro_use] extern crate log; mod base_cache; mod core_proxy; mod dispatch; mod state_cache; mod view; use std::io; use std::path::Path; use crate::xi_core::plugin_rpc::{GetDataResponse, TextUnit}; use crate::xi_core::{ConfigTable, LanguageId}; use serde_json::Value; use xi_rope::interval::IntervalBounds; use xi_rope::RopeDelta; use xi_rpc::{ReadError, RpcLoop}; use self::dispatch::Dispatcher; pub use crate::base_cache::ChunkCache; pub use crate::core_proxy::CoreProxy; pub use crate::state_cache::StateCache; pub use crate::view::View; pub use crate::xi_core::plugin_rpc::{Hover, Range}; /// Abstracts getting data from the peer. Mainly exists for mocking in tests. pub trait DataSource { fn get_data( &self, start: usize, unit: TextUnit, max_size: usize, rev: u64, ) -> Result<GetDataResponse, Error>; } /// A generic interface for types that cache a remote document. /// /// In general, users of this library should not need to implement this trait; /// we provide two concrete Cache implementations, [`ChunkCache`] and /// [`StateCache`]. If however a plugin's particular needs are not met by /// those implementations, a user may choose to implement their own. /// /// [`ChunkCache`]: ../base_cache/struct.ChunkCache.html /// [`StateCache`]: ../state_cache/struct.StateCache.html pub trait Cache { /// Create a new instance of this type; instances are created automatically /// as relevant views are added. fn new(buf_size: usize, rev: u64, num_lines: usize) -> Self; /// Returns the line at `line_num` (zero-indexed). Returns an `Err(_)` if /// there is a problem connecting to the peer, or if the requested line /// is out of bounds. /// /// The `source` argument is some type that implements [`DataSource`]; in /// the general case this is backed by the remote peer. /// /// [`DataSource`]: trait.DataSource.html fn get_line<DS: DataSource>(&mut self, source: &DS, line_num: usize) -> Result<&str, Error>; /// Returns the specified region of the buffer. Returns an `Err(_)` if /// there is a problem connecting to the peer, or if the requested line /// is out of bounds. /// /// The `source` argument is some type that implements [`DataSource`]; in /// the general case this is backed by the remote peer. /// /// [`DataSource`]: trait.DataSource.html fn get_region<DS, I>(&mut self, source: &DS, interval: I) -> Result<&str, Error> where DS: DataSource, I: IntervalBounds; /// Returns the entire contents of the remote document, fetching as needed. fn get_document<DS: DataSource>(&mut self, source: &DS) -> Result<String, Error>; /// Returns the offset of the line at `line_num`, zero-indexed, fetching /// data from `source` if needed. /// /// # Errors /// /// Returns an error if `line_num` is greater than the total number of lines /// in the document, or if there is a problem communicating with `source`. fn offset_of_line<DS: DataSource>( &mut self, source: &DS, line_num: usize, ) -> Result<usize, Error>; /// Returns the index of the line containing `offset`, fetching /// data from `source` if needed. /// /// # Errors /// /// Returns an error if `offset` is greater than the total length of /// the document, or if there is a problem communicating with `source`. fn line_of_offset<DS: DataSource>( &mut self, source: &DS, offset: usize, ) -> Result<usize, Error>; /// Updates the cache by applying this delta. fn update(&mut self, delta: Option<&RopeDelta>, buf_size: usize, num_lines: usize, rev: u64); /// Flushes any state held by this cache. fn clear(&mut self); } /// An interface for plugins. /// /// Users of this library must implement this trait for some type. pub trait Plugin { type Cache: Cache; /// Called when the Plugin is initialized. The plugin receives CoreProxy /// object that is a wrapper around the RPC Peer and can be used to call /// related methods on the Core in a type-safe manner. #[allow(unused_variables)] fn initialize(&mut self, core: CoreProxy) {} /// Called when an edit has occurred in the remote view. If the plugin wishes /// to add its own edit, it must do so using asynchronously via the edit notification. fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, edit_type: String, author: String, ); /// Called when a buffer has been saved to disk. The buffer's previous /// path, if one existed, is passed as `old_path`. fn did_save(&mut self, view: &mut View<Self::Cache>, old_path: Option<&Path>); /// Called when a view has been closed. By the time this message is received, /// It is possible to send messages to this view. The plugin may wish to /// perform cleanup, however. fn did_close(&mut self, view: &View<Self::Cache>); /// Called when there is a new view that this buffer is interested in. /// This is called once per view, and is paired with a call to /// `Plugin::did_close` when the view is closed. fn new_view(&mut self, view: &mut View<Self::Cache>); /// Called when a config option has changed for this view. `changes` /// is a map of keys/values that have changed; previous values are available /// in the existing config, accessible through `view.get_config()`. fn config_changed(&mut self, view: &mut View<Self::Cache>, changes: &ConfigTable); /// Called when syntax language has changed for this view. /// New language is available in the `view`, and old language is available in `old_lang`. #[allow(unused_variables)] fn language_changed(&mut self, view: &mut View<Self::Cache>, old_lang: LanguageId) {} /// Called with a custom command. #[allow(unused_variables)] fn custom_command(&mut self, view: &mut View<Self::Cache>, method: &str, params: Value) {} /// Called when the runloop is idle, if the plugin has previously /// asked to be scheduled via `View::schedule_idle()`. Plugins that /// are doing things like full document analysis can use this mechanism /// to perform their work incrementally while remaining responsive. #[allow(unused_variables)] fn idle(&mut self, view: &mut View<Self::Cache>) {} /// Language Plugins specific methods #[allow(unused_variables)] fn get_hover(&mut self, view: &mut View<Self::Cache>, request_id: usize, position: usize) {} } #[derive(Debug)] pub enum Error { RpcError(xi_rpc::Error), WrongReturnType, BadRequest, PeerDisconnect, // Just used in tests Other(String), } /// Run `plugin` until it exits, blocking the current thread. pub fn mainloop<P: Plugin>(plugin: &mut P) -> Result<(), ReadError> { let stdin = io::stdin(); let stdout = io::stdout(); let mut rpc_looper = RpcLoop::new(stdout); let mut dispatcher = Dispatcher::new(plugin); rpc_looper.mainloop(|| stdin.lock(), &mut dispatcher) }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/plugin-lib/src/view.rs
rust/plugin-lib/src/view.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use serde::Deserialize; use serde_json::{self, Value}; use std::path::{Path, PathBuf}; use crate::xi_core::plugin_rpc::{ GetDataResponse, PluginBufferInfo, PluginEdit, ScopeSpan, TextUnit, }; use crate::xi_core::{BufferConfig, ConfigTable, LanguageId, PluginPid, ViewId}; use xi_core_lib::annotations::AnnotationType; use xi_core_lib::plugin_rpc::DataSpan; use xi_rope::interval::IntervalBounds; use xi_rope::RopeDelta; use xi_trace::trace_block; use xi_rpc::RpcPeer; use super::{Cache, DataSource, Error}; /// A type that acts as a proxy for a remote view. Provides access to /// a document cache, and implements various methods for querying and modifying /// view state. pub struct View<C> { pub(crate) cache: C, pub(crate) peer: RpcPeer, pub(crate) path: Option<PathBuf>, pub(crate) config: BufferConfig, pub(crate) config_table: ConfigTable, plugin_id: PluginPid, // TODO: this is only public to avoid changing the syntect impl // this should go away with async edits pub rev: u64, pub undo_group: Option<usize>, buf_size: usize, pub(crate) view_id: ViewId, pub(crate) language_id: LanguageId, } impl<C: Cache> View<C> { pub(crate) fn new(peer: RpcPeer, plugin_id: PluginPid, info: PluginBufferInfo) -> Self { let PluginBufferInfo { views, rev, path, config, buf_size, nb_lines, syntax, .. } = info; assert_eq!(views.len(), 1, "assuming single view"); let view_id = views.first().unwrap().to_owned(); let path = path.map(PathBuf::from); View { cache: C::new(buf_size, rev, nb_lines), peer, config_table: config.clone(), config: serde_json::from_value(Value::Object(config)).unwrap(), path, plugin_id, view_id, rev, undo_group: None, buf_size, language_id: syntax, } } pub(crate) fn update( &mut self, delta: Option<&RopeDelta>, new_len: usize, new_num_lines: usize, rev: u64, undo_group: Option<usize>, ) { self.cache.update(delta, new_len, new_num_lines, rev); self.rev = rev; self.undo_group = undo_group; self.buf_size = new_len; } pub(crate) fn set_language(&mut self, new_language_id: LanguageId) { self.language_id = new_language_id; } //NOTE: (discuss in review) this feels bad, but because we're mutating cache, // which we own, we can't just pass in a reference to something else we own; // so we create this on each call. The `clone`is only cloning an `Arc`, // but we could maybe use a RefCell or something and make this cleaner. /// Returns a `FetchCtx`, a thin wrapper around an RpcPeer that implements /// the `DataSource` trait and can be used when updating a cache. pub(crate) fn make_ctx(&self) -> FetchCtx { FetchCtx { view_id: self.view_id, plugin_id: self.plugin_id, peer: self.peer.clone() } } /// Returns the length of the view's buffer, in bytes. pub fn get_buf_size(&self) -> usize { self.buf_size } pub fn get_path(&self) -> Option<&Path> { self.path.as_deref() } pub fn get_language_id(&self) -> &LanguageId { &self.language_id } pub fn get_config(&self) -> &BufferConfig { &self.config } pub fn get_cache(&mut self) -> &mut C { &mut self.cache } pub fn get_id(&self) -> ViewId { self.view_id } pub fn get_line(&mut self, line_num: usize) -> Result<&str, Error> { let ctx = self.make_ctx(); self.cache.get_line(&ctx, line_num) } /// Returns a region of the view's buffer. pub fn get_region<I: IntervalBounds>(&mut self, interval: I) -> Result<&str, Error> { let ctx = self.make_ctx(); self.cache.get_region(&ctx, interval) } pub fn get_document(&mut self) -> Result<String, Error> { let ctx = self.make_ctx(); self.cache.get_document(&ctx) } pub fn offset_of_line(&mut self, line_num: usize) -> Result<usize, Error> { let ctx = self.make_ctx(); self.cache.offset_of_line(&ctx, line_num) } pub fn line_of_offset(&mut self, offset: usize) -> Result<usize, Error> { let ctx = self.make_ctx(); self.cache.line_of_offset(&ctx, offset) } pub fn add_scopes(&self, scopes: &[Vec<String>]) { let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "scopes": scopes, }); self.peer.send_rpc_notification("add_scopes", &params); } pub fn edit( &self, delta: RopeDelta, priority: u64, after_cursor: bool, new_undo_group: bool, author: String, ) { let undo_group = if new_undo_group { None } else { self.undo_group }; let edit = PluginEdit { rev: self.rev, delta, priority, after_cursor, undo_group, author }; let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "edit": edit }); self.peer.send_rpc_notification("edit", &params); } pub fn update_spans(&self, start: usize, len: usize, spans: &[ScopeSpan]) { let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "start": start, "len": len, "rev": self.rev, "spans": spans, }); self.peer.send_rpc_notification("update_spans", &params); } pub fn update_annotations( &self, start: usize, len: usize, annotation_spans: &[DataSpan], annotation_type: &AnnotationType, ) { let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "start": start, "len": len, "rev": self.rev, "spans": annotation_spans, "annotation_type": annotation_type, }); self.peer.send_rpc_notification("update_annotations", &params); } pub fn schedule_idle(&self) { let token: usize = self.view_id.into(); self.peer.schedule_idle(token); } /// Returns `true` if an incoming RPC is pending. This is intended /// to reduce latency for bulk operations done in the background. pub fn request_is_pending(&self) -> bool { self.peer.request_is_pending() } pub fn add_status_item(&self, key: &str, value: &str, alignment: &str) { let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "key": key, "value": value, "alignment": alignment }); self.peer.send_rpc_notification("add_status_item", &params); } pub fn update_status_item(&self, key: &str, value: &str) { let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "key": key, "value": value }); self.peer.send_rpc_notification("update_status_item", &params); } pub fn remove_status_item(&self, key: &str) { let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "key": key }); self.peer.send_rpc_notification("remove_status_item", &params); } } /// A simple wrapper type that acts as a `DataSource`. pub struct FetchCtx { plugin_id: PluginPid, view_id: ViewId, peer: RpcPeer, } impl DataSource for FetchCtx { fn get_data( &self, start: usize, unit: TextUnit, max_size: usize, rev: u64, ) -> Result<GetDataResponse, Error> { let _t = trace_block("FetchCtx::get_data", &["plugin"]); let params = json!({ "plugin_id": self.plugin_id, "view_id": self.view_id, "start": start, "unit": unit, "max_size": max_size, "rev": rev, }); let result = self.peer.send_rpc_request("get_data", &params).map_err(Error::RpcError)?; GetDataResponse::deserialize(result).map_err(|_| Error::WrongReturnType) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/plugin-lib/src/dispatch.rs
rust/plugin-lib/src/dispatch.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashMap; use std::path::PathBuf; use serde_json::{self, Value}; use crate::core_proxy::CoreProxy; use crate::xi_core::plugin_rpc::{HostNotification, HostRequest, PluginBufferInfo, PluginUpdate}; use crate::xi_core::{ConfigTable, LanguageId, PluginPid, ViewId}; use xi_rpc::{Handler as RpcHandler, RemoteError, RpcCtx}; use xi_trace::{self, trace, trace_block, trace_block_payload}; use super::{Plugin, View}; /// Convenience for unwrapping a view, when handling RPC notifications. macro_rules! bail { ($opt:expr, $method:expr, $pid:expr, $view:expr) => { match $opt { Some(t) => t, None => { warn!("{:?} missing {:?} for {:?}", $pid, $view, $method); return; } } }; } /// Convenience for unwrapping a view when handling RPC requests. /// Prints an error if the view is missing, and returns an appropriate error. macro_rules! bail_err { ($opt:expr, $method:expr, $pid:expr, $view:expr) => { match $opt { Some(t) => t, None => { warn!("{:?} missing {:?} for {:?}", $pid, $view, $method); return Err(RemoteError::custom(404, "missing view", None)); } } }; } /// Handles raw RPCs from core, updating state and forwarding calls /// to the plugin, pub struct Dispatcher<'a, P: 'a + Plugin> { //TODO: when we add multi-view, this should be an Arc+Mutex/Rc+RefCell views: HashMap<ViewId, View<P::Cache>>, pid: Option<PluginPid>, plugin: &'a mut P, } impl<'a, P: 'a + Plugin> Dispatcher<'a, P> { pub(crate) fn new(plugin: &'a mut P) -> Self { Dispatcher { views: HashMap::new(), pid: None, plugin } } fn do_initialize( &mut self, ctx: &RpcCtx, plugin_id: PluginPid, buffers: Vec<PluginBufferInfo>, ) { assert!(self.pid.is_none(), "initialize rpc received with existing pid"); info!("Initializing plugin {:?}", plugin_id); self.pid = Some(plugin_id); let core_proxy = CoreProxy::new(self.pid.unwrap(), ctx); self.plugin.initialize(core_proxy); self.do_new_buffer(ctx, buffers); } fn do_did_save(&mut self, view_id: ViewId, path: PathBuf) { let v = bail!(self.views.get_mut(&view_id), "did_save", self.pid, view_id); let prev_path = v.path.take(); v.path = Some(path); self.plugin.did_save(v, prev_path.as_deref()); } fn do_config_changed(&mut self, view_id: ViewId, changes: &ConfigTable) { let v = bail!(self.views.get_mut(&view_id), "config_changed", self.pid, view_id); self.plugin.config_changed(v, changes); for (key, value) in changes.iter() { v.config_table.insert(key.to_owned(), value.to_owned()); } let conf = serde_json::from_value(Value::Object(v.config_table.clone())); v.config = conf.unwrap(); } fn do_language_changed(&mut self, view_id: ViewId, new_lang: LanguageId) { let v = bail!(self.views.get_mut(&view_id), "language_changed", self.pid, view_id); let old_lang = v.language_id.clone(); v.set_language(new_lang); self.plugin.language_changed(v, old_lang); } fn do_custom_command(&mut self, view_id: ViewId, method: &str, params: Value) { let v = bail!(self.views.get_mut(&view_id), method, self.pid, view_id); self.plugin.custom_command(v, method, params); } fn do_new_buffer(&mut self, ctx: &RpcCtx, buffers: Vec<PluginBufferInfo>) { let plugin_id = self.pid.unwrap(); buffers .into_iter() .map(|info| View::new(ctx.get_peer().clone(), plugin_id, info)) .for_each(|view| { let mut view = view; self.plugin.new_view(&mut view); self.views.insert(view.view_id, view); }); } fn do_close(&mut self, view_id: ViewId) { { let v = bail!(self.views.get(&view_id), "close", self.pid, view_id); self.plugin.did_close(v); } self.views.remove(&view_id); } fn do_shutdown(&mut self) { info!("rust plugin lib does not shutdown"); //TODO: handle shutdown } fn do_get_hover(&mut self, view_id: ViewId, request_id: usize, position: usize) { let v = bail!(self.views.get_mut(&view_id), "get_hover", self.pid, view_id); self.plugin.get_hover(v, request_id, position) } fn do_tracing_config(&mut self, enabled: bool) { if enabled { xi_trace::enable_tracing(); info!("Enabling tracing in global plugin {:?}", self.pid); trace("enable tracing", &["plugin"]); } else { xi_trace::disable_tracing(); info!("Disabling tracing in global plugin {:?}", self.pid); trace("disable tracing", &["plugin"]); } } fn do_update(&mut self, update: PluginUpdate) -> Result<Value, RemoteError> { let _t = trace_block("Dispatcher::do_update", &["plugin"]); let PluginUpdate { view_id, delta, new_len, new_line_count, rev, undo_group, edit_type, author, } = update; let v = bail_err!(self.views.get_mut(&view_id), "update", self.pid, view_id); v.update(delta.as_ref(), new_len, new_line_count, rev, undo_group); self.plugin.update(v, delta.as_ref(), edit_type, author); Ok(Value::from(1)) } fn do_collect_trace(&self) -> Result<Value, RemoteError> { use xi_trace::chrome_trace_dump; let samples = xi_trace::samples_cloned_unsorted(); chrome_trace_dump::to_value(&samples).map_err(|e| RemoteError::Custom { code: 0, message: format!("Could not serialize trace: {:?}", e), data: None, }) } } impl<'a, P: Plugin> RpcHandler for Dispatcher<'a, P> { type Notification = HostNotification; type Request = HostRequest; fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) { use self::HostNotification::*; let _t = trace_block("Dispatcher::handle_notif", &["plugin"]); match rpc { Initialize { plugin_id, buffer_info } => { self.do_initialize(ctx, plugin_id, buffer_info) } DidSave { view_id, path } => self.do_did_save(view_id, path), ConfigChanged { view_id, changes } => self.do_config_changed(view_id, &changes), NewBuffer { buffer_info } => self.do_new_buffer(ctx, buffer_info), DidClose { view_id } => self.do_close(view_id), Shutdown(..) => self.do_shutdown(), TracingConfig { enabled } => self.do_tracing_config(enabled), GetHover { view_id, request_id, position } => { self.do_get_hover(view_id, request_id, position) } LanguageChanged { view_id, new_lang } => self.do_language_changed(view_id, new_lang), CustomCommand { view_id, method, params } => { self.do_custom_command(view_id, &method, params) } Ping(..) => (), } } fn handle_request(&mut self, _ctx: &RpcCtx, rpc: Self::Request) -> Result<Value, RemoteError> { use self::HostRequest::*; let _t = trace_block("Dispatcher::handle_request", &["plugin"]); match rpc { Update(params) => self.do_update(params), CollectTrace(..) => self.do_collect_trace(), } } fn idle(&mut self, _ctx: &RpcCtx, token: usize) { let _t = trace_block_payload("Dispatcher::idle", &["plugin"], format!("token: {}", token)); let view_id: ViewId = token.into(); let v = bail!(self.views.get_mut(&view_id), "idle", self.pid, view_id); self.plugin.idle(v); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/plugin-lib/src/core_proxy.rs
rust/plugin-lib/src/core_proxy.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A proxy for the methods on Core use crate::xi_core::plugin_rpc::Hover; use crate::xi_core::plugins::PluginId; use crate::xi_core::ViewId; use xi_rpc::{RemoteError, RpcCtx, RpcPeer}; #[derive(Clone)] pub struct CoreProxy { plugin_id: PluginId, peer: RpcPeer, } impl CoreProxy { pub fn new(plugin_id: PluginId, rpc_ctx: &RpcCtx) -> Self { CoreProxy { plugin_id, peer: rpc_ctx.get_peer().clone() } } pub fn add_status_item(&mut self, view_id: ViewId, key: &str, value: &str, alignment: &str) { let params = json!({ "plugin_id": self.plugin_id, "view_id": view_id, "key": key, "value": value, "alignment": alignment }); self.peer.send_rpc_notification("add_status_item", &params) } pub fn update_status_item(&mut self, view_id: ViewId, key: &str, value: &str) { let params = json!({ "plugin_id": self.plugin_id, "view_id": view_id, "key": key, "value": value }); self.peer.send_rpc_notification("update_status_item", &params) } pub fn remove_status_item(&mut self, view_id: ViewId, key: &str) { let params = json!({ "plugin_id": self.plugin_id, "view_id": view_id, "key": key }); self.peer.send_rpc_notification("remove_status_item", &params) } pub fn display_hover( &mut self, view_id: ViewId, request_id: usize, result: &Result<Hover, RemoteError>, ) { let params = json!({ "plugin_id": self.plugin_id, "request_id": request_id, "result": result, "view_id": view_id }); self.peer.send_rpc_notification("show_hover", &params); } pub fn schedule_idle(&mut self, view_id: ViewId) { let token: usize = view_id.into(); self.peer.schedule_idle(token); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/plugin-lib/src/state_cache.rs
rust/plugin-lib/src/state_cache.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A more sophisticated cache that manages user state. use rand::{thread_rng, Rng}; use xi_rope::interval::IntervalBounds; use xi_rope::{LinesMetric, RopeDelta}; use xi_trace::trace_block; use super::{Cache, DataSource, Error, View}; use crate::base_cache::ChunkCache; const CACHE_SIZE: usize = 1024; /// Number of probes for eviction logic. const NUM_PROBES: usize = 5; struct CacheEntry<S> { line_num: usize, offset: usize, user_state: Option<S>, } /// The caching state #[derive(Default)] pub struct StateCache<S> { pub(crate) buf_cache: ChunkCache, state_cache: Vec<CacheEntry<S>>, /// The frontier, represented as a sorted list of line numbers. frontier: Vec<usize>, } impl<S: Clone + Default> Cache for StateCache<S> { fn new(buf_size: usize, rev: u64, num_lines: usize) -> Self { StateCache { buf_cache: ChunkCache::new(buf_size, rev, num_lines), state_cache: Vec::new(), frontier: Vec::new(), } } fn get_line<DS: DataSource>(&mut self, source: &DS, line_num: usize) -> Result<&str, Error> { self.buf_cache.get_line(source, line_num) } fn get_region<DS, I>(&mut self, source: &DS, interval: I) -> Result<&str, Error> where DS: DataSource, I: IntervalBounds, { self.buf_cache.get_region(source, interval) } fn get_document<DS: DataSource>(&mut self, source: &DS) -> Result<String, Error> { self.buf_cache.get_document(source) } fn offset_of_line<DS: DataSource>( &mut self, source: &DS, line_num: usize, ) -> Result<usize, Error> { self.buf_cache.offset_of_line(source, line_num) } fn line_of_offset<DS: DataSource>( &mut self, source: &DS, offset: usize, ) -> Result<usize, Error> { self.buf_cache.line_of_offset(source, offset) } /// Updates the cache by applying this delta. fn update(&mut self, delta: Option<&RopeDelta>, buf_size: usize, num_lines: usize, rev: u64) { let _t = trace_block("StateCache::update", &["plugin"]); if let Some(delta) = delta { self.update_line_cache(delta); } else { // if there's no delta (very large edit) we blow away everything self.clear_to_start(0); } self.buf_cache.update(delta, buf_size, num_lines, rev); } /// Flushes any state held by this cache. fn clear(&mut self) { self.reset() } } impl<S: Clone + Default> StateCache<S> { /// Find an entry in the cache by line num. On return `Ok(i)` means entry /// at index `i` is an exact match, while `Err(i)` means the entry would be /// inserted at `i`. fn find_line(&self, line_num: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.line_num.cmp(&line_num)) } /// Find an entry in the cache by offset. Similar to `find_line`. pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.state_cache.binary_search_by(|probe| probe.offset.cmp(&offset)) } /// Get the state from the nearest cache entry at or before given line number. /// Returns line number, offset, and user state. pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { if line_num > 0 { let mut ix = match self.find_line(line_num) { Ok(ix) => ix, Err(0) => return (0, 0, S::default()), Err(ix) => ix - 1, }; loop { let item = &self.state_cache[ix]; if let Some(ref s) = item.user_state { return (item.line_num, item.offset, s.clone()); } if ix == 0 { break; } ix -= 1; } } (0, 0, S::default()) } /// Get the state at the given line number, if it exists in the cache. pub fn get(&self, line_num: usize) -> Option<&S> { self.find_line(line_num).ok().and_then(|ix| self.state_cache[ix].user_state.as_ref()) } /// Set the state at the given line number. Note: has no effect if line_num /// references the end of the partial line at EOF. pub fn set<DS>(&mut self, source: &DS, line_num: usize, s: S) where DS: DataSource, { if let Some(entry) = self.get_entry(source, line_num) { entry.user_state = Some(s); } } /// Get the cache entry at the given line number, creating it if necessary. /// Returns None if line_num > number of newlines in doc (ie if it references /// the end of the partial line at EOF). fn get_entry<DS>(&mut self, source: &DS, line_num: usize) -> Option<&mut CacheEntry<S>> where DS: DataSource, { match self.find_line(line_num) { Ok(ix) => Some(&mut self.state_cache[ix]), Err(_ix) => { if line_num == self.buf_cache.num_lines { None } else { let offset = self .buf_cache .offset_of_line(source, line_num) .expect("get_entry should validate inputs"); let new_ix = self.insert_entry(line_num, offset, None); Some(&mut self.state_cache[new_ix]) } } } } /// Insert a new entry into the cache, returning its index. fn insert_entry(&mut self, line_num: usize, offset: usize, user_state: Option<S>) -> usize { if self.state_cache.len() >= CACHE_SIZE { self.evict(); } match self.find_line(line_num) { Ok(_ix) => panic!("entry already exists"), Err(ix) => { self.state_cache.insert(ix, CacheEntry { line_num, offset, user_state }); ix } } } /// Evict one cache entry. fn evict(&mut self) { let ix = self.choose_victim(); self.state_cache.remove(ix); } fn choose_victim(&self) -> usize { let mut best = None; let mut rng = thread_rng(); for _ in 0..NUM_PROBES { let ix = rng.gen_range(0, self.state_cache.len()); let gap = self.compute_gap(ix); if best.map(|(last_gap, _)| gap < last_gap).unwrap_or(true) { best = Some((gap, ix)); } } best.unwrap().1 } /// Compute the gap that would result after deleting the given entry. fn compute_gap(&self, ix: usize) -> usize { let before = if ix == 0 { 0 } else { self.state_cache[ix - 1].offset }; let after = if let Some(item) = self.state_cache.get(ix + 1) { item.offset } else { self.buf_cache.buf_size }; assert!(after >= before, "{} < {} ix: {}", after, before, ix); after - before } /// Release all state _after_ the given offset. fn truncate_cache(&mut self, offset: usize) { let (line_num, ix) = match self.find_offset(offset) { Ok(ix) => (self.state_cache[ix].line_num, ix + 1), Err(ix) => (if ix == 0 { 0 } else { self.state_cache[ix - 1].line_num }, ix), }; self.truncate_frontier(line_num); self.state_cache.truncate(ix); } pub(crate) fn truncate_frontier(&mut self, line_num: usize) { match self.frontier.binary_search(&line_num) { Ok(ix) => self.frontier.truncate(ix + 1), Err(ix) => { self.frontier.truncate(ix); self.frontier.push(line_num); } } } /// Updates the line cache to reflect this delta. fn update_line_cache(&mut self, delta: &RopeDelta) { let (iv, new_len) = delta.summary(); if let Some(n) = delta.as_simple_insert() { assert_eq!(iv.size(), 0); assert_eq!(new_len, n.len()); let newline_count = n.measure::<LinesMetric>(); self.line_cache_simple_insert(iv.start(), new_len, newline_count); } else if delta.is_simple_delete() { assert_eq!(new_len, 0); self.line_cache_simple_delete(iv.start(), iv.end()) } else { self.clear_to_start(iv.start()); } } fn line_cache_simple_insert(&mut self, start: usize, new_len: usize, newline_num: usize) { let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; for entry in &mut self.state_cache[ix..] { entry.line_num += newline_num; entry.offset += new_len; } self.patchup_frontier(ix, newline_num as isize); } fn line_cache_simple_delete(&mut self, start: usize, end: usize) { let off = self.buf_cache.offset; let chunk_end = off + self.buf_cache.contents.len(); if start >= off && end <= chunk_end { let del_newline_num = count_newlines(&self.buf_cache.contents[start - off..end - off]); // delete all entries that overlap the deleted range let ix = match self.find_offset(start) { Ok(ix) => ix + 1, Err(ix) => ix, }; while ix < self.state_cache.len() && self.state_cache[ix].offset <= end { self.state_cache.remove(ix); } for entry in &mut self.state_cache[ix..] { entry.line_num -= del_newline_num; entry.offset -= end - start; } self.patchup_frontier(ix, -(del_newline_num as isize)); } else { // if this region isn't in our chunk we can't correctly adjust newlines self.clear_to_start(start); } } fn patchup_frontier(&mut self, cache_idx: usize, nl_count_delta: isize) { let line_num = match cache_idx { 0 => 0, ix => self.state_cache[ix - 1].line_num, }; let mut new_frontier = Vec::new(); let mut need_push = true; for old_ln in &self.frontier { if *old_ln < line_num { new_frontier.push(*old_ln); } else if need_push { new_frontier.push(line_num); need_push = false; if let Some(entry) = self.state_cache.get(cache_idx) { if *old_ln >= entry.line_num { new_frontier.push(old_ln.wrapping_add(nl_count_delta as usize)); } } } } if need_push { new_frontier.push(line_num); } self.frontier = new_frontier; } /// Clears any cached text and anything in the state cache before `start`. fn clear_to_start(&mut self, start: usize) { self.truncate_cache(start); } /// Clear all state and reset frontier to start. pub fn reset(&mut self) { self.truncate_cache(0); } /// The frontier keeps track of work needing to be done. A typical /// user will call `get_frontier` to get a line number, do the work /// on that line, insert state for the next line, and then call either /// `update_frontier` or `close_frontier` depending on whether there /// is more work to be done at that location. pub fn get_frontier(&self) -> Option<usize> { self.frontier.first().cloned() } /// Updates the frontier. This can go backward, but most typically /// goes forward by 1 line (compared to the `get_frontier` result). pub fn update_frontier(&mut self, new_frontier: usize) { if self.frontier.get(1) == Some(&new_frontier) { self.frontier.remove(0); } else { self.frontier[0] = new_frontier; } } /// Closes the current frontier. This is the correct choice to handle /// EOF. pub fn close_frontier(&mut self) { self.frontier.remove(0); } } /// StateCache specific extensions on `View` impl<S: Default + Clone> View<StateCache<S>> { pub fn get_frontier(&self) -> Option<usize> { self.cache.get_frontier() } pub fn get_prev(&self, line_num: usize) -> (usize, usize, S) { self.cache.get_prev(line_num) } pub fn get(&self, line_num: usize) -> Option<&S> { self.cache.get(line_num) } pub fn set(&mut self, line_num: usize, s: S) { let ctx = self.make_ctx(); self.cache.set(&ctx, line_num, s) } pub fn update_frontier(&mut self, new_frontier: usize) { self.cache.update_frontier(new_frontier) } pub fn close_frontier(&mut self) { self.cache.close_frontier() } pub fn reset(&mut self) { self.cache.reset() } pub fn find_offset(&self, offset: usize) -> Result<usize, usize> { self.cache.find_offset(offset) } } fn count_newlines(s: &str) -> usize { bytecount::count(s.as_bytes(), b'\n') }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/plugin-lib/src/base_cache.rs
rust/plugin-lib/src/base_cache.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The simplest cache. This should eventually offer line-oriented access //! to the remote document, and can be used as a building block for more //! complicated caching schemes. use memchr::memchr; use crate::xi_core::plugin_rpc::{GetDataResponse, TextUnit}; use xi_rope::interval::IntervalBounds; use xi_rope::{DeltaElement, Interval, LinesMetric, Rope, RopeDelta}; use xi_trace::trace_block; use super::{Cache, DataSource, Error}; #[cfg(not(test))] const CHUNK_SIZE: usize = 1024 * 1024; #[cfg(test)] const CHUNK_SIZE: usize = 16; /// A simple cache, holding a single contiguous chunk of the document. #[derive(Debug, Clone, Default)] pub struct ChunkCache { /// The position of this chunk relative to the tracked document. /// All offsets are guaranteed to be valid UTF-8 character boundaries. pub offset: usize, /// A chunk of the remote buffer. pub contents: String, /// The (zero-based) line number of the line containing the start of the chunk. pub first_line: usize, /// The byte offset of the start of the chunk from the start of `first_line`. /// If this chunk starts at a line break, this will be 0. pub first_line_offset: usize, /// A list of indexes of newlines in this chunk. pub line_offsets: Vec<usize>, /// The total size of the tracked document. pub buf_size: usize, pub num_lines: usize, pub rev: u64, } impl Cache for ChunkCache { fn new(buf_size: usize, rev: u64, num_lines: usize) -> Self { ChunkCache { buf_size, num_lines, rev, ..Default::default() } } /// Returns the line at `line_num` (zero-indexed). Returns an `Err(_)` if /// there is a problem connecting to the peer, or if the requested line /// is out of bounds. /// /// The `source` argument is some type that implements [`DataSource`]; in /// the general case this is backed by the remote peer. /// /// # Errors /// /// Returns an error if `line_num` is greater than the total number of lines /// in the document, or if there is a problem communicating with `source`. /// /// [`DataSource`]: trait.DataSource.html fn get_line<DS>(&mut self, source: &DS, line_num: usize) -> Result<&str, Error> where DS: DataSource, { if line_num >= self.num_lines { return Err(Error::BadRequest); } // if chunk does not include the start of this line, fetch and reset everything if self.contents.is_empty() || line_num < self.first_line || (line_num == self.first_line && self.first_line_offset > 0) || (line_num > self.first_line + self.line_offsets.len()) { let resp = source.get_data(line_num, TextUnit::Line, CHUNK_SIZE, self.rev)?; self.reset_chunk(resp); } // We now know that the start of this line is contained in self.contents. let mut start_off = self.cached_offset_of_line(line_num).unwrap() - self.offset; // Now we make sure we also contain the end of the line, fetching more // of the document as necessary. loop { if let Some(end_off) = self.cached_offset_of_line(line_num + 1) { return Ok(&self.contents[start_off..end_off - self.offset]); } // if we have a chunk and we're fetching more, discard unnecessary // portion of our chunk. if start_off != 0 { self.clear_up_to(start_off); start_off = 0; } let chunk_end = self.offset + self.contents.len(); let resp = source.get_data(chunk_end, TextUnit::Utf8, CHUNK_SIZE, self.rev)?; self.append_chunk(&resp); } } fn get_region<DS, I>(&mut self, source: &DS, interval: I) -> Result<&str, Error> where DS: DataSource, I: IntervalBounds, { let Interval { start, end } = interval.into_interval(self.buf_size); if self.contents.is_empty() || start < self.offset || start >= self.offset + self.contents.len() { let resp = source.get_data(start, TextUnit::Utf8, CHUNK_SIZE, self.rev)?; self.reset_chunk(resp); } loop { let start_off = start - self.offset; let end_off = end - self.offset; if end_off <= self.contents.len() { return Ok(&self.contents[start_off..end_off]); } if start_off != 0 { self.clear_up_to(start_off); } let chunk_end = self.offset + self.contents.len(); let resp = source.get_data(chunk_end, TextUnit::Utf8, CHUNK_SIZE, self.rev)?; self.append_chunk(&resp); } } // could reimplement this with get_region, but this doesn't bloat the cache. // Not clear that's a win, though, since if we're using this at all caching // is probably worth it? fn get_document<DS: DataSource>(&mut self, source: &DS) -> Result<String, Error> { let mut result = String::new(); let mut cur_idx = 0; while cur_idx < self.buf_size { if self.contents.is_empty() || cur_idx != self.offset { let resp = source.get_data(cur_idx, TextUnit::Utf8, CHUNK_SIZE, self.rev)?; self.reset_chunk(resp); } result.push_str(&self.contents); cur_idx = self.offset + self.contents.len(); } Ok(result) } fn offset_of_line<DS: DataSource>( &mut self, source: &DS, line_num: usize, ) -> Result<usize, Error> { if line_num > self.num_lines { return Err(Error::BadRequest); } match self.cached_offset_of_line(line_num) { Some(offset) => Ok(offset), None => { let resp = source.get_data(line_num, TextUnit::Line, CHUNK_SIZE, self.rev)?; self.reset_chunk(resp); self.offset_of_line(source, line_num) } } } fn line_of_offset<DS: DataSource>( &mut self, source: &DS, offset: usize, ) -> Result<usize, Error> { if offset > self.buf_size { return Err(Error::BadRequest); } if self.contents.is_empty() || offset < self.offset || offset > self.offset + self.contents.len() { let resp = source.get_data(offset, TextUnit::Utf8, CHUNK_SIZE, self.rev)?; self.reset_chunk(resp); } let rel_offset = offset - self.offset; let line_num = match self.line_offsets.binary_search(&rel_offset) { Ok(ix) => ix + self.first_line + 1, Err(ix) => ix + self.first_line, }; Ok(line_num) } /// Updates the chunk to reflect changes in this delta. fn update(&mut self, delta: Option<&RopeDelta>, new_len: usize, num_lines: usize, rev: u64) { let _t = trace_block("ChunkCache::update", &["plugin"]); let is_empty = self.offset == 0 && self.contents.is_empty(); let should_clear = match delta { Some(delta) if !is_empty => self.should_clear(delta), // if no contents, clearing is a noop Some(_) => true, // no delta means a very large edit None => true, }; if should_clear { self.clear(); } else { // only reached if delta exists self.update_chunk(delta.unwrap()); } self.buf_size = new_len; self.num_lines = num_lines; self.rev = rev; } fn clear(&mut self) { self.contents.clear(); self.offset = 0; self.line_offsets.clear(); self.first_line = 0; self.first_line_offset = 0; } } impl ChunkCache { /// Returns the offset of the provided `line_num` if it can be determined /// without fetching data. The offset of line 0 is always 0, and there /// is an implicit line at the last offset in the buffer. fn cached_offset_of_line(&self, line_num: usize) -> Option<usize> { if line_num < self.first_line { return None; } let rel_line_num = line_num - self.first_line; if rel_line_num == 0 { return Some(self.offset - self.first_line_offset); } if rel_line_num <= self.line_offsets.len() { return Some(self.offset + self.line_offsets[rel_line_num - 1]); } // EOF if line_num == self.num_lines && self.offset + self.contents.len() == self.buf_size { return Some(self.offset + self.contents.len()); } None } /// Clears anything in the cache up to `offset`, which is indexed relative /// to `self.contents`. /// /// # Panics /// /// Panics if `offset` is not a character boundary, or if `offset` is greater than /// the length of `self.content`. fn clear_up_to(&mut self, offset: usize) { if offset > self.contents.len() { panic!("offset greater than content length: {} > {}", offset, self.contents.len()) } let new_contents = self.contents.split_off(offset); self.contents = new_contents; self.offset += offset; // first find out if offset is a line offset, and set first_line / first_line_offset let (new_line, new_line_off) = match self.line_offsets.binary_search(&offset) { Ok(idx) => (self.first_line + idx + 1, 0), Err(0) => (self.first_line, self.first_line_offset + offset), Err(idx) => (self.first_line + idx, offset - self.line_offsets[idx - 1]), }; // then clear line_offsets up to and including offset self.line_offsets = self.line_offsets.iter().filter(|i| **i > offset).map(|i| i - offset).collect(); self.first_line = new_line; self.first_line_offset = new_line_off; } /// Discard any existing cache, starting again with the new data. fn reset_chunk(&mut self, data: GetDataResponse) { self.contents = data.chunk; self.offset = data.offset; self.first_line = data.first_line; self.first_line_offset = data.first_line_offset; self.recalculate_line_offsets(); } /// Append to the existing cache, leaving existing data in place. fn append_chunk(&mut self, data: &GetDataResponse) { self.contents.push_str(data.chunk.as_str()); // this is doing extra work in the case where we're fetching a single // massive (multiple of CHUNK_SIZE) line, but unclear if it's worth optimizing self.recalculate_line_offsets(); } fn recalculate_line_offsets(&mut self) { self.line_offsets.clear(); newline_offsets(&self.contents, &mut self.line_offsets); } /// Determine whether we should update our state with this delta, /// or if we should clear it. In the update case, also patches up /// offsets. fn should_clear(&mut self, delta: &RopeDelta) -> bool { let (iv, _) = delta.summary(); let start = iv.start(); let end = iv.end(); // we only apply the delta if it is a simple edit, which // begins inside or immediately following our chunk. // - If it begins _before_ our chunk, we are likely going to // want to fetch the edited region, which will reset our state; // - If it's a complex edit the logic is tricky, and this should // be rare enough we can afford to discard. // The one 'complex edit' we should probably be handling is // the replacement of a single range. This could be a new // convenience method on `Delta`? if start < self.offset || start > self.offset + self.contents.len() { true } else if delta.is_simple_delete() { // Don't go over cache boundary. let end = end.min(self.offset + self.contents.len()); self.simple_delete(start, end); false } else if let Some(text) = delta.as_simple_insert() { assert_eq!(iv.size(), 0); self.simple_insert(text, start); false } else { true } } /// Patches up `self.line_offsets` in the simple insert case. fn simple_insert(&mut self, text: &Rope, ins_offset: usize) { let has_newline = text.measure::<LinesMetric>() > 0; let self_off = self.offset; assert!(ins_offset >= self_off); // regardless of if we are inserting newlines we adjust offsets self.line_offsets.iter_mut().for_each(|off| { if *off > ins_offset - self_off { *off += text.len() } }); // calculate and insert new newlines if necessary // we could save some hassle and just rerun memchr on the chunk here? if has_newline { let mut new_offsets = Vec::new(); newline_offsets(&String::from(text), &mut new_offsets); new_offsets.iter_mut().for_each(|off| *off += ins_offset - self_off); let split_idx = self .line_offsets .binary_search(&new_offsets[0]) .err() .expect("new index cannot be occupied"); self.line_offsets = [&self.line_offsets[..split_idx], &new_offsets, &self.line_offsets[split_idx..]] .concat(); } } /// Patches up `self.line_offsets` in the simple delete case. fn simple_delete(&mut self, start: usize, end: usize) { let del_size = end - start; let start = start - self.offset; let end = end - self.offset; let has_newline = memchr(b'\n', &self.contents.as_bytes()[start..end]).is_some(); // a bit too fancy: only reallocate if we need to remove an item if has_newline { self.line_offsets = self .line_offsets .iter() .filter_map(|off| match *off { x if x <= start => Some(x), x if x > start && x <= end => None, x if x > end => Some(x - del_size), hmm => panic!("invariant violated {} {} {}?", start, end, hmm), }) .collect(); } else { self.line_offsets.iter_mut().for_each(|off| { if *off >= end { *off -= del_size } }); } } /// Updates `self.contents` with the given delta. fn update_chunk(&mut self, delta: &RopeDelta) { let chunk_start = self.offset; let chunk_end = chunk_start + self.contents.len(); let mut new_state = String::with_capacity(self.contents.len()); let mut prev_copy_end = 0; let mut del_before: usize = 0; let mut ins_before: usize = 0; for op in delta.els.as_slice() { match *op { DeltaElement::Copy(start, end) => { if start < chunk_start { del_before += start - prev_copy_end; if end >= chunk_start { let cp_end = (end - chunk_start).min(self.contents.len()); new_state.push_str(&self.contents[0..cp_end]); } } else if start <= chunk_end { if prev_copy_end < chunk_start { del_before += chunk_start - prev_copy_end; } let cp_start = start - chunk_start; let cp_end = (end - chunk_start).min(self.contents.len()); new_state.push_str(&self.contents[cp_start..cp_end]); } prev_copy_end = end; } DeltaElement::Insert(ref s) => { if prev_copy_end < chunk_start { ins_before += s.len(); } else if prev_copy_end <= chunk_end { let s: String = s.into(); new_state.push_str(&s); } } } } self.offset += ins_before; self.offset -= del_before; self.contents = new_state; } } /// Calculates the offsets of newlines in `text`, /// inserting the results into `storage`. The offsets are the offset /// of the start of the line, not the line break character. fn newline_offsets(text: &str, storage: &mut Vec<usize>) { let mut cur_idx = 0; while let Some(idx) = memchr(b'\n', &text.as_bytes()[cur_idx..]) { storage.push(cur_idx + idx + 1); cur_idx += idx + 1; } } #[cfg(test)] mod tests { use super::*; use crate::xi_core::plugin_rpc::GetDataResponse; use xi_rope::delta::Delta; use xi_rope::interval::Interval; use xi_rope::rope::{LinesMetric, Rope}; struct MockDataSource(Rope); impl DataSource for MockDataSource { fn get_data( &self, start: usize, unit: TextUnit, _max_size: usize, _rev: u64, ) -> Result<GetDataResponse, Error> { let offset = unit .resolve_offset(&self.0, start) .ok_or(Error::Other("unable to resolve offset".into()))?; let first_line = self.0.line_of_offset(offset); let first_line_offset = offset - self.0.offset_of_line(first_line); let end_off = (offset + CHUNK_SIZE).min(self.0.len()); // not the right error, but okay for this if offset > self.0.len() { Err(Error::Other("offset too big".into())) } else { let chunk = self.0.slice_to_cow(offset..end_off).into_owned(); Ok(GetDataResponse { chunk, offset, first_line, first_line_offset }) } } } #[test] fn simple_chunk() { let mut c = ChunkCache::default(); c.buf_size = 2; c.contents = "oh".into(); let d = Delta::simple_edit(Interval::new(0, 0), "yay".into(), c.contents.len()); c.update(Some(&d), d.new_document_len(), 1, 1); assert_eq!(&c.contents, "yayoh"); assert_eq!(c.offset, 0); let d = Delta::simple_edit(Interval::new(0, 0), "ahh".into(), c.contents.len()); c.update(Some(&d), d.new_document_len(), 1, 2); assert_eq!(&c.contents, "ahhyayoh"); assert_eq!(c.offset, 0); let d = Delta::simple_edit(Interval::new(2, 2), "_oops_".into(), c.contents.len()); assert_eq!(d.els.len(), 3); c.update(Some(&d), d.new_document_len(), 1, 3); assert_eq!(&c.contents, "ah_oops_hyayoh"); assert_eq!(c.offset, 0); let d = Delta::simple_edit(Interval::new(9, 9), "fin".into(), c.contents.len()); c.update(Some(&d), d.new_document_len(), 1, 5); assert_eq!(&c.contents, "ah_oops_hfinyayoh"); assert_eq!(c.offset, 0); } #[test] fn get_lines() { let remote_document = MockDataSource("this\nhas\nfour\nlines!".into()); let mut c = ChunkCache::default(); c.buf_size = remote_document.0.len(); c.num_lines = remote_document.0.measure::<LinesMetric>() + 1; assert_eq!(c.num_lines, 4); assert_eq!(c.buf_size, 20); assert_eq!(c.line_offsets.len(), 0); assert_eq!(c.get_line(&remote_document, 0).ok(), Some("this\n")); assert_eq!(c.line_offsets.len(), 3); assert_eq!(c.offset, 0); assert_eq!(c.buf_size, 20); assert_eq!(c.contents.len(), 16); assert_eq!(c.get_line(&remote_document, 2).ok(), Some("four\n")); assert_eq!(c.cached_offset_of_line(3), Some(14)); assert_eq!(c.cached_offset_of_line(4), None); assert_eq!(c.get_line(&remote_document, 3).ok(), Some("lines!")); assert!(c.get_line(&remote_document, 4).is_err()); } #[test] fn get_region() { let remote_document = MockDataSource("but\nthis big fella\nhas\nFIVE\nlines!".into()); let mut c = ChunkCache::default(); c.buf_size = remote_document.0.len(); c.num_lines = remote_document.0.measure::<LinesMetric>() + 1; assert_eq!(c.get_region(&remote_document, ..3).ok(), Some("but")); assert_eq!(c.get_region(&remote_document, 28..).ok(), Some("lines!")); assert!(c.offset > 0); assert_eq!( c.get_region(&remote_document, ..).ok(), Some("but\nthis big fella\nhas\nFIVE\nlines!") ); } #[test] fn reset_chunk() { let data = GetDataResponse { chunk: "1\n2\n3\n4\n5\n6\n7".into(), offset: 0, first_line: 0, first_line_offset: 0, }; let mut cache = ChunkCache::default(); cache.reset_chunk(data); assert_eq!(cache.line_offsets.len(), 6); assert_eq!(cache.line_offsets, vec![2, 4, 6, 8, 10, 12]); let idx_1 = cache.cached_offset_of_line(1).unwrap(); let idx_2 = cache.cached_offset_of_line(2).unwrap(); assert_eq!(&cache.contents.as_str()[idx_1..idx_2], "2\n"); } #[test] fn clear_up_to() { let mut c = ChunkCache::default(); let data = GetDataResponse { chunk: "this\n has a newline at idx 4\nand at idx 28".into(), offset: 0, first_line: 0, first_line_offset: 0, }; c.reset_chunk(data); assert_eq!(c.line_offsets, vec![5, 29]); c.clear_up_to(5); assert_eq!(c.offset, 5); assert_eq!(c.first_line, 1); assert_eq!(c.first_line_offset, 0); assert_eq!(c.line_offsets, vec![24]); c.clear_up_to(10); assert_eq!(c.offset, 15); assert_eq!(c.first_line, 1); assert_eq!(c.first_line_offset, 10); assert_eq!(c.line_offsets, vec![14]); } #[test] fn simple_insert() { let mut c = ChunkCache::default(); c.contents = "some".into(); c.buf_size = 4; let d = Delta::simple_edit(Interval::new(0, 0), "two\nline\nbreaks".into(), c.contents.len()); assert!(d.as_simple_insert().is_some()); assert!(!d.is_simple_delete()); c.update(Some(&d), d.new_document_len(), 3, 1); assert_eq!(c.line_offsets, vec![4, 9]); let d = Delta::simple_edit(Interval::new(4, 4), "one\nmore".into(), c.contents.len()); assert!(d.as_simple_insert().is_some()); c.update(Some(&d), d.new_document_len(), 4, 2); assert_eq!(&c.contents, "two\none\nmoreline\nbreakssome"); assert_eq!(c.line_offsets, vec![4, 8, 17]); } #[test] fn offset_of_line() { let source = MockDataSource("this\nhas\nfour\nlines!".into()); let mut c = ChunkCache::default(); c.buf_size = source.0.len(); c.num_lines = source.0.measure::<LinesMetric>() + 1; assert_eq!(c.num_lines, 4); assert_eq!(c.cached_offset_of_line(0), Some(0)); assert_eq!(c.offset_of_line(&source, 0).unwrap(), 0); assert_eq!(c.offset_of_line(&source, 1).unwrap(), 5); assert_eq!(c.offset_of_line(&source, 2).unwrap(), 9); assert_eq!(c.offset_of_line(&source, 3).unwrap(), 14); } #[test] fn cached_offset_of_line() { let data = GetDataResponse { chunk: "zer\none\ntwo\ntri".into(), offset: 0, first_line: 0, first_line_offset: 0, }; // ensure that the manual num_lines we set below is the same we would // receive on the wire assert_eq!(Rope::from(&data.chunk).measure::<LinesMetric>() + 1, 4); let mut c = ChunkCache::default(); c.buf_size = data.chunk.len(); c.num_lines = 4; c.reset_chunk(data); assert_eq!(&c.contents, "zer\none\ntwo\ntri"); assert_eq!(&c.line_offsets, &[4, 8, 12]); assert_eq!(c.cached_offset_of_line(0), Some(0)); assert_eq!(c.cached_offset_of_line(1), Some(4)); assert_eq!(c.cached_offset_of_line(2), Some(8)); assert_eq!(c.cached_offset_of_line(3), Some(12)); assert_eq!(c.cached_offset_of_line(4), Some(15)); assert_eq!(c.cached_offset_of_line(5), None); // delete a newline, and see that line_offsets is correctly updated let delta = Delta::simple_edit(Interval::new(3, 4), "".into(), c.buf_size); assert!(delta.is_simple_delete()); c.update(Some(&delta), delta.new_document_len(), 3, 1); assert_eq!(&c.contents, "zerone\ntwo\ntri"); assert_eq!(&c.line_offsets, &[7, 11]); assert_eq!(c.cached_offset_of_line(0), Some(0)); assert_eq!(c.cached_offset_of_line(1), Some(7)); assert_eq!(c.cached_offset_of_line(2), Some(11)); assert_eq!(c.cached_offset_of_line(3), Some(14)); assert_eq!(c.cached_offset_of_line(4), None); } #[test] fn simple_delete() { let data = GetDataResponse { chunk: "zer\none\ntwo\ntri".into(), offset: 0, first_line: 0, first_line_offset: 0, }; // ensure that the manual num_lines we set below is the same we would // receive on the wire assert_eq!(Rope::from(&data.chunk).measure::<LinesMetric>() + 1, 4); let mut c = ChunkCache::default(); c.buf_size = data.chunk.len(); c.num_lines = 4; c.reset_chunk(data); assert_eq!(&c.contents, "zer\none\ntwo\ntri"); assert_eq!(&c.line_offsets, &[4, 8, 12]); let delta = Delta::simple_edit(Interval::new(3, 4), "".into(), c.buf_size); assert!(delta.is_simple_delete()); let (iv, _) = delta.summary(); let start = iv.start(); let end = iv.end(); assert_eq!((start, end), (3, 4)); assert_eq!(c.offset, 0); c.simple_delete(start, end); assert_eq!(&c.line_offsets, &[7, 11]); } #[test] fn large_delete() { // Issue #1136 on github let large_str = "This string literal is larger than CHUNK_SIZE."; assert!(large_str.len() > CHUNK_SIZE); let data = GetDataResponse { // Emulate a cache that has only a part of the buffer. chunk: large_str.split_at(CHUNK_SIZE).0.into(), offset: 0, first_line: 0, first_line_offset: 0, }; let mut c = ChunkCache::default(); c.reset_chunk(data); // This delta deletes everything. let delta = Delta::simple_edit(Interval::new(0, large_str.len()), "".into(), large_str.len()); assert!(delta.is_simple_delete()); c.update(Some(&delta), delta.new_document_len(), 1, 1); // Should succeed } #[test] fn simple_edits_with_offset() { let mut source = MockDataSource("this\nhas\nfour\nlines!".into()); let mut c = ChunkCache::default(); c.buf_size = source.0.len(); c.num_lines = source.0.measure::<LinesMetric>() + 1; // get line fetches from source, starting at this line assert_eq!(c.get_line(&source, 2).ok(), Some("four\n")); assert_eq!(c.offset, 9); assert_eq!(&c.contents, "four\nlines!"); assert_eq!(c.offset_of_line(&source, 3).unwrap(), 14); let d = Delta::simple_edit( Interval::new(10, 10), "ive nice\ns".into(), c.contents.len() + c.offset, ); c.update(Some(&d), d.new_document_len(), 5, 1); // keep our source up to date source.0 = "this\nhas\nfive nice\nsour\nlines!".into(); assert_eq!(&c.contents, "five nice\nsour\nlines!"); assert_eq!(c.offset, 9); assert_eq!(c.offset_of_line(&source, 3).unwrap(), 19); assert_eq!(c.offset_of_line(&source, 4).unwrap(), 24); // this isn't in the chunk, so should cause a fetch that brings in the line assert_eq!(c.offset_of_line(&source, 0).unwrap(), 0); assert_eq!(c.offset, 0); // during tests, we fetch the document in 16 byte chunks assert_eq!(&c.contents, "this\nhas\nfive ni"); // "ce\nsour\nlines!"); assert_eq!(c.offset_of_line(&source, 1).unwrap(), 5); assert_eq!(c.offset_of_line(&source, 3).unwrap(), 19); assert_eq!(c.offset_of_line(&source, 4).unwrap(), 24); // reset and fetch the middle, so we have an offset: let _ = c.offset_of_line(&source, 0); c.clear_up_to(5); assert_eq!(&c.contents, &"this\nhas\nfive nice\nsour\nlines!"[5..CHUNK_SIZE]); assert_eq!(c.offset, 5); assert_eq!(c.first_line, 1); //assert_eq!(c.offset_of_line(&source, 2).unwrap(), 9); let d = Delta::simple_edit(Interval::new(6, 10), "".into(), c.contents.len() + c.offset); assert!(d.is_simple_delete()); c.update(Some(&d), d.new_document_len(), 4, 1); source.0 = "this\nhive nice\nsour\nlines!".into(); assert_eq!(c.offset, 5); assert_eq!(c.first_line, 1); assert_eq!(c.get_line(&source, 1).unwrap(), "hive nice\n"); assert_eq!(c.offset_of_line(&source, 2).unwrap(), 15); } #[test] fn cache_offsets() { let mut c = ChunkCache::default(); // "this\nstring\nis\nour\ntotal\nbuffer" c.contents = "ring\nis\nour\ntotal\nbuffer".into(); c.buf_size = c.contents.len() + 7; c.offset = 7; c.first_line = 1; c.first_line_offset = 2; c.recalculate_line_offsets(); assert_eq!(c.cached_offset_of_line(2), Some(12)); assert_eq!(c.cached_offset_of_line(3), Some(15)); assert_eq!(c.cached_offset_of_line(0), None); assert_eq!(c.cached_offset_of_line(1), Some(5)); } #[test] fn get_big_line() { let test_str = "this\nhas one big line in the middle\nwow, multi-fetch!\nyay!"; let source = MockDataSource(test_str.into()); let mut c = ChunkCache::default(); c.buf_size = source.0.len(); c.num_lines = source.0.measure::<LinesMetric>() + 1; assert_eq!(c.num_lines, 4); assert_eq!(c.get_line(&source, 0).unwrap(), "this\n"); assert_eq!(c.contents, test_str[..CHUNK_SIZE]); assert_eq!(c.get_line(&source, 1).unwrap(), "has one big line in the middle\n"); // fetches are always in an interval of CHUNK_SIZE. because getting this line // requres multiple fetches, contents is truncated at the start of the line. assert_eq!(c.contents, test_str[5..CHUNK_SIZE * 3]); assert_eq!(c.get_line(&source, 3).unwrap(), "yay!"); assert_eq!(c.first_line, 3); } // if get_line is passed a line (0-indexed) that == the total number of lines // (1-indexed) we should always be returning a ::BadRequest error. #[test] fn get_last_line() { let base_document = "\ one\n\ two\n three\n\ four"; let source = MockDataSource(base_document.into()); let mut c = ChunkCache::default(); let delta = Delta::simple_edit(Interval::new(0, 0), base_document.into(), 0); c.update(Some(&delta), base_document.len(), 4, 0); match c.get_line(&source, 4) { Err(Error::BadRequest) => (), other => assert!(false, "expected BadRequest, found {:?}", other), }; } #[test] fn convert_lines_offsets() { let source = MockDataSource("this\nhas\nfour\nlines!".into()); let mut c = ChunkCache::default(); c.buf_size = source.0.len(); c.num_lines = source.0.measure::<LinesMetric>() + 1; assert_eq!(c.line_of_offset(&source, 0).unwrap(), 0); assert_eq!(c.line_of_offset(&source, 1).unwrap(), 0); eprintln!("{:?} {} {}", c.line_offsets, c.offset, c.buf_size); assert_eq!(c.line_of_offset(&source, 4).unwrap(), 0); assert_eq!(c.line_of_offset(&source, 5).unwrap(), 1);
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
true
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/syntect-plugin/src/main.rs
rust/syntect-plugin/src/main.rs
// Copyright 2016 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A syntax highlighting plugin based on syntect. extern crate serde_json; extern crate syntect; extern crate xi_core_lib as xi_core; extern crate xi_plugin_lib; extern crate xi_rope; extern crate xi_trace; mod stackmap; use std::collections::HashMap; use std::ops::Range; use std::path::Path; use std::str::FromStr; use std::sync::MutexGuard; use crate::xi_core::plugin_rpc::ScopeSpan; use crate::xi_core::{ConfigTable, LanguageId, ViewId}; use xi_plugin_lib::{mainloop, Cache, Error, Plugin, StateCache, View}; use xi_rope::{DeltaBuilder, Interval, Rope, RopeDelta, RopeInfo}; use xi_trace::{trace, trace_block}; use syntect::dumps::from_binary; use syntect::parsing::{ ParseState, ScopeRepository, ScopeStack, ScopedMetadata, SyntaxSet, SCOPE_REPO, }; use crate::stackmap::{LookupResult, StackMap}; const LINES_PER_RPC: usize = 10; const INDENTATION_PRIORITY: u64 = 100; type EditBuilder = DeltaBuilder<RopeInfo>; /// Edit types that will get processed. #[derive(PartialEq, Clone, Copy)] pub enum EditType { Insert, Newline, Other, } impl FromStr for EditType { type Err = (); fn from_str(s: &str) -> Result<EditType, ()> { match s { "insert" => Ok(EditType::Insert), "newline" => Ok(EditType::Newline), "other" => Ok(EditType::Other), _ => Err(()), } } } #[derive(PartialEq, Clone)] enum IndentationTask { Newline(usize), Edit(usize), Batch(Range<usize>), } /// The state for syntax highlighting of one file. struct PluginState { stack_idents: StackMap, offset: usize, initial_state: LineState, spans_start: usize, // unflushed spans spans: Vec<ScopeSpan>, new_scopes: Vec<Vec<String>>, // keeps track of the lines (start, end) that might need indentation after edit indentation_state: Vec<IndentationTask>, } type LockedRepo = MutexGuard<'static, ScopeRepository>; /// The syntax highlighting state corresponding to the beginning of a line /// (as stored in the state cache). // Note: this needs to be option because the caching layer relies on Default. // We can't implement that because the actual initial state depends on the // syntax. There are other ways to handle this, but this will do for now. type LineState = Option<(ParseState, ScopeStack)>; /// The state of syntax highlighting for a collection of buffers. struct Syntect<'a> { view_state: HashMap<ViewId, PluginState>, syntax_set: &'a SyntaxSet, } impl<'a> PluginState { fn new() -> Self { PluginState { stack_idents: StackMap::default(), offset: 0, initial_state: None, spans_start: 0, spans: Vec::new(), new_scopes: Vec::new(), indentation_state: Vec::new(), } } /// Compute syntax for one line, optionally also accumulating the style spans. /// /// NOTE: `accumulate_spans` should be true if we're doing syntax highlighting, /// and want to update the client. It should be `false` if we need syntax /// information for another purpose, such as auto-indent. fn compute_syntax( &mut self, line: &str, state: LineState, syntax_set: &SyntaxSet, accumulate_spans: bool, ) -> LineState { let (mut parse_state, mut scope_state) = state.or_else(|| self.initial_state.clone()).unwrap(); let ops = parse_state.parse_line(line, syntax_set); let mut prev_cursor = 0; let repo = SCOPE_REPO.lock().unwrap(); for (cursor, batch) in ops { if !scope_state.is_empty() { let scope_id = self.identifier_for_stack(&scope_state, &repo); let start = self.offset - self.spans_start + prev_cursor; let end = start + (cursor - prev_cursor); if accumulate_spans && start != end { let span = ScopeSpan { start, end, scope_id }; self.spans.push(span); } } prev_cursor = cursor; scope_state.apply(&batch); } if accumulate_spans { // add span for final state let start = self.offset - self.spans_start + prev_cursor; let end = start + (line.len() - prev_cursor); let scope_id = self.identifier_for_stack(&scope_state, &repo); let span = ScopeSpan { start, end, scope_id }; self.spans.push(span); } Some((parse_state, scope_state)) } /// Returns the unique identifier for this `ScopeStack`. We use identifiers /// so we aren't constantly sending long stack names to the peer. fn identifier_for_stack(&mut self, stack: &ScopeStack, repo: &LockedRepo) -> u32 { let identifier = self.stack_idents.get_value(stack.as_slice()); match identifier { LookupResult::Existing(id) => id, LookupResult::New(id) => { let stack_strings = stack.as_slice().iter().map(|slice| repo.to_string(*slice)).collect::<Vec<_>>(); self.new_scopes.push(stack_strings); id } } } // Return true if there's any more work to be done. fn highlight_one_line(&mut self, ctx: &mut MyView, syntax_set: &SyntaxSet) -> bool { if let Some(line_num) = ctx.get_frontier() { let (line_num, offset, state) = ctx.get_prev(line_num); if offset != self.offset { self.flush_spans(ctx); self.offset = offset; self.spans_start = offset; } let new_frontier = match ctx.get_line(line_num) { Ok("") => None, Ok(s) => { let new_state = self.compute_syntax(s, state, syntax_set, true); self.offset += s.len(); if s.as_bytes().last() == Some(&b'\n') { Some((new_state, line_num + 1)) } else { None } } Err(_) => None, }; let mut converged = false; if let Some((ref new_state, new_line_num)) = new_frontier { if let Some(old_state) = ctx.get(new_line_num) { converged = old_state.as_ref().unwrap().0 == new_state.as_ref().unwrap().0; } } if !converged { if let Some((new_state, new_line_num)) = new_frontier { ctx.set(new_line_num, new_state); ctx.update_frontier(new_line_num); return true; } } ctx.close_frontier(); } false } fn flush_spans(&mut self, ctx: &mut MyView) { let _t = trace_block("PluginState::flush_spans", &["syntect"]); if !self.new_scopes.is_empty() { ctx.add_scopes(&self.new_scopes); self.new_scopes.clear(); } if self.spans_start != self.offset { ctx.update_spans(self.spans_start, self.offset - self.spans_start, &self.spans); self.spans.clear(); } self.spans_start = self.offset; } pub fn indent_lines(&mut self, view: &mut MyView, syntax_set: &SyntaxSet) { let mut builder = DeltaBuilder::new(view.get_buf_size()); for indentation_task in self.indentation_state.clone() { match indentation_task { IndentationTask::Newline(line) => self .autoindent_line(view, &mut builder, syntax_set, line) .expect("auto-indent error on newline"), IndentationTask::Edit(line) => self .check_indent_active_edit(view, &mut builder, syntax_set, line) .expect("auto-indent error on insert"), IndentationTask::Batch(range) => self .bulk_autoindent(view, &mut builder, syntax_set, range) .expect("auto-indent error on other"), }; } if !builder.is_empty() { view.edit(builder.build(), INDENTATION_PRIORITY, false, false, String::from("syntect")); } self.indentation_state.clear(); } /// Returns the metadata relevant to the given line. Computes the syntax /// for this line (during normal editing this is only likely for line 0) if /// necessary; in general reuses the syntax state calculated for highlighting. fn get_metadata( &mut self, view: &mut MyView, syntax_set: &'a SyntaxSet, line: usize, ) -> Option<ScopedMetadata<'a>> { let text = view.get_line(line).unwrap_or(""); let scope = self.compute_syntax(text, None, syntax_set, false).map(|(_, scope)| scope)?; Some(syntax_set.metadata().metadata_for_scope(scope.as_slice())) } /// Checks for possible auto-indent changes after an appropriate edit. fn consider_indentation(&mut self, view: &mut MyView, delta: &RopeDelta, edit_type: EditType) { for region in delta.iter_inserts() { let line_of_edit = view.line_of_offset(region.new_offset).unwrap(); let last_line_of_edit = view.line_of_offset(region.new_offset + region.len).unwrap(); match edit_type { EditType::Newline => { self.indentation_state.push(IndentationTask::Newline(line_of_edit + 1)) } EditType::Insert => { let range = region.new_offset..region.new_offset + region.len; let is_whitespace = { let insert_region = view.get_region(range).expect("view must return region"); insert_region.as_bytes().iter().all(u8::is_ascii_whitespace) }; if !is_whitespace { self.indentation_state.push(IndentationTask::Edit(line_of_edit)); } } EditType::Other => { // we are mainly interested in auto-indenting after paste let range = Range { start: line_of_edit, end: last_line_of_edit }; self.indentation_state.push(IndentationTask::Batch(range)); } }; } } fn bulk_autoindent( &mut self, view: &mut MyView, builder: &mut EditBuilder, syntax_set: &SyntaxSet, range: Range<usize>, ) -> Result<(), Error> { let _t = trace_block("Syntect::bulk_autoindent", &["syntect"]); let tab_size = view.get_config().tab_size; let use_spaces = view.get_config().translate_tabs_to_spaces; let mut base_indent = if range.start > 0 { self.previous_nonblank_line(view, range.start)? .map(|l| self.indent_level_of_line(view, l)) .unwrap_or(0) } else { 0 }; for line in range.start..=range.end { let current_line_indent = self.indent_level_of_line(view, line); if line > 0 { let increase_level = self.test_increase(view, syntax_set, line)?; let decrease_level = self.test_decrease(view, syntax_set, line)?; let increase = if increase_level { tab_size } else { 0 }; let decrease = if decrease_level { tab_size } else { 0 }; let final_level = base_indent + increase - decrease; base_indent = final_level; } if base_indent != current_line_indent { let edit_start = view.offset_of_line(line)?; let edit_len = { let line = view.get_line(line)?; line.as_bytes().iter().take_while(|b| **b == b' ' || **b == b'\t').count() }; let indent_text = if use_spaces { n_spaces(base_indent) } else { n_tabs(base_indent / tab_size) }; let iv = Interval::new(edit_start, edit_start + edit_len); builder.replace(iv, indent_text.into()); } } Ok(()) } /// Called when freshly computing a line's indent level, such as after /// a newline, or when re-indenting a block. fn autoindent_line( &mut self, view: &mut MyView, builder: &mut EditBuilder, syntax_set: &SyntaxSet, line: usize, ) -> Result<(), Error> { let _t = trace_block("Syntect::autoindent", &["syntect"]); debug_assert!(line > 0); let tab_size = view.get_config().tab_size; let current_indent = self.indent_level_of_line(view, line); let base_indent = self .previous_nonblank_line(view, line)? .map(|l| self.indent_level_of_line(view, l)) .unwrap_or(0); let increase_level = self.test_increase(view, syntax_set, line)?; let decrease_level = self.test_decrease(view, syntax_set, line)?; let increase = if increase_level { tab_size } else { 0 }; let decrease = if decrease_level { tab_size } else { 0 }; let final_level = base_indent + increase - decrease; if final_level != current_indent { self.set_indent(view, builder, line, final_level) } else { Ok(()) } } /// Called when actively editing a line; chiefly checks for whether or not /// the current line should be de-indented, such as after a closing '}'. fn check_indent_active_edit( &mut self, view: &mut MyView, builder: &mut EditBuilder, syntax_set: &SyntaxSet, line: usize, ) -> Result<(), Error> { let _t = trace_block("Syntect::check_indent_active_line", &["syntect"]); if line == 0 { return Ok(()); } let tab_size = view.get_config().tab_size; let current_indent = self.indent_level_of_line(view, line); if line == 0 || current_indent == 0 { return Ok(()); } let just_increased = self.test_increase(view, syntax_set, line)?; let decrease = self.test_decrease(view, syntax_set, line)?; let prev_line = self.previous_nonblank_line(view, line)?; let mut indent_level = prev_line.map(|l| self.indent_level_of_line(view, l)).unwrap_or(0); if decrease { // the first line after an increase should just match the previous line if !just_increased { indent_level = indent_level.saturating_sub(tab_size); } // we don't want to change indent level if this line doesn't // match `test_decrease`, because the user could have changed // it manually, and we respect that. if indent_level != current_indent { return self.set_indent(view, builder, line, indent_level); } } Ok(()) } fn set_indent( &self, view: &mut MyView, builder: &mut EditBuilder, line: usize, level: usize, ) -> Result<(), Error> { let edit_start = view.offset_of_line(line)?; let edit_len = { let line = view.get_line(line)?; line.as_bytes().iter().take_while(|b| **b == b' ' || **b == b'\t').count() }; let use_spaces = view.get_config().translate_tabs_to_spaces; let tab_size = view.get_config().tab_size; let indent_text = if use_spaces { n_spaces(level) } else { n_tabs(level / tab_size) }; let iv = Interval::new(edit_start, edit_start + edit_len); builder.replace(iv, indent_text.into()); Ok(()) } /// Test whether the indent level should be increased for this line, /// by testing the _previous_ line against a regex. fn test_increase( &mut self, view: &mut MyView, syntax_set: &SyntaxSet, line: usize, ) -> Result<bool, Error> { debug_assert!(line > 0, "increasing indent requires a previous line"); let prev_line = match self.previous_nonblank_line(view, line) { Ok(Some(l)) => l, Ok(None) => return Ok(false), Err(e) => return Err(e), }; let metadata = self.get_metadata(view, syntax_set, prev_line).ok_or(Error::PeerDisconnect)?; let line = view.get_line(prev_line)?; let comment_str = match metadata.line_comment().map(|s| s.to_owned()) { Some(s) => s, None => return Ok(metadata.increase_indent(line)), }; // if the previous line is a comment, the indent level should not be increased if line.trim().starts_with(&comment_str.trim()) { Ok(false) } else { Ok(metadata.increase_indent(line)) } } /// Test whether the indent level for this line should be decreased, by /// checking this line against a regex. fn test_decrease( &mut self, view: &mut MyView, syntax_set: &SyntaxSet, line: usize, ) -> Result<bool, Error> { if line == 0 { return Ok(false); } let metadata = self.get_metadata(view, syntax_set, line).ok_or(Error::PeerDisconnect)?; let line = view.get_line(line)?; Ok(metadata.decrease_indent(line)) } fn previous_nonblank_line( &self, view: &mut MyView, line: usize, ) -> Result<Option<usize>, Error> { debug_assert!(line > 0); let mut line = line; while line > 0 { line -= 1; let text = view.get_line(line)?; if !text.bytes().all(|b| b.is_ascii_whitespace()) { return Ok(Some(line)); } } Ok(None) } fn indent_level_of_line(&self, view: &mut MyView, line: usize) -> usize { let tab_size = view.get_config().tab_size; let line = view.get_line(line).unwrap_or(""); line.as_bytes() .iter() .take_while(|b| **b == b' ' || **b == b'\t') .map(|b| if b == &b' ' { 1 } else { tab_size }) .sum() } fn reindent(&mut self, view: &mut MyView, syntax_set: &SyntaxSet, lines: &[(usize, usize)]) { let mut builder = DeltaBuilder::new(view.get_buf_size()); for (start, end) in lines { let range = Range { start: *start, end: *end - 1 }; self.bulk_autoindent(view, &mut builder, syntax_set, range).expect("error on reindent"); } view.edit(builder.build(), INDENTATION_PRIORITY, false, false, String::from("syntect")); } fn toggle_comment( &mut self, view: &mut MyView, syntax_set: &SyntaxSet, lines: &[(usize, usize)], ) { let _t = trace_block("Syntect::toggle_comment", &["syntect"]); if lines.is_empty() { return; } let mut builder = DeltaBuilder::new(view.get_buf_size()); for (start, end) in lines { let range = Range { start: *start, end: *end }; self.toggle_comment_line_range(view, syntax_set, &mut builder, range); } if builder.is_empty() { eprintln!("no delta for lines {:?}", &lines); } else { view.edit(builder.build(), INDENTATION_PRIORITY, false, true, String::from("syntect")); } } fn toggle_comment_line_range( &mut self, view: &mut MyView, syntax_set: &SyntaxSet, builder: &mut EditBuilder, line_range: Range<usize>, ) { let comment_str = match self .get_metadata(view, syntax_set, line_range.start) .and_then(|s| s.line_comment().map(|s| s.to_owned())) { Some(s) => s, None => return, }; match view .get_line(line_range.start) .map(|l| comment_str.trim() == l.trim() || l.trim().starts_with(&comment_str)) { Ok(true) => self.remove_comment_marker(view, builder, line_range, &comment_str), Ok(false) => self.insert_comment_marker(view, builder, line_range, &comment_str), Err(e) => eprintln!("toggle comment error: {:?}", e), } } fn insert_comment_marker( &self, view: &mut MyView, builder: &mut EditBuilder, line_range: Range<usize>, comment_str: &str, ) { // when commenting out multiple lines, we insert all comment markers at // the same indent level: that of the least indented line. let line_offset = line_range .clone() .map(|num| { view.get_line(num) .ok() .and_then(|line| line.as_bytes().iter().position(|b| *b != b' ' && *b != b'\t')) .unwrap_or(0) }) .min() .unwrap_or(0); let comment_txt = Rope::from(&comment_str); for num in line_range { let offset = view.offset_of_line(num).unwrap(); let line = view.get_line(num).unwrap(); if line.trim().starts_with(&comment_str) { continue; } let iv = Interval::new(offset + line_offset, offset + line_offset); builder.replace(iv, comment_txt.clone()); } } fn remove_comment_marker( &self, view: &mut MyView, builder: &mut EditBuilder, lines: Range<usize>, comment_str: &str, ) { for num in lines { let offset = view.offset_of_line(num).unwrap(); let line = view.get_line(num).unwrap(); let (comment_start, len) = match line.find(&comment_str) { Some(off) => (offset + off, comment_str.len()), None if line.trim() == comment_str.trim() => (offset, comment_str.trim().len()), None => continue, }; let iv = Interval::new(comment_start, comment_start + len); builder.delete(iv); } } } type MyView = View<StateCache<LineState>>; impl<'a> Syntect<'a> { fn new(syntax_set: &'a SyntaxSet) -> Self { Syntect { view_state: HashMap::new(), syntax_set } } /// Wipes any existing state and starts highlighting with `syntax`. fn do_highlighting(&mut self, view: &mut MyView) { let initial_state = { let language_id = view.get_language_id(); let syntax = self .syntax_set .find_syntax_by_name(language_id.as_ref()) .unwrap_or_else(|| self.syntax_set.find_syntax_plain_text()); Some((ParseState::new(syntax), ScopeStack::new())) }; let state = self.view_state.get_mut(&view.get_id()).unwrap(); state.initial_state = initial_state; state.spans = Vec::new(); state.new_scopes = Vec::new(); state.offset = 0; state.spans_start = 0; view.get_cache().clear(); view.schedule_idle(); } } impl<'a> Plugin for Syntect<'a> { type Cache = StateCache<LineState>; fn new_view(&mut self, view: &mut View<Self::Cache>) { let _t = trace_block("Syntect::new_view", &["syntect"]); let view_id = view.get_id(); let state = PluginState::new(); self.view_state.insert(view_id, state); self.do_highlighting(view); } fn did_close(&mut self, view: &View<Self::Cache>) { self.view_state.remove(&view.get_id()); } fn did_save(&mut self, view: &mut View<Self::Cache>, _old: Option<&Path>) { let _t = trace_block("Syntect::did_save", &["syntect"]); self.do_highlighting(view); } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn language_changed(&mut self, view: &mut View<Self::Cache>, _old_lang: LanguageId) { self.do_highlighting(view); } fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, edit_type: String, author: String, ) { let _t = trace_block("Syntect::update", &["syntect"]); view.schedule_idle(); let should_auto_indent = view.get_config().auto_indent; let edit_type = edit_type.parse::<EditType>().ok(); if should_auto_indent && author == "core" && (edit_type == Some(EditType::Newline) || edit_type == Some(EditType::Insert) || edit_type == Some(EditType::Other)) { if let Some(delta) = delta { let state = self.view_state.get_mut(&view.get_id()).unwrap(); state.consider_indentation(view, delta, edit_type.unwrap()); } } } fn custom_command( &mut self, view: &mut View<Self::Cache>, method: &str, params: serde_json::Value, ) { match method { "toggle_comment" => { let lines: Vec<(usize, usize)> = serde_json::from_value(params).unwrap(); let state = self.view_state.get_mut(&view.get_id()).unwrap(); state.toggle_comment(view, self.syntax_set, &lines); } "reindent" => { let lines: Vec<(usize, usize)> = serde_json::from_value(params).unwrap(); let state = self.view_state.get_mut(&view.get_id()).unwrap(); state.reindent(view, self.syntax_set, &lines); } other => eprintln!("syntect received unexpected command {}", other), } } fn idle(&mut self, view: &mut View<Self::Cache>) { let state = self.view_state.get_mut(&view.get_id()).unwrap(); state.indent_lines(view, self.syntax_set); for _ in 0..LINES_PER_RPC { if !state.highlight_one_line(view, self.syntax_set) { state.flush_spans(view); return; } if view.request_is_pending() { trace("yielding for request", &["syntect"]); break; } } state.flush_spans(view); view.schedule_idle(); } } fn main() { let mut syntax_set: SyntaxSet = from_binary(include_bytes!("../assets/default.packdump")); let metadata = from_binary(include_bytes!("../assets/default_meta.packdump")); syntax_set.set_metadata(metadata); let mut state = Syntect::new(&syntax_set); mainloop(&mut state).unwrap(); } fn n_spaces(n: usize) -> &'static str { // when someone opens an issue complaining about this we know we've made it const MAX_SPACES: usize = 160; static MANY_SPACES: [u8; MAX_SPACES] = [b' '; MAX_SPACES]; unsafe { ::std::str::from_utf8_unchecked(&MANY_SPACES[..n.min(MAX_SPACES)]) } } fn n_tabs(n: usize) -> &'static str { const MAX_TABS: usize = 40; static MANY_TABS: [u8; MAX_TABS] = [b'\t'; MAX_TABS]; unsafe { ::std::str::from_utf8_unchecked(&MANY_TABS[..n.min(MAX_TABS)]) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/syntect-plugin/src/stackmap.rs
rust/syntect-plugin/src/stackmap.rs
// Copyright 2017 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! StackMap is a simple nested map type (a trie) used to map `StackScope`s to //! u32s so they can be efficiently sent to xi-core. //! //! For discussion of this approach, see [this //! issue](https://github.com/google/xi-editor/issues/284). use std::collections::HashMap; use syntect::parsing::Scope; #[derive(Debug, Default)] struct Node { value: Option<u32>, children: HashMap<Scope, Node>, } #[derive(Debug, Default)] /// Nested lookup table for stacks of scopes. pub struct StackMap { next_id: u32, scopes: Node, } #[derive(Debug, PartialEq)] /// Result type for `StackMap` lookups. Used to communicate to the user /// whether or not a new identifier has been assigned, which will need to /// be communicated to the peer. pub enum LookupResult { Existing(u32), New(u32), } impl Node { pub fn new(value: u32) -> Self { Node { value: Some(value), children: HashMap::new() } } fn get_value(&mut self, stack: &[Scope], next_id: u32) -> LookupResult { // if this is last item on the stack, get the value, inserting if necessary. let first = stack.first().unwrap(); if stack.len() == 1 { if !self.children.contains_key(first) { self.children.insert(first.to_owned(), Node::new(next_id)); return LookupResult::New(next_id); } // if key exists, value still might not be assigned: let needs_value = self.children[first].value.is_none(); if needs_value { let node = self.children.get_mut(first).unwrap(); node.value = Some(next_id); return LookupResult::New(next_id); } else { let value = self.children[first].value.unwrap(); return LookupResult::Existing(value); } } // not the last item: recurse, creating node as necessary if self.children.get(first).is_none() { self.children.insert(first.to_owned(), Node::default()); } self.children.get_mut(first).unwrap().get_value(&stack[1..], next_id) } } impl StackMap { /// Returns the identifier for this stack, creating it if needed. pub fn get_value(&mut self, stack: &[Scope]) -> LookupResult { assert!(!stack.is_empty()); let result = self.scopes.get_value(stack, self.next_id); if result.is_new() { self.next_id += 1; } result } } impl LookupResult { pub fn is_new(&self) -> bool { matches!(*self, LookupResult::New(_)) } } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; use syntect::parsing::ScopeStack; #[test] fn test_get_value() { let mut stackmap = StackMap::default(); let stack = ScopeStack::from_str("text.rust.test scope.level.three").unwrap(); assert_eq!(stack.as_slice().len(), 2); assert_eq!(stackmap.get_value(stack.as_slice()), LookupResult::New(0)); assert_eq!(stackmap.get_value(stack.as_slice()), LookupResult::Existing(0)); // we don't assign values to intermediate scopes during traversal let stack2 = ScopeStack::from_str("text.rust.test").unwrap(); assert_eq!(stackmap.get_value(stack2.as_slice()), LookupResult::New(1)); assert_eq!(stack2.as_slice().len(), 1); } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/syntect-plugin/examples/make_manifest.rs
rust/syntect-plugin/examples/make_manifest.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A simple tool that generates the syntect plugin's manifest. extern crate syntect; extern crate toml; extern crate xi_core_lib as xi_core; use std::fs::{self, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use crate::xi_core::plugin_manifest::*; use crate::xi_core::LanguageDefinition; use syntect::dumps::dump_to_file; use syntect::parsing::{SyntaxReference, SyntaxSetBuilder}; use toml::Value; const OUT_FILE_NAME: &str = "manifest.toml"; /// Extracts the name and version from Cargo.toml fn parse_name_and_version() -> Result<(String, String), io::Error> { eprintln!("exe: {:?}", ::std::env::current_exe()); let path = PathBuf::from("./Cargo.toml"); let toml_str = fs::read_to_string(path)?; let value = toml_str.parse::<Value>().unwrap(); let package_table = value["package"].as_table().unwrap(); let name = package_table["name"].as_str().unwrap().to_string(); let version = package_table["version"].as_str().unwrap().to_string(); Ok((name, version)) } fn main() -> Result<(), io::Error> { let package_dir = "syntect-resources/Packages"; let packpath = "assets/default.packdump"; let metasource = "syntect-resources/DefaultPackage"; let metapath = "assets/default_meta.packdump"; let mut builder = SyntaxSetBuilder::new(); builder.add_plain_text_syntax(); builder.add_from_folder(package_dir, true).unwrap(); builder.add_from_folder(metasource, false).unwrap(); let syntax_set = builder.build(); dump_to_file(&syntax_set, packpath).unwrap(); dump_to_file(&syntax_set.metadata(), metapath).unwrap(); let lang_defs = syntax_set .syntaxes() .iter() .filter(|syntax| !syntax.file_extensions.is_empty()) .map(lang_from_syn) .collect::<Vec<_>>(); let (name, version) = parse_name_and_version()?; let exec_path = PathBuf::from(format!("./bin/{}", &name)); let mani = PluginDescription { name, version, scope: PluginScope::Global, exec_path, activations: vec![PluginActivation::Autorun], commands: vec![], languages: lang_defs, }; let toml_str = toml::to_string(&mani).unwrap(); let file_path = Path::new(OUT_FILE_NAME); let mut f = File::create(file_path)?; f.write_all(toml_str.as_ref()) } fn lang_from_syn(src: &SyntaxReference) -> LanguageDefinition { let mut extensions = src.file_extensions.clone(); // add support for .xiconfig if extensions.contains(&String::from("toml")) { extensions.push(String::from("xiconfig")); } LanguageDefinition { name: src.name.as_str().into(), extensions, first_line_match: src.first_line_match.clone(), scope: src.scope.to_string(), default_config: None, } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/lib.rs
rust/lsp-lib/src/lib.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate log; extern crate chrono; extern crate fern; extern crate jsonrpc_lite; extern crate languageserver_types as lsp_types; extern crate serde; extern crate url; extern crate xi_core_lib as xi_core; extern crate xi_plugin_lib; extern crate xi_rope; extern crate xi_rpc; use xi_plugin_lib::mainloop; use xi_plugin_lib::Plugin; pub mod conversion_utils; pub mod language_server_client; pub mod lsp_plugin; pub mod parse_helper; mod result_queue; pub mod types; mod utils; pub use crate::lsp_plugin::LspPlugin; pub use crate::types::Config; pub fn start_mainloop<P: Plugin>(plugin: &mut P) { mainloop(plugin).unwrap(); }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/lsp_plugin.rs
rust/lsp-lib/src/lsp_plugin.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Implementation of Language Server Plugin use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; use url::Url; use xi_plugin_lib::{ChunkCache, CoreProxy, Plugin, View}; use xi_rope::rope::RopeDelta; use crate::conversion_utils::*; use crate::language_server_client::LanguageServerClient; use crate::lsp_types::*; use crate::result_queue::ResultQueue; use crate::types::{Config, LanguageResponseError, LspResponse}; use crate::utils::*; use crate::xi_core::{ConfigTable, ViewId}; pub struct ViewInfo { version: u64, ls_identifier: String, } /// Represents the state of the Language Server Plugin pub struct LspPlugin { pub config: Config, view_info: HashMap<ViewId, ViewInfo>, core: Option<CoreProxy>, result_queue: ResultQueue, language_server_clients: HashMap<String, Arc<Mutex<LanguageServerClient>>>, } impl LspPlugin { pub fn new(config: Config) -> Self { LspPlugin { config, core: None, result_queue: ResultQueue::new(), view_info: HashMap::new(), language_server_clients: HashMap::new(), } } } impl Plugin for LspPlugin { type Cache = ChunkCache; fn initialize(&mut self, core: CoreProxy) { self.core = Some(core) } fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, _edit_type: String, _author: String, ) { let view_info = self.view_info.get_mut(&view.get_id()); if let Some(view_info) = view_info { // This won't fail since we definitely have a client for the given // client identifier let ls_client = &self.language_server_clients[&view_info.ls_identifier]; let mut ls_client = ls_client.lock().unwrap(); let sync_kind = ls_client.get_sync_kind(); view_info.version += 1; if let Some(changes) = get_change_for_sync_kind(sync_kind, view, delta) { ls_client.send_did_change(view.get_id(), changes, view_info.version); } } } fn did_save(&mut self, view: &mut View<Self::Cache>, _old: Option<&Path>) { trace!("saved view {}", view.get_id()); let document_text = view.get_document().unwrap(); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_save(view.get_id(), &document_text); }); } fn did_close(&mut self, view: &View<Self::Cache>) { trace!("close view {}", view.get_id()); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_close(view.get_id()); }); } fn new_view(&mut self, view: &mut View<Self::Cache>) { trace!("new view {}", view.get_id()); let document_text = view.get_document().unwrap(); let path = view.get_path(); let view_id = view.get_id(); // TODO: Use Language Idenitifier assigned by core when the // implementation is settled if let Some(language_id) = self.get_language_for_view(view) { let path = path.unwrap(); let workspace_root_uri = { let config = &self.config.language_config.get_mut(&language_id).unwrap(); config.workspace_identifier.clone().and_then(|identifier| { let path = view.get_path().unwrap(); let q = get_workspace_root_uri(&identifier, path); q.ok() }) }; let result = self.get_lsclient_from_workspace_root(&language_id, &workspace_root_uri); if let Some((identifier, ls_client)) = result { self.view_info .insert(view.get_id(), ViewInfo { version: 0, ls_identifier: identifier }); let mut ls_client = ls_client.lock().unwrap(); let document_uri = Url::from_file_path(path).unwrap(); if !ls_client.is_initialized { ls_client.send_initialize(workspace_root_uri, move |ls_client, result| { if let Ok(result) = result { let init_result: InitializeResult = serde_json::from_value(result).unwrap(); debug!("Init Result: {:?}", init_result); ls_client.server_capabilities = Some(init_result.capabilities); ls_client.is_initialized = true; ls_client.send_did_open(view_id, document_uri, document_text); } }); } else { ls_client.send_did_open(view_id, document_uri, document_text); } } } } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn get_hover(&mut self, view: &mut View<Self::Cache>, request_id: usize, position: usize) { let view_id = view.get_id(); let position_ls = get_position_of_offset(view, position); self.with_language_server_for_view(view, |ls_client| match position_ls { Ok(position) => ls_client.request_hover(view_id, position, move |ls_client, result| { let res = result .map_err(|e| LanguageResponseError::LanguageServerError(format!("{:?}", e))) .and_then(|h| { let hover: Option<Hover> = serde_json::from_value(h).unwrap(); hover.ok_or(LanguageResponseError::NullResponse) }); ls_client.result_queue.push_result(request_id, LspResponse::Hover(res)); ls_client.core.schedule_idle(view_id); }), Err(err) => { ls_client.result_queue.push_result(request_id, LspResponse::Hover(Err(err.into()))); ls_client.core.schedule_idle(view_id); } }); } fn idle(&mut self, view: &mut View<Self::Cache>) { let result = self.result_queue.pop_result(); if let Some((request_id, reponse)) = result { match reponse { LspResponse::Hover(res) => { let res = res.and_then(|h| core_hover_from_hover(view, h)).map_err(|e| e.into()); self.with_language_server_for_view(view, |ls_client| { ls_client.core.display_hover(view.get_id(), request_id, &res) }); } } } } } /// Util Methods impl LspPlugin { /// Get the Language Server Client given the Workspace root /// This method checks if a language server is running at the specified root /// and returns it else it tries to spawn a new language server and returns a /// Arc reference to it fn get_lsclient_from_workspace_root( &mut self, language_id: &str, workspace_root: &Option<Url>, ) -> Option<(String, Arc<Mutex<LanguageServerClient>>)> { workspace_root .clone() .map(|r| r.into_string()) .or_else(|| { let config = &self.config.language_config[language_id]; if config.supports_single_file { // A generic client is the one that supports single files i.e. // Non-Workspace projects as well Some(String::from("generic")) } else { None } }) .and_then(|language_server_identifier| { let contains = self.language_server_clients.contains_key(&language_server_identifier); if contains { let client = self.language_server_clients[&language_server_identifier].clone(); Some((language_server_identifier, client)) } else { let config = &self.config.language_config[language_id]; let client = start_new_server( config.start_command.clone(), config.start_arguments.clone(), config.extensions.clone(), language_id, // Unwrap is safe self.core.clone().unwrap(), self.result_queue.clone(), ); match client { Ok(client) => { let client_clone = client.clone(); self.language_server_clients .insert(language_server_identifier.clone(), client); Some((language_server_identifier, client_clone)) } Err(err) => { error!( "Error occured while starting server for Language: {}: {:?}", language_id, err ); None } } } }) } /// Tries to get language for the View using the extension of the document. /// Only searches for the languages supported by the Language Plugin as /// defined in the config fn get_language_for_view(&mut self, view: &View<ChunkCache>) -> Option<String> { view.get_path() .and_then(|path| path.extension()) .and_then(|extension| extension.to_str()) .and_then(|extension_str| { for (lang, config) in &self.config.language_config { if config.extensions.iter().any(|x| x == extension_str) { return Some(lang.clone()); } } None }) } fn with_language_server_for_view<F, R>(&mut self, view: &View<ChunkCache>, f: F) -> Option<R> where F: FnOnce(&mut LanguageServerClient) -> R, { let view_info = self.view_info.get_mut(&view.get_id())?; let ls_client_arc = &self.language_server_clients[&view_info.ls_identifier]; let mut ls_client = ls_client_arc.lock().unwrap(); Some(f(&mut ls_client)) } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/result_queue.rs
rust/lsp-lib/src/result_queue.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::types::LspResponse; use std::collections::VecDeque; use std::sync::{Arc, Mutex}; #[derive(Clone, Debug, Default)] pub struct ResultQueue(Arc<Mutex<VecDeque<(usize, LspResponse)>>>); impl ResultQueue { pub fn new() -> Self { ResultQueue(Arc::new(Mutex::new(VecDeque::new()))) } pub fn push_result(&mut self, request_id: usize, response: LspResponse) { let mut queue = self.0.lock().unwrap(); queue.push_back((request_id, response)); } pub fn pop_result(&mut self) -> Option<(usize, LspResponse)> { let mut queue = self.0.lock().unwrap(); queue.pop_front() } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/types.rs
rust/lsp-lib/src/types.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashMap; use std::io::Error as IOError; use jsonrpc_lite::Error as JsonRpcError; use serde_json::Value; use url::ParseError as UrlParseError; use xi_plugin_lib::Error as PluginLibError; use xi_rpc::RemoteError; use crate::language_server_client::LanguageServerClient; use crate::lsp_types::*; pub enum LspHeader { ContentType, ContentLength(usize), } pub trait Callable: Send { fn call( self: Box<Self>, client: &mut LanguageServerClient, result: Result<Value, JsonRpcError>, ); } impl<F: Send + FnOnce(&mut LanguageServerClient, Result<Value, JsonRpcError>)> Callable for F { fn call(self: Box<F>, client: &mut LanguageServerClient, result: Result<Value, JsonRpcError>) { (*self)(client, result) } } pub type Callback = Box<dyn Callable>; #[derive(Serialize, Deserialize)] /// Language Specific Configuration pub struct LanguageConfig { pub language_name: String, pub start_command: String, pub start_arguments: Vec<String>, pub extensions: Vec<String>, pub supports_single_file: bool, pub workspace_identifier: Option<String>, } /// Represents the config for the Language Plugin #[derive(Serialize, Deserialize)] pub struct Config { pub language_config: HashMap<String, LanguageConfig>, } // Error Types /// Type to represent errors occurred while parsing LSP RPCs #[derive(Debug)] pub enum ParseError { Io(std::io::Error), ParseInt(std::num::ParseIntError), Utf8(std::string::FromUtf8Error), Json(serde_json::Error), Unknown(String), } impl From<std::io::Error> for ParseError { fn from(err: std::io::Error) -> ParseError { ParseError::Io(err) } } impl From<std::string::FromUtf8Error> for ParseError { fn from(err: std::string::FromUtf8Error) -> ParseError { ParseError::Utf8(err) } } impl From<serde_json::Error> for ParseError { fn from(err: serde_json::Error) -> ParseError { ParseError::Json(err) } } impl From<std::num::ParseIntError> for ParseError { fn from(err: std::num::ParseIntError) -> ParseError { ParseError::ParseInt(err) } } impl From<String> for ParseError { fn from(s: String) -> ParseError { ParseError::Unknown(s) } } // TODO: Improve Error handling in module and add more types as necessary /// Types to represent errors in the module. #[derive(Debug)] pub enum Error { PathError, FileUrlParseError, IOError(IOError), UrlParseError(UrlParseError), } impl From<UrlParseError> for Error { fn from(err: UrlParseError) -> Error { Error::UrlParseError(err) } } impl From<IOError> for Error { fn from(err: IOError) -> Error { Error::IOError(err) } } /// Possible Errors that can occur while handling Language Plugins #[derive(Debug)] pub enum LanguageResponseError { LanguageServerError(String), PluginLibError(PluginLibError), NullResponse, FallbackResponse, } impl From<PluginLibError> for LanguageResponseError { fn from(error: PluginLibError) -> Self { LanguageResponseError::PluginLibError(error) } } impl From<LanguageResponseError> for RemoteError { fn from(src: LanguageResponseError) -> Self { match src { LanguageResponseError::NullResponse => { RemoteError::custom(0, "null response from server", None) } LanguageResponseError::FallbackResponse => { RemoteError::custom(1, "fallback response from server", None) } LanguageResponseError::LanguageServerError(error) => { RemoteError::custom(2, "language server error occured", Some(Value::String(error))) } LanguageResponseError::PluginLibError(error) => RemoteError::custom( 3, "Plugin Lib Error", Some(Value::String(format!("{:?}", error))), ), } } } #[derive(Debug)] pub enum LspResponse { Hover(Result<Hover, LanguageResponseError>), }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/conversion_utils.rs
rust/lsp-lib/src/conversion_utils.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Utility functions meant for converting types from LSP to Core format //! and vice-versa use crate::lsp_types::*; use crate::types::LanguageResponseError; use xi_plugin_lib::{Cache, Error as PluginLibError, Hover as CoreHover, Range as CoreRange, View}; pub(crate) fn marked_string_to_string(marked_string: &MarkedString) -> String { match *marked_string { MarkedString::String(ref text) => text.to_owned(), MarkedString::LanguageString(ref d) => format!("```{}\n{}\n```", d.language, d.value), } } pub(crate) fn markdown_from_hover_contents( hover_contents: HoverContents, ) -> Result<String, LanguageResponseError> { let res = match hover_contents { HoverContents::Scalar(content) => marked_string_to_string(&content), HoverContents::Array(content) => { let res: Vec<String> = content.iter().map(marked_string_to_string).collect(); res.join("\n") } HoverContents::Markup(content) => content.value, }; if res.is_empty() { Err(LanguageResponseError::FallbackResponse) } else { Ok(res) } } /// Counts the number of utf-16 code units in the given string. pub(crate) fn count_utf16(s: &str) -> usize { let mut utf16_count = 0; for &b in s.as_bytes() { if (b as i8) >= -0x40 { utf16_count += 1; } if b >= 0xf0 { utf16_count += 1; } } utf16_count } /// Get LSP Style Utf-16 based position given the xi-core style utf-8 offset pub(crate) fn get_position_of_offset<C: Cache>( view: &mut View<C>, offset: usize, ) -> Result<Position, PluginLibError> { let line_num = view.line_of_offset(offset)?; let line_offset = view.offset_of_line(line_num)?; let char_offset = count_utf16(&(view.get_line(line_num)?[0..(offset - line_offset)])); Ok(Position { line: line_num as u64, character: char_offset as u64 }) } pub(crate) fn offset_of_position<C: Cache>( view: &mut View<C>, position: Position, ) -> Result<usize, PluginLibError> { let line_offset = view.offset_of_line(position.line as usize); let mut cur_len_utf16 = 0; let mut cur_len_utf8 = 0; for u in view.get_line(position.line as usize)?.chars() { if cur_len_utf16 >= (position.character as usize) { break; } cur_len_utf16 += u.len_utf16(); cur_len_utf8 += u.len_utf8(); } Ok(cur_len_utf8 + line_offset?) } pub(crate) fn core_range_from_range<C: Cache>( view: &mut View<C>, range: Range, ) -> Result<CoreRange, PluginLibError> { Ok(CoreRange { start: offset_of_position(view, range.start)?, end: offset_of_position(view, range.end)?, }) } pub(crate) fn core_hover_from_hover<C: Cache>( view: &mut View<C>, hover: Hover, ) -> Result<CoreHover, LanguageResponseError> { Ok(CoreHover { content: markdown_from_hover_contents(hover.contents)?, range: match hover.range { Some(range) => Some(core_range_from_range(view, range)?), None => None, }, }) }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/utils.rs
rust/lsp-lib/src/utils.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::ffi::OsStr; use std::io::{BufReader, BufWriter}; use std::path::Path; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex}; use url::Url; use xi_plugin_lib::{Cache, ChunkCache, CoreProxy, Error as PluginLibError, View}; use xi_rope::rope::RopeDelta; use crate::conversion_utils::*; use crate::language_server_client::LanguageServerClient; use crate::lsp_types::*; use crate::parse_helper; use crate::result_queue::ResultQueue; use crate::types::Error; /// Get contents changes of a document modeled according to Language Server Protocol /// given the RopeDelta pub fn get_document_content_changes<C: Cache>( delta: Option<&RopeDelta>, view: &mut View<C>, ) -> Result<Vec<TextDocumentContentChangeEvent>, PluginLibError> { if let Some(delta) = delta { let (interval, _) = delta.summary(); let (start, end) = interval.start_end(); // TODO: Handle more trivial cases like typing when there's a selection or transpose if let Some(node) = delta.as_simple_insert() { let text = String::from(node); let (start, end) = interval.start_end(); let text_document_content_change_event = TextDocumentContentChangeEvent { range: Some(Range { start: get_position_of_offset(view, start)?, end: get_position_of_offset(view, end)?, }), range_length: Some((end - start) as u64), text, }; return Ok(vec![text_document_content_change_event]); } // Or a simple delete else if delta.is_simple_delete() { let mut end_position = get_position_of_offset(view, end)?; // Hack around sending VSCode Style Positions to Language Server. // See this issue to understand: https://github.com/Microsoft/vscode/issues/23173 if end_position.character == 0 { // There is an assumption here that the line separator character is exactly // 1 byte wide which is true for "\n" but it will be an issue if they are not // for example for u+2028 let mut ep = get_position_of_offset(view, end - 1)?; ep.character += 1; end_position = ep; } let text_document_content_change_event = TextDocumentContentChangeEvent { range: Some(Range { start: get_position_of_offset(view, start)?, end: end_position, }), range_length: Some((end - start) as u64), text: String::new(), }; return Ok(vec![text_document_content_change_event]); } } let text_document_content_change_event = TextDocumentContentChangeEvent { range: None, range_length: None, text: view.get_document()?, }; Ok(vec![text_document_content_change_event]) } /// Get changes to be sent to server depending upon the type of Sync supported /// by server pub fn get_change_for_sync_kind( sync_kind: TextDocumentSyncKind, view: &mut View<ChunkCache>, delta: Option<&RopeDelta>, ) -> Option<Vec<TextDocumentContentChangeEvent>> { match sync_kind { TextDocumentSyncKind::None => None, TextDocumentSyncKind::Full => { let text_document_content_change_event = TextDocumentContentChangeEvent { range: None, range_length: None, text: view.get_document().unwrap(), }; Some(vec![text_document_content_change_event]) } TextDocumentSyncKind::Incremental => match get_document_content_changes(delta, view) { Ok(result) => Some(result), Err(err) => { warn!("Error: {:?} Occured. Sending Whole Doc", err); let text_document_content_change_event = TextDocumentContentChangeEvent { range: None, range_length: None, text: view.get_document().unwrap(), }; Some(vec![text_document_content_change_event]) } }, } } /// Get workspace root using the Workspace Identifier and the opened document path /// For example: Cargo.toml can be used to identify a Rust Workspace /// This method traverses up to file tree to return the path to the Workspace root folder pub fn get_workspace_root_uri( workspace_identifier: &str, document_path: &Path, ) -> Result<Url, Error> { let identifier_os_str = OsStr::new(&workspace_identifier); let mut current_path = document_path; loop { let parent_path = current_path.parent(); if let Some(path) = parent_path { for entry in (path.read_dir()?).flatten() { if entry.file_name() == identifier_os_str { return Url::from_file_path(path).map_err(|_| Error::FileUrlParseError); }; } current_path = path; } else { break Err(Error::PathError); } } } /// Start a new Language Server Process by spawning a process given the parameters /// Returns a Arc to the Language Server Client which abstracts connection to the /// server pub fn start_new_server( command: String, arguments: Vec<String>, file_extensions: Vec<String>, language_id: &str, core: CoreProxy, result_queue: ResultQueue, ) -> Result<Arc<Mutex<LanguageServerClient>>, String> { let mut process = Command::new(command) .args(arguments) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("Error Occurred"); let writer = Box::new(BufWriter::new(process.stdin.take().unwrap())); let language_server_client = Arc::new(Mutex::new(LanguageServerClient::new( writer, core, result_queue, language_id.to_owned(), file_extensions, ))); { let ls_client = language_server_client.clone(); let mut stdout = process.stdout; // Unwrap to indicate that we want thread to panic on failure std::thread::Builder::new() .name(format!("{}-lsp-stdout-Looper", language_id)) .spawn(move || { let mut reader = Box::new(BufReader::new(stdout.take().unwrap())); loop { match parse_helper::read_message(&mut reader) { Ok(message_str) => { let mut server_locked = ls_client.lock().unwrap(); server_locked.handle_message(message_str.as_ref()); } Err(err) => error!("Error occurred {:?}", err), }; } }) .unwrap(); } Ok(language_server_client) }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/language_server_client.rs
rust/lsp-lib/src/language_server_client.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Implementation for Language Server Client use std::collections::{HashMap, HashSet}; use std::io::Write; use std::process; use jsonrpc_lite::{Error, Id, JsonRpc, Params}; use serde_json::{to_value, Value}; use url::Url; use xi_plugin_lib::CoreProxy; use crate::lsp_types::*; use crate::result_queue::ResultQueue; use crate::types::Callback; use crate::xi_core::ViewId; /// A type to abstract communication with the language server pub struct LanguageServerClient { writer: Box<dyn Write + Send>, pending: HashMap<u64, Callback>, next_id: u64, language_id: String, pub result_queue: ResultQueue, pub status_items: HashSet<String>, pub core: CoreProxy, pub is_initialized: bool, pub opened_documents: HashMap<ViewId, Url>, pub server_capabilities: Option<ServerCapabilities>, pub file_extensions: Vec<String>, } /// Prepare Language Server Protocol style JSON String from /// a serde_json object `Value` fn prepare_lsp_json(msg: &Value) -> Result<String, serde_json::error::Error> { let request = serde_json::to_string(&msg)?; Ok(format!("Content-Length: {}\r\n\r\n{}", request.len(), request)) } /// Get numeric id from the request id. fn number_from_id(id: &Id) -> u64 { match *id { Id::Num(n) => n as u64, Id::Str(ref s) => s.parse().expect("failed to convert string id to u64"), _ => panic!("unexpected value for id: None"), } } impl LanguageServerClient { pub fn new( writer: Box<dyn Write + Send>, core: CoreProxy, result_queue: ResultQueue, language_id: String, file_extensions: Vec<String>, ) -> Self { LanguageServerClient { writer, pending: HashMap::new(), next_id: 1, is_initialized: false, core, result_queue, status_items: HashSet::new(), language_id, server_capabilities: None, opened_documents: HashMap::new(), file_extensions, } } pub fn write(&mut self, msg: &str) { self.writer.write_all(msg.as_bytes()).expect("error writing to stdin"); self.writer.flush().expect("error flushing child stdin"); } pub fn handle_message(&mut self, message: &str) { match JsonRpc::parse(message) { Ok(JsonRpc::Request(obj)) => trace!("client received unexpected request: {:?}", obj), Ok(value @ JsonRpc::Notification(_)) => { self.handle_notification(value.get_method().unwrap(), value.get_params().unwrap()) } Ok(value @ JsonRpc::Success(_)) => { let id = number_from_id(&value.get_id().unwrap()); let result = value.get_result().unwrap(); self.handle_response(id, Ok(result.clone())); } Ok(value @ JsonRpc::Error(_)) => { let id = number_from_id(&value.get_id().unwrap()); let error = value.get_error().unwrap(); self.handle_response(id, Err(error.clone())); } Err(err) => error!("Error in parsing incoming string: {}", err), } } pub fn handle_response(&mut self, id: u64, result: Result<Value, Error>) { let callback = self .pending .remove(&id) .unwrap_or_else(|| panic!("id {} missing from request table", id)); callback.call(self, result); } pub fn handle_notification(&mut self, method: &str, params: Params) { trace!("Notification Received =>\n Method: {}, params: {:?}", method, params); match method { "window/showMessage" => {} "window/logMessage" => {} "textDocument/publishDiagnostics" => {} "telemetry/event" => {} _ => self.handle_misc_notification(method, params), } } pub fn handle_misc_notification(&mut self, method: &str, params: Params) { match self.language_id.to_lowercase().as_ref() { "rust" => self.handle_rust_misc_notification(method, params), _ => warn!("Unknown notification: {}", method), } } fn remove_status_item(&mut self, id: &str) { self.status_items.remove(id); for view_id in self.opened_documents.keys() { self.core.remove_status_item(*view_id, id); } } fn add_status_item(&mut self, id: &str, value: &str, alignment: &str) { self.status_items.insert(id.to_string()); for view_id in self.opened_documents.keys() { self.core.add_status_item(*view_id, id, value, alignment); } } fn update_status_item(&mut self, id: &str, value: &str) { for view_id in self.opened_documents.keys() { self.core.update_status_item(*view_id, id, value); } } pub fn send_request(&mut self, method: &str, params: Params, completion: Callback) { let request = JsonRpc::request_with_params(Id::Num(self.next_id as i64), method, params); self.pending.insert(self.next_id, completion); self.next_id += 1; self.send_rpc(&to_value(&request).unwrap()); } fn send_rpc(&mut self, value: &Value) { let rpc = match prepare_lsp_json(value) { Ok(r) => r, Err(err) => panic!("Encoding Error {:?}", err), }; trace!("Sending RPC: {:?}", rpc); self.write(rpc.as_ref()); } pub fn send_notification(&mut self, method: &str, params: Params) { let notification = JsonRpc::notification_with_params(method, params); let res = to_value(&notification).unwrap(); self.send_rpc(&res); } } /// Methods to abstract sending notifications and requests to the language server impl LanguageServerClient { /// Send the Initialize Request given the Root URI of the /// Workspace. It is None for non-workspace projects. pub fn send_initialize<CB>(&mut self, root_uri: Option<Url>, on_init: CB) where CB: 'static + Send + FnOnce(&mut LanguageServerClient, Result<Value, Error>), { let client_capabilities = ClientCapabilities::default(); let init_params = InitializeParams { process_id: Some(u64::from(process::id())), root_uri, root_path: None, initialization_options: None, capabilities: client_capabilities, trace: Some(TraceOption::Verbose), workspace_folders: None, }; let params = Params::from(serde_json::to_value(init_params).unwrap()); self.send_request("initialize", params, Box::new(on_init)); } /// Send textDocument/didOpen Notification to the Language Server pub fn send_did_open(&mut self, view_id: ViewId, document_uri: Url, document_text: String) { self.opened_documents.insert(view_id, document_uri.clone()); let text_document_did_open_params = DidOpenTextDocumentParams { text_document: TextDocumentItem { language_id: self.language_id.clone(), uri: document_uri, version: 0, text: document_text, }, }; let params = Params::from(serde_json::to_value(text_document_did_open_params).unwrap()); self.send_notification("textDocument/didOpen", params); } /// Send textDocument/didClose Notification to the Language Server pub fn send_did_close(&mut self, view_id: ViewId) { let uri = self.opened_documents[&view_id].clone(); let text_document_did_close_params = DidCloseTextDocumentParams { text_document: TextDocumentIdentifier { uri } }; let params = Params::from(serde_json::to_value(text_document_did_close_params).unwrap()); self.send_notification("textDocument/didClose", params); self.opened_documents.remove(&view_id); } /// Send textDocument/didChange Notification to the Language Server pub fn send_did_change( &mut self, view_id: ViewId, changes: Vec<TextDocumentContentChangeEvent>, version: u64, ) { let text_document_did_change_params = DidChangeTextDocumentParams { text_document: VersionedTextDocumentIdentifier { uri: self.opened_documents[&view_id].clone(), version: Some(version), }, content_changes: changes, }; let params = Params::from(serde_json::to_value(text_document_did_change_params).unwrap()); self.send_notification("textDocument/didChange", params); } /// Send textDocument/didSave notification to the Language Server pub fn send_did_save(&mut self, view_id: ViewId, _document_text: &str) { // Add support for sending document text as well. Currently missing in LSP types // and is optional in LSP Specification let text_document_did_save_params = DidSaveTextDocumentParams { text_document: TextDocumentIdentifier { uri: self.opened_documents[&view_id].clone() }, }; let params = Params::from(serde_json::to_value(text_document_did_save_params).unwrap()); self.send_notification("textDocument/didSave", params); } pub fn request_hover<CB>(&mut self, view_id: ViewId, position: Position, on_result: CB) where CB: 'static + Send + FnOnce(&mut LanguageServerClient, Result<Value, Error>), { let text_document_position_params = TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: self.opened_documents[&view_id].clone() }, position, }; let params = Params::from(serde_json::to_value(text_document_position_params).unwrap()); self.send_request("textDocument/hover", params, Box::new(on_result)) } } /// Helper methods to query the capabilities of the Language Server before making /// a request. For example: we can check if the Language Server supports sending /// incremental edits before proceeding to send one. impl LanguageServerClient { /// Method to get the sync kind Supported by the Server pub fn get_sync_kind(&mut self) -> TextDocumentSyncKind { match self.server_capabilities.as_ref().and_then(|c| c.text_document_sync.as_ref()) { Some(&TextDocumentSyncCapability::Kind(kind)) => kind, _ => TextDocumentSyncKind::Full, } } } /// Language Specific Notification handling implementations impl LanguageServerClient { pub fn handle_rust_misc_notification(&mut self, method: &str, params: Params) { match method { "window/progress" => { match params { Params::Map(m) => { let done = m.get("done").unwrap_or(&Value::Bool(false)); if let Value::Bool(done) = done { let id: String = serde_json::from_value(m.get("id").unwrap().clone()).unwrap(); if *done { self.remove_status_item(&id); } else { let mut value = String::new(); if let Some(Value::String(s)) = &m.get("title") { value.push_str(&format!("{} ", s)); } if let Some(Value::Number(n)) = &m.get("percentage") { value.push_str(&format!( "{} %", (n.as_f64().unwrap() * 100.00).round() )); } if let Some(Value::String(s)) = &m.get("message") { value.push_str(s); } // Add or update item if self.status_items.contains(&id) { self.update_status_item(&id, &value); } else { self.add_status_item(&id, &value, "left"); } } } } _ => warn!("Unexpected type"), } } _ => warn!("Unknown Notification from RLS: {} ", method), } } }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/parse_helper.rs
rust/lsp-lib/src/parse_helper.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Utility methods to parse the input from the Language Server use crate::types::{LspHeader, ParseError}; use std::io::BufRead; const HEADER_CONTENT_LENGTH: &str = "content-length"; const HEADER_CONTENT_TYPE: &str = "content-type"; /// parse header from the incoming input string fn parse_header(s: &str) -> Result<LspHeader, ParseError> { let split: Vec<String> = s.splitn(2, ": ").map(|s| s.trim().to_lowercase()).collect(); if split.len() != 2 { return Err(ParseError::Unknown("Malformed".to_string())); }; match split[0].as_ref() { HEADER_CONTENT_TYPE => Ok(LspHeader::ContentType), HEADER_CONTENT_LENGTH => Ok(LspHeader::ContentLength(split[1].parse()?)), _ => Err(ParseError::Unknown("Unknown parse error occurred".to_string())), } } /// Blocking call to read a message from the provided BufRead pub fn read_message<T: BufRead>(reader: &mut T) -> Result<String, ParseError> { let mut buffer = String::new(); let mut content_length: Option<usize> = None; loop { buffer.clear(); let _result = reader.read_line(&mut buffer); match &buffer { s if s.trim().is_empty() => break, s => { match parse_header(s)? { LspHeader::ContentLength(len) => content_length = Some(len), LspHeader::ContentType => (), }; } }; } let content_length = content_length.ok_or_else(|| format!("missing content-length header: {}", buffer))?; let mut body_buffer = vec![0; content_length]; reader.read_exact(&mut body_buffer)?; let body = String::from_utf8(body_buffer)?; Ok(body) }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
xi-editor/xi-editor
https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/lsp-lib/src/bin/xi-lsp-plugin.rs
rust/lsp-lib/src/bin/xi-lsp-plugin.rs
// Copyright 2018 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate xi_lsp_lib; #[macro_use] extern crate serde_json; extern crate chrono; extern crate fern; extern crate log; use xi_lsp_lib::{start_mainloop, Config, LspPlugin}; fn init_logger() -> Result<(), fern::InitError> { let level_filter = match std::env::var("XI_LOG") { Ok(level) => match level.to_lowercase().as_ref() { "trace" => log::LevelFilter::Trace, "debug" => log::LevelFilter::Debug, _ => log::LevelFilter::Info, }, // Default to info Err(_) => log::LevelFilter::Info, }; fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) .level(level_filter) .chain(std::io::stderr()) .chain(fern::log_file("xi-lsp-plugin.log")?) .apply() .map_err(|e| e.into()) } fn main() { // The specified language server must be in PATH. XCode does not use // the PATH variable of your shell. See the answers below to modify PATH to // have language servers in PATH while running from XCode. // https://stackoverflow.com/a/17394454 and https://stackoverflow.com/a/43043687 let config = json!({ "language_config": { // Install instructions here: https://github.com/rust-lang-nursery/rls "rust" : { "language_name": "Rust", "start_command": "rls", "start_arguments": [], "extensions": ["rs"], "supports_single_file": false, "workspace_identifier": "Cargo.toml" }, // Install with: npm install -g vscode-json-languageserver "json": { "language_name": "Json", "start_command": "vscode-json-languageserver", "start_arguments": ["--stdio"], "extensions": ["json", "jsonc"], "supports_single_file": true, }, // Install with: npm install -g javascript-typescript-langserver "typescript": { "language_name": "Typescript", "start_command": "javascript-typescript-stdio", "start_arguments": [], "extensions": ["ts", "js", "jsx", "tsx"], "supports_single_file": true, "workspace_identifier": "package.json" } } }); init_logger().expect("Failed to start logger for LSP Plugin"); let config: Config = serde_json::from_value(config).unwrap(); let mut plugin = LspPlugin::new(config); start_mainloop(&mut plugin); }
rust
Apache-2.0
a2dea3059312795c77caadc639df49bf8a7008eb
2026-01-04T15:41:09.005987Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores_macro/src/lib.rs
reactive_stores_macro/src/lib.rs
use convert_case::{Case, Casing}; use proc_macro2::{Span, TokenStream}; use proc_macro_error2::{abort, abort_call_site, proc_macro_error, OptionExt}; use quote::{quote, ToTokens}; use syn::{ parse::{Parse, ParseStream, Parser}, punctuated::Punctuated, token::Comma, ExprClosure, Field, Fields, GenericParam, Generics, Ident, Index, Meta, Result, Token, Type, TypeParam, Variant, Visibility, WhereClause, }; #[proc_macro_error] #[proc_macro_derive(Store, attributes(store))] pub fn derive_store(input: proc_macro::TokenStream) -> proc_macro::TokenStream { syn::parse_macro_input!(input as Model) .into_token_stream() .into() } #[proc_macro_error] #[proc_macro_derive(Patch, attributes(store, patch))] pub fn derive_patch(input: proc_macro::TokenStream) -> proc_macro::TokenStream { syn::parse_macro_input!(input as PatchModel) .into_token_stream() .into() } /// Removes all constraints from generics arguments list. /// /// # Example /// /// ```rust,ignore /// struct Data< /// 'a, /// T1: ToString + PatchField, /// T2: PatchField, /// T3: 'static + PatchField, /// T4, /// > /// where /// T3: ToString, /// T4: ToString + PatchField, /// { /// data1: &'a T1, /// data2: T2, /// data3: T3, /// data4: T4, /// } /// ``` /// /// Fort the struct above the `[syn::DeriveInput::parse]` will return the instance of [syn::Generics] /// which will conceptually look like this /// /// ```text /// Generics: /// params: /// [ /// 'a, /// T1: ToString + PatchField, /// T2: PatchField, /// T3: 'static + PatchField, /// T4, /// ] /// where_clause: /// [ /// T3: ToString, /// T4: ToString + PatchField, /// ] /// ``` /// /// This method would return a new instance of [syn::Generics] which will conceptually look like this /// /// ```text /// Generics: /// params: /// [ /// 'a, /// T1, /// T2, /// T3, /// T4, /// ] /// where_clause: /// [] /// ``` /// /// This is useful when you want to use a generic arguments list for `impl` sections for type definitions. fn remove_constraint_from_generics(generics: &Generics) -> Generics { let mut new_generics = generics.clone(); // remove contraints directly placed in the generic arguments list // // For generics for `struct A<T: MyTrait>` the `T: MyTrait` becomes `T` for param in new_generics.params.iter_mut() { match param { GenericParam::Lifetime(lifetime) => { lifetime.bounds.clear(); // remove bounds lifetime.colon_token = None; } GenericParam::Type(type_param) => { type_param.bounds.clear(); // remove bounds type_param.colon_token = None; type_param.eq_token = None; type_param.default = None; } GenericParam::Const(const_param) => { // replaces const generic with type param without bounds which is basically an `ident` token *param = GenericParam::Type(TypeParam { attrs: const_param.attrs.clone(), ident: const_param.ident.clone(), colon_token: None, bounds: Punctuated::new(), eq_token: None, default: None, }); } } } new_generics.where_clause = None; // remove where clause new_generics } struct Model { vis: Visibility, name: Ident, generics: Generics, ty: ModelTy, } enum ModelTy { Struct { fields: Vec<Field> }, Enum { variants: Vec<Variant> }, } impl Parse for Model { fn parse(input: ParseStream) -> Result<Self> { let input = syn::DeriveInput::parse(input)?; let ty = match input.data { syn::Data::Struct(s) => { let fields = match s.fields { syn::Fields::Unit => { abort!(s.semi_token, "unit structs are not supported"); } syn::Fields::Named(fields) => { fields.named.into_iter().collect::<Vec<_>>() } syn::Fields::Unnamed(fields) => { fields.unnamed.into_iter().collect::<Vec<_>>() } }; ModelTy::Struct { fields } } syn::Data::Enum(e) => ModelTy::Enum { variants: e.variants.into_iter().collect(), }, _ => { abort_call_site!( "only structs and enums can be used with `Store`" ); } }; Ok(Self { vis: input.vis, generics: input.generics, name: input.ident, ty, }) } } #[derive(Clone)] enum SubfieldMode { Keyed(Box<ExprClosure>, Box<Type>), Skip, } impl Parse for SubfieldMode { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { let mode: Ident = input.parse()?; if mode == "key" { let _col: Token![:] = input.parse()?; let ty: Type = input.parse()?; let _eq: Token![=] = input.parse()?; let closure: ExprClosure = input.parse()?; Ok(SubfieldMode::Keyed(Box::new(closure), Box::new(ty))) } else if mode == "skip" { Ok(SubfieldMode::Skip) } else { Err(input.error("expected `key: <Type> = <closure>`")) } } } impl ToTokens for Model { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let library_path = quote! { reactive_stores }; let Model { vis, name, generics, ty, } = &self; let any_store_field = Ident::new("AnyStoreField", Span::call_site()); let trait_name = Ident::new(&format!("{name}StoreFields"), name.span()); let clear_generics = remove_constraint_from_generics(generics); let params = &generics.params; let clear_params = &clear_generics.params; let generics_with_orig = quote! { <#any_store_field, #params> }; let where_with_orig = { generics .where_clause .as_ref() .map(|w| { let WhereClause { where_token, predicates, } = &w; quote! { #where_token #any_store_field: #library_path::StoreField<Value = #name < #clear_params > >, #predicates } }) .unwrap_or_else(|| quote! { where #any_store_field: #library_path::StoreField<Value = #name < #clear_params > > }) }; // define an extension trait that matches this struct // and implement that trait for all StoreFields let (trait_fields, read_fields): (Vec<_>, Vec<_>) = ty.to_field_data( &library_path, generics, &clear_generics, &any_store_field, name, ); // read access tokens.extend(quote! { #vis trait #trait_name <AnyStoreField, #params> #where_with_orig { #(#trait_fields)* } impl #generics_with_orig #trait_name <AnyStoreField, #clear_params> for AnyStoreField #where_with_orig { #(#read_fields)* } }); } } impl ModelTy { fn to_field_data( &self, library_path: &TokenStream, generics: &Generics, clear_generics: &Generics, any_store_field: &Ident, name: &Ident, ) -> (Vec<TokenStream>, Vec<TokenStream>) { match self { ModelTy::Struct { fields } => fields .iter() .enumerate() .map(|(idx, field)| { let Field { ident, ty, attrs, .. } = &field; let modes = attrs .iter() .find_map(|attr| { attr.meta.path().is_ident("store").then(|| { match &attr.meta { Meta::List(list) => { match Punctuated::< SubfieldMode, Comma, >::parse_terminated .parse2(list.tokens.clone()) { Ok(modes) => Some( modes .iter() .cloned() .collect::<Vec<_>>(), ), Err(e) => abort!(list, e), } } _ => None, } }) }) .flatten(); ( field_to_tokens( idx, false, modes.as_deref(), library_path, ident.as_ref(), generics, clear_generics, any_store_field, name, ty, ), field_to_tokens( idx, true, modes.as_deref(), library_path, ident.as_ref(), generics, clear_generics, any_store_field, name, ty, ), ) }) .unzip(), ModelTy::Enum { variants } => variants .iter() .map(|variant| { let Variant { ident, fields, .. } = variant; ( variant_to_tokens( false, library_path, ident, generics, clear_generics, any_store_field, name, fields, ), variant_to_tokens( true, library_path, ident, generics, clear_generics, any_store_field, name, fields, ), ) }) .unzip(), } } } #[allow(clippy::too_many_arguments)] fn field_to_tokens( idx: usize, include_body: bool, modes: Option<&[SubfieldMode]>, library_path: &proc_macro2::TokenStream, orig_ident: Option<&Ident>, _generics: &Generics, clear_generics: &Generics, any_store_field: &Ident, name: &Ident, ty: &Type, ) -> proc_macro2::TokenStream { let ident = if orig_ident.is_none() { let idx = Ident::new(&format!("field{idx}"), Span::call_site()); quote! { #idx } } else { quote! { #orig_ident } }; let locator = if orig_ident.is_none() { let idx = Index::from(idx); quote! { #idx } } else { quote! { #ident } }; if let Some(modes) = modes { if modes.len() == 1 { let mode = &modes[0]; match mode { SubfieldMode::Keyed(keyed_by, key_ty) => { let signature = quote! { #[track_caller] fn #ident(self) -> #library_path::KeyedSubfield<#any_store_field, #name #clear_generics, #key_ty, #ty> }; return if include_body { quote! { #signature { #library_path::KeyedSubfield::new( self, #idx.into(), #keyed_by, |prev| &prev.#locator, |prev| &mut prev.#locator, ) } } } else { quote! { #signature; } }; } SubfieldMode::Skip => return quote! {}, } } else { abort!( orig_ident .map(|ident| ident.span()) .unwrap_or_else(Span::call_site), "multiple modes not currently supported" ); } } // default subfield if include_body { quote! { fn #ident(self) -> #library_path::Subfield<#any_store_field, #name #clear_generics, #ty> { #library_path::Subfield::new( self, #idx.into(), |prev| &prev.#locator, |prev| &mut prev.#locator, ) } } } else { quote! { fn #ident(self) -> #library_path::Subfield<#any_store_field, #name #clear_generics, #ty>; } } } #[allow(clippy::too_many_arguments)] fn variant_to_tokens( include_body: bool, library_path: &proc_macro2::TokenStream, ident: &Ident, _generics: &Generics, clear_generics: &Generics, any_store_field: &Ident, name: &Ident, fields: &Fields, ) -> proc_macro2::TokenStream { // the method name will always be the snake_cased ident let orig_ident = &ident; let ident = Ident::new(&ident.to_string().to_case(Case::Snake), ident.span()); match fields { // For unit enum fields, we will just return a `bool` subfield, which is // true when this field matches Fields::Unit => { // default subfield if include_body { quote! { fn #ident(self) -> bool { match #library_path::StoreField::reader(&self) { Some(reader) => { #library_path::StoreField::track_field(&self); matches!(&*reader, #name::#orig_ident) }, None => false } } } } else { quote! { fn #ident(self) -> bool; } } } // If an enum branch has named fields, we create N + 1 methods: // 1 `bool` subfield, which is true when this field matches // N `Option<T>` subfields for each of the named fields Fields::Named(fields) => { let mut tokens = if include_body { quote! { fn #ident(self) -> bool { match #library_path::StoreField::reader(&self) { Some(reader) => { #library_path::StoreField::track_field(&self); matches!(&*reader, #name::#orig_ident { .. }) }, None => false } } } } else { quote! { fn #ident(self) -> bool; } }; tokens.extend(fields .named .iter() .map(|field| { let field_ident = field.ident.as_ref().unwrap(); let field_ty = &field.ty; let combined_ident = Ident::new( &format!("{ident}_{field_ident}"), field_ident.span(), ); // default subfield if include_body { quote! { fn #combined_ident(self) -> Option<#library_path::Subfield<#any_store_field, #name #clear_generics, #field_ty>> { #library_path::StoreField::track_field(&self); let reader = #library_path::StoreField::reader(&self); let matches = reader .map(|reader| matches!(&*reader, #name::#orig_ident { .. })) .unwrap_or(false); if matches { Some(#library_path::Subfield::new( self, 0.into(), |prev| { match prev { #name::#orig_ident { #field_ident, .. } => Some(#field_ident), _ => None, } .expect("accessed an enum field that is no longer matched") }, |prev| { match prev { #name::#orig_ident { #field_ident, .. } => Some(#field_ident), _ => None, } .expect("accessed an enum field that is no longer matched") }, )) } else { None } } } } else { quote! { fn #combined_ident(self) -> Option<#library_path::Subfield<#any_store_field, #name #clear_generics, #field_ty>>; } } })); tokens } // If an enum branch has unnamed fields, we create N + 1 methods: // 1 `bool` subfield, which is true when this field matches // N `Option<T>` subfields for each of the unnamed fields Fields::Unnamed(fields) => { let mut tokens = if include_body { quote! { fn #ident(self) -> bool { match #library_path::StoreField::reader(&self) { Some(reader) => { #library_path::StoreField::track_field(&self); matches!(&*reader, #name::#orig_ident { .. }) }, None => false } } } } else { quote! { fn #ident(self) -> bool; } }; let number_of_fields = fields.unnamed.len(); tokens.extend(fields .unnamed .iter() .enumerate() .map(|(idx, field)| { let field_ident = idx; let field_ty = &field.ty; let combined_ident = Ident::new( &format!("{ident}_{field_ident}"), ident.span(), ); let ignore_before = (0..idx).map(|_| quote! { _, }); let ignore_before2 = ignore_before.clone(); let ignore_after = (idx..number_of_fields.saturating_sub(1)).map(|_| quote !{_, }); let ignore_after2 = ignore_after.clone(); // default subfield if include_body { quote! { fn #combined_ident(self) -> Option<#library_path::Subfield<#any_store_field, #name #clear_generics, #field_ty>> { #library_path::StoreField::track_field(&self); let reader = #library_path::StoreField::reader(&self); let matches = reader .map(|reader| matches!(&*reader, #name::#orig_ident(..))) .unwrap_or(false); if matches { Some(#library_path::Subfield::new( self, 0.into(), |prev| { match prev { #name::#orig_ident(#(#ignore_before)* this, #(#ignore_after)*) => Some(this), _ => None, } .expect("accessed an enum field that is no longer matched") }, |prev| { match prev { #name::#orig_ident(#(#ignore_before2)* this, #(#ignore_after2)*) => Some(this), _ => None, } .expect("accessed an enum field that is no longer matched") }, )) } else { None } } } } else { quote! { fn #combined_ident(self) -> Option<#library_path::Subfield<#any_store_field, #name #clear_generics, #field_ty>>; } } })); tokens } } } struct PatchModel { pub name: Ident, pub generics: Generics, pub ty: PatchModelTy, } enum PatchModelTy { Struct { fields: Vec<Field>, }, #[allow(dead_code)] Enum { variants: Vec<Variant>, }, } impl Parse for PatchModel { fn parse(input: ParseStream) -> Result<Self> { let input = syn::DeriveInput::parse(input)?; let ty = match input.data { syn::Data::Struct(s) => { let fields = match s.fields { syn::Fields::Unit => { abort!(s.semi_token, "unit structs are not supported"); } syn::Fields::Named(fields) => { fields.named.into_iter().collect::<Vec<_>>() } syn::Fields::Unnamed(fields) => { fields.unnamed.into_iter().collect::<Vec<_>>() } }; PatchModelTy::Struct { fields } } syn::Data::Enum(_e) => { abort_call_site!("only structs can be used with `Patch`"); // TODO: support enums later on // PatchModelTy::Enum { // variants: e.variants.into_iter().collect(), // } } _ => { abort_call_site!( "only structs and enums can be used with `Store`" ); } }; Ok(Self { name: input.ident, generics: input.generics, ty, }) } } impl ToTokens for PatchModel { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let library_path = quote! { reactive_stores }; let PatchModel { name, generics, ty } = &self; let fields = match ty { PatchModelTy::Struct { fields } => { fields.iter().enumerate().map(|(idx, field)| { let Field { attrs, ident, .. } = &field; let locator = match &ident { Some(ident) => Either::Left(ident), None => Either::Right(Index::from(idx)), }; let closure = attrs .iter() .find_map(|attr| { attr.meta.path().is_ident("patch").then( || match &attr.meta { Meta::List(list) => { match Punctuated::< ExprClosure, Comma, >::parse_terminated .parse2(list.tokens.clone()) { Ok(closures) => { let closure = closures.iter().next().cloned().expect_or_abort("should have ONE closure"); if closure.inputs.len() != 2 { abort!(closure.inputs, "patch closure should have TWO params as in #[patch(|this, new| ...)]"); } closure }, Err(e) => abort!(list, e), } } _ => abort!(attr.meta, "needs to be as `#[patch(|this, new| ...)]`"), }, ) }); if let Some(closure) = closure { let params = closure.inputs; let body = closure.body; quote! { if new.#locator != self.#locator { _ = { let (#params) = (&mut self.#locator, new.#locator); #body }; notify(&new_path); } new_path.replace_last(#idx + 1); } } else { quote! { #library_path::PatchField::patch_field( &mut self.#locator, new.#locator, &new_path, notify ); new_path.replace_last(#idx + 1); } } }).collect::<Vec<_>>() } PatchModelTy::Enum { variants: _ } => { unreachable!("not implemented currently") } }; let clear_generics = remove_constraint_from_generics(generics); let params = clear_generics.params; let where_clause = &generics.where_clause; // read access tokens.extend(quote! { impl #generics #library_path::PatchField for #name <#params> #where_clause { fn patch_field( &mut self, new: Self, path: &#library_path::StorePath, notify: &mut dyn FnMut(&#library_path::StorePath), ) { let mut new_path = path.clone(); new_path.push(0); #(#fields)* } } }); } } enum Either<A, B> { Left(A), Right(B), } impl<A: ToTokens, B: ToTokens> ToTokens for Either<A, B> { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Either::Left(a) => a.to_tokens(tokens), Either::Right(b) => b.to_tokens(tokens), } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/build.rs
leptos_macro/build.rs
use rustc_version::{version_meta, Channel}; fn main() { // Set cfg flags depending on release channel if matches!(version_meta().unwrap().channel, Channel::Nightly) { println!("cargo:rustc-cfg=rustc_nightly"); } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/slice.rs
leptos_macro/src/slice.rs
extern crate proc_macro; use proc_macro::TokenStream; use quote::{quote, ToTokens}; use syn::{ parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, Token, }; struct SliceMacroInput { root: syn::Ident, path: Punctuated<syn::Member, Token![.]>, } impl Parse for SliceMacroInput { fn parse(input: ParseStream) -> syn::Result<Self> { let root: syn::Ident = input.parse()?; input.parse::<Token![.]>()?; // do not accept trailing punctuation let path: Punctuated<syn::Member, Token![.]> = Punctuated::parse_separated_nonempty(input)?; if path.is_empty() { return Err(input.error("expected identifier")); } if !input.is_empty() { return Err(input.error("unexpected token")); } Ok(Self { root, path }) } } impl ToTokens for SliceMacroInput { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let root = &self.root; let path = &self.path; tokens.extend(quote! { ::leptos::reactive::computed::create_slice( #root, |st: &_| st.#path.clone(), |st: &mut _, n| st.#path = n ) }) } } pub fn slice_impl(tokens: TokenStream) -> TokenStream { let input = parse_macro_input!(tokens as SliceMacroInput); input.into_token_stream().into() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/lib.rs
leptos_macro/src/lib.rs
//! Macros for use with the Leptos framework. #![cfg_attr(all(feature = "nightly", rustc_nightly), feature(proc_macro_span))] #![forbid(unsafe_code)] // to prevent warnings from popping up when a nightly feature is stabilized #![allow(stable_features)] // FIXME? every use of quote! {} is warning here -- false positive? #![allow(unknown_lints)] #![allow(private_macro_use)] #![deny(missing_docs)] #[macro_use] extern crate proc_macro_error2; use component::DummyModel; use proc_macro::TokenStream; use proc_macro2::{Span, TokenTree}; use quote::{quote, ToTokens}; use std::str::FromStr; use syn::{parse_macro_input, spanned::Spanned, token::Pub, Visibility}; mod params; mod view; use crate::component::unmodified_fn_name_from_fn_name; mod component; mod lazy; mod memo; mod slice; mod slot; /// The `view` macro uses RSX (like JSX, but Rust!) It follows most of the /// same rules as HTML, with the following differences: /// /// 1. Text content should be provided as a Rust string, i.e., double-quoted: /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// view! { <p>"Here’s some text"</p> } /// # } /// ``` /// /// 2. Self-closing tags need an explicit `/` as in XML/XHTML /// ```rust,compile_fail /// # use leptos::prelude::*; /// /// # fn test() -> impl IntoView { /// // ❌ not like this /// view! { <input type="text" name="name"> } /// # ; /// # } /// ``` /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// // ✅ add that slash /// view! { <input type="text" name="name" /> } /// # } /// ``` /// /// 3. Components (functions annotated with `#[component]`) can be inserted as camel-cased tags. (Generics /// on components are specified as `<Component<T>/>`, not the turbofish `<Component::<T>/>`.) /// ```rust /// # use leptos::prelude::*; /// /// # #[component] /// # fn Counter(initial_value: i32) -> impl IntoView { view! { <p></p>} } /// # fn test() -> impl IntoView { /// view! { <div><Counter initial_value=3 /></div> } /// # ; /// # } /// ``` /// /// 4. Dynamic content can be wrapped in curly braces (`{ }`) to insert text nodes, elements, or set attributes. /// If you insert a signal here, Leptos will create an effect to update the DOM whenever the value changes. /// *(“Signal” here means `Fn() -> T` where `T` is the appropriate type for that node: a `String` in case /// of text nodes, a `bool` for `class:` attributes, etc.)* /// /// Attributes can take a wide variety of primitive types that can be converted to strings. They can also /// take an `Option`, in which case `Some` sets the attribute and `None` removes the attribute. /// /// Note that in some cases, rust-analyzer support may be better if attribute values are surrounded with braces (`{}`). /// Unlike in JSX, attribute values are not required to be in braces, but braces can be used and may improve this LSP support. /// /// ```rust,ignore /// # use leptos::prelude::*; /// /// # fn test() -> impl IntoView { /// let (count, set_count) = create_signal(0); /// /// view! { /// // ❌ not like this: `count.get()` returns an `i32`, not a function /// <p>{count.get()}</p> /// // ✅ this is good: Leptos sees the function and knows it's a dynamic value /// <p>{move || count.get()}</p> /// // 🔥 with the `nightly` feature, `count` is a function, so `count` itself can be passed directly into the view /// <p>{count}</p> /// } /// # ; /// # }; /// ``` /// /// 5. Event handlers can be added with `on:` attributes. In most cases, the events are given the correct type /// based on the event name. /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// view! { /// <button on:click=|ev| { /// log::debug!("click event: {ev:#?}"); /// }> /// "Click me" /// </button> /// } /// # } /// ``` /// /// 6. DOM properties can be set with `prop:` attributes, which take any primitive type or `JsValue` (or a signal /// that returns a primitive or JsValue). They can also take an `Option`, in which case `Some` sets the property /// and `None` deletes the property. /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// let (name, set_name) = create_signal("Alice".to_string()); /// /// view! { /// <input /// type="text" /// name="user_name" /// value={move || name.get()} // this only sets the default value! /// prop:value={move || name.get()} // here's how you update values. Sorry, I didn’t invent the DOM. /// on:click=move |ev| set_name.set(event_target_value(&ev)) // `event_target_value` is a useful little Leptos helper /// /> /// } /// # } /// ``` /// /// 7. Classes can be toggled with `class:` attributes, which take a `bool` (or a signal that returns a `bool`). /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// let (count, set_count) = create_signal(2); /// view! { <div class:hidden-div={move || count.get() < 3}>"Now you see me, now you don’t."</div> } /// # } /// ``` /// /// Class names can include dashes, and since v0.5.0 can include a dash-separated segment of only numbers. /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// let (count, set_count) = create_signal(2); /// view! { <div class:hidden-div-25={move || count.get() < 3}>"Now you see me, now you don’t."</div> } /// # } /// ``` /// /// Class names cannot include special symbols. /// ```rust,compile_fail /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// let (count, set_count) = create_signal(2); /// // class:hidden-[div]-25 is invalid attribute name /// view! { <div class:hidden-[div]-25={move || count.get() < 3}>"Now you see me, now you don’t."</div> } /// # } /// ``` /// /// However, you can pass arbitrary class names using the syntax `class=("name", value)`. /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// let (count, set_count) = create_signal(2); /// // this allows you to use CSS frameworks that include complex class names /// view! { /// <div /// class=("is-[this_-_really]-necessary-42", move || count.get() < 3) /// > /// "Now you see me, now you don’t." /// </div> /// } /// # } /// ``` /// /// 8. Individual styles can also be set with `style:` or `style=("property-name", value)` syntax. /// ```rust /// # use leptos::prelude::*; /// /// # fn test() -> impl IntoView { /// let (x, set_x) = create_signal(0); /// let (y, set_y) = create_signal(0); /// view! { /// <div /// style="position: absolute" /// style:left=move || format!("{}px", x.get()) /// style:top=move || format!("{}px", y.get()) /// style=("background-color", move || format!("rgb({}, {}, 100)", x.get(), y.get())) /// > /// "Moves when coordinates change" /// </div> /// } /// # } /// ``` /// /// 9. You can use the `node_ref` or `_ref` attribute to store a reference to its DOM element in a /// [NodeRef](https://docs.rs/leptos/latest/leptos/prelude/struct.NodeRef.html) to use later. /// ```rust /// # use leptos::prelude::*; /// /// # fn test() -> impl IntoView { /// use leptos::html::Input; /// /// let (value, set_value) = signal(0); /// let my_input = NodeRef::<Input>::new(); /// view! { <input type="text" node_ref=my_input/> } /// // `my_input` now contains an `Element` that we can use anywhere /// # ; /// # }; /// ``` /// /// 10. You can add the same class to every element in the view by passing in a special /// `class = {/* ... */},` argument after ``. This is useful for injecting a class /// provided by a scoped styling library. /// ```rust /// # use leptos::prelude::*; /// /// # fn test() -> impl IntoView { /// let class = "mycustomclass"; /// view! { class = class, /// <div> // will have class="mycustomclass" /// <p>"Some text"</p> // will also have class "mycustomclass" /// </div> /// } /// # } /// ``` /// /// 11. You can set any HTML element’s `innerHTML` with the `inner_html` attribute on an /// element. Be careful: this HTML will not be escaped, so you should ensure that it /// only contains trusted input. /// ```rust /// # use leptos::prelude::*; /// # fn test() -> impl IntoView { /// let html = "<p>This HTML will be injected.</p>"; /// view! { /// <div inner_html=html/> /// } /// # } /// ``` /// /// Here’s a simple example that shows off several of these features, put together /// ```rust /// # use leptos::prelude::*; /// pub fn SimpleCounter() -> impl IntoView { /// // create a reactive signal with the initial value /// let (value, set_value) = create_signal(0); /// /// // create event handlers for our buttons /// // note that `value` and `set_value` are `Copy`, so it's super easy to move them into closures /// let clear = move |_ev| set_value.set(0); /// let decrement = move |_ev| set_value.update(|value| *value -= 1); /// let increment = move |_ev| set_value.update(|value| *value += 1); /// /// view! { /// <div> /// <button on:click=clear>"Clear"</button> /// <button on:click=decrement>"-1"</button> /// <span>"Value: " {move || value.get().to_string()} "!"</span> /// <button on:click=increment>"+1"</button> /// </div> /// } /// } /// ``` #[proc_macro_error2::proc_macro_error] #[proc_macro] #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))] pub fn view(tokens: TokenStream) -> TokenStream { view_macro_impl(tokens, false) } /// The `template` macro behaves like [`view`](view!), except that it wraps the entire tree in a /// [`ViewTemplate`](https://docs.rs/leptos/0.7.0-gamma3/leptos/prelude/struct.ViewTemplate.html). This optimizes creation speed by rendering /// most of the view into a `<template>` tag with HTML rendered at compile time, then hydrating it. /// In exchange, there is a small binary size overhead. #[proc_macro_error2::proc_macro_error] #[proc_macro] #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))] pub fn template(tokens: TokenStream) -> TokenStream { if cfg!(feature = "__internal_erase_components") { view(tokens) } else { view_macro_impl(tokens, true) } } fn view_macro_impl(tokens: TokenStream, template: bool) -> TokenStream { let tokens: proc_macro2::TokenStream = tokens.into(); let mut tokens = tokens.into_iter(); let first = tokens.next(); let second = tokens.next(); let third = tokens.next(); let fourth = tokens.next(); let global_class = match (&first, &second) { (Some(TokenTree::Ident(first)), Some(TokenTree::Punct(eq))) if *first == "class" && eq.as_char() == '=' => { match &fourth { Some(TokenTree::Punct(comma)) if comma.as_char() == ',' => { third.clone() } _ => { abort!( second, "To create a scope class with the view! macro you must put a comma `,` after the value"; help = r#"e.g., view!{ class="my-class", <div>...</div>}"# ) } } } _ => None, }; let tokens = if global_class.is_some() { tokens.collect::<proc_macro2::TokenStream>() } else { [first, second, third, fourth] .into_iter() .flatten() .chain(tokens) .collect() }; let config = rstml::ParserConfig::default().recover_block(true); let parser = rstml::Parser::new(config); let (mut nodes, errors) = parser.parse_recoverable(tokens).split_vec(); let errors = errors.into_iter().map(|e| e.emit_as_expr_tokens()); let nodes_output = view::render_view( &mut nodes, global_class.as_ref(), normalized_call_site(proc_macro::Span::call_site()), template, ); // The allow lint needs to be put here instead of at the expansion of // view::attribute_value(). Adding this next to the expanded expression // seems to break rust-analyzer, but it works when the allow is put here. let output = quote! { { #[allow(unused_braces)] { #(#errors;)* #nodes_output } } }; if template { quote! { ::leptos::prelude::ViewTemplate::new(#output) } } else { output } .into() } fn normalized_call_site(site: proc_macro::Span) -> Option<String> { if cfg!(debug_assertions) { Some(leptos_hot_reload::span_to_stable_id( site.file(), site.start().line(), )) } else { _ = site; None } } /// This behaves like the [`view`](view!) macro, but loads the view from an external file instead of /// parsing it inline. /// /// This is designed to allow editing views in a separate file, if this improves a user's workflow. /// /// The file is loaded and parsed during proc-macro execution, and its path is resolved relative to /// the crate root rather than relative to the file from which it is called. #[proc_macro_error2::proc_macro_error] #[proc_macro] pub fn include_view(tokens: TokenStream) -> TokenStream { let file_name = syn::parse::<syn::LitStr>(tokens).unwrap_or_else(|_| { abort!( Span::call_site(), "the only supported argument is a string literal" ); }); let file = std::fs::read_to_string(file_name.value()).unwrap_or_else(|_| { abort!(Span::call_site(), "could not open file"); }); let tokens = proc_macro2::TokenStream::from_str(&file) .unwrap_or_else(|e| abort!(Span::call_site(), e)); view(tokens.into()) } /// Annotates a function so that it can be used with your template as a Leptos `<Component/>`. /// /// The `#[component]` macro allows you to annotate plain Rust functions as components /// and use them within your Leptos [view](crate::view!) as if they were custom HTML elements. The /// component function takes any number of other arguments. When you use the component somewhere else, /// the names of its arguments are the names of the properties you use in the [view](crate::view!) macro. /// /// Every component function should have the return type `-> impl IntoView`. /// /// You can add Rust doc comments to component function arguments and the macro will use them to /// generate documentation for the component. /// /// Here’s how you would define and use a simple Leptos component which can accept custom properties for a name and age: /// /// ```rust /// # use leptos::prelude::*; /// use std::time::Duration; /// /// #[component] /// fn HelloComponent( /// /// The user's name. /// name: String, /// /// The user's age. /// age: u8, /// ) -> impl IntoView { /// // create the signals (reactive values) that will update the UI /// let (age, set_age) = create_signal(age); /// // increase `age` by 1 every second /// set_interval( /// move || set_age.update(|age| *age += 1), /// Duration::from_secs(1), /// ); /// /// // return the user interface, which will be automatically updated /// // when signal values change /// view! { /// <p>"Your name is " {name} " and you are " {move || age.get()} " years old."</p> /// } /// } /// /// #[component] /// fn App() -> impl IntoView { /// view! { /// <main> /// <HelloComponent name="Greg".to_string() age=32/> /// </main> /// } /// } /// ``` /// /// Here are some important details about how Leptos components work within the framework: /// /// * **The component function only runs once.** Your component function is not a “render” function /// that re-runs whenever changes happen in the state. It’s a “setup” function that runs once to /// create the user interface, and sets up a reactive system to update it. This means it’s okay /// to do relatively expensive work within the component function, as it will only happen once, /// not on every state change. /// /// * Component names are usually in `PascalCase`. If you use a `snake_case` name, then the generated /// component's name will still be in `PascalCase`. This is how the framework recognizes that /// a particular tag is a component, not an HTML element. /// /// ``` /// # use leptos::prelude::*; /// // PascalCase: Generated component will be called MyComponent /// #[component] /// fn MyComponent() -> impl IntoView {} /// /// // snake_case: Generated component will be called MySnakeCaseComponent /// #[component] /// fn my_snake_case_component() -> impl IntoView {} /// ``` /// /// 5. You can access the children passed into the component with the `children` property, which takes /// an argument of the type `Children`. This is an alias for `Box<dyn FnOnce() -> AnyView<_>>`. /// If you need `children` to be a `Fn` or `FnMut`, you can use the `ChildrenFn` or `ChildrenFnMut` /// type aliases. If you want to iterate over the children, you can take `ChildrenFragment`. /// /// ``` /// # use leptos::prelude::*; /// #[component] /// fn ComponentWithChildren(children: ChildrenFragment) -> impl IntoView { /// view! { /// <ul> /// {children() /// .nodes /// .into_iter() /// .map(|child| view! { <li>{child}</li> }) /// .collect::<Vec<_>>()} /// </ul> /// } /// } /// /// #[component] /// fn WrapSomeChildren() -> impl IntoView { /// view! { /// <ComponentWithChildren> /// "Ooh, look at us!" /// <span>"We're being projected!"</span> /// </ComponentWithChildren> /// } /// } /// ``` /// /// ## Customizing Properties /// /// You can use the `#[prop]` attribute on individual component properties (function arguments) to /// customize the types that component property can receive. You can use the following attributes: /// /// * `#[prop(into)]`: This will call `.into()` on any value passed into the component prop. (For example, /// you could apply `#[prop(into)]` to a prop that takes /// [Signal](https://docs.rs/leptos/latest/leptos/prelude/struct.Signal.html), which would /// allow users to pass a [ReadSignal](https://docs.rs/leptos/latest/leptos/prelude/struct.ReadSignal.html) or /// [RwSignal](https://docs.rs/leptos/latest/leptos/prelude/struct.RwSignal.html) /// and automatically convert it.) /// * `#[prop(optional)]`: If the user does not specify this property when they use the component, /// it will be set to its default value. If the property type is `Option<T>`, values should be passed /// as `name=T` and will be received as `Some(T)`. /// * `#[prop(optional_no_strip)]`: The same as `optional`, but requires values to be passed as `None` or /// `Some(T)` explicitly. This means that the optional property can be omitted (and be `None`), or explicitly /// specified as either `None` or `Some(T)`. /// * `#[prop(default = <expr>)]`: Optional property that specifies a default value, which is used when the /// property is not specified. /// * `#[prop(name = "new_name")]`: Specifiy a different name for the property. Can be used to destructure /// fields in component function parameters (see example below). /// /// ```rust /// # use leptos::prelude::*; /// /// #[component] /// pub fn MyComponent( /// #[prop(into)] name: String, /// #[prop(optional)] optional_value: Option<i32>, /// #[prop(optional_no_strip)] optional_no_strip: Option<i32>, /// #[prop(default = 7)] optional_default: i32, /// #[prop(name = "data")] UserInfo { email, user_id }: UserInfo, /// ) -> impl IntoView { /// // whatever UI you need /// } /// /// #[component] /// pub fn App() -> impl IntoView { /// view! { /// <MyComponent /// name="Greg" // automatically converted to String with `.into()` /// optional_value=42 // received as `Some(42)` /// optional_no_strip=Some(42) // received as `Some(42)` /// optional_default=42 // received as `42` /// data=UserInfo {email: "foo", user_id: "bar" } /// /> /// <MyComponent /// name="Bob" // automatically converted to String with `.into()` /// data=UserInfo {email: "foo", user_id: "bar" } /// // optional values can be omitted /// /> /// } /// } /// /// pub struct UserInfo { /// pub email: &'static str, /// pub user_id: &'static str, /// } /// ``` #[proc_macro_error2::proc_macro_error] #[proc_macro_attribute] pub fn component(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream { let is_transparent = if !args.is_empty() { let transparent = parse_macro_input!(args as syn::Ident); if transparent != "transparent" { abort!( transparent, "only `transparent` is supported"; help = "try `#[component(transparent)]` or `#[component]`" ); } true } else { false }; component_macro(s, is_transparent, false, None) } /// Defines a component as an interactive island when you are using the /// `islands` feature of Leptos. Apart from the macro name, /// the API is the same as the [`component`](macro@component) macro. /// /// When you activate the `islands` feature, every `#[component]` /// is server-only by default. This "default to server" behavior is important: /// you opt into shipping code to the client, rather than opting out. You can /// opt into client-side interactivity for any given component by changing from /// `#[component]` to `#[island]`—the two macros are otherwise identical. /// /// Everything that is included inside an island will be compiled to WASM and /// shipped to the browser. So the key to really benefiting from this architecture /// is to make islands as small as possible, and include only the minimal /// required amount of functionality in islands themselves. /// /// Only code included in an island itself is compiled to WASM. This means: /// 1. `children` can be provided from a server `#[component]` to an `#[island]` /// without the island needing to be able to hydrate them. /// 2. Props can be passed from the server to an island. /// /// ## Present Limitations /// A few noteworthy limitations, at the moment: /// 1. `children` are completely opaque in islands. You can't iterate over `children`; /// in fact they're all bundled into a single `<leptos-children>` HTML element. /// 2. Similarly, `children` need to be used in the HTML rendered on the server. /// If they need to be displayed conditionally, they should be included in the HTML /// and rendered or not using `display: none` rather than `<Show>` or ordinary control flow. /// This is because the children aren't serialized at all, other than as HTML: if that /// HTML isn't present in the DOM, even if hidden, it is never sent and not available /// to the client at all. /// /// ## Example /// ```rust,ignore /// use leptos::prelude::*; /// /// #[component] /// pub fn App() -> impl IntoView { /// // this would panic if it ran in the browser /// // but because this isn't an island, it only runs on the server /// let file = /// std::fs::read_to_string("./src/is_this_a_server_component.txt") /// .unwrap(); /// let len = file.len(); /// /// view! { /// <p>"The starting value for the button is the file's length."</p> /// // `value` is serialized and given to the island as a prop /// <Island value=len> /// // `file` is only available on the server /// // island props are projected in, so we can nest /// // server-only content inside islands inside server content etc. /// <p>{file}</p> /// </Island> /// } /// } /// /// #[island] /// pub fn Island( /// #[prop(into)] value: RwSignal<usize>, /// children: Children, /// ) -> impl IntoView { /// // because `RwSignal<T>` implements `From<T>`, we can pass in a plain /// // value and use it as the starting value of a signal here /// view! { /// <button on:click=move |_| value.update(|n| *n += 1)> /// {value} /// </button> /// {children()} /// } /// } /// ``` #[proc_macro_error2::proc_macro_error] #[proc_macro_attribute] pub fn island(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream { let (is_transparent, is_lazy) = if !args.is_empty() { let arg = parse_macro_input!(args as syn::Ident); if arg != "transparent" && arg != "lazy" { abort!( arg, "only `transparent` or `lazy` are supported"; help = "try `#[island(transparent)]`, `#[island(lazy)]`, or `#[island]`" ); } (arg == "transparent", arg == "lazy") } else { (false, false) }; let island_src = s.to_string(); component_macro(s, is_transparent, is_lazy, Some(island_src)) } fn component_macro( s: TokenStream, is_transparent: bool, is_lazy: bool, island: Option<String>, ) -> TokenStream { let mut dummy = syn::parse::<DummyModel>(s.clone()); let parse_result = syn::parse::<component::Model>(s); if let (Ok(ref mut unexpanded), Ok(model)) = (&mut dummy, parse_result) { let expanded = model .is_transparent(is_transparent) .is_lazy(is_lazy) .with_island(island) .into_token_stream(); if !matches!(unexpanded.vis, Visibility::Public(_)) { unexpanded.vis = Visibility::Public(Pub { span: unexpanded.vis.span(), }) } unexpanded.sig.ident = unmodified_fn_name_from_fn_name(&unexpanded.sig.ident); quote! { #expanded #[doc(hidden)] #[allow(clippy::too_many_arguments, clippy::needless_lifetimes)] #unexpanded } } else { match dummy { Ok(mut dummy) => { dummy.sig.ident = unmodified_fn_name_from_fn_name(&dummy.sig.ident); quote! { #[doc(hidden)] #[allow(clippy::too_many_arguments, clippy::needless_lifetimes)] #dummy } } Err(e) => { proc_macro_error2::abort!(e.span(), e); } } }.into() } /// Annotates a struct so that it can be used with your Component as a `slot`. /// /// The `#[slot]` macro allows you to annotate plain Rust struct as component slots and use them /// within your Leptos [`component`](macro@crate::component) properties. The struct can contain any number /// of fields. When you use the component somewhere else, the names of the slot fields are the /// names of the properties you use in the [view](crate::view!) macro. /// /// Here’s how you would define and use a simple Leptos component which can accept a custom slot: /// ```rust /// # use leptos::prelude::*; /// use std::time::Duration; /// /// #[slot] /// struct HelloSlot { /// // Same prop syntax as components. /// #[prop(optional)] /// children: Option<Children>, /// } /// /// #[component] /// fn HelloComponent( /// /// Component slot, should be passed through the <HelloSlot slot> syntax. /// hello_slot: HelloSlot, /// ) -> impl IntoView { /// hello_slot.children.map(|children| children()) /// } /// /// #[component] /// fn App() -> impl IntoView { /// view! { /// <HelloComponent> /// <HelloSlot slot> /// "Hello, World!" /// </HelloSlot> /// </HelloComponent> /// } /// } /// ``` /// /// /// Here are some important details about how slots work within the framework: /// 1. Most of the same rules from [`macro@component`] macro should also be followed on slots. /// /// 2. Specifying only `slot` without a name (such as in `<HelloSlot slot>`) will default the chosen slot to /// the a snake case version of the slot struct name (`hello_slot` for `<HelloSlot>`). /// /// 3. Event handlers cannot be specified directly on the slot. /// /// ```compile_error /// // ❌ This won't work /// # use leptos::prelude::*; /// /// #[slot] /// struct SlotWithChildren { /// children: Children, /// } /// /// #[component] /// fn ComponentWithSlot(slot: SlotWithChildren) -> impl IntoView { /// (slot.children)() /// } /// /// #[component] /// fn App() -> impl IntoView { /// view! { /// <ComponentWithSlot> /// <SlotWithChildren slot:slot on:click=move |_| {}> /// <h1>"Hello, World!"</h1> /// </SlotWithChildren> /// </ComponentWithSlot> /// } /// } /// ``` /// /// ``` /// // ✅ Do this instead /// # use leptos::prelude::*; /// /// #[slot] /// struct SlotWithChildren { /// children: Children, /// } /// /// #[component] /// fn ComponentWithSlot(slot: SlotWithChildren) -> impl IntoView { /// (slot.children)() /// } /// /// #[component] /// fn App() -> impl IntoView { /// view! { /// <ComponentWithSlot> /// <SlotWithChildren slot:slot> /// <div on:click=move |_| {}> /// <h1>"Hello, World!"</h1> /// </div> /// </SlotWithChildren> /// </ComponentWithSlot> /// } /// } /// ``` #[proc_macro_error2::proc_macro_error] #[proc_macro_attribute] pub fn slot(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream { if !args.is_empty() { abort!( Span::call_site(), "no arguments are supported"; help = "try just `#[slot]`" ); } parse_macro_input!(s as slot::Model) .into_token_stream() .into() } /// Declares that a function is a [server function](https://docs.rs/server_fn/latest/server_fn/index.html). /// This means that its body will only run on the server, i.e., when the `ssr` feature on this crate is enabled. /// /// If you call a server function from the client (i.e., when the `csr` or `hydrate` features /// are enabled), it will instead make a network request to the server. /// /// ## Named Arguments /// /// You can provide any combination of the following named arguments: /// - `name`: sets the identifier for the server function’s type, which is a struct created /// to hold the arguments (defaults to the function identifier in PascalCase) /// - `prefix`: a prefix at which the server function handler will be mounted (defaults to `/api`) /// your prefix must begin with `/`. Otherwise your function won't be found. /// - `endpoint`: specifies the exact path at which the server function handler will be mounted, /// relative to the prefix (defaults to the function name followed by unique hash) /// - `input`: the encoding for the arguments (defaults to `PostUrl`) /// - `output`: the encoding for the response (defaults to `Json`) /// - `client`: a custom `Client` implementation that will be used for this server fn /// - `encoding`: (legacy, may be deprecated in future) specifies the encoding, which may be one /// of the following (not case sensitive) /// - `"Url"`: `POST` request with URL-encoded arguments and JSON response /// - `"GetUrl"`: `GET` request with URL-encoded arguments and JSON response /// - `"Cbor"`: `POST` request with CBOR-encoded arguments and response /// - `"GetCbor"`: `GET` request with URL-encoded arguments and CBOR response /// - `req` and `res` specify the HTTP request and response types to be used on the server (these /// should usually only be necessary if you are integrating with a server other than Actix/Axum) /// - `impl_from`: specifies whether to implement trait `From` for server function's type or not. /// By default, if a server function only has one argument, the macro automatically implements the `From` trait /// to convert from the argument type to the server function type, and vice versa, allowing you to convert /// between them easily. Setting `impl_from` to `false` disables this, which can be necessary for argument types /// for which this would create a conflicting implementation. (defaults to `true`) /// /// ```rust,ignore /// #[server( /// name = SomeStructName, /// prefix = "/my_api", /// endpoint = "my_fn", /// input = Cbor, /// output = Json /// impl_from = true /// )] /// pub async fn my_wacky_server_fn(input: Vec<String>) -> Result<usize, ServerFnError> { /// todo!() /// } /// ``` /// /// ## Server Function Encodings /// /// Server functions are designed to allow a flexible combination of `input` and `output` encodings, the set /// of which can be found in the [`server_fn::codec`](../server_fn/codec/index.html) module. ///
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
true
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/slot.rs
leptos_macro/src/slot.rs
use crate::component::{ convert_from_snake_case, drain_filter, is_option, unwrap_option, Docs, }; use attribute_derive::FromAttr; use proc_macro2::{Ident, TokenStream}; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{ parse::Parse, parse_quote, Field, ItemStruct, LitStr, Meta, Type, Visibility, }; pub struct Model { docs: Docs, vis: Visibility, name: Ident, props: Vec<Prop>, body: ItemStruct, } impl Parse for Model { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { let mut item = ItemStruct::parse(input)?; let docs = Docs::new(&item.attrs); let props = item .fields .clone() .into_iter() .map(Prop::new) .collect::<Vec<_>>(); // We need to remove the `#[doc = ""]` and `#[builder(_)]` // attrs from the function signature drain_filter(&mut item.attrs, |attr| match &attr.meta { Meta::NameValue(attr) => attr.path == parse_quote!(doc), Meta::List(attr) => attr.path == parse_quote!(prop), _ => false, }); item.fields.iter_mut().for_each(|arg| { drain_filter(&mut arg.attrs, |attr| match &attr.meta { Meta::NameValue(attr) => attr.path == parse_quote!(doc), Meta::List(attr) => attr.path == parse_quote!(prop), _ => false, }); }); Ok(Self { docs, vis: item.vis.clone(), name: convert_from_snake_case(&item.ident), props, body: item, }) } } impl ToTokens for Model { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { docs, vis, name, props, body, } = self; let (_, generics, where_clause) = body.generics.split_for_impl(); let prop_builder_fields = prop_builder_fields(vis, props); let prop_docs = generate_prop_docs(props); let builder_name_doc = LitStr::new( &format!("Props for the [`{name}`] slot."), name.span(), ); let output = quote! { #[doc = #builder_name_doc] #[doc = ""] #docs #prop_docs #[derive(::leptos::typed_builder_macro::TypedBuilder)] #[builder(doc, crate_module_path=::leptos::typed_builder)] #vis struct #name #generics #where_clause { #prop_builder_fields } impl #generics From<#name #generics> for Vec<#name #generics> #where_clause { fn from(value: #name #generics) -> Self { vec![value] } } /*impl #impl_generics ::leptos::Props for #name #generics #where_clause { type Builder = #builder_name #generics; fn builder() -> Self::Builder { #name::builder() } } impl #impl_generics ::leptos::DynAttrs for #name #generics #where_clause { fn dyn_attrs(mut self, v: Vec<(&'static str, ::leptos::Attribute)>) -> Self { #dyn_attrs_props self } }*/ }; tokens.append_all(output) } } struct Prop { docs: Docs, prop_opts: PropOpt, name: Ident, ty: Type, } impl Prop { fn new(arg: Field) -> Self { let prop_opts = PropOpt::from_attributes(&arg.attrs).unwrap_or_else(|e| { // TODO: replace with `.unwrap_or_abort()` once https://gitlab.com/CreepySkeleton/proc-macro-error/-/issues/17 is fixed abort!(e.span(), e.to_string()); }); let name = if let Some(i) = arg.ident { i } else { abort!( arg.ident, "only `prop: bool` style types are allowed within the \ `#[slot]` macro" ); }; Self { docs: Docs::new(&arg.attrs), prop_opts, name, ty: arg.ty, } } } #[derive(Clone, Debug, FromAttr)] #[attribute(ident = prop)] struct PropOpt { #[attribute(conflicts = [optional_no_strip, strip_option])] pub optional: bool, #[attribute(conflicts = [optional, strip_option])] pub optional_no_strip: bool, #[attribute(conflicts = [optional, optional_no_strip])] pub strip_option: bool, #[attribute(example = "5 * 10")] pub default: Option<syn::Expr>, pub into: bool, pub attrs: bool, } struct TypedBuilderOpts<'a> { default: bool, default_with_value: Option<syn::Expr>, strip_option: bool, into: bool, ty: &'a Type, } impl<'a> TypedBuilderOpts<'a> { pub fn from_opts(opts: &PropOpt, ty: &'a Type) -> Self { Self { default: opts.optional || opts.optional_no_strip || opts.attrs, default_with_value: opts.default.clone(), strip_option: opts.strip_option || opts.optional && is_option(ty), into: opts.into, ty, } } } impl ToTokens for TypedBuilderOpts<'_> { fn to_tokens(&self, tokens: &mut TokenStream) { let default = if let Some(v) = &self.default_with_value { let v = v.to_token_stream().to_string(); quote! { default_code=#v, } } else if self.default { quote! { default, } } else { quote! {} }; // If self.strip_option && self.into, then the strip_option will be represented as part of the transform closure. let strip_option = if self.strip_option && !self.into { quote! { strip_option, } } else { quote! {} }; let into = if self.into { if !self.strip_option { let ty = &self.ty; quote! { fn transform<__IntoReactiveValueMarker>(value: impl ::leptos::prelude::IntoReactiveValue<#ty, __IntoReactiveValueMarker>) -> #ty { value.into_reactive_value() }, } } else { let ty = unwrap_option(self.ty); quote! { fn transform<__IntoReactiveValueMarker>(value: impl ::leptos::prelude::IntoReactiveValue<#ty, __IntoReactiveValueMarker>) -> Option<#ty> { Some(value.into_reactive_value()) }, } } } else { quote! {} }; let setter = if !strip_option.is_empty() || !into.is_empty() { quote! { setter(#strip_option #into) } } else { quote! {} }; let output = if !default.is_empty() || !setter.is_empty() { quote! { #[builder(#default #setter)] } } else { quote! {} }; tokens.append_all(output); } } fn prop_builder_fields(vis: &Visibility, props: &[Prop]) -> TokenStream { props .iter() .map(|prop| { let Prop { docs, name, prop_opts, ty, } = prop; let builder_attrs = TypedBuilderOpts::from_opts(prop_opts, ty); let builder_docs = prop_to_doc(prop, PropDocStyle::Inline); quote! { #docs #builder_docs #builder_attrs #vis #name: #ty, } }) .collect() } fn generate_prop_docs(props: &[Prop]) -> TokenStream { let required_prop_docs = props .iter() .filter(|Prop { prop_opts, .. }| { !(prop_opts.optional || prop_opts.optional_no_strip) }) .map(|p| prop_to_doc(p, PropDocStyle::List)) .collect::<TokenStream>(); let optional_prop_docs = props .iter() .filter(|Prop { prop_opts, .. }| { prop_opts.optional || prop_opts.optional_no_strip }) .map(|p| prop_to_doc(p, PropDocStyle::List)) .collect::<TokenStream>(); let required_prop_docs = if !required_prop_docs.is_empty() { quote! { #[doc = "# Required Props"] #required_prop_docs } } else { quote! {} }; let optional_prop_docs = if !optional_prop_docs.is_empty() { quote! { #[doc = "# Optional Props"] #optional_prop_docs } } else { quote! {} }; quote! { #required_prop_docs #optional_prop_docs } } #[derive(Clone, Copy)] enum PropDocStyle { List, Inline, } fn prop_to_doc( Prop { docs, name, ty, prop_opts, }: &Prop, style: PropDocStyle, ) -> TokenStream { let ty = if (prop_opts.optional || prop_opts.strip_option) && is_option(ty) { unwrap_option(ty) } else { ty.to_owned() }; let type_item: syn::Item = parse_quote! { type SomeType = #ty; }; let file = syn::File { shebang: None, attrs: vec![], items: vec![type_item], }; let pretty_ty = prettyplease::unparse(&file); let pretty_ty = &pretty_ty[16..&pretty_ty.len() - 2]; match style { PropDocStyle::List => { let arg_ty_doc = LitStr::new( &if !prop_opts.into { format!("- **{}**: [`{}`]", quote!(#name), pretty_ty) } else { format!( "- **{}**: `impl`[`Into<{}>`]", quote!(#name), pretty_ty ) }, name.span(), ); let arg_user_docs = docs.padded(); quote! { #[doc = #arg_ty_doc] #arg_user_docs } } PropDocStyle::Inline => { let arg_ty_doc = LitStr::new( &if !prop_opts.into { format!( "**{}**: [`{}`]{}", quote!(#name), pretty_ty, docs.typed_builder() ) } else { format!( "**{}**: `impl`[`Into<{}>`]{}", quote!(#name), pretty_ty, docs.typed_builder() ) }, name.span(), ); quote! { #[builder(setter(doc = #arg_ty_doc))] } } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/params.rs
leptos_macro/src/params.rs
use quote::{quote, quote_spanned}; use syn::spanned::Spanned; pub fn params_impl(ast: &syn::DeriveInput) -> proc_macro::TokenStream { let name = &ast.ident; let fields = if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(ref fields), .. }) = ast.data { fields .named .iter() .map(|field| { let field_name_string = &field .ident .as_ref() .expect("expected named struct fields") .to_string() .trim_start_matches("r#") .to_owned(); let ident = &field.ident; let ty = &field.ty; let span = field.span(); quote_spanned! { span=> #ident: ::leptos_router::params::macro_helpers::Wrapper::<#ty>::__into_param( map.get_str(#field_name_string), #field_name_string )? } }) .collect() } else { vec![] }; let gen = quote! { impl Params for #name { fn from_map(map: &::leptos_router::params::ParamsMap) -> ::core::result::Result<Self, ::leptos_router::params::ParamsError> { use ::leptos_router::params::macro_helpers::Fallback as _; Ok(Self { #(#fields,)* }) } } }; gen.into() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/lazy.rs
leptos_macro/src/lazy.rs
use convert_case::{Case, Casing}; use proc_macro::TokenStream; use proc_macro2::Ident; use proc_macro_error2::abort; use quote::{format_ident, quote}; use std::{ hash::{DefaultHasher, Hash, Hasher}, mem, }; use syn::{parse_macro_input, parse_quote, ItemFn, ReturnType, Stmt}; pub fn lazy_impl(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream { let name = if !args.is_empty() { Some(parse_macro_input!(args as syn::Ident)) } else { None }; let fun = syn::parse::<ItemFn>(s).unwrap_or_else(|e| { abort!(e.span(), "`lazy` can only be used on a function") }); let was_async = fun.sig.asyncness.is_some(); let converted_name = name.unwrap_or_else(|| { Ident::new( &fun.sig.ident.to_string().to_case(Case::Snake), fun.sig.ident.span(), ) }); let (unique_name, unique_name_str) = { let span = proc_macro::Span::call_site(); let location = (span.line(), span.start().column(), span.file()); let mut hasher = DefaultHasher::new(); location.hash(&mut hasher); let hash = hasher.finish(); let unique_name_str = format!("{converted_name}_{hash}"); ( Ident::new(&unique_name_str, converted_name.span()), unique_name_str, ) }; let is_wasm = cfg!(feature = "csr") || cfg!(feature = "hydrate"); if is_wasm { let mut fun = fun; let mut return_wrapper = None; if was_async { fun.sig.asyncness = None; let ty = match &fun.sig.output { ReturnType::Default => quote! { () }, ReturnType::Type(_, ty) => quote! { #ty }, }; let sync_output: ReturnType = parse_quote! { -> ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = #ty> + ::std::marker::Send + ::std::marker::Sync>> }; let async_output = mem::replace(&mut fun.sig.output, sync_output); let stmts = mem::take(&mut fun.block.stmts); fun.block.stmts.push(Stmt::Expr(parse_quote! { ::std::boxed::Box::pin(::leptos::__reexports::send_wrapper::SendWrapper::new(async move { #( #stmts )* })) }, None)); return_wrapper = Some(quote! { return_wrapper(let future = _; { future.await } #async_output), }); } let preload_name = format_ident!("__preload_{}", fun.sig.ident); quote! { #[::leptos::wasm_split::wasm_split( #unique_name, wasm_split_path = ::leptos::wasm_split, preload(#[doc(hidden)] #[allow(non_snake_case)] #preload_name), #return_wrapper )] #fun } } else { let mut fun = fun; if !was_async { fun.sig.asyncness = Some(Default::default()); } let statements = &mut fun.block.stmts; let old_statements = mem::take(statements); statements.push(parse_quote! { ::leptos::prefetch_lazy_fn_on_server(#unique_name_str); }); statements.extend(old_statements); quote! { #fun } } .into() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/memo.rs
leptos_macro/src/memo.rs
extern crate proc_macro; use proc_macro::TokenStream; use quote::{quote, ToTokens}; use syn::{ parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, Token, }; struct MemoMacroInput { root: syn::Ident, path: Punctuated<syn::Member, Token![.]>, } impl Parse for MemoMacroInput { fn parse(input: ParseStream) -> syn::Result<Self> { let root: syn::Ident = input.parse()?; input.parse::<Token![.]>()?; // do not accept trailing punctuation let path: Punctuated<syn::Member, Token![.]> = Punctuated::parse_separated_nonempty(input)?; if path.is_empty() { return Err(input.error("expected identifier")); } if !input.is_empty() { return Err(input.error("unexpected token")); } Ok(Self { root, path }) } } impl ToTokens for MemoMacroInput { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let root = &self.root; let path = &self.path; tokens.extend(quote! { ::leptos::reactive::computed::Memo::new( move |_| { use ::leptos::reactive::traits::With; #root.with(|st: _| st.#path.clone()) } ) }) } } pub fn memo_impl(tokens: TokenStream) -> TokenStream { let input = parse_macro_input!(tokens as MemoMacroInput); input.into_token_stream().into() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/component.rs
leptos_macro/src/component.rs
use attribute_derive::FromAttr; use convert_case::{ Case::{Pascal, Snake}, Casing, }; use itertools::Itertools; use leptos_hot_reload::parsing::value_to_string; use proc_macro2::{Ident, Span, TokenStream}; use proc_macro_error2::abort; use quote::{format_ident, quote, quote_spanned, ToTokens, TokenStreamExt}; use std::hash::DefaultHasher; use syn::{ parse::Parse, parse_quote, spanned::Spanned, token::Colon, visit_mut::VisitMut, AngleBracketedGenericArguments, Attribute, FnArg, GenericArgument, GenericParam, Item, ItemFn, LitStr, Meta, Pat, PatIdent, Path, PathArguments, ReturnType, Signature, Stmt, Type, TypeImplTrait, TypeParam, TypePath, Visibility, }; pub struct Model { is_transparent: bool, is_lazy: bool, island: Option<String>, docs: Docs, unknown_attrs: UnknownAttrs, vis: Visibility, name: Ident, props: Vec<Prop>, body: ItemFn, ret: ReturnType, } impl Parse for Model { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { let mut item = ItemFn::parse(input)?; maybe_modify_return_type(&mut item.sig.output); convert_impl_trait_to_generic(&mut item.sig); let docs = Docs::new(&item.attrs); let unknown_attrs = UnknownAttrs::new(&item.attrs); let props = item .sig .inputs .clone() .into_iter() .map(Prop::new) .collect::<Vec<_>>(); // We need to remove the `#[doc = ""]` and `#[builder(_)]` // attrs from the function signature drain_filter(&mut item.attrs, |attr| match &attr.meta { Meta::NameValue(attr) => attr.path == parse_quote!(doc), Meta::List(attr) => attr.path == parse_quote!(prop), _ => false, }); item.sig.inputs.iter_mut().for_each(|arg| { if let FnArg::Typed(ty) = arg { drain_filter(&mut ty.attrs, |attr| match &attr.meta { Meta::NameValue(attr) => attr.path == parse_quote!(doc), Meta::List(attr) => attr.path == parse_quote!(prop), _ => false, }); } }); Ok(Self { is_transparent: false, is_lazy: false, island: None, docs, unknown_attrs, vis: item.vis.clone(), name: convert_from_snake_case(&item.sig.ident), props, ret: item.sig.output.clone(), body: item, }) } } /// Exists to fix nested routes defined in a separate component in erased mode, /// by replacing the return type with AnyNestedRoute, which is what it'll be, but is required as the return type for compiler inference. fn maybe_modify_return_type(ret: &mut ReturnType) { #[cfg(feature = "__internal_erase_components")] { if let ReturnType::Type(_, ty) = ret { if let Type::ImplTrait(TypeImplTrait { bounds, .. }) = ty.as_ref() { // If one of the bounds is MatchNestedRoutes, we need to replace the return type with AnyNestedRoute: if bounds.iter().any(|bound| { if let syn::TypeParamBound::Trait(trait_bound) = bound { if trait_bound.path.segments.iter().any( |path_segment| { path_segment.ident == "MatchNestedRoutes" }, ) { return true; } } false }) { *ty = parse_quote!( ::leptos_router::any_nested_route::AnyNestedRoute ); } } } } #[cfg(not(feature = "__internal_erase_components"))] { let _ = ret; } } // implemented manually because Vec::drain_filter is nightly only // follows std recommended parallel pub fn drain_filter<T>( vec: &mut Vec<T>, mut some_predicate: impl FnMut(&mut T) -> bool, ) { let mut i = 0; while i < vec.len() { if some_predicate(&mut vec[i]) { _ = vec.remove(i); } else { i += 1; } } } pub fn convert_from_snake_case(name: &Ident) -> Ident { let name_str = name.to_string(); if !name_str.is_case(Snake) { name.clone() } else { Ident::new(&name_str.to_case(Pascal), name.span()) } } impl ToTokens for Model { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { is_transparent, is_lazy, island, docs, unknown_attrs, vis, name, props, body, ret, } = self; let is_island = island.is_some(); let no_props = props.is_empty(); // check for components that end ; if !is_transparent { let ends_semi = body.block.stmts.iter().last().and_then(|stmt| match stmt { Stmt::Item(Item::Macro(mac)) => mac.semi_token.as_ref(), _ => None, }); if let Some(semi) = ends_semi { proc_macro_error2::emit_error!( semi.span(), "A component that ends with a `view!` macro followed by a \ semicolon will return (), an empty view. This is usually \ an accident, not intentional, so we prevent it. If you’d \ like to return (), you can do it it explicitly by \ returning () as the last item from the component." ); } } //body.sig.ident = format_ident!("__{}", body.sig.ident); #[allow(clippy::redundant_clone)] // false positive let body_name = body.sig.ident.clone(); let (impl_generics, generics, where_clause) = body.sig.generics.split_for_impl(); let props_name = format_ident!("{name}Props"); let props_builder_name = format_ident!("{name}PropsBuilder"); let props_serialized_name = format_ident!("{name}PropsSerialized"); #[cfg(feature = "tracing")] let trace_name = format!("<{name} />"); let is_island_with_children = is_island && props.iter().any(|prop| prop.name.ident == "children"); let is_island_with_other_props = is_island && ((is_island_with_children && props.len() > 1) || (!is_island_with_children && !props.is_empty())); let prop_builder_fields = prop_builder_fields(vis, props, is_island_with_other_props); let props_serializer = if is_island_with_other_props { let fields = prop_serializer_fields(vis, props); quote! { #[derive(::leptos::serde::Deserialize)] #vis struct #props_serialized_name { #fields } } } else { quote! {} }; let prop_names = prop_names(props); let builder_name_doc = LitStr::new( &format!(" Props for the [`{name}`] component."), name.span(), ); let component_fn_prop_docs = generate_component_fn_prop_docs(props); let docs_and_prop_docs = if component_fn_prop_docs.is_empty() { // Avoid generating an empty doc line in case the component has no doc and no props. quote! { #docs } } else { quote! { #docs #[doc = ""] #component_fn_prop_docs } }; let ( tracing_instrument_attr, tracing_span_expr, tracing_guard_expr, tracing_props_expr, ) = { #[cfg(feature = "tracing")] { /* TODO for 0.8: fix this * * The problem is that cargo now warns about an expected "tracing" cfg if * you don't have a "tracing" feature in your actual crate * * However, until https://github.com/tokio-rs/tracing/pull/1819 is merged * (?), you can't provide an alternate path for `tracing` (for example, * ::leptos::tracing), which means that if you're going to use the macro * you *must* have `tracing` in your Cargo.toml. * * Including the feature-check here causes cargo warnings on * previously-working projects. * * Removing the feature-check here breaks any project that uses leptos with * the tracing feature turned on, but without a tracing dependency in its * Cargo.toml. * / */ let instrument = cfg!(feature = "trace-components").then(|| quote! { #[cfg_attr( feature = "tracing", ::leptos::tracing::instrument(level = "info", name = #trace_name, skip_all) )] }); ( quote! { #[allow(clippy::let_with_type_underscore)] #instrument }, quote! { let __span = ::leptos::tracing::Span::current(); }, quote! { #[cfg(debug_assertions)] let _guard = __span.entered(); }, if no_props || !cfg!(feature = "trace-component-props") { quote!() } else { quote! { ::leptos::leptos_dom::tracing_props![#prop_names]; } }, ) } #[cfg(not(feature = "tracing"))] { (quote!(), quote!(), quote!(), quote!()) } }; let component_id = name.to_string(); let hydrate_fn_name = is_island.then(|| { use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); island.hash(&mut hasher); let caller = hasher.finish() as usize; Ident::new(&format!("{component_id}_{caller:?}"), name.span()) }); let island_serialize_props = if is_island_with_other_props { quote! { let _leptos_ser_props = ::leptos::serde_json::to_string(&props).expect("couldn't serialize island props"); } } else { quote! {} }; let island_serialized_props = if is_island_with_other_props { quote! { .with_props( _leptos_ser_props) } } else { quote! {} }; let body_name = unmodified_fn_name_from_fn_name(&body_name); let body_expr = if is_island { quote! { ::leptos::reactive::owner::Owner::new().with(|| { ::leptos::reactive::owner::Owner::with_hydration(move || { ::leptos::tachys::reactive_graph::OwnedView::new({ #body_name(#prop_names) }) }) }) } } else { quote! { #body_name(#prop_names) } }; let component = if *is_transparent { body_expr } else if cfg!(feature = "__internal_erase_components") { quote! { ::leptos::prelude::IntoMaybeErased::into_maybe_erased( ::leptos::reactive::graph::untrack_with_diagnostics( move || { #tracing_guard_expr #tracing_props_expr #body_expr } ) ) } } else { quote! { ::leptos::reactive::graph::untrack_with_diagnostics( move || { #tracing_guard_expr #tracing_props_expr #body_expr } ) } }; // add island wrapper if island let component = if is_island { let hydrate_fn_name = hydrate_fn_name.as_ref().unwrap(); quote! { ::leptos::tachys::html::islands::Island::new( stringify!(#hydrate_fn_name), #component ) #island_serialized_props } } else { component }; let props_arg = if no_props { quote! {} } else { quote! { props: #props_name #generics } }; let destructure_props = if no_props { quote! {} } else { let wrapped_children = if is_island_with_children { quote! { use leptos::tachys::view::any_view::IntoAny; let children = Box::new(|| { let sc = ::leptos::reactive::owner::Owner::current_shared_context().unwrap(); let prev = sc.get_is_hydrating(); let owner = ::leptos::reactive::owner::Owner::new(); let value = owner.clone().with(|| { ::leptos::reactive::owner::Owner::with_no_hydration(move || { ::leptos::tachys::reactive_graph::OwnedView::new({ ::leptos::tachys::html::islands::IslandChildren::new_with_on_hydrate( children(), { let owner = owner.clone(); move || { owner.set() } } ) }).into_any() }) }); sc.set_is_hydrating(prev); value }); } } else { quote! {} }; quote! { #island_serialize_props let #props_name { #prop_names } = props; #wrapped_children } }; let body = quote! { #destructure_props #tracing_span_expr #component }; let binding = if is_island { let island_props = if is_island_with_children || is_island_with_other_props { let (destructure, prop_builders, optional_props) = if is_island_with_other_props { let prop_names = props .iter() .filter_map(|prop| { if prop.name.ident == "children" { None } else { let name = &prop.name.ident; Some(quote! { #name, }) } }) .collect::<TokenStream>(); let destructure = quote! { let #props_serialized_name { #prop_names } = props; }; let prop_builders = props .iter() .filter_map(|prop| { if prop.name.ident == "children" || prop.prop_opts.optional { None } else { let name = &prop.name.ident; Some(quote! { .#name(#name) }) } }) .collect::<TokenStream>(); let optional_props = props .iter() .filter_map(|prop| { if prop.name.ident == "children" || !prop.prop_opts.optional { None } else { let name = &prop.name.ident; Some(quote! { if let Some(#name) = #name { props.#name = Some(#name) } }) } }) .collect::<TokenStream>(); (destructure, prop_builders, optional_props) } else { (quote! {}, quote! {}, quote! {}) }; let children = if is_island_with_children { quote! { .children({ let owner = leptos::reactive::owner::Owner::current(); Box::new(move || { use leptos::tachys::view::any_view::IntoAny; ::leptos::tachys::html::islands::IslandChildren::new_with_on_hydrate( (), { let owner = owner.clone(); move || { if let Some(owner) = &owner { owner.set() } } } ).into_any()})}) } } else { quote! {} }; quote! {{ #destructure let mut props = #props_name::builder() #prop_builders #children .build(); #optional_props props }} } else { quote! {} }; let deserialize_island_props = if is_island_with_other_props { quote! { let props = el.dataset().get(::leptos::wasm_bindgen::intern("props")) .and_then(|data| ::leptos::serde_json::from_str::<#props_serialized_name>(&data).ok()) .expect("could not deserialize props"); } } else { quote! {} }; let hydrate_fn_name = hydrate_fn_name.as_ref().unwrap(); let hydrate_fn_inner = quote! { #deserialize_island_props let island = #name(#island_props); let state = island.hydrate_from_position::<true>(&el, ::leptos::tachys::view::Position::Current); // TODO better cleanup std::mem::forget(state); }; if *is_lazy { let outer_name = Ident::new(&format!("{name}_loader"), name.span()); quote! { #[::leptos::prelude::lazy] #[allow(non_snake_case)] fn #outer_name (el: ::leptos::web_sys::HtmlElement) { #hydrate_fn_inner } #[::leptos::wasm_bindgen::prelude::wasm_bindgen( wasm_bindgen = ::leptos::wasm_bindgen, wasm_bindgen_futures = ::leptos::__reexports::wasm_bindgen_futures )] #[allow(non_snake_case)] pub async fn #hydrate_fn_name(el: ::leptos::web_sys::HtmlElement) { #outer_name(el).await } } } else { quote! { #[::leptos::wasm_bindgen::prelude::wasm_bindgen(wasm_bindgen = ::leptos::wasm_bindgen)] #[allow(non_snake_case)] pub fn #hydrate_fn_name(el: ::leptos::web_sys::HtmlElement) { #hydrate_fn_inner } } } } else { quote! {} }; let props_derive_serialize = if is_island_with_other_props { quote! { , ::leptos::serde::Serialize } } else { quote! {} }; let output = quote! { #[doc = #builder_name_doc] #[doc = ""] #docs_and_prop_docs #[derive(::leptos::typed_builder_macro::TypedBuilder #props_derive_serialize)] //#[builder(doc)] #[builder(crate_module_path=::leptos::typed_builder)] #[allow(non_snake_case)] #vis struct #props_name #impl_generics #where_clause { #prop_builder_fields } #props_serializer #[allow(missing_docs)] #binding impl #impl_generics ::leptos::component::Props for #props_name #generics #where_clause { type Builder = #props_builder_name #generics; fn builder() -> Self::Builder { #props_name::builder() } } // TODO restore dyn attrs /*impl #impl_generics ::leptos::DynAttrs for #props_name #generics #where_clause { fn dyn_attrs(mut self, v: Vec<(&'static str, ::leptos::Attribute)>) -> Self { #dyn_attrs_props self } } */ #unknown_attrs #docs_and_prop_docs #[allow(non_snake_case, clippy::too_many_arguments)] #[allow(clippy::needless_lifetimes)] #tracing_instrument_attr #vis fn #name #impl_generics ( #props_arg ) #ret #where_clause { #body } }; tokens.append_all(output) } } impl Model { #[allow(clippy::wrong_self_convention)] pub fn is_transparent(mut self, is_transparent: bool) -> Self { self.is_transparent = is_transparent; self } #[allow(clippy::wrong_self_convention)] pub fn is_lazy(mut self, is_lazy: bool) -> Self { self.is_lazy = is_lazy; self } #[allow(clippy::wrong_self_convention)] pub fn with_island(mut self, island: Option<String>) -> Self { self.island = island; self } } /// A model that is more lenient in case of a syntax error in the function body, /// but does not actually implement the behavior of the real model. This is /// used to improve IDEs and rust-analyzer's auto-completion behavior in case /// of a syntax error. pub struct DummyModel { pub attrs: Vec<Attribute>, pub vis: Visibility, pub sig: Signature, pub body: TokenStream, } impl Parse for DummyModel { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { let mut attrs = input.call(Attribute::parse_outer)?; // Drop unknown attributes like #[deprecated] drain_filter(&mut attrs, |attr| { let path = attr.path(); !(path.is_ident("doc") || path.is_ident("allow") || path.is_ident("expect") || path.is_ident("warn") || path.is_ident("deny") || path.is_ident("forbid")) }); let vis: Visibility = input.parse()?; let mut sig: Signature = input.parse()?; maybe_modify_return_type(&mut sig.output); // The body is left untouched, so it will not cause an error // even if the syntax is invalid. let body: TokenStream = input.parse()?; Ok(Self { attrs, vis, sig, body, }) } } impl ToTokens for DummyModel { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { attrs, vis, sig, body, } = self; // Strip attributes like documentation comments and #[prop] // from the signature, so as to not confuse the user with incorrect // error messages. let sig = { let mut sig = sig.clone(); sig.inputs.iter_mut().for_each(|arg| { if let FnArg::Typed(ty) = arg { ty.attrs.retain(|attr| match &attr.meta { Meta::List(list) => list .path .segments .first() .map(|n| n.ident != "prop") .unwrap_or(true), Meta::NameValue(name_value) => name_value .path .segments .first() .map(|n| n.ident != "doc") .unwrap_or(true), _ => true, }); } }); sig }; let output = quote! { #(#attrs)* #vis #sig #body }; tokens.append_all(output) } } struct Prop { docs: Docs, prop_opts: PropOpt, name: PatIdent, ty: Type, } impl Prop { fn new(arg: FnArg) -> Self { let typed = if let FnArg::Typed(ty) = arg { ty } else { abort!(arg, "receiver not allowed in `fn`"); }; let prop_opts = PropOpt::from_attributes(&typed.attrs).unwrap_or_else(|e| { // TODO: replace with `.unwrap_or_abort()` once https://gitlab.com/CreepySkeleton/proc-macro-error/-/issues/17 is fixed abort!(e.span(), e.to_string()); }); let name = match *typed.pat { Pat::Ident(i) => { if let Some(name) = &prop_opts.name { PatIdent { attrs: vec![], by_ref: None, mutability: None, ident: Ident::new(name, i.span()), subpat: None, } } else { i } } Pat::Struct(_) | Pat::Tuple(_) | Pat::TupleStruct(_) => { if let Some(name) = &prop_opts.name { PatIdent { attrs: vec![], by_ref: None, mutability: None, ident: Ident::new(name, typed.pat.span()), subpat: None, } } else { abort!( typed.pat, "destructured props must be given a name e.g. \ #[prop(name = \"data\")]" ); } } _ => { abort!( typed.pat, "only `prop: bool` style types are allowed within the \ `#[component]` macro" ); } }; Self { docs: Docs::new(&typed.attrs), prop_opts, name, ty: *typed.ty, } } } #[derive(Clone)] pub struct Docs(Vec<(String, Span)>); impl ToTokens for Docs { fn to_tokens(&self, tokens: &mut TokenStream) { let s = self .0 .iter() .map(|(doc, span)| quote_spanned!(*span=> #[doc = #doc])) .collect::<TokenStream>(); tokens.append_all(s); } } impl Docs { pub fn new(attrs: &[Attribute]) -> Self { #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum ViewCodeFenceState { Outside, Rust, Rsx, } let mut quotes = "```".to_string(); let mut quote_ws = "".to_string(); let mut view_code_fence_state = ViewCodeFenceState::Outside; // todo fix docs stuff const RSX_START: &str = "# ::leptos::view! {"; const RSX_END: &str = "# };"; // Separated out of chain to allow rustfmt to work let map = |(doc, span): (String, Span)| { doc.split('\n') .map(str::trim_end) .flat_map(|doc| { let trimmed_doc = doc.trim_start(); let leading_ws = &doc[..doc.len() - trimmed_doc.len()]; let trimmed_doc = trimmed_doc.trim_end(); match view_code_fence_state { ViewCodeFenceState::Outside if trimmed_doc.starts_with("```") && trimmed_doc .trim_start_matches('`') .starts_with("view") => { view_code_fence_state = ViewCodeFenceState::Rust; let view = trimmed_doc.find('v').unwrap(); trimmed_doc[..view].clone_into(&mut quotes); leading_ws.clone_into(&mut quote_ws); let rust_options = &trimmed_doc [view + "view".len()..] .trim_start(); vec![ format!("{leading_ws}{quotes}{rust_options}"), format!("{leading_ws}"), ] } ViewCodeFenceState::Rust if trimmed_doc == quotes => { view_code_fence_state = ViewCodeFenceState::Outside; vec![format!("{leading_ws}"), doc.to_owned()] } ViewCodeFenceState::Rust if trimmed_doc.starts_with('<') => { view_code_fence_state = ViewCodeFenceState::Rsx; vec![ format!("{leading_ws}{RSX_START}"), doc.to_owned(), ] } ViewCodeFenceState::Rsx if trimmed_doc == quotes => { view_code_fence_state = ViewCodeFenceState::Outside; vec![ format!("{leading_ws}{RSX_END}"), doc.to_owned(), ] } _ => vec![doc.to_string()], } }) .map(|l| (l, span)) .collect_vec() }; let mut attrs = attrs .iter() .filter_map(|attr| { let Meta::NameValue(attr) = &attr.meta else { return None; }; if !attr.path.is_ident("doc") { return None; } let Some(val) = value_to_string(&attr.value) else { abort!( attr, "expected string literal in value of doc comment" ); }; Some((val, attr.path.span())) }) .flat_map(map) .collect_vec(); if view_code_fence_state != ViewCodeFenceState::Outside { if view_code_fence_state == ViewCodeFenceState::Rust { attrs.push((quote_ws.clone(), Span::call_site())) } else {
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
true
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/view/slot_helper.rs
leptos_macro/src/view/slot_helper.rs
use super::{ component_builder::maybe_optimised_component_children, convert_to_snake_case, full_path_from_tag_name, }; use crate::view::{fragment_to_tokens, utils::filter_prefixed_attrs, TagType}; use proc_macro2::{Ident, TokenStream, TokenTree}; use quote::{quote, quote_spanned}; use rstml::node::{CustomNode, KeyedAttribute, NodeAttribute, NodeElement}; use std::collections::HashMap; use syn::spanned::Spanned; pub(crate) fn slot_to_tokens( node: &mut NodeElement<impl CustomNode>, slot: &KeyedAttribute, parent_slots: Option<&mut HashMap<String, Vec<TokenStream>>>, global_class: Option<&TokenTree>, disable_inert_html: bool, ) { let name = slot.key.to_string(); let name = name.trim(); let name = convert_to_snake_case(if name.starts_with("slot:") { name.replacen("slot:", "", 1) } else { node.name().to_string() }); let component_path = full_path_from_tag_name(node.name()); let Some(parent_slots) = parent_slots else { proc_macro_error2::emit_error!( node.name().span(), "slots cannot be used inside HTML elements" ); return; }; let attrs = node .attributes() .iter() .filter_map(|node| { if let NodeAttribute::Attribute(node) = node { if is_slot(node) { None } else { Some(node) } } else { None } }) .cloned() .collect::<Vec<_>>(); let props = attrs .iter() .filter(|attr| { !attr.key.to_string().starts_with("let:") && !attr.key.to_string().starts_with("clone:") && !attr.key.to_string().starts_with("attr:") }) .map(|attr| { let name = &attr.key; let value = attr .value() .map(|v| { quote! { #v } }) .unwrap_or_else(|| quote! { #name }); quote! { .#name(#[allow(unused_braces)] { #value }) } }); let items_to_bind = filter_prefixed_attrs(attrs.iter(), "let:") .into_iter() .map(|ident| quote! { #ident }) .collect::<Vec<_>>(); let items_to_clone = filter_prefixed_attrs(attrs.iter(), "clone:"); let dyn_attrs = attrs .iter() .filter(|attr| attr.key.to_string().starts_with("attr:")) .filter_map(|attr| { let name = &attr.key.to_string(); let name = name.strip_prefix("attr:"); let value = attr.value().map(|v| { quote! { #v } })?; Some(quote! { (#name, #value) }) }) .collect::<Vec<_>>(); let dyn_attrs = if dyn_attrs.is_empty() { quote! {} } else { quote! { .dyn_attrs(vec![#(#dyn_attrs),*]) } }; let mut slots = HashMap::new(); let children = if node.children.is_empty() { quote! {} } else if let Some(children) = maybe_optimised_component_children( &node.children, &items_to_bind, &items_to_clone, ) { children } else { let children = fragment_to_tokens( &mut node.children, TagType::Unknown, Some(&mut slots), global_class, None, disable_inert_html, ); // TODO view markers for hot-reloading /* cfg_if::cfg_if! { if #[cfg(debug_assertions)] { let marker = format!("<{component_name}/>-children"); // For some reason spanning for `.children` breaks, unless `#view_marker` // is also covered by `children.span()`. let view_marker = quote_spanned!(children.span()=> .with_view_marker(#marker)); } else { let view_marker = quote! {}; } } */ let view_marker = quote! {}; if let Some(children) = children { let bindables = items_to_bind.iter().map(|ident| quote! { #ident, }); let clonables = items_to_clone.iter().map(|ident| { quote_spanned! {ident.span()=> let #ident = ::core::clone::Clone::clone(&#ident); } }); if bindables.len() > 0 { quote_spanned! {children.span()=> .children({ #(#clonables)* move |#(#bindables)*| #children #view_marker }) } } else { quote_spanned! {children.span()=> .children({ #(#clonables)* ::leptos::children::ToChildren::to_children(move || #children #view_marker) }) } } } else { quote! {} } }; let slots = slots.drain().map(|(slot, mut values)| { let span = values .last() .expect("List of slots must not be empty") .span(); let slot = Ident::new(&slot, span); let value = if values.len() > 1 { quote! { ::std::vec![ #(#values)* ] } } else { values.remove(0) }; quote! { .#slot(#value) } }); let build = quote_spanned! {node.name().span()=> .build() }; let slot = quote_spanned! {node.span()=> { let slot = #component_path::builder() #(#props)* #(#slots)* #children #build #dyn_attrs; #[allow(unreachable_code, clippy::useless_conversion)] slot.into() }, }; // We need to move "allow" out of "quote_spanned" because it breaks hovering in rust-analyzer let slot = quote!(#[allow(unused_braces)] #slot); parent_slots .entry(name) .and_modify(|entry| entry.push(slot.clone())) .or_insert(vec![slot]); } pub(crate) fn is_slot(node: &KeyedAttribute) -> bool { let key = node.key.to_string(); let key = key.trim(); key == "slot" || key.starts_with("slot:") } pub(crate) fn get_slot( node: &NodeElement<impl CustomNode>, ) -> Option<&KeyedAttribute> { node.attributes().iter().find_map(|node| { if let NodeAttribute::Attribute(node) = node { if is_slot(node) { Some(node) } else { None } } else { None } }) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/view/component_builder.rs
leptos_macro/src/view/component_builder.rs
use super::{ fragment_to_tokens, utils::is_nostrip_optional_and_update_key, TagType, }; use crate::view::{ attribute_absolute, text_to_tokens, utils::filter_prefixed_attrs, }; use proc_macro2::{Ident, TokenStream, TokenTree}; use quote::{format_ident, quote, quote_spanned}; use rstml::node::{ CustomNode, KeyedAttributeValue, Node, NodeAttribute, NodeBlock, NodeElement, NodeName, }; use std::collections::HashMap; use syn::{ spanned::Spanned, Expr, ExprPath, ExprRange, Item, RangeLimits, Stmt, }; pub(crate) fn component_to_tokens( node: &mut NodeElement<impl CustomNode>, global_class: Option<&TokenTree>, disable_inert_html: bool, ) -> TokenStream { #[allow(unused)] // TODO this is used by hot-reloading #[cfg(debug_assertions)] let component_name = super::ident_from_tag_name(node.name()); // an attribute that contains {..} can be used to split props from attributes // anything before it is a prop, unless it uses the special attribute syntaxes // (attr:, style:, on:, prop:, etc.) // anything after it is a plain HTML attribute to be spread onto the prop let spread_marker = node .attributes() .iter() .position(|node| match node { NodeAttribute::Block(NodeBlock::ValidBlock(block)) => { matches!( block.stmts.first(), Some(Stmt::Expr( Expr::Range(ExprRange { start: None, limits: RangeLimits::HalfOpen(_), end: None, .. }), _, )) ) } _ => false, }) .unwrap_or_else(|| node.attributes().len()); // Initially using uncloned mutable reference, as the node.key might be mutated during prop extraction (for nostrip:) let mut attrs = node .attributes_mut() .iter_mut() .filter_map(|node| { if let NodeAttribute::Attribute(node) = node { Some(node) } else { None } }) .collect::<Vec<_>>(); let mut required_props = vec![]; let mut optional_props = vec![]; for (_, attr) in attrs.iter_mut().enumerate().filter(|(idx, attr)| { idx < &spread_marker && { let attr_key = attr.key.to_string(); !is_attr_let(&attr.key) && !attr_key.starts_with("clone:") && !attr_key.starts_with("class:") && !attr_key.starts_with("style:") && !attr_key.starts_with("attr:") && !attr_key.starts_with("prop:") && !attr_key.starts_with("on:") && !attr_key.starts_with("use:") } }) { let optional = is_nostrip_optional_and_update_key(&mut attr.key); let name = &attr.key; let value = attr .value() .map(|v| { quote! { #v } }) .unwrap_or_else(|| quote! { #name }); if optional { optional_props.push(quote! { props.#name = { #value }.map(::leptos::prelude::IntoReactiveValue::into_reactive_value); }) } else { required_props.push(quote! { .#name(#[allow(unused_braces)] { #value }) }) } } // Drop the mutable reference to the node, go to an owned clone: let attrs = attrs.into_iter().map(|a| a.clone()).collect::<Vec<_>>(); let items_to_bind = attrs .iter() .filter_map(|attr| { if !is_attr_let(&attr.key) { return None; } let KeyedAttributeValue::Binding(binding) = &attr.possible_value else { if let Some(ident) = attr.key.to_string().strip_prefix("let:") { let span = match &attr.key { NodeName::Punctuated(path) => path[1].span(), _ => unreachable!(), }; let ident1 = format_ident!("{ident}", span = span); return Some(quote_spanned! { span => #ident1 }); } else { return None; } }; let inputs = &binding.inputs; Some(quote! { #inputs }) }) .collect::<Vec<_>>(); let items_to_clone = filter_prefixed_attrs(attrs.iter(), "clone:"); // include all attribute that are either // 1) blocks ({..attrs} or {attrs}), // 2) start with attr: and can be used as actual attributes, or // 3) the custom attribute types (on:, class:, style:, prop:, use:) let spreads = node .attributes() .iter() .enumerate() .filter_map(|(idx, attr)| { if idx == spread_marker { return None; } if let NodeAttribute::Block(block) = attr { let dotted = if let NodeBlock::ValidBlock(block) = block { match block.stmts.first() { Some(Stmt::Expr( Expr::Range(ExprRange { start: None, limits: RangeLimits::HalfOpen(_), end: Some(end), .. }), _, )) => Some(quote! { #end }), _ => None, } } else { None }; Some(dotted.unwrap_or_else(|| { quote! { #node } })) } else if let NodeAttribute::Attribute(node) = attr { attribute_absolute(node, idx >= spread_marker) } else { None } }) .collect::<Vec<_>>(); let spreads = (!(spreads.is_empty())).then(|| { if cfg!(feature = "__internal_erase_components") { quote! { .add_any_attr({ vec![#(::leptos::attr::any_attribute::IntoAnyAttribute::into_any_attr(#spreads),)*] }) } } else { quote! { .add_any_attr((#(#spreads,)*)) } } }); /*let directives = attrs .clone() .filter_map(|attr| { attr.key .to_string() .strip_prefix("use:") .map(|ident| directive_call_from_attribute_node(attr, ident)) }) .collect::<Vec<_>>(); let events_and_directives = events.into_iter().chain(directives).collect::<Vec<_>>(); */ let mut slots = HashMap::new(); let children = if node.children.is_empty() { quote! {} } else if let Some(children) = maybe_optimised_component_children( &node.children, &items_to_bind, &items_to_clone, ) { children } else { let children = fragment_to_tokens( &mut node.children, TagType::Unknown, Some(&mut slots), global_class, None, disable_inert_html, ); // TODO view marker for hot-reloading /* cfg_if::cfg_if! { if #[cfg(debug_assertions)] { let marker = format!("<{component_name}/>-children"); // For some reason spanning for `.children` breaks, unless `#view_marker` // is also covered by `children.span()`. let view_marker = quote_spanned!(children.span()=> .with_view_marker(#marker)); } else { let view_marker = quote! {}; } } */ if let Some(children) = children { let bindables = items_to_bind.iter().map(|ident| quote! { #ident, }); let clonables = items_to_clone_to_tokens(&items_to_clone); if bindables.len() > 0 { quote_spanned! {children.span()=> .children({ #(#clonables)* move |#(#bindables)*| #children }) } } else { quote_spanned! {children.span()=> .children({ #(#clonables)* ::leptos::children::ToChildren::to_children(move || #children) }) } } } else { quote! {} } }; let slots = slots.drain().map(|(slot, mut values)| { let span = values .last() .expect("List of slots must not be empty") .span(); let slot = Ident::new(&slot, span); let value = if values.len() > 1 { quote_spanned! {span=> ::std::vec![ #(#values)* ] } } else { values.remove(0) }; quote! { .#slot(#value) } }); let generics = &node.open_tag.generics; let generics = if generics.lt_token.is_some() { quote! { ::#generics } } else { quote! {} }; let name = node.name(); #[allow(unused_mut)] // used in debug let mut component = quote! { { #[allow(unreachable_code)] #[allow(unused_mut)] #[allow(clippy::let_and_return)] ::leptos::component::component_view( #[allow(clippy::needless_borrows_for_generic_args)] &#name, { let mut props = ::leptos::component::component_props_builder(&#name #generics) #(#required_props)* #(#slots)* #children .build(); #(#optional_props)* props } ) #spreads } }; // (Temporarily?) removed // See note on the function itself below. /* #[cfg(debug_assertions)] IdeTagHelper::add_component_completion(&mut component, node); */ component } fn is_attr_let(key: &NodeName) -> bool { if key.to_string().starts_with("let:") { true } else if let NodeName::Path(ExprPath { path, .. }) = key { path.segments.len() == 1 && path.segments[0].ident == "let" } else { false } } pub fn items_to_clone_to_tokens( items_to_clone: &[Ident], ) -> impl Iterator<Item = TokenStream> + '_ { items_to_clone.iter().map(|ident| { let ident_ref = quote_spanned!(ident.span()=> &#ident); quote! { let #ident = ::core::clone::Clone::clone(#ident_ref); } }) } /// By default all children are placed in an outer closure || #children. /// This is to work with all the variants of the leptos::children::ToChildren::to_children trait. /// Strings are optimised to be passed without the wrapping closure, providing significant compile time and binary size improvements. pub fn maybe_optimised_component_children( children: &[Node<impl CustomNode>], items_to_bind: &[TokenStream], items_to_clone: &[Ident], ) -> Option<TokenStream> { // If there are bindables will have to be in a closure: if !items_to_bind.is_empty() { return None; } // Filter out comments: let mut children_iter = children .iter() .filter(|child| !matches!(child, Node::Comment(_))); let children = if let Some(child) = children_iter.next() { // If more than one child after filtering out comments, don't think we can optimise: if children_iter.next().is_some() { return None; } match child { Node::Text(text) => text_to_tokens(&text.value), Node::RawText(raw) => { let text = raw.to_string_best(); let text = syn::LitStr::new(&text, raw.span()); text_to_tokens(&text) } // Specifically allow std macros that produce strings: Node::Block(NodeBlock::ValidBlock(block)) => { fn is_supported(mac: &syn::Macro) -> bool { for string_macro in ["format", "include_str"] { if mac.path.is_ident(string_macro) { return true; } } false } if block.stmts.len() > 1 { return None; } else if let Some(stmt) = block.stmts.first() { match stmt { Stmt::Macro(mac) => { // eprintln!("Macro: {:?}", mac.mac.path); if is_supported(&mac.mac) { quote! { #block } } else { return None; } } Stmt::Item(Item::Macro(mac)) => { // eprintln!("Item Macro: {:?}", mac.mac.path); if is_supported(&mac.mac) { quote! { #block } } else { return None; } } Stmt::Expr(Expr::Macro(mac), _) => { // eprintln!("Expr Macro: {:?}", mac.mac.path); if is_supported(&mac.mac) { quote! { #block } } else { return None; } } _ => return None, } } else { return Some(quote! {}); } } _ => return None, } } else { return None; }; // // Debug check to see how many use this optimisation: // static COUNT: std::sync::atomic::AtomicUsize = // std::sync::atomic::AtomicUsize::new(0); // COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); // eprintln!( // "Optimised children: {}", // COUNT.load(std::sync::atomic::Ordering::Relaxed) // ); let clonables = items_to_clone_to_tokens(items_to_clone); Some(quote_spanned! {children.span()=> .children({ #(#clonables)* ::leptos::children::ToChildren::to_children(::leptos::children::ChildrenOptContainer(#children)) }) }) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/view/utils.rs
leptos_macro/src/view/utils.rs
use proc_macro2::Ident; use quote::format_ident; use rstml::node::{KeyedAttribute, NodeName}; use syn::{spanned::Spanned, ExprPath}; pub fn filter_prefixed_attrs<'a, A>(attrs: A, prefix: &str) -> Vec<Ident> where A: IntoIterator<Item = &'a KeyedAttribute> + Clone, { attrs .into_iter() .filter_map(|attr| { attr.key .to_string() .strip_prefix(prefix) .map(|ident| format_ident!("{ident}", span = attr.key.span())) }) .collect() } /// Handle nostrip: prefix: /// if there strip from the name, and return true to indicate that /// the prop should be an Option<T> and shouldn't be called on the builder if None, /// if Some(T) then T supplied to the builder. pub fn is_nostrip_optional_and_update_key(key: &mut NodeName) -> bool { let maybe_cleaned_name_and_span = if let NodeName::Punctuated(punct) = &key { if punct.len() == 2 { if let Some(cleaned_name) = key.to_string().strip_prefix("nostrip:") { punct .get(1) .map(|segment| (cleaned_name.to_string(), segment.span())) } else { None } } else { None } } else { None }; if let Some((cleaned_name, span)) = maybe_cleaned_name_and_span { *key = NodeName::Path(ExprPath { attrs: vec![], qself: None, path: format_ident!("{}", cleaned_name, span = span).into(), }); true } else { false } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/src/view/mod.rs
leptos_macro/src/view/mod.rs
mod component_builder; mod slot_helper; mod utils; use self::{ component_builder::component_to_tokens, slot_helper::{get_slot, slot_to_tokens}, }; use convert_case::{ Case::{Snake, UpperCamel}, Casing, }; use leptos_hot_reload::parsing::{is_component_node, value_to_string}; use proc_macro2::{Ident, Span, TokenStream, TokenTree}; use proc_macro_error2::abort; use quote::{format_ident, quote, quote_spanned, ToTokens}; use rstml::node::{ CustomNode, KVAttributeValue, KeyedAttribute, Node, NodeAttribute, NodeBlock, NodeElement, NodeName, NodeNameFragment, }; use std::{ cmp::Ordering, collections::{HashMap, HashSet, VecDeque}, }; use syn::{ punctuated::Pair::{End, Punctuated}, spanned::Spanned, Expr::{self, Tuple}, ExprArray, ExprLit, ExprPath, ExprRange, Lit, LitStr, RangeLimits, Stmt, }; #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum TagType { Unknown, Html, Svg, Math, } pub fn render_view( nodes: &mut [Node], global_class: Option<&TokenTree>, view_marker: Option<String>, disable_inert_html: bool, ) -> Option<TokenStream> { let disable_inert_html = disable_inert_html || global_class.is_some(); let (base, should_add_view) = match nodes.len() { 0 => { let span = Span::call_site(); ( Some(quote_spanned! { span => () }), false, ) } 1 => ( node_to_tokens( &mut nodes[0], TagType::Unknown, None, global_class, view_marker.as_deref(), true, disable_inert_html, ), // only add View wrapper and view marker to a regular HTML // element or component, not to a <{..} /> attribute list match &nodes[0] { Node::Element(node) => !is_spread_marker(node), _ => false, }, ), _ => ( fragment_to_tokens( nodes, TagType::Unknown, None, global_class, view_marker.as_deref(), disable_inert_html, ), true, ), }; base.map(|view| { if !should_add_view { view } else if let Some(vm) = view_marker { quote! { ::leptos::prelude::View::new( #view ) .with_view_marker(#vm) } } else { quote! { ::leptos::prelude::View::new( #view ) } } }) } fn is_inert_element(orig_node: &Node<impl CustomNode>) -> bool { // do not use this if the top-level node is not an Element, // or if it's an element with no children and no attrs match orig_node { Node::Element(el) => { if el.attributes().is_empty() && el.children.is_empty() { return false; } // also doesn't work if the top-level element is a MathML element let el_name = el.name().to_string(); if is_math_ml_element(&el_name) { return false; } } _ => return false, } // otherwise, walk over all the nodes to make sure everything is inert let mut nodes = VecDeque::from([orig_node]); while let Some(current_element) = nodes.pop_front() { match current_element { Node::Text(_) | Node::RawText(_) => {} Node::Element(node) => { if is_component_node(node) { return false; } if is_spread_marker(node) { return false; } match node.name() { NodeName::Block(_) => return false, _ => { // check all attributes for attr in node.attributes() { match attr { NodeAttribute::Block(_) => return false, NodeAttribute::Attribute(attr) => { let static_key = !matches!(attr.key, NodeName::Block(_)); let static_value = match attr .possible_value .to_value() { None => true, Some(value) => { matches!(&value.value, KVAttributeValue::Expr(expr) if { if let Expr::Lit(lit) = expr { let key = attr.key.to_string(); if key.starts_with("style:") || key.starts_with("prop:") || key.starts_with("on:") || key.starts_with("use:") || key.starts_with("bind") { false } else { matches!(&lit.lit, Lit::Str(_)) } } else { false } }) } }; if !static_key || !static_value { return false; } } } } // check all children nodes.extend(&node.children); } } } _ => return false, } } true } enum Item<'a, T> { Node(&'a Node<T>, bool), ClosingTag(String), } enum InertElementBuilder<'a> { GlobalClass { global_class: &'a TokenTree, strs: Vec<GlobalClassItem<'a>>, buffer: String, }, NoGlobalClass { buffer: String, }, } impl ToTokens for InertElementBuilder<'_> { fn to_tokens(&self, tokens: &mut TokenStream) { match self { InertElementBuilder::GlobalClass { strs, .. } => { tokens.extend(quote! { [#(#strs),*].join("") }); } InertElementBuilder::NoGlobalClass { buffer } => { tokens.extend(quote! { #buffer }) } } } } enum GlobalClassItem<'a> { Global(&'a TokenTree), String(String), } impl ToTokens for GlobalClassItem<'_> { fn to_tokens(&self, tokens: &mut TokenStream) { let addl_tokens = match self { GlobalClassItem::Global(v) => v.to_token_stream(), GlobalClassItem::String(v) => v.to_token_stream(), }; tokens.extend(addl_tokens); } } impl<'a> InertElementBuilder<'a> { fn new(global_class: Option<&'a TokenTree>) -> Self { match global_class { None => Self::NoGlobalClass { buffer: String::new(), }, Some(global_class) => Self::GlobalClass { global_class, strs: Vec::new(), buffer: String::new(), }, } } fn push(&mut self, c: char) { match self { InertElementBuilder::GlobalClass { buffer, .. } => buffer.push(c), InertElementBuilder::NoGlobalClass { buffer } => buffer.push(c), } } fn push_str(&mut self, s: &str) { match self { InertElementBuilder::GlobalClass { buffer, .. } => { buffer.push_str(s) } InertElementBuilder::NoGlobalClass { buffer } => buffer.push_str(s), } } fn push_class(&mut self, class: &str) { match self { InertElementBuilder::GlobalClass { global_class, strs, buffer, } => { buffer.push_str(" class=\""); strs.push(GlobalClassItem::String(std::mem::take(buffer))); strs.push(GlobalClassItem::Global(global_class)); buffer.push(' '); buffer.push_str(class); buffer.push('"'); } InertElementBuilder::NoGlobalClass { buffer } => { buffer.push_str(" class=\""); buffer.push_str(class); buffer.push('"'); } } } fn finish(&mut self) { match self { InertElementBuilder::GlobalClass { strs, buffer, .. } => { strs.push(GlobalClassItem::String(std::mem::take(buffer))); } InertElementBuilder::NoGlobalClass { .. } => {} } } } fn inert_element_to_tokens( node: &Node<impl CustomNode>, escape_text: bool, global_class: Option<&TokenTree>, ) -> TokenStream { let mut html = InertElementBuilder::new(global_class); let mut nodes = VecDeque::from([Item::Node(node, escape_text)]); while let Some(current) = nodes.pop_front() { match current { Item::ClosingTag(tag) => { // closing tag html.push_str("</"); html.push_str(&tag); html.push('>'); } Item::Node(current, escape) => { match current { Node::RawText(raw) => { let text = raw.to_string_best(); let text = if escape { html_escape::encode_text(&text) } else { text.into() }; html.push_str(&text); } Node::Text(text) => { let text = text.value_string(); let text = if escape { html_escape::encode_text(&text) } else { text.into() }; html.push_str(&text); } Node::Element(node) => { let self_closing = is_self_closing(node); let el_name = node.name().to_string(); let escape = el_name != "script" && el_name != "style" && el_name != "textarea"; // opening tag html.push('<'); html.push_str(&el_name); for attr in node.attributes() { if let NodeAttribute::Attribute(attr) = attr { let attr_name = attr.key.to_string(); // trim r# from raw identifiers like r#as let attr_name = attr_name.trim_start_matches("r#"); if attr_name != "class" { html.push(' '); html.push_str(attr_name); } if let Some(value) = attr.possible_value.to_value() { if let KVAttributeValue::Expr(Expr::Lit( lit, )) = &value.value { if let Lit::Str(txt) = &lit.lit { let value = txt.value(); let value = html_escape::encode_double_quoted_attribute(&value); if attr_name == "class" { html.push_class(&value); } else { html.push_str("=\""); html.push_str(&value); html.push('"'); } } } }; } } html.push('>'); // render all children if !self_closing { nodes.push_front(Item::ClosingTag(el_name)); let children = node.children.iter().rev(); for child in children { nodes.push_front(Item::Node(child, escape)); } } } _ => {} } } } } html.finish(); quote! { ::leptos::tachys::html::InertElement::new(#html) } } /// # Note /// Should not be used on top level `<svg>` elements. /// Use [`inert_element_to_tokens`] instead. fn inert_svg_element_to_tokens( node: &Node<impl CustomNode>, escape_text: bool, global_class: Option<&TokenTree>, ) -> TokenStream { let mut html = InertElementBuilder::new(global_class); let mut nodes = VecDeque::from([Item::Node(node, escape_text)]); while let Some(current) = nodes.pop_front() { match current { Item::ClosingTag(tag) => { // closing tag html.push_str("</"); html.push_str(&tag); html.push('>'); } Item::Node(current, escape) => { match current { Node::RawText(raw) => { let text = raw.to_string_best(); let text = if escape { html_escape::encode_text(&text) } else { text.into() }; html.push_str(&text); } Node::Text(text) => { let text = text.value_string(); let text = if escape { html_escape::encode_text(&text) } else { text.into() }; html.push_str(&text); } Node::Element(node) => { let self_closing = is_self_closing(node); let el_name = node.name().to_string(); let escape = el_name != "script" && el_name != "style" && el_name != "textarea"; // opening tag html.push('<'); html.push_str(&el_name); for attr in node.attributes() { if let NodeAttribute::Attribute(attr) = attr { let attr_name = attr.key.to_string(); // trim r# from raw identifiers like r#as let attr_name = attr_name.trim_start_matches("r#"); if attr_name != "class" { html.push(' '); html.push_str(attr_name); } if let Some(value) = attr.possible_value.to_value() { if let KVAttributeValue::Expr(Expr::Lit( lit, )) = &value.value { if let Lit::Str(txt) = &lit.lit { let value = txt.value(); let value = html_escape::encode_double_quoted_attribute(&value); if attr_name == "class" { html.push_class(&value); } else { html.push_str("=\""); html.push_str(&value); html.push('"'); } } } }; } } html.push('>'); // render all children if !self_closing { nodes.push_front(Item::ClosingTag(el_name)); let children = node.children.iter().rev(); for child in children { nodes.push_front(Item::Node(child, escape)); } } } _ => {} } } } } html.finish(); quote! { ::leptos::tachys::svg::InertElement::new(#html) } } fn element_children_to_tokens( nodes: &mut [Node<impl CustomNode>], parent_type: TagType, parent_slots: Option<&mut HashMap<String, Vec<TokenStream>>>, global_class: Option<&TokenTree>, view_marker: Option<&str>, disable_inert_html: bool, ) -> Option<TokenStream> { let children = children_to_tokens( nodes, parent_type, parent_slots, global_class, view_marker, false, disable_inert_html, ); if children.is_empty() { None } else if children.len() == 1 { let child = &children[0]; Some(quote! { .child( #[allow(unused_braces)] { #child } ) }) } else if cfg!(feature = "__internal_erase_components") { Some(quote! { .child( ::leptos::tachys::view::iterators::StaticVec::from(vec![#( ::leptos::prelude::IntoMaybeErased::into_maybe_erased(#children) ),*]) ) }) } else if children.len() > 16 { // implementations of various traits used in routing and rendering are implemented for // tuples of sizes 0, 1, 2, 3, ... N. N varies but is > 16. The traits are also implemented // for tuples of tuples, so if we have more than 16 items, we can split them out into // multiple tuples. let chunks = children.chunks(16).map(|children| { quote! { (#(#children),*) } }); Some(quote! { .child( (#(#chunks),*) ) }) } else { Some(quote! { .child( (#(#children),*) ) }) } } fn fragment_to_tokens( nodes: &mut [Node<impl CustomNode>], parent_type: TagType, parent_slots: Option<&mut HashMap<String, Vec<TokenStream>>>, global_class: Option<&TokenTree>, view_marker: Option<&str>, disable_inert_html: bool, ) -> Option<TokenStream> { let children = children_to_tokens( nodes, parent_type, parent_slots, global_class, view_marker, true, disable_inert_html, ); if children.is_empty() { None } else if children.len() == 1 { children.into_iter().next() } else if cfg!(feature = "__internal_erase_components") { Some(quote! { ::leptos::tachys::view::iterators::StaticVec::from(vec![#( ::leptos::prelude::IntoMaybeErased::into_maybe_erased(#children) ),*]) }) } else if children.len() > 16 { // implementations of various traits used in routing and rendering are implemented for // tuples of sizes 0, 1, 2, 3, ... N. N varies but is > 16. The traits are also implemented // for tuples of tuples, so if we have more than 16 items, we can split them out into // multiple tuples. let chunks = children.chunks(16).map(|children| { quote! { (#(#children),*) } }); Some(quote! { (#(#chunks),*) }) } else { Some(quote! { (#(#children),*) }) } } fn children_to_tokens( nodes: &mut [Node<impl CustomNode>], parent_type: TagType, parent_slots: Option<&mut HashMap<String, Vec<TokenStream>>>, global_class: Option<&TokenTree>, view_marker: Option<&str>, top_level: bool, disable_inert_html: bool, ) -> Vec<TokenStream> { if nodes.len() == 1 { match node_to_tokens( &mut nodes[0], parent_type, parent_slots, global_class, view_marker, top_level, disable_inert_html, ) { Some(tokens) => vec![tokens], None => vec![], } } else { let mut slots = HashMap::new(); let nodes = nodes .iter_mut() .filter_map(|node| { node_to_tokens( node, TagType::Unknown, Some(&mut slots), global_class, view_marker, top_level, disable_inert_html, ) }) .collect(); if let Some(parent_slots) = parent_slots { for (slot, mut values) in slots.drain() { parent_slots .entry(slot) .and_modify(|entry| entry.append(&mut values)) .or_insert(values); } } nodes } } fn node_to_tokens( node: &mut Node<impl CustomNode>, parent_type: TagType, parent_slots: Option<&mut HashMap<String, Vec<TokenStream>>>, global_class: Option<&TokenTree>, view_marker: Option<&str>, top_level: bool, disable_inert_html: bool, ) -> Option<TokenStream> { let is_inert = !disable_inert_html && is_inert_element(node); match node { Node::Comment(_) => None, Node::Doctype(node) => { let value = node.value.to_string_best(); Some(quote! { ::leptos::tachys::html::doctype(#value) }) } Node::Fragment(fragment) => fragment_to_tokens( &mut fragment.children, parent_type, parent_slots, global_class, view_marker, disable_inert_html, ), Node::Block(block) => { Some(quote! { ::leptos::prelude::IntoRender::into_render(#block) }) } Node::Text(text) => Some(text_to_tokens(&text.value)), Node::RawText(raw) => { let text = raw.to_string_best(); let text = syn::LitStr::new(&text, raw.span()); Some(text_to_tokens(&text)) } Node::Element(el_node) => { if !top_level && is_inert { let el_name = el_node.name().to_string(); let escape = el_name != "script" && el_name != "style" && el_name != "textarea"; let el_name = el_node.name().to_string(); if is_svg_element(&el_name) && el_name != "svg" { Some(inert_svg_element_to_tokens( node, escape, global_class, )) } else { Some(inert_element_to_tokens(node, escape, global_class)) } } else { element_to_tokens( el_node, parent_type, parent_slots, global_class, view_marker, disable_inert_html, ) } } Node::Custom(node) => Some(node.to_token_stream()), } } fn text_to_tokens(text: &LitStr) -> TokenStream { // on nightly, can use static string optimization if cfg!(all(feature = "nightly", rustc_nightly)) { quote! { ::leptos::tachys::view::static_types::Static::<#text> } } // otherwise, just use the literal string else { quote! { #text } } } pub(crate) fn element_to_tokens( node: &mut NodeElement<impl CustomNode>, mut parent_type: TagType, parent_slots: Option<&mut HashMap<String, Vec<TokenStream>>>, global_class: Option<&TokenTree>, view_marker: Option<&str>, disable_inert_html: bool, ) -> Option<TokenStream> { // attribute sorting: // // the `class` and `style` attributes overwrite individual `class:` and `style:` attributes // when they are set. as a result, we're going to sort the attributes so that `class` and // `style` always come before all other attributes. // if there's a spread marker, we don't want to move `class` or `style` before it // so let's only sort attributes that come *before* a spread marker let spread_position = node .attributes() .iter() .position(|n| match n { NodeAttribute::Block(node) => as_spread_attr(node).is_some(), _ => false, }) .unwrap_or_else(|| node.attributes().len()); // now, sort the attributes node.attributes_mut()[0..spread_position].sort_by(|a, b| { let key_a = match a { NodeAttribute::Attribute(attr) => match &attr.key { NodeName::Path(attr) => { attr.path.segments.first().map(|n| n.ident.to_string()) } _ => None, }, _ => None, }; let key_b = match b { NodeAttribute::Attribute(attr) => match &attr.key { NodeName::Path(attr) => { attr.path.segments.first().map(|n| n.ident.to_string()) } _ => None, }, _ => None, }; if let NodeAttribute::Attribute(a) = a { if let Some(Tuple(_)) = a.value() { return Ordering::Greater; } } if let NodeAttribute::Attribute(b) = b { if let Some(Tuple(_)) = b.value() { return Ordering::Less; } } match (key_a.as_deref(), key_b.as_deref()) { (Some("class"), Some("class")) | (Some("style"), Some("style")) => { Ordering::Equal } (Some("class"), _) | (Some("style"), _) => Ordering::Less, (_, Some("class")) | (_, Some("style")) => Ordering::Greater, _ => Ordering::Equal, } }); // check for duplicate attribute names and emit an error for all subsequent ones let mut names = HashSet::new(); // allow multiple class=(...) or style=(...) attributes fn allow_multiples(name: &str, attr: &KeyedAttribute) -> bool { (name == "class" || name == "style") && matches!(attr.value(), Some(Expr::Tuple(..))) } for attr in node.attributes() { if let NodeAttribute::Attribute(attr) = attr { let mut name = attr.key.to_string(); match tuple_name(&name, attr) { TupleName::None => {} TupleName::Str(tuple_name) => { name.push(':'); name.push_str(&tuple_name); } TupleName::Array(names) => { for tuple_name in names { name.push(':'); name.push_str(&tuple_name); } } } if names.contains(&name) && !allow_multiples(&name, attr) { proc_macro_error2::emit_error!( attr.span(), format!("This element already has a `{name}` attribute.") ); } else { names.insert(name); } } } let name = node.name(); if is_component_node(node) { if let Some(slot) = get_slot(node) { let slot = slot.clone(); slot_to_tokens( node, &slot, parent_slots, global_class, disable_inert_html, ); None } else { Some(component_to_tokens(node, global_class, disable_inert_html)) } } else if is_spread_marker(node) { let mut attributes = Vec::new(); let mut additions = Vec::new(); for node in node.attributes() { match node { NodeAttribute::Block(block) => { if let NodeBlock::ValidBlock(block) = block { match block.stmts.first() { Some(Stmt::Expr( Expr::Range(ExprRange { start: None, limits: RangeLimits::HalfOpen(_), end: Some(end), .. }), _, )) => { additions.push(quote! { #end }); } _ => { additions.push(quote! { #block }); } } } else { additions.push(quote! { #block }); } } NodeAttribute::Attribute(node) => { if let Some(content) = attribute_absolute(node, true) { attributes.push(content); } } } } if cfg!(feature = "__internal_erase_components") { Some(quote! { vec![#(#attributes.into_any_attr(),)*] #(.add_any_attr(#additions))* }) } else { Some(quote! { (#(#attributes,)*) #(.add_any_attr(#additions))* }) } } else { let tag = name.to_string(); // collect close_tag name to emit semantic information for IDE. /* TODO restore this let mut ide_helper_close_tag = IdeTagHelper::new(); let close_tag = node.close_tag.as_ref().map(|c| &c.name);*/ let is_custom = is_custom_element(&tag); let name = if is_custom { let name = node.name().to_string(); // link custom ident to name span for IDE docs let custom = Ident::new("custom", name.span()); quote_spanned! { node.name().span() => ::leptos::tachys::html::element::#custom(#name) } } else if is_svg_element(&tag) { parent_type = TagType::Svg; let name = if tag == "use" || tag == "use_" { Ident::new_raw("use", name.span()).to_token_stream() } else { name.to_token_stream() }; quote_spanned! { node.name().span() => ::leptos::tachys::svg::#name() } } else if is_math_ml_element(&tag) { parent_type = TagType::Math; quote_spanned! { node.name().span() => ::leptos::tachys::mathml::#name() } } else if is_ambiguous_element(&tag) { match parent_type { TagType::Unknown => { // We decided this warning was too aggressive, but I'll leave it here in case we want it later /* proc_macro_error2::emit_warning!(name.span(), "The view macro is assuming this is an HTML element, \
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
true
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/slice.rs
leptos_macro/tests/slice.rs
use leptos::prelude::RwSignal; use leptos_macro::slice; #[derive(Default)] pub struct OuterState { count: i32, inner: InnerState, } #[derive(Clone, PartialEq, Default)] pub struct InnerState { inner_count: i32, inner_tuple: InnerTuple, } #[derive(Clone, PartialEq, Default)] pub struct InnerTuple(String); #[test] fn green() { let outer_signal = RwSignal::new(OuterState::default()); let (_, _) = slice!(outer_signal.count); let (_, _) = slice!(outer_signal.inner.inner_count); let (_, _) = slice!(outer_signal.inner.inner_tuple.0); } #[test] fn red() { let t = trybuild::TestCases::new(); t.compile_fail("tests/slice/red.rs") }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/params.rs
leptos_macro/tests/params.rs
use leptos::prelude::*; use leptos_router::params::Params; #[derive(PartialEq, Debug, Params)] struct UserInfo { user_id: Option<String>, email: Option<String>, r#type: Option<i32>, not_found: Option<i32>, } #[test] fn params_test() { let mut map = leptos_router::params::ParamsMap::new(); map.insert("user_id", "12".to_owned()); map.insert("email", "em@il".to_owned()); map.insert("type", "12".to_owned()); let user_info = UserInfo::from_map(&map).unwrap(); assert_eq!( UserInfo { email: Some("em@il".to_owned()), user_id: Some("12".to_owned()), r#type: Some(12), not_found: None, }, user_info ); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/ui.rs
leptos_macro/tests/ui.rs
#[cfg(not(feature = "__internal_erase_components"))] #[test] fn ui() { let t = trybuild::TestCases::new(); #[cfg(all(feature = "nightly", rustc_nightly))] t.compile_fail("tests/ui/component.rs"); #[cfg(all(feature = "nightly", rustc_nightly))] t.compile_fail("tests/ui/component_absolute.rs"); t.compile_fail("tests/ui/server.rs"); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/server.rs
leptos_macro/tests/server.rs
#[cfg(not(feature = "ssr"))] pub mod tests { use leptos::{ server, server_fn::{codec, Http, ServerFn, ServerFnError}, }; use std::any::TypeId; #[test] fn server_default() { #[server] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!( <MyServerAction as ServerFn>::PATH .trim_end_matches(char::is_numeric), "/api/my_server_action" ); assert_eq!( TypeId::of::<<MyServerAction as ServerFn>::Protocol>(), TypeId::of::<Http<codec::PostUrl, codec::Json>>() ); } #[test] fn server_full_legacy() { #[server(FooBar, "/foo/bar", "Cbor", "my_path")] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!(<FooBar as ServerFn>::PATH, "/foo/bar/my_path"); assert_eq!( TypeId::of::<<FooBar as ServerFn>::Protocol>(), TypeId::of::<Http<codec::Cbor, codec::Cbor>>() ); } #[test] fn server_all_keywords() { #[server(endpoint = "my_path", encoding = "Cbor", prefix = "/foo/bar", name = FooBar)] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!(<FooBar as ServerFn>::PATH, "/foo/bar/my_path"); assert_eq!( TypeId::of::<<FooBar as ServerFn>::Protocol>(), TypeId::of::<Http<codec::Cbor, codec::Cbor>>() ); } #[test] fn server_mix() { #[server(FooBar, endpoint = "my_path")] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!(<FooBar as ServerFn>::PATH, "/api/my_path"); assert_eq!( TypeId::of::<<FooBar as ServerFn>::Protocol>(), TypeId::of::<Http<codec::PostUrl, codec::Json>>() ); } #[test] fn server_name() { #[server(name = FooBar)] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!( <FooBar as ServerFn>::PATH.trim_end_matches(char::is_numeric), "/api/my_server_action" ); assert_eq!( TypeId::of::<<FooBar as ServerFn>::Protocol>(), TypeId::of::<Http<codec::PostUrl, codec::Json>>() ); } #[test] fn server_prefix() { #[server(prefix = "/foo/bar")] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!( <MyServerAction as ServerFn>::PATH .trim_end_matches(char::is_numeric), "/foo/bar/my_server_action" ); assert_eq!( TypeId::of::<<MyServerAction as ServerFn>::Protocol>(), TypeId::of::<Http<codec::PostUrl, codec::Json>>() ); } #[test] fn server_encoding() { #[server(encoding = "GetJson")] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!( <MyServerAction as ServerFn>::PATH .trim_end_matches(char::is_numeric), "/api/my_server_action" ); assert_eq!( TypeId::of::<<MyServerAction as ServerFn>::Protocol>(), TypeId::of::<Http<codec::GetUrl, codec::Json>>() ); } #[test] fn server_endpoint() { #[server(endpoint = "/path/to/my/endpoint")] pub async fn my_server_action() -> Result<(), ServerFnError> { Ok(()) } assert_eq!( <MyServerAction as ServerFn>::PATH, "/api/path/to/my/endpoint" ); assert_eq!( TypeId::of::<<MyServerAction as ServerFn>::Protocol>(), TypeId::of::<Http<codec::PostUrl, codec::Json>>() ); } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/memo.rs
leptos_macro/tests/memo.rs
use leptos::prelude::RwSignal; use leptos_macro::memo; #[derive(Default)] pub struct OuterState { count: i32, inner: InnerState, } #[derive(Clone, PartialEq, Default)] pub struct InnerState { inner_count: i32, inner_tuple: InnerTuple, } #[derive(Clone, PartialEq, Default)] pub struct InnerTuple(String); #[test] fn green() { let outer_signal = RwSignal::new(OuterState::default()); let _ = memo!(outer_signal.count); let _ = memo!(outer_signal.inner.inner_count); let _ = memo!(outer_signal.inner.inner_tuple.0); } #[test] fn red() { let t = trybuild::TestCases::new(); t.compile_fail("tests/memo/red.rs") }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/component.rs
leptos_macro/tests/component.rs
use core::num::NonZeroUsize; use leptos::prelude::*; #[derive(PartialEq, Debug)] struct UserInfo { user_id: String, email: String, } #[derive(PartialEq, Debug)] struct Admin(bool); #[component] fn Component( #[prop(optional)] optional: bool, #[prop(optional, into)] optional_into: Option<String>, #[prop(optional_no_strip)] optional_no_strip: Option<String>, #[prop(strip_option)] strip_option: Option<u8>, #[prop(default = NonZeroUsize::new(10).unwrap())] default: NonZeroUsize, #[prop(into)] into: String, impl_trait: impl Fn() -> i32 + 'static, #[prop(name = "data")] UserInfo { email, user_id }: UserInfo, #[prop(name = "tuple")] (name, id): (String, i32), #[prop(name = "tuple_struct")] Admin(is_admin): Admin, #[prop(name = "outside_name")] inside_name: i32, ) -> impl IntoView { _ = optional; _ = optional_into; _ = optional_no_strip; _ = strip_option; _ = default; _ = into; _ = impl_trait; _ = email; _ = user_id; _ = id; _ = name; _ = is_admin; _ = inside_name; } #[test] fn component() { let cp = ComponentProps::builder() .into("") .strip_option(9) .impl_trait(|| 42) .data(UserInfo { email: "em@il".into(), user_id: "1".into(), }) .tuple(("Joe".into(), 12)) .tuple_struct(Admin(true)) .outside_name(1) .build(); assert!(!cp.optional); assert_eq!(cp.optional_into, None); assert_eq!(cp.optional_no_strip, None); assert_eq!(cp.strip_option, Some(9)); assert_eq!(cp.default, NonZeroUsize::new(10).unwrap()); assert_eq!(cp.into, ""); assert_eq!((cp.impl_trait)(), 42); assert_eq!( cp.data, UserInfo { email: "em@il".into(), user_id: "1".into(), } ); assert_eq!(cp.tuple, ("Joe".into(), 12)); assert_eq!(cp.tuple_struct, Admin(true)); assert_eq!(cp.outside_name, 1); } #[test] fn component_nostrip() { // Should compile (using nostrip:optional_into in second <Component />) view! { <Component optional_into="foo" strip_option=9 into="" impl_trait=|| 42 data=UserInfo { email: "em@il".into(), user_id: "1".into(), } tuple=("Joe".into(), 12) tuple_struct=Admin(true) outside_name=1 /> <Component nostrip:optional_into=Some("foo") strip_option=9 into="" impl_trait=|| 42 data=UserInfo { email: "em@il".into(), user_id: "1".into(), } tuple=("Joe".into(), 12) tuple_struct=Admin(true) outside_name=1 /> }; } #[component] fn WithLifetime<'a>(data: &'a str) -> impl IntoView { _ = data; "static lifetime" } #[test] fn returns_static_lifetime() { #[allow(unused)] fn can_return_impl_intoview_from_body() -> impl IntoView { let val = String::from("non_static_lifetime"); WithLifetime(WithLifetimeProps::builder().data(&val).build()) } } #[cfg(not(feature = "nightly"))] #[component] pub fn IntoReactiveValueTestComponentSignal( #[prop(into)] arg1: Signal<String>, #[prop(into)] arg2: Signal<String>, #[prop(into)] arg3: Signal<String>, #[prop(into)] arg4: Signal<usize>, #[prop(into)] arg5: Signal<usize>, #[prop(into)] arg6: Signal<usize>, #[prop(into)] arg7: Signal<Option<usize>>, #[prop(into)] arg8: ArcSignal<String>, #[prop(into)] arg9: ArcSignal<String>, #[prop(into)] arg10: ArcSignal<String>, #[prop(into)] arg11: ArcSignal<usize>, #[prop(into)] arg12: ArcSignal<usize>, #[prop(into)] arg13: ArcSignal<usize>, #[prop(into)] arg14: ArcSignal<Option<usize>>, // Optionals: #[prop(into, optional)] arg15: Option<Signal<usize>>, #[prop(into, optional)] arg16_purposely_omitted: Option<Signal<usize>>, #[prop(into, optional)] arg17: Option<Signal<usize>>, #[prop(into, strip_option)] arg18: Option<Signal<usize>>, ) -> impl IntoView { move || { view! { <div> <p>{arg1.get()}</p> <p>{arg2.get()}</p> <p>{arg3.get()}</p> <p>{arg4.get()}</p> <p>{arg5.get()}</p> <p>{arg6.get()}</p> <p>{arg7.get()}</p> <p>{arg8.get()}</p> <p>{arg9.get()}</p> <p>{arg10.get()}</p> <p>{arg11.get()}</p> <p>{arg12.get()}</p> <p>{arg13.get()}</p> <p>{arg14.get()}</p> <p>{arg15.get()}</p> <p>{arg16_purposely_omitted.get()}</p> <p>{arg17.get()}</p> <p>{arg18.get()}</p> </div> } } } #[component] pub fn IntoReactiveValueTestComponentCallback( #[prop(into)] arg1: Callback<(), String>, #[prop(into)] arg2: Callback<usize, String>, #[prop(into)] arg3: Callback<(usize,), String>, #[prop(into)] arg4: Callback<(usize, String), String>, #[prop(into)] arg5: UnsyncCallback<(), String>, #[prop(into)] arg6: UnsyncCallback<usize, String>, #[prop(into)] arg7: UnsyncCallback<(usize,), String>, #[prop(into)] arg8: UnsyncCallback<(usize, String), String>, ) -> impl IntoView { move || { view! { <div> <p>{arg1.run(())}</p> <p>{arg2.run(1)}</p> <p>{arg3.run((2,))}</p> <p>{arg4.run((3, "three".into()))}</p> <p>{arg5.run(())}</p> <p>{arg6.run(1)}</p> <p>{arg7.run((2,))}</p> <p>{arg8.run((3, "three".into()))}</p> </div> } } } #[cfg(not(feature = "nightly"))] #[test] fn test_into_reactive_value_signal() { let _ = view! { <IntoReactiveValueTestComponentSignal arg1=move || "I was a reactive closure!" arg2="I was a basic str!" arg3=Signal::stored("I was already a signal!") arg4=move || 2 arg5=3 arg6=Signal::stored(4) arg7=|| 2 arg8=move || "I was a reactive closure!" arg9="I was a basic str!" arg10=ArcSignal::stored("I was already a signal!".to_string()) arg11=move || 2 arg12=3 arg13=ArcSignal::stored(4) arg14=|| 2 arg15=|| 2 nostrip:arg17=Some(|| 2) arg18=|| 2 /> }; } #[test] fn test_into_reactive_value_callback() { let _ = view! { <IntoReactiveValueTestComponentCallback arg1=|| "I was a callback static str!" arg2=|_n| "I was a callback static str!" arg3=|(_n,)| "I was a callback static str!" arg4=|(_n, _s)| "I was a callback static str!" arg5=|| "I was a callback static str!" arg6=|_n| "I was a callback static str!" arg7=|(_n,)| "I was a callback static str!" arg8=|(_n, _s)| "I was a callback static str!" /> }; } // an attempt to catch unhygienic macros regression mod macro_hygiene { // To ensure no relative module path to leptos inside macros. mod leptos {} // doing this separately to below due to this being the smallest // unit with the lowest import surface. #[test] fn view() { use ::leptos::IntoView; use ::leptos_macro::{component, view}; #[component] fn Component() -> impl IntoView { view! { {()} {()} } } } // may extend this test with other items as necessary. #[test] fn view_into_any() { use ::leptos::{ prelude::{ElementChild, IntoAny}, IntoView, }; use ::leptos_macro::{component, view}; #[component] fn Component() -> impl IntoView { view! { <div>{().into_any()} {()}</div> } } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/slice/red.rs
leptos_macro/tests/slice/red.rs
use leptos_macro::slice; use leptos::prelude::RwSignal; #[derive(Default, PartialEq)] pub struct OuterState { count: i32, inner: InnerState, } #[derive(Clone, PartialEq, Default)] pub struct InnerState { inner_count: i32, inner_name: String, } fn main() { let outer_signal = RwSignal::new(OuterState::default()); let (_, _) = slice!(); let (_, _) = slice!(outer_signal); let (_, _) = slice!(outer_signal.); let (_, _) = slice!(outer_signal.inner.); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/ui/component_absolute.rs
leptos_macro/tests/ui/component_absolute.rs
#[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] fn missing_return_type() {} #[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] fn unknown_prop_option(#[prop(hello)] test: bool) -> impl ::leptos::IntoView { _ = test; } #[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] fn optional_and_optional_no_strip( #[prop(optional, optional_no_strip)] conflicting: bool, ) -> impl IntoView { _ = conflicting; } #[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] fn optional_and_strip_option( #[prop(optional, strip_option)] conflicting: bool, ) -> impl ::leptos::IntoView { _ = conflicting; } #[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] fn optional_no_strip_and_strip_option( #[prop(optional_no_strip, strip_option)] conflicting: bool, ) -> impl ::leptos::IntoView { _ = conflicting; } #[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] fn default_without_value( #[prop(default)] default: bool, ) -> impl ::leptos::IntoView { _ = default; } #[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] fn default_with_invalid_value( #[prop(default= |)] default: bool, ) -> impl ::leptos::IntoView { _ = default; } #[cfg(all(feature = "nightly", rustc_nightly))] #[::leptos::component] pub fn using_the_view_macro() -> impl ::leptos::IntoView { leptos::view! { "ok" } } fn main() {}
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/ui/server.rs
leptos_macro/tests/ui/server.rs
use leptos::prelude::*; #[server(endpoint = "my_path", FooBar)] pub async fn positional_argument_follows_keyword_argument( ) -> Result<(), ServerFnError> { Ok(()) } #[server(endpoint = "first", endpoint = "second")] pub async fn keyword_argument_repeated() -> Result<(), ServerFnError> { Ok(()) } #[server(Foo, Bar)] pub async fn expected_string_literal() -> Result<(), ServerFnError> { Ok(()) } #[server(Foo, Bar, bazz)] pub async fn expected_string_literal_2() -> Result<(), ServerFnError> { Ok(()) } #[server("Foo")] pub async fn expected_identifier() -> Result<(), ServerFnError> { Ok(()) } #[server(Foo Bar)] pub async fn expected_comma() -> Result<(), ServerFnError> { Ok(()) } #[server(FooBar, "/foo/bar", "Cbor", "my_path", "extra")] pub async fn unexpected_extra_argument() -> Result<(), ServerFnError> { Ok(()) } #[server(encoding = "wrong")] pub async fn encoding_not_found() -> Result<(), ServerFnError> { Ok(()) } fn main() {}
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/ui/component.rs
leptos_macro/tests/ui/component.rs
use leptos::prelude::*; #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn missing_scope() {} #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn missing_return_type() {} #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn unknown_prop_option(#[prop(hello)] test: bool) -> impl IntoView { _ = test; } #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn optional_and_optional_no_strip( #[prop(optional, optional_no_strip)] conflicting: bool, ) -> impl IntoView { _ = conflicting; } #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn optional_and_strip_option( #[prop(optional, strip_option)] conflicting: bool, ) -> impl IntoView { _ = conflicting; } #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn optional_no_strip_and_strip_option( #[prop(optional_no_strip, strip_option)] conflicting: bool, ) -> impl IntoView { _ = conflicting; } #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn default_without_value(#[prop(default)] default: bool) -> impl IntoView { _ = default; } #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn default_with_invalid_value( #[prop(default= |)] default: bool, ) -> impl IntoView { _ = default; } #[cfg(all(feature = "nightly", rustc_nightly))] #[component] fn destructure_without_name((default, value): (bool, i32)) -> impl IntoView { _ = default; _ = value; } fn main() {}
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/tests/memo/red.rs
leptos_macro/tests/memo/red.rs
use leptos::prelude::RwSignal; use leptos_macro::memo; #[derive(Default, PartialEq)] pub struct OuterState { count: i32, inner: InnerState, } #[derive(Clone, PartialEq, Default)] pub struct InnerState { inner_count: i32, inner_name: String, } fn main() { let outer_signal = RwSignal::new(OuterState::default()); let _ = memo!(); let _ = memo!(outer_signal); let _ = memo!(outer_signal.); let _ = memo!(outer_signal.inner.); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_macro/example/src/lib.rs
leptos_macro/example/src/lib.rs
use leptos::prelude::*; #[component] pub fn TestComponent( /// Rust code /// ``` /// assert_eq!("hello", stringify!(hello)); /// ``` /// View containing rust code /// ```view /// assert!(true); /// ``` /// View containing rsx /// ```view /// # use example::TestComponent; /// <TestComponent key="hello"/> /// ``` /// View containing rsx /// ```view compile_fail /// # use example::TestComponent; /// <TestComponent/> /// ``` #[prop(into)] key: String, /// rsx unclosed /// ```view /// # use example::TestComponent; /// <TestComponent key="hello"/> #[prop(optional)] another: usize, /// rust unclosed /// ```view /// use example::TestComponent; #[prop(optional)] and_another: usize, ) -> impl IntoView { _ = (key, another, and_another); } #[component] pub fn TestMutCallback<F>(mut callback: F, value: &'static str) -> impl IntoView where F: FnMut(u32) + 'static, { let value = value.to_owned(); view! { <button on:click=move |_| { callback(5); }>{value}</button> <TestComponent key="test"/> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/build.rs
tachys/build.rs
use rustc_version::{version_meta, Channel}; fn main() { // Set cfg flags depending on release channel if matches!(version_meta().unwrap().channel, Channel::Nightly) { println!("cargo:rustc-cfg=rustc_nightly"); } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/lib.rs
tachys/src/lib.rs
//! Allows rendering user interfaces based on a statically-typed view tree. //! //! This view tree is generic over rendering backends, and agnostic about reactivity/change //! detection. // this is specifically used for `unsized_const_params` below // this allows us to use const generic &'static str for static text nodes and attributes #![allow(incomplete_features)] #![cfg_attr( all(feature = "nightly", rustc_nightly), feature(unsized_const_params) )] // support for const generic &'static str has now moved back and forth between // these two features a couple times; we'll just enable both #![cfg_attr(all(feature = "nightly", rustc_nightly), feature(adt_const_params))] #![deny(missing_docs)] /// Commonly-used traits. pub mod prelude { pub use crate::{ html::{ attribute::{ any_attribute::IntoAnyAttribute, aria::AriaAttributes, custom::CustomAttribute, global::{ ClassAttribute, GlobalAttributes, GlobalOnAttributes, OnAttribute, OnTargetAttribute, PropAttribute, StyleAttribute, }, IntoAttributeValue, }, directive::DirectiveAttribute, element::{ElementChild, ElementExt, InnerHtmlAttribute}, node_ref::NodeRefAttribute, }, renderer::{dom::Dom, Renderer}, view::{ add_attr::AddAnyAttr, any_view::{AnyView, IntoAny, IntoMaybeErased}, IntoRender, Mountable, Render, RenderHtml, }, }; } use wasm_bindgen::JsValue; use web_sys::Node; /// Helpers for interacting with the DOM. pub mod dom; /// Types for building a statically-typed HTML view tree. pub mod html; /// Supports adding interactivity to HTML. pub mod hydration; /// Types for MathML. pub mod mathml; /// Defines various backends that can render views. pub mod renderer; /// Rendering views to HTML. pub mod ssr; /// Types for SVG. pub mod svg; /// Core logic for manipulating views. pub mod view; pub use either_of as either; #[cfg(feature = "islands")] #[doc(hidden)] pub use wasm_bindgen; #[cfg(feature = "islands")] #[doc(hidden)] pub use web_sys; /// View implementations for the `oco_ref` crate (cheaply-cloned string types). #[cfg(feature = "oco")] pub mod oco; /// View implementations for the `reactive_graph` crate. #[cfg(feature = "reactive_graph")] pub mod reactive_graph; /// A type-erased container. pub mod erased; pub(crate) trait UnwrapOrDebug { type Output; fn or_debug(self, el: &Node, label: &'static str); fn ok_or_debug( self, el: &Node, label: &'static str, ) -> Option<Self::Output>; } impl<T> UnwrapOrDebug for Result<T, JsValue> { type Output = T; #[track_caller] fn or_debug(self, el: &Node, name: &'static str) { #[cfg(any(debug_assertions, leptos_debuginfo))] { if let Err(err) = self { let location = std::panic::Location::caller(); web_sys::console::warn_3( &JsValue::from_str(&format!( "[WARNING] Non-fatal error at {location}, while \ calling {name} on " )), el, &err, ); } } #[cfg(not(any(debug_assertions, leptos_debuginfo)))] { _ = self; } } #[track_caller] fn ok_or_debug( self, el: &Node, name: &'static str, ) -> Option<Self::Output> { #[cfg(any(debug_assertions, leptos_debuginfo))] { if let Err(err) = &self { let location = std::panic::Location::caller(); web_sys::console::warn_3( &JsValue::from_str(&format!( "[WARNING] Non-fatal error at {location}, while \ calling {name} on " )), el, err, ); } self.ok() } #[cfg(not(any(debug_assertions, leptos_debuginfo)))] { self.ok() } } } #[doc(hidden)] #[macro_export] macro_rules! or_debug { ($action:expr, $el:expr, $label:literal) => { if cfg!(any(debug_assertions, leptos_debuginfo)) { $crate::UnwrapOrDebug::or_debug($action, $el, $label); } else { _ = $action; } }; } #[doc(hidden)] #[macro_export] macro_rules! ok_or_debug { ($action:expr, $el:expr, $label:literal) => { if cfg!(any(debug_assertions, leptos_debuginfo)) { $crate::UnwrapOrDebug::ok_or_debug($action, $el, $label) } else { $action.ok() } }; }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/hydration.rs
tachys/src/hydration.rs
use crate::{ renderer::{CastFrom, Rndr}, view::{Position, PositionState}, }; #[cfg(any(debug_assertions, leptos_debuginfo))] use std::cell::Cell; use std::{cell::RefCell, panic::Location, rc::Rc}; use web_sys::{Comment, Element, Node, Text}; #[cfg(feature = "mark_branches")] const COMMENT_NODE: u16 = 8; /// Hydration works by walking over the DOM, adding interactivity as needed. /// /// This cursor tracks the location in the DOM that is currently being hydrated. Each that type /// implements [`RenderHtml`](crate::view::RenderHtml) knows how to advance the cursor to access /// the nodes it needs. #[derive(Debug)] pub struct Cursor(Rc<RefCell<crate::renderer::types::Node>>); impl Clone for Cursor { fn clone(&self) -> Self { Self(Rc::clone(&self.0)) } } impl Cursor where crate::renderer::types::Element: AsRef<crate::renderer::types::Node>, { /// Creates a new cursor starting at the root element. pub fn new(root: crate::renderer::types::Element) -> Self { let root = <crate::renderer::types::Element as AsRef< crate::renderer::types::Node, >>::as_ref(&root) .clone(); Self(Rc::new(RefCell::new(root))) } /// Returns the node at which the cursor is currently located. pub fn current(&self) -> crate::renderer::types::Node { self.0.borrow().clone() } /// Advances to the next child of the node at which the cursor is located. /// /// Does nothing if there is no child. pub fn child(&self) { let mut inner = self.0.borrow_mut(); if let Some(node) = Rndr::first_child(&inner) { *inner = node; } #[cfg(feature = "mark_branches")] { while inner.node_type() == COMMENT_NODE { if let Some(content) = inner.text_content() { if content.starts_with("bo") || content.starts_with("bc") { if let Some(sibling) = Rndr::next_sibling(&inner) { *inner = sibling; continue; } } } break; } } // //drop(inner); //crate::log(">> which is "); //Rndr::log_node(&self.current()); } /// Advances to the next sibling of the node at which the cursor is located. /// /// Does nothing if there is no sibling. pub fn sibling(&self) { let mut inner = self.0.borrow_mut(); if let Some(node) = Rndr::next_sibling(&inner) { *inner = node; } #[cfg(feature = "mark_branches")] { while inner.node_type() == COMMENT_NODE { if let Some(content) = inner.text_content() { if content.starts_with("bo") || content.starts_with("bc") { if let Some(sibling) = Rndr::next_sibling(&inner) { *inner = sibling; continue; } } } break; } } //drop(inner); //crate::log(">> which is "); //Rndr::log_node(&self.current()); } /// Moves to the parent of the node at which the cursor is located. /// /// Does nothing if there is no parent. pub fn parent(&self) { let mut inner = self.0.borrow_mut(); if let Some(node) = Rndr::get_parent(&inner) { *inner = node; } } /// Sets the cursor to some node. pub fn set(&self, node: crate::renderer::types::Node) { *self.0.borrow_mut() = node; } /// Advances to the next placeholder node and returns it pub fn next_placeholder( &self, position: &PositionState, ) -> crate::renderer::types::Placeholder { //crate::dom::log("looking for placeholder after"); //Rndr::log_node(&self.current()); self.advance_to_placeholder(position); let marker = self.current(); crate::renderer::types::Placeholder::cast_from(marker.clone()) .unwrap_or_else(|| failed_to_cast_marker_node(marker)) } /// Advances to the next placeholder node. pub fn advance_to_placeholder(&self, position: &PositionState) { if position.get() == Position::FirstChild { self.child(); } else { self.sibling(); } position.set(Position::NextChild); } } #[cfg(any(debug_assertions, leptos_debuginfo))] thread_local! { static CURRENTLY_HYDRATING: Cell<Option<&'static Location<'static>>> = const { Cell::new(None) }; } pub(crate) fn set_currently_hydrating( location: Option<&'static Location<'static>>, ) { #[cfg(any(debug_assertions, leptos_debuginfo))] { CURRENTLY_HYDRATING.set(location); } #[cfg(not(any(debug_assertions, leptos_debuginfo)))] { _ = location; } } pub(crate) fn failed_to_cast_element(tag_name: &str, node: Node) -> Element { #[cfg(not(any(debug_assertions, leptos_debuginfo)))] { _ = node; unreachable!(); } #[cfg(any(debug_assertions, leptos_debuginfo))] { let hydrating = CURRENTLY_HYDRATING .take() .map(|n| n.to_string()) .unwrap_or_else(|| "{unknown}".to_string()); web_sys::console::error_3( &wasm_bindgen::JsValue::from_str(&format!( "A hydration error occurred while trying to hydrate an \ element defined at {hydrating}.\n\nThe framework expected an \ HTML <{tag_name}> element, but found this instead: ", )), &node, &wasm_bindgen::JsValue::from_str( "\n\nThe hydration mismatch may have occurred slightly \ earlier, but this is the first time the framework found a \ node of an unexpected type.", ), ); panic!( "Unrecoverable hydration error. Please read the error message \ directly above this for more details." ); } } pub(crate) fn failed_to_cast_marker_node(node: Node) -> Comment { #[cfg(not(any(debug_assertions, leptos_debuginfo)))] { _ = node; unreachable!(); } #[cfg(any(debug_assertions, leptos_debuginfo))] { let hydrating = CURRENTLY_HYDRATING .take() .map(|n| n.to_string()) .unwrap_or_else(|| "{unknown}".to_string()); web_sys::console::error_3( &wasm_bindgen::JsValue::from_str(&format!( "A hydration error occurred while trying to hydrate an \ element defined at {hydrating}.\n\nThe framework expected a \ marker node, but found this instead: ", )), &node, &wasm_bindgen::JsValue::from_str( "\n\nThe hydration mismatch may have occurred slightly \ earlier, but this is the first time the framework found a \ node of an unexpected type.", ), ); panic!( "Unrecoverable hydration error. Please read the error message \ directly above this for more details." ); } } pub(crate) fn failed_to_cast_text_node(node: Node) -> Text { #[cfg(not(any(debug_assertions, leptos_debuginfo)))] { _ = node; unreachable!(); } #[cfg(any(debug_assertions, leptos_debuginfo))] { let hydrating = CURRENTLY_HYDRATING .take() .map(|n| n.to_string()) .unwrap_or_else(|| "{unknown}".to_string()); web_sys::console::error_3( &wasm_bindgen::JsValue::from_str(&format!( "A hydration error occurred while trying to hydrate an \ element defined at {hydrating}.\n\nThe framework expected a \ text node, but found this instead: ", )), &node, &wasm_bindgen::JsValue::from_str( "\n\nThe hydration mismatch may have occurred slightly \ earlier, but this is the first time the framework found a \ node of an unexpected type.", ), ); panic!( "Unrecoverable hydration error. Please read the error message \ directly above this for more details." ); } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/erased.rs
tachys/src/erased.rs
use erased::ErasedBox; #[cfg(not(erase_components))] fn check(id_1: &std::any::TypeId, id_2: &std::any::TypeId) { if id_1 != id_2 { panic!("Erased: type mismatch") } } macro_rules! erased { ([$($new_t_params:tt)*], $name:ident) => { /// A type-erased item. This is slightly more efficient than using `Box<dyn Any (+ Send)>`. /// /// With the caveat that T must always be correct upon retrieval. /// In erased mode T retrieval is unchecked to minimise codegen, in other modes T will be verified and a panic otherwise. pub struct $name { #[cfg(not(erase_components))] type_id: std::any::TypeId, value: Option<ErasedBox>, drop: fn(ErasedBox), } impl $name { /// Create a new type-erased item. pub fn new<T: $($new_t_params)*>(item: T) -> Self { Self { #[cfg(not(erase_components))] type_id: std::any::TypeId::of::<T>(), value: Some(ErasedBox::new(Box::new(item))), drop: |value| { let _ = unsafe { value.into_inner::<T>() }; }, } } /// Get a reference to the inner value. pub fn get_ref<T: 'static>(&self) -> &T { #[cfg(not(erase_components))] check(&self.type_id, &std::any::TypeId::of::<T>()); unsafe { self.value.as_ref().unwrap().get_ref::<T>() } } /// Get a mutable reference to the inner value. pub fn get_mut<T: 'static>(&mut self) -> &mut T { #[cfg(not(erase_components))] check(&self.type_id, &std::any::TypeId::of::<T>()); unsafe { self.value.as_mut().unwrap().get_mut::<T>() } } /// Consume the item and return the inner value. pub fn into_inner<T: 'static>(mut self) -> T { #[cfg(not(erase_components))] check(&self.type_id, &std::any::TypeId::of::<T>()); *unsafe { self.value.take().unwrap().into_inner::<T>() } } } /// If into_inner() wasn't called, the value would leak and destructors wouldn't run, this prevents that from happening. impl Drop for $name { fn drop(&mut self) { if let Some(value) = self.value.take() { (self.drop)(value); } } } }; } erased!([Send + 'static], Erased); erased!(['static], ErasedLocal); /// SAFETY: `Erased::new` ensures that `T` is `Send` and `'static`. unsafe impl Send for Erased {}
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/dom.rs
tachys/src/dom.rs
use wasm_bindgen::JsCast; use web_sys::{Document, HtmlElement, Window}; thread_local! { pub(crate) static WINDOW: web_sys::Window = web_sys::window().unwrap(); pub(crate) static DOCUMENT: web_sys::Document = web_sys::window().unwrap().document().unwrap(); } /// Returns the [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window). /// /// This is cached as a thread-local variable, so calling `window()` multiple times /// requires only one call out to JavaScript. pub fn window() -> Window { WINDOW.with(Clone::clone) } /// Returns the [`Document`](https://developer.mozilla.org/en-US/docs/Web/API/Document). /// /// This is cached as a thread-local variable, so calling `document()` multiple times /// requires only one call out to JavaScript. /// /// ## Panics /// Panics if called outside a browser environment. pub fn document() -> Document { DOCUMENT.with(Clone::clone) } /// The `<body>` element. /// /// ## Panics /// Panics if there is no `<body>` in the current document, or if it is called outside a browser /// environment. pub fn body() -> HtmlElement { document().body().unwrap() } /// Helper function to extract [`Event.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target) /// from any event. pub fn event_target<T>(event: &web_sys::Event) -> T where T: JsCast, { event.target().unwrap().unchecked_into::<T>() } /// Helper function to extract `event.target.value` from an event. /// /// This is useful in the `on:input` or `on:change` listeners for an `<input>` element. pub fn event_target_value<T>(event: &T) -> String where T: JsCast, { event .unchecked_ref::<web_sys::Event>() .target() .unwrap() .unchecked_into::<web_sys::HtmlInputElement>() .value() } /// Helper function to extract `event.target.checked` from an event. /// /// This is useful in the `on:change` listeners for an `<input type="checkbox">` element. pub fn event_target_checked(ev: &web_sys::Event) -> bool { ev.target() .unwrap() .unchecked_into::<web_sys::HtmlInputElement>() .checked() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/oco.rs
tachys/src/oco.rs
use crate::{ html::{ attribute::{any_attribute::AnyAttribute, AttributeValue}, class::IntoClass, property::IntoProperty, style::IntoStyle, }, hydration::Cursor, no_attrs, prelude::{Mountable, Render, RenderHtml}, renderer::Rndr, view::{strings::StrState, Position, PositionState, ToTemplate}, }; use oco_ref::Oco; use wasm_bindgen::JsValue; /// Retained view state for [`Oco`]. pub struct OcoStrState { node: crate::renderer::types::Text, str: Oco<'static, str>, } impl Render for Oco<'static, str> { type State = OcoStrState; fn build(self) -> Self::State { let node = Rndr::create_text_node(&self); OcoStrState { node, str: self } } fn rebuild(self, state: &mut Self::State) { let OcoStrState { node, str } = state; if &self != str { Rndr::set_text(node, &self); *str = self; } } } no_attrs!(Oco<'static, str>); impl RenderHtml for Oco<'static, str> { type AsyncOutput = Self; type Owned = Self; const MIN_LENGTH: usize = 0; fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn to_html_with_buf( self, buf: &mut String, position: &mut Position, escape: bool, mark_branches: bool, extra_attrs: Vec<AnyAttribute>, ) { <&str as RenderHtml>::to_html_with_buf( &self, buf, position, escape, mark_branches, extra_attrs, ) } fn hydrate<const FROM_SERVER: bool>( self, cursor: &Cursor, position: &PositionState, ) -> Self::State { let this: &str = self.as_ref(); let StrState { node, .. } = <&str as RenderHtml>::hydrate::<FROM_SERVER>( this, cursor, position, ); OcoStrState { node, str: self } } fn into_owned(self) -> <Self as RenderHtml>::Owned { self } } impl ToTemplate for Oco<'static, str> { const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE; fn to_template( buf: &mut String, class: &mut String, style: &mut String, inner_html: &mut String, position: &mut Position, ) { <&str as ToTemplate>::to_template( buf, class, style, inner_html, position, ) } } impl Mountable for OcoStrState { fn unmount(&mut self) { self.node.unmount() } fn mount( &mut self, parent: &crate::renderer::types::Element, marker: Option<&crate::renderer::types::Node>, ) { Rndr::insert_node(parent, self.node.as_ref(), marker); } fn insert_before_this(&self, child: &mut dyn Mountable) -> bool { self.node.insert_before_this(child) } fn elements(&self) -> Vec<crate::renderer::types::Element> { vec![] } } impl AttributeValue for Oco<'static, str> { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Oco<'static, str>); type Cloneable = Self; type CloneableOwned = Self; fn html_len(&self) -> usize { self.as_str().len() } fn to_html(self, key: &str, buf: &mut String) { <&str as AttributeValue>::to_html(self.as_str(), key, buf); } fn to_template(_key: &str, _buf: &mut String) {} fn hydrate<const FROM_SERVER: bool>( self, key: &str, el: &crate::renderer::types::Element, ) -> Self::State { let (el, _) = <&str as AttributeValue>::hydrate::<FROM_SERVER>( self.as_str(), key, el, ); (el, self) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { Rndr::set_attribute(el, key, &self); (el.clone(), self) } fn rebuild(self, key: &str, state: &mut Self::State) { let (el, prev_value) = state; if self != *prev_value { Rndr::set_attribute(el, key, &self); } *prev_value = self; } fn into_cloneable(mut self) -> Self::Cloneable { // ensure it's reference-counted self.upgrade_inplace(); self } fn into_cloneable_owned(mut self) -> Self::CloneableOwned { // ensure it's reference-counted self.upgrade_inplace(); self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } } impl IntoClass for Oco<'static, str> { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Self); type Cloneable = Self; type CloneableOwned = Self; fn html_len(&self) -> usize { self.as_str().len() } fn to_html(self, class: &mut String) { IntoClass::to_html(self.as_str(), class); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { if !FROM_SERVER { Rndr::set_attribute(el, "class", &self); } (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "class", &self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "class", &self); } *prev = self; } fn into_cloneable(mut self) -> Self::Cloneable { // ensure it's reference-counted self.upgrade_inplace(); self } fn into_cloneable_owned(mut self) -> Self::CloneableOwned { // ensure it's reference-counted self.upgrade_inplace(); self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "class"); } } impl IntoProperty for Oco<'static, str> { type State = (crate::renderer::types::Element, JsValue); type Cloneable = Self; type CloneableOwned = Self; fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = JsValue::from_str(self.as_ref()); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = JsValue::from_str(self.as_ref()); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn rebuild(self, state: &mut Self::State, key: &str) { let (el, prev) = state; let value = JsValue::from_str(self.as_ref()); Rndr::set_property_or_value(el, key, &value); *prev = value; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } } impl IntoStyle for Oco<'static, str> { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Self); type Cloneable = Self; type CloneableOwned = Self; fn to_html(self, style: &mut String) { style.push_str(&self); style.push(';'); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "style", &self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "style", &self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "style"); } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/renderer/sledgehammer.rs
tachys/src/renderer/sledgehammer.rs
#![allow(missing_docs)] // Allow missing docs for experimental backend use super::{CastFrom, DomRenderer, RemoveEventHandler, Renderer}; use crate::{ dom::window, view::{Mountable, ToTemplate}, }; use linear_map::LinearMap; use rustc_hash::FxHashSet; use sledgehammer_bindgen::bindgen; use std::{ any::TypeId, borrow::Cow, cell::{Cell, RefCell}, rc::Rc, }; use wasm_bindgen::{ prelude::{wasm_bindgen, Closure}, JsCast, JsValue, }; use web_sys::Node; #[wasm_bindgen] extern "C" { #[wasm_bindgen] fn queueMicrotask(closure: &Closure<dyn Fn() -> ()>); type Global; } #[bindgen] mod js { //#[extends(NodeInterpreter)] struct Channel; const JS: &str = r#" function Queue() { var head, tail; return Object.freeze({ enqueue(value) { const link = {value, next: undefined}; tail = head ? tail.next = link : head = link; }, dequeue() { if (head) { const value = head.value; head = head.next; return value; } }, peek() { return head?.value } }); } this.nodes = [null]; this.jsvalues = Queue(); "#; fn drop_node(id: u32) { "this.nodes[$id$]=null;" } fn store_body(id: u32) { "this.nodes[$id$]=document.body;" } fn create_text_node(id: u32, data: &str) { "this.nodes[$id$]=document.createTextNode($data$);" } fn create_comment(id: u32) { "this.nodes[$id$]=document.createComment();" } fn create_element(id: u32, name: &'static str<u8, name_cache>) { "this.nodes[$id$]=document.createElement($name$);" } fn set_attribute( id: u32, name: &str<u8, name_cache>, val: impl Writable<u8>, ) { "this.nodes[$id$].setAttribute($name$,$val$);" } fn remove_child(parent: u32, child: u32) { "this.nodes[$parent$].removeChild(this.nodes[$child$]);" } fn remove_attribute(id: u32, name: &str<u8, name_cache>) { "this.nodes[$id$].removeAttribute($name$);" } fn append_child(id: u32, id2: u32) { "this.nodes[$id$].appendChild(nodes[$id2$]);" } fn insert_before(parent: u32, child: u32, marker: u32) { "this.nodes[$parent$].insertBefore(this.nodes[$child$],this.\ nodes[$marker$]);" } fn set_text(id: u32, text: impl Writable<u8>) { "this.nodes[$id$].textContent=$text$;" } fn remove(id: u32) { "this.nodes[$id$].remove();" } fn replace(id: u32, id2: u32) { "this.nodes[$id$].replaceWith(this.nodes[$id2$]);" } fn first_child(parent: u32, child: u32) { "this.nodes[$child$]=this.nodes[$parent$].firstChild;" } fn next_sibling(anchor: u32, sibling: u32) { "this.nodes[$sibling$]=this.nodes[$anchor$].nextSibling;" } fn class_list(el: u32, class_list: u32) { "this.nodes[$class_list$]=this.nodes[$el$].classList;" } fn add_class(class_list: u32, name: &str<u8, class_cache>) { "this.nodes[$class_list$].add($name$);" } fn remove_class(class_list: u32, name: &str<u8, class_cache>) { "this.nodes[$class_list$].remove($name$);" } fn set_inner_html(node: u32, html: &str) { "this.nodes[$node$].innerHTML = $html$;" } fn clone_template(tpl_node: u32, into_node: u32) { "this.nodes[$into_node$]=this.nodes[$tpl_node$].content.\ cloneNode(true);" } fn set_property(node: u32, name: &str<u8, name_cache>) { "{let jsv=this.jsvalues.dequeue();this.nodes[$node$][$name$]=jsv;}" } fn add_listener(node: u32, name: &str<u8, name_cache>) { "{let jsv=this.jsvalues.dequeue();this.nodes[$node$].\ addEventListener($name$, jsv);}" } } #[wasm_bindgen(inline_js = " export function get_node(channel, id){ return channel.nodes[id]; } export function store_node(channel, id, node){ channel.nodes[id] = node; } export function store_jsvalue(channel, value) { channel.jsvalues.enqueue(value); } ")] extern "C" { fn get_node(channel: &JSChannel, id: u32) -> Node; fn store_node(channel: &JSChannel, id: u32, node: Node); fn store_jsvalue(channel: &JSChannel, value: JsValue); } #[derive(Debug)] pub struct Sledgehammer; impl Sledgehammer { pub fn body() -> SNode { let node = SNode::new(); with(|channel| channel.store_body(node.0 .0)); node } pub fn store(node: Node) -> SNode { let snode = SNode::new(); with(|channel| store_node(channel.js_channel(), snode.0 .0, node)); snode } pub fn element(tag_name: &'static str) -> SNode { let node = SNode::new(); with(|channel| channel.create_element(node.0 .0, tag_name)); node } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct SNode(Rc<SNodeInner>); #[derive(Debug, PartialEq, Eq, Hash)] struct SNodeInner(u32); impl SNode { fn new() -> Self { let id = if let Some(id) = RECYCLE_IDS.with_borrow_mut(Vec::pop) { id } else { let new_id = NEXT_ID.get(); NEXT_ID.set(new_id + 1); new_id }; Self(Rc::new(SNodeInner(id))) } pub fn to_node(&self) -> Node { CHANNEL.with_borrow(|channel| get_node(channel.js_channel(), self.0 .0)) } } impl Drop for SNodeInner { fn drop(&mut self) { RECYCLE_IDS.with_borrow_mut(|ids| ids.push(self.0)); with(|channel| channel.drop_node(self.0)); } } impl AsRef<SNode> for SNode { fn as_ref(&self) -> &SNode { self } } impl CastFrom<SNode> for SNode { fn cast_from(source: SNode) -> Option<Self> { Some(source) } } thread_local! { static CHANNEL: RefCell<Channel> = RefCell::new(Channel::default()); static FLUSH_PENDING: Cell<bool> = const { Cell::new(false) }; static FLUSH_CLOSURE: Closure<dyn Fn()> = Closure::new(|| { FLUSH_PENDING.set(false); CHANNEL.with_borrow_mut(|channel| { channel.flush(); }); }); static NEXT_ID: Cell<u32> = const { Cell::new(1) }; static RECYCLE_IDS: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) }; pub(crate) static GLOBAL_EVENTS: RefCell<FxHashSet<Cow<'static, str>>> = Default::default(); } fn with(fun: impl FnOnce(&mut Channel)) { CHANNEL.with_borrow_mut(fun); flush(); } #[allow(unused)] // might be handy at some point! fn flush_sync() { FLUSH_PENDING.set(false); CHANNEL.with_borrow_mut(|channel| channel.flush()); } fn flush() { let was_pending = FLUSH_PENDING.replace(true); if !was_pending { FLUSH_CLOSURE.with(queueMicrotask); } } impl Renderer for Sledgehammer { type Node = SNode; type Text = SNode; type Element = SNode; type Placeholder = SNode; fn intern(text: &str) -> &str { text } fn create_text_node(text: &str) -> Self::Text { let node = SNode::new(); with(|channel| channel.create_text_node(node.0 .0, text)); node } fn create_placeholder() -> Self::Placeholder { let node = SNode::new(); with(|channel| channel.create_comment(node.0 .0)); node } fn set_text(node: &Self::Text, text: &str) { with(|channel| channel.set_text(node.0 .0, text)); } fn set_attribute(node: &Self::Element, name: &str, value: &str) { with(|channel| channel.set_attribute(node.0 .0, name, value)); } fn remove_attribute(node: &Self::Element, name: &str) { with(|channel| channel.remove_attribute(node.0 .0, name)); } fn insert_node( parent: &Self::Element, new_child: &Self::Node, anchor: Option<&Self::Node>, ) { with(|channel| { channel.insert_before( parent.0 .0, new_child.0 .0, anchor.map(|n| n.0 .0).unwrap_or(0), ) }); } fn remove_node( parent: &Self::Element, child: &Self::Node, ) -> Option<Self::Node> { with(|channel| channel.remove_child(parent.0 .0, child.0 .0)); Some(child.clone()) } fn remove(node: &Self::Node) { with(|channel| channel.remove(node.0 .0)); } fn get_parent(_node: &Self::Node) -> Option<Self::Node> { todo!() // node.parent_node() } fn first_child(node: &Self::Node) -> Option<Self::Node> { let child = SNode::new(); with(|channel| channel.first_child(node.0 .0, child.0 .0)); Some(child) } fn next_sibling(node: &Self::Node) -> Option<Self::Node> { let sibling = SNode::new(); with(|channel| channel.next_sibling(node.0 .0, sibling.0 .0)); Some(sibling) } fn log_node(_node: &Self::Node) { todo!() } fn clear_children(parent: &Self::Element) { with(|channel| channel.set_text(parent.0 .0, "")); } } #[derive(Debug, Clone)] pub struct ClassList(SNode); #[derive(Debug, Clone)] #[allow(dead_code)] // this will be used, it's just all unimplemented pub struct CssStyle(SNode); impl DomRenderer for Sledgehammer { type Event = JsValue; type ClassList = ClassList; type CssStyleDeclaration = CssStyle; type TemplateElement = SNode; fn set_property(_el: &Self::Element, _key: &str, _value: &JsValue) { todo!() } fn add_event_listener( el: &Self::Element, name: &str, cb: Box<dyn FnMut(Self::Event)>, ) -> RemoveEventHandler<Self::Element> { let cb = wasm_bindgen::closure::Closure::wrap(cb).into_js_value(); CHANNEL.with_borrow_mut(|channel| { channel.add_listener(el.0 .0, name); let channel = channel.js_channel(); store_jsvalue(channel, cb); }); // return the remover RemoveEventHandler(Box::new(move |_el| todo!())) } fn event_target<T>(_ev: &Self::Event) -> T where T: CastFrom<Self::Element>, { todo!() /*let el = ev .unchecked_ref::<Event>() .target() .expect("event.target not found") .unchecked_into::<Element>(); T::cast_from(el).expect("incorrect element type")*/ } fn add_event_listener_delegated( el: &Self::Element, name: Cow<'static, str>, delegation_key: Cow<'static, str>, cb: Box<dyn FnMut(Self::Event)>, ) -> RemoveEventHandler<Self::Element> { let cb = Closure::wrap(cb).into_js_value(); CHANNEL.with_borrow_mut(|channel| { channel.set_property(el.0 .0, &delegation_key); let channel = channel.js_channel(); store_jsvalue(channel, cb); }); GLOBAL_EVENTS.with(|global_events| { let mut events = global_events.borrow_mut(); if !events.contains(&name) { // create global handler let key = JsValue::from_str(&delegation_key); let handler = move |ev: web_sys::Event| { let target = ev.target(); let node = ev.composed_path().get(0); let mut node = if node.is_undefined() || node.is_null() { JsValue::from(target) } else { node }; // TODO reverse Shadow DOM retargetting // TODO simulate currentTarget while !node.is_null() { let node_is_disabled = js_sys::Reflect::get( &node, &JsValue::from_str("disabled"), ) .unwrap() .is_truthy(); if !node_is_disabled { let maybe_handler = js_sys::Reflect::get(&node, &key).unwrap(); if !maybe_handler.is_undefined() { let f = maybe_handler .unchecked_ref::<js_sys::Function>(); let _ = f.call1(&node, &ev); if ev.cancel_bubble() { return; } } } // navigate up tree if let Some(parent) = node.unchecked_ref::<web_sys::Node>().parent_node() { node = parent.into() } else if let Some(root) = node.dyn_ref::<web_sys::ShadowRoot>() { node = root.host().unchecked_into(); } else { node = JsValue::null() } } }; let handler = Box::new(handler) as Box<dyn FnMut(web_sys::Event)>; let handler = Closure::wrap(handler).into_js_value(); window() .add_event_listener_with_callback( &name, handler.unchecked_ref(), ) .unwrap(); // register that we've created handler events.insert(name); } }); // return the remover RemoveEventHandler(Box::new(move |_el| todo!())) } fn class_list(el: &Self::Element) -> Self::ClassList { let class_list = SNode::new(); with(|channel| channel.class_list(el.0 .0, class_list.0 .0)); ClassList(class_list) } fn add_class(list: &Self::ClassList, name: &str) { with(|channel| channel.add_class(list.0 .0 .0, name)); } fn remove_class(list: &Self::ClassList, name: &str) { with(|channel| channel.remove_class(list.0 .0 .0, name)); } fn style(_el: &Self::Element) -> Self::CssStyleDeclaration { todo!() //el.unchecked_ref::<HtmlElement>().style() } fn set_css_property( _style: &Self::CssStyleDeclaration, _name: &str, _value: &str, ) { todo!() /*or_debug!( style.set_property(name, value), style.unchecked_ref(), "setProperty" );*/ } fn set_inner_html(el: &Self::Element, html: &str) { with(|channel| channel.set_inner_html(el.0 .0, html)) } fn get_template<V>() -> Self::TemplateElement where V: ToTemplate + 'static, { thread_local! { static TEMPLATES: RefCell<LinearMap<TypeId, SNode>> = Default::default(); } TEMPLATES.with(|t| { t.borrow_mut() .entry(TypeId::of::<V>()) .or_insert_with(|| { let mut buf = String::new(); V::to_template( &mut buf, &mut String::new(), &mut String::new(), &mut String::new(), &mut Default::default(), ); let node = SNode::new(); with(|channel| { channel.create_element(node.0 .0, "template"); channel.set_inner_html(node.0 .0, &buf) }); node }) .clone() }) } fn clone_template(tpl: &Self::TemplateElement) -> Self::Element { let node = SNode::new(); with(|channel| { channel.clone_template(tpl.0 .0, node.0 .0); }); node } fn create_element_from_html(_html: &str) -> Self::Element { todo!() } } impl Mountable<Sledgehammer> for SNode { fn unmount(&mut self) { with(|channel| channel.remove(self.0 .0)); } fn mount(&mut self, parent: &SNode, marker: Option<&SNode>) { Sledgehammer::insert_node(parent, self, marker); } fn insert_before_this( &self, _child: &mut dyn Mountable<Sledgehammer>, ) -> bool { todo!() } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/renderer/mod.rs
tachys/src/renderer/mod.rs
use crate::view::{Mountable, ToTemplate}; use std::{borrow::Cow, fmt::Debug, marker::PhantomData}; use wasm_bindgen::JsValue; /// A DOM renderer. pub mod dom; /// The renderer being used for the application. /// /// ### Note /// This was designed to be included as a generic on view types, to support different rendering /// backends using the same view tree structure. However, adding the number of generics that was /// required to make this work caused catastrophic compile times and linker errors on larger /// applications, so this "generic rendering" approach was removed before 0.7.0 release. /// /// It is possible that we will try a different approach to achieve the same functionality in the /// future, so to the extent possible the rest of the crate tries to stick to using /// [`Renderer`]. /// methods rather than directly manipulating the DOM inline. pub type Rndr = dom::Dom; /// Types used by the renderer. /// /// See [`Rndr`] for additional information on this rendering approach. pub mod types { pub use super::dom::{ ClassList, CssStyleDeclaration, Element, Event, Node, Placeholder, TemplateElement, Text, }; } /* #[cfg(feature = "testing")] /// A renderer based on a mock DOM. pub mod mock_dom; /// A DOM renderer optimized for element creation. #[cfg(feature = "sledgehammer")] pub mod sledgehammer; */ /// Implements the instructions necessary to render an interface on some platform. /// /// By default, this is implemented for the Document Object Model (DOM) in a Web /// browser, but implementing this trait for some other platform allows you to use /// the library to render any tree-based UI. pub trait Renderer: Send + Sized + Debug + 'static { /// The basic type of node in the view tree. type Node: Mountable + Clone + 'static; /// A visible element in the view tree. type Element: AsRef<Self::Node> + CastFrom<Self::Node> + Mountable + Clone + 'static; /// A text node in the view tree. type Text: AsRef<Self::Node> + CastFrom<Self::Node> + Mountable + Clone + 'static; /// A placeholder node, which can be inserted into the tree but does not /// appear (e.g., a comment node in the DOM). type Placeholder: AsRef<Self::Node> + CastFrom<Self::Node> + Mountable + Clone + 'static; /// Interns a string slice, if that is available on this platform and useful as an optimization. fn intern(text: &str) -> &str; /// Creates a new text node. fn create_text_node(text: &str) -> Self::Text; /// Creates a new placeholder node. fn create_placeholder() -> Self::Placeholder; /// Sets the text content of the node. If it's not a text node, this does nothing. fn set_text(node: &Self::Text, text: &str); /// Sets the given attribute on the given node by key and value. fn set_attribute(node: &Self::Element, name: &str, value: &str); /// Removes the given attribute on the given node. fn remove_attribute(node: &Self::Element, name: &str); /// Appends the new child to the parent, before the anchor node. If `anchor` is `None`, /// append to the end of the parent's children. fn insert_node( parent: &Self::Element, new_child: &Self::Node, marker: Option<&Self::Node>, ); /// Removes the child node from the parents, and returns the removed node. fn remove_node( parent: &Self::Element, child: &Self::Node, ) -> Option<Self::Node>; /// Removes all children from the parent element. fn clear_children(parent: &Self::Element); /// Removes the node. fn remove(node: &Self::Node); /// Gets the parent of the given node, if any. fn get_parent(node: &Self::Node) -> Option<Self::Node>; /// Returns the first child node of the given node, if any. fn first_child(node: &Self::Node) -> Option<Self::Node>; /// Returns the next sibling of the given node, if any. fn next_sibling(node: &Self::Node) -> Option<Self::Node>; /// Logs the given node in a platform-appropriate way. fn log_node(node: &Self::Node); } /// A function that can be called to remove an event handler from an element after it has been added. #[must_use = "This will invalidate the event handler when it is dropped. You \ should store it in some other data structure to clean it up \ later to avoid dropping it immediately, or leak it with \ std::mem::forget() to never drop it."] #[allow(clippy::type_complexity)] pub struct RemoveEventHandler<T>( Option<Box<dyn FnOnce() + Send + Sync>>, // only here to keep the generic, removing which would be a breaking change // TODO remove generic in 0.9 PhantomData<fn() -> T>, ); impl<T> RemoveEventHandler<T> { /// Creates a new container with a function that will be called when it is dropped. pub(crate) fn new(remove: impl FnOnce() + Send + Sync + 'static) -> Self { Self(Some(Box::new(remove)), PhantomData) } #[allow(clippy::type_complexity)] pub(crate) fn into_inner( mut self, ) -> Option<Box<dyn FnOnce() + Send + Sync>> { self.0.take() } } impl<T> Drop for RemoveEventHandler<T> { fn drop(&mut self) { if let Some(cb) = self.0.take() { cb() } } } /// Additional rendering behavior that applies only to DOM nodes. pub trait DomRenderer: Renderer { /// Generic event type, from which any specific event can be converted. type Event; /// The list of CSS classes for an element. type ClassList: Clone + 'static; /// The CSS styles for an element. type CssStyleDeclaration: Clone + 'static; /// The type of a `<template>` element. type TemplateElement; /// Sets a JavaScript object property on a DOM element. fn set_property(el: &Self::Element, key: &str, value: &JsValue); /// Adds an event listener to an element. /// /// Returns a function to remove the listener. fn add_event_listener( el: &Self::Element, name: &str, cb: Box<dyn FnMut(Self::Event)>, ) -> RemoveEventHandler<Self::Element>; /// Adds an event listener to an element, delegated to the window if possible. /// /// Returns a function to remove the listener. fn add_event_listener_delegated( el: &Self::Element, name: Cow<'static, str>, delegation_key: Cow<'static, str>, cb: Box<dyn FnMut(Self::Event)>, ) -> RemoveEventHandler<Self::Element>; /// Return the `event.target`, cast to the given type. fn event_target<T>(ev: &Self::Event) -> T where T: CastFrom<Self::Element>; /// The list of CSS classes for an element. fn class_list(el: &Self::Element) -> Self::ClassList; /// Add a class to the list. fn add_class(class_list: &Self::ClassList, name: &str); /// Remove a class from the list. fn remove_class(class_list: &Self::ClassList, name: &str); /// The set of styles for an element. fn style(el: &Self::Element) -> Self::CssStyleDeclaration; /// Sets a CSS property. fn set_css_property( style: &Self::CssStyleDeclaration, name: &str, value: &str, ); /// Sets the `innerHTML` of a DOM element, without escaping any values. fn set_inner_html(el: &Self::Element, html: &str); /// Returns a cached template element created from the given type. fn get_template<V>() -> Self::TemplateElement where V: ToTemplate + 'static; /// Deeply clones a template. fn clone_template(tpl: &Self::TemplateElement) -> Self::Element; /// Creates a single element from a string of HTML. fn create_element_from_html(html: &str) -> Self::Element; } /// Attempts to cast from one type to another. /// /// This works in a similar way to `TryFrom`. We implement it as a separate trait /// simply so we don't have to create wrappers for the `web_sys` types; it can't be /// implemented on them directly because of the orphan rules. pub trait CastFrom<T> where Self: Sized, { /// Casts a node from one type to another. fn cast_from(source: T) -> Option<Self>; }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/renderer/dom.rs
tachys/src/renderer/dom.rs
#![allow(missing_docs)] //! See [`Renderer`](crate::renderer::Renderer) and [`Rndr`](crate::renderer::Rndr) for additional information. use super::{CastFrom, RemoveEventHandler}; use crate::{ dom::{document, window}, ok_or_debug, or_debug, view::{Mountable, ToTemplate}, }; use linear_map::LinearMap; use rustc_hash::FxHashSet; use std::{ any::TypeId, borrow::Cow, cell::{LazyCell, RefCell}, }; use wasm_bindgen::{intern, prelude::Closure, JsCast, JsValue}; use web_sys::{AddEventListenerOptions, Comment, HtmlTemplateElement}; /// A [`Renderer`](crate::renderer::Renderer) that uses `web-sys` to manipulate DOM elements in the browser. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Dom; thread_local! { pub(crate) static GLOBAL_EVENTS: RefCell<FxHashSet<Cow<'static, str>>> = Default::default(); pub static TEMPLATE_CACHE: RefCell<Vec<(Cow<'static, str>, web_sys::Element)>> = Default::default(); } pub type Node = web_sys::Node; pub type Text = web_sys::Text; pub type Element = web_sys::Element; pub type Placeholder = web_sys::Comment; pub type Event = wasm_bindgen::JsValue; pub type ClassList = web_sys::DomTokenList; pub type CssStyleDeclaration = web_sys::CssStyleDeclaration; pub type TemplateElement = web_sys::HtmlTemplateElement; /// A microtask is a short function which will run after the current task has /// completed its work and when there is no other code waiting to be run before /// control of the execution context is returned to the browser's event loop. /// /// Microtasks are especially useful for libraries and frameworks that need /// to perform final cleanup or other just-before-rendering tasks. /// /// [MDN queueMicrotask](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) pub fn queue_microtask(task: impl FnOnce() + 'static) { use js_sys::{Function, Reflect}; let task = Closure::once_into_js(task); let window = window(); let queue_microtask = Reflect::get(&window, &JsValue::from_str("queueMicrotask")) .expect("queueMicrotask not available"); let queue_microtask = queue_microtask.unchecked_into::<Function>(); _ = queue_microtask.call1(&JsValue::UNDEFINED, &task); } fn queue(fun: Box<dyn FnOnce()>) { use std::cell::{Cell, RefCell}; thread_local! { static PENDING: Cell<bool> = const { Cell::new(false) }; static QUEUE: RefCell<Vec<Box<dyn FnOnce()>>> = RefCell::new(Vec::new()); } QUEUE.with_borrow_mut(|q| q.push(fun)); if !PENDING.replace(true) { queue_microtask(|| { let tasks = QUEUE.take(); for task in tasks { task(); } PENDING.set(false); }) } } impl Dom { pub fn intern(text: &str) -> &str { intern(text) } pub fn create_element(tag: &str, namespace: Option<&str>) -> Element { if let Some(namespace) = namespace { document() .create_element_ns( Some(Self::intern(namespace)), Self::intern(tag), ) .unwrap() } else { document().create_element(Self::intern(tag)).unwrap() } } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn create_text_node(text: &str) -> Text { document().create_text_node(text) } pub fn create_placeholder() -> Placeholder { thread_local! { static COMMENT: LazyCell<Comment> = LazyCell::new(|| { document().create_comment("") }); } COMMENT.with(|n| n.clone_node().unwrap().unchecked_into()) } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn set_text(node: &Text, text: &str) { node.set_node_value(Some(text)); } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn set_attribute(node: &Element, name: &str, value: &str) { or_debug!(node.set_attribute(name, value), node, "setAttribute"); } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn remove_attribute(node: &Element, name: &str) { or_debug!(node.remove_attribute(name), node, "removeAttribute"); } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn insert_node( parent: &Element, new_child: &Node, anchor: Option<&Node>, ) { ok_or_debug!( parent.insert_before(new_child, anchor), parent, "insertNode" ); } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn try_insert_node( parent: &Element, new_child: &Node, anchor: Option<&Node>, ) -> bool { parent.insert_before(new_child, anchor).is_ok() } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn remove_node(parent: &Element, child: &Node) -> Option<Node> { ok_or_debug!(parent.remove_child(child), parent, "removeNode") } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn remove(node: &Node) { node.unchecked_ref::<Element>().remove(); } pub fn get_parent(node: &Node) -> Option<Node> { node.parent_node() } pub fn first_child(node: &Node) -> Option<Node> { #[cfg(debug_assertions)] { let node = node.first_child(); // if it's a comment node that starts with hot-reload, it's a marker that should be // ignored if let Some(node) = node.as_ref() { if node.node_type() == 8 && node .text_content() .unwrap_or_default() .starts_with("hot-reload") { return Self::next_sibling(node); } } node } #[cfg(not(debug_assertions))] { node.first_child() } } pub fn next_sibling(node: &Node) -> Option<Node> { #[cfg(debug_assertions)] { let node = node.next_sibling(); // if it's a comment node that starts with hot-reload, it's a marker that should be // ignored if let Some(node) = node.as_ref() { if node.node_type() == 8 && node .text_content() .unwrap_or_default() .starts_with("hot-reload") { return Self::next_sibling(node); } } node } #[cfg(not(debug_assertions))] { node.next_sibling() } } pub fn log_node(node: &Node) { web_sys::console::log_1(node); } #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace"))] pub fn clear_children(parent: &Element) { parent.set_text_content(Some("")); } /// Mounts the new child before the marker as its sibling. /// /// ## Panics /// The default implementation panics if `before` does not have a parent [`crate::renderer::types::Element`]. pub fn mount_before<M>(new_child: &mut M, before: &Node) where M: Mountable, { let parent = Element::cast_from( Self::get_parent(before).expect("could not find parent element"), ) .expect("placeholder parent should be Element"); new_child.mount(&parent, Some(before)); } /// Tries to mount the new child before the marker as its sibling. /// /// Returns `false` if the child did not have a valid parent. #[track_caller] pub fn try_mount_before<M>(new_child: &mut M, before: &Node) -> bool where M: Mountable, { if let Some(parent) = Self::get_parent(before).and_then(Element::cast_from) { new_child.mount(&parent, Some(before)); true } else { false } } pub fn set_property_or_value(el: &Element, key: &str, value: &JsValue) { if key == "value" { queue(Box::new({ let el = el.clone(); let value = value.clone(); move || { Self::set_property(&el, "value", &value); } })) } else { Self::set_property(el, key, value); } } pub fn set_property(el: &Element, key: &str, value: &JsValue) { or_debug!( js_sys::Reflect::set( el, &wasm_bindgen::JsValue::from_str(key), value, ), el, "setProperty" ); } pub fn add_event_listener( el: &Element, name: &str, cb: Box<dyn FnMut(Event)>, ) -> RemoveEventHandler<Element> { let cb = wasm_bindgen::closure::Closure::wrap(cb); let name = intern(name); or_debug!( el.add_event_listener_with_callback( name, cb.as_ref().unchecked_ref() ), el, "addEventListener" ); // return the remover RemoveEventHandler::new({ let name = name.to_owned(); let el = el.clone(); // safe to construct this here, because it will only run in the browser // so it will always be accessed or dropped from the main thread let cb = send_wrapper::SendWrapper::new(move || { or_debug!( el.remove_event_listener_with_callback( intern(&name), cb.as_ref().unchecked_ref() ), &el, "removeEventListener" ) }); move || cb() }) } pub fn add_event_listener_use_capture( el: &Element, name: &str, cb: Box<dyn FnMut(Event)>, ) -> RemoveEventHandler<Element> { let cb = wasm_bindgen::closure::Closure::wrap(cb); let name = intern(name); let options = AddEventListenerOptions::new(); options.set_capture(true); or_debug!( el.add_event_listener_with_callback_and_add_event_listener_options( name, cb.as_ref().unchecked_ref(), &options ), el, "addEventListenerUseCapture" ); // return the remover RemoveEventHandler::new({ let name = name.to_owned(); let el = el.clone(); // safe to construct this here, because it will only run in the browser // so it will always be accessed or dropped from the main thread let cb = send_wrapper::SendWrapper::new(move || { or_debug!( el.remove_event_listener_with_callback_and_bool( intern(&name), cb.as_ref().unchecked_ref(), true ), &el, "removeEventListener" ) }); move || cb() }) } pub fn event_target<T>(ev: &Event) -> T where T: CastFrom<Element>, { let el = ev .unchecked_ref::<web_sys::Event>() .target() .expect("event.target not found") .unchecked_into::<Element>(); T::cast_from(el).expect("incorrect element type") } pub fn add_event_listener_delegated( el: &Element, name: Cow<'static, str>, delegation_key: Cow<'static, str>, cb: Box<dyn FnMut(Event)>, ) -> RemoveEventHandler<Element> { let cb = Closure::wrap(cb); let key = intern(&delegation_key); or_debug!( js_sys::Reflect::set(el, &JsValue::from_str(key), cb.as_ref()), el, "set property" ); GLOBAL_EVENTS.with(|global_events| { let mut events = global_events.borrow_mut(); if !events.contains(&name) { // create global handler let key = JsValue::from_str(key); let handler = move |ev: web_sys::Event| { let target = ev.target(); let node = ev.composed_path().get(0); let mut node = if node.is_undefined() || node.is_null() { JsValue::from(target) } else { node }; // TODO reverse Shadow DOM retargetting // TODO simulate currentTarget while !node.is_null() { let node_is_disabled = js_sys::Reflect::get( &node, &JsValue::from_str("disabled"), ) .unwrap() .is_truthy(); if !node_is_disabled { let maybe_handler = js_sys::Reflect::get(&node, &key).unwrap(); if !maybe_handler.is_undefined() { let f = maybe_handler .unchecked_ref::<js_sys::Function>(); let _ = f.call1(&node, &ev); if ev.cancel_bubble() { return; } } } // navigate up tree if let Some(parent) = node.unchecked_ref::<web_sys::Node>().parent_node() { node = parent.into() } else if let Some(root) = node.dyn_ref::<web_sys::ShadowRoot>() { node = root.host().unchecked_into(); } else { node = JsValue::null() } } }; let handler = Box::new(handler) as Box<dyn FnMut(web_sys::Event)>; let handler = Closure::wrap(handler).into_js_value(); window() .add_event_listener_with_callback( &name, handler.unchecked_ref(), ) .unwrap(); // register that we've created handler events.insert(name); } }); // return the remover RemoveEventHandler::new({ let key = key.to_owned(); let el = el.clone(); // safe to construct this here, because it will only run in the browser // so it will always be accessed or dropped from the main thread let el_cb = send_wrapper::SendWrapper::new((el, cb)); move || { let (el, cb) = el_cb.take(); drop(cb); or_debug!( js_sys::Reflect::delete_property( &el, &JsValue::from_str(&key) ), &el, "delete property" ); } }) } pub fn class_list(el: &Element) -> ClassList { el.class_list() } pub fn add_class(list: &ClassList, name: &str) { or_debug!(list.add_1(name), list.unchecked_ref(), "add()"); } pub fn remove_class(list: &ClassList, name: &str) { or_debug!(list.remove_1(name), list.unchecked_ref(), "remove()"); } pub fn style(el: &Element) -> CssStyleDeclaration { el.unchecked_ref::<web_sys::HtmlElement>().style() } pub fn set_css_property( style: &CssStyleDeclaration, name: &str, value: &str, ) { or_debug!( style.set_property(name, value), style.unchecked_ref(), "setProperty" ); } pub fn remove_css_property(style: &CssStyleDeclaration, name: &str) { or_debug!( style.remove_property(name), style.unchecked_ref(), "removeProperty" ); } pub fn set_inner_html(el: &Element, html: &str) { el.set_inner_html(html); } pub fn get_template<V>() -> TemplateElement where V: ToTemplate + 'static, { thread_local! { static TEMPLATE_ELEMENT: LazyCell<HtmlTemplateElement> = LazyCell::new(|| document().create_element(Dom::intern("template")).unwrap().unchecked_into()); static TEMPLATES: RefCell<LinearMap<TypeId, HtmlTemplateElement>> = Default::default(); } TEMPLATES.with(|t| { t.borrow_mut() .entry(TypeId::of::<V>()) .or_insert_with(|| { let tpl = TEMPLATE_ELEMENT.with(|t| { t.clone_node() .unwrap() .unchecked_into::<HtmlTemplateElement>() }); let mut buf = String::new(); V::to_template( &mut buf, &mut String::new(), &mut String::new(), &mut String::new(), &mut Default::default(), ); tpl.set_inner_html(&buf); tpl }) .clone() }) } pub fn clone_template(tpl: &TemplateElement) -> Element { tpl.content() .clone_node_with_deep(true) .unwrap() .unchecked_into() } pub fn create_element_from_html(html: Cow<'static, str>) -> Element { let tpl = TEMPLATE_CACHE.with(|cache| { let mut cache = cache.borrow_mut(); if let Some(tpl_content) = cache.iter().find_map(|(key, tpl)| { (html == *key) .then_some(Self::clone_template(tpl.unchecked_ref())) }) { tpl_content } else { let tpl = document() .create_element(Self::intern("template")) .unwrap(); tpl.set_inner_html(&html); let tpl_content = Self::clone_template(tpl.unchecked_ref()); cache.push((html, tpl)); tpl_content } }); tpl.first_element_child().unwrap_or(tpl) } pub fn create_svg_element_from_html(html: Cow<'static, str>) -> Element { let tpl = TEMPLATE_CACHE.with(|cache| { let mut cache = cache.borrow_mut(); if let Some(tpl_content) = cache.iter().find_map(|(key, tpl)| { (html == *key) .then_some(Self::clone_template(tpl.unchecked_ref())) }) { tpl_content } else { let tpl = document() .create_element(Self::intern("template")) .unwrap(); let svg = document() .create_element_ns( Some(Self::intern("http://www.w3.org/2000/svg")), Self::intern("svg"), ) .unwrap(); let g = document() .create_element_ns( Some(Self::intern("http://www.w3.org/2000/svg")), Self::intern("g"), ) .unwrap(); g.set_inner_html(&html); svg.append_child(&g).unwrap(); tpl.unchecked_ref::<TemplateElement>() .content() .append_child(&svg) .unwrap(); let tpl_content = Self::clone_template(tpl.unchecked_ref()); cache.push((html, tpl)); tpl_content } }); let svg = tpl.first_element_child().unwrap(); svg.first_element_child().unwrap_or(svg) } } impl Mountable for Node { fn unmount(&mut self) { todo!() } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { Dom::insert_node(parent, self, marker); } fn try_mount(&mut self, parent: &Element, marker: Option<&Node>) -> bool { Dom::try_insert_node(parent, self, marker) } fn insert_before_this(&self, child: &mut dyn Mountable) -> bool { let parent = Dom::get_parent(self).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self)); return true; } false } fn elements(&self) -> Vec<crate::renderer::types::Element> { vec![] } } impl Mountable for Text { fn unmount(&mut self) { self.remove(); } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { Dom::insert_node(parent, self, marker); } fn try_mount(&mut self, parent: &Element, marker: Option<&Node>) -> bool { Dom::try_insert_node(parent, self, marker) } fn insert_before_this(&self, child: &mut dyn Mountable) -> bool { let parent = Dom::get_parent(self.as_ref()).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self)); return true; } false } fn elements(&self) -> Vec<crate::renderer::types::Element> { vec![] } } impl Mountable for Comment { fn unmount(&mut self) { self.remove(); } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { Dom::insert_node(parent, self, marker); } fn try_mount(&mut self, parent: &Element, marker: Option<&Node>) -> bool { Dom::try_insert_node(parent, self, marker) } fn insert_before_this(&self, child: &mut dyn Mountable) -> bool { let parent = Dom::get_parent(self.as_ref()).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self)); return true; } false } fn elements(&self) -> Vec<crate::renderer::types::Element> { vec![] } } impl Mountable for Element { fn unmount(&mut self) { self.remove(); } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { Dom::insert_node(parent, self, marker); } fn insert_before_this(&self, child: &mut dyn Mountable) -> bool { let parent = Dom::get_parent(self.as_ref()).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self)); return true; } false } fn elements(&self) -> Vec<crate::renderer::types::Element> { vec![self.clone()] } } impl CastFrom<Node> for Text { fn cast_from(node: Node) -> Option<Text> { node.clone().dyn_into().ok() } } impl CastFrom<Node> for Comment { fn cast_from(node: Node) -> Option<Comment> { node.clone().dyn_into().ok() } } impl CastFrom<Node> for Element { fn cast_from(node: Node) -> Option<Element> { node.clone().dyn_into().ok() } } impl<T> CastFrom<JsValue> for T where T: JsCast, { fn cast_from(source: JsValue) -> Option<Self> { source.dyn_into::<T>().ok() } } impl<T> CastFrom<Element> for T where T: JsCast, { fn cast_from(source: Element) -> Option<Self> { source.dyn_into::<T>().ok() } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/renderer/mock_dom.rs
tachys/src/renderer/mock_dom.rs
#![allow(unused)] //! A stupidly-simple mock DOM implementation that can be used for testing. //! //! Do not use this for anything real. use super::{CastFrom, DomRenderer, RemoveEventHandler, Renderer}; use crate::{ html::element::{CreateElement, ElementType}, view::Mountable, }; use indexmap::IndexMap; use slotmap::{new_key_type, SlotMap}; use std::{borrow::Cow, cell::RefCell, rc::Rc}; use wasm_bindgen::JsValue; /// A [`Renderer`] that uses a mock DOM structure running in Rust code. /// /// This is intended as a rendering background that can be used to test component logic, without /// running a browser. #[derive(Debug)] pub struct MockDom; new_key_type! { /// A unique identifier for a mock DOM node. pub struct NodeId; } /// A mock DOM node. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Node(NodeId); /// A mock element. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Element(Node); /// A mock text node. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Text(Node); /// A mock comment node. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Placeholder(Node); impl AsRef<Node> for Node { fn as_ref(&self) -> &Node { self } } impl AsRef<Node> for Element { fn as_ref(&self) -> &Node { &self.0 } } impl AsRef<Node> for Text { fn as_ref(&self) -> &Node { &self.0 } } impl AsRef<Node> for Placeholder { fn as_ref(&self) -> &Node { &self.0 } } /// Tests whether two nodes are references to the same underlying node. pub fn node_eq(a: impl AsRef<Node>, b: impl AsRef<Node>) -> bool { a.as_ref() == b.as_ref() } impl From<Text> for Node { fn from(value: Text) -> Self { Node(value.0 .0) } } impl From<Element> for Node { fn from(value: Element) -> Self { Node(value.0 .0) } } impl From<Placeholder> for Node { fn from(value: Placeholder) -> Self { Node(value.0 .0) } } impl Element { /// Outputs an HTML form of the element, for testing and debugging purposes. pub fn to_debug_html(&self) -> String { let mut buf = String::new(); self.debug_html(&mut buf); buf } } /// The DOM data associated with a particular node. #[derive(Debug, PartialEq, Eq)] pub struct NodeData { /// The node's parent. pub parent: Option<NodeId>, /// The node itself. pub ty: NodeType, } trait DebugHtml { fn debug_html(&self, buf: &mut String); } impl DebugHtml for Element { fn debug_html(&self, buf: &mut String) { Document::with_node(self.0 .0, |node| { node.debug_html(buf); }); } } impl DebugHtml for Text { fn debug_html(&self, buf: &mut String) { Document::with_node(self.0 .0, |node| { node.debug_html(buf); }); } } impl DebugHtml for Node { fn debug_html(&self, buf: &mut String) { Document::with_node(self.0, |node| { node.debug_html(buf); }); } } impl DebugHtml for NodeData { fn debug_html(&self, buf: &mut String) { match &self.ty { NodeType::Text(text) => buf.push_str(text), NodeType::Element { tag, attrs, children, } => { buf.push('<'); buf.push_str(tag); for (k, v) in attrs { buf.push(' '); buf.push_str(k); buf.push_str("=\""); buf.push_str(v); buf.push('"'); } buf.push('>'); for child in children { child.debug_html(buf); } buf.push_str("</"); buf.push_str(tag); buf.push('>'); } NodeType::Placeholder => buf.push_str("<!>"), } } } /// The mock DOM document. #[derive(Clone)] pub struct Document(Rc<RefCell<SlotMap<NodeId, NodeData>>>); impl Document { /// Creates a new document. pub fn new() -> Self { Document(Default::default()) } fn with_node<U>(id: NodeId, f: impl FnOnce(&NodeData) -> U) -> Option<U> { DOCUMENT.with(|d| { let data = d.0.borrow(); let data = data.get(id); data.map(f) }) } fn with_node_mut<U>( id: NodeId, f: impl FnOnce(&mut NodeData) -> U, ) -> Option<U> { DOCUMENT.with(|d| { let mut data = d.0.borrow_mut(); let data = data.get_mut(id); data.map(f) }) } /// Resets the document's contents. pub fn reset(&self) { self.0.borrow_mut().clear(); } fn create_element(&self, tag: &str) -> Element { Element(Node(self.0.borrow_mut().insert(NodeData { parent: None, ty: NodeType::Element { tag: tag.to_string().into(), attrs: IndexMap::new(), children: Vec::new(), }, }))) } fn create_text_node(&self, data: &str) -> Text { Text(Node(self.0.borrow_mut().insert(NodeData { parent: None, ty: NodeType::Text(data.to_string()), }))) } fn create_placeholder(&self) -> Placeholder { Placeholder(Node(self.0.borrow_mut().insert(NodeData { parent: None, ty: NodeType::Placeholder, }))) } } // TODO! impl DomRenderer for MockDom { type Event = (); type ClassList = (); type CssStyleDeclaration = (); type TemplateElement = (); fn set_property(el: &Self::Element, key: &str, value: &JsValue) { todo!() } fn add_event_listener( el: &Self::Element, name: &str, cb: Box<dyn FnMut(Self::Event)>, ) -> RemoveEventHandler<Self::Element> { todo!() } fn add_event_listener_delegated( el: &Self::Element, name: Cow<'static, str>, delegation_key: Cow<'static, str>, cb: Box<dyn FnMut(Self::Event)>, ) -> RemoveEventHandler<Self::Element> { todo!() } fn class_list(el: &Self::Element) -> Self::ClassList { todo!() } fn add_class(class_list: &Self::ClassList, name: &str) { todo!() } fn remove_class(class_list: &Self::ClassList, name: &str) { todo!() } fn style(el: &Self::Element) -> Self::CssStyleDeclaration { todo!() } fn set_css_property( style: &Self::CssStyleDeclaration, name: &str, value: &str, ) { todo!() } fn set_inner_html(el: &Self::Element, html: &str) { todo!() } fn event_target<T>(ev: &Self::Event) -> T where T: CastFrom<Self::Element>, { todo!() } fn get_template<V>() -> Self::TemplateElement where V: crate::view::ToTemplate + 'static, { todo!() } fn clone_template(tpl: &Self::TemplateElement) -> Self::Element { todo!() } fn create_element_from_html(html: &str) -> Self::Element { todo!() } } impl Default for Document { fn default() -> Self { Self::new() } } thread_local! { static DOCUMENT: Document = Document::new(); } /// Returns the global document. pub fn document() -> Document { DOCUMENT.with(Clone::clone) } /// The type of mock DOM node. #[derive(Debug, PartialEq, Eq)] pub enum NodeType { /// A text node. Text(String), /// An element. Element { /// The HTML tag name. tag: Cow<'static, str>, /// The attributes. attrs: IndexMap<String, String>, /// The element's children. children: Vec<Node>, }, /// A placeholder. Placeholder, } impl Mountable<MockDom> for Node { fn unmount(&mut self) { todo!() } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { MockDom::insert_node(parent, self, marker); } fn insert_before_this(&self, child: &mut dyn Mountable<MockDom>) -> bool { let parent = MockDom::get_parent(self).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self)); return true; } false } } impl Mountable<MockDom> for Text { fn unmount(&mut self) { todo!() } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { MockDom::insert_node(parent, self.as_ref(), marker); } fn insert_before_this(&self, child: &mut dyn Mountable<MockDom>) -> bool { let parent = MockDom::get_parent(self.as_ref()).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self.as_ref())); return true; } false } } impl Mountable<MockDom> for Element { fn unmount(&mut self) { todo!() } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { MockDom::insert_node(parent, self.as_ref(), marker); } fn insert_before_this(&self, child: &mut dyn Mountable<MockDom>) -> bool { let parent = MockDom::get_parent(self.as_ref()).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self.as_ref())); return true; } false } } impl Mountable<MockDom> for Placeholder { fn unmount(&mut self) { todo!() } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { MockDom::insert_node(parent, self.as_ref(), marker); } fn insert_before_this(&self, child: &mut dyn Mountable<MockDom>) -> bool { let parent = MockDom::get_parent(self.as_ref()).and_then(Element::cast_from); if let Some(parent) = parent { child.mount(&parent, Some(self.as_ref())); return true; } false } } impl<E: ElementType> CreateElement<MockDom> for E { fn create_element(&self) -> crate::renderer::types::Element { document().create_element(E::TAG) } } impl Renderer for MockDom { type Node = Node; type Text = Text; type Element = Element; type Placeholder = Placeholder; fn intern(text: &str) -> &str { text } fn create_text_node(data: &str) -> Self::Text { document().create_text_node(data) } fn create_placeholder() -> Self::Placeholder { document().create_placeholder() } fn set_text(node: &Self::Text, text: &str) { Document::with_node_mut(node.0 .0, |node| { if let NodeType::Text(ref mut node) = node.ty { *node = text.to_string(); } }); } fn set_attribute(node: &Self::Element, name: &str, value: &str) { Document::with_node_mut(node.0 .0, |node| { if let NodeType::Element { ref mut attrs, .. } = node.ty { attrs.insert(name.to_string(), value.to_string()); } }); } fn remove_attribute(node: &Self::Element, name: &str) { Document::with_node_mut(node.0 .0, |node| { if let NodeType::Element { ref mut attrs, .. } = node.ty { attrs.shift_remove(name); } }); } fn insert_node( parent: &Self::Element, new_child: &Self::Node, anchor: Option<&Self::Node>, ) { debug_assert!(&parent.0 != new_child); // remove if already mounted if let Some(parent) = MockDom::get_parent(new_child) { let parent = Element(parent); MockDom::remove_node(&parent, new_child); } // mount on new parent Document::with_node_mut(parent.0 .0, |parent| { if let NodeType::Element { ref mut children, .. } = parent.ty { match anchor { None => children.push(new_child.clone()), Some(anchor) => { let anchor_pos = children .iter() .position(|item| item.0 == anchor.0) .expect("anchor is not a child of the parent"); children.insert(anchor_pos, new_child.clone()); } } } else { panic!("parent is not an element"); } }); // set parent on child node Document::with_node_mut(new_child.0, |node| { node.parent = Some(parent.0 .0) }); } fn remove_node( parent: &Self::Element, child: &Self::Node, ) -> Option<Self::Node> { let child = Document::with_node_mut(parent.0 .0, |parent| { if let NodeType::Element { ref mut children, .. } = parent.ty { let current_pos = children .iter() .position(|item| item.0 == child.0) .expect("anchor is not a child of the parent"); Some(children.remove(current_pos)) } else { None } }) .flatten()?; Document::with_node_mut(child.0, |node| { node.parent = None; }); Some(child) } fn remove(node: &Self::Node) { let parent = Element(Node( Self::get_parent(node) .expect("tried to remove a parentless node") .0, )); Self::remove_node(&parent, node); } fn get_parent(node: &Self::Node) -> Option<Self::Node> { Document::with_node(node.0, |node| node.parent) .flatten() .map(Node) } fn first_child(node: &Self::Node) -> Option<Self::Node> { Document::with_node(node.0, |node| match &node.ty { NodeType::Text(_) => None, NodeType::Element { children, .. } => children.first().cloned(), NodeType::Placeholder => None, }) .flatten() } fn next_sibling(node: &Self::Node) -> Option<Self::Node> { let node_id = node.0; Document::with_node(node_id, |node| { node.parent.and_then(|parent| { Document::with_node(parent, |parent| match &parent.ty { NodeType::Element { children, .. } => { let this = children .iter() .position(|check| check == &Node(node_id))?; children.get(this + 1).cloned() } _ => panic!( "Called next_sibling with parent as a node that's not \ an Element." ), }) }) }) .flatten() .flatten() } fn log_node(node: &Self::Node) { eprintln!("{node:?}"); } fn clear_children(parent: &Self::Element) { let prev_children = Document::with_node_mut(parent.0 .0, |node| match node.ty { NodeType::Element { ref mut children, .. } => std::mem::take(children), _ => panic!("Called clear_children on a non-Element node."), }) .unwrap_or_default(); for child in prev_children { Document::with_node_mut(child.0, |node| { node.parent = None; }); } } } impl CastFrom<Node> for Text { fn cast_from(source: Node) -> Option<Self> { Document::with_node(source.0, |node| { matches!(node.ty, NodeType::Text(_)) }) .and_then(|matches| matches.then_some(Text(Node(source.0)))) } } impl CastFrom<Node> for Element { fn cast_from(source: Node) -> Option<Self> { Document::with_node(source.0, |node| { matches!(node.ty, NodeType::Element { .. }) }) .and_then(|matches| matches.then_some(Element(Node(source.0)))) } } impl CastFrom<Node> for Placeholder { fn cast_from(source: Node) -> Option<Self> { Document::with_node(source.0, |node| { matches!(node.ty, NodeType::Placeholder) }) .and_then(|matches| matches.then_some(Placeholder(Node(source.0)))) } } #[cfg(test)] mod tests { use super::MockDom; use crate::{ html::element, renderer::{mock_dom::node_eq, Renderer}, }; #[test] fn html_debugging_works() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); MockDom::set_attribute(&p, "id", "foo"); let text = MockDom::create_text_node("Hello, world!"); MockDom::insert_node(&main, p.as_ref(), None); MockDom::insert_node(&p, text.as_ref(), None); assert_eq!( main.to_debug_html(), "<main><p id=\"foo\">Hello, world!</p></main>" ); } #[test] fn remove_attribute_works() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); MockDom::set_attribute(&p, "id", "foo"); let text = MockDom::create_text_node("Hello, world!"); MockDom::insert_node(&main, p.as_ref(), None); MockDom::insert_node(&p, text.as_ref(), None); MockDom::remove_attribute(&p, "id"); assert_eq!(main.to_debug_html(), "<main><p>Hello, world!</p></main>"); } #[test] fn remove_node_works() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); MockDom::set_attribute(&p, "id", "foo"); let text = MockDom::create_text_node("Hello, world!"); MockDom::insert_node(&main, p.as_ref(), None); MockDom::insert_node(&p, text.as_ref(), None); MockDom::remove_node(&main, p.as_ref()); assert_eq!(main.to_debug_html(), "<main></main>"); } #[test] fn insert_before_works() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); let span = MockDom::create_element(element::Span); let text = MockDom::create_text_node("Hello, world!"); MockDom::insert_node(&main, p.as_ref(), None); MockDom::insert_node(&span, text.as_ref(), None); MockDom::insert_node(&main, span.as_ref(), Some(p.as_ref())); assert_eq!( main.to_debug_html(), "<main><span>Hello, world!</span><p></p></main>" ); } #[test] fn insert_before_sets_parent() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); MockDom::insert_node(&main, p.as_ref(), None); let parent = MockDom::get_parent(p.as_ref()).expect("p should have parent set"); assert!(node_eq(parent, main)); } #[test] fn insert_before_moves_node() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); let span = MockDom::create_element(element::Span); let text = MockDom::create_text_node("Hello, world!"); MockDom::insert_node(&main, p.as_ref(), None); MockDom::insert_node(&span, text.as_ref(), None); MockDom::insert_node(&main, span.as_ref(), Some(p.as_ref())); MockDom::insert_node(&main, p.as_ref(), Some(span.as_ref())); assert_eq!( main.to_debug_html(), "<main><p></p><span>Hello, world!</span></main>" ); } #[test] fn first_child_gets_first_child() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); let span = MockDom::create_element(element::Span); MockDom::insert_node(&main, p.as_ref(), None); MockDom::insert_node(&p, span.as_ref(), None); assert_eq!( MockDom::first_child(main.as_ref()).as_ref(), Some(p.as_ref()) ); assert_eq!( MockDom::first_child(&MockDom::first_child(main.as_ref()).unwrap()) .as_ref(), Some(span.as_ref()) ); } #[test] fn next_sibling_gets_next_sibling() { let main = MockDom::create_element(element::Main); let p = MockDom::create_element(element::P); let span = MockDom::create_element(element::Span); let text = MockDom::create_text_node("foo"); MockDom::insert_node(&main, p.as_ref(), None); MockDom::insert_node(&main, span.as_ref(), None); MockDom::insert_node(&main, text.as_ref(), None); assert_eq!( MockDom::next_sibling(p.as_ref()).as_ref(), Some(span.as_ref()) ); assert_eq!( MockDom::next_sibling(span.as_ref()).as_ref(), Some(text.as_ref()) ); } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/ssr/mod.rs
tachys/src/ssr/mod.rs
use crate::{ html::attribute::any_attribute::AnyAttribute, view::{Position, RenderHtml}, }; use futures::Stream; use std::{ collections::VecDeque, fmt::{Debug, Write}, future::Future, mem, pin::Pin, sync::Arc, task::{Context, Poll}, }; /// Manages streaming HTML rendering for the response to a single request. #[derive(Default)] pub struct StreamBuilder { pub(crate) sync_buf: String, pub(crate) chunks: VecDeque<StreamChunk>, pending: Option<ChunkFuture>, pending_ooo: VecDeque<PinnedFuture<OooChunk>>, id: Option<Vec<u16>>, } type PinnedFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>; type ChunkFuture = PinnedFuture<VecDeque<StreamChunk>>; impl StreamBuilder { /// Creates a new HTML stream. pub fn new(id: Option<Vec<u16>>) -> Self { Self::with_capacity(0, id) } /// Creates a new stream with a given capacity in the synchronous buffer and an identifier. pub fn with_capacity(capacity: usize, id: Option<Vec<u16>>) -> Self { Self { id, sync_buf: String::with_capacity(capacity), ..Default::default() } } /// Reserves additional space in the synchronous buffer. pub fn reserve(&mut self, additional: usize) { self.sync_buf.reserve(additional); } /// Pushes text into the synchronous buffer. pub fn push_sync(&mut self, string: &str) { self.sync_buf.push_str(string); } /// Pushes an async block into the stream. pub fn push_async( &mut self, fut: impl Future<Output = VecDeque<StreamChunk>> + Send + 'static, ) { // flush sync chunk let sync = mem::take(&mut self.sync_buf); if !sync.is_empty() { self.chunks.push_back(StreamChunk::Sync(sync)); } self.chunks.push_back(StreamChunk::Async { chunks: Box::pin(fut) as PinnedFuture<VecDeque<StreamChunk>>, }); } /// Mutates the synchronous buffer. pub fn with_buf(&mut self, fun: impl FnOnce(&mut String)) { fun(&mut self.sync_buf) } /// Takes all chunks currently available in the stream, including the synchronous buffer. pub fn take_chunks(&mut self) -> VecDeque<StreamChunk> { let sync = mem::take(&mut self.sync_buf); if !sync.is_empty() { self.chunks.push_back(StreamChunk::Sync(sync)); } mem::take(&mut self.chunks) } /// Appends another stream to this one. pub fn append(&mut self, mut other: StreamBuilder) { if !self.sync_buf.is_empty() { self.chunks .push_back(StreamChunk::Sync(mem::take(&mut self.sync_buf))); } self.chunks.append(&mut other.chunks); self.sync_buf.push_str(&other.sync_buf); } /// Completes the stream. pub fn finish(mut self) -> Self { let sync_buf_remaining = mem::take(&mut self.sync_buf); if sync_buf_remaining.is_empty() { return self; } else if let Some(StreamChunk::Sync(buf)) = self.chunks.back_mut() { buf.push_str(&sync_buf_remaining); } else { self.chunks.push_back(StreamChunk::Sync(sync_buf_remaining)); } self } // Out-of-Order Streaming /// Pushes a fallback for out-of-order streaming. pub fn push_fallback<View>( &mut self, fallback: View, position: &mut Position, mark_branches: bool, extra_attrs: Vec<AnyAttribute>, ) where View: RenderHtml, { self.write_chunk_marker(true); fallback.to_html_with_buf( &mut self.sync_buf, position, true, mark_branches, extra_attrs, ); self.write_chunk_marker(false); *position = Position::NextChild; } /// Increments the chunk ID. pub fn next_id(&mut self) { if let Some(last) = self.id.as_mut().and_then(|ids| ids.last_mut()) { *last += 1; } } /// Returns the current ID. pub fn clone_id(&self) -> Option<Vec<u16>> { self.id.clone() } /// Returns an ID that is a child of the current one. pub fn child_id(&self) -> Option<Vec<u16>> { let mut child = self.id.clone(); if let Some(child) = child.as_mut() { child.push(0); } child } /// Inserts a marker for the current out-of-order chunk. pub fn write_chunk_marker(&mut self, opening: bool) { if let Some(id) = &self.id { self.sync_buf.reserve(11 + (id.len() * 2)); self.sync_buf.push_str("<!--s-"); for piece in id { write!(&mut self.sync_buf, "{piece}-").unwrap(); } if opening { self.sync_buf.push_str("o-->"); } else { self.sync_buf.push_str("c-->"); } } } /// Injects an out-of-order chunk into the stream. pub fn push_async_out_of_order<View>( &mut self, view: impl Future<Output = Option<View>> + Send + 'static, position: &mut Position, mark_branches: bool, extra_attrs: Vec<AnyAttribute>, ) where View: RenderHtml, { self.push_async_out_of_order_with_nonce( view, position, mark_branches, None, extra_attrs, ); } /// Injects an out-of-order chunk into the stream, using the given nonce for `<script>` tags. pub fn push_async_out_of_order_with_nonce<View>( &mut self, view: impl Future<Output = Option<View>> + Send + 'static, position: &mut Position, mark_branches: bool, nonce: Option<Arc<str>>, extra_attrs: Vec<AnyAttribute>, ) where View: RenderHtml, { let id = self.clone_id(); // copy so it's not updated by additional iterations // i.e., restart in the same position we were at when we suspended let mut position = *position; self.chunks.push_back(StreamChunk::OutOfOrder { chunks: Box::pin(async move { let view = view.await; let mut subbuilder = StreamBuilder::new(id); let mut id = String::new(); if let Some(ids) = &subbuilder.id { for piece in ids { write!(&mut id, "{piece}-").unwrap(); } } if let Some(id) = subbuilder.id.as_mut() { id.push(0); } let replace = view.is_some(); view.to_html_async_with_buf::<true>( &mut subbuilder, &mut position, true, mark_branches, extra_attrs, ); let chunks = subbuilder.finish().take_chunks(); let mut flattened_chunks = VecDeque::with_capacity(chunks.len()); for chunk in chunks { // this will wait for any ErrorBoundary async nodes and flatten them out if let StreamChunk::Async { chunks } = chunk { flattened_chunks.extend(chunks.await); } else { flattened_chunks.push_back(chunk); } } OooChunk { id, chunks: flattened_chunks, replace, nonce, } }), }); } } impl Debug for StreamBuilder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("StreamBuilderInner") .field("sync_buf", &self.sync_buf) .field("chunks", &self.chunks) .field("pending", &self.pending.is_some()) .finish() } } /// A chunk of the HTML stream. pub enum StreamChunk { /// Some synchronously-available HTML. Sync(String), /// The chunk can be rendered asynchronously in order. Async { /// A collection of in-order chunks. chunks: PinnedFuture<VecDeque<StreamChunk>>, }, /// The chunk can be rendered asynchronously out of order. OutOfOrder { /// A collection of out-of-order chunks chunks: PinnedFuture<OooChunk>, }, } /// A chunk of the out-of-order stream. #[derive(Debug)] pub struct OooChunk { id: String, chunks: VecDeque<StreamChunk>, replace: bool, nonce: Option<Arc<str>>, } impl OooChunk { /// Pushes an opening `<template>` tag into the buffer. pub fn push_start(id: &str, buf: &mut String) { buf.push_str("<template id=\""); buf.push_str(id); buf.push('f'); buf.push_str("\">"); } /// Pushes a closing `</template>` and update script into the buffer. pub fn push_end(replace: bool, id: &str, buf: &mut String) { Self::push_end_with_nonce(replace, id, buf, None); } /// Pushes a closing `</template>` and update script with the given nonce into the buffer. pub fn push_end_with_nonce( replace: bool, id: &str, buf: &mut String, nonce: Option<&str>, ) { buf.push_str("</template>"); if let Some(nonce) = nonce { buf.push_str("<script nonce=\""); buf.push_str(nonce); buf.push_str(r#"">(function() { let id = ""#); } else { buf.push_str(r#"<script>(function() { let id = ""#); } buf.push_str(id); buf.push_str( "\";let open = undefined;let close = undefined;let walker = \ document.createTreeWalker(document.body, \ NodeFilter.SHOW_COMMENT);while(walker.nextNode()) \ {if(walker.currentNode.textContent == `s-${id}o`){ \ open=walker.currentNode; } else \ if(walker.currentNode.textContent == `s-${id}c`) { close = \ walker.currentNode;}}let range = new Range(); \ range.setStartBefore(open); range.setEndBefore(close);", ); if replace { buf.push_str( "range.deleteContents(); let tpl = \ document.getElementById(`${id}f`); \ close.parentNode.insertBefore(tpl.content.cloneNode(true), \ close);close.remove();", ); } else { buf.push_str("close.remove();open.remove();"); } buf.push_str("})()</script>"); } /// Consumes this structure and returns its inner chunks of the stream. pub fn take_chunks(self) -> VecDeque<StreamChunk> { self.chunks } } impl Debug for StreamChunk { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Sync(arg0) => f.debug_tuple("Sync").field(arg0).finish(), Self::Async { .. } => { f.debug_struct("Async").finish_non_exhaustive() } Self::OutOfOrder { .. } => { f.debug_struct("OutOfOrder").finish_non_exhaustive() } } } } impl Stream for StreamBuilder { type Item = String; fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { let mut this = self.as_mut(); let pending = this.pending.take(); if let Some(mut pending) = pending { match pending.as_mut().poll(cx) { Poll::Pending => { this.pending = Some(pending); Poll::Pending } Poll::Ready(chunks) => { for chunk in chunks.into_iter().rev() { this.chunks.push_front(chunk); } self.poll_next(cx) } } } else { let next_chunk = this.chunks.pop_front(); match next_chunk { None => { if this.pending_ooo.is_empty() { if this.sync_buf.is_empty() { Poll::Ready(None) } else { Poll::Ready(Some(mem::take(&mut this.sync_buf))) } } else { // check if *any* pending out-of-order chunk is ready for mut chunk in mem::take(&mut this.pending_ooo) { match chunk.as_mut().poll(cx) { Poll::Ready(OooChunk { id, chunks, replace, nonce, }) => { let opening = format!("<!--s-{id}o-->"); let placeholder_at = this.sync_buf.find(&opening); if let Some(start) = placeholder_at { let closing = format!("<!--s-{id}c-->"); let end = this .sync_buf .find(&closing) .unwrap(); let chunks_iter = chunks.into_iter().rev(); // TODO can probably make this more efficient let (before, replaced) = this.sync_buf.split_at(start); let (_, after) = replaced.split_at( end - start + closing.len(), ); let mut buf = String::new(); buf.push_str(before); let mut held_chunks = VecDeque::new(); for chunk in chunks_iter { if let StreamChunk::Sync(ready) = chunk { buf.push_str(&ready); } else { held_chunks.push_front(chunk); } } buf.push_str(after); this.sync_buf = buf; for chunk in held_chunks { this.chunks.push_front(chunk); } } else { OooChunk::push_start( &id, &mut this.sync_buf, ); for chunk in chunks.into_iter().rev() { if let StreamChunk::Sync(ready) = chunk { this.sync_buf.push_str(&ready); } else { this.chunks.push_front(chunk); } } OooChunk::push_end_with_nonce( replace, &id, &mut this.sync_buf, nonce.as_deref(), ); } } Poll::Pending => { this.pending_ooo.push_back(chunk); } } } if this.sync_buf.is_empty() { Poll::Pending } else { Poll::Ready(Some(mem::take(&mut this.sync_buf))) } } } Some(StreamChunk::Sync(value)) => { this.sync_buf.push_str(&value); loop { match this.chunks.pop_front() { None => break, Some(StreamChunk::Async { chunks }) => { this.chunks .push_front(StreamChunk::Async { chunks }); break; } Some(StreamChunk::OutOfOrder { chunks, .. }) => { this.pending_ooo.push_back(chunks); break; } Some(StreamChunk::Sync(next)) => { this.sync_buf.push_str(&next); } } } this.poll_next(cx) } Some(StreamChunk::Async { chunks, .. }) => { this.pending = Some(chunks); if this.sync_buf.is_empty() { self.poll_next(cx) } else { Poll::Ready(Some(mem::take(&mut this.sync_buf))) } } Some(StreamChunk::OutOfOrder { chunks, .. }) => { this.pending_ooo.push_back(chunks); if this.sync_buf.is_empty() { self.poll_next(cx) } else { Poll::Ready(Some(mem::take(&mut this.sync_buf))) } } } } } } /* #[cfg(test)] mod tests { use crate::{ async_views::{FutureViewExt, Suspend}, html::element::{em, main, p, ElementChild, HtmlElement, Main}, renderer::dom::Dom, view::RenderHtml, }; use futures::StreamExt; use std::time::Duration; use tokio::time::sleep; #[tokio::test] async fn in_order_stream_of_sync_content_ready_immediately() { let el: HtmlElement<Main, _, _, Dom> = main().child(p().child(( "Hello, ", em().child("beautiful"), " world!", ))); let mut stream = el.to_html_stream_in_order(); let html = stream.next().await.unwrap(); assert_eq!( html, "<main><p>Hello, <em>beautiful</em> world!</p></main>" ); } #[tokio::test] async fn in_order_single_async_block_in_stream() { let el = async { sleep(Duration::from_millis(250)).await; "Suspended" } .suspend(); let mut stream = <Suspend<false, _, _> as RenderHtml<Dom>>::to_html_stream_in_order( el, ); let html = stream.next().await.unwrap(); assert_eq!(html, "Suspended<!>"); } #[tokio::test] async fn in_order_async_with_siblings_in_stream() { let el = ( "Before Suspense", async { sleep(Duration::from_millis(250)).await; "Suspended" } .suspend(), ); let mut stream = <(&str, Suspend<false, _, _>) as RenderHtml<Dom>>::to_html_stream_in_order( el, ); assert_eq!(stream.next().await.unwrap(), "Before Suspense"); assert_eq!(stream.next().await.unwrap(), "<!>Suspended"); assert!(stream.next().await.is_none()); } #[tokio::test] async fn in_order_async_inside_element_in_stream() { let el: HtmlElement<_, _, _, Dom> = p().child(( "Before Suspense", async { sleep(Duration::from_millis(250)).await; "Suspended" } .suspend(), )); let mut stream = el.to_html_stream_in_order(); assert_eq!(stream.next().await.unwrap(), "<p>Before Suspense"); assert_eq!(stream.next().await.unwrap(), "<!>Suspended</p>"); assert!(stream.next().await.is_none()); } #[tokio::test] async fn in_order_nested_async_blocks() { let el: HtmlElement<_, _, _, Dom> = main().child(( "Before Suspense", async { sleep(Duration::from_millis(250)).await; p().child(( "Before inner Suspense", async { sleep(Duration::from_millis(250)).await; "Inner Suspense" } .suspend(), )) } .suspend(), )); let mut stream = el.to_html_stream_in_order(); assert_eq!(stream.next().await.unwrap(), "<main>Before Suspense"); assert_eq!(stream.next().await.unwrap(), "<p>Before inner Suspense"); assert_eq!( stream.next().await.unwrap(), "<!>Inner Suspense</p></main>" ); } #[tokio::test] async fn out_of_order_stream_of_sync_content_ready_immediately() { let el: HtmlElement<Main, _, _, Dom> = main().child(p().child(( "Hello, ", em().child("beautiful"), " world!", ))); let mut stream = el.to_html_stream_out_of_order(); let html = stream.next().await.unwrap(); assert_eq!( html, "<main><p>Hello, <em>beautiful</em> world!</p></main>" ); } #[tokio::test] async fn out_of_order_single_async_block_in_stream() { let el = async { sleep(Duration::from_millis(250)).await; "Suspended" } .suspend() .with_fallback("Loading..."); let mut stream = <Suspend<false, _, _> as RenderHtml<Dom>>::to_html_stream_out_of_order( el, ); assert_eq!( stream.next().await.unwrap(), "<!--s-1-o-->Loading...<!--s-1-c-->" ); assert_eq!( stream.next().await.unwrap(), "<template id=\"1-f\">Suspended</template><script>(function() { \ let id = \"1-\";let open = undefined;let close = undefined;let \ walker = document.createTreeWalker(document.body, \ NodeFilter.SHOW_COMMENT);while(walker.nextNode()) \ {if(walker.currentNode.textContent == `s-${id}o`){ \ open=walker.currentNode; } else \ if(walker.currentNode.textContent == `s-${id}c`) { close = \ walker.currentNode;}}let range = new Range(); \ range.setStartAfter(open); range.setEndBefore(close); \ range.deleteContents(); let tpl = \ document.getElementById(`${id}f`); \ close.parentNode.insertBefore(tpl.content.cloneNode(true), \ close);})()</script>" ); } #[tokio::test] async fn out_of_order_inside_element_in_stream() { let el: HtmlElement<_, _, _, Dom> = p().child(( "Before Suspense", async { sleep(Duration::from_millis(250)).await; "Suspended" } .suspend() .with_fallback("Loading..."), "After Suspense", )); let mut stream = el.to_html_stream_out_of_order(); assert_eq!( stream.next().await.unwrap(), "<p>Before Suspense<!--s-1-o--><!>Loading...<!--s-1-c-->After \ Suspense</p>" ); assert!(stream.next().await.unwrap().contains("Suspended")); assert!(stream.next().await.is_none()); } #[tokio::test] async fn out_of_order_nested_async_blocks() { let el: HtmlElement<_, _, _, Dom> = main().child(( "Before Suspense", async { sleep(Duration::from_millis(250)).await; p().child(( "Before inner Suspense", async { sleep(Duration::from_millis(250)).await; "Inner Suspense" } .suspend() .with_fallback("Loading Inner..."), "After inner Suspense", )) } .suspend() .with_fallback("Loading..."), "After Suspense", )); let mut stream = el.to_html_stream_out_of_order(); assert_eq!( stream.next().await.unwrap(), "<main>Before Suspense<!--s-1-o--><!>Loading...<!--s-1-c-->After \ Suspense</main>" ); let loading_inner = stream.next().await.unwrap(); assert!(loading_inner.contains( "<p>Before inner Suspense<!--s-1-1-o--><!>Loading \ Inner...<!--s-1-1-c-->After inner Suspense</p>" )); assert!(loading_inner.contains("let id = \"1-\";")); let inner = stream.next().await.unwrap(); assert!(inner.contains("Inner Suspense")); assert!(inner.contains("let id = \"1-1-\";")); assert!(stream.next().await.is_none()); } } */
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/mathml/mod.rs
tachys/src/mathml/mod.rs
use crate::{ html::{ attribute::{Attr, Attribute, AttributeValue, NextAttribute}, element::{ElementType, ElementWithChildren, HtmlElement}, }, view::Render, }; use std::fmt::Debug; macro_rules! mathml_global { ($tag:ty, $attr:ty) => { paste::paste! { /// A MathML attribute. pub fn $attr<V>(self, value: V) -> HtmlElement < [<$tag:camel>], <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>, Ch > where V: AttributeValue, At: NextAttribute, <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>: Attribute, { let HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes } = self; HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes: attributes.add_any_attr($crate::html::attribute::$attr(value)), } } } } } macro_rules! mathml_elements { ($($tag:ident [$($attr:ty),*]),* $(,)?) => { paste::paste! { $( // `tag()` function /// A MathML element. #[track_caller] pub fn $tag() -> HtmlElement<[<$tag:camel>], (), ()> where { HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: std::panic::Location::caller(), tag: [<$tag:camel>], attributes: (), children: (), } } /// A MathML element. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct [<$tag:camel>]; impl<At, Ch> HtmlElement<[<$tag:camel>], At, Ch> where At: Attribute, Ch: Render, { mathml_global!($tag, displaystyle); mathml_global!($tag, href); mathml_global!($tag, id); mathml_global!($tag, mathbackground); mathml_global!($tag, mathcolor); mathml_global!($tag, mathsize); mathml_global!($tag, mathvariant); mathml_global!($tag, scriptlevel); $( /// A MathML attribute. pub fn $attr<V>(self, value: V) -> HtmlElement < [<$tag:camel>], <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>, Ch > where V: AttributeValue, At: NextAttribute, <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>: Attribute, { let HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes } = self; HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes: attributes.add_any_attr($crate::html::attribute::$attr(value)), } } )* } impl ElementType for [<$tag:camel>] { type Output = web_sys::Element; const TAG: &'static str = stringify!($tag); const SELF_CLOSING: bool = false; const ESCAPE_CHILDREN: bool = true; const NAMESPACE: Option<&'static str> = Some("http://www.w3.org/1998/Math/MathML"); #[inline(always)] fn tag(&self) -> &str { Self::TAG } } impl ElementWithChildren for [<$tag:camel>] {} )* } } } mathml_elements![ math [display, xmlns], mi [], mn [], mo [ accent, fence, lspace, maxsize, minsize, movablelimits, rspace, separator, stretchy, symmetric, form ], ms [], mspace [height, width], mtext [], menclose [notation], merror [], mfenced [], mfrac [linethickness], mpadded [depth, height, voffset, width], mphantom [], mroot [], mrow [], msqrt [], mstyle [], mmultiscripts [], mover [accent], mprescripts [], msub [], msubsup [], msup [], munder [accentunder], munderover [accent, accentunder], mtable [ align, columnalign, columnlines, columnspacing, frame, framespacing, rowalign, rowlines, rowspacing, width ], mtd [columnalign, columnspan, rowalign, rowspan], mtr [columnalign, rowalign], maction [], annotation [], semantics [], ];
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/event.rs
tachys/src/html/event.rs
use crate::{ html::attribute::{ maybe_next_attr_erasure_macros::next_attr_combine, Attribute, NamedAttributeKey, }, renderer::{CastFrom, RemoveEventHandler, Rndr}, view::{Position, ToTemplate}, }; use send_wrapper::SendWrapper; use std::{ borrow::Cow, cell::RefCell, fmt::Debug, marker::PhantomData, ops::{Deref, DerefMut}, rc::Rc, }; use wasm_bindgen::convert::FromWasmAbi; /// A cloneable event callback. pub type SharedEventCallback<E> = Rc<RefCell<dyn FnMut(E)>>; /// A function that can be called in response to an event. pub trait EventCallback<E>: 'static { /// Runs the event handler. fn invoke(&mut self, event: E); /// Converts this into a cloneable/shared event handler. fn into_shared(self) -> SharedEventCallback<E>; } impl<E: 'static> EventCallback<E> for SharedEventCallback<E> { fn invoke(&mut self, event: E) { let mut fun = self.borrow_mut(); fun(event) } fn into_shared(self) -> SharedEventCallback<E> { self } } impl<F, E> EventCallback<E> for F where F: FnMut(E) + 'static, { fn invoke(&mut self, event: E) { self(event) } fn into_shared(self) -> SharedEventCallback<E> { Rc::new(RefCell::new(self)) } } /// An event listener with a typed event target. pub struct Targeted<E, T> { event: E, el_ty: PhantomData<T>, } impl<E, T> Targeted<E, T> { /// Returns the inner event. pub fn into_inner(self) -> E { self.event } /// Returns the event's target, as an HTML element of the correct type. pub fn target(&self) -> T where T: CastFrom<crate::renderer::types::Element>, crate::renderer::types::Event: From<E>, E: Clone, { let ev = crate::renderer::types::Event::from(self.event.clone()); Rndr::event_target(&ev) } } impl<E, T> Deref for Targeted<E, T> { type Target = E; fn deref(&self) -> &Self::Target { &self.event } } impl<E, T> DerefMut for Targeted<E, T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.event } } impl<E, T> From<E> for Targeted<E, T> { fn from(event: E) -> Self { Targeted { event, el_ty: PhantomData, } } } /// Creates an [`Attribute`] that will add an event listener to an element. pub fn on<E, F>(event: E, cb: F) -> On<E, F> where F: FnMut(E::EventType) + 'static, E: EventDescriptor + Send + 'static, E::EventType: 'static, E::EventType: From<crate::renderer::types::Event>, { On { event, #[cfg(feature = "reactive_graph")] owner: reactive_graph::owner::Owner::current().unwrap_or_default(), cb: (!cfg!(feature = "ssr")).then(|| SendWrapper::new(cb)), } } /// Creates an [`Attribute`] that will add an event listener with a typed target to an element. #[allow(clippy::type_complexity)] pub fn on_target<E, T, F>( event: E, mut cb: F, ) -> On<E, Box<dyn FnMut(E::EventType)>> where T: HasElementType, F: FnMut(Targeted<E::EventType, <T as HasElementType>::ElementType>) + 'static, E: EventDescriptor + Send + 'static, E::EventType: 'static, E::EventType: From<crate::renderer::types::Event>, { on(event, Box::new(move |ev: E::EventType| cb(ev.into()))) } /// An [`Attribute`] that adds an event listener to an element. pub struct On<E, F> { event: E, #[cfg(feature = "reactive_graph")] owner: reactive_graph::owner::Owner, cb: Option<SendWrapper<F>>, } impl<E, F> Clone for On<E, F> where E: Clone, F: Clone, { fn clone(&self) -> Self { Self { event: self.event.clone(), #[cfg(feature = "reactive_graph")] owner: self.owner.clone(), cb: self.cb.clone(), } } } impl<E, F> On<E, F> where F: EventCallback<E::EventType>, E: EventDescriptor + Send + 'static, E::EventType: 'static, E::EventType: From<crate::renderer::types::Event>, { /// Attaches the event listener to the element. pub fn attach( self, el: &crate::renderer::types::Element, ) -> RemoveEventHandler<crate::renderer::types::Element> { fn attach_inner( el: &crate::renderer::types::Element, cb: Box<dyn FnMut(crate::renderer::types::Event)>, name: Cow<'static, str>, // TODO investigate: does passing this as an option // (rather than, say, having a const DELEGATED: bool) // add to binary size? delegation_key: Option<Cow<'static, str>>, ) -> RemoveEventHandler<crate::renderer::types::Element> { match delegation_key { None => Rndr::add_event_listener(el, &name, cb), Some(key) => { Rndr::add_event_listener_delegated(el, name, key, cb) } } } let mut cb = self.cb.expect("callback removed before attaching").take(); #[cfg(feature = "tracing")] let span = tracing::Span::current(); let cb = Box::new(move |ev: crate::renderer::types::Event| { #[cfg(all(debug_assertions, feature = "reactive_graph"))] let _rx_guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter(); #[cfg(feature = "tracing")] let _tracing_guard = span.enter(); let ev = E::EventType::from(ev); #[cfg(feature = "reactive_graph")] self.owner.with(|| cb.invoke(ev)); #[cfg(not(feature = "reactive_graph"))] cb.invoke(ev); }) as Box<dyn FnMut(crate::renderer::types::Event)>; attach_inner( el, cb, self.event.name(), (E::BUBBLES && cfg!(feature = "delegation")) .then(|| self.event.event_delegation_key()), ) } /// Attaches the event listener to the element as a listener that is triggered during the capture phase, /// meaning it will fire before any event listeners further down in the DOM. pub fn attach_capture( self, el: &crate::renderer::types::Element, ) -> RemoveEventHandler<crate::renderer::types::Element> { fn attach_inner( el: &crate::renderer::types::Element, cb: Box<dyn FnMut(crate::renderer::types::Event)>, name: Cow<'static, str>, ) -> RemoveEventHandler<crate::renderer::types::Element> { Rndr::add_event_listener_use_capture(el, &name, cb) } let mut cb = self.cb.expect("callback removed before attaching").take(); #[cfg(feature = "tracing")] let span = tracing::Span::current(); let cb = Box::new(move |ev: crate::renderer::types::Event| { #[cfg(all(debug_assertions, feature = "reactive_graph"))] let _rx_guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter(); #[cfg(feature = "tracing")] let _tracing_guard = span.enter(); let ev = E::EventType::from(ev); #[cfg(feature = "reactive_graph")] self.owner.with(|| cb.invoke(ev)); #[cfg(not(feature = "reactive_graph"))] cb.invoke(ev); }) as Box<dyn FnMut(crate::renderer::types::Event)>; attach_inner(el, cb, self.event.name()) } } impl<E, F> Debug for On<E, F> where E: Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("On").field(&self.event).finish() } } impl<E, F> Attribute for On<E, F> where F: EventCallback<E::EventType>, E: EventDescriptor + Send + 'static, E::EventType: 'static, E::EventType: From<crate::renderer::types::Event>, { const MIN_LENGTH: usize = 0; type AsyncOutput = Self; // a function that can be called once to remove the event listener type State = ( crate::renderer::types::Element, Option<RemoveEventHandler<crate::renderer::types::Element>>, ); type Cloneable = On<E, SharedEventCallback<E::EventType>>; type CloneableOwned = On<E, SharedEventCallback<E::EventType>>; #[inline(always)] fn html_len(&self) -> usize { 0 } #[inline(always)] fn to_html( self, _buf: &mut String, _class: &mut String, _style: &mut String, _inner_html: &mut String, ) { } #[inline(always)] fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { let cleanup = if E::CAPTURE { self.attach_capture(el) } else { self.attach(el) }; (el.clone(), Some(cleanup)) } #[inline(always)] fn build(self, el: &crate::renderer::types::Element) -> Self::State { let cleanup = if E::CAPTURE { self.attach_capture(el) } else { self.attach(el) }; (el.clone(), Some(cleanup)) } #[inline(always)] fn rebuild(self, state: &mut Self::State) { let (el, prev_cleanup) = state; if let Some(prev) = prev_cleanup.take() { if let Some(remove) = prev.into_inner() { remove(); } } *prev_cleanup = Some(if E::CAPTURE { self.attach_capture(el) } else { self.attach(el) }); } fn into_cloneable(self) -> Self::Cloneable { On { cb: self.cb.map(|cb| SendWrapper::new(cb.take().into_shared())), #[cfg(feature = "reactive_graph")] owner: self.owner, event: self.event, } } fn into_cloneable_owned(self) -> Self::CloneableOwned { On { cb: self.cb.map(|cb| SendWrapper::new(cb.take().into_shared())), #[cfg(feature = "reactive_graph")] owner: self.owner, event: self.event, } } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn keys(&self) -> Vec<NamedAttributeKey> { vec![] } } impl<E, F> NextAttribute for On<E, F> where F: EventCallback<E::EventType>, E: EventDescriptor + Send + 'static, E::EventType: 'static, E::EventType: From<crate::renderer::types::Event>, { next_attr_output_type!(Self, NewAttr); fn add_any_attr<NewAttr: Attribute>( self, new_attr: NewAttr, ) -> Self::Output<NewAttr> { next_attr_combine!(self, new_attr) } } impl<E, F> ToTemplate for On<E, F> { #[inline(always)] fn to_template( _buf: &mut String, _class: &mut String, _style: &mut String, _inner_html: &mut String, _position: &mut Position, ) { } } /// A trait for converting types into [web_sys events](web_sys). pub trait EventDescriptor: Clone { /// The [`web_sys`] event type, such as [`web_sys::MouseEvent`]. type EventType: FromWasmAbi; /// Indicates if this event bubbles. For example, `click` bubbles, /// but `focus` does not. /// /// If this is true, then the event will be delegated globally if the `delegation` /// feature is enabled. Otherwise, event listeners will be directly attached to the element. const BUBBLES: bool; /// Indicates if this event should be handled during the capture phase. const CAPTURE: bool = false; /// The name of the event, such as `click` or `mouseover`. fn name(&self) -> Cow<'static, str>; /// The key used for event delegation. fn event_delegation_key(&self) -> Cow<'static, str>; /// Return the options for this type. This is only used when you create a [`Custom`] event /// handler. #[inline(always)] fn options(&self) -> Option<&web_sys::AddEventListenerOptions> { None } } /// A wrapper that tells the framework to handle an event during the capture phase. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Capture<E> { inner: E, } /// Wraps an event to indicate that it should be handled during the capture phase. pub fn capture<E>(event: E) -> Capture<E> { Capture { inner: event } } impl<E: EventDescriptor> EventDescriptor for Capture<E> { type EventType = E::EventType; const CAPTURE: bool = true; const BUBBLES: bool = E::BUBBLES; fn name(&self) -> Cow<'static, str> { self.inner.name() } fn event_delegation_key(&self) -> Cow<'static, str> { self.inner.event_delegation_key() } } /// A custom event. #[derive(Debug)] pub struct Custom<E: FromWasmAbi = web_sys::Event> { name: Cow<'static, str>, options: Option<SendWrapper<web_sys::AddEventListenerOptions>>, _event_type: PhantomData<fn() -> E>, } impl<E: FromWasmAbi> Clone for Custom<E> { fn clone(&self) -> Self { Self { name: self.name.clone(), options: self.options.clone(), _event_type: PhantomData, } } } impl<E: FromWasmAbi> EventDescriptor for Custom<E> { type EventType = E; fn name(&self) -> Cow<'static, str> { self.name.clone() } fn event_delegation_key(&self) -> Cow<'static, str> { format!("$$${}", self.name).into() } const BUBBLES: bool = false; #[inline(always)] fn options(&self) -> Option<&web_sys::AddEventListenerOptions> { self.options.as_deref() } } impl<E: FromWasmAbi> Custom<E> { /// Creates a custom event type that can be used within /// [`OnAttribute::on`](crate::prelude::OnAttribute::on), for events /// which are not covered in the [`ev`](crate::html::event) module. pub fn new(name: impl Into<Cow<'static, str>>) -> Self { Self { name: name.into(), options: None, _event_type: PhantomData, } } /// Modify the [`AddEventListenerOptions`] used for this event listener. /// /// ```rust /// # use tachys::prelude::*; /// # use tachys::html; /// # use tachys::html::event as ev; /// # fn custom_event() -> impl Render { /// let mut non_passive_wheel = ev::Custom::new("wheel"); /// non_passive_wheel.options_mut().set_passive(false); /// /// let canvas = /// html::element::canvas().on(non_passive_wheel, |e: ev::WheelEvent| { /// // handle event /// }); /// # canvas /// # } /// ``` /// /// [`AddEventListenerOptions`]: web_sys::AddEventListenerOptions pub fn options_mut(&mut self) -> &mut web_sys::AddEventListenerOptions { // It is valid to construct a `SendWrapper` here because // its inner data will only be accessed in the browser's main thread. self.options.get_or_insert_with(|| { SendWrapper::new(web_sys::AddEventListenerOptions::new()) }) } } macro_rules! generate_event_types { {$( $( #[$does_not_bubble:ident] )? $( $event:ident )+ : $web_event:ident ),* $(,)?} => { ::paste::paste! { $( #[doc = "The `" [< $($event)+ >] "` event, which receives [" $web_event "](web_sys::" $web_event ") as its argument."] #[derive(Copy, Clone, Debug)] #[allow(non_camel_case_types)] pub struct [<$( $event )+ >]; impl EventDescriptor for [< $($event)+ >] { type EventType = web_sys::$web_event; #[inline(always)] fn name(&self) -> Cow<'static, str> { stringify!([< $($event)+ >]).into() } #[inline(always)] fn event_delegation_key(&self) -> Cow<'static, str> { concat!("$$$", stringify!([< $($event)+ >])).into() } const BUBBLES: bool = true $(&& generate_event_types!($does_not_bubble))?; } )* } }; (does_not_bubble) => { false } } generate_event_types! { // ========================================================= // WindowEventHandlersEventMap // ========================================================= #[does_not_bubble] after print: Event, #[does_not_bubble] before print: Event, #[does_not_bubble] before unload: BeforeUnloadEvent, #[does_not_bubble] gamepad connected: GamepadEvent, #[does_not_bubble] gamepad disconnected: GamepadEvent, hash change: HashChangeEvent, #[does_not_bubble] language change: Event, #[does_not_bubble] message: MessageEvent, #[does_not_bubble] message error: MessageEvent, #[does_not_bubble] offline: Event, #[does_not_bubble] online: Event, #[does_not_bubble] page hide: PageTransitionEvent, #[does_not_bubble] page show: PageTransitionEvent, pop state: PopStateEvent, rejection handled: PromiseRejectionEvent, #[does_not_bubble] storage: StorageEvent, #[does_not_bubble] unhandled rejection: PromiseRejectionEvent, #[does_not_bubble] unload: Event, // ========================================================= // GlobalEventHandlersEventMap // ========================================================= #[does_not_bubble] abort: UiEvent, animation cancel: AnimationEvent, animation end: AnimationEvent, animation iteration: AnimationEvent, animation start: AnimationEvent, aux click: MouseEvent, before input: InputEvent, before toggle: Event, // web_sys does not include `ToggleEvent` #[does_not_bubble] blur: FocusEvent, #[does_not_bubble] can play: Event, #[does_not_bubble] can play through: Event, change: Event, click: MouseEvent, #[does_not_bubble] close: Event, composition end: CompositionEvent, composition start: CompositionEvent, composition update: CompositionEvent, context menu: MouseEvent, #[does_not_bubble] cue change: Event, dbl click: MouseEvent, drag: DragEvent, drag end: DragEvent, drag enter: DragEvent, drag leave: DragEvent, drag over: DragEvent, drag start: DragEvent, drop: DragEvent, #[does_not_bubble] duration change: Event, #[does_not_bubble] emptied: Event, #[does_not_bubble] ended: Event, #[does_not_bubble] error: ErrorEvent, #[does_not_bubble] focus: FocusEvent, #[does_not_bubble] focus in: FocusEvent, #[does_not_bubble] focus out: FocusEvent, form data: Event, // web_sys does not include `FormDataEvent` #[does_not_bubble] got pointer capture: PointerEvent, input: Event, #[does_not_bubble] invalid: Event, key down: KeyboardEvent, key press: KeyboardEvent, key up: KeyboardEvent, #[does_not_bubble] load: Event, #[does_not_bubble] loaded data: Event, #[does_not_bubble] loaded metadata: Event, #[does_not_bubble] load start: Event, lost pointer capture: PointerEvent, mouse down: MouseEvent, #[does_not_bubble] mouse enter: MouseEvent, #[does_not_bubble] mouse leave: MouseEvent, mouse move: MouseEvent, mouse out: MouseEvent, mouse over: MouseEvent, mouse up: MouseEvent, #[does_not_bubble] pause: Event, #[does_not_bubble] play: Event, #[does_not_bubble] playing: Event, pointer cancel: PointerEvent, pointer down: PointerEvent, #[does_not_bubble] pointer enter: PointerEvent, #[does_not_bubble] pointer leave: PointerEvent, pointer move: PointerEvent, pointer out: PointerEvent, pointer over: PointerEvent, pointer up: PointerEvent, #[does_not_bubble] progress: ProgressEvent, #[does_not_bubble] rate change: Event, reset: Event, #[does_not_bubble] resize: UiEvent, #[does_not_bubble] scroll: Event, #[does_not_bubble] scroll end: Event, security policy violation: SecurityPolicyViolationEvent, #[does_not_bubble] seeked: Event, #[does_not_bubble] seeking: Event, select: Event, #[does_not_bubble] selection change: Event, select start: Event, slot change: Event, #[does_not_bubble] stalled: Event, submit: SubmitEvent, #[does_not_bubble] suspend: Event, #[does_not_bubble] time update: Event, #[does_not_bubble] toggle: Event, touch cancel: TouchEvent, touch end: TouchEvent, touch move: TouchEvent, touch start: TouchEvent, transition cancel: TransitionEvent, transition end: TransitionEvent, transition run: TransitionEvent, transition start: TransitionEvent, #[does_not_bubble] volume change: Event, #[does_not_bubble] waiting: Event, webkit animation end: Event, webkit animation iteration: Event, webkit animation start: Event, webkit transition end: Event, wheel: WheelEvent, // ========================================================= // WindowEventMap // ========================================================= D O M Content Loaded: Event, // Hack for correct casing #[does_not_bubble] device motion: DeviceMotionEvent, #[does_not_bubble] device orientation: DeviceOrientationEvent, #[does_not_bubble] orientation change: Event, // ========================================================= // DocumentAndElementEventHandlersEventMap // ========================================================= copy: ClipboardEvent, cut: ClipboardEvent, paste: ClipboardEvent, // ========================================================= // DocumentEventMap // ========================================================= fullscreen change: Event, fullscreen error: Event, pointer lock change: Event, pointer lock error: Event, #[does_not_bubble] ready state change: Event, visibility change: Event, } // Export `web_sys` event types use super::{ attribute::{ maybe_next_attr_erasure_macros::next_attr_output_type, NextAttribute, }, element::HasElementType, }; #[doc(no_inline)] pub use web_sys::{ AnimationEvent, BeforeUnloadEvent, ClipboardEvent, CompositionEvent, CustomEvent, DeviceMotionEvent, DeviceOrientationEvent, DragEvent, ErrorEvent, Event, FocusEvent, GamepadEvent, HashChangeEvent, InputEvent, KeyboardEvent, MessageEvent, MouseEvent, PageTransitionEvent, PointerEvent, PopStateEvent, ProgressEvent, PromiseRejectionEvent, SecurityPolicyViolationEvent, StorageEvent, SubmitEvent, TouchEvent, TransitionEvent, UiEvent, WheelEvent, };
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/class.rs
tachys/src/html/class.rs
use super::attribute::{ maybe_next_attr_erasure_macros::next_attr_output_type, Attribute, NamedAttributeKey, NextAttribute, }; use crate::{ html::attribute::maybe_next_attr_erasure_macros::next_attr_combine, renderer::Rndr, view::{Position, ToTemplate}, }; use std::{borrow::Cow, future::Future, sync::Arc}; /// Adds a CSS class. #[inline(always)] pub fn class<C>(class: C) -> Class<C> where C: IntoClass, { Class { class } } /// A CSS class. #[derive(Debug)] pub struct Class<C> { class: C, } impl<C> Clone for Class<C> where C: Clone, { fn clone(&self) -> Self { Self { class: self.class.clone(), } } } impl<C> Attribute for Class<C> where C: IntoClass, { const MIN_LENGTH: usize = C::MIN_LENGTH; type AsyncOutput = Class<C::AsyncOutput>; type State = C::State; type Cloneable = Class<C::Cloneable>; type CloneableOwned = Class<C::CloneableOwned>; fn html_len(&self) -> usize { self.class.html_len() + 1 } fn to_html( self, _buf: &mut String, class: &mut String, _style: &mut String, _inner_html: &mut String, ) { // If this is a class="..." attribute (not class:name=value), clear previous value if self.class.should_overwrite() { class.clear(); } class.push(' '); self.class.to_html(class); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { self.class.hydrate::<FROM_SERVER>(el) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { self.class.build(el) } fn rebuild(self, state: &mut Self::State) { self.class.rebuild(state) } fn into_cloneable(self) -> Self::Cloneable { Class { class: self.class.into_cloneable(), } } fn into_cloneable_owned(self) -> Self::CloneableOwned { Class { class: self.class.into_cloneable_owned(), } } fn dry_resolve(&mut self) { self.class.dry_resolve(); } async fn resolve(self) -> Self::AsyncOutput { Class { class: self.class.resolve().await, } } fn keys(&self) -> Vec<NamedAttributeKey> { vec![NamedAttributeKey::Attribute("class".into())] } } impl<C> NextAttribute for Class<C> where C: IntoClass, { next_attr_output_type!(Self, NewAttr); fn add_any_attr<NewAttr: Attribute>( self, new_attr: NewAttr, ) -> Self::Output<NewAttr> { next_attr_combine!(self, new_attr) } } impl<C> ToTemplate for Class<C> where C: IntoClass, { const CLASS: &'static str = C::TEMPLATE; fn to_template( _buf: &mut String, class: &mut String, _style: &mut String, _inner_html: &mut String, _position: &mut Position, ) { C::to_template(class); } } /// A possible value for a CSS class. pub trait IntoClass: Send { /// The HTML that should be included in a `<template>`. const TEMPLATE: &'static str = ""; /// The minimum length of the HTML. const MIN_LENGTH: usize = Self::TEMPLATE.len(); /// The type after all async data have resolved. type AsyncOutput: IntoClass; /// The view state retained between building and rebuilding. type State; /// An equivalent value that can be cloned. type Cloneable: IntoClass + Clone; /// An equivalent value that can be cloned and is `'static`. type CloneableOwned: IntoClass + Clone + 'static; /// The estimated length of the HTML. fn html_len(&self) -> usize; /// Renders the class to HTML. fn to_html(self, class: &mut String); /// Whether this class attribute should overwrite previous class values. /// Returns `true` for `class="..."` attributes, `false` for `class:name=value` directives. fn should_overwrite(&self) -> bool { false } /// Renders the class to HTML for a `<template>`. #[allow(unused)] // it's used with `nightly` feature fn to_template(class: &mut String) {} /// Adds interactivity as necessary, given DOM nodes that were created from HTML that has /// either been rendered on the server, or cloned for a `<template>`. fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State; /// Adds this class to the element during client-side rendering. fn build(self, el: &crate::renderer::types::Element) -> Self::State; /// Updates the value. fn rebuild(self, state: &mut Self::State); /// Converts this to a cloneable type. fn into_cloneable(self) -> Self::Cloneable; /// Converts this to a cloneable, owned type. fn into_cloneable_owned(self) -> Self::CloneableOwned; /// “Runs” the attribute without other side effects. For primitive types, this is a no-op. For /// reactive types, this can be used to gather data about reactivity or about asynchronous data /// that needs to be loaded. fn dry_resolve(&mut self); /// “Resolves” this into a type that is not waiting for any asynchronous data. fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send; /// Reset the class list to the state before this class was added. fn reset(state: &mut Self::State); } impl<T: IntoClass> IntoClass for Option<T> { type AsyncOutput = Option<T::AsyncOutput>; type State = (crate::renderer::types::Element, Option<T::State>); type Cloneable = Option<T::Cloneable>; type CloneableOwned = Option<T::CloneableOwned>; fn html_len(&self) -> usize { self.as_ref().map_or(0, IntoClass::html_len) } fn to_html(self, class: &mut String) { if let Some(t) = self { t.to_html(class); } } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { if let Some(t) = self { (el.clone(), Some(t.hydrate::<FROM_SERVER>(el))) } else { (el.clone(), None) } } fn build(self, el: &crate::renderer::types::Element) -> Self::State { if let Some(t) = self { (el.clone(), Some(t.build(el))) } else { (el.clone(), None) } } fn rebuild(self, state: &mut Self::State) { let el = &state.0; let prev_state = &mut state.1; let maybe_next_t_state = match (prev_state.take(), self) { (Some(mut prev_t_state), None) => { T::reset(&mut prev_t_state); Some(None) } (None, Some(t)) => Some(Some(t.build(el))), (Some(mut prev_t_state), Some(t)) => { t.rebuild(&mut prev_t_state); Some(Some(prev_t_state)) } (None, None) => Some(None), }; if let Some(next_t_state) = maybe_next_t_state { state.1 = next_t_state; } } fn into_cloneable(self) -> Self::Cloneable { self.map(|t| t.into_cloneable()) } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.map(|t| t.into_cloneable_owned()) } fn dry_resolve(&mut self) { if let Some(t) = self { t.dry_resolve(); } } async fn resolve(self) -> Self::AsyncOutput { if let Some(t) = self { Some(t.resolve().await) } else { None } } fn reset(state: &mut Self::State) { if let Some(prev_t_state) = &mut state.1 { T::reset(prev_t_state); } } } impl IntoClass for &str { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Self); type Cloneable = Self; type CloneableOwned = Arc<str>; fn html_len(&self) -> usize { self.len() } fn to_html(self, class: &mut String) { class.push_str(self); } fn should_overwrite(&self) -> bool { true } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { if !FROM_SERVER { Rndr::set_attribute(el, "class", self); } (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "class", self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "class", self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.into() } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "class"); } } impl IntoClass for Cow<'_, str> { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Self); type Cloneable = Arc<str>; type CloneableOwned = Arc<str>; fn html_len(&self) -> usize { self.len() } fn to_html(self, class: &mut String) { IntoClass::to_html(&*self, class); } fn should_overwrite(&self) -> bool { true } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { if !FROM_SERVER { Rndr::set_attribute(el, "class", &self); } (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "class", &self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "class", &self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self.into() } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.into() } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "class"); } } impl IntoClass for String { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Self); type Cloneable = Arc<str>; type CloneableOwned = Arc<str>; fn html_len(&self) -> usize { self.len() } fn to_html(self, class: &mut String) { IntoClass::to_html(self.as_str(), class); } fn should_overwrite(&self) -> bool { true } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { if !FROM_SERVER { Rndr::set_attribute(el, "class", &self); } (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "class", &self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "class", &self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self.into() } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.into() } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "class"); } } impl IntoClass for Arc<str> { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Self); type Cloneable = Self; type CloneableOwned = Self; fn html_len(&self) -> usize { self.len() } fn to_html(self, class: &mut String) { IntoClass::to_html(self.as_ref(), class); } fn should_overwrite(&self) -> bool { true } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { if !FROM_SERVER { Rndr::set_attribute(el, "class", &self); } (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "class", &self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "class", &self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "class"); } } impl IntoClass for (&'static str, bool) { type AsyncOutput = Self; type State = (crate::renderer::types::ClassList, bool, &'static str); type Cloneable = Self; type CloneableOwned = Self; fn html_len(&self) -> usize { self.0.len() } fn to_html(self, class: &mut String) { let (name, include) = self; if include { class.push_str(name); } } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { let (name, include) = self; let class_list = Rndr::class_list(el); if !FROM_SERVER && include { Rndr::add_class(&class_list, name); } (class_list, self.1, name) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { let (name, include) = self; let class_list = Rndr::class_list(el); if include { Rndr::add_class(&class_list, name); } (class_list, self.1, name) } fn rebuild(self, state: &mut Self::State) { let (name, include) = self; let (class_list, prev_include, prev_name) = state; if name == *prev_name { if include != *prev_include { if include { Rndr::add_class(class_list, name); } else { Rndr::remove_class(class_list, name); } } } else { if *prev_include { Rndr::remove_class(class_list, prev_name); } if include { Rndr::add_class(class_list, name); } } *prev_include = include; *prev_name = name; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::Cloneable { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (class_list, _, name) = state; Rndr::remove_class(class_list, name); } } #[cfg(all(feature = "nightly", rustc_nightly))] impl<const V: &'static str> IntoClass for crate::view::static_types::Static<V> { const TEMPLATE: &'static str = V; type AsyncOutput = Self; type State = (); type Cloneable = Self; type CloneableOwned = Self; fn html_len(&self) -> usize { V.len() } fn to_html(self, class: &mut String) { class.push_str(V); } fn to_template(class: &mut String) { class.push_str(V); } fn hydrate<const FROM_SERVER: bool>( self, _el: &crate::renderer::types::Element, ) -> Self::State { } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "class", V); } fn rebuild(self, _state: &mut Self::State) {} fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(_state: &mut Self::State) {} } /* #[cfg(test)] mod tests { use crate::{ html::{ class::class, element::{p, HtmlElement}, }, renderer::dom::Dom, view::{Position, PositionState, RenderHtml}, }; #[test] fn adds_simple_class() { let mut html = String::new(); let el: HtmlElement<_, _, _, Dom> = p(class("foo bar"), ()); el.to_html(&mut html, &PositionState::new(Position::FirstChild)); assert_eq!(html, r#"<p class="foo bar"></p>"#); } #[test] fn adds_class_with_dynamic() { let mut html = String::new(); let el: HtmlElement<_, _, _, Dom> = p((class("foo bar"), class(("baz", true))), ()); el.to_html(&mut html, &PositionState::new(Position::FirstChild)); assert_eq!(html, r#"<p class="foo bar baz"></p>"#); } #[test] fn adds_class_with_dynamic_and_function() { let mut html = String::new(); let el: HtmlElement<_, _, _, Dom> = p( ( class("foo bar"), class(("baz", || true)), class(("boo", false)), ), (), ); el.to_html(&mut html, &PositionState::new(Position::FirstChild)); assert_eq!(html, r#"<p class="foo bar baz"></p>"#); } } */
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/directive.rs
tachys/src/html/directive.rs
use super::attribute::{ maybe_next_attr_erasure_macros::next_attr_output_type, Attribute, NextAttribute, }; use crate::{ html::attribute::{ maybe_next_attr_erasure_macros::next_attr_combine, NamedAttributeKey, }, prelude::AddAnyAttr, view::{Position, ToTemplate}, }; use send_wrapper::SendWrapper; use std::{marker::PhantomData, sync::Arc}; /// Adds a directive to the element, which runs some custom logic in the browser when the element /// is created or hydrated. pub trait DirectiveAttribute<T, P, D> where D: IntoDirective<T, P>, { /// The type of the element with the directive added. type Output; /// Adds a directive to the element, which runs some custom logic in the browser when the element /// is created or hydrated. fn directive(self, handler: D, param: P) -> Self::Output; } impl<V, T, P, D> DirectiveAttribute<T, P, D> for V where V: AddAnyAttr, D: IntoDirective<T, P>, P: Clone + 'static, T: 'static, { type Output = <Self as AddAnyAttr>::Output<Directive<T, D, P>>; fn directive(self, handler: D, param: P) -> Self::Output { self.add_any_attr(directive(handler, param)) } } /// Adds a directive to the element, which runs some custom logic in the browser when the element /// is created or hydrated. #[inline(always)] pub fn directive<T, P, D>(handler: D, param: P) -> Directive<T, D, P> where D: IntoDirective<T, P>, { Directive((!cfg!(feature = "ssr")).then(|| { SendWrapper::new(DirectiveInner { handler, param, t: PhantomData, }) })) } /// Custom logic that runs in the browser when the element is created or hydrated. #[derive(Debug)] pub struct Directive<T, D, P>(Option<SendWrapper<DirectiveInner<T, D, P>>>); impl<T, D, P> Clone for Directive<T, D, P> where P: Clone + 'static, D: Clone, { fn clone(&self) -> Self { Self(self.0.clone()) } } #[derive(Debug)] struct DirectiveInner<T, D, P> { handler: D, param: P, t: PhantomData<T>, } impl<T, D, P> Clone for DirectiveInner<T, D, P> where P: Clone + 'static, D: Clone, { fn clone(&self) -> Self { Self { handler: self.handler.clone(), param: self.param.clone(), t: PhantomData, } } } impl<T, P, D> Attribute for Directive<T, D, P> where D: IntoDirective<T, P>, P: Clone + 'static, // TODO this is just here to make them cloneable T: 'static, { const MIN_LENGTH: usize = 0; type AsyncOutput = Self; type State = crate::renderer::types::Element; type Cloneable = Directive<T, D::Cloneable, P>; type CloneableOwned = Directive<T, D::Cloneable, P>; fn html_len(&self) -> usize { 0 } fn to_html( self, _buf: &mut String, _class: &mut String, _style: &mut String, _inner_html: &mut String, ) { } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { let inner = self.0.expect("directive removed early").take(); inner.handler.run(el.clone(), inner.param); el.clone() } fn build(self, el: &crate::renderer::types::Element) -> Self::State { let inner = self.0.expect("directive removed early").take(); inner.handler.run(el.clone(), inner.param); el.clone() } fn rebuild(self, state: &mut Self::State) { let inner = self.0.expect("directive removed early").take(); inner.handler.run(state.clone(), inner.param); } fn into_cloneable(self) -> Self::Cloneable { self.into_cloneable_owned() } fn into_cloneable_owned(self) -> Self::CloneableOwned { let inner = self.0.map(|inner| { let DirectiveInner { handler, param, t } = inner.take(); SendWrapper::new(DirectiveInner { handler: handler.into_cloneable(), param, t, }) }); Directive(inner) } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn keys(&self) -> Vec<NamedAttributeKey> { vec![] } } impl<T, D, P> NextAttribute for Directive<T, D, P> where D: IntoDirective<T, P>, P: Clone + 'static, T: 'static, { next_attr_output_type!(Self, NewAttr); fn add_any_attr<NewAttr: Attribute>( self, new_attr: NewAttr, ) -> Self::Output<NewAttr> { next_attr_combine!(self, new_attr) } } impl<T, D, P> ToTemplate for Directive<T, D, P> { const CLASS: &'static str = ""; fn to_template( _buf: &mut String, _class: &mut String, _style: &mut String, _inner_html: &mut String, _position: &mut Position, ) { } } /// Trait for a directive handler function. /// This is used so it's possible to use functions with one or two /// parameters as directive handlers. /// /// You can use directives like the following. /// /// ```ignore /// # use leptos::{*, html::AnyElement}; /// /// // This doesn't take an attribute value /// fn my_directive(el: crate::renderer::types::Element) { /// // do sth /// } /// /// // This requires an attribute value /// fn another_directive(el: crate::renderer::types::Element, params: i32) { /// // do sth /// } /// /// #[component] /// pub fn MyComponent() -> impl IntoView { /// view! { /// // no attribute value /// <div use:my_directive></div> /// /// // with an attribute value /// <div use:another_directive=8></div> /// } /// } /// ``` /// /// A directive is just syntactic sugar for /// /// ```ignore /// let node_ref = create_node_ref(); /// /// create_effect(move |_| { /// if let Some(el) = node_ref.get() { /// directive_func(el, possibly_some_param); /// } /// }); /// ``` /// /// A directive can be a function with one or two parameters. /// The first is the element the directive is added to and the optional /// second is the parameter that is provided in the attribute. pub trait IntoDirective<T: ?Sized, P> { /// An equivalent to this directive that is cloneable and owned. type Cloneable: IntoDirective<T, P> + Clone + 'static; /// Calls the handler function fn run(&self, el: crate::renderer::types::Element, param: P); /// Converts this into a cloneable type. fn into_cloneable(self) -> Self::Cloneable; } impl<F> IntoDirective<(crate::renderer::types::Element,), ()> for F where F: Fn(crate::renderer::types::Element) + 'static, { type Cloneable = Arc<dyn Fn(crate::renderer::types::Element)>; fn run(&self, el: crate::renderer::types::Element, _: ()) { self(el) } fn into_cloneable(self) -> Self::Cloneable { Arc::new(self) } } impl IntoDirective<(crate::renderer::types::Element,), ()> for Arc<dyn Fn(crate::renderer::types::Element)> { type Cloneable = Arc<dyn Fn(crate::renderer::types::Element)>; fn run(&self, el: crate::renderer::types::Element, _: ()) { self(el) } fn into_cloneable(self) -> Self::Cloneable { self } } impl<F, P> IntoDirective<(crate::renderer::types::Element, P), P> for F where F: Fn(crate::renderer::types::Element, P) + 'static, P: 'static, { type Cloneable = Arc<dyn Fn(crate::renderer::types::Element, P)>; fn run(&self, el: crate::renderer::types::Element, param: P) { self(el, param); } fn into_cloneable(self) -> Self::Cloneable { Arc::new(self) } } impl<P> IntoDirective<(crate::renderer::types::Element, P), P> for Arc<dyn Fn(crate::renderer::types::Element, P)> where P: 'static, { type Cloneable = Arc<dyn Fn(crate::renderer::types::Element, P)>; fn run(&self, el: crate::renderer::types::Element, param: P) { self(el, param) } fn into_cloneable(self) -> Self::Cloneable { self } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/node_ref.rs
tachys/src/html/node_ref.rs
use super::{ attribute::{ maybe_next_attr_erasure_macros::next_attr_output_type, Attribute, NextAttribute, }, element::ElementType, }; use crate::{ html::{ attribute::{ maybe_next_attr_erasure_macros::next_attr_combine, NamedAttributeKey, }, element::HtmlElement, }, prelude::Render, view::add_attr::AddAnyAttr, }; use std::marker::PhantomData; /// Describes a container that can be used to hold a reference to an HTML element. pub trait NodeRefContainer<E>: Send + Clone + 'static where E: ElementType, { /// Fills the container with the element. fn load(self, el: &crate::renderer::types::Element); } /// An [`Attribute`] that will fill a [`NodeRefContainer`] with an HTML element. #[derive(Debug)] pub struct NodeRefAttr<E, C> { container: C, ty: PhantomData<E>, } impl<E, C> Clone for NodeRefAttr<E, C> where C: Clone, { fn clone(&self) -> Self { Self { container: self.container.clone(), ty: PhantomData, } } } /// Creates an attribute that will fill a [`NodeRefContainer`] with the element it is applied to. pub fn node_ref<E, C>(container: C) -> NodeRefAttr<E, C> where E: ElementType, C: NodeRefContainer<E>, { NodeRefAttr { container, ty: PhantomData, } } impl<E, C> Attribute for NodeRefAttr<E, C> where E: ElementType, C: NodeRefContainer<E>, crate::renderer::types::Element: PartialEq, { const MIN_LENGTH: usize = 0; type AsyncOutput = Self; type State = crate::renderer::types::Element; type Cloneable = Self; type CloneableOwned = Self; #[inline(always)] fn html_len(&self) -> usize { 0 } fn to_html( self, _buf: &mut String, _class: &mut String, _style: &mut String, _inner_html: &mut String, ) { } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { self.container.load(el); el.to_owned() } fn build(self, el: &crate::renderer::types::Element) -> Self::State { self.container.load(el); el.to_owned() } fn rebuild(self, state: &mut Self::State) { self.container.load(state); } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::Cloneable { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn keys(&self) -> Vec<NamedAttributeKey> { vec![] } } impl<E, C> NextAttribute for NodeRefAttr<E, C> where E: ElementType, C: NodeRefContainer<E>, crate::renderer::types::Element: PartialEq, { next_attr_output_type!(Self, NewAttr); fn add_any_attr<NewAttr: Attribute>( self, new_attr: NewAttr, ) -> Self::Output<NewAttr> { next_attr_combine!(self, new_attr) } } /// Adds the `node_ref` attribute to an element. pub trait NodeRefAttribute<E, C> where E: ElementType, C: NodeRefContainer<E>, crate::renderer::types::Element: PartialEq, { /// Binds this HTML element to a [`NodeRefContainer`]. fn node_ref( self, container: C, ) -> <Self as AddAnyAttr>::Output<NodeRefAttr<E, C>> where Self: Sized + AddAnyAttr, <Self as AddAnyAttr>::Output<NodeRefAttr<E, C>>: Render, { self.add_any_attr(node_ref(container)) } } impl<E, At, Ch, C> NodeRefAttribute<E, C> for HtmlElement<E, At, Ch> where E: ElementType, At: Attribute, Ch: Render, C: NodeRefContainer<E>, crate::renderer::types::Element: PartialEq, { }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/mod.rs
tachys/src/html/mod.rs
use self::attribute::Attribute; use crate::{ hydration::Cursor, no_attrs, prelude::{AddAnyAttr, Mountable}, renderer::{ dom::{Element, Node}, CastFrom, Rndr, }, view::{Position, PositionState, Render, RenderHtml}, }; use attribute::any_attribute::AnyAttribute; use std::borrow::Cow; /// Types for HTML attributes. pub mod attribute; /// Types for manipulating the `class` attribute and `classList`. pub mod class; /// Types for creating user-defined attributes with custom behavior (directives). pub mod directive; /// Types for HTML elements. pub mod element; /// Types for DOM events. pub mod event; /// Types for adding interactive islands to inert HTML pages. pub mod islands; /// Types for accessing a reference to an HTML element. pub mod node_ref; /// Types for DOM properties. pub mod property; /// Types for the `style` attribute and individual style manipulation. pub mod style; /// A `<!DOCTYPE>` declaration. pub struct Doctype { value: &'static str, } /// Creates a `<!DOCTYPE>`. pub fn doctype(value: &'static str) -> Doctype { Doctype { value } } impl Render for Doctype { type State = (); fn build(self) -> Self::State {} fn rebuild(self, _state: &mut Self::State) {} } no_attrs!(Doctype); impl RenderHtml for Doctype { type AsyncOutput = Self; type Owned = Self; const MIN_LENGTH: usize = "<!DOCTYPE html>".len(); fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn to_html_with_buf( self, buf: &mut String, _position: &mut Position, _escape: bool, _mark_branches: bool, _extra_attrs: Vec<AnyAttribute>, ) { buf.push_str("<!DOCTYPE "); buf.push_str(self.value); buf.push('>'); } fn hydrate<const FROM_SERVER: bool>( self, _cursor: &Cursor, _position: &PositionState, ) -> Self::State { } fn into_owned(self) -> Self::Owned { self } } /// An element that contains no interactivity, and whose contents can be known at compile time. pub struct InertElement { html: Cow<'static, str>, } impl InertElement { /// Creates a new inert element. pub fn new(html: impl Into<Cow<'static, str>>) -> Self { Self { html: html.into() } } } /// Retained view state for [`InertElement`]. pub struct InertElementState(Cow<'static, str>, Element); impl Mountable for InertElementState { fn unmount(&mut self) { self.1.unmount(); } fn mount(&mut self, parent: &Element, marker: Option<&Node>) { self.1.mount(parent, marker) } fn insert_before_this(&self, child: &mut dyn Mountable) -> bool { self.1.insert_before_this(child) } fn elements(&self) -> Vec<crate::renderer::types::Element> { vec![self.1.clone()] } } impl Render for InertElement { type State = InertElementState; fn build(self) -> Self::State { let el = Rndr::create_element_from_html(self.html.clone()); InertElementState(self.html, el) } fn rebuild(self, state: &mut Self::State) { let InertElementState(prev, el) = state; if &self.html != prev { let mut new_el = Rndr::create_element_from_html(self.html.clone()); el.insert_before_this(&mut new_el); el.unmount(); *el = new_el; *prev = self.html; } } } impl AddAnyAttr for InertElement { type Output<SomeNewAttr: Attribute> = Self; fn add_any_attr<NewAttr: Attribute>( self, _attr: NewAttr, ) -> Self::Output<NewAttr> where Self::Output<NewAttr>: RenderHtml, { panic!( "InertElement does not support adding attributes. It should only \ be used as a child, and not returned at the top level." ) } } impl RenderHtml for InertElement { type AsyncOutput = Self; type Owned = Self; const MIN_LENGTH: usize = 0; fn html_len(&self) -> usize { self.html.len() } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self { self } fn to_html_with_buf( self, buf: &mut String, position: &mut Position, _escape: bool, _mark_branches: bool, _extra_attrs: Vec<AnyAttribute>, ) { buf.push_str(&self.html); *position = Position::NextChild; } fn hydrate<const FROM_SERVER: bool>( self, cursor: &Cursor, position: &PositionState, ) -> Self::State { let curr_position = position.get(); if curr_position == Position::FirstChild { cursor.child(); } else if curr_position != Position::Current { cursor.sibling(); } let el = crate::renderer::types::Element::cast_from(cursor.current()) .unwrap(); position.set(Position::NextChild); InertElementState(self.html, el) } fn into_owned(self) -> Self::Owned { self } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/style.rs
tachys/src/html/style.rs
use super::attribute::{ maybe_next_attr_erasure_macros::next_attr_output_type, Attribute, NextAttribute, }; #[cfg(all(feature = "nightly", rustc_nightly))] use crate::view::static_types::Static; use crate::{ html::attribute::{ maybe_next_attr_erasure_macros::next_attr_combine, NamedAttributeKey, }, renderer::{dom::CssStyleDeclaration, Rndr}, view::{Position, ToTemplate}, }; use std::{future::Future, sync::Arc}; /// Returns an [`Attribute`] that will add to an element's CSS styles. #[inline(always)] pub fn style<S>(style: S) -> Style<S> where S: IntoStyle, { Style { style } } /// An [`Attribute`] that will add to an element's CSS styles. #[derive(Debug)] pub struct Style<S> { style: S, } impl<S> Clone for Style<S> where S: Clone, { fn clone(&self) -> Self { Self { style: self.style.clone(), } } } impl<S> Attribute for Style<S> where S: IntoStyle, { const MIN_LENGTH: usize = 0; type AsyncOutput = Style<S::AsyncOutput>; type State = S::State; type Cloneable = Style<S::Cloneable>; type CloneableOwned = Style<S::CloneableOwned>; // TODO #[inline(always)] fn html_len(&self) -> usize { 0 } fn to_html( self, _buf: &mut String, _style: &mut String, style: &mut String, _inner_html: &mut String, ) { self.style.to_html(style); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { self.style.hydrate::<FROM_SERVER>(el) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { self.style.build(el) } fn rebuild(self, state: &mut Self::State) { self.style.rebuild(state) } fn into_cloneable(self) -> Self::Cloneable { Style { style: self.style.into_cloneable(), } } fn into_cloneable_owned(self) -> Self::CloneableOwned { Style { style: self.style.into_cloneable_owned(), } } fn dry_resolve(&mut self) { self.style.dry_resolve(); } async fn resolve(self) -> Self::AsyncOutput { Style { style: self.style.resolve().await, } } fn keys(&self) -> Vec<NamedAttributeKey> { vec![NamedAttributeKey::Attribute("style".into())] } } impl<S> NextAttribute for Style<S> where S: IntoStyle, { next_attr_output_type!(Self, NewAttr); fn add_any_attr<NewAttr: Attribute>( self, new_attr: NewAttr, ) -> Self::Output<NewAttr> { next_attr_combine!(self, new_attr) } } impl<S> ToTemplate for Style<S> where S: IntoStyle, { fn to_template( _buf: &mut String, _style: &mut String, _class: &mut String, _inner_html: &mut String, _position: &mut Position, ) { // TODO: should there be some templating for static styles? } } /// Any type that can be added to the `style` attribute or set as a style in /// the [`CssStyleDeclaration`](web_sys::CssStyleDeclaration). /// /// This could be a plain string, or a property name-value pair. pub trait IntoStyle: Send { /// The type after all async data have resolved. type AsyncOutput: IntoStyle; /// The view state retained between building and rebuilding. type State; /// An equivalent value that can be cloned. type Cloneable: IntoStyle + Clone; /// An equivalent value that can be cloned and is `'static`. type CloneableOwned: IntoStyle + Clone + 'static; /// Renders the style to HTML. fn to_html(self, style: &mut String); /// Adds interactivity as necessary, given DOM nodes that were created from HTML that has /// either been rendered on the server, or cloned for a `<template>`. fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State; /// Adds this style to the element during client-side rendering. fn build(self, el: &crate::renderer::types::Element) -> Self::State; /// Updates the value. fn rebuild(self, state: &mut Self::State); /// Converts this to a cloneable type. fn into_cloneable(self) -> Self::Cloneable; /// Converts this to a cloneable, owned type. fn into_cloneable_owned(self) -> Self::CloneableOwned; /// “Runs” the attribute without other side effects. For primitive types, this is a no-op. For /// reactive types, this can be used to gather data about reactivity or about asynchronous data /// that needs to be loaded. fn dry_resolve(&mut self); /// “Resolves” this into a type that is not waiting for any asynchronous data. fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send; /// Reset the styling to the state before this style was added. fn reset(state: &mut Self::State); } impl<T: IntoStyle> IntoStyle for Option<T> { type AsyncOutput = Option<T::AsyncOutput>; type State = (crate::renderer::types::Element, Option<T::State>); type Cloneable = Option<T::Cloneable>; type CloneableOwned = Option<T::CloneableOwned>; fn to_html(self, style: &mut String) { if let Some(t) = self { t.to_html(style); } } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { if let Some(t) = self { (el.clone(), Some(t.hydrate::<FROM_SERVER>(el))) } else { (el.clone(), None) } } fn build(self, el: &crate::renderer::types::Element) -> Self::State { if let Some(t) = self { (el.clone(), Some(t.build(el))) } else { (el.clone(), None) } } fn rebuild(self, state: &mut Self::State) { let el = &state.0; let prev_state = &mut state.1; let maybe_next_t_state = match (prev_state.take(), self) { (Some(mut prev_t_state), None) => { T::reset(&mut prev_t_state); Some(None) } (None, Some(t)) => Some(Some(t.build(el))), (Some(mut prev_t_state), Some(t)) => { t.rebuild(&mut prev_t_state); Some(Some(prev_t_state)) } (None, None) => Some(None), }; if let Some(next_t_state) = maybe_next_t_state { state.1 = next_t_state; } } fn into_cloneable(self) -> Self::Cloneable { self.map(|t| t.into_cloneable()) } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.map(|t| t.into_cloneable_owned()) } fn dry_resolve(&mut self) { if let Some(t) = self { t.dry_resolve(); } } async fn resolve(self) -> Self::AsyncOutput { if let Some(t) = self { Some(t.resolve().await) } else { None } } fn reset(state: &mut Self::State) { if let Some(prev_t_state) = &mut state.1 { T::reset(prev_t_state); } } } impl<'a> IntoStyle for &'a str { type AsyncOutput = Self; type State = (crate::renderer::types::Element, &'a str); type Cloneable = Self; type CloneableOwned = Arc<str>; fn to_html(self, style: &mut String) { style.push_str(self); style.push(';'); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "style", self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "style", self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.into() } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "style"); } } impl IntoStyle for Arc<str> { type AsyncOutput = Self; type State = (crate::renderer::types::Element, Arc<str>); type Cloneable = Self; type CloneableOwned = Self; fn to_html(self, style: &mut String) { style.push_str(&self); style.push(';'); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "style", &self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "style", &self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "style"); } } impl IntoStyle for String { type AsyncOutput = Self; type State = (crate::renderer::types::Element, String); type Cloneable = Arc<str>; type CloneableOwned = Arc<str>; fn to_html(self, style: &mut String) { style.push_str(&self); style.push(';'); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { (el.clone(), self) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "style", &self); (el.clone(), self) } fn rebuild(self, state: &mut Self::State) { let (el, prev) = state; if self != *prev { Rndr::set_attribute(el, "style", &self); } *prev = self; } fn into_cloneable(self) -> Self::Cloneable { self.into() } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.into() } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(state: &mut Self::State) { let (el, _prev) = state; Rndr::remove_attribute(el, "style"); } } /// Any type that can be used to set an individual style in the /// [`CssStyleDeclaration`](web_sys::CssStyleDeclaration). /// /// This is the value in a `(name, value)` tuple that implements [`IntoStyle`]. pub trait IntoStyleValue: Send { /// The type after all async data have resolved. type AsyncOutput: IntoStyleValue; /// The view state retained between building and rebuilding. type State; /// An equivalent value that can be cloned. type Cloneable: Clone + IntoStyleValue; /// An equivalent value that can be cloned and is `'static`. type CloneableOwned: Clone + IntoStyleValue + 'static; /// Renders the style to HTML. fn to_html(self, name: &str, style: &mut String); /// Adds this style to the element during client-side rendering. fn build(self, style: &CssStyleDeclaration, name: &str) -> Self::State; /// Updates the value. fn rebuild( self, style: &CssStyleDeclaration, name: &str, state: &mut Self::State, ); /// Adds interactivity as necessary, given DOM nodes that were created from HTML that has /// either been rendered on the server, or cloned for a `<template>`. fn hydrate(self, style: &CssStyleDeclaration, name: &str) -> Self::State; /// Converts this to a cloneable type. fn into_cloneable(self) -> Self::Cloneable; /// Converts this to a cloneable, owned type. fn into_cloneable_owned(self) -> Self::CloneableOwned; /// “Runs” the attribute without other side effects. For primitive types, this is a no-op. For /// reactive types, this can be used to gather data about reactivity or about asynchronous data /// that needs to be loaded. fn dry_resolve(&mut self); /// “Resolves” this into a type that is not waiting for any asynchronous data. fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send; } impl<K, V> IntoStyle for (K, V) where K: AsRef<str> + Clone + Send + 'static, V: IntoStyleValue, { type AsyncOutput = (K, V::AsyncOutput); type State = (crate::renderer::types::CssStyleDeclaration, K, V::State); type Cloneable = (K, V::Cloneable); type CloneableOwned = (K, V::CloneableOwned); fn to_html(self, style: &mut String) { let (name, value) = self; value.to_html(name.as_ref(), style); } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { let style = Rndr::style(el); let state = self.1.hydrate(&style, self.0.as_ref()); (style, self.0, state) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { let (name, value) = self; let style = Rndr::style(el); let state = value.build(&style, name.as_ref()); (style, name, state) } fn rebuild(self, state: &mut Self::State) { let (name, value) = self; // state.1 was the previous name, theoretically the css name could be changed: if name.as_ref() != state.1.as_ref() { <Self as IntoStyle>::reset(state); state.2 = value.build(&state.0, name.as_ref()); } else { value.rebuild(&state.0, name.as_ref(), &mut state.2); } } fn into_cloneable(self) -> Self::Cloneable { (self.0, self.1.into_cloneable()) } fn into_cloneable_owned(self) -> Self::CloneableOwned { (self.0, self.1.into_cloneable_owned()) } fn dry_resolve(&mut self) { self.1.dry_resolve(); } async fn resolve(self) -> Self::AsyncOutput { (self.0, self.1.resolve().await) } /// Reset the renderer to the state before this style was added. fn reset(state: &mut Self::State) { let (style, name, _value) = state; Rndr::remove_css_property(style, name.as_ref()); } } macro_rules! impl_style_value { ($ty:ty) => { impl IntoStyleValue for $ty { type AsyncOutput = Self; type State = Self; type Cloneable = Self; type CloneableOwned = Self; fn to_html(self, name: &str, style: &mut String) { style.push_str(name); style.push(':'); style.push_str(&self); style.push(';'); } fn build( self, style: &CssStyleDeclaration, name: &str, ) -> Self::State { Rndr::set_css_property(style, name, &self); self } fn rebuild( self, style: &CssStyleDeclaration, name: &str, state: &mut Self::State, ) { if &self != &*state { Rndr::set_css_property(style, name, &self); } *state = self; } fn hydrate( self, _style: &CssStyleDeclaration, _name: &str, ) -> Self::State { self } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } } impl IntoStyleValue for Option<$ty> { type AsyncOutput = Self; type State = Self; type Cloneable = Self; type CloneableOwned = Self; fn to_html(self, name: &str, style: &mut String) { if let Some(value) = self { style.push_str(name); style.push(':'); style.push_str(&value); style.push(';'); } } fn build( self, style: &CssStyleDeclaration, name: &str, ) -> Self::State { if let Some(value) = &self { Rndr::set_css_property(style, name, &value); } self } fn rebuild( self, style: &CssStyleDeclaration, name: &str, state: &mut Self::State, ) { match (&state, &self) { (None, None) => {} (Some(_), None) => Rndr::remove_css_property(style, name), (None, Some(value)) => { Rndr::set_css_property(style, name, &value) } (Some(old), Some(new)) => { if new != &*old { Rndr::set_css_property(style, name, &new); } } } *state = self; } fn hydrate( self, _style: &CssStyleDeclaration, _name: &str, ) -> Self::State { self } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } } }; } impl_style_value!(&'static str); impl_style_value!(Arc<str>); impl_style_value!(String); #[cfg(feature = "oco")] impl_style_value!(oco_ref::Oco<'static, str>); #[cfg(all(feature = "nightly", rustc_nightly))] impl<const V: &'static str> IntoStyleValue for Static<V> { type AsyncOutput = Self; type State = Self; type Cloneable = Self; type CloneableOwned = Self; fn to_html(self, name: &str, style: &mut String) { style.push_str(name); style.push(':'); style.push_str(V); style.push(';'); } fn build(self, style: &CssStyleDeclaration, name: &str) -> Self::State { Rndr::set_css_property(style, name, V); self } fn rebuild( self, _style: &CssStyleDeclaration, _name: &str, _state: &mut Self::State, ) { } fn hydrate(self, _style: &CssStyleDeclaration, _name: &str) -> Self::State { self } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } } #[cfg(all(feature = "nightly", rustc_nightly))] impl<const V: &'static str> IntoStyleValue for Option<Static<V>> { type AsyncOutput = Self; type State = Self; type Cloneable = Self; type CloneableOwned = Self; fn to_html(self, name: &str, style: &mut String) { if self.is_some() { style.push_str(name); style.push(':'); style.push_str(V); style.push(';'); } } fn build(self, style: &CssStyleDeclaration, name: &str) -> Self::State { if self.is_some() { Rndr::set_css_property(style, name, V); } self } fn rebuild( self, style: &CssStyleDeclaration, name: &str, state: &mut Self::State, ) { match (&state, &self) { (None, None) => {} (Some(_), None) => Rndr::remove_css_property(style, name), (None, Some(_)) => Rndr::set_css_property(style, name, V), (Some(_), Some(_)) => {} } *state = self; } fn hydrate(self, _style: &CssStyleDeclaration, _name: &str) -> Self::State { self } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } } #[cfg(all(feature = "nightly", rustc_nightly))] impl<const V: &'static str> IntoStyle for crate::view::static_types::Static<V> { type AsyncOutput = Self; type State = (); type Cloneable = Self; type CloneableOwned = Self; fn to_html(self, style: &mut String) { style.push_str(V); style.push(';'); } fn hydrate<const FROM_SERVER: bool>( self, _el: &crate::renderer::types::Element, ) -> Self::State { } fn build(self, el: &crate::renderer::types::Element) -> Self::State { Rndr::set_attribute(el, "style", V); } fn rebuild(self, _state: &mut Self::State) {} fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn reset(_state: &mut Self::State) {} } /* #[cfg(test)] mod tests { use crate::{ html::{ element::{p, HtmlElement}, style::style, }, renderer::dom::Dom, view::{Position, PositionState, RenderHtml}, }; #[test] fn adds_simple_style() { let mut html = String::new(); let el: HtmlElement<_, _, _, Dom> = p(style("display: block"), ()); el.to_html(&mut html, &PositionState::new(Position::FirstChild)); assert_eq!(html, r#"<p style="display: block;"></p>"#); } #[test] fn mixes_plain_and_specific_styles() { let mut html = String::new(); let el: HtmlElement<_, _, _, Dom> = p((style("display: block"), style(("color", "blue"))), ()); el.to_html(&mut html, &PositionState::new(Position::FirstChild)); assert_eq!(html, r#"<p style="display: block;color:blue;"></p>"#); } #[test] fn handles_dynamic_styles() { let mut html = String::new(); let el: HtmlElement<_, _, _, Dom> = p( ( style("display: block"), style(("color", "blue")), style(("font-weight", || "bold".to_string())), ), (), ); el.to_html(&mut html, &PositionState::new(Position::FirstChild)); assert_eq!( html, r#"<p style="display: block;color:blue;font-weight:bold;"></p>"# ); } } */
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/property.rs
tachys/src/html/property.rs
use super::attribute::{ maybe_next_attr_erasure_macros::next_attr_output_type, Attribute, NextAttribute, }; use crate::{ html::attribute::{ maybe_next_attr_erasure_macros::next_attr_combine, NamedAttributeKey, }, renderer::Rndr, view::{Position, ToTemplate}, }; use send_wrapper::SendWrapper; use std::{borrow::Cow, sync::Arc}; use wasm_bindgen::JsValue; /// Creates an [`Attribute`] that will set a DOM property on an element. #[inline(always)] pub fn prop<K, P>(key: K, value: P) -> Property<K, P> where K: AsRef<str>, P: IntoProperty, { Property { key, value: (!cfg!(feature = "ssr")).then(|| SendWrapper::new(value)), } } /// An [`Attribute`] that will set a DOM property on an element. #[derive(Debug)] pub struct Property<K, P> { key: K, // property values will only be accessed in the browser value: Option<SendWrapper<P>>, } impl<K, P> Clone for Property<K, P> where K: Clone, P: Clone, { fn clone(&self) -> Self { Self { key: self.key.clone(), value: self.value.clone(), } } } impl<K, P> Attribute for Property<K, P> where K: AsRef<str> + Send, P: IntoProperty, { const MIN_LENGTH: usize = 0; type AsyncOutput = Self; type State = P::State; type Cloneable = Property<Arc<str>, P::Cloneable>; type CloneableOwned = Property<Arc<str>, P::CloneableOwned>; #[inline(always)] fn html_len(&self) -> usize { 0 } fn to_html( self, _buf: &mut String, _class: &mut String, _style: &mut String, _inner_html: &mut String, ) { } fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, ) -> Self::State { self.value .expect("property removed early") .take() .hydrate::<FROM_SERVER>(el, self.key.as_ref()) } fn build(self, el: &crate::renderer::types::Element) -> Self::State { self.value .expect("property removed early") .take() .build(el, self.key.as_ref()) } fn rebuild(self, state: &mut Self::State) { self.value .expect("property removed early") .take() .rebuild(state, self.key.as_ref()) } fn into_cloneable(self) -> Self::Cloneable { Property { key: self.key.as_ref().into(), value: self .value .map(|value| SendWrapper::new(value.take().into_cloneable())), } } fn into_cloneable_owned(self) -> Self::CloneableOwned { Property { key: self.key.as_ref().into(), value: self.value.map(|value| { SendWrapper::new(value.take().into_cloneable_owned()) }), } } fn dry_resolve(&mut self) {} async fn resolve(self) -> Self::AsyncOutput { self } fn keys(&self) -> Vec<NamedAttributeKey> { vec![NamedAttributeKey::Property( self.key.as_ref().to_string().into(), )] } } impl<K, P> NextAttribute for Property<K, P> where K: AsRef<str> + Send, P: IntoProperty, { next_attr_output_type!(Self, NewAttr); fn add_any_attr<NewAttr: Attribute>( self, new_attr: NewAttr, ) -> Self::Output<NewAttr> { next_attr_combine!(self, new_attr) } } impl<K, P> ToTemplate for Property<K, P> where K: AsRef<str>, P: IntoProperty, { fn to_template( _buf: &mut String, _class: &mut String, _style: &mut String, _inner_html: &mut String, _position: &mut Position, ) { } } /// A possible value for a DOM property. pub trait IntoProperty { /// The view state retained between building and rebuilding. type State; /// An equivalent value that can be cloned. type Cloneable: IntoProperty + Clone; /// An equivalent value that can be cloned and is `'static`. type CloneableOwned: IntoProperty + Clone + 'static; /// Adds the property on an element created from HTML. fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State; /// Adds the property during client-side rendering. fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State; /// Updates the property with a new value. fn rebuild(self, state: &mut Self::State, key: &str); /// Converts this to a cloneable type. fn into_cloneable(self) -> Self::Cloneable; /// Converts this to a cloneable, owned type. fn into_cloneable_owned(self) -> Self::CloneableOwned; } macro_rules! prop_type { ($prop_type:ty) => { impl IntoProperty for $prop_type { type State = (crate::renderer::types::Element, JsValue); type Cloneable = Self; type CloneableOwned = Self; fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = self.into(); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = self.into(); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn rebuild(self, state: &mut Self::State, key: &str) { let (el, prev) = state; let value = self.into(); Rndr::set_property_or_value(el, key, &value); *prev = value; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } } impl IntoProperty for Option<$prop_type> { type State = (crate::renderer::types::Element, JsValue); type Cloneable = Self; type CloneableOwned = Self; fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let was_some = self.is_some(); let value = self.into(); if was_some { Rndr::set_property_or_value(el, key, &value); } (el.clone(), value) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let was_some = self.is_some(); let value = self.into(); if was_some { Rndr::set_property_or_value(el, key, &value); } (el.clone(), value) } fn rebuild(self, state: &mut Self::State, key: &str) { let (el, prev) = state; let value = self.into(); Rndr::set_property_or_value(el, key, &value); *prev = value; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } } }; } macro_rules! prop_type_str { ($prop_type:ty) => { impl IntoProperty for $prop_type { type State = (crate::renderer::types::Element, JsValue); type Cloneable = Arc<str>; type CloneableOwned = Arc<str>; fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = JsValue::from(&*self); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = JsValue::from(&*self); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn rebuild(self, state: &mut Self::State, key: &str) { let (el, prev) = state; let value = JsValue::from(&*self); Rndr::set_property_or_value(el, key, &value); *prev = value; } fn into_cloneable(self) -> Self::Cloneable { let this: &str = &*self; this.into() } fn into_cloneable_owned(self) -> Self::CloneableOwned { let this: &str = &*self; this.into() } } impl IntoProperty for Option<$prop_type> { type State = (crate::renderer::types::Element, JsValue); type Cloneable = Option<Arc<str>>; type CloneableOwned = Option<Arc<str>>; fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let was_some = self.is_some(); let value = JsValue::from(self.map(|n| JsValue::from_str(&n))); if was_some { Rndr::set_property_or_value(el, key, &value); } (el.clone(), value) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let was_some = self.is_some(); let value = JsValue::from(self.map(|n| JsValue::from_str(&n))); if was_some { Rndr::set_property_or_value(el, key, &value); } (el.clone(), value) } fn rebuild(self, state: &mut Self::State, key: &str) { let (el, prev) = state; let value = JsValue::from(self.map(|n| JsValue::from_str(&n))); Rndr::set_property_or_value(el, key, &value); *prev = value; } fn into_cloneable(self) -> Self::Cloneable { self.map(|n| { let this: &str = &*n; this.into() }) } fn into_cloneable_owned(self) -> Self::CloneableOwned { self.map(|n| { let this: &str = &*n; this.into() }) } } }; } impl IntoProperty for Arc<str> { type State = (crate::renderer::types::Element, JsValue); type Cloneable = Self; type CloneableOwned = Self; fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = JsValue::from_str(self.as_ref()); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let value = JsValue::from_str(self.as_ref()); Rndr::set_property_or_value(el, key, &value); (el.clone(), value) } fn rebuild(self, state: &mut Self::State, key: &str) { let (el, prev) = state; let value = JsValue::from_str(self.as_ref()); Rndr::set_property_or_value(el, key, &value); *prev = value; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } } impl IntoProperty for Option<Arc<str>> { type State = (crate::renderer::types::Element, JsValue); type Cloneable = Self; type CloneableOwned = Self; fn hydrate<const FROM_SERVER: bool>( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let was_some = self.is_some(); let value = JsValue::from(self.map(|n| JsValue::from_str(&n))); if was_some { Rndr::set_property_or_value(el, key, &value); } (el.clone(), value) } fn build( self, el: &crate::renderer::types::Element, key: &str, ) -> Self::State { let was_some = self.is_some(); let value = JsValue::from(self.map(|n| JsValue::from_str(&n))); if was_some { Rndr::set_property_or_value(el, key, &value); } (el.clone(), value) } fn rebuild(self, state: &mut Self::State, key: &str) { let (el, prev) = state; let value = JsValue::from(self.map(|n| JsValue::from_str(&n))); Rndr::set_property_or_value(el, key, &value); *prev = value; } fn into_cloneable(self) -> Self::Cloneable { self } fn into_cloneable_owned(self) -> Self::CloneableOwned { self } } prop_type!(JsValue); prop_type!(usize); prop_type!(u8); prop_type!(u16); prop_type!(u32); prop_type!(u64); prop_type!(u128); prop_type!(isize); prop_type!(i8); prop_type!(i16); prop_type!(i32); prop_type!(i64); prop_type!(i128); prop_type!(f32); prop_type!(f64); prop_type!(bool); prop_type_str!(String); prop_type_str!(&String); prop_type_str!(&str); prop_type_str!(Cow<'_, str>);
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/islands.rs
tachys/src/html/islands.rs
use super::attribute::{any_attribute::AnyAttribute, Attribute}; use crate::{ hydration::Cursor, prelude::{Render, RenderHtml}, ssr::StreamBuilder, view::{add_attr::AddAnyAttr, Position, PositionState}, }; /// An island of interactivity in an otherwise-inert HTML document. pub struct Island<View> { has_element_representation: bool, component: &'static str, props_json: String, view: View, } const ISLAND_TAG: &str = "leptos-island"; const ISLAND_CHILDREN_TAG: &str = "leptos-children"; impl<View> Island<View> { /// Creates a new island with the given component name. pub fn new(component: &'static str, view: View) -> Self { Island { has_element_representation: Self::should_have_element_representation(), component, props_json: String::new(), view, } } /// Adds serialized component props as JSON. pub fn with_props(mut self, props_json: String) -> Self { self.props_json = props_json; self } fn open_tag(component: &'static str, props: &str, buf: &mut String) { buf.push('<'); buf.push_str(ISLAND_TAG); buf.push(' '); buf.push_str("data-component=\""); buf.push_str(component); buf.push('"'); if !props.is_empty() { buf.push_str(" data-props=\""); buf.push_str(&html_escape::encode_double_quoted_attribute(&props)); buf.push('"'); } buf.push('>'); } fn close_tag(buf: &mut String) { buf.push_str("</"); buf.push_str(ISLAND_TAG); buf.push('>'); } /// Whether this island should be represented by an actual HTML element fn should_have_element_representation() -> bool { #[cfg(feature = "reactive_graph")] { use reactive_graph::owner::{use_context, IsHydrating}; let already_hydrating = use_context::<IsHydrating>().map(|h| h.0).unwrap_or(false); !already_hydrating } #[cfg(not(feature = "reactive_graph"))] { true } } } impl<View> Render for Island<View> where View: Render, { type State = View::State; fn build(self) -> Self::State { self.view.build() } fn rebuild(self, state: &mut Self::State) { self.view.rebuild(state); } } impl<View> AddAnyAttr for Island<View> where View: RenderHtml, { type Output<SomeNewAttr: Attribute> = Island<<View as AddAnyAttr>::Output<SomeNewAttr>>; fn add_any_attr<NewAttr: Attribute>( self, attr: NewAttr, ) -> Self::Output<NewAttr> where Self::Output<NewAttr>: RenderHtml, { let Island { has_element_representation, component, props_json, view, } = self; Island { has_element_representation, component, props_json, view: view.add_any_attr(attr), } } } impl<View> RenderHtml for Island<View> where View: RenderHtml, { type AsyncOutput = Island<View::AsyncOutput>; type Owned = Island<View::Owned>; const MIN_LENGTH: usize = ISLAND_TAG.len() * 2 + "<>".len() + "</>".len() + "data-component".len() + View::MIN_LENGTH; fn dry_resolve(&mut self) { self.view.dry_resolve() } async fn resolve(self) -> Self::AsyncOutput { let Island { has_element_representation, component, props_json, view, } = self; Island { has_element_representation, component, props_json, view: view.resolve().await, } } fn to_html_with_buf( self, buf: &mut String, position: &mut Position, escape: bool, mark_branches: bool, extra_attrs: Vec<AnyAttribute>, ) { let has_element = self.has_element_representation; if has_element { Self::open_tag(self.component, &self.props_json, buf); } self.view.to_html_with_buf( buf, position, escape, mark_branches, extra_attrs, ); if has_element { Self::close_tag(buf); } } fn to_html_async_with_buf<const OUT_OF_ORDER: bool>( self, buf: &mut StreamBuilder, position: &mut Position, escape: bool, mark_branches: bool, extra_attrs: Vec<AnyAttribute>, ) where Self: Sized, { let has_element = self.has_element_representation; // insert the opening tag synchronously let mut tag = String::new(); if has_element { Self::open_tag(self.component, &self.props_json, &mut tag); } buf.push_sync(&tag); // streaming render for the view self.view.to_html_async_with_buf::<OUT_OF_ORDER>( buf, position, escape, mark_branches, extra_attrs, ); // and insert the closing tag synchronously tag.clear(); if has_element { Self::close_tag(&mut tag); } buf.push_sync(&tag); } fn hydrate<const FROM_SERVER: bool>( self, cursor: &Cursor, position: &PositionState, ) -> Self::State { if self.has_element_representation { if position.get() == Position::FirstChild { cursor.child(); } else if position.get() == Position::NextChild { cursor.sibling(); } position.set(Position::FirstChild); } self.view.hydrate::<FROM_SERVER>(cursor, position) } fn into_owned(self) -> Self::Owned { Island { has_element_representation: self.has_element_representation, component: self.component, props_json: self.props_json, view: self.view.into_owned(), } } } /// The children that will be projected into an [`Island`]. pub struct IslandChildren<View> { view: View, on_hydrate: Option<Box<dyn Fn() + Send + Sync>>, } impl<View> IslandChildren<View> { /// Creates a new representation of the children. pub fn new(view: View) -> Self { IslandChildren { view, on_hydrate: None, } } /// Creates a new representation of the children, with a function to be called whenever /// a child island hydrates. pub fn new_with_on_hydrate( view: View, on_hydrate: impl Fn() + Send + Sync + 'static, ) -> Self { IslandChildren { view, on_hydrate: Some(Box::new(on_hydrate)), } } fn open_tag(buf: &mut String) { buf.push('<'); buf.push_str(ISLAND_CHILDREN_TAG); buf.push('>'); } fn close_tag(buf: &mut String) { buf.push_str("</"); buf.push_str(ISLAND_CHILDREN_TAG); buf.push('>'); } } impl<View> Render for IslandChildren<View> where View: Render, { type State = (); fn build(self) -> Self::State {} fn rebuild(self, _state: &mut Self::State) {} } impl<View> AddAnyAttr for IslandChildren<View> where View: RenderHtml, { type Output<SomeNewAttr: Attribute> = IslandChildren<<View as AddAnyAttr>::Output<SomeNewAttr>>; fn add_any_attr<NewAttr: Attribute>( self, attr: NewAttr, ) -> Self::Output<NewAttr> where Self::Output<NewAttr>: RenderHtml, { let IslandChildren { view, on_hydrate } = self; IslandChildren { view: view.add_any_attr(attr), on_hydrate, } } } impl<View> RenderHtml for IslandChildren<View> where View: RenderHtml, { type AsyncOutput = IslandChildren<View::AsyncOutput>; type Owned = IslandChildren<View::Owned>; const MIN_LENGTH: usize = ISLAND_CHILDREN_TAG.len() * 2 + "<>".len() + "</>".len() + View::MIN_LENGTH; fn dry_resolve(&mut self) { self.view.dry_resolve() } async fn resolve(self) -> Self::AsyncOutput { let IslandChildren { view, on_hydrate } = self; IslandChildren { view: view.resolve().await, on_hydrate, } } fn to_html_with_buf( self, buf: &mut String, position: &mut Position, escape: bool, mark_branches: bool, extra_attrs: Vec<AnyAttribute>, ) { Self::open_tag(buf); self.view.to_html_with_buf( buf, position, escape, mark_branches, extra_attrs, ); Self::close_tag(buf); } fn to_html_async_with_buf<const OUT_OF_ORDER: bool>( self, buf: &mut StreamBuilder, position: &mut Position, escape: bool, mark_branches: bool, extra_attrs: Vec<AnyAttribute>, ) where Self: Sized, { // insert the opening tag synchronously let mut tag = String::new(); Self::open_tag(&mut tag); buf.push_sync(&tag); // streaming render for the view self.view.to_html_async_with_buf::<OUT_OF_ORDER>( buf, position, escape, mark_branches, extra_attrs, ); // and insert the closing tag synchronously tag.clear(); Self::close_tag(&mut tag); buf.push_sync(&tag); } fn hydrate<const FROM_SERVER: bool>( self, cursor: &Cursor, position: &PositionState, ) -> Self::State { // island children aren't hydrated // we update the walk to pass over them // but we don't hydrate their children let curr_position = position.get(); if curr_position == Position::FirstChild { cursor.child(); } else if curr_position != Position::Current { cursor.sibling(); } position.set(Position::NextChild); if let Some(on_hydrate) = self.on_hydrate { use crate::{ hydration::failed_to_cast_element, renderer::CastFrom, }; let el = crate::renderer::types::Element::cast_from(cursor.current()) .unwrap_or_else(|| { failed_to_cast_element( "leptos-children", cursor.current(), ) }); let cb = wasm_bindgen::closure::Closure::wrap( on_hydrate as Box<dyn Fn()>, ); _ = js_sys::Reflect::set( &el, &wasm_bindgen::JsValue::from_str("$$on_hydrate"), &cb.into_js_value(), ); } } fn into_owned(self) -> Self::Owned { IslandChildren { view: self.view.into_owned(), on_hydrate: self.on_hydrate, } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/element/mod.rs
tachys/src/html/element/mod.rs
#[cfg(any(debug_assertions, leptos_debuginfo))] use crate::hydration::set_currently_hydrating; #[cfg(erase_components)] use crate::view::any_view::AnyView; use crate::{ html::attribute::Attribute, hydration::{failed_to_cast_element, Cursor}, renderer::{CastFrom, Rndr}, ssr::StreamBuilder, view::{ add_attr::AddAnyAttr, IntoRender, Mountable, Position, PositionState, Render, RenderHtml, ToTemplate, }, }; use const_str_slice_concat::{ const_concat, const_concat_with_prefix, str_from_buffer, }; use futures::future::join; use std::ops::Deref; mod custom; mod element_ext; mod elements; mod inner_html; use super::attribute::{ any_attribute::AnyAttribute, escape_attr, NextAttribute, }; pub use custom::*; pub use element_ext::*; pub use elements::*; pub use inner_html::*; #[cfg(any(debug_assertions, leptos_debuginfo))] use std::panic::Location; /// The typed representation of an HTML element. #[derive(Debug, PartialEq, Eq)] pub struct HtmlElement<E, At, Ch> { #[cfg(any(debug_assertions, leptos_debuginfo))] pub(crate) defined_at: &'static Location<'static>, pub(crate) tag: E, pub(crate) attributes: At, pub(crate) children: Ch, } impl<E: Clone, At: Clone, Ch: Clone> Clone for HtmlElement<E, At, Ch> { fn clone(&self) -> Self { HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: self.defined_at, tag: self.tag.clone(), attributes: self.attributes.clone(), children: self.children.clone(), } } } impl<E: Copy, At: Copy, Ch: Copy> Copy for HtmlElement<E, At, Ch> {} /*impl<E, At, Ch> ElementType for HtmlElement<E, At, Ch> where E: ElementType, { type Output = E::Output; const TAG: &'static str = E::TAG; const SELF_CLOSING: bool = E::SELF_CLOSING; fn tag(&self) -> &str { Self::TAG } }*/ #[cfg(not(erase_components))] impl<E, At, Ch, NewChild> ElementChild<NewChild> for HtmlElement<E, At, Ch> where E: ElementWithChildren, Ch: RenderHtml + next_tuple::NextTuple, <Ch as next_tuple::NextTuple>::Output<NewChild::Output>: Render, NewChild: IntoRender, NewChild::Output: RenderHtml, { type Output = HtmlElement< E, At, <Ch as next_tuple::NextTuple>::Output<NewChild::Output>, >; fn child(self, child: NewChild) -> Self::Output { HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: self.defined_at, tag: self.tag, attributes: self.attributes, children: self.children.next_tuple(child.into_render()), } } } #[cfg(erase_components)] impl<E, At, Ch, NewChild> ElementChild<NewChild> for HtmlElement<E, At, Ch> where E: ElementWithChildren, Ch: RenderHtml + NextChildren, NewChild: IntoRender, NewChild::Output: RenderHtml, { type Output = HtmlElement<E, At, crate::view::iterators::StaticVec<AnyView>>; fn child(self, child: NewChild) -> Self::Output { use crate::view::any_view::IntoAny; HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: self.defined_at, tag: self.tag, attributes: self.attributes, children: self .children .next_children(child.into_render().into_any()), } } } #[cfg(erase_components)] trait NextChildren { fn next_children( self, child: AnyView, ) -> crate::view::iterators::StaticVec<AnyView>; } #[cfg(erase_components)] mod erased_tuples { use super::*; use crate::view::{any_view::IntoAny, iterators::StaticVec}; impl NextChildren for StaticVec<AnyView> { fn next_children(mut self, child: AnyView) -> StaticVec<AnyView> { self.0.push(child); self } } impl NextChildren for () { fn next_children(self, child: AnyView) -> StaticVec<AnyView> { vec![child].into() } } impl<T: RenderHtml> NextChildren for (T,) { fn next_children(self, child: AnyView) -> StaticVec<AnyView> { vec![self.0.into_owned().into_any(), child].into() } } macro_rules! impl_next_children_tuples { ($($ty:ident),*) => { impl<$($ty: RenderHtml),*> NextChildren for ($($ty,)*) { fn next_children( self, child: AnyView, ) -> StaticVec<AnyView> { #[allow(non_snake_case)] let ($($ty,)*) = self; vec![$($ty.into_owned().into_any(),)* child].into() } } }; } impl_next_children_tuples!(AA, BB); impl_next_children_tuples!(AA, BB, CC); impl_next_children_tuples!(AA, BB, CC, DD); impl_next_children_tuples!(AA, BB, CC, DD, EE); impl_next_children_tuples!(AA, BB, CC, DD, EE, FF); impl_next_children_tuples!(AA, BB, CC, DD, EE, FF, GG); impl_next_children_tuples!(AA, BB, CC, DD, EE, FF, GG, HH); impl_next_children_tuples!(AA, BB, CC, DD, EE, FF, GG, HH, II); impl_next_children_tuples!(AA, BB, CC, DD, EE, FF, GG, HH, II, JJ); impl_next_children_tuples!(AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK); impl_next_children_tuples!(AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT, UU ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT, UU, VV ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT, UU, VV, WW ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT, UU, VV, WW, XX ); impl_next_children_tuples!( AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT, UU, VV, WW, XX, YY ); } impl<E, At, Ch> AddAnyAttr for HtmlElement<E, At, Ch> where E: ElementType + Send, At: Attribute + Send, Ch: RenderHtml + Send, { type Output<SomeNewAttr: Attribute> = HtmlElement<E, <At as NextAttribute>::Output<SomeNewAttr>, Ch>; fn add_any_attr<NewAttr: Attribute>( self, attr: NewAttr, ) -> Self::Output<NewAttr> { let HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, attributes, children, } = self; HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, attributes: attributes.add_any_attr(attr), children, } } } /// Adds a child to the element. pub trait ElementChild<NewChild> where NewChild: IntoRender, { /// The type of the element, with the child added. type Output; /// Adds a child to an element. fn child(self, child: NewChild) -> Self::Output; } /// An HTML element. pub trait ElementType: Send + 'static { /// The underlying native widget type that this represents. type Output; /// The element's tag. const TAG: &'static str; /// Whether the element is self-closing. const SELF_CLOSING: bool; /// Whether the element's children should be escaped. This should be `true` except for elements /// like `<style>` and `<script>`, which include other languages that should not use HTML /// entity escaping. const ESCAPE_CHILDREN: bool; /// The element's namespace, if it is not HTML. const NAMESPACE: Option<&'static str>; /// The element's tag. fn tag(&self) -> &str; } /// Denotes that the type that implements this has a particular HTML element type. pub trait HasElementType { /// The element type. type ElementType; } pub(crate) trait ElementWithChildren {} impl<E, At, Ch> HasElementType for HtmlElement<E, At, Ch> where E: ElementType, { type ElementType = E::Output; } impl<E, At, Ch> Render for HtmlElement<E, At, Ch> where E: ElementType, At: Attribute, Ch: Render, { type State = ElementState<At::State, Ch::State>; fn rebuild(self, state: &mut Self::State) { // check whether the tag is the same, for custom elements // because this is const `false` for all other element types, // the compiler should be able to optimize it out if E::TAG.is_empty() { // see https://github.com/leptos-rs/leptos/issues/4412 let new_tag = self.tag.tag(); // this is not particularly efficient, but it saves us from // having to keep track of the tag name for every element state let old_tag = state.el.tag_name(); if new_tag != old_tag { let mut new_state = self.build(); state.insert_before_this(&mut new_state); state.unmount(); *state = new_state; return; } } // rebuild attributes and children for any element let ElementState { attrs, children, .. } = state; self.attributes.rebuild(attrs); if let Some(children) = children { self.children.rebuild(children); } } fn build(self) -> Self::State { let el = Rndr::create_element(self.tag.tag(), E::NAMESPACE); let attrs = self.attributes.build(&el); let children = if E::SELF_CLOSING { None } else { let mut children = self.children.build(); children.mount(&el, None); Some(children) }; ElementState { el, attrs, children, } } } impl<E, At, Ch> RenderHtml for HtmlElement<E, At, Ch> where E: ElementType + Send, At: Attribute + Send, Ch: RenderHtml + Send, { type AsyncOutput = HtmlElement<E, At::AsyncOutput, Ch::AsyncOutput>; type Owned = HtmlElement<E, At::CloneableOwned, Ch::Owned>; const MIN_LENGTH: usize = if E::SELF_CLOSING { 3 // < ... /> + E::TAG.len() + At::MIN_LENGTH } else { 2 // < ... > + E::TAG.len() + At::MIN_LENGTH + Ch::MIN_LENGTH + 3 // </ ... > + E::TAG.len() }; fn dry_resolve(&mut self) { self.attributes.dry_resolve(); self.children.dry_resolve(); } async fn resolve(self) -> Self::AsyncOutput { let (attributes, children) = join(self.attributes.resolve(), self.children.resolve()).await; HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: self.defined_at, tag: self.tag, attributes, children, } } fn html_len(&self) -> usize { if E::SELF_CLOSING { 3 // < ... /> + E::TAG.len() + self.attributes.html_len() } else { 2 // < ... > + E::TAG.len() + self.attributes.html_len() + self.children.html_len() + 3 // </ ... > + E::TAG.len() } } fn to_html_with_buf( self, buf: &mut String, position: &mut Position, _escape: bool, mark_branches: bool, extra_attributes: Vec<AnyAttribute>, ) { // opening tag buf.push('<'); buf.push_str(self.tag.tag()); let inner_html = attributes_to_html((self.attributes, extra_attributes), buf); buf.push('>'); if !E::SELF_CLOSING { if !inner_html.is_empty() { buf.push_str(&inner_html); } else if Ch::EXISTS { // children *position = Position::FirstChild; self.children.to_html_with_buf( buf, position, E::ESCAPE_CHILDREN, mark_branches, vec![], ); } // closing tag buf.push_str("</"); buf.push_str(self.tag.tag()); buf.push('>'); } *position = Position::NextChild; } fn to_html_async_with_buf<const OUT_OF_ORDER: bool>( self, buffer: &mut StreamBuilder, position: &mut Position, _escape: bool, mark_branches: bool, extra_attributes: Vec<AnyAttribute>, ) where Self: Sized, { let mut buf = String::with_capacity(Self::MIN_LENGTH); // opening tag buf.push('<'); buf.push_str(self.tag.tag()); let inner_html = attributes_to_html((self.attributes, extra_attributes), &mut buf); buf.push('>'); buffer.push_sync(&buf); if !E::SELF_CLOSING { // children *position = Position::FirstChild; if !inner_html.is_empty() { buffer.push_sync(&inner_html); } else if Ch::EXISTS { self.children.to_html_async_with_buf::<OUT_OF_ORDER>( buffer, position, E::ESCAPE_CHILDREN, mark_branches, vec![], ); } // closing tag let mut buf = String::with_capacity(3 + E::TAG.len()); buf.push_str("</"); buf.push_str(self.tag.tag()); buf.push('>'); buffer.push_sync(&buf); } *position = Position::NextChild; } fn hydrate<const FROM_SERVER: bool>( self, cursor: &Cursor, position: &PositionState, ) -> Self::State { // non-Static custom elements need special support in templates // because they haven't been inserted type-wise if E::TAG.is_empty() && !FROM_SERVER { panic!("Custom elements are not supported in ViewTemplate."); } // codegen optimisation: fn inner_1( cursor: &Cursor, position: &PositionState, tag_name: &str, #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: &'static std::panic::Location<'static>, ) -> crate::renderer::types::Element { #[cfg(any(debug_assertions, leptos_debuginfo))] { set_currently_hydrating(Some(defined_at)); } let curr_position = position.get(); if curr_position == Position::FirstChild { cursor.child(); } else if curr_position != Position::Current { cursor.sibling(); } crate::renderer::types::Element::cast_from(cursor.current()) .unwrap_or_else(|| { failed_to_cast_element(tag_name, cursor.current()) }) } let el = inner_1( cursor, position, E::TAG, #[cfg(any(debug_assertions, leptos_debuginfo))] self.defined_at, ); let attrs = self.attributes.hydrate::<FROM_SERVER>(&el); // hydrate children let children = if !Ch::EXISTS || !E::ESCAPE_CHILDREN { None } else { position.set(Position::FirstChild); Some(self.children.hydrate::<FROM_SERVER>(cursor, position)) }; // codegen optimisation: fn inner_2( cursor: &Cursor, position: &PositionState, el: &crate::renderer::types::Element, ) { // go to next sibling cursor.set( <crate::renderer::types::Element as AsRef< crate::renderer::types::Node, >>::as_ref(el) .clone(), ); position.set(Position::NextChild); } inner_2(cursor, position, &el); ElementState { el, attrs, children, } } async fn hydrate_async( self, cursor: &Cursor, position: &PositionState, ) -> Self::State { // codegen optimisation: fn inner_1( cursor: &Cursor, position: &PositionState, tag_name: &str, #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: &'static std::panic::Location<'static>, ) -> crate::renderer::types::Element { #[cfg(any(debug_assertions, leptos_debuginfo))] { set_currently_hydrating(Some(defined_at)); } let curr_position = position.get(); if curr_position == Position::FirstChild { cursor.child(); } else if curr_position != Position::Current { cursor.sibling(); } crate::renderer::types::Element::cast_from(cursor.current()) .unwrap_or_else(|| { failed_to_cast_element(tag_name, cursor.current()) }) } let el = inner_1( cursor, position, E::TAG, #[cfg(any(debug_assertions, leptos_debuginfo))] self.defined_at, ); let attrs = self.attributes.hydrate::<true>(&el); // hydrate children let children = if !Ch::EXISTS || !E::ESCAPE_CHILDREN { None } else { position.set(Position::FirstChild); Some(self.children.hydrate_async(cursor, position).await) }; // codegen optimisation: fn inner_2( cursor: &Cursor, position: &PositionState, el: &crate::renderer::types::Element, ) { // go to next sibling cursor.set( <crate::renderer::types::Element as AsRef< crate::renderer::types::Node, >>::as_ref(el) .clone(), ); position.set(Position::NextChild); } inner_2(cursor, position, &el); ElementState { el, attrs, children, } } fn into_owned(self) -> Self::Owned { HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: self.defined_at, tag: self.tag, attributes: self.attributes.into_cloneable_owned(), children: self.children.into_owned(), } } } /// Renders an [`Attribute`] (which can be one or more HTML attributes) into an HTML buffer. pub fn attributes_to_html<At>(attr: At, buf: &mut String) -> String where At: Attribute, { // `class` and `style` are created first, and pushed later // this is because they can be filled by a mixture of values that include // either the whole value (`class="..."` or `style="..."`) and individual // classes and styles (`class:foo=true` or `style:height="40px"`), so they // need to be filled during the whole attribute-creation process and then // added // String doesn't allocate until the first push, so this is cheap if there // is no class or style on an element let mut class = String::new(); let mut style = String::new(); let mut inner_html = String::new(); // inject regular attributes, and fill class and style attr.to_html(buf, &mut class, &mut style, &mut inner_html); if !class.is_empty() { buf.push(' '); buf.push_str("class=\""); buf.push_str(&escape_attr(class.trim_start().trim_end())); buf.push('"'); } if !style.is_empty() { buf.push(' '); buf.push_str("style=\""); buf.push_str(&escape_attr(style.trim_start().trim_end())); buf.push('"'); } inner_html } /// The retained view state for an HTML element. pub struct ElementState<At, Ch> { pub(crate) el: crate::renderer::types::Element, pub(crate) attrs: At, pub(crate) children: Option<Ch>, } impl<At, Ch> Deref for ElementState<At, Ch> { type Target = crate::renderer::types::Element; fn deref(&self) -> &Self::Target { &self.el } } impl<At, Ch> Mountable for ElementState<At, Ch> { fn unmount(&mut self) { Rndr::remove(self.el.as_ref()); } fn mount( &mut self, parent: &crate::renderer::types::Element, marker: Option<&crate::renderer::types::Node>, ) { Rndr::insert_node(parent, self.el.as_ref(), marker); } fn try_mount( &mut self, parent: &crate::renderer::types::Element, marker: Option<&crate::renderer::types::Node>, ) -> bool { Rndr::try_insert_node(parent, self.el.as_ref(), marker) } fn insert_before_this(&self, child: &mut dyn Mountable) -> bool { if let Some(parent) = Rndr::get_parent(self.el.as_ref()) { if let Some(element) = crate::renderer::types::Element::cast_from(parent) { child.mount(&element, Some(self.el.as_ref())); return true; } } false } fn elements(&self) -> Vec<crate::renderer::types::Element> { vec![self.el.clone()] } } impl<E, At, Ch> ToTemplate for HtmlElement<E, At, Ch> where E: ElementType, At: Attribute + ToTemplate, Ch: Render + ToTemplate, { const TEMPLATE: &'static str = str_from_buffer(&const_concat(&[ "<", E::TAG, At::TEMPLATE, str_from_buffer(&const_concat_with_prefix( &[At::CLASS], " class=\"", "\"", )), str_from_buffer(&const_concat_with_prefix( &[At::STYLE], " style=\"", "\"", )), ">", Ch::TEMPLATE, "</", E::TAG, ">", ])); #[allow(unused)] // the variables `class` and `style` might be used, but only with `nightly` feature fn to_template( buf: &mut String, class: &mut String, style: &mut String, inner_html: &mut String, position: &mut Position, ) { // for custom elements without type known at compile time, do nothing if !E::TAG.is_empty() { // opening tag and attributes let mut class = String::new(); let mut style = String::new(); let mut inner_html = String::new(); buf.push('<'); buf.push_str(E::TAG); <At as ToTemplate>::to_template_attribute( buf, &mut class, &mut style, &mut inner_html, position, ); if !class.is_empty() { buf.push(' '); buf.push_str("class=\""); buf.push_str(class.trim_start().trim_end()); buf.push('"'); } if !style.is_empty() { buf.push(' '); buf.push_str("style=\""); buf.push_str(style.trim_start().trim_end()); buf.push('"'); } buf.push('>'); // children *position = Position::FirstChild; class.clear(); style.clear(); inner_html.clear(); Ch::to_template( buf, &mut class, &mut style, &mut inner_html, position, ); // closing tag buf.push_str("</"); buf.push_str(E::TAG); buf.push('>'); *position = Position::NextChild; } } } /* #[cfg(all(test, feature = "testing"))] mod tests { #[cfg(all(feature = "nightly", rustc_nightly))] use super::RenderHtml; use super::{main, p, HtmlElement}; use crate::{ html::{ attribute::global::GlobalAttributes, element::{em, ElementChild, Main}, }, renderer::mock_dom::MockDom, view::Render, }; #[test] fn mock_dom_creates_element() { let el: HtmlElement<Main, _, _, MockDom> = main().child(p().id("test").lang("en").child("Hello, world!")); let el = el.build(); assert_eq!( el.el.to_debug_html(), "<main><p id=\"test\" lang=\"en\">Hello, world!</p></main>" ); } #[test] fn mock_dom_creates_element_with_several_children() { let el: HtmlElement<Main, _, _, MockDom> = main().child(p().child(( "Hello, ", em().child("beautiful"), " world!", ))); let el = el.build(); assert_eq!( el.el.to_debug_html(), "<main><p>Hello, <em>beautiful</em> world!</p></main>" ); } #[cfg(all(feature = "nightly", rustc_nightly))] #[test] fn html_render_allocates_appropriate_buffer() { use crate::view::static_types::Static; let el: HtmlElement<Main, _, _, MockDom> = main().child(p().child(( Static::<"Hello, ">, em().child(Static::<"beautiful">), Static::<" world!">, ))); let allocated_len = el.html_len(); let html = el.to_html(); assert_eq!( html, "<main><p>Hello, <em>beautiful</em> world!</p></main>" ); assert_eq!(html.len(), allocated_len); } } */
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/element/elements.rs
tachys/src/html/element/elements.rs
use crate::{ html::{ attribute::{Attr, Attribute, AttributeValue, NextAttribute}, element::{ElementType, ElementWithChildren, HtmlElement}, }, view::Render, }; use std::fmt::Debug; macro_rules! html_element_inner { ( #[$meta:meta] $tag:ident $struct_name:ident $ty:ident [$($attr:ty),*] $escape:literal ) => { paste::paste! { #[$meta] #[track_caller] pub fn $tag() -> HtmlElement<$struct_name, (), ()> where { HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: std::panic::Location::caller(), tag: $struct_name, attributes: (), children: (), } } #[$meta] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct $struct_name; // Typed attribute methods impl<At, Ch> HtmlElement<$struct_name, At, Ch> where At: Attribute, Ch: Render, { $( #[doc = concat!("The [`", stringify!($attr), "`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/", stringify!($tag), "#", stringify!($attr) ,") attribute on `<", stringify!($tag), ">`.")] pub fn $attr<V>(self, value: V) -> HtmlElement < $struct_name, <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>, Ch > where V: AttributeValue, At: NextAttribute, <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>: Attribute, { let HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes } = self; HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes: attributes.add_any_attr($crate::html::attribute::$attr(value)), } } )* } impl ElementType for $struct_name { type Output = web_sys::$ty; const TAG: &'static str = stringify!($tag); const SELF_CLOSING: bool = false; const ESCAPE_CHILDREN: bool = $escape; const NAMESPACE: Option<&'static str> = None; #[inline(always)] fn tag(&self) -> &str { Self::TAG } } impl ElementWithChildren for $struct_name {} } }; } macro_rules! html_elements { ($( #[$meta:meta] $tag:ident $ty:ident [$($attr:ty),*] $escape:literal ),* $(,)? ) => { paste::paste! { $(html_element_inner! { #[$meta] $tag [<$tag:camel>] $ty [$($attr),*] $escape })* } } } macro_rules! html_self_closing_elements { ($( #[$meta:meta] $tag:ident $ty:ident [$($attr:ty),*] $escape:literal ),* $(,)? ) => { paste::paste! { $( #[$meta] #[track_caller] pub fn $tag() -> HtmlElement<[<$tag:camel>], (), ()> where { HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at: std::panic::Location::caller(), attributes: (), children: (), tag: [<$tag:camel>], } } #[$meta] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct [<$tag:camel>]; // Typed attribute methods impl<At> HtmlElement<[<$tag:camel>], At, ()> where At: Attribute, { $( #[doc = concat!("The [`", stringify!($attr), "`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/", stringify!($tag), "#", stringify!($attr) ,") attribute on `<", stringify!($tag), ">`.")] pub fn $attr<V>(self, value: V) -> HtmlElement< [<$tag:camel>], <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>, (), > where V: AttributeValue, At: NextAttribute, <At as NextAttribute>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>: Attribute, { let HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes, } = self; HtmlElement { #[cfg(any(debug_assertions, leptos_debuginfo))] defined_at, tag, children, attributes: attributes.add_any_attr($crate::html::attribute::$attr(value)), } } )* } impl ElementType for [<$tag:camel>] { type Output = web_sys::$ty; const TAG: &'static str = stringify!($tag); const SELF_CLOSING: bool = true; const ESCAPE_CHILDREN: bool = $escape; const NAMESPACE: Option<&'static str> = None; #[inline(always)] fn tag(&self) -> &str { Self::TAG } } )* } } } html_self_closing_elements! { /// The `<area>` HTML element defines an area inside an image map that has predefined clickable areas. An image map allows geometric areas on an image to be associated with Hyperlink. area HtmlAreaElement [alt, coords, download, href, hreflang, ping, rel, shape, target] true, /// The `<base>` HTML element specifies the base URL to use for all relative URLs in a document. There can be only one `<base>` element in a document. base HtmlBaseElement [href, target] true, /// The `<br>` HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant. br HtmlBrElement [] true, /// The `<col>` HTML element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a colgroup element. col HtmlTableColElement [span] true, /// The `<embed>` HTML element embeds external content at the specified point in the document. This content is provided by an external application or other source of interactive content such as a browser plug-in. embed HtmlEmbedElement [height, src, r#type, width] true, /// The `<hr>` HTML element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section. hr HtmlHrElement [] true, /// The `<img>` HTML element embeds an image into the document. img HtmlImageElement [alt, attributionsrc, crossorigin, decoding, elementtiming, fetchpriority, height, ismap, loading, referrerpolicy, sizes, src, srcset, usemap, width] true, /// The `<input>` HTML element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. The `<input>` element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes. input HtmlInputElement [accept, alt, autocomplete, capture, checked, dirname, disabled, form, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, name, pattern, placeholder, popovertarget, popovertargetaction, readonly, required, size, src, step, r#type, value, width] true, /// The `<link>` HTML element specifies relationships between the current document and an external resource. This element is most commonly used to link to CSS, but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things. link HtmlLinkElement [r#as, blocking, crossorigin, fetchpriority, href, hreflang, imagesizes, imagesrcset, integrity, media, rel, referrerpolicy, sizes, r#type] true, /// The `<meta>` HTML element represents Metadata that cannot be represented by other HTML meta-related elements, like base, link, script, style or title. meta HtmlMetaElement [charset, content, http_equiv, name] true, /// The `<source>` HTML element specifies multiple media resources for the picture, the audio element, or the video element. It is an empty element, meaning that it has no content and does not have a closing tag. It is commonly used to offer the same media content in multiple file formats in order to provide compatibility with a broad range of browsers given their differing support for image file formats and media file formats. source HtmlSourceElement [src, r#type, srcset, sizes, media, height, width] true, /// The `<track>` HTML element is used as a child of the media elements, audio and video. It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in WebVTT format (.vtt files) — Web Video Text Tracks. track HtmlTrackElement [default, kind, label, src, srclang] true, /// The `<wbr>` HTML element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location. wbr HtmlElement [] true, } html_elements! { /// The `<a>` HTML element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address. a HtmlAnchorElement [download, href, hreflang, ping, referrerpolicy, rel, target, r#type ] true, /// The `<abbr>` HTML element represents an abbreviation or acronym; the optional title attribute can provide an expansion or description for the abbreviation. If present, title must contain this full description and nothing else. abbr HtmlElement [] true, /// The `<address>` HTML element indicates that the enclosed HTML provides contact information for a person or people, or for an organization. address HtmlElement [] true, /// The `<article>` HTML element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include: a forum post, a magazine or newspaper article, or a blog entry, a product card, a user-submitted comment, an interactive widget or gadget, or any other independent item of content. article HtmlElement [] true, /// The `<aside>` HTML element represents a portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes. aside HtmlElement [] true, /// The `<audio>` HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the source element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream. audio HtmlAudioElement [autoplay, controls, crossorigin, r#loop, muted, preload, src] true, /// The `<b>` HTML element is used to draw the reader's attention to the element's contents, which are not otherwise granted special importance. This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use `<b>` for styling text; instead, you should use the CSS font-weight property to create boldface text, or the strong element to indicate that text is of special importance. b HtmlElement [] true, /// The `<bdi>` HTML element tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. It's particularly useful when a website dynamically inserts some text and doesn't know the directionality of the text being inserted. bdi HtmlElement [] true, /// The `<bdo>` HTML element overrides the current directionality of text, so that the text within is rendered in a different direction. bdo HtmlElement [] true, /// The `<blockquote>` HTML element indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see Notes for how to change it). A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the cite element. blockquote HtmlQuoteElement [cite] true, /// The `<body>` HTML element represents the content of an HTML document. There can be only one `<body>` element in a document. body HtmlBodyElement [] true, /// The `<button>` HTML element represents a clickable button, used to submit forms or anywhere in a document for accessible, standard button functionality. button HtmlButtonElement [command, commandfor, disabled, form, formaction, formenctype, formmethod, formnovalidate, formtarget, name, r#type, value, popovertarget, popovertargetaction] true, /// Use the HTML `<canvas>` element with either the canvas scripting API or the WebGL API to draw graphics and animations. canvas HtmlCanvasElement [height, width] true, /// The `<caption>` HTML element specifies the caption (or title) of a table. caption HtmlTableCaptionElement [] true, /// The `<cite>` HTML element is used to describe a reference to a cited creative work, and must include the title of that work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata. cite HtmlElement [] true, /// The `<code>` HTML element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the user agent default monospace font. code HtmlElement [] true, /// The `<colgroup>` HTML element defines a group of columns within a table. colgroup HtmlTableColElement [span] true, /// The `<data>` HTML element links a given piece of content with a machine-readable translation. If the content is time- or date-related, the time element must be used. data HtmlDataElement [value] true, /// The `<datalist>` HTML element contains a set of option elements that represent the permissible or recommended options available to choose from within other controls. datalist HtmlDataListElement [] true, /// The `<dd>` HTML element provides the description, definition, or value for the preceding term (dt) in a description list (dl). dd HtmlElement [] true, /// The `<del>` HTML element represents a range of text that has been deleted from a document. This can be used when rendering "track changes" or source code diff information, for example. The ins element can be used for the opposite purpose: to indicate text that has been added to the document. del HtmlModElement [cite, datetime] true, /// The `<details>` HTML element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the summary element. details HtmlDetailsElement [name, open] true, /// The `<dfn>` HTML element is used to indicate the term being defined within the context of a definition phrase or sentence. The p element, the dt/dd pairing, or the section element which is the nearest ancestor of the `<dfn>` is considered to be the definition of the term. dfn HtmlElement [] true, /// The `<dialog>` HTML element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow. dialog HtmlDialogElement [open] true, /// The `<div>` HTML element is the generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g. styling is directly applied to it, or some kind of layout model like Flexbox is applied to its parent element). div HtmlDivElement [] true, /// The `<dl>` HTML element represents a description list. The element encloses a list of groups of terms (specified using the dt element) and descriptions (provided by dd elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs). dl HtmlDListElement [] true, /// The `<dt>` HTML element specifies a term in a description or definition list, and as such must be used inside a dl element. It is usually followed by a dd element; however, multiple `<dt>` elements in a row indicate several terms that are all defined by the immediate next dd element. dt HtmlElement [] true, /// The `<em>` HTML element marks text that has stress emphasis. The `<em>` element can be nested, with each level of nesting indicating a greater degree of emphasis. em HtmlElement [] true, /// The `<fieldset>` HTML element is used to group several controls as well as labels (label) within a web form. fieldset HtmlFieldSetElement [disabled, form, name] true, /// The `<figcaption>` HTML element represents a caption or legend describing the rest of the contents of its parent figure element. figcaption HtmlElement [] true, /// The `<figure>` HTML element represents self-contained content, potentially with an optional caption, which is specified using the figcaption element. The figure, its caption, and its contents are referenced as a single unit. figure HtmlElement [] true, /// The `<footer>` HTML element represents a footer for its nearest sectioning content or sectioning root element. A `<footer>` typically contains information about the author of the section, copyright data or links to related documents. footer HtmlElement [] true, /// The `<form>` HTML element represents a document section containing interactive controls for submitting information. form HtmlFormElement [accept_charset, action, autocomplete, enctype, method, name, novalidate, target] true, /// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. h1 HtmlHeadingElement [] true, /// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. h2 HtmlHeadingElement [] true, /// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. h3 HtmlHeadingElement [] true, /// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. h4 HtmlHeadingElement [] true, /// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. h5 HtmlHeadingElement [] true, /// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. h6 HtmlHeadingElement [] true, /// The `<head>` HTML element contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets. head HtmlHeadElement [] true, /// The `<header>` HTML element represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also a logo, a search form, an author name, and other elements. header HtmlElement [] true, /// The `<hgroup>` HTML element represents a heading and related content. It groups a single `<h1>–<h6>` element with one or more `<p>`. hgroup HtmlElement [] true, /// The `<html>` HTML element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element. html HtmlHtmlElement [] true, /// The `<i>` HTML element represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. Historically, these have been presented using italicized type, which is the original source of the `<i>` naming of this element. i HtmlElement [] true, /// The `<iframe>` HTML element represents a nested browsing context, embedding another HTML page into the current one. iframe HtmlIFrameElement [allow, allowfullscreen, allowpaymentrequest, height, name, referrerpolicy, sandbox, src, srcdoc, width] true, /// The `<ins>` HTML element represents a range of text that has been added to a document. You can use the del element to similarly represent a range of text that has been deleted from the document. ins HtmlElement [cite, datetime] true, /// The `<kbd>` HTML element represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the user agent defaults to rendering the contents of a `<kbd>` element using its default monospace font, although this is not mandated by the HTML standard. kbd HtmlElement [] true, /// The `<label>` HTML element represents a caption for an item in a user interface. label HtmlLabelElement [r#for, form] true, /// The `<legend>` HTML element represents a caption for the content of its parent fieldset. legend HtmlLegendElement [] true, /// The `<li>` HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list (ol), an unordered list (ul), or a menu (menu). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter. li HtmlLiElement [value] true, /// The `<main>` HTML element represents the dominant content of the body of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. main HtmlElement [] true, /// The `<map>` HTML element is used with area elements to define an image map (a clickable link area). map HtmlMapElement [name] true, /// The `<mark>` HTML element represents text which is marked or highlighted for reference or notation purposes, due to the marked passage's relevance or importance in the enclosing context. mark HtmlElement [] true, /// The `<menu>` HTML element is a semantic alternative to ul. It represents an unordered list of items (represented by li elements), each of these represent a link or other command that the user can activate. menu HtmlMenuElement [] true, /// The `<meter>` HTML element represents either a scalar value within a known range or a fractional value. meter HtmlMeterElement [value, min, max, low, high, optimum, form] true, /// The `<nav>` HTML element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes. nav HtmlElement [] true, /// The `<noscript>` HTML element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. noscript HtmlElement [] false, /// The `<object>` HTML element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin. object HtmlObjectElement [data, form, height, name, r#type, usemap, width] true, /// The `<ol>` HTML element represents an ordered list of items — typically rendered as a numbered list. ol HtmlOListElement [reversed, start, r#type] true, /// The `<optgroup>` HTML element creates a grouping of options within a select element. optgroup HtmlOptGroupElement [disabled, label] true, /// The `<output>` HTML element is a container element into which a site or app can inject the results of a calculation or the outcome of a user action. output HtmlOutputElement [r#for, form, name] true, /// The `<p>` HTML element represents a paragraph. Paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but HTML paragraphs can be any structural grouping of related content, such as images or form fields. p HtmlParagraphElement [] true, /// The `<picture>` HTML element contains zero or more source elements and one img element to offer alternative versions of an image for different display/device scenarios. picture HtmlPictureElement [] true, /// The `<portal>` HTML element enables the embedding of another HTML page into the current one for the purposes of allowing smoother navigation into new pages. portal HtmlElement [referrerpolicy, src] true, /// The `<pre>` HTML element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional, or "monospaced, font. Whitespace inside this element is displayed as written. pre HtmlPreElement [] true, /// The `<progress>` HTML element displays an indicator showing the completion progress of a task, typically displayed as a progress bar. progress HtmlProgressElement [min, max, value] true, /// The `<q>` HTML element indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the blockquote element. q HtmlQuoteElement [cite] true, /// The `<rp>` HTML element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the ruby element. One `<rp>` element should enclose each of the opening and closing parentheses that wrap the rt element that contains the annotation's text. rp HtmlElement [] true, /// The `<rt>` HTML element specifies the ruby text component of a ruby annotation, which is used to provide pronunciation, translation, or transliteration information for East Asian typography. The `<rt>` element must always be contained within a ruby element. rt HtmlElement [] true, /// The `<ruby>` HTML element represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common. ruby HtmlElement [] true, /// The `<s>` HTML element renders text with a strikethrough, or a line through it. Use the `<s>` element to represent things that are no longer relevant or no longer accurate. However, `<s>` is not appropriate when indicating document edits; for that, use the del and ins elements, as appropriate. s HtmlElement [] true, /// The `<samp>` HTML element is used to enclose inline text which represents sample (or quoted) output from a computer program. Its contents are typically rendered using the browser's default monospaced font (such as Courier or Lucida Console). samp HtmlElement [] true, /// The `<script>` HTML element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The `<script>` element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON. script HtmlScriptElement [r#async, crossorigin, defer, fetchpriority, integrity, nomodule, referrerpolicy, src, r#type, blocking] false, /// The `<search>` HTML element is a container representing the parts of the document or application with form controls or other content related to performing a search or filtering operation. search HtmlElement [] true, /// The `<section>` HTML element represents a generic standalone section of a document, which doesn't have a more specific semantic element to represent it. Sections should always have a heading, with very few exceptions. section HtmlElement [] true, /// The `<select>` HTML element represents a control that provides a menu of options: select HtmlSelectElement [autocomplete, disabled, form, multiple, name, required, size] true, /// The `<slot>` HTML element—part of the Web Components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. slot HtmlSlotElement [name] true, /// The `<small>` HTML element represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font-size smaller, such as from small to x-small. small HtmlElement [] true, /// The `<span>` HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate. `<span>` is very much like a div element, but div is a block-level element whereas a `<span>` is an inline element. span HtmlSpanElement [] true, /// The `<strong>` HTML element indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type. strong HtmlElement [] true, /// The `<style>` HTML element contains style information for a document, or part of a document. It contains CSS, which is applied to the contents of the document containing the `<style>` element. style HtmlStyleElement [media, blocking] false, /// The `<sub>` HTML element specifies inline text which should be displayed as subscript for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text. sub HtmlElement [] true, /// The `<summary>` HTML element specifies a summary, caption, or legend for a details element's disclosure box. Clicking the `<summary>` element toggles the state of the parent `<details>` element open and closed. summary HtmlElement [] true, /// The `<sup>` HTML element specifies inline text which is to be displayed as superscript for solely typographical reasons. Superscripts are usually rendered with a raised baseline using smaller text. sup HtmlElement [] true, /// The `<table>` HTML element represents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. table HtmlTableElement [] true, /// The `<tbody>` HTML element encapsulates a set of table rows (tr elements), indicating that they comprise the body of the table (table). tbody HtmlTableSectionElement [] true,
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
true
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/element/element_ext.rs
tachys/src/html/element/element_ext.rs
use crate::{ html::{ attribute::Attribute, class::IntoClass, event::{on, EventDescriptor}, style::IntoStyle, }, renderer::RemoveEventHandler, }; use wasm_bindgen::JsValue; use web_sys::Element; /// Extends an HTML element, allowing you to add attributes and children to the /// element's built state at runtime, with a similar API to how they /// can be added to the static view tree at compile time. /// /// ```rust,ignore /// use tachys::html::element::ElementExt; /// /// let view: HtmlElement<_, _, _, MockDom> = button(); /// /// // add an event listener as part of the static type /// // this will be lazily added when the element is built /// let view = element.on(ev::click, move |_| /* ... */); /// /// // `element` now contains the actual element /// let element = element.build(); /// let remove = element.on(ev::blur, move |_| /* ... */); /// ``` pub trait ElementExt { /// Adds an attribute to the element, at runtime. fn attr<At>(&self, attribute: At) -> At::State where At: Attribute; /// Adds a class to the element, at runtime. fn class<C>(&self, class: C) -> C::State where C: IntoClass; /// Adds a style to the element, at runtime. fn style<S>(&self, style: S) -> S::State where S: IntoStyle; /// Adds an event listener to the element, at runtime. fn on<E>( &self, ev: E, cb: impl FnMut(E::EventType) + 'static, ) -> RemoveEventHandler<Element> where E: EventDescriptor + Send + 'static, E::EventType: 'static, E::EventType: From<JsValue>; } impl<T> ElementExt for T where T: AsRef<Element>, { fn attr<At>(&self, attribute: At) -> At::State where At: Attribute, { attribute.build(self.as_ref()) } fn class<C>(&self, class: C) -> C::State where C: IntoClass, { class.build(self.as_ref()) } fn on<E>( &self, ev: E, cb: impl FnMut(E::EventType) + 'static, ) -> RemoveEventHandler<Element> where E: EventDescriptor + Send + 'static, E::EventType: 'static, E::EventType: From<JsValue>, { on::<E, _>(ev, cb).attach(self.as_ref()) } fn style<S>(&self, style: S) -> S::State where S: IntoStyle, { style.build(self.as_ref()) } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false