1use std::collections::{HashMap, HashSet};
18use std::path::{Path, PathBuf};
19
20use rucc_base::{Interner, Symbol};
21use rucc_diag::{Diagnostic, FileId, SourceMapFull, Span};
22use rucc_gnu::Kind;
23use rucc_lex::{Options, PpToken, PpTokenKind, Punct, TokenFlags, tokenize};
24use rucc_session::{Found, IncludeForm, PrefixMap, Preinclude};
25use rucc_target::TargetInfo;
26
27use crate::cond;
28use crate::embed;
29use crate::expand::Expander;
30use crate::include::{
31 Context, Dependency, Frame, Header, Reader, directory_of, header_from_token,
32 header_from_tokens, spelling,
33};
34use crate::macros::{Builtin, MacroTable, parse_define};
35use crate::predef::{BUILT_IN, COMMAND_LINE, Predef, built_in, command_line};
36use crate::token::Tok;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40enum Guard {
41 Once,
43 Macro(Symbol),
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52enum Scan {
53 Start,
55 Inside(Symbol),
57 Closed(Symbol),
59 No,
61}
62
63#[derive(Debug)]
65struct Cond {
66 span: Span,
68 live: bool,
71 taken: bool,
74 enclosing_live: bool,
76 seen_else: bool,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct LineDirective {
83 pub span: Span,
85 pub line: u32,
87 pub file: Option<Symbol>,
89 pub at: usize,
98}
99
100#[derive(Debug, Default)]
105pub struct Preprocessor {
106 macros: MacroTable,
107 expander: Expander,
108 diagnostics: Vec<Diagnostic>,
109 conds: Vec<Cond>,
110 lines: Vec<LineDirective>,
111 stack: Vec<Frame>,
113 markers: Vec<String>,
117 seen: HashMap<PathBuf, Guard>,
121 deps: Vec<Dependency>,
128 dep_ids: HashSet<PathBuf>,
140}
141
142impl Preprocessor {
143 pub fn new() -> Preprocessor {
145 Preprocessor::default()
146 }
147
148 pub fn with_prefix_map(map: PrefixMap) -> Preprocessor {
155 Preprocessor { expander: Expander::with_prefix_map(map), ..Preprocessor::default() }
156 }
157
158 pub fn macros(&self) -> &MacroTable {
160 &self.macros
161 }
162
163 pub fn macros_mut(&mut self) -> &mut MacroTable {
165 &mut self.macros
166 }
167
168 pub fn diagnostics(&self) -> &[Diagnostic] {
170 &self.diagnostics
171 }
172
173 pub fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
175 std::mem::take(&mut self.diagnostics)
176 }
177
178 pub fn dependencies(&self) -> &[Dependency] {
183 &self.deps
184 }
185
186 pub fn line_directives(&self) -> &[LineDirective] {
192 &self.lines
193 }
194
195 pub fn predefine(
207 &mut self,
208 target: &TargetInfo,
209 opts: &Predef,
210 cx: &mut Context<'_>,
211 ) -> Result<(), SourceMapFull> {
212 let names = Names::new(cx.interner);
213 let file = self.synthetic(BUILT_IN, built_in(target, opts), cx, &names)?;
214 let start = cx.sources.file(file).start;
220 for (spelling, builtin) in Builtin::ALL {
221 let name = cx.interner.intern(spelling);
222 self.macros.define_builtin(name, builtin, Span::new(start, start));
223 }
224 let text = command_line(opts);
225 if !text.is_empty() {
226 self.synthetic(COMMAND_LINE, text, cx, &names)?;
227 }
228 Ok(())
229 }
230
231 fn synthetic(
233 &mut self,
234 name: &str,
235 text: String,
236 cx: &mut Context<'_>,
237 names: &Names,
238 ) -> Result<FileId, SourceMapFull> {
239 let file = cx.sources.add(name, text.into_bytes())?;
240 let mut out = Vec::new();
241 let path = PathBuf::from(name);
245 let id = cx.fs.identity(&path);
246 self.stack.push(Frame { at: Span::DUMMY, path, id, dir: None, next: 0 });
247 self.process(file, &mut out, cx, names);
248 self.stack.clear();
249 debug_assert!(out.is_empty(), "{name} is directives only and produces no tokens");
250 Ok(file)
251 }
252
253 pub fn preinclude(
275 &mut self,
276 files: &[Preinclude],
277 out: &mut Vec<Tok>,
278 cx: &mut Context<'_>,
279 ) -> Result<(), SourceMapFull> {
280 if files.is_empty() {
281 return Ok(());
282 }
283 let names = Names::new(cx.interner);
284 let mut text = String::new();
288 let mut order: Vec<(usize, &Preinclude)> = Vec::new();
289 for macros_only in [true, false] {
290 for file in files.iter().filter(|f| f.macros_only == macros_only) {
291 text.push_str(if macros_only { "-imacros " } else { "-include " });
292 order.push((text.len(), file));
293 text.push_str(&file.name);
294 text.push('\n');
295 }
296 }
297 let record = cx.sources.add(COMMAND_LINE, text.into_bytes())?;
298 let start = cx.sources.file(record).start;
299 let path = PathBuf::from(COMMAND_LINE);
303 let id = cx.fs.identity(&path);
304 self.stack.push(Frame { at: Span::DUMMY, path, id, dir: None, next: 0 });
305 let here = Path::new(".");
306 for (offset, file) in order {
307 let at = Span::new(start + offset as u32, start + (offset + file.name.len()) as u32);
308 let form = IncludeForm::Quoted;
309 let found = cx.search.resolve(cx.fs, &file.name, form, Some(here), 0);
310 let Some(found) = found else {
311 let tried = cx.search.tried(&file.name, form, Some(here), 0);
312 self.not_found(&file.name, at, &tried);
313 continue;
314 };
315 let mut discarded = Vec::new();
316 let sink = if file.macros_only { &mut discarded } else { &mut *out };
317 self.read(found, at, sink, cx, &names);
318 }
319 self.stack.clear();
320 Ok(())
321 }
322
323 pub fn run(&mut self, file: FileId, cx: &mut Context<'_>) -> Vec<Tok> {
328 let names = Names::new(cx.interner);
329 let mut out = Vec::new();
330 let name = cx.sources.file(file).name.clone();
331 let dir = directory_of(&name);
332 let path = PathBuf::from(name);
335 let id = cx.fs.identity(&path);
336 self.stack.push(Frame { at: Span::DUMMY, path, id, dir, next: 0 });
337 self.process(file, &mut out, cx, &names);
338 self.stack.clear();
339 out
340 }
341
342 fn process(&mut self, file: FileId, out: &mut Vec<Tok>, cx: &mut Context<'_>, names: &Names) {
344 let bytes = cx.sources.file(file).shared_bytes();
347 let start = cx.sources.file(file).start;
348 let mut reader = Reader::new(bytes.as_slice(), start, cx.lex);
349 let depth_on_entry = self.conds.len();
350 let mut text: Vec<Tok> = Vec::new();
354 let mut body: Vec<PpToken> = Vec::new();
355 let mut scan = Scan::Start;
356
357 loop {
358 let was_live = self.live();
359 let first = reader.next(cx.interner);
360 if first.is_eof() {
361 break;
362 }
363 if is_directive(first) {
364 self.flush(&mut text, out, cx, names);
365 body.clear();
366 let name_tok = reader.next(cx.interner);
367 if name_tok.is_eof() || name_tok.flags.has(TokenFlags::START_OF_LINE) {
370 reader.put_back(name_tok);
371 continue;
372 }
373 body.push(name_tok);
374 if was_live && is_include(ident_of(&name_tok), names) {
379 if let Some(header) = reader.header_name(cx.interner) {
380 body.push(header);
381 }
382 }
383 reader.line(cx.interner, &mut body);
384 let opens =
385 matches!(scan, Scan::Start).then(|| guard_opener(&body, names)).flatten();
386 self.directive(&body, first.span, out, cx, names);
387 scan = match scan {
388 Scan::Start => match opens {
392 Some(name) if self.conds.len() == depth_on_entry + 1 => Scan::Inside(name),
393 _ => Scan::No,
394 },
395 Scan::Inside(name) if self.conds.len() == depth_on_entry => Scan::Closed(name),
396 Scan::Inside(name) => Scan::Inside(name),
397 Scan::Closed(_) | Scan::No => Scan::No,
398 };
399 } else {
400 body.clear();
401 reader.line(cx.interner, &mut body);
402 if self.live() {
403 let operator = ident_of(&first) == Some(names.pragma_op)
409 || body.iter().any(|t| ident_of(t) == Some(names.pragma_op));
410 if operator {
411 self.flush(&mut text, out, cx, names);
412 }
413 text.push(Tok::new(first));
414 text.extend(body.iter().copied().map(Tok::new));
415 if operator {
416 self.flush(&mut text, out, cx, names);
417 }
418 }
419 if !matches!(scan, Scan::Inside(_)) {
421 scan = Scan::No;
422 }
423 }
424 let complaints = reader.take_diagnostics();
427 if was_live || self.live() {
428 self.diagnostics.extend(complaints);
429 }
430 }
431 self.flush(&mut text, out, cx, names);
432 self.diagnostics.extend(reader.take_diagnostics());
433
434 if let Scan::Closed(name) = scan {
437 if self.macros.is_defined(name) {
438 if let Some(frame) = self.stack.last() {
439 self.seen.entry(frame.id.clone()).or_insert(Guard::Macro(name));
440 }
441 }
442 }
443
444 for cond in self.conds.drain(depth_on_entry..) {
447 self.diagnostics
448 .push(Diagnostic::error("unterminated `#if`", cond.span).with_code("E0330"));
449 }
450 }
451
452 fn live(&self) -> bool {
454 self.conds.last().is_none_or(|c| c.live)
455 }
456
457 fn flush(
459 &mut self,
460 text: &mut Vec<Tok>,
461 out: &mut Vec<Tok>,
462 cx: &mut Context<'_>,
463 names: &Names,
464 ) {
465 if text.is_empty() {
466 return;
467 }
468 let taken = std::mem::take(text);
469 let expanded = self.expander.expand_toks(taken, &self.macros, cx.interner, cx.sources);
470 self.diagnostics.append(&mut self.expander.take_diagnostics());
471 let expanded = self.resolve_has(expanded, cx, names, Pass::Text);
476 self.pragma_operator(expanded, out, cx.interner, names);
477 }
478
479 fn directive(
481 &mut self,
482 body: &[PpToken],
483 hash: Span,
484 out: &mut Vec<Tok>,
485 cx: &mut Context<'_>,
486 names: &Names,
487 ) {
488 let Some(first) = body.first().copied() else {
489 return;
490 };
491 let name = ident_of(&first);
492 let rest = &body[1..];
493
494 if name == Some(names.r#if) {
497 let value = self.live() && self.eval(rest, hash, cx, names);
498 self.open(hash, value);
499 return;
500 }
501 if name == Some(names.ifdef) || name == Some(names.ifndef) {
502 let want = name == Some(names.ifdef);
503 let value = self.live() && self.defined_check(rest, hash, want, names);
504 self.open(hash, value);
505 return;
506 }
507 if name == Some(names.elif) || name == Some(names.elifdef) || name == Some(names.elifndef) {
508 self.elif(name, rest, hash, cx, names);
509 return;
510 }
511 if name == Some(names.r#else) {
512 self.branch_else(rest, hash);
513 return;
514 }
515 if name == Some(names.endif) {
516 self.endif(rest, hash);
517 return;
518 }
519 if !self.live() {
520 return;
524 }
525
526 if name.is_none() && decimal(&first, cx.interner).is_some() {
530 self.line_marker(body, hash, out.len(), cx);
531 return;
532 }
533
534 let interner = &mut *cx.interner;
535 if name == Some(names.define) {
536 let (def, diagnostics) = parse_define(rest, interner);
537 self.diagnostics.extend(diagnostics);
538 if let Some(def) = def {
539 if let Some(problem) = self.macros.define(def, interner) {
540 self.diagnostics.push(problem);
541 }
542 }
543 } else if name == Some(names.undef) {
544 self.undef(rest, hash, interner);
545 } else if name == Some(names.error) || name == Some(names.warning) {
546 self.message(rest, hash, name == Some(names.error), interner);
547 } else if name == Some(names.line) {
548 self.line(rest, hash, out.len(), cx);
549 } else if name == Some(names.pragma) {
550 if rest.len() == 1 && ident_of(&rest[0]) == Some(names.once) {
557 self.pragma_once(rest[0].span);
558 } else if !self.macro_stack_pragma(rest, hash, interner, names) {
559 self.pass_through(body, hash, out);
560 }
561 } else if name == Some(names.include) || name == Some(names.include_next) {
562 self.include(rest, hash, name == Some(names.include_next), out, cx, names);
563 } else if name == Some(names.embed) {
564 self.embed(rest, hash, out, cx);
565 } else {
566 self.diagnostics.push(
567 Diagnostic::error("invalid preprocessing directive", first.span).with_code("E0332"),
568 );
569 }
570 }
571
572 fn macro_stack_pragma(
584 &mut self,
585 rest: &[PpToken],
586 at: Span,
587 interner: &mut Interner,
588 names: &Names,
589 ) -> bool {
590 let which = match rest.first().and_then(ident_of) {
591 Some(name) if name == names.push_macro => names.push_macro,
592 Some(name) if name == names.pop_macro => names.pop_macro,
593 _ => return false,
594 };
595 let word = if which == names.push_macro { "push_macro" } else { "pop_macro" };
596 let [_, open, text, close, extra @ ..] = rest else {
601 self.invalid_pragma(word, at);
602 return true;
603 };
604 if open.punct() != Some(Punct::LParen)
605 || text.kind != PpTokenKind::StringLit
606 || close.punct() != Some(Punct::RParen)
607 {
608 self.invalid_pragma(word, at);
609 return true;
610 }
611 self.extra_tokens(extra, "#pragma");
612 let Some(name) = identifier_in(*text, interner) else {
617 return true;
618 };
619 if which == names.push_macro {
620 self.macros.push_macro(name);
621 } else {
622 self.macros.pop_macro(name);
623 }
624 true
625 }
626
627 fn invalid_pragma(&mut self, word: &str, at: Span) {
628 self.diagnostics.push(
629 Diagnostic::error(format!("invalid `#pragma {word}` directive"), at).with_code("E0672"),
630 );
631 }
632
633 fn pragma_once(&mut self, at: Span) {
635 if self.stack.len() <= 1 {
640 self.diagnostics.push(
641 Diagnostic::warning("`#pragma once` in the main file", at).with_code("W0332"),
642 );
643 }
644 if let Some(frame) = self.stack.last() {
645 self.seen.insert(frame.id.clone(), Guard::Once);
646 }
647 }
648
649 fn skip(&self, id: &Path) -> bool {
651 match self.seen.get(id) {
652 Some(Guard::Once) => true,
653 Some(Guard::Macro(name)) => self.macros.is_defined(*name),
654 None => false,
655 }
656 }
657
658 fn pass_through(&mut self, body: &[PpToken], hash: Span, out: &mut Vec<Tok>) {
660 let _ = self;
661 out.push(Tok::synthetic(
662 PpTokenKind::Punct(Punct::Hash),
663 None,
664 TokenFlags::START_OF_LINE,
665 hash,
666 ));
667 for (at, token) in body.iter().copied().enumerate() {
672 let mut token = Tok::new(token);
673 if at == 0 {
674 token.flags = token.flags.without(TokenFlags::LEADING_SPACE);
675 }
676 out.push(token);
677 }
678 }
679
680 fn include(
682 &mut self,
683 rest: &[PpToken],
684 hash: Span,
685 is_next: bool,
686 out: &mut Vec<Tok>,
687 cx: &mut Context<'_>,
688 names: &Names,
689 ) {
690 let Some(header) = self.header_of(rest, hash, cx) else {
691 return;
692 };
693 let (form, relative_to, from) = self.where_to_look(&header, is_next, cx);
694 let found = cx.search.resolve(cx.fs, &header.name, form, relative_to.as_deref(), from);
695 let Some(found) = found else {
696 let tried = cx.search.tried(&header.name, form, relative_to.as_deref(), from);
697 self.not_found(&header.name, hash, &tried);
698 return;
699 };
700 self.read(found, hash, out, cx, names);
701 }
702
703 fn not_found(&mut self, name: &str, at: Span, tried: &[PathBuf]) {
705 let where_looked = if tried.is_empty() && Path::new(name).is_absolute() {
709 "the name is an absolute path, so the search path was not used".to_owned()
710 } else if tried.is_empty() {
711 "the include search path is empty".to_owned()
712 } else {
713 let list: Vec<String> =
714 tried.iter().map(|d| d.to_string_lossy().into_owned()).collect();
715 format!("searched: {}", list.join(", "))
716 };
717 self.diagnostics.push(
718 Diagnostic::error(format!("`{name}` file not found"), at)
719 .with_code("E0341")
720 .note(where_looked, at),
721 );
722 }
723
724 fn read(
731 &mut self,
732 found: Found,
733 at: Span,
734 out: &mut Vec<Tok>,
735 cx: &mut Context<'_>,
736 names: &Names,
737 ) {
738 let id = cx.fs.identity(&found.path);
739 if self.dep_ids.insert(id.clone()) {
744 let path = rucc_session::path_key(&found.path);
751 self.deps.push(Dependency { path, is_system: found.is_system });
752 }
753 if self.skip(&id) {
758 return;
759 }
760 if self.stack.len() >= cx.max_include_depth as usize {
761 let mut diagnostic = Diagnostic::error("`#include` nested too deeply", at)
762 .with_code("E0342")
763 .note("a header that includes itself with no include guard is the usual cause", at);
764 if let Some(outer) = self.stack.first().filter(|f| !f.at.is_dummy()) {
765 diagnostic = diagnostic.note("the outermost include is here", outer.at);
766 }
767 self.diagnostics.push(diagnostic);
768 return;
769 }
770 let added = cx.sources.add_shared(found.name.clone(), found.bytes.clone(), Some(at));
771 let file = match added {
772 Ok(file) => file,
773 Err(full) => {
774 self.diagnostics.push(Diagnostic::error(full.to_string(), at).with_code("E0344"));
775 return;
776 }
777 };
778 self.stack.push(Frame {
779 at,
780 dir: found.path.parent().map(Path::to_path_buf),
781 id,
782 path: found.path,
783 next: found.next,
784 });
785 self.process(file, out, cx, names);
786 self.stack.pop();
787 }
788
789 fn embed(&mut self, rest: &[PpToken], hash: Span, out: &mut Vec<Tok>, cx: &mut Context<'_>) {
791 let Some((header, params)) = self.embed_line(rest, hash, cx) else {
792 return;
793 };
794 let Some(found) = self.find(&header, false, cx) else {
795 self.diagnostics.push(
796 Diagnostic::error(format!("`{}` resource not found", header.name), hash)
797 .with_code("E0341")
798 .note("an `#embed` resource is looked for on the include path", hash),
799 );
800 return;
801 };
802 embed::tokens(found.bytes.as_slice(), ¶ms, hash, cx.interner, out);
807 }
808
809 fn embed_line(
811 &mut self,
812 rest: &[PpToken],
813 hash: Span,
814 cx: &mut Context<'_>,
815 ) -> Option<(Header, embed::Params)> {
816 if rest.is_empty() {
817 self.bad_header(hash);
818 return None;
819 }
820 let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
821 let line = if line[0].kind == PpTokenKind::HeaderName {
827 line
828 } else {
829 let expanded = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
830 self.diagnostics.append(&mut self.expander.take_diagnostics());
831 expanded
832 };
833 let Some(used) = embed::header_length(&line) else {
834 self.bad_header(line.first().map_or(hash, |t| t.report_span()));
835 return None;
836 };
837 let header = if line[0].kind == PpTokenKind::HeaderName {
838 header_from_token(spelling(line[0], cx.interner))
839 } else {
840 let spellings: Vec<&str> =
841 line[..used].iter().map(|t| spelling(*t, cx.interner)).collect();
842 header_from_tokens(&spellings)
843 };
844 let Some(header) = header else {
845 self.bad_header(line[0].report_span());
846 return None;
847 };
848 let params = self.embed_params(&line[used..], hash, cx)?;
849 Some((header, params))
850 }
851
852 fn embed_params(
854 &mut self,
855 line: &[Tok],
856 at: Span,
857 cx: &mut Context<'_>,
858 ) -> Option<embed::Params> {
859 let Preprocessor { expander, macros, diagnostics, .. } = self;
860 let sources = &mut *cx.sources;
861 let mut expand = |toks: Vec<Tok>, interner: &mut Interner| {
862 expander.expand_toks(toks, macros, interner, sources)
863 };
864 let params = embed::parse(line, at, cx.interner, diagnostics, &mut expand);
865 self.diagnostics.append(&mut self.expander.take_diagnostics());
866 params
867 }
868
869 fn where_to_look(
880 &self,
881 header: &Header,
882 is_next: bool,
883 cx: &Context<'_>,
884 ) -> (IncludeForm, Option<PathBuf>, usize) {
885 let form = if header.angled { IncludeForm::Angled } else { IncludeForm::Quoted };
886 let frame = self.stack.last();
887 let from = if is_next {
888 frame.map_or(0, |f| f.next).max(cx.search.start(form))
889 } else {
890 cx.search.start(form)
891 };
892 let relative_to = if is_next { None } else { frame.and_then(|f| f.dir.clone()) };
893 (form, relative_to, from)
894 }
895
896 fn find(&self, header: &Header, is_next: bool, cx: &Context<'_>) -> Option<Found> {
898 let (form, relative_to, from) = self.where_to_look(header, is_next, cx);
899 cx.search.resolve(cx.fs, &header.name, form, relative_to.as_deref(), from)
900 }
901
902 fn header_of(&mut self, rest: &[PpToken], hash: Span, cx: &mut Context<'_>) -> Option<Header> {
904 if let Some(first) = rest.first().copied() {
905 if first.kind == PpTokenKind::HeaderName {
906 let text = first.value.map_or("", |v| cx.interner.resolve(v));
907 let header = header_from_token(text);
908 if header.is_none() {
909 self.bad_header(first.span);
910 }
911 self.extra_tokens(&rest[1..], "#include");
912 return header;
913 }
914 }
915 if rest.is_empty() {
919 self.bad_header(hash);
920 return None;
921 }
922 let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
923 let expanded = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
924 self.diagnostics.append(&mut self.expander.take_diagnostics());
925 let spellings: Vec<&str> = expanded.iter().map(|t| spelling(*t, cx.interner)).collect();
926 let header = header_from_tokens(&spellings);
927 if header.is_none() {
928 let at = expanded.first().map_or(hash, |t| t.report_span());
929 self.bad_header(at);
930 }
931 header
932 }
933
934 fn bad_operand(&mut self, tok: Tok, at: Span, interner: &Interner) {
936 self.diagnostics.push(
937 Diagnostic::error(
938 format!("expected an identifier as the operand of `{}`", spelling(tok, interner)),
939 at,
940 )
941 .with_code("E0345"),
942 );
943 }
944
945 fn bad_header(&mut self, at: Span) {
946 self.diagnostics.push(
947 Diagnostic::error("expected a file name in `<>` or `\"\"`", at).with_code("E0343"),
948 );
949 }
950
951 fn open(&mut self, span: Span, value: bool) {
953 let enclosing_live = self.live();
954 self.conds.push(Cond {
955 span,
956 live: enclosing_live && value,
957 taken: value,
958 enclosing_live,
959 seen_else: false,
960 });
961 }
962
963 fn elif(
964 &mut self,
965 name: Option<Symbol>,
966 rest: &[PpToken],
967 hash: Span,
968 cx: &mut Context<'_>,
969 names: &Names,
970 ) {
971 let Some(top) = self.conds.last() else {
972 self.stray("elif", hash);
973 return;
974 };
975 if top.seen_else {
976 self.diagnostics
977 .push(Diagnostic::error("`#elif` after `#else`", hash).with_code("E0333"));
978 return;
979 }
980 let (enclosing_live, already_taken) = (top.enclosing_live, top.taken);
983 let consider = enclosing_live && !already_taken;
984 let value = if !consider {
985 false
986 } else if name == Some(names.elif) {
987 self.eval(rest, hash, cx, names)
988 } else {
989 self.defined_check(rest, hash, name == Some(names.elifdef), names)
990 };
991 let top = self.conds.last_mut().expect("checked above and nothing popped");
992 top.live = consider && value;
993 top.taken = already_taken || value;
994 }
995
996 fn branch_else(&mut self, rest: &[PpToken], hash: Span) {
997 let Some(top) = self.conds.last_mut() else {
998 self.stray("else", hash);
999 return;
1000 };
1001 if top.seen_else {
1002 self.diagnostics.push(Diagnostic::error("a second `#else`", hash).with_code("E0333"));
1003 return;
1004 }
1005 top.live = top.enclosing_live && !top.taken;
1006 top.taken = true;
1007 top.seen_else = true;
1008 let enclosing_live = top.enclosing_live;
1009 if enclosing_live {
1010 self.extra_tokens(rest, "#else");
1011 }
1012 }
1013
1014 fn endif(&mut self, rest: &[PpToken], hash: Span) {
1015 if self.conds.pop().is_none() {
1016 self.stray("endif", hash);
1017 return;
1018 }
1019 if self.live() {
1020 self.extra_tokens(rest, "#endif");
1021 }
1022 }
1023
1024 fn stray(&mut self, what: &str, hash: Span) {
1025 self.diagnostics
1026 .push(Diagnostic::error(format!("`#{what}` without `#if`"), hash).with_code("E0334"));
1027 }
1028
1029 fn extra_tokens(&mut self, rest: &[PpToken], what: &str) {
1034 if let Some(first) = rest.first() {
1035 self.diagnostics.push(
1036 Diagnostic::warning(format!("extra tokens after `{what}`"), first.span)
1037 .with_code("W0330"),
1038 );
1039 }
1040 }
1041
1042 fn eval(&mut self, rest: &[PpToken], hash: Span, cx: &mut Context<'_>, names: &Names) -> bool {
1044 let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
1045 let line = self.resolve_defined(line, cx.interner, names);
1051 let line = self.resolve_has(line, cx, names, Pass::Headers);
1056 let line = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
1057 self.diagnostics.append(&mut self.expander.take_diagnostics());
1058 let line = self.resolve_defined(line, cx.interner, names);
1059 let line = self.resolve_has(line, cx, names, Pass::Rest);
1060 cond::evaluate(&line, cx.interner, &mut self.diagnostics, hash)
1061 }
1062
1063 fn resolve_has(
1068 &mut self,
1069 line: Vec<Tok>,
1070 cx: &mut Context<'_>,
1071 names: &Names,
1072 pass: Pass,
1073 ) -> Vec<Tok> {
1074 if !line.iter().any(|t| t.ident().is_some_and(|n| names.has.op(n).is_some())) {
1075 return line;
1076 }
1077 let mut out = Vec::with_capacity(line.len());
1078 let mut at = 0;
1079 while at < line.len() {
1080 let tok = line[at];
1081 let op = tok.ident().and_then(|n| names.has.op(n));
1082 let Some(op) = op.filter(|op| pass.answers(*op)) else {
1083 if pass == Pass::Text && op.is_some_and(Op::is_header) {
1084 self.outside_a_directive(tok, cx);
1085 }
1086 out.push(tok);
1087 at += 1;
1088 continue;
1089 };
1090 let Some((operand, after)) = arguments(&line, at + 1) else {
1091 if pass != Pass::Headers {
1095 self.diagnostics.push(
1096 Diagnostic::error(
1097 format!("expected `(` after `{}`", spelling(tok, cx.interner)),
1098 tok.report_span(),
1099 )
1100 .with_code("E0345"),
1101 );
1102 }
1103 out.push(tok);
1104 at += 1;
1105 continue;
1106 };
1107 at = after;
1108 let value = self.ask(op, operand, tok, cx);
1111 let sym = cx.interner.intern(&value.to_string());
1112 out.push(Tok::synthetic(PpTokenKind::Number, Some(sym), tok.flags, tok.report_span()));
1113 }
1114 out
1115 }
1116
1117 fn outside_a_directive(&mut self, tok: Tok, cx: &Context<'_>) {
1125 self.diagnostics.push(
1126 Diagnostic::error(
1127 format!(
1128 "`{}` used outside of a preprocessing directive",
1129 spelling(tok, cx.interner)
1130 ),
1131 tok.report_span(),
1132 )
1133 .with_code("E0350"),
1134 );
1135 }
1136
1137 fn ask(&mut self, op: Op, operand: &[Tok], tok: Tok, cx: &mut Context<'_>) -> u32 {
1139 let at = operand.first().map_or(tok.report_span(), |t| t.report_span());
1140 match op {
1141 Op::Include | Op::IncludeNext => {
1142 let spellings: Vec<&str> =
1143 operand.iter().map(|t| spelling(*t, cx.interner)).collect();
1144 let Some(header) = header_from_tokens(&spellings) else {
1145 self.bad_header(at);
1146 return 0;
1147 };
1148 u32::from(self.find(&header, op == Op::IncludeNext, cx).is_some())
1149 }
1150 Op::Embed => {
1151 let Some(used) = embed::header_length(operand) else {
1156 self.bad_header(at);
1157 return 0;
1158 };
1159 let header = if operand[0].kind == PpTokenKind::HeaderName {
1160 header_from_token(spelling(operand[0], cx.interner))
1161 } else {
1162 let spellings: Vec<&str> =
1163 operand[..used].iter().map(|t| spelling(*t, cx.interner)).collect();
1164 header_from_tokens(&spellings)
1165 };
1166 let Some(header) = header else {
1167 self.bad_header(at);
1168 return 0;
1169 };
1170 let Some(params) = self.embed_params(&operand[used..], at, cx) else {
1175 return 0;
1176 };
1177 match self.find(&header, false, cx) {
1178 None => 0,
1179 Some(found) => {
1180 let taken = params.taken(found.bytes.as_slice().len() as u64);
1181 if taken == 0 { 2 } else { 1 }
1182 }
1183 }
1184 }
1185 Op::BuildingModule => {
1186 if attribute_name(operand, cx.interner).is_none() {
1187 self.bad_operand(tok, at, cx.interner);
1188 }
1189 0
1196 }
1197 Op::Table(kind) => {
1198 let Some(name) = attribute_name(operand, cx.interner) else {
1199 self.bad_operand(tok, at, cx.interner);
1200 return 0;
1201 };
1202 match kind {
1203 Kind::Attribute => rucc_gnu::has_attribute(name),
1204 Kind::CAttribute => rucc_gnu::has_c_attribute(name),
1205 Kind::Builtin => rucc_gnu::has_builtin(name),
1206 Kind::Feature => rucc_gnu::has_feature(name),
1207 Kind::Extension => rucc_gnu::has_extension(name),
1208 }
1209 }
1210 }
1211 }
1212
1213 fn resolve_defined(
1215 &mut self,
1216 line: Vec<Tok>,
1217 interner: &mut Interner,
1218 names: &Names,
1219 ) -> Vec<Tok> {
1220 if !line.iter().any(|t| t.ident() == Some(names.defined)) {
1221 return line;
1222 }
1223 let mut out = Vec::with_capacity(line.len());
1224 let mut at = 0;
1225 while at < line.len() {
1226 let tok = line[at];
1227 if tok.ident() != Some(names.defined) {
1228 out.push(tok);
1229 at += 1;
1230 continue;
1231 }
1232 let parenthesised = line.get(at + 1).is_some_and(|t| t.is(Punct::LParen));
1233 let name_at = if parenthesised { at + 2 } else { at + 1 };
1234 let name = line.get(name_at).and_then(|t| t.ident());
1235 let Some(name) = name else {
1236 self.diagnostics.push(
1237 Diagnostic::error("`defined` without a macro name", tok.report_span())
1238 .with_code("E0335"),
1239 );
1240 out.push(tok);
1241 at += 1;
1242 continue;
1243 };
1244 at = name_at + 1;
1245 if parenthesised {
1246 if line.get(at).is_some_and(|t| t.is(Punct::RParen)) {
1247 at += 1;
1248 } else {
1249 self.diagnostics.push(
1250 Diagnostic::error("expected `)` after `defined`", tok.report_span())
1251 .with_code("E0335"),
1252 );
1253 }
1254 }
1255 let value = self.macros.is_defined(name) || names.has.op(name).is_some();
1259 out.push(number(value, tok.flags, tok.report_span(), interner));
1260 }
1261 out
1262 }
1263
1264 fn defined_check(
1266 &mut self,
1267 rest: &[PpToken],
1268 hash: Span,
1269 want_defined: bool,
1270 names: &Names,
1271 ) -> bool {
1272 let Some(name) = rest.first().and_then(ident_of) else {
1273 self.diagnostics.push(
1274 Diagnostic::error("expected a macro name", rest.first().map_or(hash, |t| t.span))
1275 .with_code("E0336"),
1276 );
1277 return false;
1278 };
1279 self.extra_tokens(&rest[1..], if want_defined { "#ifdef" } else { "#ifndef" });
1280 let defined = self.macros.is_defined(name) || names.has.op(name).is_some();
1281 defined == want_defined
1282 }
1283
1284 fn undef(&mut self, rest: &[PpToken], hash: Span, interner: &Interner) {
1285 let Some(name) = rest.first().and_then(ident_of) else {
1286 self.diagnostics.push(
1287 Diagnostic::error("expected a macro name", rest.first().map_or(hash, |t| t.span))
1288 .with_code("E0336"),
1289 );
1290 return;
1291 };
1292 let text = interner.resolve(name);
1295 if text == "defined" || text.starts_with("__STDC_") {
1296 self.diagnostics.push(
1297 Diagnostic::error(format!("`{text}` cannot be undefined"), rest[0].span)
1298 .with_code("E0337"),
1299 );
1300 return;
1301 }
1302 self.macros.undef(name);
1303 self.extra_tokens(&rest[1..], "#undef");
1304 }
1305
1306 fn message(&mut self, rest: &[PpToken], hash: Span, fatal: bool, interner: &Interner) {
1308 let text = spell_line(rest, interner);
1309 let span = rest.first().map_or(hash, |t| t.span.to(last_span(rest)));
1310 let diag = if fatal {
1311 Diagnostic::error(text, span).with_code("E0338")
1312 } else {
1313 Diagnostic::warning(text, span).with_code("W0331")
1314 };
1315 self.diagnostics.push(diag);
1316 }
1317
1318 fn line(&mut self, rest: &[PpToken], hash: Span, at: usize, cx: &mut Context<'_>) {
1323 let line: Vec<Tok> = rest.iter().copied().map(Tok::new).collect();
1324 let line = self.expander.expand_toks(line, &self.macros, cx.interner, cx.sources);
1325 self.diagnostics.append(&mut self.expander.take_diagnostics());
1326 let interner = &mut *cx.interner;
1327
1328 let number_text = line
1329 .first()
1330 .filter(|t| t.kind == PpTokenKind::Number)
1331 .and_then(|t| t.value)
1332 .map(|v| interner.resolve(v));
1333 let Some(parsed) = number_text.and_then(|t| t.parse::<u64>().ok()) else {
1334 self.diagnostics.push(
1335 Diagnostic::error(
1336 "`#line` needs a decimal line number",
1337 line.first().map_or(hash, |t| t.report_span()),
1338 )
1339 .with_code("E0339"),
1340 );
1341 return;
1342 };
1343 if parsed == 0 || parsed > 2_147_483_647 {
1346 self.diagnostics.push(
1347 Diagnostic::error("`#line` number is out of range", line[0].report_span())
1348 .with_code("E0339"),
1349 );
1350 return;
1351 }
1352
1353 let mut file = None;
1354 if let Some(second) = line.get(1) {
1355 if second.kind == PpTokenKind::StringLit {
1356 file = second.value;
1357 } else {
1358 self.diagnostics.push(
1359 Diagnostic::error(
1360 "`#line` file name must be a string literal",
1361 second.report_span(),
1362 )
1363 .with_code("E0339"),
1364 );
1365 return;
1366 }
1367 }
1368 if let Some(extra) = line.get(2) {
1369 self.diagnostics.push(
1370 Diagnostic::warning("extra tokens after `#line`", extra.report_span())
1371 .with_code("W0330"),
1372 );
1373 }
1374 #[expect(
1375 clippy::cast_possible_truncation,
1376 reason = "the range check above keeps this inside i32, let alone u32"
1377 )]
1378 let number = parsed as u32;
1379 self.lines.push(LineDirective { span: hash, line: number, file, at });
1380 let name = file.map(|v| destringize(cx.interner.resolve(v)));
1381 cx.sources.set_presumed(hash.lo, number, name);
1382 }
1383
1384 fn line_marker(&mut self, body: &[PpToken], hash: Span, at: usize, cx: &mut Context<'_>) {
1401 let Some(number) = decimal(&body[0], cx.interner) else { return };
1402 let mut rest = &body[1..];
1403 let mut file = None;
1404 if let Some(first) = rest.first().filter(|t| t.kind == PpTokenKind::StringLit) {
1405 file = first.value;
1406 rest = &rest[1..];
1407 }
1408
1409 let (mut entering, mut leaving) = (false, false);
1410 for flag in rest {
1411 match decimal(flag, cx.interner) {
1412 Some(1) => entering = true,
1413 Some(2) => leaving = true,
1414 Some(3 | 4) => {}
1415 _ => {
1416 let text = spell_line(std::slice::from_ref(flag), cx.interner);
1417 self.diagnostics.push(
1418 Diagnostic::error(
1419 format!("invalid flag `{text}` in line directive"),
1420 flag.span,
1421 )
1422 .with_code("E0339"),
1423 );
1424 return;
1425 }
1426 }
1427 }
1428
1429 let name = file.map(|v| destringize(cx.interner.resolve(v)));
1430 if leaving {
1431 if let Some(name) = &name {
1432 if !self.leave_marker(name) {
1433 self.diagnostics.push(
1434 Diagnostic::warning(
1435 format!("file `{name}` linemarker ignored due to incorrect nesting"),
1436 last_span(body),
1437 )
1438 .with_code("W0330"),
1439 );
1440 return;
1441 }
1442 } else {
1443 self.markers.pop();
1444 }
1445 }
1446 if entering {
1447 let here = cx.sources.presumed(hash.lo).map(|loc| loc.name.to_owned());
1448 self.markers.push(here.unwrap_or_default());
1449 }
1450
1451 self.lines.push(LineDirective { span: hash, line: number, file, at });
1452 cx.sources.set_presumed(hash.lo, number, name);
1453 }
1454
1455 fn leave_marker(&mut self, name: &str) -> bool {
1469 if let Some(at) = self.markers.iter().rposition(|outer| outer == name) {
1470 self.markers.truncate(at);
1471 return true;
1472 }
1473 let found = self.stack.iter().rev().skip(1).any(|f| f.path.as_os_str() == name);
1476 if found {
1477 self.markers.clear();
1478 }
1479 found
1480 }
1481
1482 fn pragma_operator(
1488 &mut self,
1489 expanded: Vec<Tok>,
1490 out: &mut Vec<Tok>,
1491 interner: &mut Interner,
1492 names: &Names,
1493 ) {
1494 if !expanded.iter().any(|t| t.ident() == Some(names.pragma_op)) {
1495 out.extend(expanded);
1496 return;
1497 }
1498 let mut at = 0;
1499 let mut ends_a_line = false;
1504 while at < expanded.len() {
1505 let mut tok = expanded[at];
1506 if tok.ident() != Some(names.pragma_op) {
1507 if ends_a_line {
1508 tok.flags = tok.flags.with(TokenFlags::START_OF_LINE);
1509 ends_a_line = false;
1510 }
1511 out.push(tok);
1512 at += 1;
1513 continue;
1514 }
1515 let open = expanded.get(at + 1).is_some_and(|t| t.is(Punct::LParen));
1516 let text = expanded.get(at + 2).filter(|t| t.kind == PpTokenKind::StringLit);
1517 let close = expanded.get(at + 3).is_some_and(|t| t.is(Punct::RParen));
1518 let (Some(text), true, true) = (text, open, close) else {
1519 self.diagnostics.push(
1520 Diagnostic::error("`_Pragma` takes a single string literal", tok.report_span())
1521 .with_code("E0340"),
1522 );
1523 out.push(tok);
1524 at += 1;
1525 continue;
1526 };
1527 let literal = text.value.map(|v| interner.resolve(v)).unwrap_or_default();
1528 let body = destringize(literal);
1529 self.emit_pragma(&body, tok, out, interner, names);
1530 ends_a_line = true;
1531 at += 4;
1532 }
1533 }
1534
1535 fn emit_pragma(
1537 &mut self,
1538 body: &str,
1539 at: Tok,
1540 out: &mut Vec<Tok>,
1541 interner: &mut Interner,
1542 names: &Names,
1543 ) {
1544 let span = at.report_span();
1545 let (tokens, diagnostics) = tokenize(body.as_bytes(), 0, Options::new(), interner);
1546 self.diagnostics.extend(
1549 diagnostics
1550 .into_iter()
1551 .map(|d| Diagnostic::new(d.severity, d.message, span).with_code("E0340")),
1552 );
1553 let tokens: Vec<PpToken> = tokens.into_iter().filter(|t| !t.is_eof()).collect();
1554 if self.macro_stack_pragma(&tokens, span, interner, names) {
1558 return;
1559 }
1560 out.push(Tok::synthetic(
1561 PpTokenKind::Punct(Punct::Hash),
1562 None,
1563 TokenFlags::START_OF_LINE,
1564 span,
1565 ));
1566 out.push(Tok::synthetic(PpTokenKind::Ident, Some(names.pragma), TokenFlags::EMPTY, span));
1567 for (at, t) in tokens.into_iter().enumerate() {
1571 let spaced = at == 0 || t.flags.has(TokenFlags::LEADING_SPACE);
1574 let flags = if spaced {
1575 TokenFlags::EMPTY.with(TokenFlags::LEADING_SPACE)
1576 } else {
1577 TokenFlags::EMPTY
1578 };
1579 out.push(Tok::synthetic(t.kind, t.value, flags, span));
1580 }
1581 }
1582}
1583
1584fn guard_opener(body: &[PpToken], names: &Names) -> Option<Symbol> {
1589 let name = ident_of(body.first()?)?;
1590 let rest = &body[1..];
1591 if name == names.ifndef {
1592 let [only] = rest else {
1593 return None;
1594 };
1595 return ident_of(only);
1596 }
1597 if name != names.r#if {
1598 return None;
1599 }
1600 let [bang, defined, tail @ ..] = rest else {
1601 return None;
1602 };
1603 if bang.punct() != Some(Punct::Bang) || ident_of(defined) != Some(names.defined) {
1604 return None;
1605 }
1606 match tail {
1607 [only] => ident_of(only),
1608 [open, only, close]
1609 if open.punct() == Some(Punct::LParen) && close.punct() == Some(Punct::RParen) =>
1610 {
1611 ident_of(only)
1612 }
1613 _ => None,
1614 }
1615}
1616
1617fn is_include(name: Option<Symbol>, names: &Names) -> bool {
1619 name == Some(names.include) || name == Some(names.include_next) || name == Some(names.embed)
1620}
1621
1622fn is_directive(tok: PpToken) -> bool {
1624 tok.flags.has(TokenFlags::START_OF_LINE) && tok.punct() == Some(Punct::Hash)
1625}
1626
1627fn ident_of(tok: &PpToken) -> Option<Symbol> {
1628 match tok.kind {
1629 PpTokenKind::Ident => tok.value,
1630 _ => None,
1631 }
1632}
1633
1634fn last_span(tokens: &[PpToken]) -> Span {
1635 tokens.last().map_or(Span::DUMMY, |t| t.span)
1636}
1637
1638fn decimal(tok: &PpToken, interner: &Interner) -> Option<u32> {
1644 if tok.kind != PpTokenKind::Number {
1645 return None;
1646 }
1647 let text = interner.resolve(tok.value?);
1648 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
1649 return None;
1650 }
1651 text.parse::<u32>().ok().filter(|n| *n <= 2_147_483_647)
1654}
1655
1656fn number(value: bool, flags: TokenFlags, span: Span, interner: &mut Interner) -> Tok {
1658 let sym = interner.intern(if value { "1" } else { "0" });
1659 Tok::synthetic(PpTokenKind::Number, Some(sym), flags, span)
1660}
1661
1662fn spell_line(tokens: &[PpToken], interner: &Interner) -> String {
1664 let mut out = String::new();
1665 for (index, tok) in tokens.iter().enumerate() {
1666 if index > 0 && tok.flags.has(TokenFlags::LEADING_SPACE) {
1667 out.push(' ');
1668 }
1669 match tok.value {
1670 Some(sym) => out.push_str(interner.resolve(sym)),
1671 None => {
1672 if let Some(p) = tok.punct() {
1673 out.push_str(p.as_str());
1674 }
1675 }
1676 }
1677 }
1678 out
1679}
1680
1681fn identifier_in(text: PpToken, interner: &mut Interner) -> Option<Symbol> {
1686 let literal = interner.resolve(text.value?).to_string();
1687 let (tokens, _) = tokenize(destringize(&literal).as_bytes(), 0, Options::new(), interner);
1688 let mut real = tokens.into_iter().filter(|t| !t.is_eof());
1689 let first = real.next()?;
1690 if first.kind != PpTokenKind::Ident || real.next().is_some() {
1691 return None;
1692 }
1693 first.value
1694}
1695
1696fn destringize(literal: &str) -> String {
1701 let body = literal
1702 .trim_start_matches(['L', 'u', 'U', '8'])
1703 .strip_prefix('"')
1704 .and_then(|s| s.strip_suffix('"'))
1705 .unwrap_or(literal);
1706 let mut out = String::with_capacity(body.len());
1707 let mut chars = body.chars();
1708 while let Some(c) = chars.next() {
1709 if c != '\\' {
1710 out.push(c);
1711 continue;
1712 }
1713 match chars.next() {
1714 Some('"') => out.push('"'),
1715 Some('\\') => out.push('\\'),
1716 Some(other) => {
1717 out.push('\\');
1718 out.push(other);
1719 }
1720 None => out.push('\\'),
1721 }
1722 }
1723 out
1724}
1725
1726fn arguments(line: &[Tok], at: usize) -> Option<(&[Tok], usize)> {
1732 if !line.get(at)?.is(Punct::LParen) {
1733 return None;
1734 }
1735 let mut depth = 1u32;
1736 let mut end = at + 1;
1737 while end < line.len() {
1738 if line[end].is(Punct::LParen) {
1739 depth += 1;
1740 } else if line[end].is(Punct::RParen) {
1741 depth -= 1;
1742 if depth == 0 {
1743 return Some((&line[at + 1..end], end + 1));
1744 }
1745 }
1746 end += 1;
1747 }
1748 None
1749}
1750
1751fn attribute_name<'i>(operand: &[Tok], interner: &'i Interner) -> Option<&'i str> {
1757 let name = match operand {
1758 [one] => one,
1759 [_, scope, name] if scope.is(Punct::ColonColon) => name,
1760 _ => return None,
1761 };
1762 name.ident().map(|sym| interner.resolve(sym))
1763}
1764
1765#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1772enum Pass {
1773 Headers,
1775 Rest,
1778 Text,
1780}
1781
1782impl Pass {
1783 fn answers(self, op: Op) -> bool {
1785 match self {
1786 Pass::Headers => op.is_header(),
1787 Pass::Rest => true,
1788 Pass::Text => !op.is_header(),
1789 }
1790 }
1791}
1792
1793#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1795enum Op {
1796 Include,
1798 IncludeNext,
1800 Embed,
1803 BuildingModule,
1805 Table(Kind),
1807}
1808
1809impl Op {
1810 fn is_header(self) -> bool {
1812 matches!(self, Op::Include | Op::IncludeNext | Op::Embed)
1813 }
1814}
1815
1816struct HasOps {
1821 ops: [(Symbol, Op); 9],
1822 range: (Symbol, Symbol),
1829}
1830
1831impl HasOps {
1832 fn new(interner: &mut Interner) -> HasOps {
1833 let ops = [
1834 (interner.intern("__has_include"), Op::Include),
1835 (interner.intern("__has_include_next"), Op::IncludeNext),
1836 (interner.intern("__has_embed"), Op::Embed),
1837 (interner.intern("__has_attribute"), Op::Table(Kind::Attribute)),
1838 (interner.intern("__has_c_attribute"), Op::Table(Kind::CAttribute)),
1839 (interner.intern("__has_builtin"), Op::Table(Kind::Builtin)),
1840 (interner.intern("__has_feature"), Op::Table(Kind::Feature)),
1841 (interner.intern("__has_extension"), Op::Table(Kind::Extension)),
1842 (interner.intern("__building_module"), Op::BuildingModule),
1843 ];
1844 let mut range = (ops[0].0, ops[0].0);
1845 for &(sym, _) in &ops {
1846 range = (range.0.min(sym), range.1.max(sym));
1847 }
1848 HasOps { ops, range }
1849 }
1850
1851 #[inline]
1853 fn op(&self, name: Symbol) -> Option<Op> {
1854 if name < self.range.0 || name > self.range.1 {
1855 return None;
1856 }
1857 self.ops.iter().find(|(sym, _)| *sym == name).map(|(_, op)| *op)
1858 }
1859}
1860
1861struct Names {
1867 define: Symbol,
1868 undef: Symbol,
1869 r#if: Symbol,
1870 ifdef: Symbol,
1871 ifndef: Symbol,
1872 elif: Symbol,
1873 elifdef: Symbol,
1874 elifndef: Symbol,
1875 r#else: Symbol,
1876 endif: Symbol,
1877 line: Symbol,
1878 error: Symbol,
1879 warning: Symbol,
1880 pragma: Symbol,
1881 include: Symbol,
1882 include_next: Symbol,
1883 embed: Symbol,
1884 defined: Symbol,
1885 once: Symbol,
1886 push_macro: Symbol,
1887 pop_macro: Symbol,
1888 pragma_op: Symbol,
1889 has: HasOps,
1890}
1891
1892impl Names {
1893 fn new(interner: &mut Interner) -> Names {
1894 Names {
1895 define: interner.intern("define"),
1896 undef: interner.intern("undef"),
1897 r#if: interner.intern("if"),
1898 ifdef: interner.intern("ifdef"),
1899 ifndef: interner.intern("ifndef"),
1900 elif: interner.intern("elif"),
1901 elifdef: interner.intern("elifdef"),
1902 elifndef: interner.intern("elifndef"),
1903 r#else: interner.intern("else"),
1904 endif: interner.intern("endif"),
1905 line: interner.intern("line"),
1906 error: interner.intern("error"),
1907 warning: interner.intern("warning"),
1908 pragma: interner.intern("pragma"),
1909 include: interner.intern("include"),
1910 include_next: interner.intern("include_next"),
1911 embed: interner.intern("embed"),
1912 defined: interner.intern("defined"),
1913 once: interner.intern("once"),
1914 push_macro: interner.intern("push_macro"),
1915 pop_macro: interner.intern("pop_macro"),
1916 pragma_op: interner.intern("_Pragma"),
1917 has: HasOps::new(interner),
1918 }
1919 }
1920}
1921
1922#[cfg(test)]
1923mod tests {
1924 use rucc_diag::{Severity, SourceMap};
1925 use rucc_session::{MemoryFileSystem, SearchPath};
1926
1927 use super::*;
1928 use rucc_session::Std;
1929
1930 use crate::predef::Timestamp;
1931
1932 fn slashes(text: &str) -> String {
1940 text.replace("\\\\", "/").replace('\\', "/")
1941 }
1942
1943 struct Run {
1944 interner: Interner,
1945 sources: SourceMap,
1946 fs: MemoryFileSystem,
1947 search: SearchPath,
1948 pp: Preprocessor,
1949 }
1950
1951 impl Run {
1952 fn new() -> Run {
1953 Run {
1954 interner: Interner::new(),
1955 sources: SourceMap::new(),
1956 fs: MemoryFileSystem::new(),
1957 search: SearchPath::new(),
1958 pp: Preprocessor::new(),
1959 }
1960 }
1961
1962 fn mapping(map: &[(&str, &str)]) -> Run {
1964 let mut list = PrefixMap::new();
1965 for (old, new) in map {
1966 list.push(*old, *new);
1967 }
1968 Run { pp: Preprocessor::with_prefix_map(list), ..Run::new() }
1969 }
1970
1971 fn file(&mut self, path: &str, contents: &str) {
1973 self.fs.insert(path, contents.as_bytes().to_vec());
1974 }
1975
1976 fn bytes(&mut self, path: &str, contents: &[u8]) {
1979 self.fs.insert(path, contents.to_vec());
1980 }
1981
1982 fn dir(&mut self, path: &str) {
1984 self.search.push_bracket(path);
1985 }
1986
1987 fn predefine(&mut self, triple: &str, opts: &Predef) {
1989 let target = TargetInfo::new(triple.parse().expect("a supported triple"));
1990 let mut cx =
1991 Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
1992 self.pp.predefine(&target, opts, &mut cx).expect("the map has room");
1993 }
1994
1995 fn go(&mut self, src: &str) -> String {
1997 self.go_named("/main.c", src)
1998 }
1999
2000 fn raw(&mut self, src: &str) -> Vec<Tok> {
2002 let file = self.sources.add("/main.c", src.as_bytes().to_vec()).expect("room");
2003 let mut cx =
2004 Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
2005 self.pp.run(file, &mut cx)
2006 }
2007
2008 fn preinclude(&mut self, files: &[Preinclude]) -> String {
2010 let mut out = Vec::new();
2011 {
2012 let mut cx =
2013 Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
2014 self.pp.preinclude(files, &mut out, &mut cx).expect("the map has room");
2015 }
2016 self.spell(&out)
2017 }
2018
2019 fn go_named(&mut self, path: &str, src: &str) -> String {
2021 let file = self.sources.add(path, src.as_bytes().to_vec()).expect("the map has room");
2022 let out = {
2023 let mut cx =
2024 Context::new(&mut self.interner, &mut self.sources, &self.fs, &self.search);
2025 self.pp.run(file, &mut cx)
2026 };
2027 self.spell(&out)
2028 }
2029
2030 fn spell(&self, out: &[Tok]) -> String {
2032 let mut text = String::new();
2033 for (at, tok) in out.iter().enumerate() {
2034 let spaced = tok.flags.has(TokenFlags::LEADING_SPACE)
2035 || tok.flags.has(TokenFlags::START_OF_LINE);
2036 if at > 0 && spaced {
2037 text.push(' ');
2038 }
2039 match tok.kind {
2040 PpTokenKind::Punct(p) => text.push_str(p.as_str()),
2041 _ => text.push_str(
2042 self.interner.resolve(tok.value.expect("every non-punctuator interns")),
2043 ),
2044 }
2045 }
2046 text
2047 }
2048
2049 fn files(&self) -> usize {
2053 self.sources.files().len()
2054 }
2055
2056 fn messages(&mut self) -> Vec<String> {
2057 self.pp.take_diagnostics().into_iter().map(|d| d.message).collect()
2058 }
2059
2060 fn severities(&mut self) -> Vec<Severity> {
2061 self.pp.diagnostics().iter().map(|d| d.severity).collect()
2062 }
2063 }
2064
2065 fn clean(src: &str) -> String {
2066 let mut run = Run::new();
2067 let text = run.go(src);
2068 assert!(run.messages().is_empty(), "expected no diagnostics from {src:?}");
2069 text
2070 }
2071
2072 #[test]
2073 fn a_taken_branch_is_kept_and_the_other_is_not() {
2074 assert_eq!(clean("#if 1\nyes\n#else\nno\n#endif\n"), "yes");
2075 assert_eq!(clean("#if 0\nyes\n#else\nno\n#endif\n"), "no");
2076 }
2077
2078 #[test]
2079 fn ifdef_and_ifndef_ask_the_macro_table() {
2080 assert_eq!(clean("#define F 1\n#ifdef F\nyes\n#endif\n"), "yes");
2081 assert_eq!(clean("#ifdef F\nyes\n#endif\n"), "");
2082 assert_eq!(clean("#ifndef F\nyes\n#endif\n"), "yes");
2083 assert_eq!(clean("#define F 1\n#if 0\na\n#elifdef F\nb\n#endif\n"), "b");
2085 assert_eq!(clean("#if 0\na\n#elifndef F\nb\n#endif\n"), "b");
2086 }
2087
2088 #[test]
2089 fn only_the_first_true_branch_of_a_chain_is_taken() {
2090 assert_eq!(clean("#if 0\na\n#elif 1\nb\n#elif 1\nc\n#else\nd\n#endif\n"), "b");
2091 assert_eq!(clean("#if 0\na\n#elif 0\nb\n#else\nc\n#endif\n"), "c");
2092 }
2093
2094 #[test]
2095 fn a_branch_after_one_that_was_taken_is_not_evaluated() {
2096 assert_eq!(clean("#if 1\na\n#elif 1/0\nb\n#endif\n"), "a");
2099 }
2100
2101 #[test]
2102 fn a_skipped_region_is_not_read_for_anything_but_nesting() {
2103 let src = "#if 0\nthis is not C at all\n#frobnicate\n#define\n#if 1\ninner\n#endif\n#endif\nafter\n";
2105 assert_eq!(clean(src), "after");
2106 }
2107
2108 #[test]
2109 fn nesting_inside_a_dead_branch_stays_balanced() {
2110 let src = "#if 0\n#ifdef X\na\n#else\nb\n#endif\n#else\nc\n#endif\n";
2111 assert_eq!(clean(src), "c");
2112 }
2113
2114 #[test]
2115 fn defined_works_in_both_spellings_and_before_expansion() {
2116 assert_eq!(clean("#define F 0\n#if defined F\nyes\n#endif\n"), "yes");
2117 assert_eq!(clean("#define F 0\n#if defined(F)\nyes\n#endif\n"), "yes");
2118 assert_eq!(clean("#if defined(F)\nyes\n#endif\n"), "");
2119 assert_eq!(clean("#define F 0\n#if defined F && !F\nyes\n#endif\n"), "yes");
2122 }
2123
2124 #[test]
2125 fn an_identifier_that_survived_expansion_is_zero() {
2126 assert_eq!(clean("#if NOT_DEFINED_ANYWHERE\nyes\n#else\nno\n#endif\n"), "no");
2127 assert_eq!(clean("#if !NOT_DEFINED_ANYWHERE\nyes\n#endif\n"), "yes");
2128 }
2129
2130 #[test]
2131 fn short_circuiting_keeps_a_guarded_expression_safe() {
2132 assert_eq!(clean("#if defined(F) && 1/F\nyes\n#else\nno\n#endif\n"), "no");
2135 assert_eq!(clean("#if 1 ? 2 : 1/0\nyes\n#endif\n"), "yes");
2136 }
2137
2138 #[test]
2139 fn the_operators_have_the_precedence_they_do_in_c() {
2140 assert_eq!(clean("#if 1 + 2 * 3 == 7\nyes\n#endif\n"), "yes");
2141 assert_eq!(clean("#if (1 + 2) * 3 == 9\nyes\n#endif\n"), "yes");
2142 assert_eq!(clean("#if 1 << 4 == 16\nyes\n#endif\n"), "yes");
2143 assert_eq!(clean("#if -8 / 3 == -2\nyes\n#endif\n"), "yes");
2144 assert_eq!(clean("#if (0xff & 0x0f) == 15\nyes\n#endif\n"), "yes");
2145 }
2146
2147 #[test]
2148 fn an_unsigned_operand_makes_the_whole_comparison_unsigned() {
2149 assert_eq!(clean("#if -1 < 0u\nyes\n#else\nno\n#endif\n"), "no");
2153 assert_eq!(clean("#if -1 < 0\nyes\n#else\nno\n#endif\n"), "yes");
2154 }
2155
2156 #[test]
2157 fn character_constants_evaluate() {
2158 assert_eq!(clean("#if 'A' == 65\nyes\n#endif\n"), "yes");
2159 assert_eq!(clean("#if '\\n' == 10\nyes\n#endif\n"), "yes");
2160 }
2161
2162 #[test]
2163 fn a_macro_is_expanded_before_the_expression_is_evaluated() {
2164 assert_eq!(clean("#define V 3\n#if V > 2\nyes\n#endif\n"), "yes");
2165 assert_eq!(clean("#define M(a) ((a) * 2)\n#if M(3) == 6\nyes\n#endif\n"), "yes");
2166 }
2167
2168 #[test]
2169 fn an_invocation_may_span_lines_within_a_run_of_text() {
2170 assert_eq!(clean("#define M(a, b) a + b\nM(1,\n2)\n"), "1 + 2");
2171 }
2172
2173 #[test]
2174 fn undef_removes_a_definition() {
2175 assert_eq!(clean("#define F 1\n#undef F\n#ifdef F\nyes\n#else\nno\n#endif\n"), "no");
2176 assert_eq!(clean("#undef NEVER_DEFINED\nok\n"), "ok");
2179 }
2180
2181 #[test]
2182 fn some_names_cannot_be_undefined() {
2183 let mut run = Run::new();
2184 run.go("#undef defined\n");
2185 assert_eq!(run.messages(), vec!["`defined` cannot be undefined".to_owned()]);
2186 }
2187
2188 #[test]
2189 fn error_reports_the_rest_of_the_line() {
2190 let mut run = Run::new();
2191 run.go("#if 0\n#error not this one\n#else\n#error unsupported target\n#endif\n");
2192 assert_eq!(run.messages(), vec!["unsupported target".to_owned()]);
2193 }
2194
2195 #[test]
2196 fn warning_is_a_warning() {
2197 let mut run = Run::new();
2198 run.go("#warning this is fine\n");
2199 assert_eq!(run.severities(), vec![Severity::Warning]);
2200 assert_eq!(run.messages(), vec!["this is fine".to_owned()]);
2201 }
2202
2203 #[test]
2204 fn an_unterminated_conditional_is_reported() {
2205 let mut run = Run::new();
2206 assert_eq!(run.go("#if 1\nyes\n"), "yes");
2207 assert_eq!(run.messages(), vec!["unterminated `#if`".to_owned()]);
2208 }
2209
2210 #[test]
2211 fn a_conditional_without_an_if_is_reported() {
2212 let mut run = Run::new();
2213 run.go("#endif\n");
2214 assert_eq!(run.messages(), vec!["`#endif` without `#if`".to_owned()]);
2215
2216 let mut run = Run::new();
2217 run.go("#if 1\n#else\n#else\n#endif\n");
2218 assert_eq!(run.messages(), vec!["a second `#else`".to_owned()]);
2219
2220 let mut run = Run::new();
2221 run.go("#if 1\n#else\n#elif 1\n#endif\n");
2222 assert_eq!(run.messages(), vec!["`#elif` after `#else`".to_owned()]);
2223 }
2224
2225 #[test]
2226 fn tokens_after_endif_are_a_warning_rather_than_an_error() {
2227 let mut run = Run::new();
2230 assert_eq!(run.go("#if 1\nyes\n#endif FOO\n"), "yes");
2231 assert_eq!(run.severities(), vec![Severity::Warning]);
2232 assert_eq!(run.messages(), vec!["extra tokens after `#endif`".to_owned()]);
2233 }
2234
2235 #[test]
2236 fn the_null_directive_does_nothing() {
2237 assert_eq!(clean("#\na\n#\nb\n"), "a b");
2238 }
2239
2240 #[test]
2241 fn an_unknown_directive_is_an_error_when_the_region_is_live() {
2242 let mut run = Run::new();
2243 run.go("#frobnicate\n");
2244 assert_eq!(run.messages(), vec!["invalid preprocessing directive".to_owned()]);
2245 }
2246
2247 #[test]
2248 fn line_is_recorded_for_the_source_map() {
2249 let mut run = Run::new();
2250 run.go("#line 42 \"other.c\"\n");
2251 assert!(run.messages().is_empty());
2252 let recorded = run.pp.line_directives();
2253 assert_eq!(recorded.len(), 1);
2254 assert_eq!(recorded[0].line, 42);
2255 let file = recorded[0].file.expect("a file name was given");
2256 assert_eq!(run.interner.resolve(file), "\"other.c\"");
2257 }
2258
2259 #[test]
2260 fn line_moves_what_line_and_file_the_lines_after_it_are_on() {
2261 let mut run = Run::new();
2262 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2263 assert_eq!(run.go("#line 1000\n__LINE__ __FILE__\n__LINE__\n"), "1000 \"/main.c\" 1001");
2264 }
2265
2266 #[test]
2267 fn a_line_marker_moves_the_lines_after_it_the_way_line_does() {
2268 let mut run = Run::new();
2269 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2270 assert_eq!(run.go("# 200 \"xyz\"\n__FILE__ __LINE__\n"), "\"xyz\" 200");
2271 }
2272
2273 #[test]
2274 fn a_line_marker_with_no_name_leaves_the_name_alone() {
2275 let mut run = Run::new();
2276 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2277 assert_eq!(run.go("# 20\n__FILE__ __LINE__\n"), "\"/main.c\" 20");
2278 }
2279
2280 #[test]
2281 fn a_line_marker_may_say_line_zero() {
2282 let mut run = Run::new();
2285 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2286 assert_eq!(run.go("# 0 \"xyz\"\n__LINE__\n"), "0");
2287 }
2288
2289 #[test]
2290 fn entering_and_returning_are_a_nesting_the_marker_flags_keep() {
2291 let mut run = Run::new();
2292 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2293 let text =
2294 run.go("# 200 \"xyz\" 1\n__FILE__\n# 5 \"/main.c\" 2\n__FILE__ __LINE__\n# 9 3 4\n");
2295 assert_eq!(text, "\"xyz\" \"/main.c\" 5");
2296 assert!(run.messages().is_empty());
2297 }
2298
2299 #[test]
2300 fn returning_to_a_file_nothing_was_ever_in_is_ignored() {
2301 let mut run = Run::new();
2302 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2303 assert_eq!(run.go("# 200 \"xyz\" 2 3\n__FILE__ __LINE__\n"), "\"/main.c\" 2");
2304 assert_eq!(
2305 run.messages(),
2306 vec!["file `xyz` linemarker ignored due to incorrect nesting".to_owned()]
2307 );
2308 }
2309
2310 #[test]
2311 fn a_flag_that_is_not_one_of_the_four_is_an_error() {
2312 let mut run = Run::new();
2313 run.go("# 20 \"a\" 7\n");
2314 assert_eq!(run.messages(), vec!["invalid flag `7` in line directive".to_owned()]);
2315 }
2316
2317 #[test]
2318 fn a_hash_and_something_that_is_not_a_line_number_is_still_an_unknown_directive() {
2319 let mut run = Run::new();
2321 run.go("# 1.5 \"a\"\n");
2322 assert_eq!(run.messages(), vec!["invalid preprocessing directive".to_owned()]);
2323 }
2324
2325 #[test]
2326 fn a_name_on_the_directive_is_the_name_from_there_on() {
2327 let mut run = Run::new();
2328 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2329 assert_eq!(run.go("#line 7 \"gen.y\"\n__FILE__ __LINE__\n"), "\"gen.y\" 7");
2330 }
2331
2332 #[test]
2333 fn a_directive_with_no_name_keeps_the_one_already_in_force() {
2334 let mut run = Run::new();
2335 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2336 assert_eq!(run.go("#line 7 \"gen.y\"\n#line 20\n__FILE__ __LINE__\n"), "\"gen.y\" 20");
2337 }
2338
2339 #[test]
2340 fn the_number_is_expanded_first_because_line_plus_one_is_real_code() {
2341 let mut run = Run::new();
2342 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2343 assert_eq!(run.go("#define WHERE 300\n#line WHERE\n__LINE__\n"), "300");
2344 }
2345
2346 #[test]
2347 fn a_directive_in_a_header_does_not_move_the_file_that_included_it() {
2348 let mut run = Run::new();
2349 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2350 run.file("/h.h", "#line 500\n__LINE__\n");
2351 run.dir("/");
2352 assert_eq!(run.go("#include <h.h>\n__LINE__\n"), "500 2");
2353 }
2354
2355 #[test]
2356 fn extra_tokens_after_the_file_name_are_a_warning_and_not_an_error() {
2357 let mut run = Run::new();
2358 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2359 assert_eq!(run.go("#line 7 \"gen.y\" and more\n__LINE__\n"), "7");
2360 assert_eq!(run.messages(), vec!["extra tokens after `#line`".to_owned()]);
2361 }
2362
2363 #[test]
2364 fn a_line_number_out_of_range_is_refused() {
2365 let mut run = Run::new();
2366 run.go("#line 0\n");
2367 assert_eq!(run.messages(), vec!["`#line` number is out of range".to_owned()]);
2368
2369 let mut run = Run::new();
2370 run.go("#line notanumber\n");
2371 assert_eq!(run.messages(), vec!["`#line` needs a decimal line number".to_owned()]);
2372 }
2373
2374 #[test]
2375 fn a_pragma_passes_through_unchanged() {
2376 assert_eq!(clean("#pragma pack(1)\nint x;\n"), "#pragma pack(1) int x;");
2377 }
2378
2379 #[test]
2384 fn the_space_between_the_hash_and_the_word_comes_off_a_pragma_that_is_indented() {
2385 assert_eq!(clean("#if 1\n# pragma pack(1)\n#endif\n"), "#pragma pack(1)");
2386 assert_eq!(clean("# pragma pack( 1 )\n"), "#pragma pack( 1 )", "the rest is kept");
2387 }
2388
2389 #[test]
2390 fn the_pragma_operator_becomes_a_pragma() {
2391 assert_eq!(
2392 clean("_Pragma(\"GCC visibility push(default)\")\nint x;\n"),
2393 "#pragma GCC visibility push(default) int x;"
2394 );
2395 }
2396
2397 #[test]
2398 fn the_pragma_operator_works_from_inside_a_macro() {
2399 let src = "#define PUSH _Pragma(\"pack(push)\")\nPUSH\nint x;\n";
2402 assert_eq!(clean(src), "#pragma pack(push) int x;");
2403 }
2404
2405 #[test]
2409 fn what_follows_a_pragma_operator_starts_a_line() {
2410 let mut run = Run::new();
2411 let out = run.raw("int x; _Pragma(\"pack(1)\") int y;\n");
2412 let starts: Vec<_> =
2413 out.iter().map(|tok| tok.flags.has(TokenFlags::START_OF_LINE)).collect();
2414 assert_eq!(
2417 starts,
2418 vec![true, false, false, true, false, false, false, false, false, true, false, false]
2419 );
2420 }
2421
2422 #[test]
2423 fn a_pragma_operator_that_is_not_given_a_string_is_reported() {
2424 let mut run = Run::new();
2425 run.go("_Pragma(x)\n");
2426 assert_eq!(run.messages(), vec!["`_Pragma` takes a single string literal".to_owned()]);
2427 }
2428
2429 #[test]
2430 fn an_include_reads_the_file_it_names() {
2431 let mut run = Run::new();
2432 run.file("/dir/one.h", "int from_the_header;\n");
2433 run.dir("/dir");
2434 assert_eq!(run.go("#include <one.h>\nint after;\n"), "int from_the_header; int after;");
2435 assert!(run.messages().is_empty());
2436 }
2437
2438 #[test]
2439 fn a_quoted_include_looks_next_to_the_including_file_first() {
2440 let mut run = Run::new();
2441 run.file("/local.h", "beside\n");
2442 run.file("/dir/local.h", "on the path\n");
2443 run.dir("/dir");
2444 assert_eq!(run.go("#include \"local.h\"\n"), "beside");
2445 assert!(run.messages().is_empty());
2446 }
2447
2448 #[test]
2449 fn an_angled_include_does_not_look_next_to_the_including_file() {
2450 let mut run = Run::new();
2451 run.file("/local.h", "beside\n");
2452 run.file("/dir/local.h", "on the path\n");
2453 run.dir("/dir");
2454 assert_eq!(run.go("#include <local.h>\n"), "on the path");
2455 }
2456
2457 #[test]
2458 fn a_macro_defined_in_a_header_is_visible_after_the_include() {
2459 let mut run = Run::new();
2460 run.file("/dir/defs.h", "#define N 42\n");
2461 run.dir("/dir");
2462 assert_eq!(run.go("#include <defs.h>\nint a = N;\n"), "int a = 42;");
2463 assert!(run.messages().is_empty());
2464 }
2465
2466 #[test]
2467 fn an_include_guard_keeps_the_second_read_empty() {
2468 let mut run = Run::new();
2469 run.file("/dir/g.h", "#ifndef G\n#define G\nonce\n#endif\n");
2470 run.dir("/dir");
2471 assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "once");
2472 assert!(run.messages().is_empty());
2473 assert_eq!(run.files(), 2, "the second include is not opened at all");
2474 }
2475
2476 fn named(name: &str, macros_only: bool) -> Preinclude {
2477 Preinclude { name: name.to_owned(), macros_only }
2478 }
2479
2480 #[test]
2481 fn a_command_line_include_contributes_its_text_and_an_imacros_contributes_none() {
2482 let mut run = Run::new();
2483 run.file("i.h", "from_include\n#define I 1\n");
2484 run.file("m.h", "from_macros\n#define M 1\n");
2485 assert_eq!(run.preinclude(&[named("i.h", false), named("m.h", true)]), "from_include");
2486 assert_eq!(run.go("I M\n"), "1 1");
2488 }
2489
2490 #[test]
2491 fn every_imacros_runs_before_every_include_whatever_order_the_command_line_was_in() {
2492 for files in
2495 [[named("i.h", false), named("m.h", true)], [named("m.h", true), named("i.h", false)]]
2496 {
2497 let mut run = Run::new();
2498 run.file("i.h", "#ifdef M\nsaw_it\n#else\nmissed_it\n#endif\n");
2499 run.file("m.h", "#define M 1\n");
2500 assert_eq!(run.preinclude(&files), "saw_it");
2501 }
2502 }
2503
2504 #[test]
2505 fn a_header_read_for_its_macros_is_not_read_again_by_an_include_that_its_guard_covers() {
2506 let mut run = Run::new();
2509 run.file("/dir/g.h", "#ifndef G\n#define G\ndeclarations\n#endif\n");
2510 run.dir("/dir");
2511 assert_eq!(run.preinclude(&[named("/dir/g.h", true)]), "");
2512 assert_eq!(run.go("#include <g.h>\n"), "");
2513 assert!(run.messages().is_empty());
2514 }
2515
2516 #[test]
2517 fn a_command_line_include_is_a_dependency_and_is_named_before_the_headers_it_reads() {
2518 let mut run = Run::new();
2519 run.file("i.h", "#include \"deep.h\"\n");
2520 run.file("deep.h", "\n");
2521 run.file("m.h", "\n");
2522 run.preinclude(&[named("i.h", false), named("m.h", true)]);
2523 let names: Vec<String> =
2524 run.pp.dependencies().iter().map(|d| d.path.to_string_lossy().into_owned()).collect();
2525 let names: Vec<String> = names.iter().map(|n| n.replace('\\', "/")).collect();
2526 assert_eq!(names, ["m.h", "i.h", "deep.h"]);
2527 }
2528
2529 #[test]
2530 fn a_prerequisite_is_spelled_without_the_dot_the_search_path_was_written_with() {
2531 let mut run = Run::new();
2535 run.file("d/f.h", "\n");
2536 run.dir("./d");
2537 run.go("#include <f.h>\n");
2538 let names: Vec<String> =
2539 run.pp.dependencies().iter().map(|d| d.path.to_string_lossy().into_owned()).collect();
2540 assert_eq!(names.iter().map(|n| n.replace('\\', "/")).collect::<Vec<_>>(), ["d/f.h"]);
2541 }
2542
2543 #[test]
2544 fn a_command_line_include_that_is_nowhere_is_reported_against_the_flag_that_named_it() {
2545 let mut run = Run::new();
2546 assert_eq!(run.preinclude(&[named("nope.h", false)]), "");
2547 assert_eq!(run.messages(), ["`nope.h` file not found"]);
2548 }
2549
2550 #[test]
2551 fn the_other_spelling_of_a_guard_is_recognised_too() {
2552 for guard in ["#if !defined(G)", "#if !defined G"] {
2553 let mut run = Run::new();
2554 run.file("/dir/g.h", &format!("{guard}\n#define G\nonce\n#endif\n"));
2555 run.dir("/dir");
2556 assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "once");
2557 assert_eq!(run.files(), 2, "{guard} should be a guard");
2558 }
2559 }
2560
2561 #[test]
2562 fn a_conditional_that_is_not_a_guard_does_not_skip_anything() {
2563 let mut run = Run::new();
2566 run.file("/dir/g.h", "#ifndef G\ntwice\n#endif\n");
2567 run.dir("/dir");
2568 assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "twice twice");
2569 assert_eq!(run.files(), 3);
2570 }
2571
2572 #[test]
2573 fn a_token_outside_the_guard_stops_it_being_a_guard() {
2574 let mut run = Run::new();
2575 run.file("/dir/g.h", "#ifndef G\n#define G\n#endif\nalways\n");
2576 run.dir("/dir");
2577 assert_eq!(run.go("#include <g.h>\n#include <g.h>\n"), "always always");
2578 assert_eq!(run.files(), 3);
2579 }
2580
2581 #[test]
2582 fn pragma_once_skips_the_second_read_and_does_not_reach_the_output() {
2583 let mut run = Run::new();
2584 run.file("/dir/o.h", "#pragma once\nonce\n");
2585 run.dir("/dir");
2586 assert_eq!(run.go("#include <o.h>\n#include <o.h>\n"), "once");
2587 assert!(run.messages().is_empty());
2588 assert_eq!(run.files(), 2);
2589 }
2590
2591 #[test]
2592 fn pragma_once_in_the_main_file_is_a_warning_and_is_still_applied() {
2593 let mut run = Run::new();
2597 let src = "#pragma once\n#include <s.c>\nbody\n";
2598 run.file("/dir/s.c", src);
2599 run.dir("/dir");
2600 assert_eq!(run.go_named("/dir/s.c", src), "body");
2601 assert_eq!(run.severities(), vec![Severity::Warning]);
2602 assert_eq!(run.messages(), vec!["`#pragma once` in the main file".to_owned()]);
2603 assert_eq!(run.files(), 1);
2604 }
2605
2606 #[test]
2607 fn pragma_once_holds_across_two_spellings_of_the_one_path() {
2608 let mut run = Run::new();
2611 run.file("dir/s.c", "#pragma once\nbody\n");
2612 run.dir(".");
2613 assert_eq!(run.go("#include <dir/s.c>\n#include <dir/s.c>\n"), "body");
2614 assert!(run.messages().is_empty());
2615 assert_eq!(run.files(), 2);
2616 }
2617
2618 #[test]
2619 fn any_other_pragma_still_passes_through() {
2620 assert_eq!(clean("#pragma once_upon_a_time\n"), "#pragma once_upon_a_time");
2621 }
2622
2623 #[test]
2626 fn push_macro_and_pop_macro_put_a_definition_aside_and_bring_it_back() {
2627 let src = "#define X 1\n#pragma push_macro(\"X\")\n#undef X\n#define X 2\n a X\n#pragma pop_macro(\"X\")\nb X\n";
2628 assert_eq!(clean(src), "a 2 b 1");
2629 }
2630
2631 #[test]
2632 fn a_name_with_no_definition_pushes_and_pops_the_absence() {
2633 let src = "#pragma push_macro(\"X\")\n#define X 1\na X\n#pragma pop_macro(\"X\")\nb X\n";
2636 assert_eq!(clean(src), "a 1 b X");
2637 }
2638
2639 #[test]
2640 fn the_pushes_nest() {
2641 let src = "#define X 1\n#pragma push_macro(\"X\")\n#undef X\n#define X 2\n #pragma push_macro(\"X\")\n#undef X\n#define X 3\n a X\n#pragma pop_macro(\"X\")\nb X\n#pragma pop_macro(\"X\")\nc X\n";
2642 assert_eq!(clean(src), "a 3 b 2 c 1");
2643 }
2644
2645 #[test]
2646 fn a_pop_with_nothing_pushed_says_nothing() {
2647 assert_eq!(clean("#define X 1\n#pragma pop_macro(\"X\")\nX\n"), "1");
2650 assert_eq!(clean("#pragma pop_macro(\"Never\")\nx\n"), "x");
2651 }
2652
2653 #[test]
2654 fn the_pragma_operator_spelling_works_and_takes_effect_where_it_is_written() {
2655 let src = "#define X 1\n_Pragma(\"push_macro(\\\"X\\\")\")\n#undef X\n#define X 2\n a X\n_Pragma(\"pop_macro(\\\"X\\\")\")\nb X\n";
2660 assert_eq!(clean(src), "a 2 b 1");
2661 }
2662
2663 #[test]
2664 fn the_gcc_spelling_is_not_one_of_these_and_passes_through() {
2665 let src = "#define X 1\n#pragma GCC push_macro(\"X\")\n#undef X\n#define X 2\nX\n";
2669 assert_eq!(clean(src), "#pragma GCC push_macro(\"X\") 2");
2670 }
2671
2672 #[test]
2673 fn a_push_macro_that_is_not_the_shape_is_an_error() {
2674 for src in ["#pragma push_macro\n", "#pragma push_macro(X)\n", "#pragma pop_macro()\n"] {
2675 let mut run = Run::new();
2676 run.go(src);
2677 let word = if src.contains("push") { "push" } else { "pop" };
2678 assert_eq!(
2679 run.messages(),
2680 vec![format!("invalid `#pragma {word}_macro` directive")],
2681 "from {src:?}"
2682 );
2683 }
2684 }
2685
2686 #[test]
2687 fn a_string_that_does_not_spell_one_identifier_names_no_macro() {
2688 assert_eq!(clean("#pragma push_macro(\"a b\")\nx\n"), "x");
2691 assert_eq!(clean("#pragma push_macro(\"2\")\nx\n"), "x");
2692 }
2693
2694 #[test]
2695 fn what_follows_the_closing_parenthesis_is_the_usual_warning() {
2696 let mut run = Run::new();
2697 assert_eq!(run.go("#define X 1\n#pragma push_macro(\"X\") junk\nX\n"), "1");
2698 assert_eq!(run.severities(), vec![Severity::Warning]);
2699 assert_eq!(run.messages(), vec!["extra tokens after `#pragma`".to_owned()]);
2700 }
2701
2702 #[test]
2703 fn has_include_answers_from_the_search_path() {
2704 let mut run = Run::new();
2705 run.file("/dir/there.h", "");
2706 run.dir("/dir");
2707 let src = "#if __has_include(<there.h>)\nyes\n#endif\n\
2708 #if __has_include(<gone.h>)\nno\n#endif\n";
2709 assert_eq!(run.go(src), "yes");
2710 assert!(run.messages().is_empty(), "a header that is not there is an answer, not an error");
2711 }
2712
2713 #[test]
2714 fn has_include_asks_the_question_the_include_on_the_same_line_would() {
2715 let mut run = Run::new();
2719 run.file("/beside.h", "");
2720 let src = "#if __has_include(\"beside.h\")\nquoted\n#endif\n\
2721 #if __has_include(<beside.h>)\nangled\n#endif\n";
2722 assert_eq!(run.go(src), "quoted");
2723 }
2724
2725 #[test]
2726 fn has_include_next_starts_where_include_next_would() {
2727 let mut run = Run::new();
2728 run.file("/a/both.h", "#if __has_include_next(<both.h>)\nmore\n#endif\n");
2729 run.file("/b/both.h", "last\n");
2730 run.file("/a/only.h", "#if __has_include_next(<only.h>)\nmore\n#endif\n");
2731 run.dir("/a");
2732 run.dir("/b");
2733 assert_eq!(run.go("#include <both.h>\n"), "more");
2734 assert_eq!(run.go("#include <only.h>\n"), "", "there is nothing after /a to find it in");
2735 }
2736
2737 #[test]
2738 fn the_operand_of_has_include_is_not_macro_expanded() {
2739 let mut run = Run::new();
2742 run.file("/dir/linux/version.h", "");
2743 run.dir("/dir");
2744 let src = "#define linux 1\n#if __has_include(<linux/version.h>)\nyes\n#endif\n";
2745 assert_eq!(run.go(src), "yes");
2746 }
2747
2748 #[test]
2749 fn a_macro_may_expand_to_a_has_include() {
2750 let mut run = Run::new();
2752 run.file("/dir/there.h", "");
2753 run.dir("/dir");
2754 let src = "#define HAVE __has_include(<there.h>)\n#if HAVE\nyes\n#endif\n";
2755 assert_eq!(run.go(src), "yes");
2756 }
2757
2758 #[test]
2759 fn defined_says_the_has_operators_are_there() {
2760 let src = "#if defined(__has_include) && defined __has_builtin\nyes\n#endif\n";
2763 assert_eq!(clean(src), "yes");
2764 assert_eq!(clean("#ifdef __has_attribute\nyes\n#endif\n"), "yes");
2765 }
2766
2767 #[test]
2768 fn has_attribute_answers_out_of_the_matrix() {
2769 assert_eq!(clean("#if __has_attribute(packed)\nyes\n#endif\n"), "yes");
2773 assert_eq!(clean("#if __has_attribute(cold)\nyes\n#endif\n"), "");
2774 assert_eq!(clean("#if __has_attribute(no_such_attribute)\nyes\n#endif\n"), "");
2775 assert_eq!(clean("#if !__has_attribute(cold)\nno\n#endif\n"), "no");
2776 }
2777
2778 #[test]
2779 fn the_scoped_spelling_of_an_attribute_is_the_same_question() {
2780 assert_eq!(clean("#if __has_c_attribute(gnu::packed)\nyes\n#endif\n"), "");
2786 assert_eq!(clean("#if __has_c_attribute(deprecated)\nyes\n#endif\n"), "");
2787 }
2788
2789 #[test]
2790 fn has_builtin_answers_no_until_the_builtin_is_real() {
2791 assert_eq!(clean("#if __has_builtin(__builtin_expect)\nyes\n#endif\n"), "yes");
2792 assert_eq!(clean("#if __has_builtin(__builtin_clz)\nyes\n#endif\n"), "yes");
2793 assert_eq!(clean("#if __has_builtin(__builtin_alloca)\nyes\n#endif\n"), "");
2794 assert_eq!(clean("#if __has_builtin(__builtin_nonesuch)\nyes\n#endif\n"), "");
2795 }
2796
2797 #[test]
2798 fn has_feature_and_has_extension_read_the_same_table() {
2799 assert_eq!(clean("#if __has_feature(pragma_once)\nyes\n#endif\n"), "yes");
2802 assert_eq!(clean("#if __has_extension(pragma_once)\nyes\n#endif\n"), "yes");
2803 assert_eq!(clean("#if __has_extension(include_next)\nyes\n#endif\n"), "yes");
2804 assert_eq!(clean("#if __has_feature(include_next)\nyes\n#endif\n"), "");
2805 assert_eq!(clean("#if __has_feature(statement_expressions)\nyes\n#endif\n"), "");
2806 }
2807
2808 #[test]
2809 fn building_module_is_always_no_and_is_recognised_so_that_the_line_parses() {
2810 assert_eq!(clean("#if __building_module(m)\nyes\n#endif\n"), "");
2814 assert_eq!(clean("#if !__building_module(m)\nyes\n#endif\n"), "yes");
2815 assert_eq!(
2816 clean(
2817 "#if !defined(offsetof) || (__has_feature(modules) && !__building_module(x))\nyes\n#endif\n"
2818 ),
2819 "yes"
2820 );
2821 assert_eq!(clean("#ifdef __building_module\nyes\n#endif\n"), "yes");
2823 assert_eq!(clean("#if defined(__building_module)\nyes\n#endif\n"), "yes");
2824 }
2825
2826 #[test]
2827 fn a_has_operator_without_an_operand_is_reported() {
2828 let mut run = Run::new();
2829 run.go("#if __has_include\nyes\n#endif\n");
2830 assert_eq!(run.messages(), ["expected `(` after `__has_include`"]);
2831 let mut run = Run::new();
2832 run.go("#if __has_include(1)\nyes\n#endif\n");
2833 assert_eq!(run.messages(), ["expected a file name in `<>` or `\"\"`"]);
2834 let mut run = Run::new();
2835 run.go("#if __has_attribute(\"packed\")\nyes\n#endif\n");
2836 assert_eq!(run.messages(), ["expected an identifier as the operand of `__has_attribute`"]);
2837 }
2838
2839 #[test]
2840 fn the_has_operators_answer_in_ordinary_text_too() {
2841 assert_eq!(clean("f __has_feature(pragma_once)\n"), "f 1");
2845 assert_eq!(clean("b __has_builtin(__builtin_expect)\n"), "b 1");
2846 assert_eq!(clean("a __has_attribute(packed)\n"), "a 1");
2847 assert_eq!(clean("c __has_c_attribute(deprecated)\n"), "c 0");
2848 assert_eq!(clean("m __building_module(foo)\n"), "m 0");
2849 }
2850
2851 #[test]
2852 fn a_macro_that_expands_to_a_has_operator_is_answered_where_it_is_used() {
2853 assert_eq!(clean("#define HAVE __has_feature(pragma_once)\nx HAVE\n"), "x 1");
2856 assert_eq!(clean("#define HAVE(x) __has_attribute(x)\ny HAVE(packed)\n"), "y 1");
2857 }
2858
2859 #[test]
2860 fn a_has_operator_in_text_still_needs_its_operand() {
2861 let mut run = Run::new();
2862 run.go("tail __has_attribute;\n");
2863 assert_eq!(run.messages(), ["expected `(` after `__has_attribute`"]);
2864 }
2865
2866 #[test]
2867 fn the_header_operators_are_refused_in_ordinary_text() {
2868 let mut run = Run::new();
2871 run.file("/dir/there.h", "");
2872 run.dir("/dir");
2873 run.go("a __has_include(<there.h>)\n");
2874 assert_eq!(run.messages(), ["`__has_include` used outside of a preprocessing directive"]);
2875 let mut run = Run::new();
2876 run.go("b __has_include_next(\"x.h\")\n");
2877 assert_eq!(
2878 run.messages(),
2879 ["`__has_include_next` used outside of a preprocessing directive"]
2880 );
2881 }
2882
2883 #[test]
2884 fn the_predefined_set_is_visible_to_the_source_file() {
2885 let mut run = Run::new();
2886 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2887 let src = "#if defined(__x86_64__) && defined(__linux__) && __SIZEOF_LONG__ == 8\n\
2888 yes\n#endif\n";
2889 assert_eq!(run.go(src), "yes");
2890 assert!(run.messages().is_empty());
2891 }
2892
2893 #[test]
2894 fn the_predefined_set_follows_the_target_and_not_the_host() {
2895 let mut run = Run::new();
2896 run.predefine("aarch64-unknown-linux-gnu", &Predef::new());
2897 assert_eq!(
2898 run.go("#ifdef __x86_64__\nno\n#endif\n#ifdef __aarch64__\nyes\n#endif\n"),
2899 "yes"
2900 );
2901 }
2902
2903 #[test]
2904 fn a_predefined_macro_expands_where_it_is_used() {
2905 let mut run = Run::new();
2906 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2907 assert_eq!(run.go("__SIZE_TYPE__ n;\n"), "long unsigned int n;");
2908 }
2909
2910 #[test]
2911 fn a_command_line_define_is_a_definition_like_any_other() {
2912 let mut opts = Predef::new();
2913 opts.defines = vec!["FOO".to_owned(), "BAR=3".to_owned()];
2914 opts.undefines = vec!["__linux__".to_owned()];
2915 let mut run = Run::new();
2916 run.predefine("x86_64-unknown-linux-gnu", &opts);
2917 let src = "#if FOO && BAR == 3 && !defined(__linux__)\nyes\n#endif\n";
2918 assert_eq!(run.go(src), "yes");
2919 assert!(run.messages().is_empty());
2920 }
2921
2922 #[test]
2923 fn the_predefined_set_produces_no_tokens_of_its_own() {
2924 let mut run = Run::new();
2927 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
2928 assert_eq!(run.go("alone\n"), "alone");
2929 }
2930
2931 #[test]
2932 fn the_predefined_files_are_named_the_way_gcc_names_them() {
2933 let mut run = Run::new();
2934 let mut opts = Predef::new();
2935 opts.defines = vec!["FOO=1".to_owned()];
2936 run.predefine("x86_64-unknown-linux-gnu", &opts);
2937 let names: Vec<&str> = run.sources.files().iter().map(|f| f.name.as_str()).collect();
2938 assert_eq!(names, ["<built-in>", "<command-line>"]);
2939 }
2940
2941 #[test]
2942 fn a_dialect_without_the_gnu_extensions_says_so() {
2943 let mut opts = Predef::new();
2944 opts.gnu_extensions = false;
2945 opts.std = Std::C99;
2946 let mut run = Run::new();
2947 run.predefine("x86_64-unknown-linux-gnu", &opts);
2948 let src = "#if defined(__STRICT_ANSI__) && __STDC_VERSION__ == 199901L && !defined(linux)\n\
2949 yes\n#endif\n";
2950 assert_eq!(run.go(src), "yes");
2951 }
2952
2953 #[test]
2954 fn the_date_and_time_are_the_same_for_the_whole_translation_unit() {
2955 let mut opts = Predef::new();
2956 opts.timestamp = Timestamp::from_unix(0);
2957 let mut run = Run::new();
2958 run.predefine("x86_64-unknown-linux-gnu", &opts);
2959 assert_eq!(run.go("__DATE__ __TIME__\n"), "\"Jan 1 1970\" \"00:00:00\"");
2960 }
2961
2962 #[test]
2963 fn a_has_operator_in_a_dead_branch_is_not_asked_about() {
2964 assert_eq!(clean("#if 0\n#if __has_include\n#endif\n#endif\nafter\n"), "after");
2966 }
2967
2968 #[test]
2969 fn a_conditional_may_not_span_an_include() {
2970 let mut run = Run::new();
2974 run.file("/dir/open.h", "#if 1\n");
2975 run.dir("/dir");
2976 run.go("#include <open.h>\nkept\n#endif\n");
2977 let messages = run.messages();
2978 assert_eq!(messages.len(), 2);
2979 assert!(messages[0].contains("unterminated"));
2980 assert!(messages[1].contains("without"));
2981 }
2982
2983 #[test]
2984 fn include_next_continues_after_the_directory_the_file_came_from() {
2985 let mut run = Run::new();
2988 run.file("/a/limits.h", "wrapper\n#include_next <limits.h>\n");
2989 run.file("/b/limits.h", "real\n");
2990 run.dir("/a");
2991 run.dir("/b");
2992 assert_eq!(run.go("#include <limits.h>\n"), "wrapper real");
2993 assert!(run.messages().is_empty());
2994 }
2995
2996 #[test]
2997 fn a_computed_include_is_expanded_first() {
2998 let mut run = Run::new();
2999 run.file("/dir/sub/thing.h", "computed\n");
3000 run.dir("/dir");
3001 let src = "#define HEADER <sub/thing.h>\n#include HEADER\n";
3002 assert_eq!(run.go(src), "computed");
3003 assert!(run.messages().is_empty());
3004 let mut run = Run::new();
3006 run.file("/dir/sub/thing.h", "computed\n");
3007 run.dir("/dir");
3008 assert_eq!(run.go("#define H \"sub/thing.h\"\n#include H\n"), "computed");
3009 }
3010
3011 #[test]
3012 fn a_header_that_is_not_there_says_where_it_looked() {
3013 let mut run = Run::new();
3014 run.dir("/dir");
3015 run.go("#include <nope.h>\n");
3016 let diagnostics = run.pp.take_diagnostics();
3017 assert_eq!(diagnostics.len(), 1);
3018 assert_eq!(diagnostics[0].code, Some("E0341"));
3019 assert_eq!(diagnostics[0].message, "`nope.h` file not found");
3020 assert!(diagnostics[0].children[0].message.contains("/dir"));
3021 }
3022
3023 #[test]
3024 fn an_include_that_is_not_a_header_name_is_reported() {
3025 let mut run = Run::new();
3026 run.go("#include 3\n");
3027 let diagnostics = run.pp.take_diagnostics();
3028 assert_eq!(diagnostics[0].code, Some("E0343"));
3029 }
3030
3031 #[test]
3032 fn a_header_that_includes_itself_stops() {
3033 let mut run = Run::new();
3034 run.file("/dir/loop.h", "#include <loop.h>\n");
3035 run.dir("/dir");
3036 run.go("#include <loop.h>\n");
3037 let diagnostics = run.pp.take_diagnostics();
3038 assert_eq!(diagnostics.len(), 1, "one complaint, not one per level");
3039 assert_eq!(diagnostics[0].code, Some("E0342"));
3040 }
3041
3042 #[test]
3043 fn an_include_in_a_dead_branch_is_not_read() {
3044 let mut run = Run::new();
3045 assert_eq!(run.go("#if 0\n#include <nothing.h>\n#endif\nafter\n"), "after");
3046 assert!(run.messages().is_empty(), "a skipped include is not resolved");
3047 }
3048
3049 #[test]
3050 fn embed_writes_the_bytes_of_the_resource() {
3051 let mut run = Run::new();
3052 run.bytes("/logo.bin", &[0, 1, 127, 128, 255]);
3053 assert_eq!(run.go("#embed \"logo.bin\"\n"), "0, 1, 127, 128, 255");
3054 assert!(run.messages().is_empty());
3055 }
3056
3057 #[test]
3058 fn an_embed_is_a_valid_initializer_on_both_sides_of_empty() {
3059 let mut run = Run::new();
3064 run.bytes("/some.bin", &[7, 8]);
3065 run.bytes("/none.bin", &[]);
3066 let line = |name: &str| {
3067 format!("{{\n#embed \"{name}\" prefix(0xEF,) suffix(,0xFE) if_empty(0)\n}}\n")
3068 };
3069 assert_eq!(run.go(&line("some.bin")), "{ 0xEF,7, 8 ,0xFE }");
3070 assert_eq!(run.go_named("/other.c", &line("none.bin")), "{ 0 }");
3071 assert!(run.messages().is_empty());
3072 }
3073
3074 #[test]
3075 fn the_limit_and_the_offset_choose_a_window_of_the_resource() {
3076 let mut run = Run::new();
3077 run.bytes("/eight.bin", &[1, 2, 3, 4, 5, 6, 7, 8]);
3078 assert_eq!(run.go("#embed \"eight.bin\" limit(3)\n"), "1, 2, 3");
3079 assert_eq!(
3080 run.go_named("/b.c", "#embed \"eight.bin\" gnu::offset(4) limit(3)\n"),
3081 "5, 6, 7"
3082 );
3083 assert_eq!(run.go_named("/c.c", "#embed \"eight.bin\" limit(0) if_empty(9)\n"), "9");
3086 assert_eq!(run.go_named("/d.c", "#embed \"eight.bin\" gnu::offset(99)\n"), "");
3087 assert!(run.messages().is_empty());
3088 }
3089
3090 #[test]
3091 fn the_limit_is_a_constant_expression_and_not_just_a_number() {
3092 let mut run = Run::new();
3095 run.bytes("/eight.bin", &[1, 2, 3, 4, 5, 6, 7, 8]);
3096 assert_eq!(
3097 run.go("#define CHUNK 2\n#embed \"eight.bin\" limit(CHUNK * 2)\n"),
3098 "1, 2, 3, 4"
3099 );
3100 assert!(run.messages().is_empty());
3101 }
3102
3103 #[test]
3104 fn a_misspelled_embed_parameter_is_refused_rather_than_ignored() {
3105 let mut run = Run::new();
3108 run.bytes("/eight.bin", &[1, 2]);
3109 assert_eq!(run.go("#embed \"eight.bin\" limits(1)\n"), "");
3110 assert_eq!(run.messages(), vec!["unknown `#embed` parameter `limits`".to_owned()]);
3111 let mut vendor = Run::new();
3112 vendor.bytes("/eight.bin", &[1, 2]);
3113 assert_eq!(vendor.go("#embed \"eight.bin\" clang::offset(1)\n"), "");
3114 assert_eq!(
3115 vendor.messages(),
3116 vec!["unknown `#embed` parameter `clang::offset`".to_owned()]
3117 );
3118 }
3119
3120 #[test]
3121 fn a_missing_embed_resource_is_reported_as_a_resource() {
3122 let mut run = Run::new();
3123 run.go("#embed <nothing.bin>\n");
3124 assert_eq!(run.messages(), vec!["`nothing.bin` resource not found".to_owned()]);
3125 }
3126
3127 #[test]
3128 fn has_embed_tells_missing_from_present_from_empty() {
3129 let mut run = Run::new();
3133 run.bytes("/some.bin", &[1]);
3134 run.bytes("/none.bin", &[]);
3135 let src = "#if __has_embed(\"none.bin\") == __STDC_EMBED_EMPTY__\nempty\n#endif\n\
3136 #if __has_embed(\"some.bin\") == __STDC_EMBED_FOUND__\nfound\n#endif\n\
3137 #if __has_embed(\"gone.bin\") == __STDC_EMBED_NOT_FOUND__\ngone\n#endif\n";
3138 run.predefine("x86_64-unknown-linux-gnu", &Predef::default());
3139 assert_eq!(run.go(src), "empty found gone");
3140 assert!(run.messages().is_empty());
3141 }
3142
3143 #[test]
3144 fn has_embed_takes_the_limit_into_account() {
3145 let mut run = Run::new();
3148 run.bytes("/some.bin", &[1, 2, 3]);
3149 run.predefine("x86_64-unknown-linux-gnu", &Predef::default());
3150 let src = "#if __has_embed(\"some.bin\" limit(0)) == __STDC_EMBED_EMPTY__\nempty\n#endif\n";
3151 assert_eq!(run.go(src), "empty");
3152 assert!(run.messages().is_empty());
3153 }
3154
3155 #[test]
3156 fn a_directive_may_have_space_before_the_hash_and_after_it() {
3157 assert_eq!(clean(" # define F 1\n#ifdef F\nyes\n#endif\n"), "yes");
3158 }
3159
3160 #[test]
3161 fn a_definition_survives_across_a_conditional() {
3162 assert_eq!(clean("#if 1\n#define F 7\n#endif\nF\n"), "7");
3163 }
3164
3165 #[test]
3166 fn an_empty_if_expression_is_reported() {
3167 let mut run = Run::new();
3168 run.go("#if\n#endif\n");
3169 assert_eq!(run.messages(), vec!["`#if` with no expression".to_owned()]);
3170 }
3171
3172 #[test]
3173 fn the_file_and_the_line_say_where_the_use_is() {
3174 let mut run = Run::new();
3175 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3176 assert_eq!(run.go("__FILE__ __LINE__\n__LINE__\n"), "\"/main.c\" 1 2");
3177 assert!(run.messages().is_empty());
3178 }
3179
3180 #[test]
3181 fn a_macro_that_mentions_the_line_answers_with_the_call() {
3182 let mut run = Run::new();
3183 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3184 run.file("/where.h", "#define WHERE __FILE__ __LINE__\n");
3185 assert_eq!(run.go("#include \"where.h\"\n\n\nWHERE\n"), "\"/main.c\" 4");
3189 assert!(run.messages().is_empty());
3190 }
3191
3192 #[test]
3193 fn the_file_name_is_the_file_without_the_directories() {
3194 let mut run = Run::new();
3195 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3196 assert_eq!(run.go_named("/deep/down/main.c", "__FILE_NAME__\n"), "\"main.c\"");
3197 }
3198
3199 #[test]
3200 fn a_backslash_in_the_name_is_escaped() {
3201 let mut run = Run::new();
3202 run.predefine("x86_64-pc-windows-msvc", &Predef::new());
3203 let text = run.go_named("C:\\src\\main.c", "__FILE__ __FILE_NAME__\n");
3206 assert_eq!(text, "\"C:\\\\src\\\\main.c\" \"main.c\"");
3207 }
3208
3209 #[test]
3210 fn the_base_file_is_the_one_named_on_the_command_line() {
3211 let mut run = Run::new();
3212 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3213 run.file("/deep.h", "__FILE__ __BASE_FILE__\n");
3214 assert_eq!(run.go("#include \"deep.h\"\n"), "\"/deep.h\" \"/main.c\"");
3215 assert!(run.messages().is_empty());
3216 }
3217
3218 #[test]
3219 fn a_prefix_map_rewrites_the_file_and_the_base_file_and_not_the_file_name() {
3220 let mut run = Run::mapping(&[("/build", ".")]);
3221 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3222 run.file("/build/deep.h", "__FILE__ __BASE_FILE__ __FILE_NAME__\n");
3223 let text = run.go_named("/build/main.c", "#include \"deep.h\"\n");
3229 assert_eq!(slashes(&text), "\"./deep.h\" \"./main.c\" \"deep.h\"");
3232 assert!(run.messages().is_empty());
3233 }
3234
3235 #[test]
3236 fn the_last_rewrite_that_matches_is_the_one_that_acts() {
3237 let mut run = Run::mapping(&[("/build", "src"), ("/build/gen", "generated")]);
3240 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3241 assert_eq!(run.go_named("/build/gen/made.c", "__FILE__\n"), "\"generated/made.c\"");
3242
3243 let mut run = Run::mapping(&[("/build", "src"), ("/build/gen", "generated")]);
3244 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3245 assert_eq!(run.go_named("/build/hand.c", "__FILE__\n"), "\"src/hand.c\"");
3246
3247 let mut run = Run::mapping(&[("/build", "src")]);
3250 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3251 assert_eq!(run.go_named("/elsewhere/main.c", "__FILE__\n"), "\"/elsewhere/main.c\"");
3252 }
3253
3254 #[test]
3255 fn a_rewrite_matches_the_characters_and_not_the_directories() {
3256 let mut run = Run::mapping(&[("/bui", "X")]);
3262 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3263 assert_eq!(run.go_named("/build/main.c", "__FILE__\n"), "\"Xld/main.c\"");
3264 }
3265
3266 #[test]
3267 fn the_include_level_counts_the_headers_above_it() {
3268 let mut run = Run::new();
3269 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3270 run.file("/one.h", "__INCLUDE_LEVEL__\n#include \"two.h\"\n");
3271 run.file("/two.h", "__INCLUDE_LEVEL__\n");
3272 assert_eq!(run.go("__INCLUDE_LEVEL__\n#include \"one.h\"\n"), "0 1 2");
3273 assert!(run.messages().is_empty());
3274 }
3275
3276 #[test]
3277 fn the_counter_is_a_different_number_every_time() {
3278 let mut run = Run::new();
3279 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3280 assert_eq!(run.go("__COUNTER__ __COUNTER__ __COUNTER__\n"), "0 1 2");
3281 }
3282
3283 #[test]
3284 fn the_counter_advances_once_per_argument_rather_than_once_per_use() {
3285 let mut run = Run::new();
3286 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3287 assert_eq!(run.go("#define TWICE(x) x x\nTWICE(__COUNTER__) __COUNTER__\n"), "0 0 1");
3291 }
3292
3293 #[test]
3294 fn the_line_is_a_number_an_if_can_use() {
3295 let mut run = Run::new();
3296 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3297 assert_eq!(run.go("#if __LINE__ == 1 && __INCLUDE_LEVEL__ == 0\nyes\n#endif\n"), "yes");
3298 assert!(run.messages().is_empty());
3299 }
3300
3301 #[test]
3302 fn the_dynamic_macros_are_defined_like_any_others() {
3303 let mut run = Run::new();
3304 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3305 let src = "#ifdef __FILE__\nyes\n#endif\n#undef __LINE__\n#ifndef __LINE__\ngone\n#endif\n";
3306 assert_eq!(run.go(src), "yes gone");
3307 assert!(run.messages().is_empty(), "`#undef` of a builtin is allowed, as it is in GCC");
3308 }
3309
3310 #[test]
3311 fn redefining_a_dynamic_macro_warns_and_points_at_the_built_in_file() {
3312 let mut run = Run::new();
3313 run.predefine("x86_64-unknown-linux-gnu", &Predef::new());
3314 assert_eq!(run.go("#define __FILE__ \"mine.c\"\n__FILE__\n"), "\"mine.c\"");
3315 let complaints = run.pp.take_diagnostics();
3316 assert_eq!(complaints.len(), 1);
3317 assert_eq!(complaints[0].code, Some("W0301"));
3318 let previous = complaints[0].children.first().expect("a note saying where it was");
3319 assert_eq!(run.sources.lookup(previous.span.lo).map(|loc| loc.file), {
3320 let built_in = run.sources.files().iter().find(|f| f.name == BUILT_IN);
3321 built_in.map(|f| f.id)
3322 });
3323 }
3324
3325 #[test]
3326 fn destringizing_undoes_what_stringizing_did() {
3327 assert_eq!(destringize(r#""a \"b\" c""#), r#"a "b" c"#);
3328 assert_eq!(destringize(r#""a \\ b""#), r"a \ b");
3329 assert_eq!(destringize(r#"L"wide""#), "wide");
3330 }
3331}