fuzzing.rs 13 KB

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