structural_derive 0.4.3

Implementation detail of the structural crate.
Documentation
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
use crate::{
    ident_or_index::IdentOrIndex,
    ignored_wrapper::Ignored,
    parse_utils::ParseBufferExt,
    tokenizers::{variant_field_tokens, variant_name_tokens},
};

use as_derive_utils::ToTokenFnMut;

use core_extensions::SelfOps;

use proc_macro2::TokenStream as TokenStream2;

use quote::{quote, ToTokens, TokenStreamExt};

use syn::{
    parse::{self, Parse, ParseStream},
    Ident, Token,
};

///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq)]
pub(crate) struct FieldPaths {
    prefix: Option<NestedFieldPath>,
    paths: Vec<NestedFieldPath>,
    path_uniqueness: PathUniqueness,
}

impl FieldPaths {
    pub(crate) fn from_ident(soi: Ident) -> Self {
        soi.piped(NestedFieldPath::from_ident)
            .piped(Self::from_path)
    }

    pub(crate) fn from_path(path: NestedFieldPath) -> Self {
        Self {
            prefix: None,
            paths: vec![path],
            path_uniqueness: PathUniqueness::Unique,
        }
    }

    pub(crate) fn contains_aliased_paths(paths: &[NestedFieldPath]) -> bool {
        paths.iter().enumerate().any(|(i, path)| {
            paths[..i]
                .iter()
                .chain(&paths[i + 1..])
                .any(|p| path.is_prefix_of(p))
        })
    }

    pub(crate) fn from_iter<I>(mut paths: I) -> Self
    where
        I: ExactSizeIterator<Item = NestedFieldPath>,
    {
        match paths.len() {
            1 => paths.next().unwrap().piped(FieldPaths::from_path),
            _ => {
                let paths = paths.collect::<Vec<NestedFieldPath>>();

                let path_uniqueness = if Self::contains_aliased_paths(&paths) {
                    PathUniqueness::Aliased
                } else {
                    PathUniqueness::Unique
                };

                Self {
                    prefix: None,
                    paths,
                    path_uniqueness,
                }
            }
        }
    }

    pub(crate) fn is_set(&self) -> bool {
        self.prefix.is_some() || self.paths.len() != 1
    }

    /// Outputs the inside of `fp!`/`FP!` invocation that constructed this FieldPaths.
    pub(crate) fn write_fp_inside(&self, buff: &mut String) {
        #[cfg(feature = "test_asserts")]
        let start = buff.len();

        if let Some(prefix) = &self.prefix {
            prefix.write_str(buff);
            buff.push_str("=>");
        }
        for (i, path) in self.paths.iter().enumerate() {
            path.write_str(buff);
            if i + 1 != self.paths.len() {
                buff.push_str(", ")
            }
        }

        #[cfg(feature = "test_asserts")]
        {
            match syn::parse_str::<Self>(&buff[start..]) {
                Ok(x) => assert_eq!(*self, x),
                Err(e) => panic!("Could not parse `{}` as {:#?}", e, self),
            }
        }
    }

