racket-sys 0.3.3

Rust bindings to Racket C API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use std::path::{Path, PathBuf};
use std::{env, fs};

#[cfg(feature = "bundled")]
fn main() {
    println!("cargo:rerun-if-changed=build.rs");

    let out_dir = {
        let mut path = PathBuf::from(env::var("OUT_DIR").unwrap());
        _ = path.pop() && path.pop() && path.pop();
        path
    };
    let bundle_dir = out_dir.join("bundled");

    if fs::metadata(&bundle_dir).is_err() {
        let url = "https://github.com/rn7s2/racket-bundled.git";
        match git2::Repository::clone(url, &bundle_dir) {
            Ok(_) => (),
            Err(e) => {
                _ = fs::remove_dir_all(&bundle_dir);
                panic!("Failed to clone: {}", e);
            }
        };
    }

    // link libraries
    println!("cargo:rustc-link-search=native=m");

    let headers;
    if cfg!(windows) {
        let lib_path = {
            let mut path = bundle_dir.clone();
            path.push("windows");
            path
        };

        // link dynamic library
        println!("cargo:rustc-link-search={}", lib_path.display());
        println!("cargo:rustc-link-lib=libracketcs_dh8a0w");

        headers = {
            let path = lib_path.clone();
            let cs_h = path.join("chezscheme.h");
            let rkt_h = path.join("racketcs.h");
            (
                cs_h.to_str().unwrap().to_string(),
                rkt_h.to_str().unwrap().to_string(),
            )
        };
    } else if cfg!(target_os = "macos") {
        let lib_path = {
            let mut path = bundle_dir.clone();
            path.push("macos");
            path
        };

        // link library
        println!("cargo:rustc-link-search={}", lib_path.display());
        println!("cargo:rustc-link-lib=racketcs");

        println!("cargo:rustc-link-lib=iconv");
        println!("cargo:rustc-link-lib=ncurses");
        println!("cargo:rustc-link-lib=framework=CoreFoundation");

        headers = {
            let path = lib_path.clone();
            let cs_h = path.join("chezscheme.h");
            let rkt_h = path.join("racketcs.h");
            (
                cs_h.to_str().unwrap().to_string(),
                rkt_h.to_str().unwrap().to_string(),
            )
        };
    } else {
        let lib_path = {
            let mut path = bundle_dir.clone();
            path.push("linux");
            path
        };
        println!("cargo:rustc-link-search={}", lib_path.display());
        println!("cargo:rustc-link-lib=racketcs");

        println!("cargo:rustc-link-lib=ncurses");
        println!("cargo:rustc-link-lib=lz4");
        println!("cargo:rustc-link-lib=z");

        headers = {
            let path = lib_path.clone();
            let cs_h = path.join("chezscheme.h");
            let rkt_h = path.join("racketcs.h");
            (
                cs_h.to_str().unwrap().to_string(),
                rkt_h.to_str().unwrap().to_string(),
            )
        };
    }

    // generate bindings
    let bindings = bindgen::Builder::default()
        .header(headers.0)
        .header(headers.1)
        .generate()
        .expect("Unable to generate bindings!");

    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");

    // copy dependencies to output directory
    // works even if this crate is a dependency of another crate
    let boot_files = ["petite.boot", "scheme.boot", "racket.boot"];
    if cfg!(windows) {
        let dll_path = {
            let mut path = bundle_dir.clone();
            path.push("windows");
            path.push("libracketcs_dh8a0w.dll");
            path
        };

        fs::copy(
            dll_path,
            out_dir.to_str().unwrap().to_string() + "/libracketcs_dh8a0w.dll",
        )
        .expect("Failed to copy dll file.");

        // copy boot files
        for boot_file in boot_files.iter() {
            let boot_path = {
                let mut path = bundle_dir.clone();
                path.push("windows");
                path.push(boot_file);
                path
            };

            fs::copy(
                boot_path,
                out_dir.to_str().unwrap().to_string() + "/" + boot_file,
            )
            .expect("Failed to copy boot file.");
        }
    } else if cfg!(target_os = "macos") {
        // copy boot files
        for boot_file in boot_files.iter() {
            let boot_path = {
                let mut path = bundle_dir.clone();
                path.push("macos");
                path.push(boot_file);
                path
            };

            fs::copy(
                boot_path,
                out_dir.to_str().unwrap().to_string() + "/" + boot_file,
            )
            .expect("Failed to copy boot file.");
        }

        // copy framework
        let mut framework_dir = bundle_dir.clone();
        framework_dir.push("macos");
        framework_dir.push("Racket.framework");

        let mut out_dir = out_dir.clone();
        out_dir.pop();
        out_dir.pop();
        copy_recursively(
            framework_dir,
            out_dir.to_str().unwrap().to_string() + "/Racket.framework",
        )
        .expect("Failed to copy Racket framework.");
    } else {
        let bootfile_dir = {
            let mut path = bundle_dir.clone();
            path.push("linux");
            path
        };
        for boot_file in boot_files.iter() {
            let boot_path = {
                let mut path = bootfile_dir.clone();
                path.push(boot_file);
                path
            };

            fs::copy(
                boot_path,
                out_dir.to_str().unwrap().to_string() + "/" + boot_file,
            )
            .expect("Failed to copy boot file.");
        }
    }
}

