rustkit_clang_sys/
support.rs

1// Copyright 2016 Kyle Mayes
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Provides helper functionality.
16
17use std::{io, env};
18use std::process::{Command};
19use std::path::{Path, PathBuf};
20
21use glob;
22
23use libc::{c_int};
24
25use super::{CXVersion};
26
27//================================================
28// Macros
29//================================================
30
31// try_opt! ______________________________________
32
33macro_rules! try_opt {
34    ($option:expr) => ({
35        match $option {
36            Some(some) => some,
37            None => return None,
38        }
39    });
40}
41
42//================================================
43// Structs
44//================================================
45
46/// A `clang` executable.
47#[derive(Clone, Debug)]
48pub struct Clang {
49    /// The path to this `clang` executable.
50    pub path: PathBuf,
51    /// The version of this `clang` executable if it could be parsed.
52    pub version: Option<CXVersion>,
53    /// The directories searched by this `clang` executable for C headers if they could be parsed.
54    pub c_search_paths: Option<Vec<PathBuf>>,
55    /// The directories searched by this `clang` executable for C++ headers if they could be parsed.
56    pub cpp_search_paths: Option<Vec<PathBuf>>,
57}
58
59impl Clang {
60    //- Constructors -----------------------------
61
62    fn new(path: PathBuf, args: &[String]) -> Clang {
63        let version = parse_version(&path);
64        let c_search_paths = parse_search_paths(&path, "c", args);
65        let cpp_search_paths = parse_search_paths(&path, "c++", args);
66        Clang { path, version, c_search_paths, cpp_search_paths }
67    }
68
69    /// Returns a `clang` executable if one can be found.
70    ///
71    /// If the `CLANG_PATH` environment variable is set, that is the instance of `clang` used.
72    /// Otherwise, a series of directories are searched. First, If a path is supplied, that is the
73    /// first directory searched. Then, the directory returned by `llvm-config --bindir` is
74    /// searched. On OS X systems, `xcodebuild -find clang` will next be queried. Last, the
75    /// directories in the system's `PATH` are searched.
76    pub fn find(path: Option<&Path>, args: &[String]) -> Option<Clang> {
77        if let Ok(path) = env::var("CLANG_PATH") {
78            return Some(Clang::new(path.into(), args));
79        }
80
81        let mut paths = vec![];
82        if let Some(path) = path {
83            paths.push(path.into());
84        }
85        if let Ok(path) = run_llvm_config(&["--bindir"]) {
86            paths.push(path.into());
87        }
88        if cfg!(target_os="macos") {
89            if let Ok((path, _)) = run("xcodebuild", &["-find", "clang"]) {
90                paths.push(path.into());
91            }
92        }
93        paths.extend(env::split_paths(&env::var("PATH").unwrap()));
94
95        let default = format!("clang{}", env::consts::EXE_SUFFIX);
96        let versioned = format!("clang-[0-9]*{}", env::consts::EXE_SUFFIX);
97        let patterns = &[&default[..], &versioned[..]];
98        for path in paths {
99            if let Some(path) = find(&path, patterns) {
100                return Some(Clang::new(path, args));
101            }
102        }
103        None
104    }
105}
106
107//================================================
108// Functions
109//================================================
110
111/// Returns the first match to the supplied glob patterns in the supplied directory if there are any
112/// matches.
113fn find(directory: &Path, patterns: &[&str]) -> Option<PathBuf> {
114    for pattern in patterns {
115        let pattern = directory.join(pattern).to_string_lossy().into_owned();
116        if let Some(path) = try_opt!(glob::glob(&pattern).ok()).filter_map(|p| p.ok()).next() {
117            if path.is_file() && is_executable(&path).unwrap_or(false) {
118                return Some(path);
119            }
120        }
121    }
122    None
123}
124
125#[cfg(unix)]
126fn is_executable(path: &Path) -> io::Result<bool> {
127    use libc;
128    use std::ffi::CString;
129    use std::os::unix::ffi::OsStrExt;
130
131    let path = CString::new(path.as_os_str().as_bytes())?;
132    unsafe { Ok(libc::access(path.as_ptr(), libc::X_OK) == 0) }
133}
134
135#[cfg(not(unix))]
136fn is_executable(_: &Path) -> io::Result<bool> {
137    Ok(true)
138}
139
140/// Attempts to run an executable, returning the `stdout` and `stderr` output if successful.
141fn run(executable: &str, arguments: &[&str]) -> Result<(String, String), String> {
142    Command::new(executable).args(arguments).output().map(|o| {
143        let stdout = String::from_utf8_lossy(&o.stdout).into_owned();
144        let stderr = String::from_utf8_lossy(&o.stderr).into_owned();
145        (stdout, stderr)
146    }).map_err(|e| format!("could not run executable `{}`: {}", executable, e))
147}
148
149/// Runs `clang`, returning the `stdout` and `stderr` output.
150fn run_clang(path: &Path, arguments: &[&str]) -> (String, String) {
151    run(&path.to_string_lossy().into_owned(), arguments).unwrap()
152}
153
154/// Runs `llvm-config`, returning the `stdout` output if successful.
155fn run_llvm_config(arguments: &[&str]) -> Result<String, String> {
156    let config = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".to_string());
157    run(&config, arguments).map(|(o, _)| o)
158}
159
160/// Parses a version number if possible, ignoring trailing non-digit characters.
161fn parse_version_number(number: &str) -> Option<c_int> {
162    number.chars().take_while(|c| c.is_digit(10)).collect::<String>().parse().ok()
163}
164
165/// Parses the version from the output of a `clang` executable if possible.
166fn parse_version(path: &Path) -> Option<CXVersion> {
167    let output = run_clang(path, &["--version"]).0;
168    let start = try_opt!(output.find("version ")) + 8;
169    let mut numbers = try_opt!(output[start..].split_whitespace().nth(0)).split('.');
170    let major = try_opt!(numbers.next().and_then(parse_version_number));
171    let minor = try_opt!(numbers.next().and_then(parse_version_number));
172    let subminor = numbers.next().and_then(parse_version_number).unwrap_or(0);
173    Some(CXVersion { Major: major, Minor: minor, Subminor: subminor })
174}
175
176/// Parses the search paths from the output of a `clang` executable if possible.
177fn parse_search_paths(path: &Path, language: &str, args: &[String]) -> Option<Vec<PathBuf>> {
178    let mut clang_args = vec!["-E", "-x", language, "-", "-v"];
179    clang_args.extend(args.iter().map(|s| &**s));
180    let output = run_clang(path, &clang_args).1;
181    let start = try_opt!(output.find("#include <...> search starts here:")) + 34;
182    let end = try_opt!(output.find("End of search list."));
183    let paths = output[start..end].replace("(framework directory)", "");
184    Some(paths.lines().filter(|l| !l.is_empty()).map(|l| Path::new(l.trim()).into()).collect())
185}