fuzzing.rs 14 KB

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