genco/tokens/tokens.rs
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 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
//! A set of tokens that make up a single source-file.
//!
//! ## Example
//!
//! ```rust
//! use genco::prelude::*;
//!
//! let mut toks = java::Tokens::new();
//! toks.append("foo");
//! ```
#![allow(clippy::module_inception)]
use core::cmp;
use core::iter::FromIterator;
use core::mem;
use core::slice;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::{self, Vec};
use crate::fmt;
use crate::lang::{Lang, LangSupportsEval};
use crate::tokens::{FormatInto, Item, Register};
/// A stream of tokens.
///
/// # Structural Guarantees
///
/// This stream of tokens provides the following structural guarantees.
///
/// * Only one [`space`] occurs in sequence and indicates spacing between
/// tokens.
/// * Only one [`push`] occurs in sequence and indicates that the next token
/// should be spaced onto a new line.
/// * A [`line`] is never by a [`push`] since it would have no effect. A line
/// ensures an empty line between two tokens.
///
/// ```
/// use genco::Tokens;
/// use genco::tokens::Item;
///
/// let mut tokens = Tokens::<()>::new();
///
/// // The first push token is "overriden" by a line.
/// tokens.space();
/// tokens.space();
///
/// assert_eq!(vec![Item::Space::<()>], tokens);
///
/// let mut tokens = Tokens::<()>::new();
///
/// tokens.space();
/// tokens.push();
/// tokens.push();
///
/// assert_eq!(vec![Item::Push::<()>], tokens);
///
/// let mut tokens = Tokens::<()>::new();
///
/// // The first space and push tokens are "overriden" by a line.
/// tokens.space();
/// tokens.push();
/// tokens.line();
///
/// assert_eq!(vec![Item::Line::<()>], tokens);
/// ```
///
/// [`space`]: Self::space
/// [`push`]: Self::push
/// [`line`]: Self::line
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tokens<L = ()>
where
L: Lang,
{
items: Vec<Item<L>>,
/// The last position at which we observed a language item.
///
/// This references the `position + 1` in the items vector. A position of
/// 0 means that there are no more items.
///
/// This makes up a singly-linked list over all language items that you can
/// follow.
last_lang_item: usize,
}
impl<L> Tokens<L>
where
L: Lang,
{
/// Create a new empty stream of tokens.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let tokens = Tokens::<()>::new();
///
/// assert!(tokens.is_empty());
/// ```
pub fn new() -> Self {
Tokens {
items: Vec::new(),
last_lang_item: 0,
}
}
/// Create a new empty stream of tokens with the specified capacity.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let tokens = Tokens::<()>::with_capacity(10);
///
/// assert!(tokens.is_empty());
/// ```
pub fn with_capacity(cap: usize) -> Self {
Tokens {
items: Vec::with_capacity(cap),
last_lang_item: 0,
}
}
/// Construct an iterator over the token stream.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
/// use genco::tokens::{ItemStr, Item};
///
/// let tokens: Tokens<()> = quote!(foo bar baz);
/// let mut it = tokens.iter();
///
/// assert_eq!(Some(&Item::Literal(ItemStr::Static("foo"))), it.next());
/// assert_eq!(Some(&Item::Space), it.next());
/// assert_eq!(Some(&Item::Literal(ItemStr::Static("bar"))), it.next());
/// assert_eq!(Some(&Item::Space), it.next());
/// assert_eq!(Some(&Item::Literal(ItemStr::Static("baz"))), it.next());
/// assert_eq!(None, it.next());
/// ```
pub fn iter(&self) -> Iter<'_, L> {
Iter {
iter: self.items.iter(),
}
}
/// Append the given tokens.
///
/// This append function takes anything implementing [FormatInto] making the
/// argument's behavior customizable. Most primitive types have built-in
/// implementations of [FormatInto] treating them as raw tokens.
///
/// Most notabley, things implementing [FormatInto] can be used as arguments
/// for [interpolation] in the [quote!] macro.
///
/// [quote!]: macro.quote.html
/// [interpolation]: macro.quote.html#interpolation
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let mut tokens = Tokens::<()>::new();
/// tokens.append(4u32);
///
/// assert_eq!(quote!($(4u32)), tokens);
/// ```
pub fn append<T>(&mut self, tokens: T)
where
T: FormatInto<L>,
{
tokens.format_into(self)
}
/// Extend with another stream of tokens.
///
/// This respects the structural requirements of adding one element at a
/// time, like you would get by calling [`space`], [`push`], or [`line`].
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
/// use genco::tokens::{Item, ItemStr};
///
/// let mut tokens: Tokens<()> = quote!(foo bar);
/// tokens.extend::<Tokens<()>>(quote!($[' ']baz));
///
/// assert_eq!(tokens, quote!(foo bar baz));
/// ```
///
/// [`space`]: Self::space
/// [`push`]: Self::push
/// [`line`]: Self::line
pub fn extend<I>(&mut self, it: I)
where
I: IntoIterator<Item = Item<L>>,
{
let it = it.into_iter();
let (low, high) = it.size_hint();
self.items.reserve(high.unwrap_or(low));
for item in it {
self.item(item);
}
}
/// Walk over all imports.
///
/// The order in which the imports are returned is *not* defined. So if you
/// need them in some particular order you need to sort them.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let debug = rust::import("std::fmt", "Debug");
/// let ty = rust::import("std::collections", "HashMap");
///
/// let tokens = quote!(foo $ty<u32, dyn $debug> baz);
///
/// for import in tokens.walk_imports() {
/// println!("{:?}", import);
/// }
/// ```
pub fn walk_imports(&self) -> WalkImports<'_, L> {
WalkImports {
items: &self.items,
pos: self.last_lang_item,
}
}
/// Add an registered custom element that is _not_ rendered.
///
/// Registration can be used to generate imports that do not render a
/// visible result.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let write_bytes_ext = rust::import("byteorder", "WriteBytesExt").with_alias("_");
///
/// let tokens = quote!($(register(write_bytes_ext)));
///
/// assert_eq!("use byteorder::WriteBytesExt as _;\n", tokens.to_file_string()?);
/// # Ok::<_, genco::fmt::Error>(())
/// ```
///
/// [quote!]: macro.quote.html
pub fn register<T>(&mut self, tokens: T)
where
T: Register<L>,
{
tokens.register(self);
}
/// Check if tokens contain no items.
///
/// ```
/// use genco::prelude::*;
///
/// let tokens: Tokens<()> = quote!();
///
/// assert!(tokens.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
/// Add a single spacing to the token stream.
///
/// Note that due to structural guarantees two consequent spaces may not
/// follow each other in the same token stream.
///
/// A space operation has no effect unless it's followed by a non-whitespace
/// token.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let mut tokens = Tokens::<()>::new();
///
/// tokens.space();
/// tokens.append("hello");
/// tokens.space();
/// tokens.space(); // Note: ignored
/// tokens.append("world");
/// tokens.space();
///
/// assert_eq!(
/// vec![
/// " hello world",
/// ],
/// tokens.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn space(&mut self) {
if let Some(Item::Space) = self.items.last() {
return;
}
self.items.push(Item::Space);
}
/// Add a single push operation.
///
/// Push operations ensure that any following tokens are added to their own
/// line.
///
/// A push has no effect unless it's *preceeded* or *followed* by
/// non-whitespace tokens.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let mut tokens = Tokens::<()>::new();
///
/// tokens.push();
/// tokens.append("hello");
/// tokens.push();
/// tokens.append("world");
/// tokens.push();
///
/// assert_eq!(
/// vec![
/// "hello",
/// "world"
/// ],
/// tokens.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn push(&mut self) {
let item = loop {
match self.items.pop() {
// NB: never reconfigure a line into a push.
Some(Item::Line) => {
self.items.push(Item::Line);
return;
}
Some(Item::Space | Item::Push) => continue,
item => break item,
}
};
self.items.extend(item);
self.items.push(Item::Push);
}
/// Add a single line operation.
///
/// A line ensures that any following tokens have one line of separation
/// between them and the preceeding tokens.
///
/// A line has no effect unless it's *preceeded* and *followed* by
/// non-whitespace tokens.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let mut tokens = Tokens::<()>::new();
///
/// tokens.line();
/// tokens.append("hello");
/// tokens.line();
/// tokens.append("world");
/// tokens.line();
///
/// assert_eq!(
/// vec![
/// "hello",
/// "",
/// "world"
/// ],
/// tokens.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn line(&mut self) {
let item = loop {
match self.items.pop() {
Some(Item::Line) | Some(Item::Push) => continue,
item => break item,
}
};
self.items.extend(item);
self.items.push(Item::Line);
}
/// Increase the indentation of the token stream.
///
/// An indentation is a language-specific operation which adds whitespace to
/// the beginning of a line preceeding any non-whitespace tokens.
///
/// An indentation has no effect unless it's *followed* by non-whitespace
/// tokens. It also acts like a [`push`], in that it will shift any tokens to
/// a new line.
///
/// [`push`]: Self::push
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let mut tokens = Tokens::<()>::new();
///
/// tokens.indent();
/// tokens.append("hello");
/// tokens.indent();
/// tokens.append("world");
/// tokens.indent();
/// tokens.append("😀");
///
/// assert_eq!(
/// vec![
/// " hello",
/// " world",
/// " 😀",
/// ],
/// tokens.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn indent(&mut self) {
self.indentation(1);
}
/// Decrease the indentation of the token stream.
///
/// An indentation is a language-specific operation which adds whitespace to
/// the beginning of a line preceeding any non-whitespace tokens.
///
/// An indentation has no effect unless it's *followed* by non-whitespace
/// tokens. It also acts like a [`push`], in that it will shift any tokens to
/// a new line.
///
/// Indentation can never go below zero, and will just be ignored if that
/// were to happen. However, negative indentation is stored in the token
/// stream, so any negative indentation in place will have to be countered
/// before indentation starts again.
///
/// [`push`]: Self::push
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let mut tokens = Tokens::<()>::new();
///
/// tokens.indent();
/// tokens.append("hello");
/// tokens.unindent();
/// tokens.append("world");
/// tokens.unindent();
/// tokens.append("😀");
/// tokens.indent();
/// tokens.append("😁");
/// tokens.indent();
/// tokens.append("😂");
///
/// assert_eq!(
/// vec![
/// " hello",
/// "world",
/// "😀",
/// "😁",
/// " 😂",
/// ],
/// tokens.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn unindent(&mut self) {
self.indentation(-1);
}
/// Formatting function for token streams that gives full control over the
/// formatting environment.
///
/// The configurations and `format` arguments will be provided to all
/// registered language items as well, and can be used to customize
/// formatting through [LangItem::format()].
///
/// The `format` argument is primarily used internally by
/// [Lang::format_file] to provide intermediate state that can be affect how
/// language items are formatter. So formatting something as a file might
/// yield different results than using this raw formatting function.
///
/// Available formatters:
///
/// * [fmt::VecWriter] - To write result into a vector.
/// * [fmt::FmtWriter] - To write the result into something implementing
/// [fmt::Write][std::fmt::Write].
/// * [fmt::IoWriter]- To write the result into something implementing
/// [io::Write][std::io::Write].
///
/// # Examples
///
/// ```,no_run
/// use genco::prelude::*;
/// use genco::fmt;
///
/// let map = rust::import("std::collections", "HashMap");
///
/// let tokens: rust::Tokens = quote! {
/// let mut m = $map::new();
/// m.insert(1u32, 2u32);
/// };
///
/// let stdout = std::io::stdout();
/// let mut w = fmt::IoWriter::new(stdout.lock());
///
/// let fmt = fmt::Config::from_lang::<Rust>()
/// .with_indentation(fmt::Indentation::Space(2));
/// let mut formatter = w.as_formatter(&fmt);
/// let config = rust::Config::default();
///
/// // Default format state for Rust.
/// let format = rust::Format::default();
///
/// tokens.format(&mut formatter, &config, &format)?;
/// # Ok::<_, genco::fmt::Error>(())
/// ```
///
/// [LangItem::format()]: crate::lang::LangItem::format()
pub fn format(
&self,
out: &mut fmt::Formatter<'_>,
config: &L::Config,
format: &L::Format,
) -> fmt::Result {
out.format_items(&self.items, config, format)
}
/// Push a single item to the stream while checking for structural
/// guarantees.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
/// use genco::tokens::{Item, ItemStr};
///
/// let mut tokens = Tokens::<()>::new();
///
/// tokens.append(ItemStr::Static("foo"));
/// tokens.space();
/// tokens.space(); // Note: second space ignored
/// tokens.append(ItemStr::Static("bar"));
///
/// assert_eq!(tokens, quote!(foo bar));
/// ```
pub(crate) fn item(&mut self, item: Item<L>) {
match item {
Item::Push => self.push(),
Item::Line => self.line(),
Item::Space => self.space(),
Item::Indentation(n) => self.indentation(n),
Item::Lang(_, item) => self.lang_item(item),
Item::Register(_, item) => self.lang_item_register(item),
other => self.items.push(other),
}
}
/// Add a language item directly.
pub(crate) fn lang_item(&mut self, item: Box<L::Item>) {
// NB: recorded position needs to be adjusted.
self.items
.push(crate::tokens::Item::Lang(self.last_lang_item, item));
self.last_lang_item = self.items.len();
}
/// Register a language item directly.
pub(crate) fn lang_item_register(&mut self, item: Box<L::Item>) {
// NB: recorded position needs to be adjusted.
self.items
.push(crate::tokens::Item::Register(self.last_lang_item, item));
self.last_lang_item = self.items.len();
}
/// File formatting function for token streams that gives full control over the
/// formatting environment.
///
/// File formatting will render preambles like namespace declarations and
/// imports.
///
/// Available formatters:
///
/// * [fmt::VecWriter] - To write result into a vector.
/// * [fmt::FmtWriter] - To write the result into something implementing
/// [fmt::Write][std::fmt::Write].
/// * [fmt::IoWriter]- To write the result into something implementing
/// [io::Write][std::io::Write].
///
/// # Examples
///
/// ```,no_run
/// use genco::prelude::*;
/// use genco::fmt;
///
/// let map = rust::import("std::collections", "HashMap");
///
/// let tokens: rust::Tokens = quote! {
/// let mut m = $map::new();
/// m.insert(1u32, 2u32);
/// };
///
/// let stdout = std::io::stdout();
/// let mut w = fmt::IoWriter::new(stdout.lock());
///
/// let fmt = fmt::Config::from_lang::<Rust>()
/// .with_indentation(fmt::Indentation::Space(2));
/// let mut formatter = w.as_formatter(&fmt);
/// let config = rust::Config::default();
///
/// tokens.format_file(&mut formatter, &config)?;
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn format_file(&self, out: &mut fmt::Formatter<'_>, config: &L::Config) -> fmt::Result {
L::format_file(self, out, config)?;
out.write_trailing_line()?;
Ok(())
}
/// Internal function to modify the indentation of the token stream.
fn indentation(&mut self, mut n: i16) {
let item = loop {
// flush all whitespace preceeding the indentation change.
match self.items.pop() {
Some(Item::Push) => continue,
Some(Item::Space) => continue,
Some(Item::Line) => continue,
Some(Item::Indentation(u)) => n += u,
item => break item,
}
};
self.items.extend(item);
if n != 0 {
self.items.push(Item::Indentation(n));
}
}
}
impl<L> Default for Tokens<L>
where
L: Lang,
{
fn default() -> Self {
Self::new()
}
}
impl<L> Tokens<L>
where
L: LangSupportsEval,
{
/// Helper function to determine if the token stream supports evaluation at compile time.
#[doc(hidden)]
#[inline]
pub fn lang_supports_eval(&self) {}
}
impl<L> Tokens<L>
where
L: Lang,
L::Config: Default,
{
/// Format the token stream as a file for the given target language to a
/// string using the default configuration.
///
/// This is a shorthand to using [FmtWriter][fmt::FmtWriter] directly in
/// combination with [format][Self::format_file].
///
/// This function will render imports.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
/// use genco::fmt;
///
/// let map = rust::import("std::collections", "HashMap");
///
/// let tokens: rust::Tokens = quote! {
/// let mut m = $map::new();
/// m.insert(1u32, 2u32);
/// };
///
/// assert_eq!(
/// "use std::collections::HashMap;\n\nlet mut m = HashMap::new();\nm.insert(1u32, 2u32);\n",
/// tokens.to_file_string()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn to_file_string(&self) -> fmt::Result<String> {
let mut w = fmt::FmtWriter::new(String::new());
let fmt = fmt::Config::from_lang::<L>();
let mut formatter = w.as_formatter(&fmt);
let config = L::Config::default();
self.format_file(&mut formatter, &config)?;
Ok(w.into_inner())
}
/// Format only the current token stream as a string using the default
/// configuration.
///
/// This is a shorthand to using [FmtWriter][fmt::FmtWriter] directly in
/// combination with [format][Self::format].
///
/// This function _will not_ render imports.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let map = rust::import("std::collections", "HashMap");
///
/// let tokens: rust::Tokens = quote! {
/// let mut m = $map::new();
/// m.insert(1u32, 2u32);
/// };
///
/// assert_eq!(
/// "let mut m = HashMap::new();\nm.insert(1u32, 2u32);",
/// tokens.to_string()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn to_string(&self) -> fmt::Result<String> {
let mut w = fmt::FmtWriter::new(String::new());
let fmt = fmt::Config::from_lang::<L>();
let mut formatter = w.as_formatter(&fmt);
let config = L::Config::default();
let format = L::Format::default();
self.format(&mut formatter, &config, &format)?;
Ok(w.into_inner())
}
/// Format tokens into a vector, where each entry equals a line in the
/// resulting file using the default configuration.
///
/// This is a shorthand to using [VecWriter][fmt::VecWriter] directly in
/// combination with [format][Self::format_file].
///
/// This function will render imports.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let map = rust::import("std::collections", "HashMap");
///
/// let tokens: rust::Tokens = quote! {
/// let mut m = $map::new();
/// m.insert(1u32, 2u32);
/// };
///
/// assert_eq!(
/// vec![
/// "use std::collections::HashMap;",
/// "",
/// "let mut m = HashMap::new();",
/// "m.insert(1u32, 2u32);"
/// ],
/// tokens.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
///
/// # Example with Python indentation
///
/// ```
/// use genco::prelude::*;
///
/// let tokens: python::Tokens = quote! {
/// def foo():
/// pass
///
/// def bar():
/// pass
/// };
///
/// assert_eq!(
/// vec![
/// "def foo():",
/// " pass",
/// "",
/// "def bar():",
/// " pass",
/// ],
/// tokens.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn to_file_vec(&self) -> fmt::Result<Vec<String>> {
let mut w = fmt::VecWriter::new();
let fmt = fmt::Config::from_lang::<L>();
let mut formatter = w.as_formatter(&fmt);
let config = L::Config::default();
self.format_file(&mut formatter, &config)?;
Ok(w.into_vec())
}
/// Helper function to format tokens into a vector, where each entry equals
/// a line using the default configuration.
///
/// This is a shorthand to using [VecWriter][fmt::VecWriter] directly in
/// combination with [format][Self::format].
///
/// This function _will not_ render imports.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let map = rust::import("std::collections", "HashMap");
///
/// let tokens: rust::Tokens = quote! {
/// let mut m = $map::new();
/// m.insert(1u32, 2u32);
/// };
///
/// assert_eq!(
/// vec![
/// "let mut m = HashMap::new();",
/// "m.insert(1u32, 2u32);"
/// ],
/// tokens.to_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn to_vec(&self) -> fmt::Result<Vec<String>> {
let mut w = fmt::VecWriter::new();
let fmt = fmt::Config::from_lang::<L>();
let mut formatter = w.as_formatter(&fmt);
let config = L::Config::default();
let format = L::Format::default();
self.format(&mut formatter, &config, &format)?;
Ok(w.into_vec())
}
}
impl<L> cmp::PartialEq<Vec<Item<L>>> for Tokens<L>
where
L: Lang,
{
#[inline]
fn eq(&self, other: &Vec<Item<L>>) -> bool {
self.items == *other
}
}
impl<L> cmp::PartialEq<Tokens<L>> for Vec<Item<L>>
where
L: Lang,
{
fn eq(&self, other: &Tokens<L>) -> bool {
*self == other.items
}
}
impl<L> cmp::PartialEq<[Item<L>]> for Tokens<L>
where
L: Lang,
{
fn eq(&self, other: &[Item<L>]) -> bool {
&*self.items == other
}
}
impl<L> cmp::PartialEq<Tokens<L>> for [Item<L>]
where
L: Lang,
{
fn eq(&self, other: &Tokens<L>) -> bool {
self == &*other.items
}
}
/// Iterator over [Tokens].
///
/// This is created using [Tokens::into_iter()].
pub struct IntoIter<L>
where
L: Lang,
{
iter: vec::IntoIter<Item<L>>,
}
impl<L> Iterator for IntoIter<L>
where
L: Lang,
{
type Item = Item<L>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
/// Construct an owned iterator over the token stream.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
/// use genco::tokens::{ItemStr, Item};
///
/// let tokens: Tokens<()> = quote!(foo bar baz);
/// let mut it = tokens.into_iter();
///
/// assert_eq!(Some(Item::Literal(ItemStr::Static("foo"))), it.next());
/// assert_eq!(Some(Item::Space), it.next());
/// assert_eq!(Some(Item::Literal(ItemStr::Static("bar"))), it.next());
/// assert_eq!(Some(Item::Space), it.next());
/// assert_eq!(Some(Item::Literal(ItemStr::Static("baz"))), it.next());
/// assert_eq!(None, it.next());
/// ```
impl<L> IntoIterator for Tokens<L>
where
L: Lang,
{
type Item = Item<L>;
type IntoIter = IntoIter<L>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
iter: self.items.into_iter(),
}
}
}
/// Iterator over [Tokens].
///
/// This is created using [Tokens::iter()].
pub struct Iter<'a, L>
where
L: Lang,
{
iter: slice::Iter<'a, Item<L>>,
}
impl<'a, L> Iterator for Iter<'a, L>
where
L: Lang,
{
type Item = &'a Item<L>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, L> IntoIterator for &'a Tokens<L>
where
L: Lang,
{
type Item = &'a Item<L>;
type IntoIter = Iter<'a, L>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, L> FromIterator<&'a Item<L>> for Tokens<L>
where
L: Lang,
{
fn from_iter<I: IntoIterator<Item = &'a Item<L>>>(iter: I) -> Self {
let it = iter.into_iter();
let (low, high) = it.size_hint();
let mut tokens = Self::with_capacity(high.unwrap_or(low));
tokens.extend(it.cloned());
tokens
}
}
impl<L> FromIterator<Item<L>> for Tokens<L>
where
L: Lang,
{
fn from_iter<I: IntoIterator<Item = Item<L>>>(iter: I) -> Self {
let it = iter.into_iter();
let (low, high) = it.size_hint();
let mut tokens = Self::with_capacity(high.unwrap_or(low));
tokens.extend(it);
tokens
}
}
/// An iterator over language-specific imported items.
///
/// Constructed using the [Tokens::walk_imports] method.
pub struct WalkImports<'a, L>
where
L: Lang,
{
items: &'a [Item<L>],
pos: usize,
}
impl<'a, L> Iterator for WalkImports<'a, L>
where
L: Lang,
{
type Item = &'a L::Item;
fn next(&mut self) -> Option<Self::Item> {
let pos = mem::take(&mut self.pos);
if pos == 0 {
return None;
}
// NB: recorded position needs to be adjusted.
let item = self.items.get(pos - 1)?;
let (prev, item) = match item {
Item::Lang(prev, item) => (prev, item),
Item::Register(prev, item) => (prev, item),
_ => return None,
};
self.pos = *prev;
Some(item)
}
}
#[cfg(test)]
mod tests {
use core::fmt::Write as _;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use crate as genco;
use crate::fmt;
use crate::{quote, Tokens};
/// Own little custom language for this test.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Import(u32);
impl_lang! {
Lang {
type Config = ();
type Format = ();
type Item = Import;
}
Import {
fn format(&self, out: &mut fmt::Formatter<'_>, _: &(), _: &()) -> fmt::Result {
write!(out, "{}", self.0)
}
}
}
#[test]
fn test_walk_custom() {
let toks: Tokens<Lang> = quote! {
1:1 $(Import(1)) 1:2
bar
2:1 2:2 $(quote!(3:1 3:2)) $(Import(2))
$(String::from("nope"))
};
let mut output: Vec<_> = toks.walk_imports().cloned().collect();
output.sort();
let expected = vec![Import(1), Import(2)];
assert_eq!(expected, output);
}
}