    /// Gets a the type-level identifier.
    pub(crate) fn type_tokens(&self) -> TokenStream2 {
        if self.is_set() {
            let uniqueness = self.path_uniqueness;

            let tuple_param = if self.paths.len() > INNER_TUPLE_LEN {
                let inside_paren = ToTokenFnMut::new(|tokens| {
                    for nested_paths in self.paths.chunks(INNER_TUPLE_LEN) {
                        let path = nested_paths.iter().map(|x| x.to_token_stream());
                        tokens.append_all(quote!( (#(#path,)*), ));
                    }
                });
                quote!( ::structural::path::LargePathSet<(#inside_paren)>)
            } else {
                let path = self.paths.iter().map(|x| x.to_token_stream());
                quote!((#(#path,)*))
            };

            if let Some(prefix) = &self.prefix {
                let prefix_tokens = prefix.to_token_stream();
                quote!(
                    ::structural::NestedFieldPathSet<
                        #prefix_tokens,
                        #tuple_param,
                        #uniqueness
                    >
                )
            } else {
                quote!(
                    ::structural::FieldPathSet<#tuple_param,#uniqueness>
                )
            }
        } else {
            self.paths[0].to_token_stream()
        }
    }

    /// Gets a tokenizer that outputs a type-level NestedFieldPath(Set) value.
    pub(crate) fn inferred_expression_tokens(&self) -> TokenStream2 {
        if self.is_set() {
            if self.prefix.is_some() {
                quote!(unsafe { structural::NestedFieldPathSet::NEW.set_uniqueness() })
            } else {
                quote!(unsafe { structural::FieldPathSet::NEW.set_uniqueness() })
            }
        } else {
            quote!(structural::pmr::ConstDefault::DEFAULT)
        }
    }
}

impl Parse for FieldPaths {
    fn parse(input: ParseStream<'_>) -> parse::Result<Self> {
        let mut prefix = None::<NestedFieldPath>;
        let mut paths = Vec::<NestedFieldPath>::new();
        while !input.is_empty() {
            let path = input.parse::<NestedFieldPath>()?;
            if input.peek(Token!(=>)) {
                if prefix.is_some() {
                    return Err(input.error("Cannot use `=>` multiple times."));
                } else if !paths.is_empty() {
                    return Err(input.error("Cannot use `=>` after multiple field accesses."));
                }
                input.parse::<Token!(=>)>()?;
                prefix = Some(path);
            } else if input.peek(Token!(,)) {
                paths.push(path);
                input.parse::<Token!(,)>()?;
            } else if input.is_empty() {
                paths.push(path);
            } else {
                return Err(input.error("Expected a `=>`,a `,`, or the end of the input"));
            }
        }

        let mut this = FieldPaths::from_iter(paths.into_iter());
        this.prefix = prefix;
        Ok(this)
    }
}

/// The amount of field paths
pub(crate) const INNER_TUPLE_LEN: usize = 8;

///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq)]
pub(crate) struct NestedFieldPath {
    list: Vec<FieldPathComponent>,
    normalized: Vec<String>,
}

impl Parse for NestedFieldPath {
    fn parse(input: ParseStream<'_>) -> parse::Result<Self> {
        let mut list = Vec::<FieldPathComponent>::new();

        let mut is_first = true;
        while !is_field_path_terminator(input) {
            let (fpc, second) = FieldPathComponent::parse(input, IsFirst::new(is_first))?;
            list.push(fpc);
            if let Some(second) = second {
                list.push(second);
            }
            is_first = false;
        }

        Ok(Self::from_components(list))
    }
}

impl NestedFieldPath {
    pub(crate) fn from_components(list: Vec<FieldPathComponent>) -> Self {
        let mut normalized = Vec::new();

        for component in &list {
            component.write_normalized(&mut normalized);
        }

        NestedFieldPath { list, normalized }
    }
    pub(crate) fn from_ident(ident: Ident) -> Self {
        Self::from_components(vec![FieldPathComponent::from_ident(ident)])
    }
    pub(crate) fn write_str(&self, buff: &mut String) {
        for fpc in &self.list {
            fpc.write_str(buff);
        }
    }

    pub(crate) fn is_prefix_of(&self, other: &Self) -> bool {
        let min_len = self.normalized.len().min(other.normalized.len());

        self.normalized
            .iter()
            .take(min_len)
            .eq(other.normalized.iter().take(min_len))
    }

    pub(crate) fn to_token_stream(&self) -> TokenStream2 {
        if self.list.len() == 1 {
            let path_component = self.list[0].single_tokenizer();
            path_component.into_token_stream()
        } else {
            let tuple = self.tuple_tokens();
            quote!( structural::NestedFieldPath<#tuple> )
        }
    }

    pub(crate) fn tuple_tokens(&self) -> TokenStream2 {
        let strings = self.list.iter().map(|x| x.single_tokenizer());
        quote!( (#(#strings,)*) )
    }
}

///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Eq, PartialEq)]
pub(crate) enum FieldPathComponent {
    /// A field
    Ident(IdentOrIndex),
    VariantField {
        variant: IdentOrIndex,
        field: IdentOrIndex,
    },
    VariantName {
        variant: IdentOrIndex,
    },
}

impl FieldPathComponent {
    pub(crate) fn from_ident(ident: Ident) -> Self {
        let x = IdentOrIndex::Ident(ident);
        FieldPathComponent::Ident(x)
    }
    fn write_normalized(&self, normalized: &mut Vec<String>) {
        use self::FieldPathComponent as FPC;
        match self {
            FPC::Ident(ident) => {
                normalized.push(ident.to_string());
            }
            FPC::VariantField { variant, field } => {
                normalized.push(variant.to_string());
                normalized.push(field.to_string());
            }
            FPC::VariantName { variant } => {
                normalized.push(variant.to_string());
            }
        }
    }
    pub(crate) fn write_str(&self, buff: &mut String) {
        use self::FieldPathComponent as FPC;
        use std::fmt::Write;

        match self {
            FPC::Ident(ident) => {
                let _ = write!(buff, ".{}", ident.to_token_stream());
            }
            FPC::VariantField { variant, field } => {
                let _ = write!(
                    buff,
                    "::{}.{}",
                    variant.to_token_stream(),
                    field.to_token_stream()
                );
            }
            FPC::VariantName { variant } => {
                let _ = write!(buff, "::{}", variant.to_token_stream());
            }
        }
    }

    pub(crate) fn parse(
        input: ParseStream<'_>,
        is_first: IsFirst,
    ) -> parse::Result<(Self, Option<Self>)> {
        let fork = input.fork();

        let prefix_token = if input.peek_parse(Token!(::))?.is_some() {
            PrefixToken::Colon2
        } else if input.peek_parse(Token!(.))?.is_some() {
            PrefixToken::Dot
        } else if input.peek(Token!(?)) {
            PrefixToken::Question
        } else {
            PrefixToken::Nothing
        };

        if let PrefixToken::Question = prefix_token {
            let question = input.parse::<Token!(?)>()?;
            let span = Ignored::new(question.spans[0]);
            Ok((
                FieldPathComponent::VariantField {
                    variant: IdentOrIndex::Str {
                        str: "Some".to_string(),
                        span,
                    },
                    field: IdentOrIndex::Str {
                        str: "0".to_string(),
                        span,
                    },
                },
                None,
            ))
        } else if let PrefixToken::Colon2 = prefix_token {
            let (first, second) = parse_field(input)?;
            let variant = first;

            if let Some(field) = second {
                Ok((FieldPathComponent::VariantField { variant, field }, None))
            } else if input.peek_parse(Token!(.))?.is_some() {
                let (field, extra) = parse_field(input)?;
                Ok((
                    FieldPathComponent::VariantField { variant, field },
                    extra.map(FieldPathComponent::Ident),
                ))
            } else if is_field_path_terminator(input) {
                Ok((FieldPathComponent::VariantName { variant }, None))
            } else {
                Err(input.error("Expected either a `.field_name`,the end of the field path."))
            }
        } else {
            let (first, second) = parse_field(input)?;
            if let (PrefixToken::Nothing, IsFirst::No) = (prefix_token, is_first) {
                return Err(fork.error("expected a period"));
            }
            Ok((
                FieldPathComponent::Ident(first),
                second.map(FieldPathComponent::Ident),
            ))
        }
    }

    fn single_tokenizer(&self) -> TokenStream2 {
        use self::FieldPathComponent as FPC;

        match self {
            FPC::Ident(ident) => ident.tstr_tokens(),
            FPC::VariantField { variant, field } => {
                variant_field_tokens(variant.borrowed(), field.borrowed())
            }
            FPC::VariantName { variant } => variant_name_tokens(variant.borrowed()),
        }
    }
}

fn is_field_path_terminator(input: ParseStream<'_>) -> bool {
    input.is_empty() || input.peek(Token!(,)) || input.peek(Token!(=>))
}

fn make_ident_or_index(digits: &str) -> syn::Result<Option<IdentOrIndex>> {
    if digits.is_empty() {
        return Ok(None);
    }
    syn::parse_str::<IdentOrIndex>(digits).map(Some)
}

/// For parsing path components.
///
/// This function returns a second `IdentOrIndex` if the first token is
/// a floating point number.
pub(crate) fn parse_field(
    input: ParseStream<'_>,
) -> parse::Result<(IdentOrIndex, Option<IdentOrIndex>)> {
    if input.peek(syn::LitFloat) {
        let f = input.parse::<syn::LitFloat>()?;
        let digits = f.base10_digits();
        let mut iter = digits.split('.');

        let first = make_ident_or_index(iter.next().unwrap())?
            .expect("float literals can't have a leading `.`");

        // Handling non-integer fields ie:`0."hello"` and `0.world` here,
        // so that I don't have to store whether a float was parsed.
        let second = match make_ident_or_index(iter.next().unwrap())? {
            Some(x) => Some(x),
            // Parsing the IdentOrIndex after the `###.`  flota literal,
            None => Some(IdentOrIndex::parse(input)?),
        };
        Ok((first, second))
    } else {
        Ok((IdentOrIndex::parse(input)?, None))
    }
}

///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum IsFirst {
    No,
    Yes,
}

impl IsFirst {
    pub(crate) fn new(v: bool) -> Self {
        if v {
            IsFirst::Yes
        } else {
            IsFirst::No
        }
    }
}

///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum PathUniqueness {
    Unique,
    Aliased,
}

impl ToTokens for PathUniqueness {
    fn to_tokens(&self, ts: &mut TokenStream2) {
        match *self {
            PathUniqueness::Unique => quote!(structural::pmr::UniquePaths),
            PathUniqueness::Aliased => quote!(structural::pmr::AliasedPaths),
        }
        .to_tokens(ts);
    }
}

//////////////////////////////////////////////////////////////////////////////

#[derive(Copy, Clone)]
enum PrefixToken {
    Colon2,
    Dot,
    Question,
    Nothing,
}