use std::path::Path;
use rucc_diag::{Diagnostic, Severity, Span};
use rucc_lex::{Convert, Keywords, PpToken, convert};
use rucc_sema::{Checker, Context as CheckContext};
use rucc_session::{EmitKind, FileSystem, Options, Session};
use crate::preprocess::render;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Compiled {
pub text: String,
pub messages: Vec<String>,
pub errors: u32,
}
impl Compiled {
#[must_use]
pub fn failed(&self) -> bool {
self.errors > 0
}
}
#[must_use]
pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
let mut sess = Session::new(opts.clone());
let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
let mut diagnostics: Vec<Diagnostic> = Vec::new();
let bytes = match fs.read(Path::new(name)) {
Ok(bytes) => bytes,
Err(e) => return failure(format!("{name}: {e}")),
};
let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
return failure(format!("{name}: the source map has no room left for this file"));
};
let mut pp = rucc_pp::Preprocessor::new();
let predef = rucc_pp::Predef::for_options(opts);
let expanded: Vec<PpToken> = {
let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
return failure(format!("{name}: the source map has no room for the built in macros"));
}
pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
};
diagnostics.extend(pp.take_diagnostics());
let cx = Convert {
keywords: &keywords,
interner: &sess.interner,
target: &sess.target,
std: opts.std,
gnu: opts.gnu_extensions,
pedantic: opts.pedantic,
};
let (tokens, complaints) = convert(&expanded, &cx);
diagnostics.extend(complaints);
let parsed = rucc_parse::parse(
&tokens,
rucc_parse::Context {
interner: &sess.interner,
std: opts.std,
gnu: opts.gnu_extensions,
pedantic: opts.pedantic,
error_limit: opts.error_limit as usize,
},
);
let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
diagnostics.extend(parsed.diagnostics);
let mut text = String::new();
if !parse_failed {
let mut checker = Checker::new(
&parsed.ast,
CheckContext {
names: &sess.interner,
target: &sess.target,
std: opts.std,
gnu: opts.gnu_extensions,
pedantic: opts.pedantic,
error_limit: opts.error_limit as usize,
},
);
checker.check_unit();
let checked = checker.finish();
if !checked.failed() {
match opts.emit {
EmitKind::Tast => {
text = rucc_sema::print(&checked.tast, &checked.types, &sess.interner);
}
EmitKind::Ir => {
let lowered = rucc_lower::lower(
name,
rucc_lower::Context {
tast: &checked.tast,
types: &checked.types,
target: &sess.target,
names: &mut sess.interner,
},
);
let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
if !failed {
if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
for error in errors {
diagnostics.push(internal(&format!("invalid IR, {error}")));
}
} else {
text = rucc_ir::print(&lowered.module, &sess.interner);
}
}
diagnostics.extend(lowered.diagnostics);
}
_ => {}
}
}
diagnostics.extend(checked.diagnostics);
}
let mut messages = Vec::with_capacity(diagnostics.len());
let mut errors = 0;
for diag in &diagnostics {
if diag.severity.is_fatal()
|| (diag.severity == Severity::Warning && opts.warnings_are_errors)
{
errors += 1;
}
messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
}
if errors > 0 {
text.clear();
}
Compiled { text, messages, errors }
}
#[must_use]
pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
let mut sess = Session::new(opts.clone());
if opts.emit != EmitKind::Ir {
return failure(format!(
"{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
the C in front of it became",
opts.emit.as_str()
));
}
let bytes = match fs.read(Path::new(name)) {
Ok(bytes) => bytes,
Err(e) => return failure(format!("{name}: {e}")),
};
let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
return failure(format!("{name}: this is not text, so it is not IR"));
};
let module = match rucc_ir::parse(text, &mut sess.interner) {
Ok(module) => module,
Err(error) => {
return failure(format!("{name}:{}: {}", error.line, error.message));
}
};
let mut diagnostics: Vec<Diagnostic> = Vec::new();
if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
for error in errors {
diagnostics.push(invalid(&format!("invalid IR, {error}")));
}
}
let mut messages = Vec::with_capacity(diagnostics.len());
for diag in &diagnostics {
messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
}
let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
let text = if errors > 0 { String::new() } else { rucc_ir::print(&module, &sess.interner) };
Compiled { text, messages, errors }
}
fn invalid(message: &str) -> Diagnostic {
Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
}
fn internal(message: &str) -> Diagnostic {
Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
.with_code("E0652")
.note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
}
fn failure(message: String) -> Compiled {
Compiled { text: String::new(), messages: vec![format!("rucc: error: {message}")], errors: 1 }
}
#[cfg(test)]
mod tests {
use rucc_session::{MemoryFileSystem, Std};
use rucc_target::Triple;
use super::*;
fn options() -> Options {
let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
opts.emit = EmitKind::Tast;
opts
}
fn run(opts: &Options, source: &str) -> Compiled {
let mut fs = MemoryFileSystem::new();
fs.insert("/main.c", source.to_owned().into_bytes());
compile(opts, "/main.c", &fs)
}
fn freestanding() -> Options {
let mut opts = options();
opts.hosted = false;
opts.search.push_system(rucc_session::runtime::DIR);
opts
}
fn shipped(source: &str) -> String {
let result = run(&freestanding(), source);
assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
result.text
}
fn tast(source: &str) -> String {
let result = run(&options(), source);
assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
result.text
}
#[test]
fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
let text = shipped(concat!(
"#include <stdarg.h>\n",
"int sum(int n, ...) {\n",
" va_list ap, copy;\n",
" va_start(ap, n);\n",
" va_copy(copy, ap);\n",
" int total = va_arg(ap, int) + va_arg(copy, int);\n",
" va_end(ap);\n",
" va_end(copy);\n",
" return total;\n",
"}\n",
));
assert!(text.contains("va-start"), "{text}");
assert!(text.contains("va-copy"), "{text}");
assert!(text.contains("va-arg"), "{text}");
assert!(text.contains("va-end"), "{text}");
}
#[test]
fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
let text = shipped(concat!(
"#define __need___va_list\n",
"#include <stdarg.h>\n",
"int vprint(const char *f, __gnuc_va_list ap);\n",
"#ifdef va_start\n",
"#error va_start should not be defined\n",
"#endif\n",
"#ifdef _VA_LIST_DEFINED\n",
"#error va_list should not have been made\n",
"#endif\n",
));
assert!(text.contains("vprint"), "{text}");
}
#[test]
fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
let text = shipped(concat!(
"#define __need_size_t\n",
"#include <stddef.h>\n",
"#ifdef offsetof\n",
"#error offsetof should not be defined yet\n",
"#endif\n",
"#define __need_ptrdiff_t\n",
"#include <stddef.h>\n",
"#include <stddef.h>\n",
"size_t a;\n",
"ptrdiff_t b;\n",
"wchar_t c;\n",
"max_align_t d;\n",
"void *e = NULL;\n",
"struct P { int x; long y; };\n",
"size_t f = offsetof(struct P, y);\n",
));
assert!(text.contains("decl #0 a : unsigned long"), "{text}");
assert!(text.contains("decl #1 b : long"), "{text}");
}
#[test]
fn the_shipped_limits_and_float_are_the_targets_own_answers() {
let text = shipped(concat!(
"#include <limits.h>\n",
"#include <float.h>\n",
"int bits = CHAR_BIT;\n",
"long big = LONG_MAX;\n",
"int low = INT_MIN;\n",
"int radix = FLT_RADIX;\n",
"int digits = DBL_MANT_DIG;\n",
));
assert!(text.contains("const 8 : int"), "{text}");
assert!(text.contains("const 9223372036854775807 : long"), "{text}");
assert!(text.contains("const 2 : int"), "{text}");
assert!(text.contains("const 53 : int"), "{text}");
}
#[test]
fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
let text = shipped(concat!(
"#include <stdint.h>\n",
"int64_t a = INT64_C(1);\n",
"uint_least16_t b;\n",
"intptr_t c;\n",
"uintmax_t d = UINTMAX_MAX;\n",
"int wide = sizeof(int_fast64_t);\n",
));
assert!(text.contains("decl #0 a : long"), "{text}");
assert!(text.contains("decl #1 b : unsigned short"), "{text}");
assert!(text.contains("decl #2 c : long"), "{text}");
}
#[test]
fn the_three_formality_headers_still_have_to_work() {
let text = shipped(concat!(
"#include <stdbool.h>\n",
"#include <stdalign.h>\n",
"#include <iso646.h>\n",
"#include <stdnoreturn.h>\n",
"int t = true and not false;\n",
"_Alignas(16) char buf[16];\n",
"int a = alignof(long);\n",
));
assert!(text.contains("decl #0 t : int"), "{text}");
assert!(text.contains("const 8 : unsigned long"), "{text}");
}
#[test]
fn every_shipped_header_can_be_included_twice() {
let mut source = String::new();
for _ in 0..2 {
for name in rucc_session::runtime::names() {
source.push_str(&format!("#include <{name}>\n"));
}
}
source.push_str("int x;\n");
let text = shipped(&source);
assert!(text.starts_with("decl #0 x : int"), "{text}");
}
#[test]
fn a_file_that_is_not_there_says_so_and_produces_nothing() {
let fs = MemoryFileSystem::new();
let result = compile(&options(), "/nope.c", &fs);
assert!(result.failed());
assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
assert!(result.text.is_empty());
}
#[test]
fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
let text = tast("int x = 1;\n");
let expected = "\
decl #0 x : int object external static defined
init
+0
const 1 : int
";
assert_eq!(text, expected);
}
#[test]
fn the_macros_are_expanded_before_anything_is_parsed() {
let text = tast("#define N 2\nint a[N];\n");
assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
}
#[test]
fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
let text = tast(concat!(
"#pragma pack(4)\n",
"struct s { int a; };\n",
"#pragma pack()\n",
"int b;\n",
"_Pragma(\"GCC visibility push(default)\") int c;\n",
));
assert!(text.contains("decl #0 b : int"), "{text}");
assert!(text.contains("decl #1 c : int"), "{text}");
}
#[test]
fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
tast(concat!(
"struct A { char c; int i; } __attribute__((packed));\n",
"_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
"_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
"struct B { char c; int i; } __attribute__((aligned));\n",
"_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
"struct C { char c; int i __attribute__((packed)); };\n",
"_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
"_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
"struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
"_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
"_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
"struct E { char c; _Alignas(8) int i; };\n",
"_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
"_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
"struct F { char c; int i __attribute__((aligned(8))); };\n",
"_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
"struct G { char c; short s; } __attribute__((aligned(2)));\n",
"_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
"struct H { char c; int i; } __attribute__((aligned(2)));\n",
"_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
"struct I { [[gnu::packed]] char c; int i; };\n",
"_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
"struct J { char c; [[gnu::packed]] int i; };\n",
"_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
"struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
"_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
"struct N { char c; long long l; } __attribute__((aligned(32)));\n",
"_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
"union L { char c; int i; } __attribute__((packed));\n",
"_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
));
}
#[test]
fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
assert_eq!(
bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
1
);
assert_eq!(
bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
1
);
assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
}
fn bit_field_byte(record: &str) -> u64 {
let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
let body = body(&source);
let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
}
#[test]
fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
tast(concat!(
"struct a { char c; __attribute__((aligned(8))) int i; };\n",
"_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
"_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
"struct b { char c; __attribute__((packed)) int i; };\n",
"_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
"_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
"typedef struct { char c; int i; } __attribute__((packed)) c;\n",
"_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
));
}
#[test]
fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
tast(concat!(
"#pragma pack(1)\n",
"struct A { char c; int i; };\n",
"_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
"_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
"#pragma pack()\n",
"struct B { char c; int i; };\n",
"_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
"#pragma pack(2)\n",
"struct C { char c; int i; double d; };\n",
"_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
"_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
"struct K { char c; int i __attribute__((aligned(8))); };\n",
"_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
"_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
"struct J { char c; int i; } __attribute__((aligned(8)));\n",
"_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
"#pragma pack()\n",
"#pragma pack(push, 1)\n",
"struct D { char c; short s; };\n",
"_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
"#pragma pack(pop)\n",
"struct E { char c; short s; };\n",
"_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
"struct H { char c;\n",
"#pragma pack(1)\n",
" int i; };\n",
"_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
"#pragma pack(1)\n",
"struct I { char c;\n",
"#pragma pack()\n",
" int i; };\n",
"_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
"#pragma pack()\n",
"#pragma pack(push, 8)\n",
"#pragma pack(push, 1)\n",
"struct P { char c; int i; };\n",
"_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
"#pragma pack(pop)\n",
"struct Q { char c; int i; };\n",
"_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
"#pragma pack(pop)\n",
"#pragma pack(16)\n",
"struct R { char c; int i; };\n",
"_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
"#pragma pack()\n",
"#pragma pack(1)\n",
"struct S { char c; int i : 5; int j : 20; };\n",
"_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
"union T { char c; int i; };\n",
"_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
"#pragma pack()\n",
));
}
#[test]
fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
let result = run(
&options(),
concat!(
"#pragma pack 4\n",
"#pragma pack(pop)\n",
"#pragma pack(3)\n",
"#pragma pack(1) junk\n",
"#pragma pack(push, 1\n",
"#pragma pack(x)\n",
"#pragma pack(0)\n",
"#pragma pack(push)\n",
"struct s { char c; int i; };\n",
"#pragma pack(pop)\n",
"#pragma pack(pop, foo)\n",
),
);
let expected = [
"missing `(` after `#pragma pack` - ignored",
"`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
"alignment must be a small power of two, not 3",
"junk at end of `#pragma pack`",
"malformed `#pragma pack(push[, id][, <n>])` - ignored",
"unknown action `x` for `#pragma pack` - ignored",
"`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
];
assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
for (message, want) in result.messages.iter().zip(expected) {
assert!(message.contains(want), "expected {want:?} in {message:?}");
}
}
#[test]
fn the_wide_integer_answers_to_all_three_of_its_names() {
let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
assert!(text.contains("decl #1 b : __int128"), "{text}");
assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
}
#[test]
fn every_conversion_the_language_performs_is_a_node_in_the_output() {
let text = tast("long f(int a, long b) { return a + b; }\n");
assert!(text.contains("convert arithmetic"), "{text}");
}
#[test]
fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
for source in [
"#error stop\n",
"int f(void) { return 1 + ; }\n",
"int f(void) { return undeclared; }\n",
] {
let result = run(&options(), source);
assert!(result.failed(), "expected this to fail:\n{source}");
assert!(result.text.is_empty(), "a file that did not compile wrote a tree:\n{source}");
}
}
#[test]
fn one_undeclared_name_is_one_message_and_not_one_per_use() {
let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
assert_eq!(result.errors, 1, "{:?}", result.messages);
}
#[test]
fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
assert_eq!(result.errors, 1, "{:?}", result.messages);
}
#[test]
fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
let source = "int f(void) { char c = 300; return c; }\n";
let plain = run(&options(), source);
assert_eq!(plain.errors, 0, "{:?}", plain.messages);
assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
assert!(!plain.text.is_empty(), "a warning is not a reason to write nothing");
let mut opts = options();
opts.warnings_are_errors = true;
let strict = run(&opts, source);
assert!(strict.failed());
assert!(strict.text.is_empty(), "and under -Werror it is a reason to write nothing");
for message in &strict.messages {
assert!(!message.contains("warning:"), "{message}");
}
}
#[test]
fn the_dialect_reaches_the_keywords_and_the_checking() {
let source = "typeof(1) x;\n";
let mut opts = options();
opts.std = Std::C23;
opts.gnu_extensions = false;
assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
opts.std = Std::C17;
assert!(run(&opts, source).failed());
}
#[test]
fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
let mut opts = options();
opts.emit = EmitKind::MirFinal;
let result = run(&opts, "int x = 1;\n");
assert!(!result.failed(), "{:?}", result.messages);
assert!(result.text.is_empty());
assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
}
fn ir(source: &str) -> String {
let mut opts = options();
opts.emit = EmitKind::Ir;
let result = run(&opts, source);
assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
result.text
}
fn body(source: &str) -> String {
let text = ir(source);
let (_, rest) = text.split_once("{\n").expect("a function definition");
let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
body.to_owned()
}
#[test]
fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
let text = ir(concat!(
"int g;\n",
"int a = __builtin_constant_p(1);\n",
"int b = __builtin_constant_p(g);\n",
"int c = __builtin_constant_p(\"abc\");\n",
"int d = __builtin_constant_p(&g);\n",
"int e = __builtin_constant_p(1.5);\n",
"int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
));
assert!(text.contains("global @a : i32 = 1,"), "{text}");
assert!(text.contains("global @b : i32 = 0,"), "{text}");
assert!(text.contains("global @c : i32 = 1,"), "{text}");
assert!(text.contains("global @d : i32 = 0,"), "{text}");
assert!(text.contains("global @e : i32 = 1,"), "{text}");
assert!(text.contains("global @h : i32 = 11,"), "{text}");
assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
}
#[test]
fn a_call_to_a_library_builtin_reaches_the_library_function() {
let text = body("void f(void) { __builtin_abort(); }\n");
assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
}
#[test]
fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
let mut opts = options();
opts.emit = EmitKind::Ir;
let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
assert!(
messages.iter().any(|m| m.contains("__builtin_abort")),
"expected the written name in {messages:?}"
);
}
#[test]
fn a_classification_c_has_an_operator_for_is_that_operator() {
for (builtin, operator) in [
("__builtin_isgreater", "binary >"),
("__builtin_isgreaterequal", "binary >="),
("__builtin_isless", "binary <"),
("__builtin_islessequal", "binary <="),
] {
let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
let text = tast(&source);
assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
}
}
#[test]
fn the_classification_builtins_are_comparisons_and_not_calls() {
let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
assert_eq!(
text,
"block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
%2\n return %3\n"
);
let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
assert!(text.contains("fcmp one %0, %1"), "{text}");
let text = body("int f(double x) { return __builtin_isnan(x); }\n");
assert!(text.contains("fcmp uno %0, %0"), "{text}");
let text = body("int f(double x) { return __builtin_isinf(x); }\n");
assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
assert!(text.contains("%5 = or %3, %4"), "{text}");
let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
assert!(text.contains("%5 = and %3, %4"), "{text}");
let text = body("int f(double x) { return __builtin_signbit(x); }\n");
assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
assert!(text.contains("icmp slt %1, %2"), "{text}");
let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
assert_eq!(text.matches("call @g()").count(), 1, "{text}");
}
#[test]
fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
let text = ir(concat!(
"int a = __builtin_isinff(1e300);\n",
"int b = __builtin_isinf(1e300);\n",
"int c = __builtin_isnan(0.0);\n",
"int d = __builtin_signbit(-0.0);\n",
"int e = __builtin_islessgreater(1.0, 2.0);\n",
));
assert!(text.contains("global @a : i32 = 1,"), "{text}");
assert!(text.contains("global @b : i32 = 0,"), "{text}");
assert!(text.contains("global @c : i32 = 0,"), "{text}");
assert!(text.contains("global @d : i32 = 1,"), "{text}");
assert!(text.contains("global @e : i32 = 1,"), "{text}");
}
#[test]
fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
let mut opts = options();
opts.emit = EmitKind::Ir;
let source = concat!(
"int a(int x) { return __builtin_isnan(x); }\n",
"int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
"int c(double x) { return __builtin_isnan(x, x); }\n",
);
let messages = run(&opts, source).messages;
assert_eq!(
messages,
[
"/main.c:1:23: error: non-floating-point argument in call to function \
'__builtin_isnan' [E0685]",
"/main.c:2:30: error: non-floating-point arguments in call to function \
'__builtin_isunordered' [E0685]",
"/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
]
);
}
#[test]
fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
let text = ir(concat!(
"double a = __builtin_inf();\n",
"float b = __builtin_huge_valf();\n",
"long double c = __builtin_infl();\n",
"double d = __builtin_huge_val();\n",
));
assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
assert!(!text.contains("call"), "{text}");
}
#[test]
fn a_nan_is_written_with_the_payload_the_program_asked_for() {
let text = ir(concat!(
"double a = __builtin_nan(\"\");\n",
"double b = __builtin_nan(\"0x1\");\n",
"double c = __builtin_nan(\"010\");\n",
"double d = __builtin_nans(\"\");\n",
"double e = __builtin_nans(\"0x1\");\n",
"float f = __builtin_nanf(\"0x1\");\n",
"float g = __builtin_nansf(\"\");\n",
"long double h = __builtin_nansl(\"\");\n",
));
assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
let text = ir(concat!(
"double f(const char *p) { return __builtin_nan(p); }\n",
"double g(void) { return __builtin_nans(\"1x\"); }\n",
));
assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
}
#[test]
fn the_length_and_the_order_of_a_string_literal_are_known_here() {
let text = ir(concat!(
"unsigned long a = __builtin_strlen(\"hello\");\n",
"unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
"int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
"int d = __builtin_strcmp(\"abc\", \"abc\");\n",
"int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
));
assert!(text.contains("global @a : i64 = 5,"), "{text}");
assert!(text.contains("global @b : i64 = 1,"), "{text}");
assert!(text.contains("global @c : i32 = 1,"), "{text}");
assert!(text.contains("global @d : i32 = 0,"), "{text}");
assert!(text.contains("global @e : i32 = 1,"), "{text}");
assert!(!text.contains("call"), "{text}");
let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
assert!(text.contains("call @strlen("), "{text}");
}
#[test]
fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
let text = body("double f(double x) { return __builtin_fabs(x); }\n");
assert!(text.contains("bitcast.i64 %0"), "{text}");
assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
assert!(text.contains("and %1, %2"), "{text}");
assert!(text.contains("bitcast.f64 %3"), "{text}");
assert!(!text.contains("call"), "{text}");
let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
assert!(text.contains("%8 = or %4, %7"), "{text}");
assert!(!text.contains("call"), "{text}");
let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
assert!(text.contains("bitcast.i80 %0"), "{text}");
assert!(text.contains("bitcast.f80"), "{text}");
let text = body("double f(float x) { return __builtin_fabs(x); }\n");
assert!(text.contains("fpext.f64 %0"), "{text}");
assert!(text.contains("bitcast.i64 %1"), "{text}");
}
#[test]
fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
let text = ir(concat!(
"double a = __builtin_fabs(-3.5);\n",
"double b = __builtin_copysign(1.0, -0.0);\n",
"double c = __builtin_copysign(0.0, -2.0);\n",
"double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
"double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
"float g = __builtin_copysignf(-0.0f, 2.0f);\n",
"long double h = __builtin_copysignl(1.0L, -1.0L);\n",
"long double i = __builtin_fabsl(-__builtin_infl());\n",
));
assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
}
#[test]
fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
let text = ir(concat!(
"constexpr int side = 4;\n",
"constexpr int wider = side + 1;\n",
"constexpr double half = 1.5;\n",
"struct point { int x; int y; };\n",
"constexpr struct point origin = { 5, 6 };\n",
"int square[side * side];\n",
"int rectangle[wider];\n",
"int rounded[(int)half * 2];\n",
"int across[origin.y];\n",
"enum named { four = side };\n",
"int e = four;\n",
));
assert!(text.contains("global @square : bytes 64 ="), "{text}");
assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
assert!(text.contains("global @across : bytes 24 ="), "{text}");
assert!(text.contains("global @e : i32 = 4,"), "{text}");
let mut opts = options();
opts.emit = EmitKind::Ir;
let konst = "const int n = 1;\nint a[n];\n";
let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
assert_eq!(run(&opts, konst).messages, [message]);
let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
assert_eq!(run(&opts, subscript).messages, [message]);
let address = "constexpr int c = 3;\nint *p = &c;\n";
let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
pointer target type [E0514]";
assert_eq!(run(&opts, address).messages, [warning]);
}
#[test]
fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
let mut opts = options();
opts.std = Std::C17;
let source = concat!(
"int add(a, b)\n",
"int a;\n",
"int b;\n",
"{ return a + b; }\n",
"int promoted(c)\n",
"char c;\n",
"{ return c; }\n",
"int narrow(char);\n",
"int narrow(c)\n",
"char c;\n",
"{ return c; }\n",
"int first(a)\n",
"int a[4];\n",
"{ return a[0]; }\n",
);
let result = run(&opts, source);
assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
let text = result.text;
assert!(text.contains("add : int(int, int) function external defined"), "{text}");
assert!(text.contains("promoted : int(int) function external defined"), "{text}");
assert!(text.contains("c : char object automatic defined"), "{text}");
assert!(text.contains("narrow : int(char) function external defined"), "{text}");
assert!(text.contains("first : int(int *) function external defined"), "{text}");
}
#[test]
fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
let mut opts = options();
opts.std = Std::C17;
for (source, message) in [
("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
(
"int f(a)\nint a;\nint b;\n{ return a; }\n",
"3:5: error: declaration for parameter 'b' but no such parameter",
),
("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
(
"int f(a)\nstatic int a;\n{ return a; }\n",
"2:12: error: storage class specified for parameter 'a'",
),
(
"int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
"2:7: error: argument 'a' doesn't match prototype",
),
] {
let result = run(&opts, source);
assert!(result.failed(), "expected this to fail:\n{source}");
assert!(result.messages[0].contains(message), "{:?}", result.messages);
}
let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
let mut older = options();
older.std = Std::C89;
assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
let result = run(&opts, implicit);
assert!(
result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
"{:?}",
result.messages
);
let mut newer = options();
newer.std = Std::C23;
let plain = "int f(a)\nint a;\n{ return a; }\n";
let result = run(&newer, plain);
assert!(!result.failed(), "{:?}", result.messages);
assert_eq!(
result.messages,
["/main.c:1:5: warning: old-style function definition [E0412]"]
);
assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
}
#[test]
fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
let text = ir(concat!(
"struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
"struct brim { char buf[9223372036854775807L]; };\n",
"struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
"unsigned long h = sizeof(struct huge_struct);\n",
"unsigned long b = sizeof(struct brim);\n",
"unsigned long y = sizeof(struct bitty);\n",
));
assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
let mut opts = options();
opts.emit = EmitKind::Ir;
let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
assert_eq!(run(&opts, over).messages, [message]);
let array = "struct wide { short buf[1L << 62]; };\n";
let message = "/main.c:1:25: error: size of array 'buf' exceeds \
maximum object size '9223372036854775807' [E0537]";
assert_eq!(run(&opts, array).messages[0], message);
}
fn compile_bytes(source: &[u8]) -> Compiled {
let mut opts = options();
opts.emit = EmitKind::Ir;
let mut fs = MemoryFileSystem::new();
fs.insert("/main.c", source.to_vec());
compile(&opts, "/main.c", &fs)
}
#[test]
fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
let mut source = b"char s[] = \"a".to_vec();
source.push(0xff);
source.extend_from_slice(b"b\";\nchar c = '");
source.push(0xff);
source.extend_from_slice(b"';\n");
let result = compile_bytes(&source);
assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
assert!(result.text.contains(r#"bytes "a\ffb\00""#), "{}", result.text);
assert!(result.text.contains("global @c : i8 = -1,"), "{}", result.text);
let mut stray = b"int a".to_vec();
stray.push(0xff);
stray.extend_from_slice(b" = 1;\n");
let result = compile_bytes(&stray);
assert!(
result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
"{:?}",
result.messages
);
}
#[test]
fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
let expected = "\
func @add(i32, i32) -> i32, linkage(external) {
block0(%0: i32, %1: i32):
%2 = add.nsw %0, %1
return %2
}
";
assert!(text.contains(expected), "{text}");
}
#[test]
fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
assert!(!text.contains("alloca"), "{text}");
assert!(!text.contains("load"), "{text}");
assert!(!text.contains("store"), "{text}");
}
#[test]
fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
let expected = "\
block0:
%0 = alloca, size 4, align 4
%1 = iconst.i32 1
store %1 -> %0, align 4
%2 = call @g(%0) : (ptr) -> i32
return %2
";
assert_eq!(text, expected);
}
#[test]
fn a_loop_carries_what_it_changes_as_block_parameters() {
let text = body(
"int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
return total;\n}\n",
);
assert!(!text.contains("alloca"), "{text}");
assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
assert!(text.contains("jump block1("), "{text}");
}
#[test]
fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
assert!(text.contains("icmp slt %0, %1"), "{text}");
assert!(!text.contains("zext"), "{text}");
}
#[test]
fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
let text = body("int f(int a, int b) { return a && b; }\n");
let expected = "\
block0(%0: i32, %1: i32):
%2 = iconst.i32 0
%3 = icmp ne %0, %2
%4 = iconst.i1 0
br_if %3, block1, block2(%4)
block1:
%5 = iconst.i32 0
%6 = icmp ne %1, %5
jump block2(%6)
block2(%7: i1):
%8 = zext.i32 %7
return %8
";
assert_eq!(text, expected);
}
#[test]
fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
assert!(!text.contains("block3"), "{text}");
assert!(!text.contains("iconst.i32 3"), "{text}");
}
#[test]
fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
assert!(body("int f(void) { }\n").contains("unreachable"));
}
#[test]
fn a_structure_is_copied_rather_than_held_in_a_value() {
let text = body(
"struct point { int x, y; };\n\
int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
);
assert!(text.contains("memcpy"), "{text}");
}
#[test]
fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
assert!(text.contains("memset"), "{text}");
}
#[test]
fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
let text = body(
"int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
default: r = 4; } return r; }\n",
);
let expected = "\
block0(%0: i32):
%1 = iconst.i32 0
switch %0, block1, [1 => block2, 2 => block3(%1)]
block1:
%2 = iconst.i32 4
jump block4(%2)
block2:
%3 = iconst.i32 1
jump block3(%3)
block3(%4: i32):
%5 = iconst.i32 2
%6 = add.nsw %4, %5
jump block4(%6)
block4(%7: i32):
return %7
";
assert_eq!(text, expected);
}
#[test]
fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
assert!(text.contains("%2 = sub %0, %1"), "{text}");
assert!(text.contains("icmp ule"), "{text}");
assert!(!text.contains("switch"), "{text}");
}
#[test]
fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
let text = body(
"int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
);
assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
assert!(text.contains("block5:\n jump block7("), "{text}");
assert!(text.contains("block6:\n jump block8("), "{text}");
}
#[test]
fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
}
#[test]
fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
let text = body(
"int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
return n; }\n",
);
assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
assert!(text.contains("block5:\n jump block3("), "{text}");
}
#[test]
fn a_goto_into_a_loop_body_enters_it_without_the_test() {
let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
assert!(text.contains("br_if %7, block3, block4"), "{text}");
}
#[test]
fn a_goto_is_a_jump_to_the_block_the_label_starts() {
let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
assert!(!text.contains("alloca"), "{text}");
assert!(text.contains("block3(%4: i32):\n return %4"), "{text}");
assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
}
#[test]
fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
let text =
body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
assert!(!text.contains("alloca"), "{text}");
assert!(text.contains("block1(%2: i32):"), "{text}");
assert!(text.contains("jump block1(%5)"), "{text}");
}
#[test]
fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
assert_eq!(
body("int f(int x) { return x; spare: return 0; }\n"),
"block0(%0: i32):\n return %0\n"
);
}
#[test]
fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
let text = body(
"struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
);
assert_eq!(
text,
"\
block0(%0: ptr):
%1 = load.i8 %0, align 1
%2 = iconst.i8 3
%3 = ashr %1, %2
%4 = sext.i32 %3
return %4
"
);
}
#[test]
fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
let text =
body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
assert_eq!(
text,
"\
block0(%0: ptr, %1: i32):
%2 = iconst.i32 16777215
%3 = and %1, %2
%4 = trunc.i16 %3
store %4 -> %0, align 2
%5 = iconst.i32 16
%6 = lshr %3, %5
%7 = trunc.i8 %6
%8 = iconst.i64 2
%9 = ptr_add %0, %8
store %7 -> %9, align 1
return
"
);
}
#[test]
fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
let text =
body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
}
#[test]
fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
assert_eq!(text.matches("ashr").count(), 0, "{text}");
assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
}
#[test]
fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
let text = body(
"struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
);
assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
}
#[test]
fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
assert!(
text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
"{text}"
);
}
#[test]
fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
let text = ir(concat!(
"struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
"struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
"struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
"char s[2] = \"hi\";\n",
));
assert!(
text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
"{text}"
);
assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
}
#[test]
fn a_definition_takes_a_parameter_it_left_unnamed() {
let text = ir("int f(int a, int) { return a; }\n");
assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
let text = ir("int g(int, int n) { return n; }\n");
assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
}
#[test]
fn an_assignment_of_a_structure_is_the_object_it_wrote() {
let text = body(concat!(
"struct s { int f; int g; };\n",
"void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
"{ *d = *e = a[0] = *c; }\n",
));
assert_eq!(text.matches("memcpy").count(), 3, "{text}");
assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
}
#[test]
fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
let mut opts = options();
opts.emit = EmitKind::Ir;
let result = run(
&opts,
concat!(
"const char a[2][3] = { \"1234\", \"xyz\" };\n",
"static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
"union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
"const union u c = { { \"1234\", \"567\" } };\n",
),
);
let text = result.text;
assert_eq!(
result.messages,
["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
(5 chars into 3 available) [E0637]"]
);
assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
assert!(
text.contains(
"global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
bytes \"9\\00\", zero 3 }"
),
"{text}"
);
assert!(
text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
"{text}"
);
}
#[test]
fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
let text = body(concat!(
"struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
"void g(struct v *);\n",
"void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
));
assert_eq!(text.matches("memcpy").count(), 1, "{text}");
}
#[test]
fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
let text = ir(concat!(
"struct s { int x; };\n",
"struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
"int n = (int){ 7 };\n",
"struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
));
assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
assert!(text.contains("global @n : i32 = 7,"), "{text}");
assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
}
#[test]
fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
}
#[test]
fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
let text = ir("unsigned char foo[1][0];\n");
assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
}
#[test]
fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
}
#[test]
fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
assert!(
text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
"{text}"
);
}
#[test]
fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
let text = body(
"\
struct s { int a, b; };
struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
",
);
assert!(text.contains("block3(%7: ptr)"), "{text}");
assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
}
#[test]
fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
let text = ir("\
struct pair { int a, b; };
struct pair make(int a, int b);
struct pair twice(struct pair p) { return make(p.a, p.b); }
");
assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
assert!(text.contains("func @twice(i64) -> i64"), "{text}");
}
#[test]
fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
let text = ir("\
struct big { double v[8]; };
struct big grow(struct big b);
struct big twice(struct big b) { return grow(grow(b)); }
");
assert!(
text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
"{text}"
);
assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
assert_eq!(text.matches("call @grow").count(), 2, "{text}");
}
#[test]
fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
let text = ir("\
struct big { double v[8]; };
struct pair { int a, b; };
int p(const char *, ...);
int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
");
assert!(
text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
"{text}"
);
}
#[test]
fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
let body = body(
"\
struct pair { int a, b; };
struct pair make(int a, int b);
int second(void) { return make(1, 2).b; }
",
);
assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
}
#[test]
fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
let source = "\
struct hfa { float x, y, z; };
int take(struct hfa h);
int give(struct hfa h) { return take(h); }
";
assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
let mut opts = options();
opts.emit = EmitKind::Ir;
opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
let result = run(&opts, source);
assert_eq!(result.messages, Vec::<String>::new());
assert!(result.text.contains("func @take(f32, f32, f32) -> i32"), "{}", result.text);
}
#[test]
fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
let source = "\
int use(int *);
void f(int n) {
{
int a[n];
use(a);
}
use(0);
}
";
let body = body(source);
assert!(body.contains("mul.nsw"), "{body}");
assert!(body.contains("stacksave"), "{body}");
assert!(body.contains("alloca %"), "{body}");
assert!(body.contains("stackrestore"), "{body}");
}
#[test]
fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
let source = "\
int use(int *);
int f(int n) {
{
int a[n];
if (use(a)) goto out;
use(0);
}
out:
return 0;
}
";
let body = body(source);
assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
assert!(after.starts_with(" %4\n jump block"), "{body}");
}
#[test]
fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
let source = "\
int use(int *);
int f(int n) {
int a[n];
again:
if (use(a)) goto again;
return 0;
}
";
let body = body(source);
assert!(body.contains("stacksave"), "{body}");
assert!(!body.contains("stackrestore"), "{body}");
}
#[test]
fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
let source = "\
int use(int *);
int f(int n) {
again:
{
int a[n];
if (use(a)) goto again;
}
return 0;
}
";
let body = body(source);
assert_eq!(body.matches("stacksave").count(), 1, "{body}");
let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
}
#[test]
fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
let source = "\
int f(void);
void t(void) {
int count = 10;
for (; count--;) {
int b[f()];
int i;
for (i = 0; i < f(); i++) {
b[i] = count;
}
}
}
";
let body = body(source);
assert_eq!(body.matches("stacksave").count(), 1, "{body}");
let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
let (next, _) = after.split_once("\n\n").expect("a block after the restore");
assert!(next.contains("jump block1("), "{body}");
}
#[test]
fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
let source = "\
unsigned long f(int n) {
int a[n];
n = 0;
return sizeof a;
}
";
let body = body(source);
assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
}
#[test]
fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
let source = "\
int use(int);
int f(int x) {
return ({
int t = use(x);
t * t;
});
}
";
let expected = "\
block0(%0: i32):
%1 = call @use(%0) : (i32) -> i32
%2 = mul.nsw %1, %1
return %2
";
assert_eq!(body(source), expected);
}
#[test]
fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
let source = "int f(int x) { return ({ return x; 0; }); }\n";
assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
}
#[test]
fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
let expected = "\
block0(%0: ptr):
%1 = va_arg.f64 %0
%2 = va_arg.f64 %0
%3 = fadd %1, %2
return %3
";
assert_eq!(body(source), expected);
}
#[test]
fn one_that_reads_a_structure_answers_where_the_object_is() {
let source = "\
struct s { int a; long b; };
long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
";
let expected = "\
block0(%0: ptr):
%1 = alloca, size 16, align 8
%2 = va_object %0, size 16, align 8
memcpy %1, %2, size 16, align 8
%3 = iconst.i64 8
%4 = ptr_add %1, %3
%5 = load.i64 %4, align 8
return %5
";
assert_eq!(body(source), expected);
}
#[test]
fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
let source = "\
int f(int c) {
void *p = c ? &&one : &&two;
goto *p;
one:
return 1;
two:
return 2;
}
";
let expected = "\
block0(%0: i32):
%1 = iconst.i32 0
%2 = icmp ne %0, %1
br_if %2, block1, block2
block1:
%3 = block_addr block3
jump block4(%3)
block2:
%4 = block_addr block5
jump block4(%4)
block3:
%5 = iconst.i32 1
return %5
block4(%6: ptr):
indirect_br %6, block3, block5
block5:
%7 = iconst.i32 2
return %7
";
assert_eq!(body(source), expected);
}
#[test]
fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
let source = "void **next(void);
void f(void) { goto *next(); }
";
let expected = "\
block0:
%0 = call @next() : () -> ptr
unreachable
";
assert_eq!(body(source), expected);
}
#[test]
fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
let expected = "\
block0:
inline_asm.volatile \"mfence\", \"\", \"memory\"()
return
";
assert_eq!(body(source), expected);
}
#[test]
fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
let source = "\
int f(int x, int y) {
int r;
__asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
return r + y;
}
";
let expected = "\
block0(%0: i32, %1: i32):
%2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
%4 = add.nsw %2, %3
return %4
";
assert_eq!(body(source), expected);
}
#[test]
fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
let source = "\
struct pair { int a, b; };
int f(int x) {
int slot = x;
struct pair p = { x, x };
__asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
return slot + p.a;
}
";
let text = body(source);
assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
}
#[test]
fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
let source = "\
int f(int x) {
int r = 7;
__asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
return r;
away:
return r;
}
";
let expected = "\
block0(%0: i32):
%1 = iconst.i32 7
%2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
block1:
return %2
block2:
return %1
";
assert_eq!(body(source), expected);
}
#[test]
fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
let mut opts = options();
opts.emit = EmitKind::Ir;
for (source, expected) in [
(
"void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
"output operand constraint lacks '='",
),
(
"void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
"lvalue required in 'asm' statement",
),
(
"const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
"read-only variable 'g' used as 'asm' output",
),
(
"void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
"input operand constraint contains '='",
),
(
"void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
"memory input 0 is not directly addressable",
),
("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
(
"void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
"duplicate asm operand name 'a'",
),
("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
] {
let result = run(&opts, source);
assert!(result.failed(), "expected this to be reported:\n{source}");
assert!(
result.messages.iter().any(|m| m.contains(expected)),
"{expected}\n{:?}",
result.messages
);
}
}
#[test]
fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
let mut opts = options();
opts.emit = EmitKind::Ir;
for source in [
"int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
"int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
] {
let result = run(&opts, source);
assert!(result.failed(), "expected this to be reported:\n{source}");
assert!(
result.messages.iter().any(|m| m.contains("not supported yet")),
"{:?}",
result.messages
);
}
}
fn round_trip(source: &str) -> (String, String) {
let printed = ir(source);
let mut opts = options();
opts.emit = EmitKind::Ir;
let mut fs = MemoryFileSystem::new();
fs.insert("/main.ir", printed.clone().into_bytes());
let result = compile_ir(&opts, "/main.ir", &fs);
assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
(printed, result.text)
}
#[test]
fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
let (printed, again) = round_trip(
"struct point { int x, y; };\n static const char greeting[] = \"hi\";\n int puts(const char *);\n int f(int n) { struct point p = { n, 1 }; puts(greeting); return p.x; }\n",
);
assert_eq!(printed, again);
}
#[test]
fn ir_that_is_not_ir_says_which_line_stopped_it() {
let mut opts = options();
opts.emit = EmitKind::Ir;
let mut fs = MemoryFileSystem::new();
let text = "\
; ModuleID = 'a.c'
; format 0
target triple = \"x86_64-unknown-linux-gnu\"
target datalayout = \"e-p:64:64-i64:64-S128\"
func @f(), linkage(external) {
block0:
frobnicate
}
";
fs.insert("/main.ir", text.as_bytes().to_vec());
let result = compile_ir(&opts, "/main.ir", &fs);
assert!(result.failed());
assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
}
#[test]
fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
let mut opts = options();
opts.emit = EmitKind::Ir;
let mut fs = MemoryFileSystem::new();
let text = "\
; ModuleID = 'a.c'
; format 0
target triple = \"x86_64-unknown-linux-gnu\"
target datalayout = \"e-p:64:64-i64:64-S128\"
func @f(), linkage(external) {
block0:
%0 = iconst.i32 1
return %0
}
";
fs.insert("/main.ir", text.as_bytes().to_vec());
let result = compile_ir(&opts, "/main.ir", &fs);
assert!(result.failed());
assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
}
#[test]
fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
let mut fs = MemoryFileSystem::new();
fs.insert("/main.ir", Vec::new());
let result = compile_ir(&options(), "/main.ir", &fs);
assert!(result.failed());
assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
}
#[test]
fn the_printed_ir_reads_back_as_the_same_module() {
let text = ir("\
struct point { int x, y; };
static const char greeting[] = \"hi\";
int table[4] = { 1, 2, 3 };
int puts(const char *);
double half(double x) { return x / 2.0; }
int f(int n) {
int total = 0;
for (int i = 0; i < n; i++) {
if (i == 3) continue;
total += table[i];
}
switch (n) {
case 0: total = 1;
case 1: total++; break;
default: total = -total;
}
struct point p = { total, 1 };
int *q = &p.y;
puts(greeting);
return p.x + *q;
}
int dispatch(int c) {
void *p = c ? &&one : &&two;
goto *p;
one:
return 1;
two:
return 2;
}
int assembly(int x, int *p) {
int r;
__asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
__asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
return r;
away:
return 0;
}
");
let mut names = rucc_base::Interner::new();
let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
assert_eq!(rucc_ir::print(&module, &names), text);
}
}