Skip to main content

hexicon_compiler/
pp.rs

1//! The preprocessor: source files in, lines of preprocessed text out.
2//!
3//! This follows the reference compiler's preprocessor step for step,
4//! because what a macro expands to is something a program's author sees
5//! and depends on, down to the spacing. Where the reference does
6//! something surprising, so does this, and a comment says so.
7//!
8//! The reference keeps a line as text that ends at a zero byte, with a
9//! separate count of how long it is, and the two can disagree: cutting a
10//! line short at a `//` comment writes the zero and leaves the count
11//! alone. Text spliced on afterward goes after the count, where anything
12//! that reads up to the zero never sees it. The line buffer here is kept
13//! the same way, so a zero byte inside it ends the text for every reader
14//! that the reference has reading up to a zero.
15
16use std::collections::HashMap;
17
18use crate::lex::{
19    self, ARGCOUNT_FLAG, EmbedCtx, FOREACH_FLAG, FORMAL_FLAG, FULLY_EXPANDED_FLAG, IFEMPTY_FLAG,
20    IFNEMPTY_FLAG, LexCtx, LexNote, MACRO_EXP_END, MACRO_ID_LEN, Tok, Token, at, count_quotes,
21    is_space, is_sym,
22};
23
24#[path = "tok.rs"]
25mod tok;
26
27pub use tok::SrcToken;
28
29/// The most arguments a macro can have.
30const MAX_MACRO_ARGS: usize = 128;
31/// The deepest `#if` blocks can nest.
32const MAX_IF_NESTING: usize = 100;
33/// The deepest `#foreach`, `#ifempty`, and `#ifnempty` can nest in a
34/// macro's expansion.
35const MAX_FOREACH_NESTING: usize = 10;
36
37/// How the preprocessor gets at source files.
38pub trait SourceFiles {
39    /// The contents of a file, or `None` if it cannot be read.
40    fn read(&mut self, name: &str) -> Option<Vec<u8>>;
41    /// Whether a file is there to be read.
42    fn exists(&mut self, name: &str) -> bool;
43
44    /// Text in a named character set, as UTF-8, or `None` if the set is
45    /// not known. The compiler knows ASCII, UTF-8, UTF-16, and Latin-1
46    /// itself, and asks here for any other that a source file's
47    /// `#charset` names.
48    fn decode(&mut self, charset: &str, bytes: &[u8]) -> Option<Vec<u8>> {
49        let _ = (charset, bytes);
50        None
51    }
52}
53
54/// How serious a problem is.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Severity {
57    /// The program is still compiled.
58    Warning,
59    /// The program cannot be compiled.
60    Error,
61    /// Not a problem: text the source asked to be shown while it is
62    /// compiled, with `#pragma message`.
63    Message,
64    /// The compiler has given up: nothing is read or reported after
65    /// this.
66    Fatal,
67    /// The compiler could not do what the source asks, and the program
68    /// cannot be compiled, though the source may have nothing wrong
69    /// with it that the language forbids.
70    Internal,
71}
72
73/// How many errors are reported before the compiler gives up.
74pub(crate) const MAX_ERRORS: usize = 100;
75
76/// What is said on giving up.
77pub(crate) const TOO_MANY_ERRORS: &str =
78    "too many errors (try fixing the first couple of errors and recompiling)";
79
80/// The library a line imports, if it is `import name;` and nothing else.
81fn import_line(line: &[u8]) -> Option<String> {
82    let rest = line.trim_ascii().strip_prefix(b"import")?;
83    if !rest.first().is_some_and(|c| c.is_ascii_whitespace()) {
84        return None;
85    }
86    let rest = rest.trim_ascii_start().strip_suffix(b";")?.trim_ascii_end();
87    let valid =
88        rest.first().is_some_and(|&c| crate::lex::is_syminit(c)) && rest.iter().all(|&c| is_sym(c));
89    valid.then(|| String::from_utf8_lossy(rest).into_owned())
90}
91
92/// A problem found in the source.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct Diagnostic {
95    /// The file the problem is in, as the source named it.
96    pub file: String,
97    /// The line in that file.
98    pub line: u32,
99    /// Whether it stops the program being compiled.
100    pub severity: Severity,
101    /// What is wrong.
102    pub message: String,
103    /// More about it, said below it: in a Hexicon source, what to look
104    /// at.
105    pub note: Option<String>,
106    /// The lines of the source to show with it, first and last; with
107    /// none, the line it is on.
108    pub lines: Option<(u32, u32)>,
109    /// It is in a Hexicon source, and said in Hexicon's words (see
110    /// [`crate::wording`]), and shown with the source.
111    pub hexicon: bool,
112    /// Where on its line it is, when that is known for sure: the bytes of
113    /// the line as the file has it, from the first to past the last. A
114    /// problem found at a token has the token's.
115    pub columns: Option<(u32, u32)>,
116}
117
118impl Default for Diagnostic {
119    fn default() -> Self {
120        Self {
121            file: String::new(),
122            line: 0,
123            severity: Severity::Error,
124            message: String::new(),
125            note: None,
126            lines: None,
127            hexicon: false,
128            columns: None,
129        }
130    }
131}
132
133/// A line of preprocessed text and where it came from.
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct Line {
136    /// The text, without a line ending.
137    pub text: Vec<u8>,
138    /// Which file it came from: an index for [`Preprocessor::file_name`].
139    pub file: usize,
140    /// The number of the line in that file.
141    pub line: u32,
142}
143
144/// What a newline inside a string turns into.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146enum NewlineSpacing {
147    /// The newline and the spaces after it become one space.
148    Collapse,
149    /// They vanish.
150    Delete,
151    /// They stay.
152    Preserve,
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156enum IfState {
157    /// In an `#if` whose condition was true.
158    IfYes,
159    /// In an `#if` whose condition was false, with no branch taken yet.
160    IfNo,
161    /// In an `#elif` after a branch that was taken.
162    IfDone,
163    /// In the `#else` of an `#if` that was false throughout.
164    ElseYes,
165    /// In the `#else` of an `#if` that had a true branch.
166    ElseNo,
167}
168
169#[derive(Debug, Clone, Copy)]
170struct IfLevel {
171    state: IfState,
172    desc: usize,
173    line: u32,
174}
175
176/// A source file as the program knows it.
177#[derive(Debug, Clone)]
178struct FileDesc {
179    /// The name the file was opened by.
180    name: String,
181    /// The name without the folder.
182    root: String,
183}
184
185/// A source file being read.
186#[derive(Debug)]
187struct Stream {
188    desc: usize,
189    /// The file's text as UTF-8.
190    data: Vec<u8>,
191    pos: usize,
192    /// The number of the next line to be read.
193    next_line: u32,
194    in_comment: bool,
195    /// How many `#if` levels were open when the file was started; it
196    /// cannot close those.
197    init_if_level: usize,
198    /// The spacing mode to go back to when a file this one includes ends.
199    newline_spacing: NewlineSpacing,
200    /// The file names a character set that is not known.
201    charset_error: bool,
202}
203
204impl Stream {
205    /// The next line of the file, with a newline on the end unless the
206    /// file ends without one. `None` at the end of the file.
207    fn read_raw_line(&mut self) -> Option<Vec<u8>> {
208        if self.pos >= self.data.len() {
209            return None;
210        }
211        let data = &self.data;
212        let start = self.pos;
213        let mut i = start;
214        while i < data.len() {
215            let c = data[i];
216            // A line ends at a newline, a return, or a line separator
217            // (U+2028); a newline and a return together are one ending.
218            if c == b'\n' || c == b'\r' {
219                let mut line = data[start..i].to_vec();
220                line.push(b'\n');
221                i += 1;
222                if i < data.len() && (data[i] == b'\n' || data[i] == b'\r') && data[i] != c {
223                    i += 1;
224                }
225                self.pos = i;
226                return Some(line);
227            }
228            if c == 0xe2 && data.get(i + 1) == Some(&0x80) && data.get(i + 2) == Some(&0xa8) {
229                let mut line = data[start..i].to_vec();
230                line.push(b'\n');
231                self.pos = i + 3;
232                return Some(line);
233            }
234            i += 1;
235        }
236        self.pos = data.len();
237        Some(data[start..].to_vec())
238    }
239}
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242enum MacroKind {
243    /// An ordinary `#define`.
244    Define,
245    /// `__LINE__`.
246    Line,
247    /// `__FILE__`.
248    File,
249}
250
251/// A macro.
252#[derive(Debug, Clone)]
253struct Macro {
254    name: Vec<u8>,
255    kind: MacroKind,
256    /// Defined with a parameter list, even an empty one.
257    has_args: bool,
258    argc: usize,
259    has_varargs: bool,
260    /// The expansion, with the parameters replaced by markers.
261    expansion: Vec<u8>,
262    /// The expansion as the source wrote it, and the parameters' names,
263    /// for the program's table of macros.
264    orig: Vec<u8>,
265    params: Vec<Vec<u8>>,
266}
267
268/// A macro as the program's table of macros has it, which a program can
269/// ask for when it is run before its image is written.
270#[derive(Debug, Clone, PartialEq, Eq)]
271pub struct LinkMacro {
272    /// The macro's name.
273    pub name: Vec<u8>,
274    /// Defined with a parameter list, even an empty one.
275    pub has_args: bool,
276    /// The last parameter stands for any number of arguments.
277    pub has_varargs: bool,
278    /// The parameters' names.
279    pub params: Vec<Vec<u8>>,
280    /// The expansion as the source wrote it.
281    pub expansion: Vec<u8>,
282}
283
284impl Macro {
285    fn min_argc(&self) -> usize {
286        if self.has_varargs {
287            self.argc.saturating_sub(1)
288        } else {
289            self.argc
290        }
291    }
292}
293
294/// One level of `#foreach`, `#ifempty`, or `#ifnempty` being expanded.
295#[derive(Debug, Clone, Copy)]
296struct ExpandLevel {
297    typ: Tok,
298    is_iterator: bool,
299    delim: u8,
300    /// Where the part that is repeated starts.
301    start: usize,
302    /// Which of the variable arguments is being substituted.
303    arg: usize,
304    part: u32,
305}
306
307/// The preprocessor.
308pub struct Preprocessor<'a> {
309    files: &'a mut dyn SourceFiles,
310    descs: Vec<FileDesc>,
311    streams: Vec<Stream>,
312    include_paths: Vec<String>,
313    /// Files not to be included again.
314    include_once: Vec<String>,
315    all_once: bool,
316    /// `#pragma sourceTextGroup` has said to turn the source text groups
317    /// on or off since the parser last asked.
318    src_group_change: Option<bool>,
319
320    macros: Vec<Macro>,
321    /// The names that were ever undefined, or defined anew in a
322    /// different way: the reference keeps these out of its object file.
323    undefs: std::collections::HashSet<Vec<u8>>,
324    defines: HashMap<Vec<u8>, usize>,
325
326    /// The line being worked on. See the note at the top of the file on
327    /// zero bytes.
328    linebuf: Vec<u8>,
329    /// The first line of what is in `linebuf`, as the file has it,
330    /// before its comments are taken out and its macros expanded: where
331    /// a token's columns are found.
332    raw_line: Vec<u8>,
333    /// Where reading has got to in the line.
334    p: usize,
335    /// The macro-expanded line.
336    expbuf: Vec<u8>,
337    /// A macro whose name stands where an object's name goes in the line
338    /// being read (`stop: Fixture ...`, with `stop` a macro), and what it
339    /// stands for: the first error on the line says so.
340    macro_as_name: Option<(Vec<u8>, Vec<u8>)>,
341    /// Text read ahead and put back, to be the next line.
342    unsplicebuf: Vec<u8>,
343    curtok: Token,
344
345    /// The quote of a string that is open at the end of what has been
346    /// read, or zero.
347    in_quote: u8,
348    in_triple: bool,
349    /// Embedded expressions, as comment removal follows them.
350    comment_ec: EmbedCtx,
351    /// Embedded expressions, as macro expansion follows them.
352    macro_ec: EmbedCtx,
353    newline_spacing: NewlineSpacing,
354
355    if_stack: Vec<IfLevel>,
356    /// How many `#if` levels are nested inside one that is not being
357    /// compiled.
358    if_false_level: usize,
359
360    last_desc: Option<usize>,
361    last_line: u32,
362    /// The value of the last integer token read. The reference never
363    /// clears a token's integer value, so every token after has it.
364    last_int_val: u32,
365    appended_desc: Option<usize>,
366    appended_line: u32,
367
368    /// Shared by every expansion in progress, as in the reference, where
369    /// it is static: a macro expanded inside an argument of another
370    /// starts it over.
371    expand_stack: Vec<ExpandLevel>,
372
373    /// Only preprocessing: directives that the compiler proper would act
374    /// on are passed through.
375    pp_only: bool,
376    /// Tokens are read from the macro-expanded line, not the line buffer.
377    tok_in_expbuf: bool,
378    /// Embedded expressions, as the tokenizer follows them.
379    main_ec: EmbedCtx,
380    /// The token most recently read, and the one before it.
381    cur: SrcToken,
382    prv: SrcToken,
383    /// Tokens put back to be read again, the next one last.
384    pushed: Vec<SrcToken>,
385    /// Name files by their names without folders, so that output is the
386    /// same wherever the files are.
387    test_report: bool,
388    notes: Vec<LexNote>,
389    diagnostics: Vec<Diagnostic>,
390    /// How many of the problems found were errors.
391    errors: usize,
392    /// So many errors were found that nothing more is read.
393    gave_up: bool,
394    /// The character set of a source file that does not say what it is
395    /// in.
396    default_charset: String,
397    /// Tokens are being read for the expression of a directive, which
398    /// changes what some problems are reported as.
399    pp_expr: bool,
400    /// The libraries a Hexicon source can import, with their headers.
401    imports: Vec<(String, Option<String>)>,
402    /// The libraries imported already: importing one again is nothing.
403    imported: Vec<String>,
404    /// While the current token is one a Hexicon form was lowered to,
405    /// the form's place: see [`SrcToken::lowered`].
406    lowered_pos: Option<(usize, u32)>,
407}
408
409impl<'a> Preprocessor<'a> {
410    /// A preprocessor that reads files through `files`.
411    pub fn new(files: &'a mut dyn SourceFiles) -> Self {
412        let mut pp = Self {
413            files,
414            descs: Vec::new(),
415            streams: Vec::new(),
416            include_paths: Vec::new(),
417            include_once: Vec::new(),
418            all_once: false,
419            src_group_change: None,
420            macros: Vec::new(),
421            undefs: std::collections::HashSet::new(),
422            defines: HashMap::new(),
423            linebuf: Vec::new(),
424            raw_line: Vec::new(),
425            p: 0,
426            expbuf: Vec::new(),
427            macro_as_name: None,
428            unsplicebuf: Vec::new(),
429            curtok: Token::new(Tok::Eof),
430            in_quote: 0,
431            in_triple: false,
432            comment_ec: EmbedCtx::default(),
433            macro_ec: EmbedCtx::default(),
434            newline_spacing: NewlineSpacing::Collapse,
435            if_stack: Vec::new(),
436            if_false_level: 0,
437            last_desc: None,
438            last_line: 0,
439            last_int_val: 0,
440            appended_desc: None,
441            appended_line: 0,
442            expand_stack: Vec::new(),
443            pp_only: true,
444            tok_in_expbuf: false,
445            main_ec: EmbedCtx::default(),
446            cur: SrcToken::new(Tok::Invalid),
447            prv: SrcToken::new(Tok::Invalid),
448            pushed: Vec::new(),
449            test_report: false,
450            notes: Vec::new(),
451            diagnostics: Vec::new(),
452            errors: 0,
453            gave_up: false,
454            default_charset: "utf-8".to_owned(),
455            pp_expr: false,
456            imports: Vec::new(),
457            imported: Vec::new(),
458            lowered_pos: None,
459        };
460        pp.add_special(b"__LINE__", MacroKind::Line);
461        pp.add_special(b"__FILE__", MacroKind::File);
462        pp
463    }
464
465    /// A preprocessor whose only input is the expression of a directive,
466    /// its macros already expanded, for the compiler's parser to read as
467    /// the reference has it do: the tokens of `text`, then the end of
468    /// the directive, which reads as the end of the source.
469    pub(crate) fn for_directive_expr(files: &'a mut dyn SourceFiles, text: &[u8]) -> Self {
470        let mut pp = Self::new(files);
471        pp.pp_only = false;
472        pp.pp_expr = true;
473        pp.expbuf = text.to_vec();
474        pp.expbuf.push(lex::END_PP_LINE);
475        pp.tok_in_expbuf = true;
476        pp
477    }
478
479    /// Name files without their folders in `__FILE__` and in messages.
480    pub fn set_test_report_mode(&mut self, on: bool) {
481        self.test_report = on;
482    }
483
484    /// The libraries a Hexicon source can import (`import hexad;`), each
485    /// with the header importing it gives, if it has one.
486    pub fn set_imports(&mut self, imports: Vec<(String, Option<String>)>) {
487        self.imports = imports;
488    }
489
490    /// Set the character set of source files that do not say what they
491    /// are in, with a byte order mark or `#charset`. It is UTF-8 unless
492    /// this is called.
493    pub fn set_default_charset(&mut self, name: &str) {
494        name.clone_into(&mut self.default_charset);
495    }
496
497    /// Add a folder to look for included files in.
498    pub fn add_include_path(&mut self, path: &str) {
499        self.include_paths.push(path.to_owned());
500    }
501
502    /// Define a macro without parameters.
503    pub fn define(&mut self, name: &str, expansion: &str) {
504        let id = self.macros.len();
505        self.macros.push(Macro {
506            name: name.as_bytes().to_vec(),
507            kind: MacroKind::Define,
508            has_args: false,
509            argc: 0,
510            has_varargs: false,
511            expansion: expansion.as_bytes().to_vec(),
512            orig: expansion.as_bytes().to_vec(),
513            params: Vec::new(),
514        });
515        self.defines.insert(name.as_bytes().to_vec(), id);
516    }
517
518    /// Define a macro as the program's table of macros has it, with its
519    /// parameters, for code compiled while the program runs.
520    pub fn define_macro(&mut self, mac: &LinkMacro) {
521        let expansion = self.parse_expansion(&mac.expansion, &mac.params, mac.has_varargs);
522        let id = self.macros.len();
523        self.macros.push(Macro {
524            name: mac.name.clone(),
525            kind: MacroKind::Define,
526            has_args: mac.has_args,
527            argc: mac.params.len(),
528            has_varargs: mac.has_varargs,
529            expansion,
530            orig: mac.expansion.clone(),
531            params: mac.params.clone(),
532        });
533        self.defines.insert(mac.name.clone(), id);
534    }
535
536    /// Remove a macro's definition.
537    pub fn undefine(&mut self, name: &str) {
538        self.undefine_bytes(name.as_bytes());
539    }
540
541    fn add_special(&mut self, name: &[u8], kind: MacroKind) {
542        let id = self.macros.len();
543        self.macros.push(Macro {
544            name: name.to_vec(),
545            kind,
546            has_args: false,
547            argc: 0,
548            has_varargs: false,
549            expansion: Vec::new(),
550            orig: Vec::new(),
551            params: Vec::new(),
552        });
553        self.defines.insert(name.to_vec(), id);
554    }
555
556    /// Start reading a source file. Returns false if it cannot be read.
557    pub fn set_source(&mut self, name: &str) -> bool {
558        let Some(data) = self.files.read(name) else {
559            return false;
560        };
561        let desc = self.file_desc(name);
562        let (data, charset_error) = decode_source(&data, self.files, &self.default_charset);
563        self.streams.push(Stream {
564            desc,
565            data,
566            pos: 0,
567            next_line: 1,
568            in_comment: false,
569            init_if_level: self.if_stack.len(),
570            newline_spacing: self.newline_spacing,
571            charset_error,
572        });
573        true
574    }
575
576    /// The name of a file that a [`Line`] came from. In test report mode
577    /// it is the name without the folder.
578    pub fn file_name(&self, file: usize) -> &str {
579        match self.descs.get(file) {
580            Some(desc) if self.test_report => &desc.root,
581            Some(desc) => &desc.name,
582            None => "",
583        }
584    }
585
586    /// How many errors have been found so far.
587    pub(crate) fn error_count(&self) -> usize {
588        self.errors
589    }
590
591    /// Whether so many errors have been found that nothing more is
592    /// read: from then on the source is at its end.
593    pub fn gave_up(&self) -> bool {
594        self.gave_up
595    }
596
597    /// Record a problem. One error too many is the last thing recorded.
598    pub(crate) fn push_diagnostic(&mut self, mut diagnostic: Diagnostic) {
599        if self.gave_up {
600            return;
601        }
602        // Found at the current token, it is where the token is.
603        if diagnostic.columns.is_none()
604            && diagnostic.lines.is_none()
605            && diagnostic.line == self.cur.line
606            && diagnostic.line != 0
607            && diagnostic.file == self.file_name(self.cur.file)
608        {
609            diagnostic.columns = self.cur.columns;
610        }
611        let is_error = diagnostic.severity == Severity::Error;
612        self.diagnostics.push(diagnostic);
613        if is_error {
614            self.errors += 1;
615            if self.errors > MAX_ERRORS {
616                let file = self
617                    .last_desc
618                    .map(|desc| self.file_name(desc).to_owned())
619                    .unwrap_or_default();
620                self.diagnostics.push(Diagnostic {
621                    file,
622                    line: self.last_line,
623                    severity: Severity::Fatal,
624                    message: TOO_MANY_ERRORS.to_owned(),
625                    ..Default::default()
626                });
627                self.gave_up = true;
628            }
629        }
630    }
631
632    /// Take the problems found so far.
633    pub fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
634        std::mem::take(&mut self.diagnostics)
635    }
636
637    /// The next line of preprocessed text, or `None` at the end of the
638    /// source. There is a line of output, possibly empty, for each line
639    /// of the source.
640    pub fn next_line(&mut self) -> Option<Line> {
641        if self.gave_up || self.read_line_pp() || self.gave_up {
642            return None;
643        }
644        // The text ends at the first zero byte: see the note at the top.
645        let end = self
646            .linebuf
647            .iter()
648            .position(|&c| c == 0)
649            .unwrap_or(self.linebuf.len());
650        Some(Line {
651            text: self.linebuf[..end].to_vec(),
652            file: self.last_desc.unwrap_or(0),
653            line: self.last_line,
654        })
655    }
656
657    // ---- files ----
658
659    /// The files it reads through, lent: to read what else is wanted of
660    /// them while it is in use.
661    pub fn files(&mut self) -> &mut dyn SourceFiles {
662        &mut *self.files
663    }
664
665    /// The names of the files read, by their numbers.
666    pub fn file_names(&self) -> Vec<String> {
667        self.descs.iter().map(|desc| desc.name.clone()).collect()
668    }
669
670    fn file_desc(&mut self, name: &str) -> usize {
671        if let Some(index) = self.descs.iter().position(|desc| desc.name == name) {
672            return index;
673        }
674        self.descs.push(FileDesc {
675            name: name.to_owned(),
676            root: root_name(name).to_owned(),
677        });
678        self.descs.len() - 1
679    }
680
681    /// A file's name as a string in single quotes, for `__FILE__`.
682    fn quoted_file_name(&self, desc: usize) -> Vec<u8> {
683        let name = self.file_name(desc);
684        let mut out = vec![b'\''];
685        for &c in name.as_bytes() {
686            if c == b'\\' || c == b'\'' {
687                out.push(b'\\');
688            }
689            out.push(c);
690        }
691        out.push(b'\'');
692        out
693    }
694
695    // ---- problems ----
696
697    fn report(&mut self, severity: Severity, message: String) {
698        let file = self
699            .last_desc
700            .map(|desc| self.file_name(desc).to_owned())
701            .unwrap_or_default();
702        // An object named with a macro's name: the first error says why.
703        let note = if severity == Severity::Error {
704            self.macro_as_name.take().map(|(name, orig)| {
705                format!(
706                    "\"{}\" is a macro, which stands for \"{}\", so it cannot be an object's \
707                     name: give the object a name of its own",
708                    show_name(&name),
709                    String::from_utf8_lossy(&orig).trim()
710                )
711            })
712        } else {
713            None
714        };
715        self.push_diagnostic(Diagnostic {
716            file,
717            line: self.last_line,
718            severity,
719            message,
720            note,
721            ..Default::default()
722        });
723    }
724
725    fn error(&mut self, message: impl Into<String>) {
726        self.report(Severity::Error, message.into());
727    }
728
729    fn warning(&mut self, message: impl Into<String>) {
730        self.report(Severity::Warning, message.into());
731    }
732
733    /// Report what the scanner noticed.
734    fn flush_notes(&mut self) {
735        for note in std::mem::take(&mut self.notes) {
736            let text = show_name;
737            match note {
738                LexNote::DecimalInOctal(number) => self.error(format!(
739                    "decimal digit found in octal constant \"{}\"",
740                    text(&number)
741                )),
742                LexNote::NonAsciiSymbol(symbol) => {
743                    let name = text(&symbol);
744                    let odd = String::from_utf8_lossy(&symbol)
745                        .chars()
746                        .find(|c| !c.is_ascii())
747                        .map_or(0, u32::from);
748                    self.error(format!(
749                        "the name \"{name}\" contains non-ASCII character (U+{odd:04x})"
750                    ));
751                }
752                LexNote::SymbolTruncated(symbol) => {
753                    let kept = lex::SYM_MAX_LEN - 1;
754                    self.warning(format!(
755                        "the name \"{}\" truncated to \"{}\"",
756                        text(&symbol),
757                        text(&symbol[..kept.min(symbol.len())])
758                    ));
759                }
760                LexNote::EmbeddingTooDeep => {
761                    self.error("embedded expressions in strings are nested too deeply");
762                }
763                LexNote::UntermString => {
764                    self.error("unterminated string in preprocessor constant expression");
765                }
766            }
767        }
768    }
769
770    // ---- reading tokens ----
771
772    /// The next token of the current line, for reading a directive.
773    /// Embedded expressions are not followed.
774    fn next_on_line(&mut self) -> Tok {
775        let mut cx = LexCtx {
776            ec: None,
777            expanding: false,
778            in_pp_expr: false,
779            notes: &mut self.notes,
780        };
781        self.curtok = lex::next_on_line(&self.linebuf, &mut self.p, &mut cx);
782        self.flush_notes();
783        self.curtok.typ
784    }
785
786    fn curtok_text(&self) -> Vec<u8> {
787        self.curtok.text(&self.linebuf).to_vec()
788    }
789
790    /// The next token of `src`, for macro expansion. With a `limit`, the
791    /// text is only that long, though a token that starts within it can
792    /// run past, as it can in the reference.
793    fn next_tok(
794        &mut self,
795        src: &[u8],
796        limit: Option<usize>,
797        pos: &mut usize,
798        expanding: bool,
799    ) -> Token {
800        let old_ec = self.macro_ec;
801        let mut cx = LexCtx {
802            ec: Some(&mut self.macro_ec),
803            expanding,
804            in_pp_expr: false,
805            notes: &mut self.notes,
806        };
807        let mut tok = lex::next_on_line(src, pos, &mut cx);
808        if let Some(end) = limit.or(Some(src.len()))
809            && tok.pos >= end
810        {
811            tok = Token::new(Tok::Eof);
812            tok.pos = end;
813            self.macro_ec = old_ec;
814        }
815        self.flush_notes();
816        tok
817    }
818
819    /// The next token of a macro's stored expansion, which ends where its
820    /// text does.
821    fn next_exp_tok(&mut self, exp: &[u8], pos: &mut usize) -> Token {
822        let mut cx = LexCtx {
823            ec: Some(&mut self.macro_ec),
824            expanding: true,
825            in_pp_expr: false,
826            notes: &mut self.notes,
827        };
828        let tok = lex::next_on_line(exp, pos, &mut cx);
829        self.flush_notes();
830        tok
831    }
832
833    // ---- lines ----
834
835    fn clear_linebuf(&mut self) {
836        self.linebuf.clear();
837        self.p = 0;
838        self.tok_in_expbuf = false;
839    }
840
841    fn in_false_if(&self) -> bool {
842        match self.if_stack.last() {
843            None => false,
844            Some(level) => {
845                self.if_false_level != 0
846                    || matches!(
847                        level.state,
848                        IfState::IfNo | IfState::IfDone | IfState::ElseNo
849                    )
850            }
851        }
852    }
853
854    fn push_if(&mut self, state: IfState) {
855        if self.if_stack.len() >= MAX_IF_NESTING {
856            self.error("#if nesting too deep");
857            return;
858        }
859        if self.in_false_if() {
860            self.if_false_level += 1;
861        }
862        self.if_stack.push(IfLevel {
863            state,
864            desc: self.last_desc.unwrap_or(0),
865            line: self.last_line,
866        });
867    }
868
869    fn pop_if(&mut self) {
870        self.if_false_level = self.if_false_level.saturating_sub(1);
871        self.if_stack.pop();
872    }
873
874    /// Read a line of source into the line buffer, or onto the end of
875    /// what is there. Lines that end in a backslash are joined, and
876    /// comments are taken out. Returns where the new text starts, or
877    /// `None` at the end of all the source.
878    fn read_line(&mut self, append: bool) -> Option<usize> {
879        self.streams.last()?;
880        if !append {
881            self.clear_linebuf();
882            let stream = self.streams.last()?;
883            self.last_desc = Some(stream.desc);
884            self.last_line = stream.next_line;
885        }
886        let start_len = self.linebuf.len();
887
888        // Text that was read ahead and put back is the next line. It has
889        // been through all of this already.
890        if !self.unsplicebuf.is_empty() {
891            let text = std::mem::take(&mut self.unsplicebuf);
892            if !append {
893                self.raw_line.clone_from(&text);
894            }
895            self.linebuf.extend_from_slice(&text);
896            self.last_desc = self.appended_desc;
897            self.last_line = self.appended_line;
898            return Some(start_len);
899        }
900
901        if append {
902            let stream = self.streams.last()?;
903            self.appended_desc = Some(stream.desc);
904            self.appended_line = stream.next_line;
905        }
906
907        loop {
908            let stream = self.streams.last_mut()?;
909            let Some(text) = stream.read_raw_line() else {
910                // The file ended. If it ended in the middle of a line,
911                // that is the line.
912                if self.linebuf.len() > start_len {
913                    break;
914                }
915                // An #if that the file opened and did not close.
916                let init_level = stream.init_if_level;
917                while self.if_stack.len() > init_level {
918                    let level = self.if_stack[self.if_stack.len() - 1];
919                    let name = self.file_name(level.desc).to_owned();
920                    self.error(format!(
921                        "#if without #endif (line {}, file {})",
922                        level.line, name
923                    ));
924                    self.pop_if();
925                }
926                self.streams.pop();
927                let stream = self.streams.last()?;
928                if !append {
929                    self.last_desc = Some(stream.desc);
930                    self.last_line = stream.next_line;
931                }
932                self.newline_spacing = stream.newline_spacing;
933                continue;
934            };
935            if !append && self.linebuf.len() == start_len {
936                let end = text
937                    .iter()
938                    .rposition(|&c| c != b'\n' && c != b'\r')
939                    .map_or(0, |at| at + 1);
940                self.raw_line = text[..end].to_vec();
941            }
942            self.linebuf.extend_from_slice(&text);
943            let len = self.linebuf.len();
944            if len != 0 && self.linebuf[len - 1] != b'\n' {
945                // The last line of a file, with no newline: the next read
946                // finds the end of the file.
947            } else if len > 1 && self.linebuf[len - 2] == b'\\' {
948                self.linebuf.truncate(len - 2);
949                stream.next_line += 1;
950            } else {
951                if len != 0 {
952                    self.linebuf.truncate(len - 1);
953                }
954                stream.next_line += 1;
955                break;
956            }
957        }
958
959        self.process_comments(start_len);
960        Some(start_len)
961    }
962
963    /// Break the line at `at`: what comes after it is put back to be read
964    /// as the next line.
965    fn unsplice_line(&mut self, at: usize) {
966        let at = at.min(self.linebuf.len());
967        let mut rest = self.linebuf[at..].to_vec();
968        rest.extend_from_slice(&self.unsplicebuf);
969        self.unsplicebuf = rest;
970        self.linebuf.truncate(at);
971    }
972
973    /// Take the comments out of the line from `start` on, leaving a space
974    /// for each, and keep track of whether the text ends inside a string.
975    fn process_comments(&mut self, start: usize) {
976        let mut trailing_sp_after_bs = false;
977        let mut src = start;
978        let mut dst = start;
979        let mut in_comment = self.streams.last().is_some_and(|s| s.in_comment);
980        let mut nested_warning = false;
981        let mut cut_short = false;
982
983        while at(&self.linebuf, src) != 0 {
984            let mut cur = self.linebuf[src];
985            let next = at(&self.linebuf, src + 1);
986            if in_comment {
987                if cur == b'*' && next == b'/' {
988                    src += 1;
989                    in_comment = false;
990                } else if cur == b'/' && next == b'*' {
991                    nested_warning = true;
992                }
993                src += 1;
994                continue;
995            } else if self.in_quote != 0 {
996                if cur == b'\\' {
997                    // An escape: the backslash and what follows it are
998                    // copied as they are.
999                    src += 1;
1000                    self.linebuf[dst] = cur;
1001                    dst += 1;
1002                    cur = at(&self.linebuf, src);
1003                    if cur == 0 {
1004                        break;
1005                    }
1006                    if self.in_triple && cur == self.in_quote {
1007                        let mut count = count_quotes(&self.linebuf, src, cur);
1008                        while count > 1 {
1009                            self.linebuf[dst] = cur;
1010                            dst += 1;
1011                            src += 1;
1012                            count -= 1;
1013                        }
1014                    }
1015                } else if cur == self.in_quote {
1016                    if self.in_triple {
1017                        let count = count_quotes(&self.linebuf, src, cur);
1018                        if count >= 3 {
1019                            for _ in 1..count {
1020                                self.linebuf[dst] = cur;
1021                                dst += 1;
1022                                src += 1;
1023                            }
1024                            self.in_quote = 0;
1025                        }
1026                    } else {
1027                        self.in_quote = 0;
1028                    }
1029                } else if cur == b'<' && next == b'<' {
1030                    // An embedded expression: out of the string for now.
1031                    src += 1;
1032                    self.comment_ec.start_expr(self.in_quote, self.in_triple);
1033                    self.in_quote = 0;
1034                    self.linebuf[dst] = b'<';
1035                    dst += 1;
1036                }
1037            } else {
1038                if cur == b'\\' {
1039                    trailing_sp_after_bs = true;
1040                } else if !is_space(cur) {
1041                    trailing_sp_after_bs = false;
1042                }
1043                if cur == b'/' {
1044                    match next {
1045                        b'*' => {
1046                            in_comment = true;
1047                            cur = b' ';
1048                        }
1049                        b'/' => {
1050                            // The rest of the line is a comment. The text
1051                            // ends here, but the buffer's length is left
1052                            // as it was: see the note at the top.
1053                            self.linebuf[dst] = 0;
1054                            cut_short = true;
1055                            break;
1056                        }
1057                        _ => {}
1058                    }
1059                } else if cur == b'"' || cur == b'\'' {
1060                    self.in_quote = cur;
1061                    self.in_triple = count_quotes(&self.linebuf, src, cur) >= 3;
1062                    if self.in_triple {
1063                        src += 2;
1064                        self.linebuf[dst] = cur;
1065                        self.linebuf[dst + 1] = cur;
1066                        dst += 2;
1067                    }
1068                } else if cur < 0x09 {
1069                    // These are the preprocessor's own markers, and must
1070                    // not come in from outside.
1071                    cur = b' ';
1072                } else if self.comment_ec.in_expr() && (cur == b'(' || cur == b')') {
1073                    self.comment_ec.add_parens(if cur == b'(' { 1 } else { -1 });
1074                } else if self.comment_ec.in_expr()
1075                    && self.comment_ec.parens() == 0
1076                    && cur == b'>'
1077                    && next == b'>'
1078                {
1079                    // The end of an embedded expression: back in the
1080                    // string.
1081                    self.in_quote = self.comment_ec.quote();
1082                    self.in_triple = self.comment_ec.triple();
1083                    self.comment_ec.end_expr();
1084                    src += 1;
1085                    self.linebuf[dst] = b'>';
1086                    dst += 1;
1087                }
1088            }
1089            self.linebuf[dst] = cur;
1090            dst += 1;
1091            src += 1;
1092        }
1093
1094        if let Some(stream) = self.streams.last_mut() {
1095            stream.in_comment = in_comment;
1096        }
1097        if nested_warning {
1098            self.warning("\"/*\" found within \"/* ... */\" - nested comments are not allowed");
1099        }
1100        if cut_short {
1101            return;
1102        }
1103        self.linebuf.truncate(dst);
1104        if trailing_sp_after_bs {
1105            self.warning("line ends with whitespace following backslash");
1106        }
1107    }
1108
1109    /// The line ends inside a string: join lines onto it until the string
1110    /// ends, and put back whatever comes after that.
1111    fn splice_string(&mut self) {
1112        let mut unterm: u8 = 0;
1113        let in_quote = self.in_quote;
1114        let in_triple = self.in_triple;
1115        let ends_in_newline =
1116            |buf: &[u8], from: usize| buf.len() - from >= 2 && buf.ends_with(b"\\n");
1117        let mut explicit_nl = ends_in_newline(&self.linebuf, 0);
1118        let mut p: Option<usize> = None;
1119
1120        'splice: loop {
1121            match self.newline_spacing {
1122                NewlineSpacing::Collapse => {
1123                    if !explicit_nl {
1124                        self.linebuf.push(b' ');
1125                    }
1126                }
1127                NewlineSpacing::Delete => {}
1128                NewlineSpacing::Preserve => self.linebuf.extend_from_slice(b"\\n"),
1129            }
1130
1131            let Some(new_line) = self.read_line(true) else {
1132                break;
1133            };
1134            let mut q = new_line;
1135
1136            // The spaces that start the new line go, unless they are to
1137            // be preserved or the line before ended in an explicit
1138            // newline.
1139            if self.newline_spacing != NewlineSpacing::Preserve && !explicit_nl {
1140                while is_space(at(&self.linebuf, q)) {
1141                    q += 1;
1142                }
1143            }
1144            explicit_nl = ends_in_newline(&self.linebuf, new_line);
1145            if q > new_line {
1146                self.linebuf.drain(new_line..q.min(self.linebuf.len()));
1147            }
1148
1149            // A line with only a brace or a semicolon on it suggests that
1150            // the string was never closed.
1151            q = new_line;
1152            if matches!(at(&self.linebuf, q), b'}' | b';') {
1153                q += 1;
1154                while is_space(at(&self.linebuf, q)) {
1155                    q += 1;
1156                }
1157                if at(&self.linebuf, q) == 0 {
1158                    let line = self.appended_line;
1159                    self.error(format!(
1160                        "string appears unterminated (';' or '}}' appears alone on line {line})"
1161                    ));
1162                    unterm = in_quote;
1163                    self.in_quote = 0;
1164                    self.process_comments(new_line);
1165                    p = Some(new_line);
1166                    break 'splice;
1167                }
1168            }
1169
1170            // Look for the end of the string.
1171            q = new_line;
1172            loop {
1173                let cur = at(&self.linebuf, q);
1174                if cur == b'\\' {
1175                    q += 1;
1176                    if in_triple && at(&self.linebuf, q) == in_quote {
1177                        let count = count_quotes(&self.linebuf, q, in_quote);
1178                        q += count - 1;
1179                    } else if at(&self.linebuf, q) == b'<' {
1180                        while at(&self.linebuf, q) == b'<' {
1181                            q += 1;
1182                        }
1183                    }
1184                } else if cur == in_quote {
1185                    if in_triple {
1186                        let count = count_quotes(&self.linebuf, q, cur);
1187                        if count >= 3 {
1188                            p = Some(q + count);
1189                            break 'splice;
1190                        }
1191                    } else {
1192                        p = Some(q + 1);
1193                        break 'splice;
1194                    }
1195                } else if cur == b'<' && at(&self.linebuf, q + 1) == b'<' {
1196                    q += 2;
1197                    if at(&self.linebuf, q) == b'%' {
1198                        lex::scan_sprintf_spec(&self.linebuf, &mut q);
1199                    }
1200                    p = Some(q);
1201                    break 'splice;
1202                } else if cur == 0 {
1203                    p = Some(q);
1204                    break;
1205                }
1206                q += 1;
1207            }
1208        }
1209
1210        if let Some(p) = p {
1211            self.unsplice_line(p);
1212        }
1213        if unterm != 0 {
1214            self.linebuf.push(unterm);
1215        }
1216    }
1217
1218    /// Read the next line and preprocess it. Returns true at the end of
1219    /// the source.
1220    fn read_line_pp(&mut self) -> bool {
1221        if self.read_line(false).is_none() {
1222            return true;
1223        }
1224        let started_in_string = self.in_quote != 0;
1225        self.p = 0;
1226        while is_space(at(&self.linebuf, self.p)) {
1227            self.p += 1;
1228        }
1229
1230        if !started_in_string && at(&self.linebuf, self.p) == b'#' {
1231            self.p += 1;
1232            // A comment that is open at the end of the line makes the
1233            // next line part of the directive.
1234            while self.streams.last().is_some_and(|s| s.in_comment) {
1235                if self.read_line(true).is_none() {
1236                    break;
1237                }
1238            }
1239            self.next_on_line();
1240            if self.curtok.typ == Tok::Eof {
1241                self.clear_linebuf();
1242                return false;
1243            }
1244            let keyword = self.curtok_text();
1245            if self.curtok.typ != Tok::Sym {
1246                self.invalid_directive(&keyword);
1247                self.clear_linebuf();
1248                return false;
1249            }
1250            let in_false = self.in_false_if();
1251            // Only the directives that open and close #if blocks matter
1252            // in a block that is not being compiled.
1253            let (known, always): (bool, bool) = match keyword.as_slice() {
1254                b"charset" | b"pragma" | b"include" | b"define" | b"error" | b"undef" | b"line" => {
1255                    (true, false)
1256                }
1257                b"if" | b"ifdef" | b"ifndef" | b"else" | b"elif" | b"endif" => (true, true),
1258                _ => (false, false),
1259            };
1260            if !known {
1261                self.invalid_directive(&keyword);
1262            } else if in_false && !always {
1263                self.clear_linebuf();
1264            } else {
1265                match keyword.as_slice() {
1266                    b"charset" => self.pp_charset(),
1267                    b"pragma" => self.pp_pragma(),
1268                    b"include" => self.pp_include(),
1269                    b"define" => self.pp_define(),
1270                    b"if" => self.pp_if(),
1271                    b"ifdef" => self.pp_ifdef_or_ifndef(true),
1272                    b"ifndef" => self.pp_ifdef_or_ifndef(false),
1273                    b"else" => self.pp_else(),
1274                    b"elif" => self.pp_elif(),
1275                    b"endif" => self.pp_endif(),
1276                    b"error" => self.pp_error(),
1277                    b"undef" => self.pp_undef(),
1278                    _ => self.pp_line(),
1279                }
1280            }
1281            // A directive is one line, so a string cannot carry on from
1282            // it.
1283            self.in_quote = 0;
1284        } else if let Some(name) = (!started_in_string && !self.in_false_if())
1285            .then(|| import_line(&self.linebuf[self.p.min(self.linebuf.len())..]))
1286            .flatten()
1287        {
1288            self.pp_import(&name);
1289        } else {
1290            if self.in_false_if() {
1291                self.clear_linebuf();
1292                self.expbuf.clear();
1293            } else {
1294                if self.in_quote != 0 {
1295                    self.splice_string();
1296                }
1297                self.p = 0;
1298                self.expand_macros_curline(true, false, false);
1299            }
1300            if self.pp_only {
1301                self.linebuf = self.expbuf.clone();
1302            } else {
1303                // The compiler proper reads its tokens from the expanded
1304                // line.
1305                self.tok_in_expbuf = true;
1306                self.p = 0;
1307            }
1308        }
1309        false
1310    }
1311
1312    fn invalid_directive(&mut self, _keyword: &[u8]) {
1313        self.error("invalid preprocessor directive");
1314    }
1315
1316    // ---- macros ----
1317
1318    fn find_define(&self, name: &[u8]) -> Option<usize> {
1319        self.defines.get(name).copied()
1320    }
1321
1322    fn undefine_bytes(&mut self, name: &[u8]) {
1323        if let Some(&id) = self.defines.get(name)
1324            && self.macros[id].kind == MacroKind::Define
1325        {
1326            self.defines.remove(name);
1327            self.undefs.insert(name.to_vec());
1328        }
1329    }
1330
1331    /// The macros as the source left them, as the reference writes them
1332    /// to its object file: those defined now, but for `__LINE__` and
1333    /// `__FILE__` and any name that was ever undefined or defined anew,
1334    /// in the order of the reference's table of them (chain by chain,
1335    /// the sum of the name's bytes in 512, and in a chain the newest
1336    /// first).
1337    pub fn link_macros(&self) -> Vec<LinkMacro> {
1338        let mut ids: Vec<usize> = self
1339            .defines
1340            .values()
1341            .copied()
1342            .filter(|&id| {
1343                let mac = &self.macros[id];
1344                mac.kind == MacroKind::Define && !self.undefs.contains(&mac.name)
1345            })
1346            .collect();
1347        ids.sort_by_key(|&id| (macro_chain(&self.macros[id].name), std::cmp::Reverse(id)));
1348        ids.into_iter()
1349            .map(|id| {
1350                let mac = &self.macros[id];
1351                LinkMacro {
1352                    name: mac.name.clone(),
1353                    has_args: mac.has_args,
1354                    has_varargs: mac.has_varargs,
1355                    params: mac.params.clone(),
1356                    expansion: mac.orig.clone(),
1357                }
1358            })
1359            .collect()
1360    }
1361
1362    /// What a macro without arguments expands to.
1363    fn expansion(&self, id: usize) -> Vec<u8> {
1364        match self.macros[id].kind {
1365            MacroKind::Define => self.macros[id].expansion.clone(),
1366            MacroKind::Line => self.last_line.to_string().into_bytes(),
1367            MacroKind::File => match self.last_desc {
1368                Some(desc) => self.quoted_file_name(desc),
1369                None => Vec::new(),
1370            },
1371        }
1372    }
1373
1374    /// Expand the macros in the current line, from where reading has got
1375    /// to, into the expansion buffer.
1376    fn expand_macros_curline(
1377        &mut self,
1378        read_more: bool,
1379        allow_defined: bool,
1380        append: bool,
1381    ) -> bool {
1382        if !append {
1383            self.macro_as_name = None;
1384        }
1385        let mut src = std::mem::take(&mut self.linebuf);
1386        let mut expbuf = std::mem::take(&mut self.expbuf);
1387        let mut pos = self.p;
1388        let err = self.expand_macros(
1389            &mut src,
1390            None,
1391            &mut pos,
1392            &mut expbuf,
1393            read_more,
1394            allow_defined,
1395            append,
1396        );
1397        self.linebuf = src;
1398        self.expbuf = expbuf;
1399        self.p = pos;
1400        if err {
1401            return true;
1402        }
1403        if self.pp_only {
1404            remove_expansion_flags(&mut self.expbuf);
1405        }
1406        false
1407    }
1408
1409    /// Run something that works on the line buffer while the line is
1410    /// being held as `src`.
1411    fn with_linebuf<R>(&mut self, src: &mut Vec<u8>, run: impl FnOnce(&mut Self) -> R) -> R {
1412        std::mem::swap(src, &mut self.linebuf);
1413        let result = run(self);
1414        std::mem::swap(src, &mut self.linebuf);
1415        result
1416    }
1417
1418    /// Expand the macros in `src` from `pos`, onto `expbuf`. With
1419    /// `read_more`, `src` is the line buffer, expansions are put back
1420    /// into it to be scanned again, and more lines are read to complete a
1421    /// macro's arguments. Returns true on an error.
1422    #[allow(clippy::too_many_arguments)]
1423    fn expand_macros(
1424        &mut self,
1425        src: &mut Vec<u8>,
1426        limit: Option<usize>,
1427        pos: &mut usize,
1428        expbuf: &mut Vec<u8>,
1429        read_more: bool,
1430        allow_defined: bool,
1431        append: bool,
1432    ) -> bool {
1433        let mut subexp = Vec::new();
1434        if !append {
1435            expbuf.clear();
1436        }
1437        let mut startofs = *pos;
1438        let mut tok = self.next_tok(src, limit, pos, true);
1439        while tok.typ != Tok::Eof {
1440            if tok.typ == Tok::Sym && !tok.fully_expanded {
1441                let name = tok.text(src).to_vec();
1442                let end = limit.unwrap_or(src.len());
1443                let entry = self.find_define(&name);
1444                let expandable =
1445                    entry.is_some_and(|id| !scan_for_prior_expansion(src, *pos, end, id));
1446                if expandable || (allow_defined && name == b"defined") {
1447                    let macro_ofs = tok.pos;
1448                    if read_more
1449                        && let Some(id) = entry
1450                        && self.macros[id].kind == MacroKind::Define
1451                        && stands_as_name(src, macro_ofs, *pos)
1452                    {
1453                        self.macro_as_name = Some((name.clone(), self.macros[id].orig.clone()));
1454                    }
1455                    let expanded = match entry {
1456                        Some(id) => {
1457                            let (err, did) = self.expand_macro(
1458                                &mut subexp,
1459                                src,
1460                                limit,
1461                                pos,
1462                                macro_ofs,
1463                                id,
1464                                read_more,
1465                                allow_defined,
1466                            );
1467                            if err {
1468                                return true;
1469                            }
1470                            did
1471                        }
1472                        None => {
1473                            if self.expand_defined(&mut subexp, src, limit, pos) {
1474                                return true;
1475                            }
1476                            true
1477                        }
1478                    };
1479                    if !expanded {
1480                        tok = self.next_tok(src, limit, pos, true);
1481                        continue;
1482                    }
1483                    expbuf.extend_from_slice(slice(src, startofs, macro_ofs));
1484                    startofs = *pos;
1485                    let end = limit.unwrap_or(src.len());
1486                    if read_more {
1487                        // Put the expansion in place of the macro and
1488                        // carry on from its start, so that it is scanned
1489                        // along with what follows it.
1490                        let from = macro_ofs.min(src.len());
1491                        let to = startofs.clamp(from, src.len());
1492                        src.splice(from..to, subexp.iter().copied());
1493                        *pos = macro_ofs;
1494                        startofs = macro_ofs;
1495                        tok = self.next_tok(src, limit, pos, true);
1496                        continue;
1497                    }
1498                    subexp.extend_from_slice(slice(src, startofs, end));
1499                    let mut sub_pos = 0;
1500                    return self.expand_macros(
1501                        &mut subexp,
1502                        None,
1503                        &mut sub_pos,
1504                        expbuf,
1505                        false,
1506                        allow_defined,
1507                        true,
1508                    );
1509                }
1510            }
1511            tok = self.next_tok(src, limit, pos, true);
1512        }
1513        expbuf.extend_from_slice(slice(src, startofs, tok.pos));
1514        false
1515    }
1516
1517    /// Expand one macro, whose name has just been read. Returns whether
1518    /// there was an error, and whether the macro was expanded: one that
1519    /// takes arguments is left alone if none follow.
1520    #[allow(clippy::too_many_arguments)]
1521    fn expand_macro(
1522        &mut self,
1523        expbuf: &mut Vec<u8>,
1524        src: &mut Vec<u8>,
1525        limit: Option<usize>,
1526        pos: &mut usize,
1527        macro_ofs: usize,
1528        id: usize,
1529        read_more: bool,
1530        allow_defined: bool,
1531    ) -> (bool, bool) {
1532        let startofs = *pos;
1533        expbuf.clear();
1534        let mut argofs = vec![0usize; MAX_MACRO_ARGS + 1];
1535        let mut arglen = vec![0usize; MAX_MACRO_ARGS + 1];
1536
1537        if self.macros[id].has_args {
1538            let (err, found) =
1539                self.parse_macro_actuals(src, limit, pos, id, &mut argofs, &mut arglen, read_more);
1540            if err {
1541                return (true, false);
1542            }
1543            if !found {
1544                *expbuf = slice(src, macro_ofs, startofs).to_vec();
1545                *pos = startofs;
1546                return (false, false);
1547            }
1548        }
1549
1550        if self.macros[id].argc != 0 {
1551            match self.substitute_macro_actuals(id, src, &argofs, &arglen, allow_defined) {
1552                Some(text) => *expbuf = text,
1553                None => return (true, false),
1554            }
1555        } else {
1556            *expbuf = self.expansion(id);
1557        }
1558        expbuf.extend_from_slice(&lex::macro_end_marker(id));
1559        (false, true)
1560    }
1561
1562    /// Read the arguments of a macro call: where each one is in `src`.
1563    /// Returns whether there was an error, and whether there were any
1564    /// arguments at all.
1565    #[allow(clippy::too_many_arguments)]
1566    fn parse_macro_actuals(
1567        &mut self,
1568        src: &mut Vec<u8>,
1569        limit: Option<usize>,
1570        pos: &mut usize,
1571        id: usize,
1572        argofs: &mut [usize],
1573        arglen: &mut [usize],
1574        read_more: bool,
1575    ) -> (bool, bool) {
1576        let mut spliced = false;
1577        let mut argc = 0;
1578        let (macro_argc, has_varargs, min_argc, name) = {
1579            let m = &self.macros[id];
1580            (m.argc, m.has_varargs, m.min_argc(), show_name(&m.name))
1581        };
1582
1583        let mut tok = self.next_tok(src, limit, pos, true);
1584        if tok.typ == Tok::Eof && read_more {
1585            tok = self.actual_splice_next_line(src, pos);
1586            spliced = true;
1587        }
1588        if tok.typ != Tok::LPar {
1589            if spliced {
1590                self.with_linebuf(src, |pp| pp.unsplice_line(tok.pos));
1591            }
1592            return (false, false);
1593        }
1594
1595        argofs[argc] = tok.end();
1596        tok = self.next_tok(src, limit, pos, true);
1597        while tok.typ != Tok::RPar {
1598            if (argc >= macro_argc && !has_varargs) || argc >= MAX_MACRO_ARGS {
1599                self.error(format!("too many arguments for macro \"{name}\""));
1600                while tok.typ != Tok::RPar && tok.typ != Tok::Eof {
1601                    tok = self.next_tok(src, limit, pos, true);
1602                }
1603                break;
1604            }
1605
1606            // An argument runs to a comma or the closing bracket, outside
1607            // any brackets of its own.
1608            let (mut parens, mut brackets, mut braces) = (0i32, 0i32, 0i32);
1609            loop {
1610                if tok.typ == Tok::Comma && parens == 0 && braces == 0 && brackets == 0 {
1611                    break;
1612                }
1613                if tok.typ == Tok::RPar && parens == 0 {
1614                    break;
1615                }
1616                match tok.typ {
1617                    Tok::LPar => parens += 1,
1618                    Tok::RPar => parens -= 1,
1619                    Tok::LBrace => braces += 1,
1620                    Tok::RBrace => braces -= 1,
1621                    Tok::LBrack => brackets += 1,
1622                    Tok::RBrack => brackets -= 1,
1623                    _ => {}
1624                }
1625                tok = self.next_tok(src, limit, pos, true);
1626                if tok.typ == Tok::Eof && read_more {
1627                    tok = self.actual_splice_next_line(src, pos);
1628                    spliced = true;
1629                }
1630                if tok.typ == Tok::Eof {
1631                    break;
1632                }
1633            }
1634            if tok.typ == Tok::Eof {
1635                break;
1636            }
1637
1638            arglen[argc] = trim_end(src, argofs[argc], tok.pos) - argofs[argc];
1639            argc += 1;
1640
1641            if tok.typ == Tok::Comma {
1642                argofs[argc] = tok.end();
1643                tok = self.next_tok(src, limit, pos, true);
1644            } else if tok.typ == Tok::RPar {
1645                break;
1646            }
1647        }
1648
1649        if tok.typ != Tok::RPar {
1650            self.error(format!("missing ')' in argument list for macro \"{name}\""));
1651            return (true, false);
1652        }
1653
1654        // Take the spaces off the start and end of each argument.
1655        for i in 0..argc {
1656            let start = argofs[i];
1657            let end = start + arglen[i];
1658            let mut p = start;
1659            while p < end && is_space(at(src, p)) {
1660                p += 1;
1661            }
1662            let removed = p - start;
1663            argofs[i] += removed;
1664            arglen[i] -= removed;
1665            let start = start + removed;
1666            arglen[i] -= end - trim_end(src, start, end);
1667        }
1668
1669        if spliced {
1670            self.with_linebuf(src, |pp| pp.unsplice_line(tok.end()));
1671        }
1672
1673        if argc < min_argc {
1674            while argc < macro_argc {
1675                argofs[argc] = 0;
1676                arglen[argc] = 0;
1677                argc += 1;
1678            }
1679            self.warning(format!("not enough arguments for macro \"{name}\""));
1680        }
1681        if has_varargs && argc < MAX_MACRO_ARGS {
1682            argofs[argc] = 0;
1683            arglen[argc] = 0;
1684        }
1685        (false, true)
1686    }
1687
1688    /// A macro's arguments run past the end of the line: read the next
1689    /// line onto the end of this one and get the first token from it.
1690    fn actual_splice_next_line(&mut self, src: &mut Vec<u8>, pos: &mut usize) -> Token {
1691        src.push(b' ');
1692        loop {
1693            let new_line = self.with_linebuf(src, |pp| {
1694                let new_line = pp.read_line(true);
1695                if pp.in_quote != 0 {
1696                    pp.splice_string();
1697                }
1698                new_line
1699            });
1700            let Some(new_line) = new_line else {
1701                let mut tok = Token::new(Tok::Eof);
1702                tok.pos = src.len();
1703                return tok;
1704            };
1705            *pos = new_line;
1706            let tok = self.next_tok(src, None, pos, true);
1707            if tok.typ != Tok::Eof {
1708                return tok;
1709            }
1710        }
1711    }
1712
1713    /// Build a macro's expansion with its arguments in place. `None` on
1714    /// an error.
1715    fn substitute_macro_actuals(
1716        &mut self,
1717        id: usize,
1718        src: &mut Vec<u8>,
1719        argofs: &[usize],
1720        arglen: &[usize],
1721        allow_defined: bool,
1722    ) -> Option<Vec<u8>> {
1723        let exp = self.macros[id].expansion.clone();
1724        let macro_argc = self.macros[id].argc;
1725        let has_varargs = self.macros[id].has_varargs;
1726        let last_arg = macro_argc - 1;
1727
1728        let mut subexp: Vec<u8> = Vec::new();
1729        let mut start = 0usize;
1730        let mut expsrc = 0usize;
1731        let eof = Token::new(Tok::Eof);
1732        let mut prvtok = eof;
1733        let mut prvprvtok = eof;
1734        self.expand_stack.clear();
1735
1736        let mut tok = self.next_exp_tok(&exp, &mut expsrc);
1737        while tok.typ != Tok::Eof {
1738            // The delimiter that ends the current part of a #foreach or
1739            // an #ifempty.
1740            if let Some(top) = self.expand_stack.last().copied()
1741                && at(&exp, tok.pos) == top.delim
1742            {
1743                if tok.pos > start {
1744                    subexp.extend_from_slice(&exp[start..tok.pos]);
1745                }
1746                expsrc = tok.pos;
1747                match top.typ {
1748                    Tok::MacroForeach => {
1749                        let more = argofs[top.arg + 1] != 0;
1750                        let mut end_foreach = false;
1751                        if top.part == 0 {
1752                            if !more {
1753                                // The last time round: leave out the
1754                                // part that goes between items.
1755                                skip_delimited_group(&exp, &mut expsrc, 1);
1756                                end_foreach = true;
1757                            } else {
1758                                expsrc += 1;
1759                                if let Some(level) = self.expand_stack.last_mut() {
1760                                    level.part += 1;
1761                                }
1762                            }
1763                        } else {
1764                            expsrc += 1;
1765                            end_foreach = true;
1766                        }
1767                        if end_foreach {
1768                            if !more {
1769                                self.expand_stack.pop();
1770                            } else if let Some(level) = self.expand_stack.last_mut() {
1771                                level.arg += 1;
1772                                expsrc = level.start;
1773                                prvtok = eof;
1774                                prvprvtok = eof;
1775                                level.part = 0;
1776                            }
1777                        }
1778                    }
1779                    Tok::MacroIfEmpty | Tok::MacroIfNEmpty => {
1780                        expsrc += 1;
1781                        self.expand_stack.pop();
1782                    }
1783                    _ => {}
1784                }
1785                start = expsrc;
1786                tok = self.next_exp_tok(&exp, &mut expsrc);
1787                continue;
1788            }
1789
1790            if tok.typ == Tok::MacroForeach && has_varargs {
1791                if tok.pos > start {
1792                    subexp.extend_from_slice(&exp[start..tok.pos]);
1793                }
1794                if self.expand_stack.len() >= MAX_FOREACH_NESTING {
1795                    self.error("#foreach/#ifempty/#ifnempty nesting too deep");
1796                } else if argofs[last_arg] == 0 {
1797                    // No variable arguments: nothing to repeat.
1798                    skip_delimited_group(&exp, &mut expsrc, 2);
1799                } else {
1800                    let delim = at(&exp, expsrc);
1801                    expsrc += 1;
1802                    self.expand_stack.push(ExpandLevel {
1803                        typ: tok.typ,
1804                        is_iterator: true,
1805                        delim,
1806                        start: expsrc,
1807                        arg: last_arg,
1808                        part: 0,
1809                    });
1810                }
1811                start = expsrc;
1812                tok = self.next_exp_tok(&exp, &mut expsrc);
1813                continue;
1814            }
1815
1816            if matches!(tok.typ, Tok::MacroIfEmpty | Tok::MacroIfNEmpty) && has_varargs {
1817                if tok.pos > start {
1818                    subexp.extend_from_slice(&exp[start..tok.pos]);
1819                }
1820                let is_empty = argofs[last_arg] == 0;
1821                let expand = is_empty == (tok.typ == Tok::MacroIfEmpty);
1822                if expand {
1823                    if self.expand_stack.len() >= MAX_FOREACH_NESTING {
1824                        self.error("#foreach/#ifempty/#ifnempty nesting too deep");
1825                    } else {
1826                        let delim = at(&exp, expsrc);
1827                        expsrc += 1;
1828                        let (is_iterator, arg) = match self.expand_stack.last() {
1829                            Some(outer) => (outer.is_iterator, outer.arg),
1830                            None => (false, 0),
1831                        };
1832                        self.expand_stack.push(ExpandLevel {
1833                            typ: tok.typ,
1834                            is_iterator,
1835                            delim,
1836                            start: 0,
1837                            arg,
1838                            part: 0,
1839                        });
1840                    }
1841                } else {
1842                    skip_delimited_group(&exp, &mut expsrc, 1);
1843                }
1844                start = expsrc;
1845                tok = self.next_exp_tok(&exp, &mut expsrc);
1846                continue;
1847            }
1848
1849            if tok.typ == Tok::MacroArgCount && has_varargs {
1850                if tok.pos > start {
1851                    subexp.extend_from_slice(&exp[start..tok.pos]);
1852                }
1853                let mut i = last_arg;
1854                while argofs[i] != 0 {
1855                    i += 1;
1856                }
1857                subexp.extend_from_slice((i - last_arg).to_string().as_bytes());
1858                start = expsrc;
1859                tok = self.next_exp_tok(&exp, &mut expsrc);
1860                continue;
1861            }
1862
1863            if tok.typ == Tok::MacroFormal {
1864                let mut p = tok.pos;
1865                let mut argnum = usize::from(at(&exp, tok.pos + 1)).saturating_sub(1);
1866
1867                // In a #foreach, the variable-argument parameter stands
1868                // for the one argument this time round is for.
1869                if let Some(top) = self.expand_stack.last()
1870                    && argnum == last_arg
1871                    && top.is_iterator
1872                {
1873                    argnum = top.arg;
1874                }
1875                // Outside one, it stands for all of them, commas and all.
1876                let argnum_len =
1877                    if self.expand_stack.is_empty() && has_varargs && argnum == last_arg {
1878                        let mut i = argnum;
1879                        while i < MAX_MACRO_ARGS && argofs[i] != 0 {
1880                            i += 1;
1881                        }
1882                        if i == argnum {
1883                            0
1884                        } else {
1885                            argofs[i - 1] + arglen[i - 1] - argofs[argnum]
1886                        }
1887                    } else {
1888                        arglen[argnum]
1889                    };
1890
1891                let mut pasting = false;
1892                let mut pasting_at_left = false;
1893                let mut pasting_at_right = false;
1894                let mut stringize = false;
1895                let mut stringize_qu = b'"';
1896                let mut stringize_type = Tok::Invalid;
1897
1898                loop {
1899                    if prvtok.typ == Tok::PoundPound {
1900                        // Pasting onto what is at the left: the ## and
1901                        // the spaces before it go.
1902                        pasting = true;
1903                        pasting_at_left = true;
1904                        p = prvtok.pos;
1905                        let mut prv_ch = 0;
1906                        while p > start {
1907                            prv_ch = exp[p - 1];
1908                            if !is_space(prv_ch) {
1909                                break;
1910                            }
1911                            p -= 1;
1912                        }
1913                        // ", ## args" with no arguments loses the comma.
1914                        if prv_ch == b','
1915                            && has_varargs
1916                            && argnum == last_arg
1917                            && argofs[argnum] == 0
1918                        {
1919                            p -= 1;
1920                        }
1921                        break;
1922                    } else if matches!(prvtok.typ, Tok::Pound | Tok::PoundAt) {
1923                        p = prvtok.pos;
1924                        stringize = true;
1925                        stringize_type = prvtok.typ;
1926                        stringize_qu = if prvtok.typ == Tok::Pound {
1927                            b'"'
1928                        } else {
1929                            b'\''
1930                        };
1931                        prvtok = prvprvtok;
1932                        prvprvtok = eof;
1933                    } else {
1934                        break;
1935                    }
1936                }
1937
1938                if p > start {
1939                    subexp.extend_from_slice(&exp[start..p]);
1940                }
1941                prvprvtok = prvtok;
1942                prvtok = tok;
1943                tok = self.next_exp_tok(&exp, &mut expsrc);
1944
1945                let mut paste_at_right_tok = eof;
1946                if tok.typ == Tok::PoundPound {
1947                    pasting = true;
1948                    pasting_at_right = true;
1949                    let old_expsrc = expsrc;
1950                    let old_tok = tok;
1951                    tok = self.next_exp_tok(&exp, &mut expsrc);
1952                    paste_at_right_tok = tok;
1953                    if stringize && tok.typ == stringize_type {
1954                        expsrc = old_expsrc;
1955                        tok = old_tok;
1956                    } else {
1957                        prvprvtok = prvtok;
1958                        prvtok = old_tok;
1959                    }
1960                    start = tok.pos;
1961                } else {
1962                    start = prvtok.end();
1963                }
1964
1965                let arg_start = argofs[argnum];
1966                if pasting && stringize {
1967                    let mut add_open = true;
1968                    let mut add_close = true;
1969                    if subexp.last() == Some(&stringize_qu) {
1970                        subexp.pop();
1971                        add_open = false;
1972                    }
1973                    if pasting_at_right && at(&exp, tok.pos) == stringize_qu {
1974                        add_close = false;
1975                    }
1976                    stringize_macro_actual(
1977                        &mut subexp,
1978                        slice(src, arg_start, arg_start + argnum_len),
1979                        stringize_qu,
1980                        add_open,
1981                        add_close,
1982                    );
1983                    if !add_close {
1984                        subexp.extend_from_slice(slice(&exp, tok.pos + 1, tok.end()));
1985                        prvprvtok = prvtok;
1986                        prvtok = tok;
1987                        tok = self.next_exp_tok(&exp, &mut expsrc);
1988                        start = tok.pos;
1989                    }
1990                } else if pasting {
1991                    let mut argp = arg_start;
1992                    let mut len = argnum_len;
1993                    if pasting_at_left && at(src, argp) == FULLY_EXPANDED_FLAG {
1994                        argp += 1;
1995                        len = len.saturating_sub(1);
1996                    }
1997                    // Two strings pasted together become one.
1998                    let mut quote_char = 0;
1999                    let first = at(src, argp);
2000                    if pasting_at_left
2001                        && (first == b'\'' || first == b'"')
2002                        && subexp.last() == Some(&first)
2003                    {
2004                        subexp.pop();
2005                        quote_char = first;
2006                        argp += 1;
2007                        len = len.saturating_sub(1);
2008                    }
2009                    let mut done = false;
2010                    if pasting_at_right {
2011                        let mut old_tok = Token::new(Tok::Invalid);
2012                        let mut atok = Token::new(Tok::Invalid);
2013                        let mut q = argp;
2014                        while q < argp + len {
2015                            atok = self.next_tok(src, Some(usize::MAX), &mut q, true);
2016                            if atok.typ == Tok::Eof || atok.pos >= argp + len {
2017                                break;
2018                            }
2019                            old_tok = atok;
2020                        }
2021                        if old_tok.typ == Tok::Sym && old_tok.fully_expanded {
2022                            // The last token is marked as expanded, but
2023                            // pasting makes a new token of it: take the
2024                            // mark off.
2025                            let mark = atok.pos.saturating_sub(1);
2026                            subexp.extend_from_slice(slice(src, argp, mark));
2027                            subexp.extend_from_slice(slice(src, atok.pos, argp + len));
2028                            done = true;
2029                        } else if quote_char != 0
2030                            && paste_at_right_tok.len != 0
2031                            && at(&exp, paste_at_right_tok.pos) == quote_char
2032                        {
2033                            subexp.extend_from_slice(slice(
2034                                src,
2035                                argp,
2036                                argp + len.saturating_sub(1),
2037                            ));
2038                            subexp.extend_from_slice(slice(
2039                                &exp,
2040                                paste_at_right_tok.pos + 1,
2041                                paste_at_right_tok.end(),
2042                            ));
2043                            start = paste_at_right_tok.end();
2044                            done = true;
2045                        }
2046                    }
2047                    if !done {
2048                        subexp.extend_from_slice(slice(src, argp, argp + len));
2049                    }
2050                } else if stringize {
2051                    stringize_macro_actual(
2052                        &mut subexp,
2053                        slice(src, arg_start, arg_start + argnum_len),
2054                        stringize_qu,
2055                        true,
2056                        true,
2057                    );
2058                } else {
2059                    // An ordinary use: the argument is expanded first,
2060                    // and what comes out is marked so that it is not
2061                    // expanded again as part of this macro's expansion.
2062                    let mut actual_exp = Vec::new();
2063                    let mut actual_pos = arg_start;
2064                    if self.expand_macros(
2065                        src,
2066                        Some(arg_start + argnum_len),
2067                        &mut actual_pos,
2068                        &mut actual_exp,
2069                        false,
2070                        allow_defined,
2071                        false,
2072                    ) {
2073                        return None;
2074                    }
2075                    self.mark_full_exp_tokens(&mut subexp, &actual_exp);
2076                }
2077                continue;
2078            }
2079
2080            prvprvtok = prvtok;
2081            prvtok = tok;
2082            tok = self.next_exp_tok(&exp, &mut expsrc);
2083        }
2084
2085        subexp.extend_from_slice(slice(&exp, start, tok.pos));
2086        Some(subexp)
2087    }
2088
2089    /// Copy expanded text onto `dst`, marking each symbol that names a
2090    /// macro whose expansion it came from, so that it is left alone from
2091    /// now on.
2092    fn mark_full_exp_tokens(&mut self, dst: &mut Vec<u8>, srcbuf: &[u8]) {
2093        let from = dst.len();
2094        let mut ec = EmbedCtx::default();
2095        let mut p = 0;
2096        let mut start = 0;
2097        let end = srcbuf.len();
2098        let mut tok;
2099        loop {
2100            let old_ec = ec;
2101            let mut cx = LexCtx {
2102                ec: Some(&mut ec),
2103                expanding: true,
2104                in_pp_expr: false,
2105                notes: &mut self.notes,
2106            };
2107            tok = lex::next_on_line(srcbuf, &mut p, &mut cx);
2108            if tok.pos >= end {
2109                tok = Token::new(Tok::Eof);
2110                tok.pos = end;
2111                ec = old_ec;
2112            }
2113            if tok.typ == Tok::Eof {
2114                break;
2115            }
2116            if tok.typ == Tok::Sym
2117                && !tok.fully_expanded
2118                && let Some(id) = self.find_define(tok.text(srcbuf))
2119                && scan_for_prior_expansion(srcbuf, p, end, id)
2120            {
2121                if tok.pos > start {
2122                    dst.extend_from_slice(&srcbuf[start..tok.pos]);
2123                }
2124                dst.push(FULLY_EXPANDED_FLAG);
2125                start = tok.pos;
2126            }
2127        }
2128        self.notes.clear();
2129        if tok.pos > start {
2130            dst.extend_from_slice(&srcbuf[start..tok.pos]);
2131        }
2132        remove_end_markers(dst, from);
2133    }
2134
2135    /// `defined(NAME)` or `defined NAME` in an `#if`: one or zero.
2136    fn expand_defined(
2137        &mut self,
2138        subexp: &mut Vec<u8>,
2139        src: &[u8],
2140        limit: Option<usize>,
2141        pos: &mut usize,
2142    ) -> bool {
2143        let mut tok = self.next_tok(src, limit, pos, false);
2144        let paren = tok.typ == Tok::LPar;
2145        if paren {
2146            tok = self.next_tok(src, limit, pos, false);
2147        }
2148        if tok.typ != Tok::Sym {
2149            self.error(format!(
2150                "name required for defined() (found \"{}\")",
2151                show_name(tok.text(src))
2152            ));
2153            return true;
2154        }
2155        let found = self.find_define(tok.text(src)).is_some();
2156        *subexp = if found { b"1".to_vec() } else { b"0".to_vec() };
2157        if paren && self.next_tok(src, limit, pos, false).typ != Tok::RPar {
2158            self.error("missing ')' in defined()");
2159            return true;
2160        }
2161        false
2162    }
2163
2164    // ---- directives ----
2165
2166    fn pp_charset(&mut self) {
2167        // The directive is only meaningful at the very start of a file,
2168        // where it is taken when the file is opened. One that is still
2169        // here either is somewhere else or names a character set that is
2170        // not known.
2171        if self
2172            .streams
2173            .last()
2174            .is_some_and(|stream| stream.charset_error)
2175        {
2176            self.error("unable to load #charset");
2177        } else {
2178            self.error("unexpected or invalid #charset");
2179        }
2180        self.clear_linebuf();
2181    }
2182
2183    fn pp_pragma(&mut self) {
2184        if self.next_on_line() != Tok::Sym {
2185            let text = self.curtok_text();
2186            self.warning(format!(
2187                "unrecognized #pragma \"{}\"; ignored",
2188                show_name(&text)
2189            ));
2190            return;
2191        }
2192        let keyword = self.curtok_text();
2193        match keyword.to_ascii_lowercase().as_slice() {
2194            b"once" => {
2195                if let Some(desc) = self.streams.last().map(|stream| stream.desc) {
2196                    let name = self.descs[desc].name.clone();
2197                    self.add_include_once(&name);
2198                }
2199                self.clear_linebuf();
2200            }
2201            b"all_once" => {
2202                match self.next_on_line() {
2203                    Tok::Plus | Tok::Eof => self.all_once = true,
2204                    Tok::Minus => self.all_once = false,
2205                    _ => self.warning("invalid syntax for #pragma"),
2206                }
2207                self.clear_linebuf();
2208            }
2209            b"message" => self.pragma_message(),
2210            b"newline_spacing" => self.pragma_newline_spacing(),
2211            b"sourcetextgroup" => {
2212                // This is for the compiler proper; when only
2213                // preprocessing, the line is passed on to it.
2214                if !self.pp_only {
2215                    self.pragma_source_text_group();
2216                }
2217            }
2218            _ => self.warning(format!(
2219                "unrecognized #pragma \"{}\"; ignored",
2220                show_name(&keyword)
2221            )),
2222        }
2223    }
2224
2225    /// `#pragma sourceTextGroup`, `(on)`, or `(off)`: whether the
2226    /// objects defined from here on say which source file they are in.
2227    fn pragma_source_text_group(&mut self) {
2228        let on = match self.next_on_line() {
2229            Tok::Eof => Some(true),
2230            Tok::LPar if self.next_on_line() == Tok::Sym => {
2231                let on = match self.curtok_text().as_slice() {
2232                    b"on" => Some(true),
2233                    b"off" => Some(false),
2234                    _ => None,
2235                };
2236                if on.is_some() && self.next_on_line() != Tok::RPar {
2237                    None
2238                } else {
2239                    on
2240                }
2241            }
2242            _ => None,
2243        };
2244        match on {
2245            Some(on) => self.src_group_change = Some(on),
2246            None => self.warning("invalid syntax for #pragma"),
2247        }
2248        self.clear_linebuf();
2249    }
2250
2251    /// What `#pragma sourceTextGroup` has said since this was last
2252    /// asked, if anything.
2253    pub(crate) fn take_source_text_group(&mut self) -> Option<bool> {
2254        self.src_group_change.take()
2255    }
2256
2257    fn pragma_message(&mut self) {
2258        let startofs = self.curtok.end();
2259        self.expbuf = slice(&self.linebuf, 0, startofs).to_vec();
2260        if self.expand_macros_curline(false, false, true) {
2261            self.clear_linebuf();
2262            return;
2263        }
2264        if self.pp_only {
2265            // The line is passed on, with its macros expanded, for the
2266            // compiler proper to show.
2267            self.linebuf = self.expbuf.clone();
2268            return;
2269        }
2270        // Show what is in the parentheses: strings and names as they
2271        // are, numbers as numbers.
2272        let buf = std::mem::take(&mut self.expbuf);
2273        self.p = startofs;
2274        let mut message = String::new();
2275        let mut typ = self.next_message_token(&buf);
2276        if typ == Tok::LPar {
2277            typ = self.next_message_token(&buf);
2278        } else {
2279            self.warning("invalid syntax for #pragma");
2280        }
2281        while typ != Tok::RPar && typ != Tok::Eof {
2282            match typ {
2283                Tok::SStr | Tok::DStr | Tok::Sym => {
2284                    message.push_str(&String::from_utf8_lossy(&self.cur.text));
2285                }
2286                Tok::Int => message.push_str(&(self.cur.int_val as i32).to_string()),
2287                _ => {}
2288            }
2289            typ = self.next_message_token(&buf);
2290        }
2291        self.expbuf = buf;
2292        self.report(Severity::Message, message);
2293        self.clear_linebuf();
2294    }
2295
2296    /// The next token of a `#pragma message`, with strings translated.
2297    fn next_message_token(&mut self, buf: &[u8]) -> Tok {
2298        lex::skip_ws_and_markers(buf, &mut self.p);
2299        if matches!(at(buf, self.p), b'"' | b'\'') {
2300            return self.xlat_string_to(buf, false);
2301        }
2302        let mut cx = LexCtx {
2303            ec: None,
2304            expanding: false,
2305            in_pp_expr: false,
2306            notes: &mut self.notes,
2307        };
2308        let tok = lex::next_on_line(buf, &mut self.p, &mut cx);
2309        self.cur = SrcToken::new(tok.typ);
2310        self.cur.text = tok.text(buf).to_vec();
2311        self.cur.int_val = tok.int_val;
2312        self.flush_notes();
2313        tok.typ
2314    }
2315
2316    fn pragma_newline_spacing(&mut self) {
2317        if self.pp_only {
2318            return;
2319        }
2320        let mode = if self.next_on_line() != Tok::LPar || self.next_on_line() != Tok::Sym {
2321            None
2322        } else {
2323            match self.curtok_text().as_slice() {
2324                b"on" | b"collapse" => Some(NewlineSpacing::Collapse),
2325                b"off" | b"delete" => Some(NewlineSpacing::Delete),
2326                b"preserve" => Some(NewlineSpacing::Preserve),
2327                _ => None,
2328            }
2329        };
2330        match mode {
2331            Some(mode) if self.next_on_line() == Tok::RPar => self.newline_spacing = mode,
2332            _ => self.warning("invalid syntax for #pragma"),
2333        }
2334        self.clear_linebuf();
2335    }
2336
2337    fn add_include_once(&mut self, name: &str) {
2338        if !self.find_include_once(name) {
2339            self.include_once.push(name.to_owned());
2340        }
2341    }
2342
2343    fn find_include_once(&self, name: &str) -> bool {
2344        self.include_once
2345            .iter()
2346            .any(|once| file_names_equal(once, name))
2347    }
2348
2349    fn pp_include(&mut self) {
2350        // If the line is just a file name in quotes or angle brackets,
2351        // it is taken as it is; otherwise macros in it are expanded
2352        // first.
2353        let start = self.p;
2354        let mut expand = true;
2355        let mut q = self.p;
2356        while is_space(at(&self.linebuf, q)) {
2357            q += 1;
2358        }
2359        let close = match at(&self.linebuf, q) {
2360            b'<' => Some(b'>'),
2361            b'"' => Some(b'"'),
2362            _ => None,
2363        };
2364        if let Some(close) = close {
2365            q += 1;
2366            while at(&self.linebuf, q) != 0 && at(&self.linebuf, q) != close {
2367                q += 1;
2368            }
2369            if at(&self.linebuf, q) == close {
2370                q += 1;
2371                while is_space(at(&self.linebuf, q)) {
2372                    q += 1;
2373                }
2374                if at(&self.linebuf, q) == 0 {
2375                    expand = false;
2376                }
2377            }
2378        }
2379        self.p = start;
2380
2381        let line: Vec<u8>;
2382        let mut p;
2383        if expand {
2384            if self.expand_macros_curline(false, false, false) {
2385                self.clear_linebuf();
2386                return;
2387            }
2388            remove_expansion_flags(&mut self.expbuf);
2389            line = self.expbuf.clone();
2390            p = 0;
2391        } else {
2392            line = self.linebuf.clone();
2393            p = self.p;
2394        }
2395
2396        while is_space(at(&line, p)) {
2397            p += 1;
2398        }
2399        let (close, is_local) = match at(&line, p) {
2400            b'"' => (b'"', true),
2401            b'<' => (b'>', false),
2402            _ => {
2403                self.error("syntax error in #include");
2404                self.clear_linebuf();
2405                return;
2406            }
2407        };
2408        p += 1;
2409        let name_start = p;
2410        while at(&line, p) != 0 && at(&line, p) != close {
2411            p += 1;
2412        }
2413        if at(&line, p) == 0 {
2414            self.error("syntax error in #include");
2415            self.clear_linebuf();
2416            return;
2417        }
2418        let name = String::from_utf8_lossy(&line[name_start..p]).into_owned();
2419        p += 1;
2420        while is_space(at(&line, p)) {
2421            p += 1;
2422        }
2423        if at(&line, p) != 0 {
2424            self.warning("extraneous characters following #include filename");
2425        }
2426        self.clear_linebuf();
2427        self.include_file(&name, is_local, false);
2428    }
2429
2430    /// `import name;`, in Hexicon: the header the library of that name
2431    /// says to give the files that import it, read as `#include` would
2432    /// read it.
2433    fn pp_import(&mut self, name: &str) {
2434        self.clear_linebuf();
2435        if self.imported.iter().any(|have| have == name) {
2436            return;
2437        }
2438        let found = self.imports.iter().find(|(have, _)| have == name).cloned();
2439        match found {
2440            Some((_, Some(header))) => {
2441                self.imported.push(name.to_owned());
2442                self.include_file(&header, false, true);
2443            }
2444            Some((_, None)) => self.error(format!(
2445                "import {name}: library \"{name}\" names no header to import"
2446            )),
2447            None => self.error(format!(
2448                "import {name}: no library \"{name}\" in this build"
2449            )),
2450        }
2451    }
2452
2453    /// Read a file named by `#include` or found by `import`: in quotes
2454    /// (`is_local`), beside the file that includes it, and then, as in
2455    /// angle brackets, along the include path. A header a library names
2456    /// for `import` (`as_found`) is where its path says, if it is there.
2457    fn include_file(&mut self, name: &str, is_local: bool, as_found: bool) {
2458        let name = name.to_owned();
2459        // A file named in quotes is looked for beside the file that
2460        // includes it, and then, like one in angle brackets, in each
2461        // folder of the include path.
2462        let absolute = is_absolute(&name);
2463        let mut full_name = None;
2464        if as_found && self.files.exists(&name) {
2465            full_name = Some(name.clone());
2466        }
2467        if is_local
2468            && full_name.is_none()
2469            && let Some(desc) = self.last_desc
2470        {
2471            let candidate = join_path(dir_name(&self.descs[desc].name), &name);
2472            if self.files.exists(&candidate) {
2473                full_name = Some(candidate);
2474            }
2475        }
2476        if full_name.is_none() {
2477            for index in 0..self.include_paths.len() {
2478                let candidate = join_path(&self.include_paths[index], &name);
2479                if self.files.exists(&candidate) {
2480                    full_name = Some(candidate);
2481                    break;
2482                }
2483            }
2484        }
2485        if full_name.is_none() && absolute && self.files.exists(&name) {
2486            full_name = Some(name.clone());
2487        }
2488        // Last, the system library's headers, which are part of the
2489        // compiler.
2490        let built_in = if full_name.is_none() {
2491            crate::builtin::system_header(&name)
2492        } else {
2493            None
2494        };
2495        if built_in.is_some() {
2496            full_name = Some(format!("{}/{name}", crate::builtin::SYSTEM));
2497        }
2498
2499        let Some(full_name) = full_name else {
2500            self.error(format!("cannot open include file \"{name}\""));
2501            return;
2502        };
2503        if self.find_include_once(&full_name) {
2504            return;
2505        }
2506        let data = match built_in {
2507            Some(data) => data.to_vec(),
2508            None => {
2509                let Some(data) = self.files.read(&full_name) else {
2510                    self.error(format!("cannot open include file \"{full_name}\""));
2511                    return;
2512                };
2513                data
2514            }
2515        };
2516        let desc = self.file_desc(&full_name);
2517        if let Some(stream) = self.streams.last_mut() {
2518            stream.newline_spacing = self.newline_spacing;
2519        }
2520        let (data, charset_error) = decode_source(&data, self.files, &self.default_charset);
2521        self.streams.push(Stream {
2522            desc,
2523            data,
2524            pos: 0,
2525            next_line: 1,
2526            in_comment: false,
2527            init_if_level: self.if_stack.len(),
2528            newline_spacing: self.newline_spacing,
2529            charset_error,
2530        });
2531        if self.all_once {
2532            self.add_include_once(&full_name);
2533        }
2534    }
2535
2536    fn pp_define(&mut self) {
2537        if self.next_on_line() != Tok::Sym {
2538            let text = self.curtok_text();
2539            self.error(format!("invalid name \"{}\" for #define", show_name(&text)));
2540            self.clear_linebuf();
2541            return;
2542        }
2543        let name = self.curtok_text();
2544        let mut params: Vec<Vec<u8>> = Vec::new();
2545        let mut has_varargs = false;
2546        let mut has_args = false;
2547
2548        // A parameter list has to follow the name with no space between.
2549        if at(&self.linebuf, self.p) == b'(' {
2550            has_args = true;
2551            self.p += 1;
2552            let mut tok = self.next_on_line();
2553            let mut done = tok == Tok::RPar;
2554            while !done {
2555                if params.len() >= MAX_MACRO_ARGS {
2556                    self.error(format!(
2557                        "too many parameters for macro \"{}\" (maximum {MAX_MACRO_ARGS})",
2558                        show_name(&name)
2559                    ));
2560                    self.clear_linebuf();
2561                    return;
2562                }
2563                if tok == Tok::Eof {
2564                    self.error("missing ')' in macro parameter list");
2565                    self.clear_linebuf();
2566                    return;
2567                }
2568                if tok != Tok::Sym {
2569                    let text = self.curtok_text();
2570                    self.error(format!(
2571                        "invalid macro parameter name \"{}\"",
2572                        show_name(&text)
2573                    ));
2574                    self.clear_linebuf();
2575                    return;
2576                }
2577                params.push(self.curtok_text());
2578                tok = self.next_on_line();
2579                match tok {
2580                    Tok::Comma => tok = self.next_on_line(),
2581                    Tok::Ellipsis => {
2582                        tok = self.next_on_line();
2583                        has_varargs = true;
2584                        if tok != Tok::RPar {
2585                            let text = self.curtok_text();
2586                            self.error(format!(
2587                                "'...' in macro parameter list must be followed by ')' - found \"{}\"",
2588                                show_name(&text)
2589                            ));
2590                            self.clear_linebuf();
2591                            return;
2592                        }
2593                        done = true;
2594                    }
2595                    Tok::RPar => done = true,
2596                    _ => {
2597                        let text = self.curtok_text();
2598                        self.error(format!(
2599                            "expected ',' or ')' in macro parameter list (found \"{}\")",
2600                            show_name(&text)
2601                        ));
2602                        self.clear_linebuf();
2603                        return;
2604                    }
2605                }
2606            }
2607        }
2608
2609        while is_space(at(&self.linebuf, self.p)) {
2610            self.p += 1;
2611        }
2612        if name == b"defined" {
2613            self.error("cannot #define reserved macro name \"defined\"");
2614            self.clear_linebuf();
2615            return;
2616        }
2617        // The expansion is the rest of the line, as far as its text
2618        // goes, without the spaces at the end, unless a backslash comes
2619        // before the last of them.
2620        let expan_start = self.p;
2621        let mut expan_end = expan_start;
2622        while at(&self.linebuf, expan_end) != 0 {
2623            expan_end += 1;
2624        }
2625        while expan_end > expan_start
2626            && is_space(self.linebuf[expan_end - 1])
2627            && !(expan_end - expan_start > 1 && self.linebuf[expan_end - 2] == b'\\')
2628        {
2629            expan_end -= 1;
2630        }
2631        let orig = self.linebuf[expan_start..expan_end].to_vec();
2632        let expansion = self.parse_expansion(&orig, &params, has_varargs);
2633        let argc = params.len();
2634
2635        if let Some(old) = self.find_define(&name) {
2636            let old_macro = &self.macros[old];
2637            // Defining a macro again the same way is not a redefinition.
2638            if old_macro.has_args == has_args
2639                && old_macro.argc == argc
2640                && equal_collapse_spaces(&expansion, &self.expansion(old))
2641            {
2642                self.clear_linebuf();
2643                return;
2644            }
2645            self.warning(format!("redefinition of macro \"{}\"", show_name(&name)));
2646            self.undefs.insert(name.clone());
2647        }
2648        let id = self.macros.len();
2649        self.macros.push(Macro {
2650            name: name.clone(),
2651            kind: MacroKind::Define,
2652            has_args,
2653            argc,
2654            has_varargs,
2655            expansion,
2656            orig,
2657            params,
2658        });
2659        self.defines.insert(name, id);
2660        self.clear_linebuf();
2661    }
2662
2663    /// Put a macro's expansion in the form it is stored in: each use of a
2664    /// parameter becomes a marker, and so do `#foreach`, `#argcount`,
2665    /// `#ifempty`, and `#ifnempty` after the variable-argument parameter.
2666    fn parse_expansion(&mut self, orig: &[u8], params: &[Vec<u8>], has_varargs: bool) -> Vec<u8> {
2667        if params.is_empty() {
2668            return orig.to_vec();
2669        }
2670        let mut out = Vec::with_capacity(orig.len());
2671        let mut ec = EmbedCtx::default();
2672        let mut start = 0;
2673        let mut src = 0;
2674        let mut tok;
2675        loop {
2676            let mut cx = LexCtx {
2677                ec: Some(&mut ec),
2678                expanding: false,
2679                in_pp_expr: false,
2680                notes: &mut self.notes,
2681            };
2682            tok = lex::next_on_line(orig, &mut src, &mut cx);
2683            if tok.typ == Tok::Eof {
2684                break;
2685            }
2686            if tok.typ != Tok::Sym {
2687                continue;
2688            }
2689            // With two parameters of one name, the later one is found.
2690            let Some(index) = params.iter().rposition(|param| param == tok.text(orig)) else {
2691                continue;
2692            };
2693            let mut arg_len = params[index].len();
2694            let mut flag = FORMAL_FLAG;
2695            if has_varargs && index == params.len() - 1 && at(orig, src) == b'#' {
2696                let after = |word: &[u8]| {
2697                    orig.get(src + 1..src + 1 + word.len()) == Some(word)
2698                        && !is_sym(at(orig, src + 1 + word.len()))
2699                };
2700                if after(b"foreach") {
2701                    arg_len += 8;
2702                    flag = FOREACH_FLAG;
2703                } else if after(b"argcount") {
2704                    arg_len += 9;
2705                    flag = ARGCOUNT_FLAG;
2706                } else if after(b"ifempty") {
2707                    arg_len += 8;
2708                    flag = IFEMPTY_FLAG;
2709                } else if after(b"ifnempty") {
2710                    arg_len += 9;
2711                    flag = IFNEMPTY_FLAG;
2712                }
2713            }
2714            if tok.pos > start {
2715                out.extend_from_slice(&orig[start..tok.pos]);
2716            }
2717            start = tok.pos + arg_len;
2718            out.push(flag);
2719            if flag == FORMAL_FLAG {
2720                out.push((index + 1) as u8);
2721            }
2722        }
2723        self.flush_notes();
2724        if tok.pos > start {
2725            out.extend_from_slice(slice(orig, start, tok.pos));
2726        }
2727        // The stored text ends at a zero byte, if it has one.
2728        if let Some(end) = out.iter().position(|&c| c == 0) {
2729            out.truncate(end);
2730        }
2731        out
2732    }
2733
2734    /// Read a name that has to be the only thing on the rest of the line.
2735    fn pp_get_lone_ident(&mut self) -> Option<Vec<u8>> {
2736        if self.next_on_line() != Tok::Sym {
2737            let text = self.curtok_text();
2738            self.error(format!("invalid name \"{}\" for #define", show_name(&text)));
2739            return None;
2740        }
2741        let name = self.curtok_text();
2742        if self.next_on_line() != Tok::Eof {
2743            self.error("extra characters on line");
2744            return None;
2745        }
2746        Some(name)
2747    }
2748
2749    fn pp_ifdef_or_ifndef(&mut self, sense: bool) {
2750        let Some(name) = self.pp_get_lone_ident() else {
2751            self.clear_linebuf();
2752            self.push_if(IfState::IfYes);
2753            return;
2754        };
2755        let found = self.find_define(&name).is_some();
2756        self.push_if(if sense == found {
2757            IfState::IfYes
2758        } else {
2759            IfState::IfNo
2760        });
2761        self.clear_linebuf();
2762    }
2763
2764    /// Evaluate the expression of an `#if` or an `#elif`, whose macros
2765    /// have been expanded into the expansion buffer: whether it is true,
2766    /// or nothing if it has no constant value.
2767    fn pp_parse_expr(&mut self) -> Option<bool> {
2768        let (value, problems) = crate::parse::eval_pp_condition(&self.expbuf);
2769        self.report_all(problems);
2770        value
2771    }
2772
2773    /// Report the problems found in a directive's expression, at the
2774    /// directive.
2775    fn report_all(&mut self, problems: crate::parse::Problems) {
2776        for (severity, message) in problems {
2777            self.report(severity, message);
2778        }
2779    }
2780
2781    fn pp_if(&mut self) {
2782        if self.expand_macros_curline(false, true, false) {
2783            self.clear_linebuf();
2784            self.push_if(IfState::IfYes);
2785            return;
2786        }
2787        self.clear_linebuf();
2788        // An expression that cannot be evaluated counts as true.
2789        let value = self.pp_parse_expr().unwrap_or(true);
2790        self.push_if(if value { IfState::IfYes } else { IfState::IfNo });
2791    }
2792
2793    fn pp_elif(&mut self) {
2794        if self.expand_macros_curline(false, true, false) {
2795            self.clear_linebuf();
2796            return;
2797        }
2798        let Some(value) = self.pp_parse_expr() else {
2799            self.clear_linebuf();
2800            return;
2801        };
2802        let init_level = self.streams.last().map_or(0, |s| s.init_if_level);
2803        if self.if_stack.len() <= init_level {
2804            self.error("#elif without #if");
2805            self.clear_linebuf();
2806            return;
2807        }
2808        let state = self.if_stack.last().map(|level| level.state);
2809        match state {
2810            Some(IfState::IfYes) => self.change_if_state(IfState::IfDone),
2811            Some(IfState::IfNo) => {
2812                if value {
2813                    self.change_if_state(IfState::IfYes);
2814                }
2815            }
2816            Some(IfState::IfDone) => {}
2817            _ => self.error("#elif without #if"),
2818        }
2819        self.clear_linebuf();
2820    }
2821
2822    fn change_if_state(&mut self, state: IfState) {
2823        if let Some(level) = self.if_stack.last_mut() {
2824            level.state = state;
2825        }
2826    }
2827
2828    fn pp_else(&mut self) {
2829        if self.next_on_line() != Tok::Eof {
2830            self.error("extra characters on line");
2831        }
2832        let init_level = self.streams.last().map_or(0, |s| s.init_if_level);
2833        if self.if_stack.len() <= init_level {
2834            self.error("#else without #if");
2835            self.clear_linebuf();
2836            return;
2837        }
2838        let state = self.if_stack.last().map(|level| level.state);
2839        match state {
2840            Some(IfState::IfYes | IfState::IfDone) => self.change_if_state(IfState::ElseNo),
2841            Some(IfState::IfNo) => self.change_if_state(IfState::ElseYes),
2842            _ => self.error("#else without #if"),
2843        }
2844        self.clear_linebuf();
2845    }
2846
2847    fn pp_endif(&mut self) {
2848        if self.next_on_line() != Tok::Eof {
2849            self.error("extra characters on line");
2850        }
2851        self.clear_linebuf();
2852        let init_level = self.streams.last().map_or(0, |s| s.init_if_level);
2853        // With no #if open at all, or none that this file opened.
2854        if self.if_stack.len() <= init_level {
2855            self.error("#endif without #if");
2856            return;
2857        }
2858        self.pop_if();
2859    }
2860
2861    fn pp_error(&mut self) {
2862        let startofs = self.curtok.end();
2863        // A problem in an English source, as its reader wrote it: plain
2864        // words, not to be expanded.
2865        let english = self
2866            .streams
2867            .last()
2868            .and_then(|stream| self.descs.get(stream.desc))
2869            .is_some_and(|desc| crate::english::is_english(&desc.name));
2870        if english && !self.pp_only {
2871            let message = String::from_utf8_lossy(slice(&self.linebuf, startofs, usize::MAX))
2872                .trim()
2873                .to_owned();
2874            self.error(message);
2875            self.clear_linebuf();
2876            return;
2877        }
2878        self.expbuf = slice(&self.linebuf, 0, startofs).to_vec();
2879        if self.expand_macros_curline(false, false, true) {
2880            self.clear_linebuf();
2881            return;
2882        }
2883        remove_expansion_flags(&mut self.expbuf);
2884        if self.pp_only {
2885            // The compiler proper reports the error; the line is passed
2886            // on to it.
2887            self.linebuf = self.expbuf.clone();
2888        } else {
2889            let message =
2890                String::from_utf8_lossy(slice(&self.expbuf, startofs, usize::MAX)).into_owned();
2891            self.error(format!("#error : {message}"));
2892            self.clear_linebuf();
2893        }
2894    }
2895
2896    fn pp_undef(&mut self) {
2897        if let Some(name) = self.pp_get_lone_ident() {
2898            self.undefine_bytes(&name);
2899        }
2900        self.clear_linebuf();
2901    }
2902
2903    fn pp_line(&mut self) {
2904        if self.expand_macros_curline(false, true, false) {
2905            self.clear_linebuf();
2906            return;
2907        }
2908        let text = self.expbuf.clone();
2909        self.clear_linebuf();
2910        let (value, problems) = crate::parse::eval_pp_line(&text);
2911        self.report_all(problems);
2912        if let Some((line, name)) = value {
2913            let desc = self.file_desc(&String::from_utf8_lossy(&name));
2914            if let Some(stream) = self.streams.last_mut() {
2915                stream.next_line = line as u32;
2916                stream.desc = desc;
2917            }
2918        }
2919    }
2920}
2921
2922// ---- helpers ----
2923
2924/// A piece of a buffer, with both ends kept within it.
2925fn slice(buf: &[u8], start: usize, end: usize) -> &[u8] {
2926    let end = end.min(buf.len());
2927    let start = start.min(end);
2928    &buf[start..end]
2929}
2930
2931/// Where an argument that ends at `end` really ends, without the spaces
2932/// after it. A backslash before the spaces keeps one of them, since it
2933/// escapes it.
2934fn trim_end(buf: &[u8], start: usize, end: usize) -> usize {
2935    let mut p = end;
2936    let mut spaces = 0;
2937    while p > start {
2938        p -= 1;
2939        let c = at(buf, p);
2940        if !is_space(c) {
2941            p += 1;
2942            if c == b'\\' && spaces != 0 {
2943                p += 1;
2944            }
2945            break;
2946        }
2947        spaces += 1;
2948    }
2949    p
2950}
2951
2952/// Whether the text from `pos` has a marker for the end of the expansion
2953/// of the macro `id`: if so, the text is part of that macro's own
2954/// expansion, and the macro is not expanded again within it.
2955fn scan_for_prior_expansion(buf: &[u8], pos: usize, end: usize, id: usize) -> bool {
2956    let mut p = pos;
2957    while p < end {
2958        if at(buf, p) == MACRO_EXP_END {
2959            if lex::macro_end_id(buf, p) == id {
2960                return true;
2961            }
2962            p += 1 + MACRO_ID_LEN;
2963        } else {
2964            p += 1;
2965        }
2966    }
2967    false
2968}
2969
2970/// Take the markers out of text that is finished with macro expansion.
2971/// The text ends at a zero byte.
2972fn remove_expansion_flags(buf: &mut Vec<u8>) {
2973    let mut out = Vec::with_capacity(buf.len());
2974    let mut p = 0;
2975    while at(buf, p) != 0 {
2976        match buf[p] {
2977            MACRO_EXP_END => p += 1 + MACRO_ID_LEN,
2978            FULLY_EXPANDED_FLAG => p += 1,
2979            c => {
2980                out.push(c);
2981                p += 1;
2982            }
2983        }
2984    }
2985    *buf = out;
2986}
2987
2988/// Take the markers for the ends of expansions out of `buf` from `from`.
2989fn remove_end_markers(buf: &mut Vec<u8>, from: usize) {
2990    let mut out = buf[..from].to_vec();
2991    let mut p = from;
2992    while p < buf.len() {
2993        if buf[p] == MACRO_EXP_END {
2994            p += 1 + MACRO_ID_LEN;
2995        } else {
2996            out.push(buf[p]);
2997            p += 1;
2998        }
2999    }
3000    *buf = out;
3001}
3002
3003/// Skip the parts of a `#foreach` or `#ifempty` that are not wanted: from
3004/// the delimiter at `p`, past `parts` more of them.
3005fn skip_delimited_group(buf: &[u8], p: &mut usize, parts: u32) {
3006    let delim = at(buf, *p);
3007    if delim == 0 || delim == lex::END_PP_LINE {
3008        return;
3009    }
3010    *p += 1;
3011    let mut parts = parts;
3012    while parts != 0 {
3013        let c = at(buf, *p);
3014        if c == 0 || c == lex::END_PP_LINE {
3015            return;
3016        }
3017        if c == delim {
3018            parts -= 1;
3019            *p += 1;
3020        } else if c == FOREACH_FLAG {
3021            skip_delimited_group(buf, p, 2);
3022        } else if c == IFEMPTY_FLAG || c == IFNEMPTY_FLAG {
3023            skip_delimited_group(buf, p, 1);
3024        } else {
3025            *p += 1;
3026        }
3027    }
3028}
3029
3030/// Add an argument to `out` as a string: runs of spaces become one, and
3031/// quotes and backslashes that would end or change the string are
3032/// escaped.
3033fn stringize_macro_actual(out: &mut Vec<u8>, actual: &[u8], quote: u8, open: bool, close: bool) {
3034    if open {
3035        out.push(quote);
3036    }
3037    let len = actual.len();
3038    let mut start = 0;
3039    let mut src = 0;
3040    let mut in_inner_quote = false;
3041    let mut inner_quote = 0u8;
3042    let mut prev = 0u8;
3043    while src < len {
3044        let cur = actual[src];
3045        if is_space(cur) && prev != b'\\' {
3046            out.extend_from_slice(&actual[start..src]);
3047            while src < len && is_space(actual[src]) {
3048                src += 1;
3049            }
3050            if prev != 0 && src < len {
3051                out.push(b' ');
3052            }
3053            prev = cur;
3054            start = src;
3055            continue;
3056        }
3057        if cur == quote || (cur == b'\\' && in_inner_quote) {
3058            out.extend_from_slice(&actual[start..src]);
3059            out.push(b'\\');
3060            start = src;
3061        }
3062        if prev != b'\\' {
3063            if in_inner_quote && cur == inner_quote {
3064                in_inner_quote = false;
3065            } else if !in_inner_quote && (cur == b'"' || cur == b'\'') {
3066                in_inner_quote = true;
3067                inner_quote = cur;
3068            }
3069        }
3070        prev = cur;
3071        src += 1;
3072    }
3073    out.extend_from_slice(&actual[start..src]);
3074    if close {
3075        out.push(quote);
3076    }
3077}
3078
3079/// Whether two expansions are the same, counting any run of spaces as
3080/// the same as any other.
3081fn equal_collapse_spaces(a: &[u8], b: &[u8]) -> bool {
3082    let (mut i, mut j) = (0, 0);
3083    while i < a.len() && j < b.len() {
3084        if is_space(a[i]) && is_space(b[j]) {
3085            while i < a.len() && is_space(a[i]) {
3086                i += 1;
3087            }
3088            while j < b.len() && is_space(b[j]) {
3089                j += 1;
3090            }
3091            continue;
3092        }
3093        if a[i] != b[j] {
3094            return false;
3095        }
3096        i += 1;
3097        j += 1;
3098    }
3099    i == a.len() && j == b.len()
3100}
3101
3102// ---- file names ----
3103
3104fn is_separator(c: char) -> bool {
3105    c == '/' || c == '\\'
3106}
3107
3108/// A file's name without its folder.
3109fn root_name(name: &str) -> &str {
3110    match name.rfind(is_separator) {
3111        Some(index) => &name[index + 1..],
3112        None => name,
3113    }
3114}
3115
3116/// The folder a file is in, or an empty string if its name has none.
3117fn dir_name(name: &str) -> &str {
3118    match name.rfind(is_separator) {
3119        Some(index) => &name[..index],
3120        None => "",
3121    }
3122}
3123
3124fn join_path(dir: &str, name: &str) -> String {
3125    if dir.is_empty() || is_absolute(name) {
3126        name.to_owned()
3127    } else if dir.ends_with(is_separator) {
3128        format!("{dir}{name}")
3129    } else if crate::builtin::is_built_in(dir) {
3130        // The built-in files are named the same on every system, so that
3131        // an image built from them is too.
3132        format!("{dir}/{name}")
3133    } else {
3134        // As the reference joins them: with the system's separator.
3135        format!("{dir}{}{name}", std::path::MAIN_SEPARATOR)
3136    }
3137}
3138
3139fn is_absolute(name: &str) -> bool {
3140    let bytes = name.as_bytes();
3141    name.starts_with(is_separator)
3142        || (bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic())
3143}
3144
3145/// Whether two names are for the same file, as far as the names show.
3146fn file_names_equal(a: &str, b: &str) -> bool {
3147    let normal = |name: &str| name.replace('\\', "/").to_ascii_lowercase();
3148    normal(a) == normal(b)
3149}
3150
3151/// Which chain of the reference's table of macros a name is in.
3152pub(crate) fn macro_chain(name: &[u8]) -> usize {
3153    name.iter().map(|&byte| usize::from(byte)).sum::<usize>() % 512
3154}
3155
3156/// A name as messages show it: a character that is not ASCII is given
3157/// as its code.
3158pub(crate) fn show_name(name: &[u8]) -> String {
3159    // The reference shows at most 60 bytes of a name, and marks one it
3160    // has cut short.
3161    const LIMIT: usize = 60;
3162    let cut = name.len() > LIMIT;
3163    let name = if cut { &name[..LIMIT] } else { name };
3164    let mut out = String::new();
3165    for c in String::from_utf8_lossy(name).chars() {
3166        if c.is_ascii() {
3167            out.push(c);
3168        } else {
3169            out.push_str(&format!("\\u{:04x}", u32::from(c)));
3170        }
3171    }
3172    if cut {
3173        out.push_str("...");
3174    }
3175    out
3176}
3177
3178/// What stands in for a byte that the file's character set has no
3179/// character for.
3180const REPLACEMENT: &str = "\u{fffd}";
3181
3182/// Text in one of the character sets that are built in, as UTF-8; `None`
3183/// for a set that is not known.
3184fn decode_charset(name: &str, bytes: &[u8]) -> Option<Vec<u8>> {
3185    let mut out = Vec::with_capacity(bytes.len());
3186    match name.to_ascii_lowercase().as_str() {
3187        "utf-8" | "utf8" => out.extend_from_slice(bytes),
3188        "us-ascii" | "ascii" | "asc7dflt" => {
3189            for &c in bytes {
3190                if c.is_ascii() {
3191                    out.push(c);
3192                } else {
3193                    out.extend_from_slice(REPLACEMENT.as_bytes());
3194                }
3195            }
3196        }
3197        "iso-8859-1" | "iso8859-1" | "iso_8859-1" | "latin1" | "latin-1" | "iso1" | "8859-1"
3198        | "l1" | "cp819" | "iso-ir-100" => {
3199            for &c in bytes {
3200                out.extend_from_slice(char::from(c).encode_utf8(&mut [0; 4]).as_bytes());
3201            }
3202        }
3203        _ => return None,
3204    }
3205    Some(out)
3206}
3207
3208/// The name in `#charset "name"`, if that is how the text starts, and
3209/// how long the directive is, up to and including its closing quote.
3210fn charset_directive(text: &[u8]) -> Option<(&[u8], usize)> {
3211    let rest = text.strip_prefix(b"#charset ")?;
3212    let spaces = rest
3213        .iter()
3214        .take_while(|&&c| c == b' ' || c == b'\t')
3215        .count();
3216    let rest = rest[spaces..].strip_prefix(b"\"")?;
3217    let len = rest
3218        .iter()
3219        .position(|&c| c == b'"' || c == b'\n' || c == b'\r')?;
3220    if rest[len] != b'"' {
3221        return None;
3222    }
3223    Some((&rest[..len], 9 + spaces + 1 + len + 1))
3224}
3225
3226/// A source file's bytes as UTF-8, and whether the file names a
3227/// character set that is not known.
3228///
3229/// A file that starts with a byte order mark is in the Unicode encoding
3230/// the mark is for. Otherwise a `#charset "name"` directive at the very
3231/// start of the file says what it is in, and without one it is plain
3232/// in the default character set, which is UTF-8 unless whoever is
3233/// compiling says otherwise. A directive that is understood is taken out, leaving the rest
3234/// of its line, so that the lines after it keep their numbers; one that
3235/// is not is left for the preprocessor to complain about.
3236fn decode_source(
3237    data: &[u8],
3238    files: &mut dyn SourceFiles,
3239    default_charset: &str,
3240) -> (Vec<u8>, bool) {
3241    if let Some(rest) = data.strip_prefix(&[0xef, 0xbb, 0xbf]) {
3242        let skip = match charset_directive(rest) {
3243            Some((name, len)) if name.eq_ignore_ascii_case(b"utf-8") => len,
3244            Some((name, len)) if name.eq_ignore_ascii_case(b"utf8") => len,
3245            _ => 0,
3246        };
3247        return (rest[skip..].to_vec(), false);
3248    }
3249    for (mark, big_endian, names) in [
3250        ([0xff, 0xfe], false, ["unicodel", "utf-16le"]),
3251        ([0xfe, 0xff], true, ["unicodeb", "utf-16be"]),
3252    ] {
3253        let Some(rest) = data.strip_prefix(&mark) else {
3254            continue;
3255        };
3256        let units: Vec<u16> = rest
3257            .as_chunks::<2>()
3258            .0
3259            .iter()
3260            .map(|pair| {
3261                if big_endian {
3262                    u16::from_be_bytes([pair[0], pair[1]])
3263                } else {
3264                    u16::from_le_bytes([pair[0], pair[1]])
3265                }
3266            })
3267            .collect();
3268        let text = String::from_utf16_lossy(&units).into_bytes();
3269        let skip = match charset_directive(&text) {
3270            Some((name, len))
3271                if names
3272                    .iter()
3273                    .any(|n| name.eq_ignore_ascii_case(n.as_bytes())) =>
3274            {
3275                len
3276            }
3277            _ => 0,
3278        };
3279        return (text[skip..].to_vec(), false);
3280    }
3281    let mut charset_error = false;
3282    if let Some((name, len)) = charset_directive(data) {
3283        let name = String::from_utf8_lossy(name);
3284        let text =
3285            decode_charset(&name, &data[len..]).or_else(|| files.decode(&name, &data[len..]));
3286        match text {
3287            Some(text) => return (text, false),
3288            None => charset_error = true,
3289        }
3290    }
3291    let text = decode_charset(default_charset, data)
3292        .or_else(|| files.decode(default_charset, data))
3293        .or_else(|| decode_charset("us-ascii", data))
3294        .unwrap_or_default();
3295    (text, charset_error)
3296}
3297
3298/// Whether the word from `start` to `end` in a line stands where an
3299/// object's name goes: nothing but spaces and `+` signs before it, and a
3300/// colon after it (not `::`).
3301fn stands_as_name(line: &[u8], start: usize, end: usize) -> bool {
3302    let start = start.min(line.len());
3303    let end = end.clamp(start, line.len());
3304    if !line[..start]
3305        .iter()
3306        .all(|&c| c == b' ' || c == b'\t' || c == b'+')
3307    {
3308        return false;
3309    }
3310    let rest = &line[end..];
3311    let after = rest
3312        .iter()
3313        .position(|&c| c != b' ' && c != b'\t')
3314        .map(|i| &rest[i..]);
3315    matches!(after, Some([b':', next, ..]) if *next != b':') || after == Some(b":")
3316}
3317
3318#[cfg(test)]
3319mod path_tests {
3320    use super::join_path;
3321
3322    #[test]
3323    fn a_built_in_file_is_named_the_same_on_every_system() {
3324        // An image records the files it was built from, so the built-in
3325        // ones must not take the system's separator.
3326        assert_eq!(
3327            join_path("<hexicon>/system", "vector.hxh"),
3328            "<hexicon>/system/vector.hxh"
3329        );
3330        let sep = std::path::MAIN_SEPARATOR;
3331        assert_eq!(
3332            join_path("inc", "vector.hxh"),
3333            format!("inc{sep}vector.hxh")
3334        );
3335    }
3336}