Skip to main content

hexicon_compiler/
tok.rs

1//! The tokenizer: the stream of tokens the parser reads.
2//!
3//! It sits on top of the preprocessor. Each line comes through macro
4//! expansion, and its tokens are read off one at a time; when a line
5//! runs out, the next one is fetched. Keywords are told apart from other
6//! symbols here, and strings are translated: the token for a string has
7//! the string's text, with escape sequences replaced by the characters
8//! they stand for. A string with expressions embedded in it comes out as
9//! several tokens: the text before the first `<<`, then the tokens of the
10//! expression, then the text after `>>`, and so on.
11//!
12//! This is a child of the preprocessor's module because the two share
13//! the line being read.
14
15use super::{Preprocessor, Severity, show_name};
16use crate::lex::{self, LexCtx, Tok, at, count_quotes, skip_ws_and_markers};
17
18/// A token as the parser sees it.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct SrcToken {
21    /// What kind of token it is.
22    pub typ: Tok,
23    /// Its text. For a string, this is the translated contents.
24    pub text: Vec<u8>,
25    /// The value, for an integer.
26    pub int_val: u32,
27    /// The file it came from: an index for [`Preprocessor::file_name`].
28    pub file: usize,
29    /// The line it came from.
30    pub line: u32,
31    /// It is one of the tokens a Hexicon form is lowered to: while it is
32    /// the current token, the parser is at the form's place, as it is at
33    /// a macro's while it reads the macro's expansion.
34    pub lowered: bool,
35    /// Where on its line it is, when that is known for sure: the bytes of
36    /// the line as the file has it, from the first to past the last.
37    pub columns: Option<(u32, u32)>,
38}
39
40impl SrcToken {
41    pub(crate) fn new(typ: Tok) -> Self {
42        Self {
43            typ,
44            text: Vec::new(),
45            int_val: 0,
46            file: 0,
47            line: 0,
48            lowered: false,
49            columns: None,
50        }
51    }
52}
53
54/// How many characters of an unterminated string a message quotes.
55const UNTERM_SHOWN: usize = 20;
56
57impl Preprocessor<'_> {
58    /// Read tokens for the compiler proper, instead of writing out
59    /// preprocessed text: directives that are the compiler's to act on
60    /// are acted on.
61    pub fn set_compile_mode(&mut self) {
62        self.pp_only = false;
63    }
64
65    /// The token most recently read.
66    pub fn cur_token(&self) -> &SrcToken {
67        &self.cur
68    }
69
70    /// Where the current token's text ends, and whether in the
71    /// macro-expanded line or in the line itself: the reference keeps
72    /// the text of some tokens only there, until the next line is read
73    /// over it.
74    pub(crate) fn cur_token_place(&self) -> (bool, usize) {
75        (self.tok_in_expbuf, self.p)
76    }
77
78    /// Whether a line buffer holds `text` just before `end`.
79    pub(crate) fn buffer_holds(&self, in_expbuf: bool, end: usize, text: &[u8]) -> bool {
80        let buf = if in_expbuf {
81            &self.expbuf
82        } else {
83            &self.linebuf
84        };
85        end >= text.len() && buf.get(end - text.len()..end) == Some(text)
86    }
87
88    /// Read the next token. At the end of the source, the token is
89    /// [`Tok::Eof`], however often it is asked for.
90    pub fn next_token(&mut self) -> Tok {
91        self.prv = self.cur.clone();
92        if self.gave_up {
93            self.cur = SrcToken::new(Tok::Eof);
94            self.cur.int_val = self.last_int_val;
95            return Tok::Eof;
96        }
97        if let Some(token) = self.pushed.pop() {
98            self.lowered_pos = token.lowered.then_some((token.file, token.line));
99            self.cur = token;
100            return self.cur.typ;
101        }
102        self.lowered_pos = None;
103        loop {
104            let typ = self.next_on_line_xlat_keep();
105            if typ == Tok::NullTok {
106                continue;
107            }
108            if typ != Tok::Eof {
109                return typ;
110            }
111            let at_directive_end = at(self.token_buf(), self.p) == lex::END_PP_LINE;
112            if at_directive_end || self.read_line_pp() {
113                self.cur = SrcToken::new(Tok::Eof);
114                self.cur.int_val = self.last_int_val;
115                return Tok::Eof;
116            }
117        }
118    }
119
120    /// Put the current token back, to be read again, and make the one
121    /// before it current. Only one token can be put back this way.
122    pub fn unget_token(&mut self) {
123        let current = std::mem::replace(&mut self.cur, self.prv.clone());
124        self.pushed.push(current);
125        self.prv = SrcToken::new(Tok::Invalid);
126    }
127
128    /// Put the current token back, to be read again, and make a token
129    /// that was read earlier current in its place.
130    pub fn unget_to(&mut self, earlier: SrcToken) {
131        let current = std::mem::replace(&mut self.cur, earlier);
132        self.pushed.push(current);
133        self.prv = SrcToken::new(Tok::Invalid);
134    }
135
136    /// Make a token the current one, as if it had just been read.
137    pub(crate) fn replace_current(&mut self, token: SrcToken) {
138        self.cur = token;
139    }
140
141    /// Put a token in front of what is still to be read.
142    pub fn push_token(&mut self, token: SrcToken) {
143        self.pushed.push(token);
144    }
145
146    /// The text that tokens are being read from: the macro-expanded line,
147    /// or the line itself while a directive is being read.
148    fn token_buf(&self) -> &[u8] {
149        if self.tok_in_expbuf {
150            &self.expbuf
151        } else {
152            &self.linebuf
153        }
154    }
155
156    fn take_token_buf(&mut self) -> Vec<u8> {
157        if self.tok_in_expbuf {
158            std::mem::take(&mut self.expbuf)
159        } else {
160            std::mem::take(&mut self.linebuf)
161        }
162    }
163
164    fn restore_token_buf(&mut self, buf: Vec<u8>) {
165        if self.tok_in_expbuf {
166            self.expbuf = buf;
167        } else {
168            self.linebuf = buf;
169        }
170    }
171
172    fn make_token(&self, typ: Tok, text: Vec<u8>) -> SrcToken {
173        SrcToken {
174            typ,
175            text,
176            int_val: self.last_int_val,
177            file: self.last_desc.unwrap_or(0),
178            line: self.last_line,
179            lowered: false,
180            columns: None,
181        }
182    }
183
184    /// Where on its line, as the file has it, the text from `start` to
185    /// `end` of `buf` is, if that is sure: the same text at the same
186    /// place (no comment or macro before it has moved it), or else the
187    /// one place on the line it is as a whole token. Text a macro made,
188    /// or that is more than once on the line, has none.
189    fn columns_of(&self, buf: &[u8], start: usize, end: usize) -> Option<(u32, u32)> {
190        let text = buf.get(start..end)?;
191        if text.is_empty() || text.contains(&b'\n') {
192            return None;
193        }
194        let line = &self.raw_line;
195        let span = |at: usize| {
196            Some((
197                u32::try_from(at).ok()?,
198                u32::try_from(at + text.len()).ok()?,
199            ))
200        };
201        if line.get(start..end) == Some(text) {
202            return span(start);
203        }
204        let is_word = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c >= 0x80;
205        let words = text.first().is_some_and(|&c| is_word(c));
206        let mut found = (0..line.len().saturating_sub(text.len() - 1)).filter(|&at| {
207            line[at..].starts_with(text)
208                && !(words && at > 0 && is_word(line[at - 1]))
209                && !(words && line.get(at + text.len()).is_some_and(|&c| is_word(c)))
210        });
211        match (found.next(), found.next()) {
212            (Some(at), None) => span(at),
213            _ => None,
214        }
215    }
216
217    /// Read the next token on the current line into the current token.
218    /// [`Tok::Eof`] is the end of the line.
219    fn next_on_line_xlat_keep(&mut self) -> Tok {
220        loop {
221            let buf = self.take_token_buf();
222            skip_ws_and_markers(&buf, &mut self.p);
223            let c = at(&buf, self.p);
224            let next = at(&buf, self.p + 1);
225            let is_string = c == b'"'
226                || c == b'\''
227                || (c == b'>'
228                    && self.main_ec.in_expr()
229                    && self.main_ec.parens() == 0
230                    && next == b'>')
231                || (c == b'R' && (next == b'"' || next == b'\''));
232            if is_string {
233                let start = self.p;
234                let typ = self.xlat_string_to(&buf, true);
235                self.cur.columns = self.columns_of(&buf, start, self.p);
236                self.restore_token_buf(buf);
237                return typ;
238            }
239
240            let mut cx = LexCtx {
241                ec: Some(&mut self.main_ec),
242                expanding: false,
243                in_pp_expr: self.pp_expr,
244                notes: &mut self.notes,
245            };
246            let tok = lex::next_on_line(&buf, &mut self.p, &mut cx);
247            let text = tok.text(&buf).to_vec();
248            // Read from the line as its macros expanded it: where nothing
249            // before it was expanded, where the file has it.
250            let columns = self.columns_of(&buf, tok.pos, tok.pos + text.len());
251            let mut typ = tok.typ;
252            if typ == Tok::Invalid {
253                // The character after one that is not valid is skipped
254                // too, as in the reference.
255                let width = utf8_width(at(&buf, self.p));
256                if at(&buf, self.p) != 0 {
257                    self.p += width;
258                }
259            }
260            self.restore_token_buf(buf);
261            self.flush_notes();
262            match typ {
263                Tok::Sym => {
264                    if let Some(keyword) = lex::keyword(&text) {
265                        typ = keyword;
266                    }
267                }
268                Tok::Invalid => {
269                    self.report(
270                        Severity::Error,
271                        format!("invalid character in input \"{}\"", show_name(&text)),
272                    );
273                    continue;
274                }
275                _ => {}
276            }
277            if typ == Tok::Int {
278                self.last_int_val = tok.int_val;
279            }
280            self.cur = self.make_token(typ, text);
281            self.cur.columns = columns;
282            return typ;
283        }
284    }
285
286    /// Read a string, or the part of one up to an embedded expression,
287    /// or the part after one, translating it into the current token.
288    /// With `embed`, expressions embedded in the string are followed.
289    pub(super) fn xlat_string_to(&mut self, buf: &[u8], embed: bool) -> Tok {
290        let mut dst: Vec<u8> = Vec::new();
291        let mut p = self.p;
292        let mut qu = at(buf, p);
293        let mut typ = match qu {
294            b'"' => Tok::DStr,
295            b'\'' => Tok::SStr,
296            b'R' => Tok::ReStr,
297            _ if embed => end_token(self.main_ec.in_expr(), self.main_ec.quote()),
298            _ => Tok::Invalid,
299        };
300        if qu == b'R' {
301            p += 1;
302            qu = at(buf, p);
303        }
304        let mut triple = false;
305        if (qu == b'"' || qu == b'\'') && count_quotes(buf, p, qu) >= 3 {
306            p += 2;
307            triple = true;
308        }
309        p += 1;
310        if qu == b'>' && embed && self.main_ec.parens() == 0 {
311            // The end of an embedded expression: the string it is in
312            // carries on.
313            p += 1;
314            qu = self.main_ec.quote();
315            triple = self.main_ec.triple();
316            self.main_ec.end_expr();
317        }
318
319        loop {
320            let cur = at(buf, p);
321            if cur == qu {
322                if triple {
323                    let mut count = count_quotes(buf, p, qu);
324                    if count >= 3 {
325                        // Quotes before the last three are part of the
326                        // string.
327                        while count > 3 {
328                            dst.push(qu);
329                            p += 1;
330                            count -= 1;
331                        }
332                        p += 3;
333                        break;
334                    }
335                } else {
336                    p += 1;
337                    break;
338                }
339            }
340            if cur == 0 {
341                self.p = p;
342                // A string with nothing in it yet, at the end of a line
343                // that was cut off from text still to come, is a quote
344                // that belongs with that text.
345                if dst.is_empty() && qu == b'"' && !self.unsplicebuf.is_empty() {
346                    self.unsplicebuf.insert(0, b'"');
347                    return Tok::NullTok;
348                }
349                let shown: String = String::from_utf8_lossy(&dst)
350                    .chars()
351                    .take(UNTERM_SHOWN)
352                    .collect();
353                let quote = char::from(qu);
354                self.report(
355                    Severity::Error,
356                    format!(
357                        "unterminated string literal: string started with {quote}{}{quote}",
358                        show_name(shown.as_bytes())
359                    ),
360                );
361                self.cur = self.make_token(typ, dst);
362                return typ;
363            }
364            if cur == b'\\' {
365                xlat_escape(&mut dst, buf, &mut p, qu, triple);
366                continue;
367            } else if embed && typ != Tok::ReStr && cur == b'<' && at(buf, p + 1) == b'<' {
368                typ = match typ {
369                    Tok::DStr => Tok::DStrStart,
370                    Tok::DStrEnd => Tok::DStrMid,
371                    Tok::SStr => Tok::SStrStart,
372                    Tok::SStrEnd => Tok::SStrMid,
373                    other => other,
374                };
375                p += 2;
376                // "<<%fmt" is a format for the value of the expression.
377                // It becomes a token of its own, read after this one.
378                if at(buf, p) == b'%' {
379                    let start = p;
380                    lex::scan_sprintf_spec(buf, &mut p);
381                    let mut spec = Vec::new();
382                    let mut q = start;
383                    while q < p {
384                        if at(buf, q) == b'\\' {
385                            xlat_escape(&mut spec, buf, &mut q, 0, false);
386                        } else {
387                            spec.push(at(buf, q));
388                            q += 1;
389                        }
390                    }
391                    let token = self.make_token(Tok::FmtSpec, spec);
392                    self.pushed.push(token);
393                }
394                if !self.main_ec.start_expr(qu, triple) {
395                    self.report(
396                        Severity::Error,
397                        "embedded expressions in strings are nested too deeply".to_owned(),
398                    );
399                }
400                break;
401            }
402            dst.push(cur);
403            p += 1;
404        }
405        self.p = p;
406        self.cur = self.make_token(typ, dst);
407        typ
408    }
409}
410
411/// The token for the part of a string that follows an embedded
412/// expression, before it is known whether another expression follows.
413fn end_token(in_expr: bool, quote: u8) -> Tok {
414    if !in_expr {
415        Tok::Invalid
416    } else if quote == b'"' {
417        Tok::DStrEnd
418    } else {
419        Tok::SStrEnd
420    }
421}
422
423/// How many bytes the character that starts with `first` takes.
424fn utf8_width(first: u8) -> usize {
425    match first {
426        0xc0..=0xdf => 2,
427        0xe0..=0xef => 3,
428        0xf0..=0xf7 => 4,
429        _ => 1,
430    }
431}
432
433fn push_char(dst: &mut Vec<u8>, code: u32) {
434    let c = char::from_u32(code).unwrap_or('\u{fffd}');
435    dst.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
436}
437
438/// Translate the escape sequence at `p`, which is at its backslash, and
439/// leave `p` after it.
440pub(super) fn xlat_escape(dst: &mut Vec<u8>, buf: &[u8], p: &mut usize, qu: u8, triple: bool) {
441    *p += 1;
442    let mut cur = at(buf, *p);
443    match cur {
444        // Characters the output formatter takes as instructions.
445        b'^' => cur = 0x0f,
446        b'v' => cur = 0x0e,
447        b'b' => cur = 0x0b,
448        b' ' => cur = 0x15,
449        b'n' => cur = b'\n',
450        b'r' => cur = b'\r',
451        b't' => cur = b'\t',
452        b'"' | b'\'' => {
453            // In a triple-quoted string, a backslash escapes a whole run
454            // of quotes.
455            if triple && cur == qu {
456                while at(buf, *p) == qu {
457                    dst.push(cur);
458                    *p += 1;
459                }
460                return;
461            }
462        }
463        b'u' | b'x' => {
464            let most = if cur == b'u' { 4 } else { 2 };
465            *p += 1;
466            let mut acc = 0u32;
467            for _ in 0..most {
468                let Some(digit) = char::from(at(buf, *p)).to_digit(16) else {
469                    break;
470                };
471                acc = 16 * acc + digit;
472                *p += 1;
473            }
474            push_char(dst, acc);
475            return;
476        }
477        b'0'..=b'7' => {
478            let mut acc = 0u32;
479            for _ in 0..3 {
480                let c = at(buf, *p);
481                if !(b'0'..=b'7').contains(&c) || 8 * acc + u32::from(c - b'0') > 255 {
482                    break;
483                }
484                acc = 8 * acc + u32::from(c - b'0');
485                *p += 1;
486            }
487            push_char(dst, acc);
488            return;
489        }
490        b'<' | b'>' | b'\\' => {}
491        0 => return,
492        _ => {
493            // Not an escape the language has: the backslash stays.
494            dst.push(b'\\');
495        }
496    }
497    if cur.is_ascii() {
498        dst.push(cur);
499        *p += 1;
500    } else {
501        // A character of several bytes after the backslash: all of it.
502        let width = utf8_width(cur);
503        for _ in 0..width {
504            if at(buf, *p) != 0 {
505                dst.push(at(buf, *p));
506                *p += 1;
507            }
508        }
509    }
510}
511
512/// What the parser needs besides tokens: where it is, and somewhere to
513/// report problems.
514impl Preprocessor<'_> {
515    /// The file and line of the token most recently read.
516    pub(crate) fn last_pos(&self) -> (usize, u32) {
517        self.lowered_pos
518            .unwrap_or((self.last_desc.unwrap_or(0), self.last_line))
519    }
520
521    /// Report an error at the current position.
522    pub(crate) fn log_error(&mut self, message: impl Into<String>) {
523        self.error(message);
524    }
525
526    /// Report a warning at the current position.
527    pub(crate) fn log_warning(&mut self, message: impl Into<String>) {
528        self.warning(message);
529    }
530
531    /// Report a problem at a line, with a note, showing a run of lines.
532    pub(crate) fn log_noted(
533        &mut self,
534        line: u32,
535        message: String,
536        note: String,
537        lines: (u32, u32),
538    ) {
539        let file = self.file_name(self.last_desc.unwrap_or(0)).to_owned();
540        self.push_diagnostic(super::Diagnostic {
541            file,
542            line,
543            severity: Severity::Error,
544            message,
545            note: Some(note),
546            lines: Some(lines),
547            ..Default::default()
548        });
549    }
550
551    /// Report a warning at a line of the current file, with a note.
552    pub(crate) fn log_warning_noted(&mut self, line: u32, message: String, note: String) {
553        let file = self.file_name(self.last_desc.unwrap_or(0)).to_owned();
554        self.push_diagnostic(super::Diagnostic {
555            file,
556            line,
557            severity: Severity::Warning,
558            message,
559            note: Some(note),
560            ..Default::default()
561        });
562    }
563
564    /// Report a problem at a given position.
565    pub(crate) fn log_at(&mut self, file: usize, line: u32, severity: Severity, message: String) {
566        let file = self.file_name(file).to_owned();
567        self.push_diagnostic(super::Diagnostic {
568            file,
569            line,
570            severity,
571            message,
572            ..Default::default()
573        });
574    }
575
576    /// The current token as a message shows it.
577    pub(crate) fn cur_token_shown(&self) -> String {
578        let text = String::from_utf8_lossy(&self.cur.text);
579        let quoted = |before: &str, after: &str| {
580            // The first twenty characters, with control characters
581            // written out, and a mark if there are more.
582            let mut shown = String::from(before);
583            let mut chars = text.chars();
584            for c in chars.by_ref().take(20) {
585                let code = u32::from(c);
586                if code >= 32 {
587                    shown.push(c);
588                    continue;
589                }
590                shown.push('\\');
591                match code {
592                    10 => shown.push('n'),
593                    13 => shown.push('r'),
594                    0x0f => shown.push('^'),
595                    0x0e => shown.push('v'),
596                    0x0b => shown.push('b'),
597                    0x15 => shown.push(' '),
598                    9 => shown.push('t'),
599                    _ => {
600                        // The reference means to give the code in
601                        // hexadecimal, but adds the digit zero to what
602                        // is already a digit.
603                        shown.push('x');
604                        for shift in [12, 8, 4, 0] {
605                            let nibble = (code >> shift) & 0xf;
606                            let digit = if nibble < 10 {
607                                u32::from(b'0') + nibble
608                            } else {
609                                u32::from(b'A') + nibble - 10
610                            };
611                            shown.push(char::from_u32(u32::from(b'0') + digit).unwrap_or('?'));
612                        }
613                    }
614                }
615            }
616            if chars.next().is_some() {
617                shown.push_str("...");
618            }
619            shown.push_str(after);
620            shown
621        };
622        let shown = match self.cur.typ {
623            Tok::Eof => "<End Of File>".to_owned(),
624            Tok::SStr => quoted("'", "'"),
625            Tok::DStr => quoted("\"", "\""),
626            Tok::DStrStart => quoted("\"", "<<"),
627            Tok::DStrMid => quoted(">>", "<<"),
628            Tok::DStrEnd => quoted(">>", "\""),
629            Tok::ReStr => quoted("R'", "'"),
630            _ => text.into_owned(),
631        };
632        show_name(shown.as_bytes())
633    }
634}