nu_protocol/ast/
import_pattern.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{ModuleId, Span, VarId};
4use std::collections::HashSet;
5
6/// possible patterns after the first module level in an [`ImportPattern`].
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub enum ImportPatternMember {
9    /// Wildcard import of items
10    Glob { span: Span },
11    /// single specific module or item
12    Name { name: Vec<u8>, span: Span },
13    /// list of items
14    List { names: Vec<(Vec<u8>, Span)> },
15}
16
17impl ImportPatternMember {
18    pub fn span(&self) -> Span {
19        match self {
20            ImportPatternMember::Glob { span } | ImportPatternMember::Name { span, .. } => *span,
21            ImportPatternMember::List { names } => {
22                let first = names
23                    .first()
24                    .map(|&(_, span)| span)
25                    .unwrap_or(Span::unknown());
26
27                let last = names
28                    .last()
29                    .map(|&(_, span)| span)
30                    .unwrap_or(Span::unknown());
31
32                Span::append(first, last)
33            }
34        }
35    }
36}
37
38/// The first item of a `use` statement needs to specify an explicit module
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct ImportPatternHead {
41    pub name: Vec<u8>,
42    pub id: Option<ModuleId>,
43    pub span: Span,
44}
45
46/// The pattern specifying modules in a `use` statement
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct ImportPattern {
49    pub head: ImportPatternHead,
50    pub members: Vec<ImportPatternMember>,
51    // communicate to eval which decls/aliases were hidden during `parse_hide()` so it does not
52    // interpret these as env var names:
53    pub hidden: HashSet<Vec<u8>>,
54    // information for the eval which const values to put into stack as variables
55    pub constants: Vec<VarId>,
56}
57
58impl ImportPattern {
59    pub fn new() -> Self {
60        ImportPattern {
61            head: ImportPatternHead {
62                name: vec![],
63                id: None,
64                span: Span::unknown(),
65            },
66            members: vec![],
67            hidden: HashSet::new(),
68            constants: vec![],
69        }
70    }
71
72    pub fn span(&self) -> Span {
73        Span::append(
74            self.head.span,
75            self.members
76                .last()
77                .map(ImportPatternMember::span)
78                .unwrap_or(self.head.span),
79        )
80    }
81
82    pub fn with_hidden(self, hidden: HashSet<Vec<u8>>) -> Self {
83        ImportPattern {
84            head: self.head,
85            members: self.members,
86            hidden,
87            constants: self.constants,
88        }
89    }
90}
91
92impl Default for ImportPattern {
93    fn default() -> Self {
94        Self::new()
95    }
96}