1
0

fuzzing.rs 13 KB

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