1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
//! Specialization for Rust code generation. //! //! # Examples //! //! ```rust //! use genco::prelude::*; //! //! # fn main() -> genco::fmt::Result { //! let toks: rust::Tokens = quote! { //! fn foo() -> u32 { //! 42 //! } //! }; //! //! assert_eq!( //! vec![ //! "fn foo() -> u32 {", //! " 42", //! "}", //! ], //! toks.to_file_vec()? //! ); //! # Ok(()) //! # } //! ``` //! //! String quoting in Rust: //! //! ```rust //! use genco::prelude::*; //! //! # fn main() -> genco::fmt::Result { //! let toks: rust::Tokens = quote!(#("hello \n world".quoted())); //! assert_eq!("\"hello \\n world\"", toks.to_string()?); //! # Ok(()) //! # } //! ``` use crate::fmt; use crate::{ItemStr, Lang}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::fmt::Write as _; use std::rc::Rc; /// Tokens container specialization for Rust. pub type Tokens = crate::Tokens<Rust>; /// Language box specialization for Rust. pub type LangBox = crate::LangBox<Rust>; impl_plain_variadic_args!(Args, Type); /// The `()` (unit) type. pub const UNIT: Type = const_local("()"); /// The `!` (never) type. pub const NEVER: Type = const_local("!"); /// The `u8` type. pub const U8: Type = const_local("u8"); /// The `u16` type. pub const U16: Type = const_local("u16"); /// The `u32` type. pub const U32: Type = const_local("u32"); /// The `u64` type. pub const U64: Type = const_local("u64"); /// The `u128` type. pub const U128: Type = const_local("u128"); /// The `i8` type. pub const I8: Type = const_local("i8"); /// The `i16` type. pub const I16: Type = const_local("i16"); /// The `i32` type. pub const I32: Type = const_local("i32"); /// The `i64` type. pub const I64: Type = const_local("i64"); /// The `i128` type. pub const I128: Type = const_local("i128"); /// The `usize` type. pub const USIZE: Type = const_local("usize"); /// The `isize` type. pub const ISIZE: Type = const_local("isize"); static SEP: &'static str = "::"; /// The inferred reference. #[derive(Debug, Clone, Copy)] pub struct Ref; /// The static reference. #[derive(Debug, Clone, Copy)] pub struct StaticRef; /// Reference information about a name. #[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] pub enum Reference { /// An anonymous reference. Ref, /// A static reference. StaticRef, /// A named reference. Named(ItemStr), } impl From<Ref> for Reference { fn from(_: Ref) -> Self { Reference::Ref } } impl From<StaticRef> for Reference { fn from(_: StaticRef) -> Self { Reference::StaticRef } } impl From<Rc<String>> for Reference { fn from(value: Rc<String>) -> Self { Reference::Named(ItemStr::from(value)) } } impl From<&'static str> for Reference { fn from(value: &'static str) -> Self { Reference::Named(ItemStr::Static(value)) } } /// Format state for Rust. #[derive(Debug, Default)] pub struct Format {} /// Language configuration for Rust. #[derive(Debug)] pub struct Config { default_import: Import, } impl Config { /// Configure the default import policy to use. /// /// See [Import] for more details. pub fn with_default_import(self, default_import: Import) -> Self { Self { default_import, ..self } } } impl Default for Config { fn default() -> Self { Config { default_import: Import::Direct, } } } /// The import policy to use when generating import statements. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Import { /// Import names without a module prefix. /// /// so for `std::fmt::Debug` it would import `std::fmt::Debug`, and use /// `Debug`. Direct, /// Import names with a module prefix. /// /// so for `std::fmt::Debug` it would import `std::fmt`, and use /// `fmt::Debug`. Prefixed, } #[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] enum Module { /// Local type. Local, /// Type imported directly from module with the specified policy. Module { import: Option<Import>, module: ItemStr, }, /// Prefixed with an alias. Aliased { module: ItemStr, alias: ItemStr }, } impl Module { /// Convert into an aliased import, or keep as same in case that's not /// feasible. fn into_module_aliased<A>(self, alias: A) -> Self where A: Into<ItemStr>, { match self { Self::Module { module, .. } => Self::Aliased { module, alias: alias.into(), }, other => other, } } /// Aliasing a type explicitly means you no longer want to import it by /// module. Set the correct import here. fn into_aliased(self) -> Self { match self { Self::Module { module, .. } => Self::Module { import: Some(Import::Direct), module, }, other => other, } } /// Convert into a prefixed, or keep as same in case that's not feasible. fn into_prefixed(self) -> Self { match self { Self::Module { module, .. } => Self::Module { module, import: Some(Import::Prefixed), }, other => other, } } } /// An imported name in Rust. #[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Type { /// Reference information on the type. reference: Option<Reference>, /// If the type is dynamic. dyn_type: bool, /// How the type is imported. module: Module, /// Name of type. name: ItemStr, /// Arguments of the class. arguments: Vec<Type>, /// Alias to use for the type. alias: Option<ItemStr>, } impl Type { /// Alias the given type as it's imported. /// /// # Examples /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let ty = rust::imported("std::fmt", "Debug").alias("FmtDebug"); /// /// let toks = quote!(#ty); /// /// assert_eq!( /// vec![ /// "use std::fmt::Debug as FmtDebug;", /// "", /// "FmtDebug", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` pub fn alias<A: Into<ItemStr>>(self, alias: A) -> Self { Self { module: self.module.into_aliased(), alias: Some(alias.into()), ..self } } /// Alias the module being imported. /// /// This also implies that the import is [prefixed]. /// /// # Examples /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let ty = rust::imported("std::fmt", "Debug").module_alias("other"); /// /// let toks = quote!(#ty); /// /// assert_eq!( /// vec![ /// "use std::fmt as other;", /// "", /// "other::Debug", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` /// /// [prefixed]: Self::prefixed() pub fn module_alias<A: Into<ItemStr>>(self, alias: A) -> Type { Type { module: self.module.into_module_aliased(alias), ..self } } /// Prefix any use of this type with the corresponding module. /// /// So importing `std::fmt::Debug` will cause the module to be referenced as /// `fmt::Debug` instead of `Debug`. /// /// This is implied if [module_alias()][Self::module_alias()] is used. /// /// # Examples /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let ty = rust::imported("std::fmt", "Debug").prefixed(); /// /// let toks = quote!(#ty); /// /// assert_eq!( /// vec![ /// "use std::fmt;", /// "", /// "fmt::Debug", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` pub fn prefixed(self) -> Type { Type { module: self.module.into_prefixed(), ..self } } /// Add generic arguments to the type. /// /// # Examples /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let ty = rust::imported("std::collections", "HashMap") /// .with_arguments((rust::local("u32"), rust::local("u32"))); /// /// let toks = quote!(#ty); /// /// assert_eq!( /// vec![ /// "use std::collections::HashMap;", /// "", /// "HashMap<u32, u32>", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let dbg = rust::imported("std::collections", "HashMap") /// .prefixed() /// .with_arguments((rust::local("T"), rust::local("U"))); /// /// let toks = quote!(#dbg); /// /// assert_eq!( /// vec![ /// "use std::collections;", /// "", /// "collections::HashMap<T, U>", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` pub fn with_arguments(self, args: impl Args) -> Type { Type { arguments: args.into_args(), ..self } } /// Convert into a reference `&<type>` type. pub fn reference<R: Into<Reference>>(self, reference: R) -> Self { Self { reference: Some(reference.into()), ..self } } /// Convert into a dynamic `dyn <type>` type. pub fn into_dyn(self) -> Self { Self { dyn_type: true, ..self } } /// Write the direct name of the type. fn write_direct(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(alias) = &self.alias { out.write_str(alias) } else { out.write_str(&self.name) } } /// Write the prefixed name of the type. fn write_prefixed(&self, out: &mut fmt::Formatter<'_>, module: &ItemStr) -> fmt::Result { if let Some(module) = module.rsplit("::").next() { out.write_str(module)?; out.write_str(SEP)?; } out.write_str(&self.name)?; Ok(()) } } impl_lang_item! { impl FormatTokens<Rust> for Type; impl From<Type> for LangBox<Rust>; impl LangItem<Rust> for Type { fn format(&self, out: &mut fmt::Formatter<'_>, config: &Config, format: &Format) -> fmt::Result { if let Some(reference) = &self.reference { match reference { Reference::StaticRef => { out.write_str("&'static ")?; } Reference::Named(name) => { out.write_str("&'")?; out.write_str(name.as_ref())?; out.write_str(" ")?; } Reference::Ref => { out.write_str("&")?; } } } if self.dyn_type { out.write_str("dyn ")?; } match &self.module { Module::Local | Module::Module { import: Some(Import::Direct), .. } => { self.write_direct(out)?; } Module::Module { import: Some(Import::Prefixed), module, } => { self.write_prefixed(out, module)?; } Module::Module { import: None, module, } => match &config.default_import { Import::Direct => self.write_direct(out)?, Import::Prefixed => self.write_prefixed(out, module)?, }, Module::Aliased { alias: ref module, .. } => { out.write_str(module)?; out.write_str(SEP)?; out.write_str(&self.name)?; } } if !self.arguments.is_empty() { let mut it = self.arguments.iter().peekable(); out.write_str("<")?; while let Some(n) = it.next() { n.format(out, config, format)?; if it.peek().is_some() { out.write_str(", ")?; } } out.write_str(">")?; } Ok(()) } fn as_import(&self) -> Option<&Self> { Some(self) } } } impl Rust { fn imports(out: &mut Tokens, config: &Config, tokens: &Tokens) { use crate as genco; use crate::quote_in; use std::collections::btree_set; let mut modules = BTreeMap::<&ItemStr, Imported>::new(); let mut queue = VecDeque::new(); for import in tokens.walk_imports() { queue.push_back(import); } while let Some(import) = queue.pop_front() { match &import.module { Module::Local => continue, Module::Module { module, import: Some(Import::Direct), } => { let module = modules.entry(module).or_default(); module.names.insert((&import.name, import.alias.as_ref())); } Module::Module { module, import: Some(Import::Prefixed), } => { let module = modules.entry(module).or_default(); module.self_import = true; } Module::Module { module, import: None, } => match config.default_import { Import::Direct => { let module = modules.entry(module).or_default(); module.names.insert((&import.name, import.alias.as_ref())); } Import::Prefixed => { let module = modules.entry(module).or_default(); module.self_import = true; } }, Module::Aliased { module, alias } => { let module = modules.entry(module).or_default(); module.self_aliases.insert(alias); } } for arg in &import.arguments { queue.push_back(arg); } } let mut has_any = false; for (m, module) in modules { let mut render = module.iter(); if let Some(first) = render.next() { has_any = true; out.push(); // render as a group if there's more than one thing being // imported. if let Some(second) = render.next() { quote_in! { *out => use #m::{#( o => first.render(o); quote_in!(*o => , #(o => second.render(o))); for item in render { quote_in!(*o => , #(o => item.render(o))); } )}; }; } else { match first { RenderItem::SelfImport => { quote_in!(*out => use #m;); } RenderItem::SelfAlias { alias } => { quote_in!(*out => use #m as #alias;); } RenderItem::Name { name, alias: Some(alias), } => { quote_in!(*out => use #m::#name as #alias;); } RenderItem::Name { name, alias: None } => { quote_in!(*out => use #m::#name;); } } } } } if has_any { out.line(); } return; /// An imported module. #[derive(Debug, Default)] struct Imported<'a> { /// If we need the module (e.g. through an alias). self_import: bool, /// Aliases for the own module. self_aliases: BTreeSet<&'a ItemStr>, /// Set of imported names. names: BTreeSet<(&'a ItemStr, Option<&'a ItemStr>)>, } impl<'a> Imported<'a> { fn iter(self) -> ImportedIter<'a> { ImportedIter { self_import: self.self_import, self_aliases: self.self_aliases.into_iter(), names: self.names.into_iter(), } } } struct ImportedIter<'a> { self_import: bool, self_aliases: btree_set::IntoIter<&'a ItemStr>, names: btree_set::IntoIter<(&'a ItemStr, Option<&'a ItemStr>)>, } impl<'a> Iterator for ImportedIter<'a> { type Item = RenderItem<'a>; fn next(&mut self) -> Option<Self::Item> { if std::mem::take(&mut self.self_import) { return Some(RenderItem::SelfImport); } if let Some(alias) = self.self_aliases.next() { return Some(RenderItem::SelfAlias { alias }); } if let Some((name, alias)) = self.names.next() { return Some(RenderItem::Name { name, alias }); } None } } #[derive(Clone, Copy)] enum RenderItem<'a> { SelfImport, SelfAlias { alias: &'a ItemStr, }, Name { name: &'a ItemStr, alias: Option<&'a ItemStr>, }, } impl RenderItem<'_> { fn render(self, out: &mut Tokens) { match self { Self::SelfImport => { quote_in!(*out => self); } Self::SelfAlias { alias } => { quote_in!(*out => self as #alias); } Self::Name { name, alias: Some(alias), } => { quote_in!(*out => #name as #alias); } Self::Name { name, alias: None } => { quote_in!(*out => #name); } } } } } } /// Language specialization for Rust. pub struct Rust(()); impl Lang for Rust { type Config = Config; type Format = Format; type Import = Type; fn quote_string(out: &mut fmt::Formatter<'_>, input: &str) -> fmt::Result { out.write_char('"')?; for c in input.chars() { match c { '\t' => out.write_str("\\t")?, '\n' => out.write_str("\\n")?, '\r' => out.write_str("\\r")?, '\'' => out.write_str("\\'")?, '"' => out.write_str("\\\"")?, '\\' => out.write_str("\\\\")?, c => out.write_char(c)?, }; } out.write_char('"')?; Ok(()) } fn format_file( tokens: &Tokens, out: &mut fmt::Formatter<'_>, config: &Self::Config, ) -> fmt::Result { let mut imports: Tokens = Tokens::new(); Self::imports(&mut imports, config, tokens); let format = Format::default(); imports.format(out, config, &format)?; tokens.format(out, config, &format)?; Ok(()) } } /// Setup an imported element. /// /// # Examples /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let a = rust::imported("std::fmt", "Debug").prefixed(); /// let b = rust::imported("std::fmt", "Debug").module_alias("fmt2"); /// let c = rust::imported("std::fmt", "Debug"); /// let d = rust::imported("std::fmt", "Debug").alias("FmtDebug"); /// /// let toks = quote!{ /// #a /// #b /// #c /// #d /// }; /// /// assert_eq!( /// vec![ /// "use std::fmt::{self, self as fmt2, Debug, Debug as FmtDebug};", /// "", /// "fmt::Debug", /// "fmt2::Debug", /// "Debug", /// "FmtDebug", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` /// /// # Example with an alias /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let ty = rust::imported("std::fmt", "Debug").alias("FmtDebug"); /// /// let toks = quote!{ /// #ty /// }; /// /// assert_eq!( /// vec![ /// "use std::fmt::Debug as FmtDebug;", /// "", /// "FmtDebug", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` /// /// # Example with a module alias /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let ty = rust::imported("std::fmt", "Debug").module_alias("fmt2"); /// /// let toks = quote!{ /// #ty /// }; /// /// assert_eq!( /// vec![ /// "use std::fmt as fmt2;", /// "", /// "fmt2::Debug", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` /// /// # Example with multiple aliases /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let a = rust::imported("std::fmt", "Debug").alias("FmtDebug"); /// let b = rust::imported("std::fmt", "Debug").alias("FmtDebug2"); /// /// let toks = quote!{ /// #a /// #b /// }; /// /// assert_eq!( /// vec![ /// "use std::fmt::{Debug as FmtDebug, Debug as FmtDebug2};", /// "", /// "FmtDebug", /// "FmtDebug2", /// ], /// toks.to_file_vec()? /// ); /// # Ok(()) /// # } /// ``` pub fn imported<M, N>(module: M, name: N) -> Type where M: Into<ItemStr>, N: Into<ItemStr>, { Type { reference: None, dyn_type: false, module: Module::Module { import: None, module: module.into(), }, name: name.into(), arguments: vec![], alias: None, } } /// Setup a local element. /// /// Local elements do not generate an import statement when added to a file. /// /// # Examples /// /// ```rust /// use genco::prelude::*; /// /// # fn main() -> genco::fmt::Result { /// let toks = quote!(#(rust::local("MyType"))); /// assert_eq!(vec!["MyType"], toks.to_file_vec()?); /// # Ok(()) /// # } /// ``` pub fn local<N>(name: N) -> Type where N: Into<ItemStr>, { Type { module: Module::Local, reference: None, dyn_type: false, name: name.into(), arguments: vec![], alias: None, } } /// Helper function to construct a constant local type. /// /// # Examples /// /// ```rust /// use genco::prelude::*; /// /// const MY_TYPE: rust::Type = rust::const_local("MyType"); /// ``` pub const fn const_local(name: &'static str) -> Type { Type { module: Module::Local, reference: None, dyn_type: false, name: ItemStr::Static(name), arguments: Vec::new(), alias: None, } }