blob: de343db2d220a4807d5413dea2e2fcc53c3ca764 [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 Crichton1cf98ae2015-09-13 11:19:02 -070046 if self.target.contains("unknown-linux-gnu") {
Alex Crichton0df7c102015-09-10 16:35:37 -070047 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 };
Alex Crichton1cf98ae2015-09-13 11:19:02 -0700214 let (os, family, env) = if self.target.contains("unknown-linux-gnu") {
Alex Crichton310d6232015-09-10 10:56:31 -0700215 ("linux", "unix", "gnu")
Alex Crichton1cf98ae2015-09-13 11:19:02 -0700216 } else if self.target.contains("unknown-linux-musl") {
217 ("linux", "unix", "musl")
Alex Crichton310d6232015-09-10 10:56:31 -0700218 } else if self.target.contains("apple-darwin") {
219 ("macos", "unix", "")
Alex Crichtonac2bd852015-09-10 17:21:20 -0700220 } else if self.target.contains("windows-msvc") {
221 ("windows", "windows", "msvc")
222 } else if self.target.contains("windows-gnu") {
223 ("windows", "windows", "gnu")
Alex Crichtond3d77922015-09-11 17:03:39 -0700224 } else if self.target.contains("android") {
225 ("android", "unix", "")
Alex Crichton310d6232015-09-10 10:56:31 -0700226 } else {
227 panic!("unknown os/family width: {}", self.target)
228 };
229
230 ret.push((family, None));
231 ret.push(("target_os", Some(os)));
232 ret.push(("target_family", Some(family)));
233 ret.push(("target_arch", Some(arch)));
234 // skip endianness
235 ret.push(("target_pointer_width", Some(target_pointer_width)));
236 ret.push(("target_env", Some(env)));
237
238 return ret
239 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700240}
241
242fn main() {
Alex Crichton310d6232015-09-10 10:56:31 -0700243 // Prep the test generator
244 let target = t!(env::var("TARGET"));
245 let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
246 let rust_out = BufWriter::new(t!(File::create(out.join("all.rs"))));
247 let c_out = BufWriter::new(t!(File::create(out.join("all.c"))));
Alex Crichton16083062015-09-09 22:59:24 -0700248 let sess = ParseSess::new();
Alex Crichton310d6232015-09-10 10:56:31 -0700249 let mut tg = TestGenerator {
250 target: target,
251 rust: Box::new(rust_out),
252 c: Box::new(c_out),
253 sh: &sess.span_diagnostic,
254 structs: HashSet::new(),
Alex Crichton31504842015-09-10 23:43:41 -0700255 abi: Abi::C,
Alex Crichton310d6232015-09-10 10:56:31 -0700256 };
257
258 // Parse the libc crate
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700259 let src = Path::new("../src/lib.rs");
260 let cfg = Vec::new();
Alex Crichton31504842015-09-10 23:43:41 -0700261 let krate = parse::parse_crate_from_file(src, cfg, &sess);
262
263 // expand macros
264 let ecfg = expand::ExpansionConfig::default("libc".to_string());
265 let exts = vec![
266 (intern("macro_rules"), SyntaxExtension::MacroRulesTT),
267 ];
268 let mut krate = expand::expand_crate(&sess, ecfg, Vec::new(),
269 exts, &mut Vec::new(), krate);
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700270
Alex Crichton310d6232015-09-10 10:56:31 -0700271 // Strip the crate down to just what's configured for our target
272 for (k, v) in tg.cfg_list() {
273 let s = InternedString::new;
274 krate.config.push(match v {
275 Some(v) => attr::mk_name_value_item_str(s(k), s(v)),
276 None => attr::mk_word_item(s(k)),
277 });
278 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700279 let mut gated_cfgs = Vec::new();
280 let krate = syntax::config::strip_unconfigured_items(&sess.span_diagnostic,
281 krate,
282 &mut gated_cfgs);
283
Alex Crichton310d6232015-09-10 10:56:31 -0700284 // Probe the crate to find all structs (used to convert type names to names
285 // in C).
286 let mut structs = StructFinder {
287 structs: HashSet::new(),
288 };
289 visit::walk_crate(&mut structs, &krate);
290 tg.structs = structs.structs;
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700291
Alex Crichton0df7c102015-09-10 16:35:37 -0700292 // Prep the C file by emitting header stuff
293 for define in tg.defines() {
294 t!(writeln!(tg.c, "#define {}", define));
295 }
Alex Crichton310d6232015-09-10 10:56:31 -0700296 for header in tg.headers() {
297 t!(writeln!(tg.c, "#include <{}>", header));
Alex Crichton16083062015-09-09 22:59:24 -0700298 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700299
300 // Walk the crate, emitting test cases for everything found
Alex Crichton310d6232015-09-10 10:56:31 -0700301 visit::walk_crate(&mut tg, &krate);
Alex Crichton16083062015-09-09 22:59:24 -0700302
Alex Crichton310d6232015-09-10 10:56:31 -0700303 // Compile our C shim to be linked into tests
Alex Crichtonac2bd852015-09-10 17:21:20 -0700304 let mut cfg = gcc::Config::new();
305 cfg.file(out.join("all.c"));
306
307 if tg.target.contains("msvc") {
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700308 cfg.flag("/W3").flag("/Wall").flag("/WX")
309 .flag("/wd4820") // weird warning about adding padding?
Alex Crichton7da9b102015-09-10 20:57:14 -0700310 .flag("/wd4100") // don't warn about unused parameters
311 .flag("/wd4996"); // don't warn about deprecated functions
Alex Crichtonac2bd852015-09-10 17:21:20 -0700312 } else {
Alex Crichtonb01a8cc2015-09-10 17:37:22 -0700313 cfg.flag("-Wall").flag("-Wextra").flag("-Werror")
Alex Crichton5f624a52015-09-10 17:39:21 -0700314 .flag("-Wno-unused-parameter");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700315 }
316
317 drop(tg);
318 cfg.compile("liball.a");
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700319}
320
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700321impl<'a> TestGenerator<'a> {
322 fn test_type(&mut self, ty: &str) {
Alex Crichton310d6232015-09-10 10:56:31 -0700323 match ty {
Alex Crichtond3d77922015-09-11 17:03:39 -0700324 // sighandler_t is crazy across platforms
Alex Crichton310d6232015-09-10 10:56:31 -0700325 "sighandler_t" => return,
Alex Crichtond3d77922015-09-11 17:03:39 -0700326
327 // Not actually defined on android, but it's not hurting anyone
328 "in_port_t" if self.target.contains("android") => return,
Alex Crichton310d6232015-09-10 10:56:31 -0700329 _ => {}
330 }
Alex Crichton22378822015-09-10 19:59:23 -0700331 let c = self.rust_ty_to_c_ty(ty);
Alex Crichton310d6232015-09-10 10:56:31 -0700332 self.test_size_align(ty, &c);
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700333 }
Alex Crichton16083062015-09-09 22:59:24 -0700334
Alex Crichton3e5155b2015-09-09 23:46:19 -0700335 fn test_struct(&mut self, ty: &str, s: &ast::StructDef) {
Alex Crichton22378822015-09-10 19:59:23 -0700336 let cty = self.rust_ty_to_c_ty(ty);
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700337 self.test_size_align(ty, &cty);
Alex Crichton3e5155b2015-09-09 23:46:19 -0700338
Alex Crichton310d6232015-09-10 10:56:31 -0700339 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700340 #[test]
341 fn field_offset_size_{ty}() {{
Alex Crichton310d6232015-09-10 10:56:31 -0700342 "#, ty = ty));
Alex Crichton3e5155b2015-09-09 23:46:19 -0700343 for field in s.fields.iter() {
344 let name = match field.node.kind {
345 ast::NamedField(name, ast::Public) => name,
346 ast::NamedField(_, ast::Inherited) => continue,
347 ast::UnnamedField(..) => panic!("no tuple structs in FFI"),
348 };
349
Alex Crichton310d6232015-09-10 10:56:31 -0700350 let cfield = self.rust2cfield(ty, &name.to_string());
Alex Crichton3e5155b2015-09-09 23:46:19 -0700351
Alex Crichton310d6232015-09-10 10:56:31 -0700352 t!(writeln!(self.c, r#"
Alex Crichton671376b2015-09-10 17:39:03 -0700353 uint64_t __test_offset_{ty}_{rust_field}(void) {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700354 return offsetof({cty}, {c_field});
355 }}
Alex Crichton671376b2015-09-10 17:39:03 -0700356 uint64_t __test_size_{ty}_{rust_field}(void) {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700357 {cty}* foo = NULL;
358 return sizeof(foo->{c_field});
359 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700360 "#, ty = ty, cty = cty, rust_field = name, c_field = cfield));
361 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700362 extern {{
363 fn __test_offset_{ty}_{field}() -> u64;
364 fn __test_size_{ty}_{field}() -> u64;
365 }}
366 unsafe {{
367 let foo = 0 as *const {ty};
368 same(offset_of!({ty}, {field}),
369 __test_offset_{ty}_{field}(),
370 "field offset {field} of {ty}");
371 same(mem::size_of_val(&(*foo).{field}) as u64,
372 __test_size_{ty}_{field}(),
373 "field size {field} of {ty}");
374 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700375 "#, ty = ty, field = name));
Alex Crichton3e5155b2015-09-09 23:46:19 -0700376 }
Alex Crichton310d6232015-09-10 10:56:31 -0700377 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700378 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700379 "#));
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700380 }
381
382 fn test_size_align(&mut self, rust: &str, c: &str) {
Alex Crichton310d6232015-09-10 10:56:31 -0700383 t!(writeln!(self.c, r#"
Alex Crichton671376b2015-09-10 17:39:03 -0700384 uint64_t __test_size_{ty}(void) {{ return sizeof({cty}); }}
385 uint64_t __test_align_{ty}(void) {{ return alignof({cty}); }}
Alex Crichton310d6232015-09-10 10:56:31 -0700386 "#, ty = rust, cty = c));
387 t!(writeln!(self.rust, r#"
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700388 #[test]
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700389 fn size_align_{ty}() {{
Alex Crichton16083062015-09-09 22:59:24 -0700390 extern {{
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700391 fn __test_size_{ty}() -> u64;
392 fn __test_align_{ty}() -> u64;
Alex Crichton16083062015-09-09 22:59:24 -0700393 }}
394 unsafe {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700395 same(mem::size_of::<{ty}>() as u64,
396 __test_size_{ty}(), "size");
Alex Crichtonc8b895c2015-09-10 13:24:15 -0700397 same(align::<{ty}>() as u64,
Alex Crichton3e5155b2015-09-09 23:46:19 -0700398 __test_align_{ty}(), "align");
Alex Crichton16083062015-09-09 22:59:24 -0700399 }}
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700400 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700401 "#, ty = rust));
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700402 }
403
Alex Crichton22378822015-09-10 19:59:23 -0700404 fn rust_ty_to_c_ty(&self, mut rust_ty: &str) -> String {
405 let mut cty = self.rust2c(&rust_ty.replace("*mut ", "")
406 .replace("*const ", ""));
407 while rust_ty.starts_with("*") {
408 if rust_ty.starts_with("*const") {
409 cty = format!("const {}*", cty);
410 rust_ty = &rust_ty[7..];
411 } else {
412 cty = format!("{}*", cty);
413 rust_ty = &rust_ty[5..];
414 }
415 }
416 return cty
417 }
418
Alex Crichton0df7c102015-09-10 16:35:37 -0700419 fn test_const(&mut self, name: &str, rust_ty: &str) {
Alex Crichton31504842015-09-10 23:43:41 -0700420 let mingw = self.target.contains("windows-gnu");
421
422 // Apparently these don't exist in mingw headers?
423 match name {
424 "MEM_RESET_UNDO" |
425 "FILE_ATTRIBUTE_NO_SCRUB_DATA" |
426 "FILE_ATTRIBUTE_INTEGRITY_STREAM" |
427 "ERROR_NOTHING_TO_TERMINATE" if mingw => return,
428 _ => {}
429 }
430
Alex Crichton22378822015-09-10 19:59:23 -0700431 let cty = self.rust_ty_to_c_ty(rust_ty);
Alex Crichton31504842015-09-10 23:43:41 -0700432
433 // SIG_IGN has weird types on platforms, just worry about it as a size_t
Alex Crichton0df7c102015-09-10 16:35:37 -0700434 let cast = if name == "SIG_IGN" {"(size_t)"} else {""};
Alex Crichton31504842015-09-10 23:43:41 -0700435
Alex Crichton0df7c102015-09-10 16:35:37 -0700436 t!(writeln!(self.c, r#"
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700437 int __test_const_{name}({cty} *outptr) {{
438 *outptr = {cast}({name});
439 return 1;
Alex Crichtone7afdd82015-09-10 17:15:20 -0700440 }}
Alex Crichton0df7c102015-09-10 16:35:37 -0700441 "#, name = name, cast = cast, cty = cty));
442 t!(writeln!(self.rust, r#"
443 #[test]
444 fn const_{name}() {{
445 extern {{
Alex Crichtone7afdd82015-09-10 17:15:20 -0700446 fn __test_const_{name}(out: *mut {ty}) -> c_int;
Alex Crichton0df7c102015-09-10 16:35:37 -0700447 }}
448 unsafe {{
Alex Crichtone7afdd82015-09-10 17:15:20 -0700449 let mut o = mem::zeroed();
450 if __test_const_{name}(&mut o) == 0 {{
451 panic!("not defined");
452 }} else {{
453 same({name}, o, "value");
454 }}
Alex Crichton0df7c102015-09-10 16:35:37 -0700455 }}
456 }}
457 "#, ty = rust_ty, name = name));
458 }
459
Alex Crichton7da9b102015-09-10 20:57:14 -0700460 fn test_extern_fn(&mut self, name: &str, cname: &str,
461 args: &[String], ret: &str,
Alex Crichton31504842015-09-10 23:43:41 -0700462 variadic: bool, abi: Abi) {
Alex Crichton22378822015-09-10 19:59:23 -0700463 match name {
464 // manually verified
465 "execv" |
466 "execve" |
467 "execvp" |
Alex Crichton7da9b102015-09-10 20:57:14 -0700468 "execvpe" |
Alex Crichton22378822015-09-10 19:59:23 -0700469 "glob" |
470 "getrlimit" |
471 "setrlimit" |
Alex Crichtone8606192015-09-10 20:19:44 -0700472 "signal" |
Alex Crichton22378822015-09-10 19:59:23 -0700473 "getopt" => return,
474 _ => {}
475 }
476 let args = if args.len() == 0 && !variadic {
477 "void".to_string()
478 } else {
479 args.iter().map(|a| self.rust_ty_to_c_ty(a)).collect::<Vec<_>>()
480 .connect(", ") + if variadic {", ..."} else {""}
481 };
482 let cret = self.rust_ty_to_c_ty(ret);
Alex Crichton31504842015-09-10 23:43:41 -0700483 let abi = match abi {
484 Abi::C => "",
485 Abi::Stdcall => "__stdcall ",
486 Abi::System if self.target.contains("i686-pc-windows") => {
487 "__stdcall "
488 }
489 Abi::System => "",
490 a => panic!("unknown ABI: {}", a),
491 };
Alex Crichton22378822015-09-10 19:59:23 -0700492 t!(writeln!(self.c, r#"
Alex Crichton31504842015-09-10 23:43:41 -0700493 {ret} ({abi}*__test_fn_{name}(void))({args}) {{
Alex Crichton7da9b102015-09-10 20:57:14 -0700494 return {cname};
Alex Crichton22378822015-09-10 19:59:23 -0700495 }}
Alex Crichton31504842015-09-10 23:43:41 -0700496 "#, name = name, cname = cname, args = args, ret = cret, abi = abi));
Alex Crichton22378822015-09-10 19:59:23 -0700497 t!(writeln!(self.rust, r#"
498 #[test]
Alex Crichton7da9b102015-09-10 20:57:14 -0700499 #[cfg_attr(windows, ignore)] // FIXME -- dllimport weirdness?
Alex Crichton22378822015-09-10 19:59:23 -0700500 fn fn_{name}() {{
501 extern {{
502 fn __test_fn_{name}() -> size_t;
503 }}
504 unsafe {{
505 same({name} as usize,
506 __test_fn_{name}() as usize, "function pointer");
507 }}
508 }}
509 "#, name = name));
510 }
511
512 fn assert_no_generics(&self, _i: ast::Ident, generics: &ast::Generics) {
513 assert!(generics.lifetimes.len() == 0);
514 assert!(generics.ty_params.len() == 0);
515 assert!(generics.where_clause.predicates.len() == 0);
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700516 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700517
518 fn ty2name(&self, ty: &ast::Ty) -> String {
519 match ty.node {
520 ast::TyPath(_, ref path) => {
521 path.segments.last().unwrap().identifier.to_string()
522 }
523 ast::TyPtr(ref t) => {
524 format!("*{} {}", match t.mutbl {
525 ast::MutImmutable => "const",
526 ast::MutMutable => "mut",
527 }, self.ty2name(&t.ty))
528 }
Alex Crichton22378822015-09-10 19:59:23 -0700529 ast::TyBareFn(ref t) => {
530 assert!(t.lifetimes.len() == 0);
531 let (ret, mut args, variadic) = self.decl2rust(&t.decl);
532 assert!(!variadic);
533 if args.len() == 0 {
534 args.push("void".to_string());
535 }
536 format!("{}(*)({})", ret, args.connect(", "))
537 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700538 _ => panic!("unknown ty {:?}", ty),
539 }
540 }
Alex Crichton22378822015-09-10 19:59:23 -0700541
542 fn decl2rust(&self, decl: &ast::FnDecl) -> (String, Vec<String>, bool) {
543 let args = decl.inputs.iter().map(|arg| {
544 self.ty2name(&arg.ty)
545 }).collect::<Vec<_>>();
546 let ret = match decl.output {
547 ast::NoReturn(..) |
548 ast::DefaultReturn(..) => "void".to_string(),
549 ast::Return(ref t) => self.ty2name(t),
550 };
551 (ret, args, decl.variadic)
552 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700553}
554
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700555impl<'a, 'v> Visitor<'v> for TestGenerator<'a> {
Alex Crichton22378822015-09-10 19:59:23 -0700556 fn visit_item(&mut self, i: &'v ast::Item) {
Alex Crichton31504842015-09-10 23:43:41 -0700557 let prev_abi = self.abi;
Alex Crichton22378822015-09-10 19:59:23 -0700558 match i.node {
559 ast::ItemTy(_, ref generics) => {
560 self.assert_no_generics(i.ident, generics);
561 self.test_type(&i.ident.to_string());
562 }
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700563
Alex Crichton22378822015-09-10 19:59:23 -0700564 ast::ItemStruct(ref s, ref generics) => {
565 self.assert_no_generics(i.ident, generics);
566 let is_c = i.attrs.iter().any(|a| {
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700567 attr::find_repr_attrs(self.sh, a).iter().any(|a| {
568 *a == ReprAttr::ReprExtern
569 })
Alex Crichton22378822015-09-10 19:59:23 -0700570 });
571 if !is_c {
572 panic!("{} is not marked #[repr(C)]", i.ident);
573 }
574 self.test_struct(&i.ident.to_string(), s);
575 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700576
Alex Crichton22378822015-09-10 19:59:23 -0700577 ast::ItemConst(ref ty, _) => {
578 let ty = self.ty2name(ty);
579 self.test_const(&i.ident.to_string(), &ty);
580 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700581
Alex Crichton31504842015-09-10 23:43:41 -0700582 ast::ItemForeignMod(ref fm) => {
583 self.abi = fm.abi;
584 }
585
Alex Crichton22378822015-09-10 19:59:23 -0700586 _ => {}
587 }
Alex Crichton31504842015-09-10 23:43:41 -0700588 visit::walk_item(self, i);
589 self.abi = prev_abi;
Alex Crichton22378822015-09-10 19:59:23 -0700590 }
591
592 fn visit_foreign_item(&mut self, i: &'v ast::ForeignItem) {
593 match i.node {
594 ast::ForeignItemFn(ref decl, ref generics) => {
595 self.assert_no_generics(i.ident, generics);
596 let (ret, args, variadic) = self.decl2rust(decl);
Alex Crichton7da9b102015-09-10 20:57:14 -0700597 let cname = match attr::first_attr_value_str_by_name(&i.attrs,
598 "link_name") {
599 Some(ref i) if !i.to_string().contains("$") => {
600 i.to_string()
601 }
602 _ => i.ident.to_string(),
603 };
Alex Crichton31504842015-09-10 23:43:41 -0700604 let abi = self.abi;
Alex Crichton7da9b102015-09-10 20:57:14 -0700605 self.test_extern_fn(&i.ident.to_string(), &cname, &args, &ret,
Alex Crichton31504842015-09-10 23:43:41 -0700606 variadic, abi);
Alex Crichton22378822015-09-10 19:59:23 -0700607 }
608 ast::ForeignItemStatic(_, _) => {
609 }
610 }
611 visit::walk_foreign_item(self, i)
612 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700613}
Alex Crichton310d6232015-09-10 10:56:31 -0700614
615impl<'v> Visitor<'v> for StructFinder {
Alex Crichton22378822015-09-10 19:59:23 -0700616 fn visit_item(&mut self, i: &'v ast::Item) {
617 match i.node {
618 ast::ItemStruct(..) => {
619 self.structs.insert(i.ident.to_string());
620 }
621 ast::ItemEnum(..) => {
622 self.structs.insert(i.ident.to_string());
623 }
Alex Crichton310d6232015-09-10 10:56:31 -0700624
Alex Crichton22378822015-09-10 19:59:23 -0700625 _ => {}
626 }
627 visit::walk_item(self, i)
628 }
Alex Crichton310d6232015-09-10 10:56:31 -0700629}