passes.rs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. use anymap::AnyMap;
  2. use rustc_hash::FxHashSet;
  3. use std::any::{Any, TypeId};
  4. use std::collections::BTreeMap;
  5. use std::sync::Arc;
  6. use crate::node::Node;
  7. use crate::node_ref::NodeView;
  8. use crate::state::State;
  9. use crate::tree::TreeViewMut;
  10. use crate::tree::{Tree, TreeView};
  11. use crate::{FxDashMap, FxDashSet, SendAnyMap};
  12. use crate::{NodeId, NodeMask};
  13. pub trait Pass: Any {
  14. /// This is a tuple of (T: Any, ..)
  15. type ParentDependencies: Dependancy;
  16. /// This is a tuple of (T: Any, ..)
  17. type ChildDependencies: Dependancy;
  18. /// This is a tuple of (T: Any, ..)
  19. type NodeDependencies: Dependancy;
  20. const NODE_MASK: NodeMask;
  21. fn pass<'a>(
  22. &mut self,
  23. node_view: NodeView,
  24. node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  25. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  26. children: Option<
  27. impl Iterator<Item = <Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  28. >,
  29. context: &SendAnyMap,
  30. ) -> bool;
  31. fn validate() {
  32. // no type can be a child and parent dependency
  33. for type_id in Self::parent_type_ids() {
  34. for type_id2 in Self::child_type_ids() {
  35. if type_id == type_id2 {
  36. panic!("type cannot be both a parent and child dependency");
  37. }
  38. }
  39. }
  40. // this type should not be a node dependency
  41. for type_id in Self::node_type_ids() {
  42. if type_id == TypeId::of::<Self>() {
  43. panic!("The current type cannot be a node dependency");
  44. }
  45. }
  46. // no states have the same type id
  47. if Self::all_dependanices()
  48. .into_iter()
  49. .collect::<FxDashSet<_>>()
  50. .len()
  51. != Self::all_dependanices().len()
  52. {
  53. panic!("all states must have unique type ids");
  54. }
  55. }
  56. fn to_type_erased<T: AnyMapLike + State>() -> TypeErasedPass<T>
  57. where
  58. Self: Sized,
  59. {
  60. Self::validate();
  61. TypeErasedPass {
  62. this_type_id: TypeId::of::<Self>(),
  63. combined_dependancy_type_ids: Self::all_dependanices().into_iter().collect(),
  64. parent_dependant: !Self::parent_type_ids().is_empty(),
  65. child_dependant: !Self::child_type_ids().is_empty(),
  66. dependants: FxHashSet::default(),
  67. mask: Self::NODE_MASK,
  68. pass_direction: Self::pass_direction(),
  69. pass: Box::new(
  70. |node_id: NodeId, any_map: &mut Tree<Node<T>>, context: &SendAnyMap| {
  71. let (current_node, parent, children) = any_map
  72. .node_parent_children_mut(node_id)
  73. .expect("tried to run pass on node that does not exist");
  74. let current_node_raw = current_node as *mut Node<T>;
  75. let node = Self::NodeDependencies::borrow_elements_from(&current_node.state)
  76. .expect("tried to get a pass that does not exist");
  77. let parent = parent.map(|parent| {
  78. Self::ParentDependencies::borrow_elements_from(&parent.state)
  79. .expect("tried to get a pass that does not exist")
  80. });
  81. let children = children.map(|children| {
  82. children.map(|child| {
  83. Self::ChildDependencies::borrow_elements_from(&child.state)
  84. .expect("tried to get a pass that does not exist")
  85. })
  86. });
  87. // safety: we have varified the pass is valid in the is_valid function
  88. let myself: &mut Self = unsafe {
  89. (*current_node_raw)
  90. .state
  91. .get_mut()
  92. .expect("tried to get a pass that does not exist")
  93. };
  94. myself.pass(
  95. NodeView::new(&current_node.node_data, Self::NODE_MASK),
  96. node,
  97. parent,
  98. children,
  99. context,
  100. )
  101. },
  102. )
  103. as Box<dyn Fn(NodeId, &mut Tree<Node<T>>, &SendAnyMap) -> bool + Send + Sync>,
  104. }
  105. }
  106. fn parent_type_ids() -> Vec<TypeId> {
  107. Self::ParentDependencies::type_ids()
  108. }
  109. fn child_type_ids() -> Vec<TypeId> {
  110. Self::ChildDependencies::type_ids()
  111. }
  112. fn node_type_ids() -> Vec<TypeId> {
  113. Self::NodeDependencies::type_ids()
  114. }
  115. fn all_dependanices() -> Vec<TypeId> {
  116. let mut dependencies = Self::parent_type_ids();
  117. dependencies.extend(Self::child_type_ids());
  118. dependencies.extend(Self::node_type_ids());
  119. dependencies
  120. }
  121. fn pass_direction() -> PassDirection {
  122. if Self::child_type_ids()
  123. .into_iter()
  124. .any(|type_id| type_id == TypeId::of::<Self>())
  125. {
  126. PassDirection::ChildToParent
  127. } else if Self::parent_type_ids()
  128. .into_iter()
  129. .any(|type_id| type_id == TypeId::of::<Self>())
  130. {
  131. PassDirection::ParentToChild
  132. } else {
  133. PassDirection::AnyOrder
  134. }
  135. }
  136. }
  137. pub struct TypeErasedPass<T: AnyMapLike + State> {
  138. pub(crate) this_type_id: TypeId,
  139. pub(crate) parent_dependant: bool,
  140. pub(crate) child_dependant: bool,
  141. pub(crate) combined_dependancy_type_ids: FxHashSet<TypeId>,
  142. pub(crate) dependants: FxHashSet<TypeId>,
  143. pub(crate) mask: NodeMask,
  144. pass: PassCallback<T>,
  145. pub(crate) pass_direction: PassDirection,
  146. }
  147. impl<T: AnyMapLike + State> TypeErasedPass<T> {
  148. fn resolve(
  149. &self,
  150. tree: &mut Tree<Node<T>>,
  151. mut dirty: DirtyNodes,
  152. dirty_states: &DirtyNodeStates,
  153. nodes_updated: &FxDashSet<NodeId>,
  154. ctx: &SendAnyMap,
  155. ) {
  156. match self.pass_direction {
  157. PassDirection::ParentToChild => {
  158. while let Some(id) = dirty.pop_front() {
  159. if (self.pass)(id, tree, ctx) {
  160. nodes_updated.insert(id);
  161. for id in tree.children_ids(id).unwrap() {
  162. for dependant in &self.dependants {
  163. dirty_states.insert(*dependant, *id);
  164. }
  165. let height = tree.height(*id).unwrap();
  166. dirty.insert(height, *id);
  167. }
  168. }
  169. }
  170. }
  171. PassDirection::ChildToParent => {
  172. while let Some(id) = dirty.pop_back() {
  173. if (self.pass)(id, tree, ctx) {
  174. nodes_updated.insert(id);
  175. if let Some(id) = tree.parent_id(id) {
  176. for dependant in &self.dependants {
  177. dirty_states.insert(*dependant, id);
  178. }
  179. let height = tree.height(id).unwrap();
  180. dirty.insert(height, id);
  181. }
  182. }
  183. }
  184. }
  185. PassDirection::AnyOrder => {
  186. while let Some(id) = dirty.pop_back() {
  187. if (self.pass)(id, tree, ctx) {
  188. nodes_updated.insert(id);
  189. for dependant in &self.dependants {
  190. dirty_states.insert(*dependant, id);
  191. }
  192. }
  193. }
  194. }
  195. }
  196. }
  197. }
  198. #[derive(Debug)]
  199. pub enum PassDirection {
  200. ParentToChild,
  201. ChildToParent,
  202. AnyOrder,
  203. }
  204. type PassCallback<T> = Box<dyn Fn(NodeId, &mut Tree<Node<T>>, &SendAnyMap) -> bool + Send + Sync>;
  205. pub trait AnyMapLike {
  206. fn get<T: Any>(&self) -> Option<&T>;
  207. fn get_mut<T: Any>(&mut self) -> Option<&mut T>;
  208. }
  209. impl AnyMapLike for AnyMap {
  210. fn get<T: Any>(&self) -> Option<&T> {
  211. self.get()
  212. }
  213. fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
  214. self.get_mut()
  215. }
  216. }
  217. impl AnyMapLike for SendAnyMap {
  218. fn get<T: Any>(&self) -> Option<&T> {
  219. todo!()
  220. }
  221. fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
  222. todo!()
  223. }
  224. }
  225. pub trait Dependancy {
  226. type ElementBorrowed<'a>
  227. where
  228. Self: 'a;
  229. fn borrow_elements_from<T: AnyMapLike>(map: &T) -> Option<Self::ElementBorrowed<'_>>;
  230. fn type_ids() -> Vec<TypeId>;
  231. }
  232. macro_rules! impl_dependancy {
  233. ($($t:ident),*) => {
  234. impl< $($t: Any),* > Dependancy for ($($t,)*) {
  235. type ElementBorrowed<'a> = ($(&'a $t,)*) where Self: 'a;
  236. #[allow(unused_variables, clippy::unused_unit, non_snake_case)]
  237. fn borrow_elements_from<T: AnyMapLike>(map: &T) -> Option<Self::ElementBorrowed<'_>> {
  238. Some(($(map.get::<$t>()?,)*))
  239. }
  240. fn type_ids() -> Vec<TypeId> {
  241. vec![$(TypeId::of::<$t>()),*]
  242. }
  243. }
  244. };
  245. }
  246. impl_dependancy!();
  247. impl_dependancy!(A);
  248. impl_dependancy!(A, B);
  249. impl_dependancy!(A, B, C);
  250. impl_dependancy!(A, B, C, D);
  251. impl_dependancy!(A, B, C, D, E);
  252. impl_dependancy!(A, B, C, D, E, F);
  253. impl_dependancy!(A, B, C, D, E, F, G);
  254. impl_dependancy!(A, B, C, D, E, F, G, H);
  255. impl_dependancy!(A, B, C, D, E, F, G, H, I);
  256. impl_dependancy!(A, B, C, D, E, F, G, H, I, J);
  257. impl_dependancy!(A, B, C, D, E, F, G, H, I, J, K);
  258. impl_dependancy!(A, B, C, D, E, F, G, H, I, J, K, L);
  259. impl_dependancy!(A, B, C, D, E, F, G, H, I, J, K, L, M);
  260. impl_dependancy!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
  261. impl_dependancy!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
  262. impl_dependancy!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
  263. #[derive(Debug, Clone, PartialEq, Eq, Default)]
  264. pub struct DirtyNodes {
  265. map: BTreeMap<u16, FxHashSet<NodeId>>,
  266. }
  267. impl DirtyNodes {
  268. pub fn insert(&mut self, depth: u16, node_id: NodeId) {
  269. self.map
  270. .entry(depth)
  271. .or_insert_with(FxHashSet::default)
  272. .insert(node_id);
  273. }
  274. fn pop_front(&mut self) -> Option<NodeId> {
  275. let (&depth, values) = self.map.iter_mut().next()?;
  276. let key = *values.iter().next()?;
  277. let node_id = values.take(&key)?;
  278. if values.is_empty() {
  279. self.map.remove(&depth);
  280. }
  281. Some(node_id)
  282. }
  283. fn pop_back(&mut self) -> Option<NodeId> {
  284. let (&depth, values) = self.map.iter_mut().rev().next()?;
  285. let key = *values.iter().next()?;
  286. let node_id = values.take(&key)?;
  287. if values.is_empty() {
  288. self.map.remove(&depth);
  289. }
  290. Some(node_id)
  291. }
  292. }
  293. #[test]
  294. fn dirty_nodes() {
  295. let mut dirty_nodes = DirtyNodes::default();
  296. dirty_nodes.insert(1, NodeId(1));
  297. dirty_nodes.insert(0, NodeId(0));
  298. dirty_nodes.insert(2, NodeId(3));
  299. dirty_nodes.insert(1, NodeId(2));
  300. assert_eq!(dirty_nodes.pop_front(), Some(NodeId(0)));
  301. assert!(matches!(dirty_nodes.pop_front(), Some(NodeId(1 | 2))));
  302. assert!(matches!(dirty_nodes.pop_front(), Some(NodeId(1 | 2))));
  303. assert_eq!(dirty_nodes.pop_front(), Some(NodeId(3)));
  304. }
  305. #[derive(Default)]
  306. pub struct DirtyNodeStates {
  307. dirty: FxDashMap<NodeId, FxHashSet<TypeId>>,
  308. }
  309. impl DirtyNodeStates {
  310. pub fn insert(&self, pass_id: TypeId, node_id: NodeId) {
  311. if let Some(mut dirty) = self.dirty.get_mut(&node_id) {
  312. dirty.insert(pass_id);
  313. } else {
  314. let mut v = FxHashSet::default();
  315. v.insert(pass_id);
  316. self.dirty.insert(node_id, v);
  317. }
  318. }
  319. fn all_dirty<T>(&self, pass_id: TypeId, dirty_nodes: &mut DirtyNodes, tree: &impl TreeView<T>) {
  320. for entry in self.dirty.iter() {
  321. let node_id = entry.key();
  322. let dirty = entry.value();
  323. if dirty.contains(&pass_id) {
  324. dirty_nodes.insert(tree.height(*node_id).unwrap(), *node_id);
  325. }
  326. }
  327. }
  328. }
  329. pub fn resolve_passes<T: AnyMapLike + State + Send>(
  330. tree: &mut Tree<Node<T>>,
  331. dirty_nodes: DirtyNodeStates,
  332. passes: &[TypeErasedPass<T>],
  333. ctx: SendAnyMap,
  334. ) -> FxDashSet<NodeId> {
  335. let dirty_states = Arc::new(dirty_nodes);
  336. let mut resolved_passes: FxHashSet<TypeId> = FxHashSet::default();
  337. let mut resolving = Vec::new();
  338. let nodes_updated = Arc::new(FxDashSet::default());
  339. let ctx = Arc::new(ctx);
  340. let mut pass_indexes_remaining: Vec<_> = (0..passes.len()).collect::<Vec<_>>();
  341. while !pass_indexes_remaining.is_empty() {
  342. let mut currently_in_use = FxHashSet::<TypeId>::default();
  343. std::thread::scope(|s| {
  344. let mut i = 0;
  345. while i < pass_indexes_remaining.len() {
  346. let passes_idx = pass_indexes_remaining[i];
  347. let pass = &passes[passes_idx];
  348. let pass_id = pass.this_type_id;
  349. // check if the pass is ready to be run
  350. if pass.combined_dependancy_type_ids.iter().all(|d| {
  351. (resolved_passes.contains(d) || *d == pass_id) && !currently_in_use.contains(d)
  352. }) {
  353. pass_indexes_remaining.remove(i);
  354. resolving.push(pass_id);
  355. currently_in_use.insert(pass.this_type_id);
  356. // this is safe because each pass only has mutable access to the member associated with this_type_id and we have verified that the pass does not overlap with any other pass currently running
  357. let tree_unbounded_mut = unsafe { &mut *(tree as *mut _) };
  358. let dirty_states = dirty_states.clone();
  359. let nodes_updated = nodes_updated.clone();
  360. let ctx = ctx.clone();
  361. s.spawn(move || {
  362. let mut dirty = DirtyNodes::default();
  363. dirty_states.all_dirty(pass_id, &mut dirty, tree_unbounded_mut);
  364. pass.resolve(
  365. tree_unbounded_mut,
  366. dirty,
  367. &dirty_states,
  368. &nodes_updated,
  369. &ctx,
  370. );
  371. });
  372. } else {
  373. i += 1;
  374. }
  375. }
  376. // all passes are resolved at the end of the scope
  377. });
  378. resolved_passes.extend(resolving.iter().copied());
  379. resolving.clear()
  380. }
  381. std::sync::Arc::try_unwrap(nodes_updated).unwrap()
  382. }
  383. // #[test]
  384. // fn node_pass() {
  385. // use crate::real_dom::RealDom;
  386. // use crate::tree::{Tree, TreeLike};
  387. // #[derive(Debug, Default, Clone, PartialEq)]
  388. // struct Number(i32);
  389. // impl State for Number {
  390. // fn create_passes() -> Box<[TypeErasedPass<Self>]> {
  391. // Box::new([Number::to_type_erased()])
  392. // }
  393. // }
  394. // impl AnyMapLike for Number {
  395. // fn get<T: Any>(&self) -> Option<&T> {
  396. // if TypeId::of::<Self>() == TypeId::of::<T>() {
  397. // Some(unsafe { &*(self as *const Self as *const T) })
  398. // } else {
  399. // None
  400. // }
  401. // }
  402. // fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
  403. // if TypeId::of::<Self>() == TypeId::of::<T>() {
  404. // Some(unsafe { &mut *(self as *mut Self as *mut T) })
  405. // } else {
  406. // None
  407. // }
  408. // }
  409. // }
  410. // impl Pass for Number {
  411. // type ChildDependencies = ();
  412. // type NodeDependencies = ();
  413. // type ParentDependencies = ();
  414. // type Ctx = ();
  415. // const MASK: NodeMask = NodeMask::new();
  416. // fn pass<'a>(
  417. // &mut self,
  418. // node_view: NodeView,
  419. // node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  420. // parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  421. // children: Option<
  422. // impl Iterator<Item = <Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  423. // >,
  424. // context: <Self::Ctx as Dependancy>::ElementBorrowed<'a>,
  425. // ) -> bool {
  426. // self.0 += 1;
  427. // true
  428. // }
  429. // }
  430. // let mut tree: RealDom<Number> = RealDom::new();
  431. // tree.dirty_nodes.insert(TypeId::of::<Number>(), NodeId(0));
  432. // tree.update_state(SendAnyMap::new());
  433. // assert_eq!(tree.get(tree.root()).unwrap().state.0, 1);
  434. // }
  435. // #[test]
  436. // fn dependant_node_pass() {
  437. // use crate::real_dom::RealDom;
  438. // #[derive(Debug, Default, Clone, PartialEq)]
  439. // struct AddNumber(i32);
  440. // impl Pass for AddNumber {
  441. // type ChildDependencies = ();
  442. // type NodeDependencies = (SubtractNumber,);
  443. // type ParentDependencies = ();
  444. // type Ctx = ();
  445. // const MASK: NodeMask = NodeMask::new();
  446. // fn pass<'a>(
  447. // &mut self,
  448. // node_view: NodeView,
  449. // node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  450. // parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  451. // children: Option<
  452. // impl Iterator<Item = <Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  453. // >,
  454. // context: <Self::Ctx as Dependancy>::ElementBorrowed<'a>,
  455. // ) -> bool {
  456. // self.0 += 1;
  457. // true
  458. // }
  459. // }
  460. // #[derive(Debug, Default, Clone, PartialEq)]
  461. // struct SubtractNumber(i32);
  462. // impl Pass for SubtractNumber {
  463. // type ChildDependencies = ();
  464. // type NodeDependencies = ();
  465. // type ParentDependencies = ();
  466. // type Ctx = ();
  467. // const MASK: NodeMask = NodeMask::new();
  468. // fn pass<'a>(
  469. // &mut self,
  470. // node_view: NodeView,
  471. // node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  472. // parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  473. // children: Option<
  474. // impl Iterator<Item = <Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  475. // >,
  476. // context: <Self::Ctx as Dependancy>::ElementBorrowed<'a>,
  477. // ) -> bool {
  478. // self.0 -= 1;
  479. // true
  480. // }
  481. // }
  482. // #[derive(Debug, Default, Clone, PartialEq)]
  483. // struct NumberState {
  484. // add_number: AddNumber,
  485. // subtract_number: SubtractNumber,
  486. // }
  487. // impl AnyMapLike for NumberState {
  488. // fn get<T: Any>(&self) -> Option<&T> {
  489. // if TypeId::of::<AddNumber>() == TypeId::of::<T>() {
  490. // Some(unsafe { &*(&self.add_number as *const AddNumber as *const T) })
  491. // } else if TypeId::of::<SubtractNumber>() == TypeId::of::<T>() {
  492. // Some(unsafe { &*(&self.subtract_number as *const SubtractNumber as *const T) })
  493. // } else {
  494. // None
  495. // }
  496. // }
  497. // fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
  498. // if TypeId::of::<AddNumber>() == TypeId::of::<T>() {
  499. // Some(unsafe { &mut *(&mut self.add_number as *mut AddNumber as *mut T) })
  500. // } else if TypeId::of::<SubtractNumber>() == TypeId::of::<T>() {
  501. // Some(unsafe { &mut *(&mut self.subtract_number as *mut SubtractNumber as *mut T) })
  502. // } else {
  503. // None
  504. // }
  505. // }
  506. // }
  507. // impl State for NumberState {
  508. // fn create_passes() -> Box<[TypeErasedPass<Self>]> {
  509. // Box::new([
  510. // AddNumber::to_type_erased(),
  511. // SubtractNumber::to_type_erased(),
  512. // ])
  513. // }
  514. // }
  515. // let mut tree: RealDom<NumberState> = RealDom::new();
  516. // tree.dirty_nodes
  517. // .insert(TypeId::of::<SubtractNumber>(), NodeId(0));
  518. // tree.update_state(dirty_nodes, SendAnyMap::new());
  519. // assert_eq!(
  520. // tree.get(tree.root()).unwrap().state,
  521. // NumberState {
  522. // add_number: AddNumber(1),
  523. // subtract_number: SubtractNumber(-1)
  524. // }
  525. // );
  526. // }
  527. // #[test]
  528. // fn independant_node_pass() {
  529. // use crate::real_dom::RealDom;
  530. // use crate::tree::{Tree, TreeLike};
  531. // #[derive(Debug, Default, Clone, PartialEq)]
  532. // struct AddNumber(i32);
  533. // impl Pass for AddNumber {
  534. // type ChildDependencies = ();
  535. // type NodeDependencies = ();
  536. // type ParentDependencies = ();
  537. // type Ctx = ();
  538. // const MASK: NodeMask = NodeMask::new();
  539. // fn pass<'a>(
  540. // &mut self,
  541. // node_view: NodeView,
  542. // node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  543. // parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  544. // children: Option<
  545. // impl Iterator<Item = <Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  546. // >,
  547. // context: <Self::Ctx as Dependancy>::ElementBorrowed<'a>,
  548. // ) -> bool {
  549. // self.0 += 1;
  550. // true
  551. // }
  552. // }
  553. // #[derive(Debug, Default, Clone, PartialEq)]
  554. // struct SubtractNumber(i32);
  555. // impl Pass for SubtractNumber {
  556. // type ChildDependencies = ();
  557. // type NodeDependencies = ();
  558. // type ParentDependencies = ();
  559. // type Ctx = ();
  560. // const MASK: NodeMask = NodeMask::new();
  561. // fn pass<'a>(
  562. // &mut self,
  563. // node_view: NodeView,
  564. // node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  565. // parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  566. // children: Option<
  567. // impl Iterator<Item = <Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  568. // >,
  569. // context: <Self::Ctx as Dependancy>::ElementBorrowed<'a>,
  570. // ) -> bool {
  571. // self.0 -= 1;
  572. // true
  573. // }
  574. // }
  575. // #[derive(Debug, Default, Clone, PartialEq)]
  576. // struct NumberState {
  577. // add_number: AddNumber,
  578. // subtract_number: SubtractNumber,
  579. // }
  580. // impl AnyMapLike for NumberState {
  581. // fn get<T: Any>(&self) -> Option<&T> {
  582. // if TypeId::of::<AddNumber>() == TypeId::of::<T>() {
  583. // Some(unsafe { &*(&self.add_number as *const AddNumber as *const T) })
  584. // } else if TypeId::of::<SubtractNumber>() == TypeId::of::<T>() {
  585. // Some(unsafe { &*(&self.subtract_number as *const SubtractNumber as *const T) })
  586. // } else {
  587. // None
  588. // }
  589. // }
  590. // fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
  591. // if TypeId::of::<AddNumber>() == TypeId::of::<T>() {
  592. // Some(unsafe { &mut *(&mut self.add_number as *mut AddNumber as *mut T) })
  593. // } else if TypeId::of::<SubtractNumber>() == TypeId::of::<T>() {
  594. // Some(unsafe { &mut *(&mut self.subtract_number as *mut SubtractNumber as *mut T) })
  595. // } else {
  596. // None
  597. // }
  598. // }
  599. // }
  600. // impl State for NumberState {
  601. // fn create_passes() -> Box<[TypeErasedPass<Self>]> {
  602. // Box::new([
  603. // AddNumber::to_type_erased(),
  604. // SubtractNumber::to_type_erased(),
  605. // ])
  606. // }
  607. // }
  608. // let mut tree: RealDom<NumberState> = RealDom::new();
  609. // tree.dirty_nodes
  610. // .insert(TypeId::of::<SubtractNumber>(), NodeId(0));
  611. // tree.update_state(SendAnyMap::new());
  612. // assert_eq!(
  613. // tree.get(tree.root()).unwrap().state,
  614. // NumberState {
  615. // add_number: AddNumber(0),
  616. // subtract_number: SubtractNumber(-1)
  617. // }
  618. // );
  619. // }
  620. // #[test]
  621. // fn down_pass() {
  622. // use crate::real_dom::RealDom;
  623. // use crate::tree::{Tree, TreeLike};
  624. // #[derive(Debug, Default, Clone, PartialEq)]
  625. // struct AddNumber(i32);
  626. // impl Pass for AddNumber {
  627. // type ChildDependencies = ();
  628. // type NodeDependencies = ();
  629. // type ParentDependencies = (AddNumber,);
  630. // type Ctx = ();
  631. // const MASK: NodeMask = NodeMask::new();
  632. // fn pass<'a>(
  633. // &mut self,
  634. // node_view: NodeView,
  635. // node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  636. // parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  637. // children: Option<
  638. // impl Iterator<Item = <Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>,
  639. // >,
  640. // context: <Self::Ctx as Dependancy>::ElementBorrowed<'a>,
  641. // ) -> bool {
  642. // if let Some((parent,)) = parent {
  643. // *self.0 += *parent.0;
  644. // }
  645. // true
  646. // }
  647. // }
  648. // #[derive(Debug, Default, Clone, PartialEq)]
  649. // struct NumberState {
  650. // add_number: AddNumber,
  651. // }
  652. // impl AnyMapLike for NumberState {
  653. // fn get<T: Any>(&self) -> Option<&T> {
  654. // if TypeId::of::<AddNumber>() == TypeId::of::<T>() {
  655. // Some(unsafe { &*(&self.add_number as *const AddNumber as *const T) })
  656. // } else {
  657. // None
  658. // }
  659. // }
  660. // fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
  661. // if TypeId::of::<AddNumber>() == TypeId::of::<T>() {
  662. // Some(unsafe { &mut *(&mut self.add_number as *mut AddNumber as *mut T) })
  663. // } else {
  664. // None
  665. // }
  666. // }
  667. // }
  668. // impl State for NumberState {
  669. // fn create_passes() -> Box<[TypeErasedPass<Self>]> {
  670. // Box::new([AddNumber::to_type_erased()])
  671. // }
  672. // }
  673. // let mut tree: RealDom<NumberState> = RealDom::new();
  674. // let parent = tree.root();
  675. // let child1 = tree.create_node(1);
  676. // tree.add_child(parent, child1);
  677. // let grandchild1 = tree.create_node(1);
  678. // tree.add_child(child1, grandchild1);
  679. // let child2 = tree.create_node(1);
  680. // tree.add_child(parent, child2);
  681. // let grandchild2 = tree.create_node(1);
  682. // tree.add_child(child2, grandchild2);
  683. // tree.dirty_nodes
  684. // .insert(TypeId::of::<AddNumber>(), NodeId(0));
  685. // tree.update_state(SendAnyMap::new());
  686. // assert_eq!(tree.get(tree.root()).unwrap().state.add_number.0, 1);
  687. // assert_eq!(tree.get(child1).unwrap().state.add_number.0, 2);
  688. // assert_eq!(tree.get(grandchild1).unwrap().state.add_number.0, 3);
  689. // assert_eq!(tree.get(child2).unwrap().state.add_number.0, 2);
  690. // assert_eq!(tree.get(grandchild2).unwrap().state.add_number.0, 3);
  691. // }
  692. // #[test]
  693. // fn dependant_down_pass() {
  694. // use crate::tree::{Tree, TreeLike};
  695. // // 0
  696. // let mut tree = Tree::new(1);
  697. // let parent = tree.root();
  698. // // 1
  699. // let child1 = tree.create_node(1);
  700. // tree.add_child(parent, child1);
  701. // // 2
  702. // let grandchild1 = tree.create_node(1);
  703. // tree.add_child(child1, grandchild1);
  704. // // 3
  705. // let child2 = tree.create_node(1);
  706. // tree.add_child(parent, child2);
  707. // // 4
  708. // let grandchild2 = tree.create_node(1);
  709. // tree.add_child(child2, grandchild2);
  710. // struct AddPass;
  711. // impl Pass for AddPass {
  712. // fn pass_id(&self) -> PassId {
  713. // PassId(0)
  714. // }
  715. // fn dependancies(&self) -> &'static [PassId] {
  716. // &[PassId(1)]
  717. // }
  718. // fn dependants(&self) -> &'static [PassId] {
  719. // &[]
  720. // }
  721. // fn mask(&self) -> MemberMask {
  722. // MemberMask(0)
  723. // }
  724. // }
  725. // impl DownwardPass<i32> for AddPass {
  726. // fn pass(&self, node: &mut i32, parent: Option<&mut i32>, _: &SendAnyMap) -> PassReturn {
  727. // if let Some(parent) = parent {
  728. // *node += *parent;
  729. // } else {
  730. // }
  731. // PassReturn {
  732. // progress: true,
  733. // mark_dirty: true,
  734. // }
  735. // }
  736. // }
  737. // struct SubtractPass;
  738. // impl Pass for SubtractPass {
  739. // fn pass_id(&self) -> PassId {
  740. // PassId(1)
  741. // }
  742. // fn dependancies(&self) -> &'static [PassId] {
  743. // &[]
  744. // }
  745. // fn dependants(&self) -> &'static [PassId] {
  746. // &[PassId(0)]
  747. // }
  748. // fn mask(&self) -> MemberMask {
  749. // MemberMask(0)
  750. // }
  751. // }
  752. // impl DownwardPass<i32> for SubtractPass {
  753. // fn pass(&self, node: &mut i32, parent: Option<&mut i32>, _: &SendAnyMap) -> PassReturn {
  754. // if let Some(parent) = parent {
  755. // *node -= *parent;
  756. // } else {
  757. // }
  758. // PassReturn {
  759. // progress: true,
  760. // mark_dirty: true,
  761. // }
  762. // }
  763. // }
  764. // let add_pass = AnyPass::Downward(&AddPass);
  765. // let subtract_pass = AnyPass::Downward(&SubtractPass);
  766. // let passes = vec![&add_pass, &subtract_pass];
  767. // let dirty_nodes: DirtyNodeStates = DirtyNodeStates::default();
  768. // dirty_nodes.insert(PassId(1), tree.root());
  769. // resolve_passes(&mut tree, dirty_nodes, passes, SendAnyMap::new());
  770. // // Tree before:
  771. // // 1=\
  772. // // 1=\
  773. // // 1
  774. // // 1=\
  775. // // 1
  776. // // Tree after subtract:
  777. // // 1=\
  778. // // 0=\
  779. // // 1
  780. // // 0=\
  781. // // 1
  782. // // Tree after add:
  783. // // 1=\
  784. // // 1=\
  785. // // 2
  786. // // 1=\
  787. // // 2
  788. // assert_eq!(tree.get(tree.root()).unwrap(), &1);
  789. // assert_eq!(tree.get(child1).unwrap(), &1);
  790. // assert_eq!(tree.get(grandchild1).unwrap(), &2);
  791. // assert_eq!(tree.get(child2).unwrap(), &1);
  792. // assert_eq!(tree.get(grandchild2).unwrap(), &2);
  793. // }
  794. // #[test]
  795. // fn up_pass() {
  796. // use crate::tree::{Tree, TreeLike};
  797. // // Tree before:
  798. // // 0=\
  799. // // 0=\
  800. // // 1
  801. // // 0=\
  802. // // 1
  803. // // Tree after:
  804. // // 2=\
  805. // // 1=\
  806. // // 1
  807. // // 1=\
  808. // // 1
  809. // let mut tree = Tree::new(0);
  810. // let parent = tree.root();
  811. // let child1 = tree.create_node(0);
  812. // tree.add_child(parent, child1);
  813. // let grandchild1 = tree.create_node(1);
  814. // tree.add_child(child1, grandchild1);
  815. // let child2 = tree.create_node(0);
  816. // tree.add_child(parent, child2);
  817. // let grandchild2 = tree.create_node(1);
  818. // tree.add_child(child2, grandchild2);
  819. // struct AddPass;
  820. // impl Pass for AddPass {
  821. // fn pass_id(&self) -> PassId {
  822. // PassId(0)
  823. // }
  824. // fn dependancies(&self) -> &'static [PassId] {
  825. // &[]
  826. // }
  827. // fn dependants(&self) -> &'static [PassId] {
  828. // &[]
  829. // }
  830. // fn mask(&self) -> MemberMask {
  831. // MemberMask(0)
  832. // }
  833. // }
  834. // impl UpwardPass<i32> for AddPass {
  835. // fn pass<'a>(
  836. // &self,
  837. // node: &mut i32,
  838. // children: &mut dyn Iterator<Item = &'a mut i32>,
  839. // _: &SendAnyMap,
  840. // ) -> PassReturn {
  841. // *node += children.map(|i| *i).sum::<i32>();
  842. // PassReturn {
  843. // progress: true,
  844. // mark_dirty: true,
  845. // }
  846. // }
  847. // }
  848. // let add_pass = AnyPass::Upward(&AddPass);
  849. // let passes = vec![&add_pass];
  850. // let dirty_nodes: DirtyNodeStates = DirtyNodeStates::default();
  851. // dirty_nodes.insert(PassId(0), grandchild1);
  852. // dirty_nodes.insert(PassId(0), grandchild2);
  853. // resolve_passes(&mut tree, dirty_nodes, passes, SendAnyMap::new());
  854. // assert_eq!(tree.get(tree.root()).unwrap(), &2);
  855. // assert_eq!(tree.get(child1).unwrap(), &1);
  856. // assert_eq!(tree.get(grandchild1).unwrap(), &1);
  857. // assert_eq!(tree.get(child2).unwrap(), &1);
  858. // assert_eq!(tree.get(grandchild2).unwrap(), &1);
  859. // }
  860. // #[test]
  861. // fn dependant_up_pass() {
  862. // use crate::tree::{Tree, TreeLike};
  863. // // 0
  864. // let mut tree = Tree::new(0);
  865. // let parent = tree.root();
  866. // // 1
  867. // let child1 = tree.create_node(0);
  868. // tree.add_child(parent, child1);
  869. // // 2
  870. // let grandchild1 = tree.create_node(1);
  871. // tree.add_child(child1, grandchild1);
  872. // // 3
  873. // let child2 = tree.create_node(0);
  874. // tree.add_child(parent, child2);
  875. // // 4
  876. // let grandchild2 = tree.create_node(1);
  877. // tree.add_child(child2, grandchild2);
  878. // struct AddPass;
  879. // impl Pass for AddPass {
  880. // fn pass_id(&self) -> PassId {
  881. // PassId(0)
  882. // }
  883. // fn dependancies(&self) -> &'static [PassId] {
  884. // &[PassId(1)]
  885. // }
  886. // fn dependants(&self) -> &'static [PassId] {
  887. // &[]
  888. // }
  889. // fn mask(&self) -> MemberMask {
  890. // MemberMask(0)
  891. // }
  892. // }
  893. // impl UpwardPass<i32> for AddPass {
  894. // fn pass<'a>(
  895. // &self,
  896. // node: &mut i32,
  897. // children: &mut dyn Iterator<Item = &'a mut i32>,
  898. // _: &SendAnyMap,
  899. // ) -> PassReturn {
  900. // *node += children.map(|i| *i).sum::<i32>();
  901. // PassReturn {
  902. // progress: true,
  903. // mark_dirty: true,
  904. // }
  905. // }
  906. // }
  907. // struct SubtractPass;
  908. // impl Pass for SubtractPass {
  909. // fn pass_id(&self) -> PassId {
  910. // PassId(1)
  911. // }
  912. // fn dependancies(&self) -> &'static [PassId] {
  913. // &[]
  914. // }
  915. // fn dependants(&self) -> &'static [PassId] {
  916. // &[PassId(0)]
  917. // }
  918. // fn mask(&self) -> MemberMask {
  919. // MemberMask(0)
  920. // }
  921. // }
  922. // impl UpwardPass<i32> for SubtractPass {
  923. // fn pass<'a>(
  924. // &self,
  925. // node: &mut i32,
  926. // children: &mut dyn Iterator<Item = &'a mut i32>,
  927. // _: &SendAnyMap,
  928. // ) -> PassReturn {
  929. // *node -= children.map(|i| *i).sum::<i32>();
  930. // PassReturn {
  931. // progress: true,
  932. // mark_dirty: true,
  933. // }
  934. // }
  935. // }
  936. // let add_pass = AnyPass::Upward(&AddPass);
  937. // let subtract_pass = AnyPass::Upward(&SubtractPass);
  938. // let passes = vec![&add_pass, &subtract_pass];
  939. // let dirty_nodes: DirtyNodeStates = DirtyNodeStates::default();
  940. // dirty_nodes.insert(PassId(1), grandchild1);
  941. // dirty_nodes.insert(PassId(1), grandchild2);
  942. // resolve_passes(&mut tree, dirty_nodes, passes, SendAnyMap::new());
  943. // // Tree before:
  944. // // 0=\
  945. // // 0=\
  946. // // 1
  947. // // 0=\
  948. // // 1
  949. // // Tree after subtract:
  950. // // 2=\
  951. // // -1=\
  952. // // 1
  953. // // -1=\
  954. // // 1
  955. // // Tree after add:
  956. // // 2=\
  957. // // 0=\
  958. // // 1
  959. // // 0=\
  960. // // 1
  961. // assert_eq!(tree.get(tree.root()).unwrap(), &2);
  962. // assert_eq!(tree.get(child1).unwrap(), &0);
  963. // assert_eq!(tree.get(grandchild1).unwrap(), &1);
  964. // assert_eq!(tree.get(child2).unwrap(), &0);
  965. // assert_eq!(tree.get(grandchild2).unwrap(), &1);
  966. // }