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
use std::marker::PhantomData;

use derive_where::derive_where;
use proc_macro2::{Span, TokenStream, TokenTree};
use quote::ToTokens;
use syn::{parse::ParseStream, spanned::Spanned, token::Brace, LitStr, Token};

use super::{CustomNode, Infallible, Node};
use crate::recoverable::ParseRecoverable;

/// Raw unquoted text
///
/// Internally it is valid `TokenStream` (stream of rust code tokens).
/// So, it has few limitations:
/// 1. It cant contain any unclosed branches, braces or parens.
/// 2. Some tokens like ' ` can be treated as invalid, because in rust it only
/// allowed in certain contexts.
///
/// Can be formatted to a string using `to_source_text`,
/// `to_token_stream_string` or `to_string_best` methods.
///
/// Note:
/// It use `Span::source_text` to retrieve source text with spaces
/// source_text method is not available in `quote!` context, or in context where
/// input is generated by another macro. In still can return default formatting
/// for TokenStream.
#[derive_where(Clone, Debug)]
pub struct RawText<C = Infallible> {
    token_stream: TokenStream,
    // Span that started before previous token, and after next.
    context_span: Option<(Span, Span)>,
    #[cfg(feature = "rawtext-stable-hack-module")]
    recovered_text: Option<String>,
    // Use type parameter to make it possible to find custom nodes in the raw_node.
    _c: PhantomData<C>,
}

impl<C> Default for RawText<C> {
    fn default() -> Self {
        Self {
            token_stream: Default::default(),
            context_span: Default::default(),
            #[cfg(feature = "rawtext-stable-hack-module")]
            recovered_text: Default::default(),
            _c: PhantomData,
        }
    }
}

impl<C> RawText<C> {
    /// Custom node type parameter is used only for parsing, so it can be
    /// changed during usage.
    pub fn convert_custom<U>(self) -> RawText<U> {
        RawText {
            token_stream: self.token_stream,
            context_span: self.context_span,
            #[cfg(feature = "rawtext-stable-hack-module")]
            recovered_text: self.recovered_text,
            _c: PhantomData,
        }
    }
    pub(crate) fn set_tag_spans(&mut self, before: impl Spanned, after: impl Spanned) {
        // todo: use span.after/before when it will be available in proc_macro2
        // for now just join full span an remove tokens from it.
        self.context_span = Some((before.span(), after.span()));
    }

    /// Convert to string using Display implementation of inner token stream.
    pub fn to_token_stream_string(&self) -> String {
        self.token_stream.to_string()
    }

    /// Try to get source text of the token stream.
    /// Internally uses `Span::source_text` and `Span::join`, so it can be not
    /// available.
    ///
    /// Optionally including whitespaces.
    /// Whitespaces can be recovered only if before and after `RawText` was
    /// other valid `Node`.
    pub fn to_source_text(&self, with_whitespaces: bool) -> Option<String> {
        if with_whitespaces {
            let (start, end) = self.context_span?;
            let full = start.join(end)?;
            let full_text = full.source_text()?;
            let start_text = start.source_text()?;
            let end_text = end.source_text()?;
            debug_assert!(full_text.ends_with(&end_text));
            debug_assert!(full_text.starts_with(&start_text));
            Some(full_text[start_text.len()..(full_text.len() - end_text.len())].to_string())
        } else {
            self.join_spans()?.source_text()
        }
    }

    /// Return Spans for all unquoted text or nothing.
    /// Usefull to detect is `Span::join` is available or not.
    pub fn join_spans(&self) -> Option<Span> {
        let mut span: Option<Span> = None;
        for tt in self.token_stream.clone().into_iter() {
            let joined = if let Some(span) = span {
                span.join(tt.span())?
            } else {
                tt.span()
            };
            span = Some(joined);
        }
        span
    }

    pub fn is_empty(&self) -> bool {
        self.token_stream.is_empty()
    }

    pub(crate) fn vec_set_context(
        open_tag_end: Span,
        close_tag_start: Option<Span>,
        mut children: Vec<Node<C>>,
    ) -> Vec<Node<C>>
    where
        C: CustomNode,
    {
        let spans: Vec<Span> = Some(open_tag_end)
            .into_iter()
            .chain(children.iter().map(|n| n.span()))
            .chain(close_tag_start)
            .collect();

        for (spans, children) in spans.windows(3).zip(&mut children) {
            if let Node::RawText(t) = children {
                t.set_tag_spans(spans[0], spans[2])
            }
        }
        children
    }

    /// Trying to return best string representation available:
    /// 1. calls `to_source_text_hack()`.
    /// 2. calls `to_source_text(true)`
    /// 3. calls `to_source_text(false)`
    /// 4. as fallback calls `to_token_stream_string()`
    pub fn to_string_best(&self) -> String {
        #[cfg(feature = "rawtext-stable-hack-module")]
        if let Some(recovered) = &self.recovered_text {
            return recovered.clone();
        }
        self.to_source_text(true)
            .or_else(|| self.to_source_text(false))
            .unwrap_or_else(|| self.to_token_stream_string())
    }

    // Returns text recovered using recover_space_hack.
    // If feature "rawtext-stable-hack-module" wasn't activated returns None.
    //
    // Recovered text, tries to save whitespaces if possible.
    pub fn to_source_text_hack(&self) -> Option<String> {
        #[cfg(feature = "rawtext-stable-hack-module")]
        {
            return self.recovered_text.clone();
        }
        #[cfg(not(feature = "rawtext-stable-hack-module"))]
        None
    }

    #[cfg(feature = "rawtext-stable-hack-module")]
    pub(crate) fn recover_space(&mut self, other: &Self) {
        self.recovered_text = Some(
            other
                .to_source_text(self.context_span.is_some())
                .expect("Cannot recover space in this context"),
        )
    }
    #[cfg(feature = "rawtext-stable-hack-module")]
    pub(crate) fn init_recover_space(&mut self, init: String) {
        self.recovered_text = Some(init)
    }
}

impl RawText {
    /// Returns true if we on nightly rust and join_spans available
    pub fn is_source_text_available() -> bool {
        // TODO: Add feature join_spans check.
        cfg!(rstml_signal_nightly)
    }
}

impl<C: CustomNode> ParseRecoverable for RawText<C> {
    fn parse_recoverable(
        parser: &mut crate::recoverable::RecoverableContext,
        input: ParseStream,
    ) -> Option<Self> {
        let mut token_stream = TokenStream::new();
        let any_node = |input: ParseStream| {
            input.peek(Token![<])
                || input.peek(Brace)
                || input.peek(LitStr)
                || C::peek_element(&input.fork())
        };
        // Parse any input until catching any node.
        // Fail only on eof.
        while !any_node(input) && !input.is_empty() {
            token_stream.extend([parser.save_diagnostics(input.parse::<TokenTree>())?])
        }
        Some(Self {
            token_stream,
            context_span: None,
            #[cfg(feature = "rawtext-stable-hack-module")]
            recovered_text: None,
            _c: PhantomData,
        })
    }
}

impl<C: CustomNode> ToTokens for RawText<C> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.token_stream.to_tokens(tokens)
    }
}

impl<C: CustomNode> From<TokenStream> for RawText<C> {
    fn from(token_stream: TokenStream) -> Self {
        Self {
            token_stream,
            context_span: None,
            #[cfg(feature = "rawtext-stable-hack-module")]
            recovered_text: None,
            _c: PhantomData,
        }
    }
}