fuzzing.rs 13 KB

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