Skip to main content

pagesift_syntax/scanner/
hcl.rs

1//! HCL 外部扫描器,移植自 tree-sitter-hcl 的 `src/scanner.c`(Apache-2.0)。
2
3use super::{MAX_SERIALIZED, ScanLexer, Scanner, is_space};
4
5const QUOTED_TEMPLATE_START: usize = 0;
6const QUOTED_TEMPLATE_END: usize = 1;
7const TEMPLATE_LITERAL_CHUNK: usize = 2;
8const TEMPLATE_INTERPOLATION_START: usize = 3;
9const TEMPLATE_INTERPOLATION_END: usize = 4;
10const TEMPLATE_DIRECTIVE_START: usize = 5;
11const TEMPLATE_DIRECTIVE_END: usize = 6;
12const HEREDOC_IDENTIFIER: usize = 7;
13
14#[derive(Clone, Copy, PartialEq, Eq)]
15enum Ctx {
16    Interpolation = 0,
17    Directive = 1,
18    Quoted = 2,
19    Heredoc = 3,
20}
21
22struct Frame {
23    kind: Ctx,
24    /// 只有 `Heredoc` 用。
25    id: Vec<u8>,
26}
27
28#[derive(Default)]
29pub struct Hcl {
30    stack: Vec<Frame>,
31}
32
33impl Hcl {
34    fn top_is(&self, k: Ctx) -> bool {
35        self.stack.last().is_some_and(|f| f.kind == k)
36    }
37
38    fn push(&mut self, kind: Ctx) {
39        self.stack.push(Frame {
40            kind,
41            id: Vec::new(),
42        });
43    }
44
45    fn in_template(&self) -> bool {
46        self.top_is(Ctx::Quoted) || self.top_is(Ctx::Heredoc)
47    }
48}
49
50fn accept(lx: &mut ScanLexer, sym: usize) -> bool {
51    lx.set_result(sym as u16);
52    true
53}
54
55fn accept_and_advance(lx: &mut ScanLexer, sym: usize) -> bool {
56    lx.next();
57    accept(lx, sym)
58}
59
60fn consume_xdigit(lx: &mut ScanLexer) -> bool {
61    lx.next();
62    lx.lookahead().is_ascii_hexdigit()
63}
64
65impl Scanner for Hcl {
66    fn scan(&mut self, lx: &mut ScanLexer, v: &[bool]) -> bool {
67        let mut ws_newline = false;
68        while is_space(lx.lookahead()) {
69            if lx.lookahead() == '\n' {
70                ws_newline = true;
71            }
72            lx.skip();
73        }
74        if lx.lookahead() == '\0' {
75            return false;
76        }
77        if v[QUOTED_TEMPLATE_START] && !self.top_is(Ctx::Quoted) && lx.lookahead() == '"' {
78            self.push(Ctx::Quoted);
79            return accept_and_advance(lx, QUOTED_TEMPLATE_START);
80        }
81        if v[QUOTED_TEMPLATE_END] && self.top_is(Ctx::Quoted) && lx.lookahead() == '"' {
82            self.stack.pop();
83            return accept_and_advance(lx, QUOTED_TEMPLATE_END);
84        }
85        if v[TEMPLATE_INTERPOLATION_START]
86            && v[TEMPLATE_LITERAL_CHUNK]
87            && !self.top_is(Ctx::Interpolation)
88            && lx.lookahead() == '$'
89        {
90            lx.next();
91            if lx.lookahead() == '{' {
92                self.push(Ctx::Interpolation);
93                return accept_and_advance(lx, TEMPLATE_INTERPOLATION_START);
94            }
95            if lx.lookahead() == '$' {
96                lx.next();
97                if lx.lookahead() == '{' {
98                    return accept_and_advance(lx, TEMPLATE_LITERAL_CHUNK);
99                }
100            }
101            return accept(lx, TEMPLATE_LITERAL_CHUNK);
102        }
103        if v[TEMPLATE_INTERPOLATION_END] && self.top_is(Ctx::Interpolation) && lx.lookahead() == '}'
104        {
105            self.stack.pop();
106            return accept_and_advance(lx, TEMPLATE_INTERPOLATION_END);
107        }
108        if v[TEMPLATE_DIRECTIVE_START]
109            && v[TEMPLATE_LITERAL_CHUNK]
110            && !self.top_is(Ctx::Directive)
111            && lx.lookahead() == '%'
112        {
113            lx.next();
114            if lx.lookahead() == '{' {
115                self.push(Ctx::Directive);
116                return accept_and_advance(lx, TEMPLATE_DIRECTIVE_START);
117            }
118            if lx.lookahead() == '%' {
119                lx.next();
120                if lx.lookahead() == '{' {
121                    return accept_and_advance(lx, TEMPLATE_LITERAL_CHUNK);
122                }
123            }
124            return accept(lx, TEMPLATE_LITERAL_CHUNK);
125        }
126        if v[TEMPLATE_DIRECTIVE_END] && self.top_is(Ctx::Directive) && lx.lookahead() == '}' {
127            self.stack.pop();
128            return accept_and_advance(lx, TEMPLATE_DIRECTIVE_END);
129        }
130        if v[HEREDOC_IDENTIFIER] && !self.top_is(Ctx::Heredoc) {
131            let mut id = Vec::new();
132            while lx.lookahead().is_alphanumeric() || matches!(lx.lookahead(), '_' | '-') {
133                id.push(lx.lookahead() as u32 as u8);
134                lx.next();
135            }
136            self.stack.push(Frame {
137                kind: Ctx::Heredoc,
138                id,
139            });
140            return accept(lx, HEREDOC_IDENTIFIER);
141        }
142        if v[HEREDOC_IDENTIFIER] && self.top_is(Ctx::Heredoc) && ws_newline {
143            let expected = self.stack.last().map(|f| f.id.clone()).unwrap_or_default();
144            for b in expected {
145                if lx.lookahead() as u32 == b as u32 {
146                    lx.next();
147                } else {
148                    return accept(lx, TEMPLATE_LITERAL_CHUNK);
149                }
150            }
151            // 标识符独占一行才算结束
152            lx.mark_end();
153            while is_space(lx.lookahead()) && lx.lookahead() != '\n' {
154                lx.next();
155            }
156            if lx.lookahead() == '\n' {
157                self.stack.pop();
158                return accept(lx, HEREDOC_IDENTIFIER);
159            }
160            lx.next();
161            lx.mark_end();
162            return accept(lx, TEMPLATE_LITERAL_CHUNK);
163        }
164        if v[TEMPLATE_LITERAL_CHUNK] && self.top_is(Ctx::Quoted) && lx.lookahead() == '\\' {
165            lx.next();
166            return match lx.lookahead() {
167                '"' | 'n' | 'r' | 't' | '\\' => accept_and_advance(lx, TEMPLATE_LITERAL_CHUNK),
168                'u' => {
169                    for _ in 0..4 {
170                        if !consume_xdigit(lx) {
171                            return false;
172                        }
173                    }
174                    accept_and_advance(lx, TEMPLATE_LITERAL_CHUNK)
175                }
176                'U' => {
177                    for _ in 0..8 {
178                        if !consume_xdigit(lx) {
179                            return false;
180                        }
181                    }
182                    accept_and_advance(lx, TEMPLATE_LITERAL_CHUNK)
183                }
184                _ => false,
185            };
186        }
187        if v[TEMPLATE_LITERAL_CHUNK] && self.in_template() {
188            return accept_and_advance(lx, TEMPLATE_LITERAL_CHUNK);
189        }
190        false
191    }
192
193    fn serialize(&self, out: &mut Vec<u8>) {
194        if self.stack.len() > 127 {
195            return;
196        }
197        let base = out.len();
198        out.extend_from_slice(&(self.stack.len() as u32).to_le_bytes());
199        for f in &self.stack {
200            if out.len() - base + 4 + 4 + f.id.len() >= MAX_SERIALIZED || f.id.len() > 127 {
201                out.truncate(base);
202                return;
203            }
204            out.extend_from_slice(&(f.kind as u32).to_le_bytes());
205            out.extend_from_slice(&(f.id.len() as u32).to_le_bytes());
206            out.extend_from_slice(&f.id);
207        }
208    }
209
210    fn deserialize(&mut self, d: &[u8]) {
211        self.stack.clear();
212        if d.len() < 4 {
213            return;
214        }
215        let n = u32::from_le_bytes([d[0], d[1], d[2], d[3]]);
216        let mut p = 4;
217        for _ in 0..n {
218            if p + 8 > d.len() {
219                return;
220            }
221            let kind = match u32::from_le_bytes([d[p], d[p + 1], d[p + 2], d[p + 3]]) {
222                0 => Ctx::Interpolation,
223                1 => Ctx::Directive,
224                2 => Ctx::Quoted,
225                _ => Ctx::Heredoc,
226            };
227            let len = u32::from_le_bytes([d[p + 4], d[p + 5], d[p + 6], d[p + 7]]) as usize;
228            p += 8;
229            let len = len.min(d.len() - p);
230            self.stack.push(Frame {
231                kind,
232                id: d[p..p + len].to_vec(),
233            });
234            p += len;
235        }
236    }
237}