lib.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. extern crate proc_macro;
  2. use layout::Layout;
  3. use nest::{Nest, NestId};
  4. use proc_macro::TokenStream;
  5. use quote::{__private::Span, format_ident, quote, ToTokens};
  6. use redirect::Redirect;
  7. use route::{Route, RouteType};
  8. use segment::RouteSegment;
  9. use syn::{parse::ParseStream, parse_macro_input, Ident, Token, Type};
  10. use proc_macro2::TokenStream as TokenStream2;
  11. use crate::{layout::LayoutId, route_tree::RouteTree};
  12. mod layout;
  13. mod nest;
  14. mod query;
  15. mod redirect;
  16. mod route;
  17. mod route_tree;
  18. mod segment;
  19. /// Derives the Routable trait for an enum of routes
  20. ///
  21. /// Each varient must:
  22. /// 1. Be struct-like with {}'s
  23. /// 2. Contain all of the dynamic parameters of the current and nested routes
  24. /// 3. Have a #[route("route")] attribute
  25. ///
  26. /// Route Segments:
  27. /// 1. Static Segments: "/static"
  28. /// 2. Dynamic Segments: "/:dynamic" (where dynamic has a type that is FromStr in all child Variants)
  29. /// 3. Catch all Segments: "/:...segments" (where segments has a type that is FromSegments in all child Variants)
  30. /// 4. Query Segments: "/?:query" (where query has a type that is FromQuery in all child Variants)
  31. ///
  32. /// Routes are matched:
  33. /// 1. By there specificity this order: Query Routes ("/?:query"), Static Routes ("/route"), Dynamic Routes ("/:route"), Catch All Routes ("/:...route")
  34. /// 2. By the order they are defined in the enum
  35. ///
  36. /// All features:
  37. /// ```rust, skip
  38. /// #[rustfmt::skip]
  39. /// #[derive(Clone, Debug, PartialEq, Routable)]
  40. /// enum Route {
  41. /// // Define routes with the route macro. If the name of the component is not the same as the variant, you can specify it as the second parameter and the props type as the third
  42. /// #[route("/", IndexComponent, ComponentProps)]
  43. /// Index {},
  44. /// // Nests with parameters have types taken from child routes
  45. /// // Everything inside the nest has the added parameter `user_id: usize`
  46. /// #[nest("/user/:user_id")]
  47. /// // All children of layouts will be rendered inside the Outlet in the layout component
  48. /// // Creates a Layout UserFrame that has the parameter `user_id: usize`
  49. /// #[layout(UserFrame)]
  50. /// // If there is a component with the name Route1 and props with the name Route1Props, you do not need to pass in the component and type
  51. /// #[route("/:dynamic?:query")]
  52. /// Route1 {
  53. /// // The type is taken from the first instance of the dynamic parameter
  54. /// user_id: usize,
  55. /// dynamic: usize,
  56. /// query: String,
  57. /// extra: String,
  58. /// },
  59. /// #[route("/hello_world")]
  60. /// // You can opt out of the layout by using the `!` prefix
  61. /// #[layout(!UserFrame)]
  62. /// Route2 { user_id: usize },
  63. /// // End layouts with #[end_layout]
  64. /// #[end_layout]
  65. /// // End nests with #[end_nest]
  66. /// #[end_nest]
  67. /// // Redirects take a path and a function that takes the parameters from the path and returns a new route
  68. /// #[redirect("/:id/user", |id: usize| Route::Route3 { dynamic: id.to_string()})]
  69. /// #[route("/:dynamic")]
  70. /// Route3 { dynamic: String },
  71. /// #[child]
  72. /// NestedRoute(NestedRoute),
  73. /// }
  74. /// ```
  75. #[proc_macro_derive(
  76. Routable,
  77. attributes(route, nest, end_nest, layout, end_layout, redirect, child)
  78. )]
  79. pub fn routable(input: TokenStream) -> TokenStream {
  80. let routes_enum = parse_macro_input!(input as syn::ItemEnum);
  81. let route_enum = match RouteEnum::parse(routes_enum) {
  82. Ok(route_enum) => route_enum,
  83. Err(err) => return err.to_compile_error().into(),
  84. };
  85. let error_type = route_enum.error_type();
  86. let parse_impl = route_enum.parse_impl();
  87. let display_impl = route_enum.impl_display();
  88. let routable_impl = route_enum.routable_impl();
  89. let name = &route_enum.name;
  90. let vis = &route_enum.vis;
  91. quote! {
  92. #vis fn Outlet(cx: dioxus::prelude::Scope) -> dioxus::prelude::Element {
  93. dioxus_router::prelude::GenericOutlet::<#name>(cx)
  94. }
  95. #vis fn Router(cx: dioxus::prelude::Scope<dioxus_router::prelude::GenericRouterProps<#name>>) -> dioxus::prelude::Element {
  96. dioxus_router::prelude::GenericRouter(cx)
  97. }
  98. #vis fn Link<'a>(cx: dioxus::prelude::Scope<'a, dioxus_router::prelude::GenericLinkProps<'a, #name>>) -> dioxus::prelude::Element<'a> {
  99. dioxus_router::prelude::GenericLink(cx)
  100. }
  101. #vis fn GoBackButton<'a>(cx: dioxus::prelude::Scope<'a, dioxus_router::prelude::GenericHistoryButtonProps<'a>>) -> dioxus::prelude::Element<'a> {
  102. dioxus_router::prelude::GenericGoBackButton::<#name>(cx)
  103. }
  104. #vis fn GoForwardButton<'a>(cx: dioxus::prelude::Scope<'a, dioxus_router::prelude::GenericHistoryButtonProps<'a>>) -> dioxus::prelude::Element<'a> {
  105. dioxus_router::prelude::GenericGoForwardButton::<#name>(cx)
  106. }
  107. #vis fn use_route(cx: &dioxus::prelude::ScopeState) -> Option<#name> {
  108. dioxus_router::prelude::use_generic_route(cx)
  109. }
  110. #vis fn use_navigator(cx: &dioxus::prelude::ScopeState) -> &dioxus_router::prelude::GenericNavigator<#name> {
  111. dioxus_router::prelude::use_generic_navigator(cx)
  112. }
  113. #error_type
  114. #display_impl
  115. #routable_impl
  116. #parse_impl
  117. }
  118. .into()
  119. }
  120. struct RouteEnum {
  121. vis: syn::Visibility,
  122. name: Ident,
  123. redirects: Vec<Redirect>,
  124. routes: Vec<Route>,
  125. nests: Vec<Nest>,
  126. layouts: Vec<Layout>,
  127. site_map: Vec<SiteMapSegment>,
  128. }
  129. impl RouteEnum {
  130. fn parse(data: syn::ItemEnum) -> syn::Result<Self> {
  131. let name = &data.ident;
  132. let vis = &data.vis;
  133. let mut site_map = Vec::new();
  134. let mut site_map_stack: Vec<Vec<SiteMapSegment>> = Vec::new();
  135. let mut routes = Vec::new();
  136. let mut redirects = Vec::new();
  137. let mut layouts: Vec<Layout> = Vec::new();
  138. let mut layout_stack = Vec::new();
  139. let mut nests = Vec::new();
  140. let mut nest_stack = Vec::new();
  141. for variant in &data.variants {
  142. let mut excluded = Vec::new();
  143. // Apply the any nesting attributes in order
  144. for attr in &variant.attrs {
  145. if attr.path.is_ident("nest") {
  146. let mut children_routes = Vec::new();
  147. {
  148. // add all of the variants of the enum to the children_routes until we hit an end_nest
  149. let mut level = 0;
  150. 'o: for variant in &data.variants {
  151. children_routes.push(variant.fields.clone());
  152. for attr in &variant.attrs {
  153. if attr.path.is_ident("nest") {
  154. level += 1;
  155. } else if attr.path.is_ident("end_nest") {
  156. level -= 1;
  157. if level < 0 {
  158. break 'o;
  159. }
  160. }
  161. }
  162. }
  163. }
  164. let nest_index = nests.len();
  165. let parser = |input: ParseStream| {
  166. Nest::parse(
  167. input,
  168. children_routes
  169. .iter()
  170. .filter_map(|f: &syn::Fields| match f {
  171. syn::Fields::Named(fields) => Some(fields.clone()),
  172. _ => None,
  173. })
  174. .collect(),
  175. nest_index,
  176. )
  177. };
  178. let nest = attr.parse_args_with(parser)?;
  179. // add the current segment to the site map stack
  180. let segments: Vec<_> = nest
  181. .segments
  182. .iter()
  183. .map(|seg| {
  184. let segment_type = seg.into();
  185. SiteMapSegment {
  186. segment_type,
  187. children: Vec::new(),
  188. }
  189. })
  190. .collect();
  191. if !segments.is_empty() {
  192. site_map_stack.push(segments);
  193. }
  194. nests.push(nest);
  195. nest_stack.push(NestId(nest_index));
  196. } else if attr.path.is_ident("end_nest") {
  197. nest_stack.pop();
  198. // pop the current nest segment off the stack and add it to the parent or the site map
  199. if let Some(segment) = site_map_stack.pop() {
  200. let children = site_map_stack
  201. .last_mut()
  202. .map(|seg| &mut seg.last_mut().unwrap().children)
  203. .unwrap_or(&mut site_map);
  204. // Turn the list of segments in the segments stack into a tree
  205. let mut iter = segment.into_iter().rev();
  206. let mut current = iter.next().unwrap();
  207. for mut segment in iter {
  208. segment.children.push(current);
  209. current = segment;
  210. }
  211. children.push(current);
  212. }
  213. } else if attr.path.is_ident("layout") {
  214. let parser = |input: ParseStream| {
  215. let bang: Option<Token![!]> = input.parse().ok();
  216. let exclude = bang.is_some();
  217. Ok((
  218. exclude,
  219. Layout::parse(input, nest_stack.iter().rev().cloned().collect())?,
  220. ))
  221. };
  222. let (exclude, layout): (bool, Layout) = attr.parse_args_with(parser)?;
  223. if exclude {
  224. let Some(layout_index) =
  225. layouts.iter().position(|l| l.comp == layout.comp) else {
  226. return Err(syn::Error::new(
  227. Span::call_site(),
  228. "Attempted to exclude a layout that does not exist",
  229. ));
  230. };
  231. excluded.push(LayoutId(layout_index));
  232. } else {
  233. let layout_index = layouts.len();
  234. layouts.push(layout);
  235. layout_stack.push(LayoutId(layout_index));
  236. }
  237. } else if attr.path.is_ident("end_layout") {
  238. layout_stack.pop();
  239. } else if attr.path.is_ident("redirect") {
  240. let parser = |input: ParseStream| {
  241. Redirect::parse(
  242. input,
  243. nest_stack.iter().rev().cloned().collect(),
  244. redirects.len(),
  245. )
  246. };
  247. let redirect = attr.parse_args_with(parser)?;
  248. redirects.push(redirect);
  249. }
  250. }
  251. let mut active_nests = nest_stack.clone();
  252. active_nests.reverse();
  253. let mut active_layouts = layout_stack.clone();
  254. active_layouts.retain(|&id| !excluded.contains(&id));
  255. let route = Route::parse(active_nests, active_layouts, variant.clone())?;
  256. // add the route to the site map
  257. let mut segment = SiteMapSegment::new(&route.segments);
  258. if let RouteType::Child(child) = &route.ty {
  259. let new_segment = SiteMapSegment {
  260. segment_type: SegmentType::Child(child.ty.clone()),
  261. children: Vec::new(),
  262. };
  263. match &mut segment {
  264. Some(segment) => {
  265. fn set_last_child_to(
  266. segment: &mut SiteMapSegment,
  267. new_segment: SiteMapSegment,
  268. ) {
  269. if let Some(last) = segment.children.last_mut() {
  270. set_last_child_to(last, new_segment);
  271. } else {
  272. segment.children = vec![new_segment];
  273. }
  274. }
  275. set_last_child_to(segment, new_segment);
  276. }
  277. None => {
  278. segment = Some(new_segment);
  279. }
  280. }
  281. }
  282. if let Some(segment) = segment {
  283. let parent = site_map_stack.last_mut();
  284. let children = match parent {
  285. Some(parent) => &mut parent.last_mut().unwrap().children,
  286. None => &mut site_map,
  287. };
  288. children.push(segment);
  289. }
  290. routes.push(route);
  291. }
  292. let myself = Self {
  293. vis: vis.clone(),
  294. name: name.clone(),
  295. routes,
  296. redirects,
  297. nests,
  298. layouts,
  299. site_map,
  300. };
  301. Ok(myself)
  302. }
  303. fn impl_display(&self) -> TokenStream2 {
  304. let mut display_match = Vec::new();
  305. for route in &self.routes {
  306. display_match.push(route.display_match(&self.nests));
  307. }
  308. let name = &self.name;
  309. quote! {
  310. impl std::fmt::Display for #name {
  311. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  312. #[allow(unused)]
  313. match self {
  314. #(#display_match)*
  315. }
  316. Ok(())
  317. }
  318. }
  319. }
  320. }
  321. fn parse_impl(&self) -> TokenStream2 {
  322. let tree = RouteTree::new(&self.routes, &self.nests, &self.redirects);
  323. let name = &self.name;
  324. let error_name = format_ident!("{}MatchError", self.name);
  325. let tokens = tree.roots.iter().map(|&id| {
  326. let route = tree.get(id).unwrap();
  327. route.to_tokens(&self.nests, &tree, self.name.clone(), error_name.clone())
  328. });
  329. quote! {
  330. impl<'a> core::convert::TryFrom<&'a str> for #name {
  331. type Error = <Self as std::str::FromStr>::Err;
  332. fn try_from(s: &'a str) -> Result<Self, Self::Error> {
  333. s.parse()
  334. }
  335. }
  336. impl std::str::FromStr for #name {
  337. type Err = dioxus_router::routable::RouteParseError<#error_name>;
  338. fn from_str(s: &str) -> Result<Self, Self::Err> {
  339. let route = s;
  340. let (route, query) = route.split_once('?').unwrap_or((route, ""));
  341. let mut segments = route.split('/');
  342. // skip the first empty segment
  343. if s.starts_with('/') {
  344. segments.next();
  345. }
  346. let mut errors = Vec::new();
  347. #(#tokens)*
  348. Err(dioxus_router::routable::RouteParseError {
  349. attempted_routes: errors,
  350. })
  351. }
  352. }
  353. }
  354. }
  355. fn error_name(&self) -> Ident {
  356. Ident::new(&(self.name.to_string() + "MatchError"), Span::call_site())
  357. }
  358. fn error_type(&self) -> TokenStream2 {
  359. let match_error_name = self.error_name();
  360. let mut type_defs = Vec::new();
  361. let mut error_variants = Vec::new();
  362. let mut display_match = Vec::new();
  363. for route in &self.routes {
  364. let route_name = &route.route_name;
  365. let error_name = route.error_ident();
  366. let route_str = &route.route;
  367. error_variants.push(quote! { #route_name(#error_name) });
  368. display_match.push(quote! { Self::#route_name(err) => write!(f, "Route '{}' ('{}') did not match:\n{}", stringify!(#route_name), #route_str, err)? });
  369. type_defs.push(route.error_type());
  370. }
  371. for nest in &self.nests {
  372. let error_variant = nest.error_variant();
  373. let error_name = nest.error_ident();
  374. let route_str = &nest.route;
  375. error_variants.push(quote! { #error_variant(#error_name) });
  376. display_match.push(quote! { Self::#error_variant(err) => write!(f, "Nest '{}' ('{}') did not match:\n{}", stringify!(#error_name), #route_str, err)? });
  377. type_defs.push(nest.error_type());
  378. }
  379. for redirect in &self.redirects {
  380. let error_variant = redirect.error_variant();
  381. let error_name = redirect.error_ident();
  382. let route_str = &redirect.route;
  383. error_variants.push(quote! { #error_variant(#error_name) });
  384. display_match.push(quote! { Self::#error_variant(err) => write!(f, "Redirect '{}' ('{}') did not match:\n{}", stringify!(#error_name), #route_str, err)? });
  385. type_defs.push(redirect.error_type());
  386. }
  387. quote! {
  388. #(#type_defs)*
  389. #[allow(non_camel_case_types)]
  390. #[derive(Debug, PartialEq)]
  391. pub enum #match_error_name {
  392. #(#error_variants),*
  393. }
  394. impl std::fmt::Display for #match_error_name {
  395. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  396. match self {
  397. #(#display_match),*
  398. }
  399. Ok(())
  400. }
  401. }
  402. }
  403. }
  404. fn routable_impl(&self) -> TokenStream2 {
  405. let name = &self.name;
  406. let site_map = &self.site_map;
  407. let mut matches = Vec::new();
  408. // Collect all routes matches
  409. for route in &self.routes {
  410. matches.push(route.routable_match(&self.layouts, &self.nests));
  411. }
  412. quote! {
  413. impl dioxus_router::routable::Routable for #name where Self: Clone {
  414. const SITE_MAP: &'static [dioxus_router::routable::SiteMapSegment] = &[
  415. #(#site_map,)*
  416. ];
  417. fn render<'a>(&self, cx: &'a dioxus::prelude::ScopeState, level: usize) -> dioxus::prelude::Element<'a> {
  418. let myself = self.clone();
  419. match (level, myself) {
  420. #(#matches)*
  421. _ => None
  422. }
  423. }
  424. }
  425. }
  426. }
  427. }
  428. struct SiteMapSegment {
  429. pub segment_type: SegmentType,
  430. pub children: Vec<SiteMapSegment>,
  431. }
  432. impl SiteMapSegment {
  433. fn new(segments: &[RouteSegment]) -> Option<Self> {
  434. let mut current = None;
  435. // walk backwards through the new segments, adding children as we go
  436. for segment in segments.iter().rev() {
  437. let segment_type = segment.into();
  438. let mut segment = SiteMapSegment {
  439. segment_type,
  440. children: Vec::new(),
  441. };
  442. // if we have a current segment, add it as a child
  443. if let Some(current) = current.take() {
  444. segment.children.push(current)
  445. }
  446. current = Some(segment);
  447. }
  448. current
  449. }
  450. }
  451. impl ToTokens for SiteMapSegment {
  452. fn to_tokens(&self, tokens: &mut TokenStream2) {
  453. let segment_type = &self.segment_type;
  454. let children = if let SegmentType::Child(ty) = &self.segment_type {
  455. quote! { #ty::SITE_MAP }
  456. } else {
  457. let children = self
  458. .children
  459. .iter()
  460. .map(|child| child.to_token_stream())
  461. .collect::<Vec<_>>();
  462. quote! {
  463. &[
  464. #(#children,)*
  465. ]
  466. }
  467. };
  468. tokens.extend(quote! {
  469. dioxus_router::routable::SiteMapSegment {
  470. segment_type: #segment_type,
  471. children: #children,
  472. }
  473. });
  474. }
  475. }
  476. enum SegmentType {
  477. Static(String),
  478. Dynamic(String),
  479. CatchAll(String),
  480. Child(Type),
  481. }
  482. impl ToTokens for SegmentType {
  483. fn to_tokens(&self, tokens: &mut TokenStream2) {
  484. match self {
  485. SegmentType::Static(s) => {
  486. tokens.extend(quote! { dioxus_router::routable::SegmentType::Static(#s) })
  487. }
  488. SegmentType::Dynamic(s) => {
  489. tokens.extend(quote! { dioxus_router::routable::SegmentType::Dynamic(#s) })
  490. }
  491. SegmentType::CatchAll(s) => {
  492. tokens.extend(quote! { dioxus_router::routable::SegmentType::CatchAll(#s) })
  493. }
  494. SegmentType::Child(_) => {
  495. tokens.extend(quote! { dioxus_router::routable::SegmentType::Child })
  496. }
  497. }
  498. }
  499. }
  500. impl<'a> From<&'a RouteSegment> for SegmentType {
  501. fn from(value: &'a RouteSegment) -> Self {
  502. match value {
  503. segment::RouteSegment::Static(s) => SegmentType::Static(s.to_string()),
  504. segment::RouteSegment::Dynamic(s, _) => SegmentType::Dynamic(s.to_string()),
  505. segment::RouteSegment::CatchAll(s, _) => SegmentType::CatchAll(s.to_string()),
  506. }
  507. }
  508. }