fuzzing.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. use dioxus::prelude::Props;
  2. use dioxus_core::*;
  3. use dioxus_native_core::{
  4. node_ref::{AttributeMaskBuilder, NodeMaskBuilder, NodeView},
  5. real_dom::RealDom,
  6. Dependancy, Pass, SendAnyMap,
  7. };
  8. use std::cell::Cell;
  9. fn random_ns() -> Option<&'static str> {
  10. let namespace = rand::random::<u8>() % 2;
  11. match namespace {
  12. 0 => None,
  13. 1 => Some(Box::leak(
  14. format!("ns{}", rand::random::<usize>()).into_boxed_str(),
  15. )),
  16. _ => unreachable!(),
  17. }
  18. }
  19. fn create_random_attribute(attr_idx: &mut usize) -> TemplateAttribute<'static> {
  20. match rand::random::<u8>() % 2 {
  21. 0 => TemplateAttribute::Static {
  22. name: Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  23. value: Box::leak(format!("value{}", rand::random::<usize>()).into_boxed_str()),
  24. namespace: random_ns(),
  25. },
  26. 1 => TemplateAttribute::Dynamic {
  27. id: {
  28. let old_idx = *attr_idx;
  29. *attr_idx += 1;
  30. old_idx
  31. },
  32. },
  33. _ => unreachable!(),
  34. }
  35. }
  36. fn create_random_template_node(
  37. dynamic_node_types: &mut Vec<DynamicNodeType>,
  38. template_idx: &mut usize,
  39. attr_idx: &mut usize,
  40. depth: usize,
  41. ) -> TemplateNode<'static> {
  42. match rand::random::<u8>() % 4 {
  43. 0 => {
  44. let attrs = {
  45. let attrs: Vec<_> = (0..(rand::random::<usize>() % 10))
  46. .map(|_| create_random_attribute(attr_idx))
  47. .collect();
  48. Box::leak(attrs.into_boxed_slice())
  49. };
  50. TemplateNode::Element {
  51. tag: Box::leak(format!("tag{}", rand::random::<usize>()).into_boxed_str()),
  52. namespace: random_ns(),
  53. attrs,
  54. children: {
  55. if depth > 4 {
  56. &[]
  57. } else {
  58. let children: Vec<_> = (0..(rand::random::<usize>() % 3))
  59. .map(|_| {
  60. create_random_template_node(
  61. dynamic_node_types,
  62. template_idx,
  63. attr_idx,
  64. depth + 1,
  65. )
  66. })
  67. .collect();
  68. Box::leak(children.into_boxed_slice())
  69. }
  70. },
  71. }
  72. }
  73. 1 => TemplateNode::Text {
  74. text: Box::leak(format!("{}", rand::random::<usize>()).into_boxed_str()),
  75. },
  76. 2 => TemplateNode::DynamicText {
  77. id: {
  78. let old_idx = *template_idx;
  79. *template_idx += 1;
  80. dynamic_node_types.push(DynamicNodeType::Text);
  81. old_idx
  82. },
  83. },
  84. 3 => TemplateNode::Dynamic {
  85. id: {
  86. let old_idx = *template_idx;
  87. *template_idx += 1;
  88. dynamic_node_types.push(DynamicNodeType::Other);
  89. old_idx
  90. },
  91. },
  92. _ => unreachable!(),
  93. }
  94. }
  95. fn generate_paths(
  96. node: &TemplateNode<'static>,
  97. current_path: &[u8],
  98. node_paths: &mut Vec<Vec<u8>>,
  99. attr_paths: &mut Vec<Vec<u8>>,
  100. ) {
  101. match node {
  102. TemplateNode::Element {
  103. children, attrs, ..
  104. } => {
  105. for attr in *attrs {
  106. match attr {
  107. TemplateAttribute::Static { .. } => {}
  108. TemplateAttribute::Dynamic { .. } => {
  109. attr_paths.push(current_path.to_vec());
  110. }
  111. }
  112. }
  113. for (i, child) in children.iter().enumerate() {
  114. let mut current_path = current_path.to_vec();
  115. current_path.push(i as u8);
  116. generate_paths(child, &current_path, node_paths, attr_paths);
  117. }
  118. }
  119. TemplateNode::Text { .. } => {}
  120. TemplateNode::DynamicText { .. } => {
  121. node_paths.push(current_path.to_vec());
  122. }
  123. TemplateNode::Dynamic { .. } => {
  124. node_paths.push(current_path.to_vec());
  125. }
  126. }
  127. }
  128. enum DynamicNodeType {
  129. Text,
  130. Other,
  131. }
  132. fn create_random_template(name: &'static str) -> (Template<'static>, Vec<DynamicNodeType>) {
  133. let mut dynamic_node_type = Vec::new();
  134. let mut template_idx = 0;
  135. let mut attr_idx = 0;
  136. let roots = (0..(1 + rand::random::<usize>() % 5))
  137. .map(|_| {
  138. create_random_template_node(&mut dynamic_node_type, &mut template_idx, &mut attr_idx, 0)
  139. })
  140. .collect::<Vec<_>>();
  141. assert!(!roots.is_empty());
  142. let roots = Box::leak(roots.into_boxed_slice());
  143. let mut node_paths = Vec::new();
  144. let mut attr_paths = Vec::new();
  145. for (i, root) in roots.iter().enumerate() {
  146. generate_paths(root, &[i as u8], &mut node_paths, &mut attr_paths);
  147. }
  148. let node_paths = Box::leak(
  149. node_paths
  150. .into_iter()
  151. .map(|v| &*Box::leak(v.into_boxed_slice()))
  152. .collect::<Vec<_>>()
  153. .into_boxed_slice(),
  154. );
  155. let attr_paths = Box::leak(
  156. attr_paths
  157. .into_iter()
  158. .map(|v| &*Box::leak(v.into_boxed_slice()))
  159. .collect::<Vec<_>>()
  160. .into_boxed_slice(),
  161. );
  162. (
  163. Template {
  164. name,
  165. roots,
  166. node_paths,
  167. attr_paths,
  168. },
  169. dynamic_node_type,
  170. )
  171. }
  172. fn create_random_dynamic_node(cx: &ScopeState, depth: usize) -> DynamicNode {
  173. let range = if depth > 3 { 1 } else { 3 };
  174. match rand::random::<u8>() % range {
  175. 0 => DynamicNode::Placeholder(Default::default()),
  176. 1 => cx.make_node((0..(rand::random::<u8>() % 5)).map(|_| VNode {
  177. key: None,
  178. parent: Default::default(),
  179. template: Cell::new(Template {
  180. name: concat!(file!(), ":", line!(), ":", column!(), ":0"),
  181. roots: &[TemplateNode::Dynamic { id: 0 }],
  182. node_paths: &[&[0]],
  183. attr_paths: &[],
  184. }),
  185. root_ids: Default::default(),
  186. dynamic_nodes: cx.bump().alloc([cx.component(
  187. create_random_element,
  188. DepthProps { depth, root: false },
  189. "create_random_element",
  190. )]),
  191. dynamic_attrs: &[],
  192. })),
  193. 2 => cx.component(
  194. create_random_element,
  195. DepthProps { depth, root: false },
  196. "create_random_element",
  197. ),
  198. _ => unreachable!(),
  199. }
  200. }
  201. fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
  202. let value = match rand::random::<u8>() % 6 {
  203. 0 => AttributeValue::Text(Box::leak(
  204. format!("{}", rand::random::<usize>()).into_boxed_str(),
  205. )),
  206. 1 => AttributeValue::Float(rand::random()),
  207. 2 => AttributeValue::Int(rand::random()),
  208. 3 => AttributeValue::Bool(rand::random()),
  209. 4 => cx.any_value(rand::random::<usize>()),
  210. 5 => AttributeValue::None,
  211. // Listener(RefCell<Option<ListenerCb<'a>>>),
  212. _ => unreachable!(),
  213. };
  214. Attribute {
  215. name: Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  216. value,
  217. namespace: random_ns(),
  218. mounted_element: Default::default(),
  219. volatile: rand::random(),
  220. }
  221. }
  222. static mut TEMPLATE_COUNT: usize = 0;
  223. #[derive(PartialEq, Props)]
  224. struct DepthProps {
  225. depth: usize,
  226. root: bool,
  227. }
  228. fn create_random_element(cx: Scope<DepthProps>) -> Element {
  229. cx.needs_update();
  230. let range = if cx.props.root { 2 } else { 3 };
  231. let node = match rand::random::<usize>() % range {
  232. 0 | 1 => {
  233. let (template, dynamic_node_types) = create_random_template(Box::leak(
  234. format!(
  235. "{}{}",
  236. concat!(file!(), ":", line!(), ":", column!(), ":"),
  237. {
  238. unsafe {
  239. let old = TEMPLATE_COUNT;
  240. TEMPLATE_COUNT += 1;
  241. old
  242. }
  243. }
  244. )
  245. .into_boxed_str(),
  246. ));
  247. println!("{template:#?}");
  248. let node = VNode {
  249. key: None,
  250. parent: None,
  251. template: Cell::new(template),
  252. root_ids: Default::default(),
  253. dynamic_nodes: {
  254. let dynamic_nodes: Vec<_> = dynamic_node_types
  255. .iter()
  256. .map(|ty| match ty {
  257. DynamicNodeType::Text => DynamicNode::Text(VText {
  258. value: Box::leak(
  259. format!("{}", rand::random::<usize>()).into_boxed_str(),
  260. ),
  261. id: Default::default(),
  262. }),
  263. DynamicNodeType::Other => {
  264. create_random_dynamic_node(cx, cx.props.depth + 1)
  265. }
  266. })
  267. .collect();
  268. cx.bump().alloc(dynamic_nodes)
  269. },
  270. dynamic_attrs: cx.bump().alloc(
  271. (0..template.attr_paths.len())
  272. .map(|_| create_random_dynamic_attr(cx))
  273. .collect::<Vec<_>>(),
  274. ),
  275. };
  276. Some(node)
  277. }
  278. _ => None,
  279. };
  280. println!("{node:#?}");
  281. node
  282. }
  283. #[derive(Debug, Clone, PartialEq, Eq, Default)]
  284. pub struct BlablaState {
  285. count: usize,
  286. }
  287. impl Pass for BlablaState {
  288. type ParentDependencies = (Self,);
  289. type ChildDependencies = ();
  290. type NodeDependencies = ();
  291. const NODE_MASK: NodeMaskBuilder = NodeMaskBuilder::new()
  292. .with_attrs(AttributeMaskBuilder::Some(&["blabla"]))
  293. .with_element();
  294. fn pass<'a>(
  295. &mut self,
  296. _: NodeView,
  297. _: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  298. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  299. _: Option<Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>>,
  300. _: &SendAnyMap,
  301. ) -> bool {
  302. if let Some((parent,)) = parent {
  303. if parent.count != 0 {
  304. self.count += 1;
  305. }
  306. }
  307. true
  308. }
  309. fn create<'a>(
  310. node_view: NodeView<()>,
  311. node: <Self::NodeDependencies as Dependancy>::ElementBorrowed<'a>,
  312. parent: Option<<Self::ParentDependencies as Dependancy>::ElementBorrowed<'a>>,
  313. children: Option<Vec<<Self::ChildDependencies as Dependancy>::ElementBorrowed<'a>>>,
  314. context: &SendAnyMap,
  315. ) -> Self {
  316. let mut myself = Self::default();
  317. myself.pass(node_view, node, parent, children, context);
  318. myself
  319. }
  320. }
  321. // test for panics when creating random nodes and templates
  322. #[test]
  323. fn create() {
  324. for _ in 0..100 {
  325. let mut vdom = VirtualDom::new_with_props(
  326. create_random_element,
  327. DepthProps {
  328. depth: 0,
  329. root: true,
  330. },
  331. );
  332. let mutations = vdom.rebuild();
  333. let mut rdom: RealDom = RealDom::new(Box::new([BlablaState::to_type_erased()]));
  334. rdom.apply_mutations(mutations);
  335. let ctx = SendAnyMap::new();
  336. rdom.update_state(ctx, false);
  337. }
  338. }
  339. // test for panics when diffing random nodes
  340. // This test will change the template every render which is not very realistic, but it helps stress the system
  341. #[test]
  342. fn diff() {
  343. for _ in 0..10 {
  344. let mut vdom = VirtualDom::new_with_props(
  345. create_random_element,
  346. DepthProps {
  347. depth: 0,
  348. root: true,
  349. },
  350. );
  351. let mutations = vdom.rebuild();
  352. let mut rdom: RealDom = RealDom::new(Box::new([BlablaState::to_type_erased()]));
  353. rdom.apply_mutations(mutations);
  354. let ctx = SendAnyMap::new();
  355. rdom.update_state(ctx, false);
  356. for _ in 0..10 {
  357. let mutations = vdom.render_immediate();
  358. rdom.apply_mutations(mutations);
  359. let ctx = SendAnyMap::new();
  360. rdom.update_state(ctx, false);
  361. }
  362. }
  363. }