blob: 8858320b154f98bce9ef5efdbc12f1b62fb94749 [file] [log] [blame]
Alex Crichton8e5f0cd2015-09-09 22:46:19 -07001extern crate gcc;
2extern crate syntex_syntax as syntax;
3
Alex Crichton310d6232015-09-10 10:56:31 -07004use std::collections::HashSet;
Alex Crichton8e5f0cd2015-09-09 22:46:19 -07005use std::env;
6use std::fs::File;
7use std::io::BufWriter;
8use std::io::prelude::*;
9use std::path::{Path, PathBuf};
10
Alex Crichton31504842015-09-10 23:43:41 -070011use syntax::abi::Abi;
Alex Crichton8e5f0cd2015-09-09 22:46:19 -070012use syntax::ast;
Alex Crichtona9adfbf2015-09-09 23:21:27 -070013use syntax::attr::{self, ReprAttr};
Alex Crichton31504842015-09-10 23:43:41 -070014use syntax::diagnostic::SpanHandler;
15use syntax::ext::base::SyntaxExtension;
16use syntax::ext::expand;
17use syntax::parse::token::{intern, InternedString};
Alex Crichton8e5f0cd2015-09-09 22:46:19 -070018use syntax::parse::{self, ParseSess};
19use syntax::visit::{self, Visitor};
20
Alex Crichton310d6232015-09-10 10:56:31 -070021macro_rules! t {
22 ($e:expr) => (match $e {
23 Ok(e) => e,
24 Err(e) => panic!("{} failed with {}", stringify!($e), e),
25 })
26}
27
Alex Crichtona9adfbf2015-09-09 23:21:27 -070028struct TestGenerator<'a> {
Alex Crichton310d6232015-09-10 10:56:31 -070029 target: String,
Alex Crichton8e5f0cd2015-09-09 22:46:19 -070030 rust: Box<Write>,
31 c: Box<Write>,
Alex Crichtona9adfbf2015-09-09 23:21:27 -070032 sh: &'a SpanHandler,
Alex Crichton310d6232015-09-10 10:56:31 -070033 structs: HashSet<String>,
Alex Crichton31504842015-09-10 23:43:41 -070034 abi: Abi,
Alex Crichton310d6232015-09-10 10:56:31 -070035}
36
37struct StructFinder {
38 structs: HashSet<String>,
39}
40
41impl<'a> TestGenerator<'a> {
Alex Crichton0df7c102015-09-10 16:35:37 -070042 fn defines(&self) -> Vec<&'static str> {
43 let mut ret = Vec::new();
Alex Crichton31504842015-09-10 23:43:41 -070044
45 // Pull in extra goodies on linux
Alex Crichton0df7c102015-09-10 16:35:37 -070046 if self.target.contains("unknown-linux") {
47 ret.push("_GNU_SOURCE");
48 }
Alex Crichton31504842015-09-10 23:43:41 -070049
50 // MSVC doesn't have stdalign.h so get alignof ourselves
Alex Crichtonac2bd852015-09-10 17:21:20 -070051 if self.target.contains("msvc") {
52 ret.push("alignof __alignof");
53 }
Alex Crichton31504842015-09-10 23:43:41 -070054
Alex Crichtond3d77922015-09-11 17:03:39 -070055 // android also doesn't have stdalign.h so get alignof ourselves
56 if self.target.contains("android") {
57 ret.push("alignof __alignof__");
58 }
59
Alex Crichton31504842015-09-10 23:43:41 -070060 // Pull in extra goodies on mingw
61 if self.target.contains("windows") {
62 ret.push("_WIN32_WINNT 0x8000");
63 }
Alex Crichton0df7c102015-09-10 16:35:37 -070064 return ret
65 }
66
Alex Crichton310d6232015-09-10 10:56:31 -070067 fn headers(&self) -> Vec<&'static str> {
Alex Crichtonac2bd852015-09-10 17:21:20 -070068 let mut base = Vec::new();
69
Alex Crichtonf81e3d32015-09-11 15:27:09 -070070 base.extend([
Alex Crichton0df7c102015-09-10 16:35:37 -070071 "errno.h",
72 "fcntl.h",
Alex Crichton0df7c102015-09-10 16:35:37 -070073 "limits.h",
Alex Crichton310d6232015-09-10 10:56:31 -070074 "stddef.h",
75 "stdint.h",
Alex Crichton0df7c102015-09-10 16:35:37 -070076 "stdio.h",
77 "stdlib.h",
Alex Crichton310d6232015-09-10 10:56:31 -070078 "sys/stat.h",
Alex Crichton310d6232015-09-10 10:56:31 -070079 "sys/types.h",
Alex Crichton310d6232015-09-10 10:56:31 -070080 "time.h",
Alex Crichton310d6232015-09-10 10:56:31 -070081 "wchar.h",
Alex Crichtonf81e3d32015-09-11 15:27:09 -070082 ].iter().cloned());
Alex Crichton310d6232015-09-10 10:56:31 -070083
84 if self.target.contains("apple-darwin") {
Alex Crichtone8606192015-09-10 20:19:44 -070085 base.push("mach-o/dyld.h");
Alex Crichton310d6232015-09-10 10:56:31 -070086 base.push("mach/mach_time.h");
87 }
Alex Crichtonac2bd852015-09-10 17:21:20 -070088
Alex Crichtond3d77922015-09-11 17:03:39 -070089 if self.target.contains("unknown-linux") ||
90 self.target.contains("android") {
Alex Crichton310d6232015-09-10 10:56:31 -070091 base.push("linux/if_packet.h");
92 base.push("net/ethernet.h");
93 }
94
Alex Crichtonac2bd852015-09-10 17:21:20 -070095 if self.target.contains("windows") {
Alex Crichton7da9b102015-09-10 20:57:14 -070096 base.push("winsock2.h"); // must be before windows.h
97
98 base.push("direct.h");
99 base.push("io.h");
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700100 base.push("sys/utime.h");
Alex Crichton7da9b102015-09-10 20:57:14 -0700101 base.push("windows.h");
102 base.push("process.h");
103 base.push("ws2ipdef.h");
Alex Crichton31504842015-09-10 23:43:41 -0700104
105 if self.target.contains("gnu") {
106 base.push("stdalign.h");
107 base.push("ws2tcpip.h");
108 }
Alex Crichtonac2bd852015-09-10 17:21:20 -0700109 } else {
Alex Crichton22378822015-09-10 19:59:23 -0700110 base.push("ctype.h");
111 base.push("dirent.h");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700112 base.push("net/if.h");
113 base.push("netdb.h");
114 base.push("netinet/in.h");
115 base.push("netinet/ip.h");
116 base.push("netinet/tcp.h");
117 base.push("pthread.h");
118 base.push("signal.h");
Alex Crichtone8606192015-09-10 20:19:44 -0700119 base.push("string.h");
Alex Crichton22378822015-09-10 19:59:23 -0700120 base.push("sys/file.h");
121 base.push("sys/ioctl.h");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700122 base.push("sys/mman.h");
123 base.push("sys/resource.h");
124 base.push("sys/socket.h");
125 base.push("sys/time.h");
126 base.push("sys/un.h");
Alex Crichton22378822015-09-10 19:59:23 -0700127 base.push("sys/wait.h");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700128 base.push("unistd.h");
Alex Crichton22378822015-09-10 19:59:23 -0700129 base.push("utime.h");
Alex Crichtond3d77922015-09-11 17:03:39 -0700130
131 if self.target.contains("android") {
132 base.push("arpa/inet.h");
133 } else {
134 base.push("glob.h");
135 base.push("ifaddrs.h");
136 base.push("stdalign.h");
137 base.push("sys/sysctl.h");
138 }
Alex Crichtonac2bd852015-09-10 17:21:20 -0700139 }
140
Alex Crichton310d6232015-09-10 10:56:31 -0700141 return base
142 }
143
144 fn rust2c(&self, ty: &str) -> String {
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700145 let windows = self.target.contains("windows");
Alex Crichton310d6232015-09-10 10:56:31 -0700146 match ty {
147 t if t.starts_with("c_") => {
148 match &ty[2..].replace("long", " long")[..] {
149 s if s.starts_with("u") => format!("unsigned {}", &s[1..]),
150 "short" => format!("short"),
151 s if s.starts_with("s") => format!("signed {}", &s[1..]),
152 s => s.to_string(),
153 }
154 }
Alex Crichton31504842015-09-10 23:43:41 -0700155
156 // Just pass all these through, no need for a "struct" prefix
Alex Crichton22378822015-09-10 19:59:23 -0700157 "glob_t" |
158 "FILE" |
159 "DIR" |
160 "fpos_t" => ty.to_string(),
Alex Crichton310d6232015-09-10 10:56:31 -0700161 t if t.starts_with("pthread") => t.to_string(),
162
Alex Crichton31504842015-09-10 23:43:41 -0700163 // Windows uppercase structs don't have `struct` in front, there's a
164 // few special cases for windows, and then otherwise put `struct` in
165 // front of everything.
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700166 t if self.structs.contains(t) => {
167 if windows && ty.chars().next().unwrap().is_uppercase() {
168 t.to_string()
169 } else if windows && t == "stat" {
170 "struct __stat64".to_string()
Alex Crichton7da9b102015-09-10 20:57:14 -0700171 } else if windows && t == "utimbuf" {
172 "struct __utimbuf64".to_string()
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700173 } else {
174 format!("struct {}", t)
175 }
176 }
Alex Crichton310d6232015-09-10 10:56:31 -0700177
Alex Crichton31504842015-09-10 23:43:41 -0700178 // Fixup a few types on windows that don't actually exist.
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700179 "time64_t" if windows => "__time64_t".to_string(),
180 "ssize_t" if windows => "SSIZE_T".to_string(),
Alex Crichton31504842015-09-10 23:43:41 -0700181
Alex Crichton310d6232015-09-10 10:56:31 -0700182 t => t.to_string(),
183 }
184 }
185
186 fn rust2cfield(&self, struct_: &str, field: &str) -> String {
187 match field {
Alex Crichton31504842015-09-10 23:43:41 -0700188 // Our stat *_nsec fields normally don't actually exist but are part
189 // of a timeval struct
Alex Crichton310d6232015-09-10 10:56:31 -0700190 s if s.ends_with("_nsec") && struct_ == "stat" => {
191 if self.target.contains("apple-darwin") {
192 s.replace("_nsec", "spec.tv_nsec")
Alex Crichtond3d77922015-09-11 17:03:39 -0700193 } else if self.target.contains("android") {
194 s.to_string()
Alex Crichton310d6232015-09-10 10:56:31 -0700195 } else {
196 s.replace("e_nsec", ".tv_nsec")
197 }
198 }
199 s => s.to_string(),
200 }
201 }
202
203 fn cfg_list(&self) -> Vec<(&'static str, Option<&'static str>)> {
204 let mut ret = Vec::new();
205 let (arch, target_pointer_width) = if self.target.starts_with("x86_64") {
206 ("x86_64", "64")
207 } else if self.target.starts_with("i686") {
208 ("x86", "32")
Alex Crichtond3d77922015-09-11 17:03:39 -0700209 } else if self.target.starts_with("arm") {
210 ("arm", "32")
Alex Crichton310d6232015-09-10 10:56:31 -0700211 } else {
212 panic!("unknown arch/pointer width: {}", self.target)
213 };
214 let (os, family, env) = if self.target.contains("unknown-linux") {
215 ("linux", "unix", "gnu")
216 } else if self.target.contains("apple-darwin") {
217 ("macos", "unix", "")
Alex Crichtonac2bd852015-09-10 17:21:20 -0700218 } else if self.target.contains("windows-msvc") {
219 ("windows", "windows", "msvc")
220 } else if self.target.contains("windows-gnu") {
221 ("windows", "windows", "gnu")
Alex Crichtond3d77922015-09-11 17:03:39 -0700222 } else if self.target.contains("android") {
223 ("android", "unix", "")
Alex Crichton310d6232015-09-10 10:56:31 -0700224 } else {
225 panic!("unknown os/family width: {}", self.target)
226 };
227
228 ret.push((family, None));
229 ret.push(("target_os", Some(os)));
230 ret.push(("target_family", Some(family)));
231 ret.push(("target_arch", Some(arch)));
232 // skip endianness
233 ret.push(("target_pointer_width", Some(target_pointer_width)));
234 ret.push(("target_env", Some(env)));
235
236 return ret
237 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700238}
239
240fn main() {
Alex Crichton310d6232015-09-10 10:56:31 -0700241 // Prep the test generator
242 let target = t!(env::var("TARGET"));
243 let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
244 let rust_out = BufWriter::new(t!(File::create(out.join("all.rs"))));
245 let c_out = BufWriter::new(t!(File::create(out.join("all.c"))));
Alex Crichton16083062015-09-09 22:59:24 -0700246 let sess = ParseSess::new();
Alex Crichton310d6232015-09-10 10:56:31 -0700247 let mut tg = TestGenerator {
248 target: target,
249 rust: Box::new(rust_out),
250 c: Box::new(c_out),
251 sh: &sess.span_diagnostic,
252 structs: HashSet::new(),
Alex Crichton31504842015-09-10 23:43:41 -0700253 abi: Abi::C,
Alex Crichton310d6232015-09-10 10:56:31 -0700254 };
255
256 // Parse the libc crate
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700257 let src = Path::new("../src/lib.rs");
258 let cfg = Vec::new();
Alex Crichton31504842015-09-10 23:43:41 -0700259 let krate = parse::parse_crate_from_file(src, cfg, &sess);
260
261 // expand macros
262 let ecfg = expand::ExpansionConfig::default("libc".to_string());
263 let exts = vec![
264 (intern("macro_rules"), SyntaxExtension::MacroRulesTT),
265 ];
266 let mut krate = expand::expand_crate(&sess, ecfg, Vec::new(),
267 exts, &mut Vec::new(), krate);
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700268
Alex Crichton310d6232015-09-10 10:56:31 -0700269 // Strip the crate down to just what's configured for our target
270 for (k, v) in tg.cfg_list() {
271 let s = InternedString::new;
272 krate.config.push(match v {
273 Some(v) => attr::mk_name_value_item_str(s(k), s(v)),
274 None => attr::mk_word_item(s(k)),
275 });
276 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700277 let mut gated_cfgs = Vec::new();
278 let krate = syntax::config::strip_unconfigured_items(&sess.span_diagnostic,
279 krate,
280 &mut gated_cfgs);
281
Alex Crichton310d6232015-09-10 10:56:31 -0700282 // Probe the crate to find all structs (used to convert type names to names
283 // in C).
284 let mut structs = StructFinder {
285 structs: HashSet::new(),
286 };
287 visit::walk_crate(&mut structs, &krate);
288 tg.structs = structs.structs;
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700289
Alex Crichton0df7c102015-09-10 16:35:37 -0700290 // Prep the C file by emitting header stuff
291 for define in tg.defines() {
292 t!(writeln!(tg.c, "#define {}", define));
293 }
Alex Crichton310d6232015-09-10 10:56:31 -0700294 for header in tg.headers() {
295 t!(writeln!(tg.c, "#include <{}>", header));
Alex Crichton16083062015-09-09 22:59:24 -0700296 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700297
298 // Walk the crate, emitting test cases for everything found
Alex Crichton310d6232015-09-10 10:56:31 -0700299 visit::walk_crate(&mut tg, &krate);
Alex Crichton16083062015-09-09 22:59:24 -0700300
Alex Crichton310d6232015-09-10 10:56:31 -0700301 // Compile our C shim to be linked into tests
Alex Crichtonac2bd852015-09-10 17:21:20 -0700302 let mut cfg = gcc::Config::new();
303 cfg.file(out.join("all.c"));
304
305 if tg.target.contains("msvc") {
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700306 cfg.flag("/W3").flag("/Wall").flag("/WX")
307 .flag("/wd4820") // weird warning about adding padding?
Alex Crichton7da9b102015-09-10 20:57:14 -0700308 .flag("/wd4100") // don't warn about unused parameters
309 .flag("/wd4996"); // don't warn about deprecated functions
Alex Crichtonac2bd852015-09-10 17:21:20 -0700310 } else {
Alex Crichtonb01a8cc2015-09-10 17:37:22 -0700311 cfg.flag("-Wall").flag("-Wextra").flag("-Werror")
Alex Crichton5f624a52015-09-10 17:39:21 -0700312 .flag("-Wno-unused-parameter");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700313 }
314
315 drop(tg);
316 cfg.compile("liball.a");
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700317}
318
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700319impl<'a> TestGenerator<'a> {
320 fn test_type(&mut self, ty: &str) {
Alex Crichton310d6232015-09-10 10:56:31 -0700321 match ty {
Alex Crichtond3d77922015-09-11 17:03:39 -0700322 // sighandler_t is crazy across platforms
Alex Crichton310d6232015-09-10 10:56:31 -0700323 "sighandler_t" => return,
Alex Crichtond3d77922015-09-11 17:03:39 -0700324
325 // Not actually defined on android, but it's not hurting anyone
326 "in_port_t" if self.target.contains("android") => return,
Alex Crichton310d6232015-09-10 10:56:31 -0700327 _ => {}
328 }
Alex Crichton22378822015-09-10 19:59:23 -0700329 let c = self.rust_ty_to_c_ty(ty);
Alex Crichton310d6232015-09-10 10:56:31 -0700330 self.test_size_align(ty, &c);
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700331 }
Alex Crichton16083062015-09-09 22:59:24 -0700332
Alex Crichton3e5155b2015-09-09 23:46:19 -0700333 fn test_struct(&mut self, ty: &str, s: &ast::StructDef) {
Alex Crichton22378822015-09-10 19:59:23 -0700334 let cty = self.rust_ty_to_c_ty(ty);
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700335 self.test_size_align(ty, &cty);
Alex Crichton3e5155b2015-09-09 23:46:19 -0700336
Alex Crichton310d6232015-09-10 10:56:31 -0700337 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700338 #[test]
339 fn field_offset_size_{ty}() {{
Alex Crichton310d6232015-09-10 10:56:31 -0700340 "#, ty = ty));
Alex Crichton3e5155b2015-09-09 23:46:19 -0700341 for field in s.fields.iter() {
342 let name = match field.node.kind {
343 ast::NamedField(name, ast::Public) => name,
344 ast::NamedField(_, ast::Inherited) => continue,
345 ast::UnnamedField(..) => panic!("no tuple structs in FFI"),
346 };
347
Alex Crichton310d6232015-09-10 10:56:31 -0700348 let cfield = self.rust2cfield(ty, &name.to_string());
Alex Crichton3e5155b2015-09-09 23:46:19 -0700349
Alex Crichton310d6232015-09-10 10:56:31 -0700350 t!(writeln!(self.c, r#"
Alex Crichton671376b2015-09-10 17:39:03 -0700351 uint64_t __test_offset_{ty}_{rust_field}(void) {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700352 return offsetof({cty}, {c_field});
353 }}
Alex Crichton671376b2015-09-10 17:39:03 -0700354 uint64_t __test_size_{ty}_{rust_field}(void) {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700355 {cty}* foo = NULL;
356 return sizeof(foo->{c_field});
357 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700358 "#, ty = ty, cty = cty, rust_field = name, c_field = cfield));
359 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700360 extern {{
361 fn __test_offset_{ty}_{field}() -> u64;
362 fn __test_size_{ty}_{field}() -> u64;
363 }}
364 unsafe {{
365 let foo = 0 as *const {ty};
366 same(offset_of!({ty}, {field}),
367 __test_offset_{ty}_{field}(),
368 "field offset {field} of {ty}");
369 same(mem::size_of_val(&(*foo).{field}) as u64,
370 __test_size_{ty}_{field}(),
371 "field size {field} of {ty}");
372 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700373 "#, ty = ty, field = name));
Alex Crichton3e5155b2015-09-09 23:46:19 -0700374 }
Alex Crichton310d6232015-09-10 10:56:31 -0700375 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700376 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700377 "#));
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700378 }
379
380 fn test_size_align(&mut self, rust: &str, c: &str) {
Alex Crichton310d6232015-09-10 10:56:31 -0700381 t!(writeln!(self.c, r#"
Alex Crichton671376b2015-09-10 17:39:03 -0700382 uint64_t __test_size_{ty}(void) {{ return sizeof({cty}); }}
383 uint64_t __test_align_{ty}(void) {{ return alignof({cty}); }}
Alex Crichton310d6232015-09-10 10:56:31 -0700384 "#, ty = rust, cty = c));
385 t!(writeln!(self.rust, r#"
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700386 #[test]
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700387 fn size_align_{ty}() {{
Alex Crichton16083062015-09-09 22:59:24 -0700388 extern {{
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700389 fn __test_size_{ty}() -> u64;
390 fn __test_align_{ty}() -> u64;
Alex Crichton16083062015-09-09 22:59:24 -0700391 }}
392 unsafe {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700393 same(mem::size_of::<{ty}>() as u64,
394 __test_size_{ty}(), "size");
Alex Crichtonc8b895c2015-09-10 13:24:15 -0700395 same(align::<{ty}>() as u64,
Alex Crichton3e5155b2015-09-09 23:46:19 -0700396 __test_align_{ty}(), "align");
Alex Crichton16083062015-09-09 22:59:24 -0700397 }}
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700398 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700399 "#, ty = rust));
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700400 }
401
Alex Crichton22378822015-09-10 19:59:23 -0700402 fn rust_ty_to_c_ty(&self, mut rust_ty: &str) -> String {
403 let mut cty = self.rust2c(&rust_ty.replace("*mut ", "")
404 .replace("*const ", ""));
405 while rust_ty.starts_with("*") {
406 if rust_ty.starts_with("*const") {
407 cty = format!("const {}*", cty);
408 rust_ty = &rust_ty[7..];
409 } else {
410 cty = format!("{}*", cty);
411 rust_ty = &rust_ty[5..];
412 }
413 }
414 return cty
415 }
416
Alex Crichton0df7c102015-09-10 16:35:37 -0700417 fn test_const(&mut self, name: &str, rust_ty: &str) {
Alex Crichton31504842015-09-10 23:43:41 -0700418 let mingw = self.target.contains("windows-gnu");
419
420 // Apparently these don't exist in mingw headers?
421 match name {
422 "MEM_RESET_UNDO" |
423 "FILE_ATTRIBUTE_NO_SCRUB_DATA" |
424 "FILE_ATTRIBUTE_INTEGRITY_STREAM" |
425 "ERROR_NOTHING_TO_TERMINATE" if mingw => return,
426 _ => {}
427 }
428
Alex Crichton22378822015-09-10 19:59:23 -0700429 let cty = self.rust_ty_to_c_ty(rust_ty);
Alex Crichton31504842015-09-10 23:43:41 -0700430
431 // SIG_IGN has weird types on platforms, just worry about it as a size_t
Alex Crichton0df7c102015-09-10 16:35:37 -0700432 let cast = if name == "SIG_IGN" {"(size_t)"} else {""};
Alex Crichton31504842015-09-10 23:43:41 -0700433
Alex Crichton0df7c102015-09-10 16:35:37 -0700434 t!(writeln!(self.c, r#"
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700435 int __test_const_{name}({cty} *outptr) {{
436 *outptr = {cast}({name});
437 return 1;
Alex Crichtone7afdd82015-09-10 17:15:20 -0700438 }}
Alex Crichton0df7c102015-09-10 16:35:37 -0700439 "#, name = name, cast = cast, cty = cty));
440 t!(writeln!(self.rust, r#"
441 #[test]
442 fn const_{name}() {{
443 extern {{
Alex Crichtone7afdd82015-09-10 17:15:20 -0700444 fn __test_const_{name}(out: *mut {ty}) -> c_int;
Alex Crichton0df7c102015-09-10 16:35:37 -0700445 }}
446 unsafe {{
Alex Crichtone7afdd82015-09-10 17:15:20 -0700447 let mut o = mem::zeroed();
448 if __test_const_{name}(&mut o) == 0 {{
449 panic!("not defined");
450 }} else {{
451 same({name}, o, "value");
452 }}
Alex Crichton0df7c102015-09-10 16:35:37 -0700453 }}
454 }}
455 "#, ty = rust_ty, name = name));
456 }
457
Alex Crichton7da9b102015-09-10 20:57:14 -0700458 fn test_extern_fn(&mut self, name: &str, cname: &str,
459 args: &[String], ret: &str,
Alex Crichton31504842015-09-10 23:43:41 -0700460 variadic: bool, abi: Abi) {
Alex Crichton22378822015-09-10 19:59:23 -0700461 match name {
462 // manually verified
463 "execv" |
464 "execve" |
465 "execvp" |
Alex Crichton7da9b102015-09-10 20:57:14 -0700466 "execvpe" |
Alex Crichton22378822015-09-10 19:59:23 -0700467 "glob" |
468 "getrlimit" |
469 "setrlimit" |
Alex Crichtone8606192015-09-10 20:19:44 -0700470 "signal" |
Alex Crichton22378822015-09-10 19:59:23 -0700471 "getopt" => return,
472 _ => {}
473 }
474 let args = if args.len() == 0 && !variadic {
475 "void".to_string()
476 } else {
477 args.iter().map(|a| self.rust_ty_to_c_ty(a)).collect::<Vec<_>>()
478 .connect(", ") + if variadic {", ..."} else {""}
479 };
480 let cret = self.rust_ty_to_c_ty(ret);
Alex Crichton31504842015-09-10 23:43:41 -0700481 let abi = match abi {
482 Abi::C => "",
483 Abi::Stdcall => "__stdcall ",
484 Abi::System if self.target.contains("i686-pc-windows") => {
485 "__stdcall "
486 }
487 Abi::System => "",
488 a => panic!("unknown ABI: {}", a),
489 };
Alex Crichton22378822015-09-10 19:59:23 -0700490 t!(writeln!(self.c, r#"
Alex Crichton31504842015-09-10 23:43:41 -0700491 {ret} ({abi}*__test_fn_{name}(void))({args}) {{
Alex Crichton7da9b102015-09-10 20:57:14 -0700492 return {cname};
Alex Crichton22378822015-09-10 19:59:23 -0700493 }}
Alex Crichton31504842015-09-10 23:43:41 -0700494 "#, name = name, cname = cname, args = args, ret = cret, abi = abi));
Alex Crichton22378822015-09-10 19:59:23 -0700495 t!(writeln!(self.rust, r#"
496 #[test]
Alex Crichton7da9b102015-09-10 20:57:14 -0700497 #[cfg_attr(windows, ignore)] // FIXME -- dllimport weirdness?
Alex Crichton22378822015-09-10 19:59:23 -0700498 fn fn_{name}() {{
499 extern {{
500 fn __test_fn_{name}() -> size_t;
501 }}
502 unsafe {{
503 same({name} as usize,
504 __test_fn_{name}() as usize, "function pointer");
505 }}
506 }}
507 "#, name = name));
508 }
509
510 fn assert_no_generics(&self, _i: ast::Ident, generics: &ast::Generics) {
511 assert!(generics.lifetimes.len() == 0);
512 assert!(generics.ty_params.len() == 0);
513 assert!(generics.where_clause.predicates.len() == 0);
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700514 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700515
516 fn ty2name(&self, ty: &ast::Ty) -> String {
517 match ty.node {
518 ast::TyPath(_, ref path) => {
519 path.segments.last().unwrap().identifier.to_string()
520 }
521 ast::TyPtr(ref t) => {
522 format!("*{} {}", match t.mutbl {
523 ast::MutImmutable => "const",
524 ast::MutMutable => "mut",
525 }, self.ty2name(&t.ty))
526 }
Alex Crichton22378822015-09-10 19:59:23 -0700527 ast::TyBareFn(ref t) => {
528 assert!(t.lifetimes.len() == 0);
529 let (ret, mut args, variadic) = self.decl2rust(&t.decl);
530 assert!(!variadic);
531 if args.len() == 0 {
532 args.push("void".to_string());
533 }
534 format!("{}(*)({})", ret, args.connect(", "))
535 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700536 _ => panic!("unknown ty {:?}", ty),
537 }
538 }
Alex Crichton22378822015-09-10 19:59:23 -0700539
540 fn decl2rust(&self, decl: &ast::FnDecl) -> (String, Vec<String>, bool) {
541 let args = decl.inputs.iter().map(|arg| {
542 self.ty2name(&arg.ty)
543 }).collect::<Vec<_>>();
544 let ret = match decl.output {
545 ast::NoReturn(..) |
546 ast::DefaultReturn(..) => "void".to_string(),
547 ast::Return(ref t) => self.ty2name(t),
548 };
549 (ret, args, decl.variadic)
550 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700551}
552
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700553impl<'a, 'v> Visitor<'v> for TestGenerator<'a> {
Alex Crichton22378822015-09-10 19:59:23 -0700554 fn visit_item(&mut self, i: &'v ast::Item) {
Alex Crichton31504842015-09-10 23:43:41 -0700555 let prev_abi = self.abi;
Alex Crichton22378822015-09-10 19:59:23 -0700556 match i.node {
557 ast::ItemTy(_, ref generics) => {
558 self.assert_no_generics(i.ident, generics);
559 self.test_type(&i.ident.to_string());
560 }
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700561
Alex Crichton22378822015-09-10 19:59:23 -0700562 ast::ItemStruct(ref s, ref generics) => {
563 self.assert_no_generics(i.ident, generics);
564 let is_c = i.attrs.iter().any(|a| {
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700565 attr::find_repr_attrs(self.sh, a).iter().any(|a| {
566 *a == ReprAttr::ReprExtern
567 })
Alex Crichton22378822015-09-10 19:59:23 -0700568 });
569 if !is_c {
570 panic!("{} is not marked #[repr(C)]", i.ident);
571 }
572 self.test_struct(&i.ident.to_string(), s);
573 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700574
Alex Crichton22378822015-09-10 19:59:23 -0700575 ast::ItemConst(ref ty, _) => {
576 let ty = self.ty2name(ty);
577 self.test_const(&i.ident.to_string(), &ty);
578 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700579
Alex Crichton31504842015-09-10 23:43:41 -0700580 ast::ItemForeignMod(ref fm) => {
581 self.abi = fm.abi;
582 }
583
Alex Crichton22378822015-09-10 19:59:23 -0700584 _ => {}
585 }
Alex Crichton31504842015-09-10 23:43:41 -0700586 visit::walk_item(self, i);
587 self.abi = prev_abi;
Alex Crichton22378822015-09-10 19:59:23 -0700588 }
589
590 fn visit_foreign_item(&mut self, i: &'v ast::ForeignItem) {
591 match i.node {
592 ast::ForeignItemFn(ref decl, ref generics) => {
593 self.assert_no_generics(i.ident, generics);
594 let (ret, args, variadic) = self.decl2rust(decl);
Alex Crichton7da9b102015-09-10 20:57:14 -0700595 let cname = match attr::first_attr_value_str_by_name(&i.attrs,
596 "link_name") {
597 Some(ref i) if !i.to_string().contains("$") => {
598 i.to_string()
599 }
600 _ => i.ident.to_string(),
601 };
Alex Crichton31504842015-09-10 23:43:41 -0700602 let abi = self.abi;
Alex Crichton7da9b102015-09-10 20:57:14 -0700603 self.test_extern_fn(&i.ident.to_string(), &cname, &args, &ret,
Alex Crichton31504842015-09-10 23:43:41 -0700604 variadic, abi);
Alex Crichton22378822015-09-10 19:59:23 -0700605 }
606 ast::ForeignItemStatic(_, _) => {
607 }
608 }
609 visit::walk_foreign_item(self, i)
610 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700611}
Alex Crichton310d6232015-09-10 10:56:31 -0700612
613impl<'v> Visitor<'v> for StructFinder {
Alex Crichton22378822015-09-10 19:59:23 -0700614 fn visit_item(&mut self, i: &'v ast::Item) {
615 match i.node {
616 ast::ItemStruct(..) => {
617 self.structs.insert(i.ident.to_string());
618 }
619 ast::ItemEnum(..) => {
620 self.structs.insert(i.ident.to_string());
621 }
Alex Crichton310d6232015-09-10 10:56:31 -0700622
Alex Crichton22378822015-09-10 19:59:23 -0700623 _ => {}
624 }
625 visit::walk_item(self, i)
626 }
Alex Crichton310d6232015-09-10 10:56:31 -0700627}