fuzzing.rs 12 KB

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