#[cfg(not(feature = "bundled"))]
fn main() {
    println!("cargo:rerun-if-changed=build.rs");

    const DEFAULT_RKT_VER: &str = "8.13";

    // directories
    let rkt_home = {
        let home = env::var("RACKET_CS_HOME");
        if cfg!(windows) {
            PathBuf::from(home.unwrap_or("C:/Program Files/Racket".to_string()))
        } else if cfg!(target_os = "macos") {
            PathBuf::from(home.unwrap_or("/Applications/Racket v".to_string() + DEFAULT_RKT_VER))
        } else {
            PathBuf::from(home.unwrap_or("/usr/".to_string()))
        }
    };
    let out_dir = {
        let mut path = PathBuf::from(env::var("OUT_DIR").unwrap());
        _ = path.pop() && path.pop() && path.pop();
        path
    };

    // link libraries
    println!("cargo:rustc-link-search=native=m");
    if cfg!(windows) {
        // generate lib file from module definition file
        let def_path = {
            let mut path = rkt_home.clone();
            path.push("lib");
            path.push("libracketcs_dh8a0w.def");
            path
        };
        let lib_path = {
            let mut path = out_dir.clone();
            path.push("libracketcs_dh8a0w.lib");
            path
        };

        let lib_tool_exe =
            locate_vs_lib_tool().expect("Failed to locate lib.exe from VS installation.");
        let status = std::process::Command::new(lib_tool_exe)
            .arg(&format!("/def:{}", def_path.to_str().unwrap()))
            .arg(&format!("/out:{}", lib_path.to_str().unwrap()))
            .arg("/machine:x64")
            .status()
            .expect("Failed to generate lib file from module def.");
        if status.code() != Some(0) {
            panic!("Failed to generate lib file from module def.");
        }

        // link dynamic library
        println!("cargo:rustc-link-search={}", out_dir.display());
        println!("cargo:rustc-link-lib=libracketcs_dh8a0w");
    } else if cfg!(target_os = "macos") {
        let version = env::var("RACKET_CS_VERSION").unwrap_or(DEFAULT_RKT_VER.to_string());
        let lib_path = {
            let mut path = rkt_home.clone();
            path.push("lib");
            path.push("Racket.framework");
            path.push("Versions");
            path.push(version + "_CS");
            path.push("Racket");
            path
        };
        let dest_lib_path = {
            let mut path = out_dir.clone();
            path.push("libracketcs.a");
            path
        };
        fs::copy(lib_path, dest_lib_path).expect("Failed to find Racket library.");

        // link library
        println!("cargo:rustc-link-search={}", out_dir.display());
        println!("cargo:rustc-link-lib=racketcs");

        println!("cargo:rustc-link-lib=iconv");
        println!("cargo:rustc-link-lib=ncurses");
        println!("cargo:rustc-link-lib=framework=CoreFoundation");
    } else {
        let lib_dir = {
            let mut path = rkt_home.clone();
            path.push("lib");
            path
        };
        println!("cargo:rustc-link-search={}", lib_dir.display());
        println!("cargo:rustc-link-lib=racketcs");

        println!("cargo:rustc-link-lib=ncurses");
        println!("cargo:rustc-link-lib=lz4");
        println!("cargo:rustc-link-lib=z");
    }

    // generate bindings
    let headers = {
        let mut path = rkt_home.clone();
        path.push("include");
        if cfg!(target_os = "linux") {
            path.push("racket");
        }

        let cs_h = path.join("chezscheme.h");
        let rkt_h = path.join("racketcs.h");
        (
            cs_h.to_str().unwrap().to_string(),
            rkt_h.to_str().unwrap().to_string(),
        )
    };
    let bindings = bindgen::Builder::default()
        .header(headers.0)
        .header(headers.1)
        .generate()
        .expect("Unable to generate bindings!");

    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");

    // copy dependencies to output directory
    // works even if this crate is a dependency of another crate
    let boot_files = ["petite.boot", "scheme.boot", "racket.boot"];
    if cfg!(windows) {
        // generate lib file from module definition file
        let dll_path = {
            let mut path = rkt_home.clone();
            path.push("lib");
            path.push("libracketcs_dh8a0w.dll");
            path
        };

        fs::copy(
            dll_path,
            out_dir.to_str().unwrap().to_string() + "/libracketcs_dh8a0w.dll",
        )
        .expect("Failed to copy dll file.");

        // copy boot files
        for boot_file in boot_files.iter() {
            let boot_path = {
                let mut path = rkt_home.clone();
                path.push("lib");
                path.push(boot_file);
                path
            };

            fs::copy(
                boot_path,
                out_dir.to_str().unwrap().to_string() + "/" + boot_file,
            )
            .expect("Failed to copy boot file.");
        }
    } else if cfg!(target_os = "macos") {
        // copy boot files
        let version = env::var("RACKET_CS_VERSION").unwrap_or(DEFAULT_RKT_VER.to_string());
        for boot_file in boot_files.iter() {
            let boot_path = {
                let mut path = rkt_home.clone();
                path.push("lib");
                path.push("Racket.framework");
                path.push("Versions");
                path.push(version.clone() + "_CS");
                path.push("boot");
                path.push(boot_file);
                path
            };

            fs::copy(
                boot_path,
                out_dir.to_str().unwrap().to_string() + "/" + boot_file,
            )
            .expect("Failed to copy boot file.");
        }

        // copy framework
        let mut framework_dir = rkt_home.clone();
        framework_dir.push("lib");
        framework_dir.push("Racket.framework");

        let mut out_dir = out_dir.clone();
        out_dir.pop();
        out_dir.pop();
        copy_recursively(
            framework_dir,
            out_dir.to_str().unwrap().to_string() + "/Racket.framework",
        )
        .expect("Failed to copy Racket framework.");
    } else {
        let bootfile_dir = {
            let mut path = rkt_home.clone();
            path.push("lib");
            path.push("racket");
            path
        };
        for boot_file in boot_files.iter() {
            let boot_path = {
                let mut path = bootfile_dir.clone();
                path.push(boot_file);
                path
            };

            fs::copy(
                boot_path,
                out_dir.to_str().unwrap().to_string() + "/" + boot_file,
            )
            .expect("Failed to copy boot file.");
        }
    }
}

/// Copy files from source to destination recursively.
/// thanks: https://nick.groenen.me/notes/recursively-copy-files-in-rust/
fn copy_recursively(
    source: impl AsRef<Path>,
    destination: impl AsRef<Path>,
) -> std::io::Result<()> {
    fs::create_dir_all(&destination)?;
    for entry in fs::read_dir(source)? {
        let entry = entry?;
        let filetype = entry.file_type()?;
        if filetype.is_dir() {
            copy_recursively(entry.path(), destination.as_ref().join(entry.file_name()))?;
        } else {
            fs::copy(entry.path(), destination.as_ref().join(entry.file_name()))?;
        }
    }
    Ok(())
}

#[allow(dead_code)]
fn locate_vs_lib_tool() -> Option<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        let mut vcvars = vcvars::Vcvars::new();
        let path = vcvars.get_cached("PATH").unwrap().to_string();
        let dirs = path.split(";").collect::<Vec<_>>();
        for dir in &dirs {
            let mut exe = PathBuf::from(dir);
            exe.push("lib.exe");
            if exe.exists() {
                return Some(exe);
            }
        }
    }
    None
}