for TokenTree {
635 fn from(g: Literal) -> Self {
636 TokenTree::Literal(g)
637 }
638 }
639
640 /// Prints the token tree as a string that is supposed to be losslessly
641 /// convertible back into the same token tree (modulo spans), except for
642 /// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
643 /// numeric literals.
644 impl Display for TokenTree {
645 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646 match self {
647 TokenTree::Group(t) => Display::fmt(t, f),
648 TokenTree::Ident(t) => Display::fmt(t, f),
649 TokenTree::Punct(t) => Display::fmt(t, f),
650 TokenTree::Literal(t) => Display::fmt(t, f),
651 }
652 }
653 }
654
655 /// Prints token tree in a form convenient for debugging.
656 impl Debug for TokenTree {
657 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
658 // Each of these has the name in the struct type in the derived debug,
659 // so don't bother with an extra layer of indirection
660 match self {
661 TokenTree::Group(t) => Debug::fmt(t, f),
662 TokenTree::Ident(t) => {
663 let mut debug = f.debug_struct("Ident");
664 debug.field("sym", &format_args!("{}", t));
665 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
666 debug.finish()
667 }
668 TokenTree::Punct(t) => Debug::fmt(t, f),
669 TokenTree::Literal(t) => Debug::fmt(t, f),
670 }
671 }
672 }
673
674 /// A delimited token stream.
675 ///
676 /// A `Group` internally contains a `TokenStream` which is surrounded by
677 /// `Delimiter`s.
678 #[derive(Clone)]
679 pub struct Group {
680 inner: imp::Group,
681 }
682
683 /// Describes how a sequence of token trees is delimited.
684 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
685 pub enum Delimiter {
686 /// `( ... )`
687 Parenthesis,
688 /// `{ ... }`
689 Brace,
690 /// `[ ... ]`
691 Bracket,
692 /// `∅ ... ∅`
693 ///
694 /// An invisible delimiter, that may, for example, appear around tokens
695 /// coming from a "macro variable" `$var`. It is important to preserve
696 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
697 /// Invisible delimiters may not survive roundtrip of a token stream through
698 /// a string.
699 ///
700 ///
701 ///
702 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
703 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
704 /// of a proc_macro macro are preserved, and only in very specific circumstances.
705 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
706 /// operator priorities as indicated above. The other `Delimiter` variants should be used
707 /// instead in this context. This is a rustc bug. For details, see
708 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
709 ///
710 ///
711 None,
712 }
713
714 impl Group {
715 fn _new(inner: imp::Group) -> Self {
716 Group { inner }
717 }
718
719 fn _new_fallback(inner: fallback::Group) -> Self {
720 Group {
721 inner: imp::Group::from(inner),
722 }
723 }
724
725 /// Creates a new `Group` with the given delimiter and token stream.
726 ///
727 /// This constructor will set the span for this group to
728 /// `Span::call_site()`. To change the span you can use the `set_span`
729 /// method below.
730 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
731 Group {
732 inner: imp::Group::new(delimiter, stream.inner),
733 }
734 }
735
736 /// Returns the punctuation used as the delimiter for this group: a set of
737 /// parentheses, square brackets, or curly braces.
738 pub fn delimiter(&self) -> Delimiter {
739 self.inner.delimiter()
740 }
741
742 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
743 ///
744 /// Note that the returned token stream does not include the delimiter
745 /// returned above.
746 pub fn stream(&self) -> TokenStream {
747 TokenStream::_new(self.inner.stream())
748 }
749
750 /// Returns the span for the delimiters of this token stream, spanning the
751 /// entire `Group`.
752 ///
753 /// ```text
754 /// pub fn span(&self) -> Span {
755 /// ^^^^^^^
756 /// ```
757 pub fn span(&self) -> Span {
758 Span::_new(self.inner.span())
759 }
760
761 /// Returns the span pointing to the opening delimiter of this group.
762 ///
763 /// ```text
764 /// pub fn span_open(&self) -> Span {
765 /// ^
766 /// ```
767 pub fn span_open(&self) -> Span {
768 Span::_new(self.inner.span_open())
769 }
770
771 /// Returns the span pointing to the closing delimiter of this group.
772 ///
773 /// ```text
774 /// pub fn span_close(&self) -> Span {
775 /// ^
776 /// ```
777 pub fn span_close(&self) -> Span {
778 Span::_new(self.inner.span_close())
779 }
780
781 /// Returns an object that holds this group's `span_open()` and
782 /// `span_close()` together (in a more compact representation than holding
783 /// those 2 spans individually).
784 pub fn delim_span(&self) -> DelimSpan {
785 DelimSpan::new(&self.inner)
786 }
787
788 /// Configures the span for this `Group`'s delimiters, but not its internal
789 /// tokens.
790 ///
791 /// This method will **not** set the span of all the internal tokens spanned
792 /// by this group, but rather it will only set the span of the delimiter
793 /// tokens at the level of the `Group`.
794 pub fn set_span(&mut self, span: Span) {
795 self.inner.set_span(span.inner);
796 }
797 }
798
799 /// Prints the group as a string that should be losslessly convertible back
800 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
801 /// with `Delimiter::None` delimiters.
802 impl Display for Group {
803 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
804 Display::fmt(&self.inner, formatter)
805 }
806 }
807
808 impl Debug for Group {
809 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
810 Debug::fmt(&self.inner, formatter)
811 }
812 }
813
814 /// A `Punct` is a single punctuation character like `+`, `-` or `#`.
815 ///
816 /// Multicharacter operators like `+=` are represented as two instances of
817 /// `Punct` with different forms of `Spacing` returned.
818 #[derive(Clone)]
819 pub struct Punct {
820 ch: char,
821 spacing: Spacing,
822 span: Span,
823 }
824
825 /// Whether a `Punct` is followed immediately by another `Punct` or followed by
826 /// another token or whitespace.
827 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
828 pub enum Spacing {
829 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
830 Alone,
831 /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
832 ///
833 /// Additionally, single quote `'` can join with identifiers to form
834 /// lifetimes `'ident`.
835 Joint,
836 }
837
838 impl Punct {
839 /// Creates a new `Punct` from the given character and spacing.
840 ///
841 /// The `ch` argument must be a valid punctuation character permitted by the
842 /// language, otherwise the function will panic.
843 ///
844 /// The returned `Punct` will have the default span of `Span::call_site()`
845 /// which can be further configured with the `set_span` method below.
846 pub fn new(ch: char, spacing: Spacing) -> Self {
847 if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'
848 | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch
849 {
850 Punct {
851 ch,
852 spacing,
853 span: Span::call_site(),
854 }
855 } else {
856 panic!("unsupported proc macro punctuation character {:?}", ch);
857 }
858 }
859
860 /// Returns the value of this punctuation character as `char`.
861 pub fn as_char(&self) -> char {
862 self.ch
863 }
864
865 /// Returns the spacing of this punctuation character, indicating whether
866 /// it's immediately followed by another `Punct` in the token stream, so
867 /// they can potentially be combined into a multicharacter operator
868 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
869 /// so the operator has certainly ended.
870 pub fn spacing(&self) -> Spacing {
871 self.spacing
872 }
873
874 /// Returns the span for this punctuation character.
875 pub fn span(&self) -> Span {
876 self.span
877 }
878
879 /// Configure the span for this punctuation character.
880 pub fn set_span(&mut self, span: Span) {
881 self.span = span;
882 }
883 }
884
885 /// Prints the punctuation character as a string that should be losslessly
886 /// convertible back into the same character.
887 impl Display for Punct {
888 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
889 Display::fmt(&self.ch, f)
890 }
891 }
892
893 impl Debug for Punct {
894 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
895 let mut debug = fmt.debug_struct("Punct");
896 debug.field("char", &self.ch);
897 debug.field("spacing", &self.spacing);
898 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
899 debug.finish()
900 }
901 }
902
903 /// A word of Rust code, which may be a keyword or legal variable name.
904 ///
905 /// An identifier consists of at least one Unicode code point, the first of
906 /// which has the XID_Start property and the rest of which have the XID_Continue
907 /// property.
908 ///
909 /// - The empty string is not an identifier. Use `Option`.
910 /// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
911 ///
912 /// An identifier constructed with `Ident::new` is permitted to be a Rust
913 /// keyword, though parsing one through its [`Parse`] implementation rejects
914 /// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
915 /// behaviour of `Ident::new`.
916 ///
917 /// [`Parse`]: https://docs.rs/syn/3/syn/parse/trait.Parse.html
918 ///
919 /// # Examples
920 ///
921 /// A new ident can be created from a string using the `Ident::new` function.
922 /// A span must be provided explicitly which governs the name resolution
923 /// behavior of the resulting identifier.
924 ///
925 /// ```
926 /// use proc_macro2::{Ident, Span};
927 ///
928 /// fn main() {
929 /// let call_ident = Ident::new("calligraphy", Span::call_site());
930 ///
931 /// println!("{}", call_ident);
932 /// }
933 /// ```
934 ///
935 /// An ident can be interpolated into a token stream using the `quote!` macro.
936 ///
937 /// ```
938 /// use proc_macro2::{Ident, Span};
939 /// use quote::quote;
940 ///
941 /// fn main() {
942 /// let ident = Ident::new("demo", Span::call_site());
943 ///
944 /// // Create a variable binding whose name is this ident.
945 /// let expanded = quote! { let #ident = 10; };
946 ///
947 /// // Create a variable binding with a slightly different name.
948 /// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
949 /// let expanded = quote! { let #temp_ident = 10; };
950 /// }
951 /// ```
952 ///
953 /// A string representation of the ident is available through the `to_string()`
954 /// method.
955 ///
956 /// ```
957 /// # use proc_macro2::{Ident, Span};
958 /// #
959 /// # let ident = Ident::new("another_identifier", Span::call_site());
960 /// #
961 /// // Examine the ident as a string.
962 /// let ident_string = ident.to_string();
963 /// if ident_string.len() > 60 {
964 /// println!("Very long identifier: {}", ident_string)
965 /// }
966 /// ```
967 #[derive(Clone)]
968 pub struct Ident {
969 inner: imp::Ident,
970 _marker: ProcMacroAutoTraits,
971 }
972
973 impl Ident {
974 fn _new(inner: imp::Ident) -> Self {
975 Ident {
976 inner,
977 _marker: MARKER,
978 }
979 }
980
981 fn _new_fallback(inner: fallback::Ident) -> Self {
982 Ident {
983 inner: imp::Ident::from(inner),
984 _marker: MARKER,
985 }
986 }
987
988 /// Creates a new `Ident` with the given `string` as well as the specified
989 /// `span`.
990 ///
991 /// The `string` argument must be a valid identifier permitted by the
992 /// language, otherwise the function will panic.
993 ///
994 /// Note that `span`, currently in rustc, configures the hygiene information
995 /// for this identifier.
996 ///
997 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
998 /// hygiene meaning that identifiers created with this span will be resolved
999 /// as if they were written directly at the location of the macro call, and
1000 /// other code at the macro call site will be able to refer to them as well.
1001 ///
1002 /// Later spans like `Span::def_site()` will allow to opt-in to
1003 /// "definition-site" hygiene meaning that identifiers created with this
1004 /// span will be resolved at the location of the macro definition and other
1005 /// code at the macro call site will not be able to refer to them.
1006 ///
1007 /// Due to the current importance of hygiene this constructor, unlike other
1008 /// tokens, requires a `Span` to be specified at construction.
1009 ///
1010 /// # Panics
1011 ///
1012 /// Panics if the input string is neither a keyword nor a legal variable
1013 /// name. If you are not sure whether the string contains an identifier and
1014 /// need to handle an error case, use
1015 /// syn::parse_str::<Ident>
1018 /// rather than `Ident::new`.
1019 #[track_caller]
1020 pub fn new(string: &str, span: Span) -> Self {
1021 Ident::_new(imp::Ident::new_checked(string, span.inner))
1022 }
1023
1024 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
1025 /// `string` argument must be a valid identifier permitted by the language
1026 /// (including keywords, e.g. `fn`). Keywords which are usable in path
1027 /// segments (e.g. `self`, `super`) are not supported, and will cause a
1028 /// panic.
1029 #[track_caller]
1030 pub fn new_raw(string: &str, span: Span) -> Self {
1031 Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
1032 }
1033
1034 /// Returns the span of this `Ident`.
1035 pub fn span(&self) -> Span {
1036 Span::_new(self.inner.span())
1037 }
1038
1039 /// Configures the span of this `Ident`, possibly changing its hygiene
1040 /// context.
1041 pub fn set_span(&mut self, span: Span) {
1042 self.inner.set_span(span.inner);
1043 }
1044 }
1045
1046 impl PartialEq for Ident {
1047 fn eq(&self, other: &Ident) -> bool {
1048 self.inner == other.inner
1049 }
1050 }
1051
1052 impl PartialEq for Ident
1053 where
1054 T: ?Sized + AsRef,
1055 {
1056 fn eq(&self, other: &T) -> bool {
1057 self.inner == other
1058 }
1059 }
1060
1061 impl Eq for Ident {}
1062
1063 impl PartialOrd for Ident {
1064 fn partial_cmp(&self, other: &Ident) -> Option {
1065 Some(self.cmp(other))
1066 }
1067 }
1068
1069 impl Ord for Ident {
1070 fn cmp(&self, other: &Ident) -> Ordering {
1071 self.to_string().cmp(&other.to_string())
1072 }
1073 }
1074
1075 impl Hash for Ident {
1076 fn hash(&self, hasher: &mut H) {
1077 self.to_string().hash(hasher);
1078 }
1079 }
1080
1081 /// Prints the identifier as a string that should be losslessly convertible back
1082 /// into the same identifier.
1083 impl Display for Ident {
1084 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1085 Display::fmt(&self.inner, f)
1086 }
1087 }
1088
1089 impl Debug for Ident {
1090 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1091 Debug::fmt(&self.inner, f)
1092 }
1093 }
1094
1095 /// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
1096 /// byte character (`b'a'`), an integer or floating point number with or without
1097 /// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1098 ///
1099 /// Boolean literals like `true` and `false` do not belong here, they are
1100 /// `Ident`s.
1101 #[derive(Clone)]
1102 pub struct Literal {
1103 inner: imp::Literal,
1104 _marker: ProcMacroAutoTraits,
1105 }
1106
1107 macro_rules! suffixed_int_literals {
1108 ($($name:ident => $kind:ident,)*) => ($(
1109 /// Creates a new suffixed integer literal with the specified value.
1110 ///
1111 /// This function will create an integer like `1u32` where the integer
1112 /// value specified is the first part of the token and the integral is
1113 /// also suffixed at the end. Literals created from negative numbers may
1114 /// not survive roundtrips through `TokenStream` or strings and may be
1115 /// broken into two tokens (`-` and positive literal).
1116 ///
1117 /// Literals created through this method have the `Span::call_site()`
1118 /// span by default, which can be configured with the `set_span` method
1119 /// below.
1120 pub fn $name(n: $kind) -> Literal {
1121 Literal::_new(imp::Literal::$name(n))
1122 }
1123 )*)
1124 }
1125
1126 macro_rules! unsuffixed_int_literals {
1127 ($($name:ident => $kind:ident,)*) => ($(
1128 /// Creates a new unsuffixed integer literal with the specified value.
1129 ///
1130 /// This function will create an integer like `1` where the integer
1131 /// value specified is the first part of the token. No suffix is
1132 /// specified on this token, meaning that invocations like
1133 /// `Literal::i8_unsuffixed(1)` are equivalent to
1134 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
1135 /// may not survive roundtrips through `TokenStream` or strings and may
1136 /// be broken into two tokens (`-` and positive literal).
1137 ///
1138 /// Literals created through this method have the `Span::call_site()`
1139 /// span by default, which can be configured with the `set_span` method
1140 /// below.
1141 pub fn $name(n: $kind) -> Literal {
1142 Literal::_new(imp::Literal::$name(n))
1143 }
1144 )*)
1145 }
1146
1147 impl Literal {
1148 fn _new(inner: imp::Literal) -> Self {
1149 Literal {
1150 inner,
1151 _marker: MARKER,
1152 }
1153 }
1154
1155 fn _new_fallback(inner: fallback::Literal) -> Self {
1156 Literal {
1157 inner: imp::Literal::from(inner),
1158 _marker: MARKER,
1159 }
1160 }
1161
1162 suffixed_int_literals! {
1163 u8_suffixed => u8,
1164 u16_suffixed => u16,
1165 u32_suffixed => u32,
1166 u64_suffixed => u64,
1167 u128_suffixed => u128,
1168 usize_suffixed => usize,
1169 i8_suffixed => i8,
1170 i16_suffixed => i16,
1171 i32_suffixed => i32,
1172 i64_suffixed => i64,
1173 i128_suffixed => i128,
1174 isize_suffixed => isize,
1175 }
1176
1177 unsuffixed_int_literals! {
1178 u8_unsuffixed => u8,
1179 u16_unsuffixed => u16,
1180 u32_unsuffixed => u32,
1181 u64_unsuffixed => u64,
1182 u128_unsuffixed => u128,
1183 usize_unsuffixed => usize,
1184 i8_unsuffixed => i8,
1185 i16_unsuffixed => i16,
1186 i32_unsuffixed => i32,
1187 i64_unsuffixed => i64,
1188 i128_unsuffixed => i128,
1189 isize_unsuffixed => isize,
1190 }
1191
1192 /// Creates a new unsuffixed floating-point literal.
1193 ///
1194 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1195 /// the float's value is emitted directly into the token but no suffix is
1196 /// used, so it may be inferred to be a `f64` later in the compiler.
1197 /// Literals created from negative numbers may not survive round-trips
1198 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1199 /// and positive literal).
1200 ///
1201 /// # Panics
1202 ///
1203 /// This function requires that the specified float is finite, for example
1204 /// if it is infinity or NaN this function will panic.
1205 pub fn f64_unsuffixed(f: f64) -> Literal {
1206 assert!(f.is_finite());
1207 Literal::_new(imp::Literal::f64_unsuffixed(f))
1208 }
1209
1210 /// Creates a new suffixed floating-point literal.
1211 ///
1212 /// This constructor will create a literal like `1.0f64` where the value
1213 /// specified is the preceding part of the token and `f64` is the suffix of
1214 /// the token. This token will always be inferred to be an `f64` in the
1215 /// compiler. Literals created from negative numbers may not survive
1216 /// round-trips through `TokenStream` or strings and may be broken into two
1217 /// tokens (`-` and positive literal).
1218 ///
1219 /// # Panics
1220 ///
1221 /// This function requires that the specified float is finite, for example
1222 /// if it is infinity or NaN this function will panic.
1223 pub fn f64_suffixed(f: f64) -> Literal {
1224 assert!(f.is_finite());
1225 Literal::_new(imp::Literal::f64_suffixed(f))
1226 }
1227
1228 /// Creates a new unsuffixed floating-point literal.
1229 ///
1230 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1231 /// the float's value is emitted directly into the token but no suffix is
1232 /// used, so it may be inferred to be a `f64` later in the compiler.
1233 /// Literals created from negative numbers may not survive round-trips
1234 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1235 /// and positive literal).
1236 ///
1237 /// # Panics
1238 ///
1239 /// This function requires that the specified float is finite, for example
1240 /// if it is infinity or NaN this function will panic.
1241 pub fn f32_unsuffixed(f: f32) -> Literal {
1242 assert!(f.is_finite());
1243 Literal::_new(imp::Literal::f32_unsuffixed(f))
1244 }
1245
1246 /// Creates a new suffixed floating-point literal.
1247 ///
1248 /// This constructor will create a literal like `1.0f32` where the value
1249 /// specified is the preceding part of the token and `f32` is the suffix of
1250 /// the token. This token will always be inferred to be an `f32` in the
1251 /// compiler. Literals created from negative numbers may not survive
1252 /// round-trips through `TokenStream` or strings and may be broken into two
1253 /// tokens (`-` and positive literal).
1254 ///
1255 /// # Panics
1256 ///
1257 /// This function requires that the specified float is finite, for example
1258 /// if it is infinity or NaN this function will panic.
1259 pub fn f32_suffixed(f: f32) -> Literal {
1260 assert!(f.is_finite());
1261 Literal::_new(imp::Literal::f32_suffixed(f))
1262 }
1263
1264 /// String literal.
1265 pub fn string(string: &str) -> Literal {
1266 Literal::_new(imp::Literal::string(string))
1267 }
1268
1269 /// Character literal.
1270 pub fn character(ch: char) -> Literal {
1271 Literal::_new(imp::Literal::character(ch))
1272 }
1273
1274 /// Byte character literal.
1275 pub fn byte_character(byte: u8) -> Literal {
1276 Literal::_new(imp::Literal::byte_character(byte))
1277 }
1278
1279 /// Byte string literal.
1280 pub fn byte_string(bytes: &[u8]) -> Literal {
1281 Literal::_new(imp::Literal::byte_string(bytes))
1282 }
1283
1284 /// C string literal.
1285 pub fn c_string(string: &CStr) -> Literal {
1286 Literal::_new(imp::Literal::c_string(string))
1287 }
1288
1289 /// Returns the span encompassing this literal.
1290 pub fn span(&self) -> Span {
1291 Span::_new(self.inner.span())
1292 }
1293
1294 /// Configures the span associated for this literal.
1295 pub fn set_span(&mut self, span: Span) {
1296 self.inner.set_span(span.inner);
1297 }
1298
1299 /// Returns a `Span` that is a subset of `self.span()` containing only
1300 /// the source bytes in range `range`. Returns `None` if the would-be
1301 /// trimmed span is outside the bounds of `self`.
1302 ///
1303 /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1304 /// nightly-only. When called from within a procedural macro not using a
1305 /// nightly compiler, this method will always return `None`.
1306 pub fn subspan>(&self, range: R) -> Option {
1307 self.inner.subspan(range).map(Span::_new)
1308 }
1309
1310 /// Returns the unescaped string value if this is a string literal.
1311 #[cfg(procmacro2_semver_exempt)]
1312 pub fn str_value(&self) -> Result {
1313 let repr = self.to_string();
1314
1315 if repr.starts_with('"') && repr[1..].ends_with('"') {
1316 let quoted = &repr[1..repr.len() - 1];
1317 let mut value = String::with_capacity(quoted.len());
1318 let mut error = None;
1319 rustc_literal_escaper::unescape_str(quoted, |_range, res| match res {
1320 Ok(ch) => value.push(ch),
1321 Err(err) => {
1322 if err.is_fatal() {
1323 error = Some(ConversionErrorKind::FailedToUnescape(err));
1324 }
1325 }
1326 });
1327 return match error {
1328 Some(error) => Err(error),
1329 None => Ok(value),
1330 };
1331 }
1332
1333 if repr.starts_with('r') {
1334 if let Some(raw) = get_raw(&repr[1..]) {
1335 return Ok(raw.to_owned());
1336 }
1337 }
1338
1339 Err(ConversionErrorKind::InvalidLiteralKind)
1340 }
1341
1342 /// Returns the unescaped string value (including nul terminator) if this is
1343 /// a c-string literal.
1344 #[cfg(procmacro2_semver_exempt)]
1345 pub fn cstr_value(&self) -> Result, ConversionErrorKind> {
1346 let repr = self.to_string();
1347
1348 if repr.starts_with("c\"") && repr[2..].ends_with('"') {
1349 let quoted = &repr[2..repr.len() - 1];
1350 let mut value = Vec::with_capacity(quoted.len());
1351 let mut error = None;
1352 rustc_literal_escaper::unescape_c_str(quoted, |_range, res| match res {
1353 Ok(MixedUnit::Char(ch)) => {
1354 value.extend_from_slice(ch.get().encode_utf8(&mut [0; 4]).as_bytes());
1355 }
1356 Ok(MixedUnit::HighByte(byte)) => value.push(byte.get()),
1357 Err(err) => {
1358 if err.is_fatal() {
1359 error = Some(ConversionErrorKind::FailedToUnescape(err));
1360 }
1361 }
1362 });
1363 return match error {
1364 Some(error) => Err(error),
1365 None => {
1366 value.push(b'\0');
1367 Ok(value)
1368 }
1369 };
1370 }
1371
1372 if repr.starts_with("cr") {
1373 if let Some(raw) = get_raw(&repr[2..]) {
1374 let mut value = Vec::with_capacity(raw.len() + 1);
1375 value.extend_from_slice(raw.as_bytes());
1376 value.push(b'\0');
1377 return Ok(value);
1378 }
1379 }
1380
1381 Err(ConversionErrorKind::InvalidLiteralKind)
1382 }
1383
1384 /// Returns the unescaped string value if this is a byte string literal.
1385 #[cfg(procmacro2_semver_exempt)]
1386 pub fn byte_str_value(&self) -> Result, ConversionErrorKind> {
1387 let repr = self.to_string();
1388
1389 if repr.starts_with("b\"") && repr[2..].ends_with('"') {
1390 let quoted = &repr[2..repr.len() - 1];
1391 let mut value = Vec::with_capacity(quoted.len());
1392 let mut error = None;
1393 rustc_literal_escaper::unescape_byte_str(quoted, |_range, res| match res {
1394 Ok(byte) => value.push(byte),
1395 Err(err) => {
1396 if err.is_fatal() {
1397 error = Some(ConversionErrorKind::FailedToUnescape(err));
1398 }
1399 }
1400 });
1401 return match error {
1402 Some(error) => Err(error),
1403 None => Ok(value),
1404 };
1405 }
1406
1407 if repr.starts_with("br") {
1408 if let Some(raw) = get_raw(&repr[2..]) {
1409 return Ok(raw.as_bytes().to_owned());
1410 }
1411 }
1412
1413 Err(ConversionErrorKind::InvalidLiteralKind)
1414 }
1415
1416 // Intended for the `quote!` macro to use when constructing a proc-macro2
1417 // token out of a macro_rules $:literal token, which is already known to be
1418 // a valid literal. This avoids reparsing/validating the literal's string
1419 // representation. This is not public API other than for quote.
1420 #[doc(hidden)]
1421 pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1422 Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
1423 }
1424 }
1425
1426 impl FromStr for Literal {
1427 type Err = LexError;
1428
1429 fn from_str(repr: &str) -> Result {
1430 match imp::Literal::from_str_checked(repr) {
1431 Ok(lit) => Ok(Literal::_new(lit)),
1432 Err(lex) => Err(LexError {
1433 inner: lex,
1434 _marker: MARKER,
1435 }),
1436 }
1437 }
1438 }
1439
1440 impl Debug for Literal {
1441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1442 Debug::fmt(&self.inner, f)
1443 }
1444 }
1445
1446 impl Display for Literal {
1447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1448 Display::fmt(&self.inner, f)
1449 }
1450 }
1451
1452 /// Error when retrieving a string literal's unescaped value.
1453 #[cfg(procmacro2_semver_exempt)]
1454 #[derive(Debug, PartialEq, Eq)]
1455 pub enum ConversionErrorKind {
1456 /// The literal is of the right string kind, but its contents are malformed
1457 /// in a way that cannot be unescaped to a value.
1458 FailedToUnescape(EscapeError),
1459 /// The literal is not of the string kind whose value was requested, for
1460 /// example byte string vs UTF-8 string.
1461 InvalidLiteralKind,
1462 }
1463
1464 // ###"..."### -> ...
1465 #[cfg(procmacro2_semver_exempt)]
1466 fn get_raw(repr: &str) -> Option<&str> {
1467 let pounds = repr.len() - repr.trim_start_matches('#').len();
1468 if repr.len() >= pounds + 1 + 1 + pounds
1469 && repr[pounds..].starts_with('"')
1470 && repr.trim_end_matches('#').len() + pounds == repr.len()
1471 && repr[..repr.len() - pounds].ends_with('"')
1472 {
1473 Some(&repr[pounds + 1..repr.len() - pounds - 1])
1474 } else {
1475 None
1476 }
1477 }
1478
1479 /// Public implementation details for the `TokenStream` type, such as iterators.
1480 pub mod token_stream {
1481 use crate::marker::{ProcMacroAutoTraits, MARKER};
1482 use crate::{imp, TokenTree};
1483 use core::fmt::{self, Debug};
1484
1485 pub use crate::TokenStream;
1486
1487 /// An iterator over `TokenStream`'s `TokenTree`s.
1488 ///
1489 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1490 /// delimited groups, and returns whole groups as token trees.
1491 #[derive(Clone)]
1492 pub struct IntoIter {
1493 inner: imp::TokenTreeIter,
1494 _marker: ProcMacroAutoTraits,
1495 }
1496
1497 impl Iterator for IntoIter {
1498 type Item = TokenTree;
1499
1500 fn next(&mut self) -> Option {
1501 self.inner.next()
1502 }
1503
1504 fn size_hint(&self) -> (usize, Option) {
1505 self.inner.size_hint()
1506 }
1507 }
1508
1509 impl Debug for IntoIter {
1510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511 f.write_str("TokenStream ")?;
1512 f.debug_list().entries(self.clone()).finish()
1513 }
1514 }
1515
1516 impl IntoIterator for TokenStream {
1517 type Item = TokenTree;
1518 type IntoIter = IntoIter;
1519
1520 fn into_iter(self) -> IntoIter {
1521 IntoIter {
1522 inner: self.inner.into_iter(),
1523 _marker: MARKER,
1524 }
1525 }
1526 }
1527 }