Skip to main content

llama_cpp_wrapper_sources/
compile_commands_file.rs

1use std::fs::File;
2use std::path::Path;
3use std::path::PathBuf;
4
5use crate::compile_command::CompileCommand;
6use crate::cpp_standard::CPP_STANDARD;
7use crate::fault_injection_define::FAULT_INJECTION_DEFINE;
8use crate::system_include_flags::system_include_flags;
9use crate::wrapper_include_dirs::WRAPPER_INCLUDE_DIRS;
10use crate::wrapper_source_paths::wrapper_source_paths;
11use crate::wrapper_sources_error::WrapperSourcesError;
12
13const CPP_COMPILER: &str = "c++";
14
15fn absolute_path(directory: &Path, relative: &str) -> String {
16    directory.join(relative).display().to_string()
17}
18
19pub struct CompileCommandsFile {
20    pub output_path: PathBuf,
21    pub sys_dir: PathBuf,
22}
23
24impl CompileCommandsFile {
25    #[must_use]
26    pub fn commands(&self) -> Vec<CompileCommand> {
27        wrapper_source_paths(&self.sys_dir)
28            .into_iter()
29            .map(|file| {
30                let mut arguments = vec![
31                    CPP_COMPILER.to_owned(),
32                    format!("-std={CPP_STANDARD}"),
33                    format!("-D{FAULT_INJECTION_DEFINE}"),
34                ];
35
36                for include_dir in WRAPPER_INCLUDE_DIRS {
37                    arguments.push(format!("-I{}", absolute_path(&self.sys_dir, include_dir)));
38                }
39
40                arguments.extend(system_include_flags(&self.sys_dir));
41
42                arguments.push("-c".to_owned());
43                arguments.push(file.display().to_string());
44
45                CompileCommand {
46                    arguments,
47                    directory: self.sys_dir.clone(),
48                    file,
49                }
50            })
51            .collect()
52    }
53
54    /// # Errors
55    ///
56    /// Returns [`WrapperSourcesError`] when the destination file cannot be created or
57    /// the compilation database cannot be written to it.
58    pub fn write(&self) -> Result<(), WrapperSourcesError> {
59        let destination =
60            File::create(&self.output_path).map_err(|source| WrapperSourcesError::Create {
61                path: self.output_path.clone(),
62                source,
63            })?;
64
65        serde_json::to_writer_pretty(destination, &self.commands()).map_err(|source| {
66            WrapperSourcesError::Serialize {
67                path: self.output_path.clone(),
68                source,
69            }
70        })
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use std::path::Path;
77    use std::path::PathBuf;
78
79    use super::CompileCommandsFile;
80    use crate::system_include_flags::system_include_flags;
81    use crate::wrapper_include_dirs::WRAPPER_INCLUDE_DIRS;
82    use crate::wrapper_source_paths::wrapper_source_paths;
83
84    fn database_for(output_path: &str) -> CompileCommandsFile {
85        CompileCommandsFile {
86            output_path: PathBuf::from(output_path),
87            sys_dir: PathBuf::from("/repo/llama-cpp-bindings-sys"),
88        }
89    }
90
91    #[test]
92    fn every_wrapper_source_becomes_one_entry() {
93        let commands = database_for("/unused").commands();
94
95        assert_eq!(
96            commands
97                .iter()
98                .map(|command| command.file.clone())
99                .collect::<Vec<PathBuf>>(),
100            wrapper_source_paths(Path::new("/repo/llama-cpp-bindings-sys"))
101        );
102    }
103
104    #[test]
105    fn every_include_dir_is_resolved_against_the_sys_dir() {
106        let commands = database_for("/unused").commands();
107
108        assert_eq!(
109            commands
110                .first()
111                .map(|command| command
112                    .arguments
113                    .iter()
114                    .filter(|argument| argument.starts_with("-I"))
115                    .cloned()
116                    .collect::<Vec<String>>())
117                .unwrap_or_default(),
118            WRAPPER_INCLUDE_DIRS
119                .iter()
120                .map(|include_dir| {
121                    format!(
122                        "-I{}",
123                        Path::new("/repo/llama-cpp-bindings-sys")
124                            .join(include_dir)
125                            .display()
126                    )
127                })
128                .collect::<Vec<String>>()
129        );
130    }
131
132    #[test]
133    fn every_command_includes_the_vendored_headers_as_system_headers() {
134        let commands = database_for("/unused").commands();
135
136        assert_eq!(
137            commands
138                .iter()
139                .map(|command| command
140                    .arguments
141                    .iter()
142                    .filter(|argument| argument.starts_with("-isystem"))
143                    .cloned()
144                    .collect::<Vec<String>>())
145                .collect::<Vec<Vec<String>>>(),
146            vec![
147                system_include_flags(Path::new("/repo/llama-cpp-bindings-sys"));
148                wrapper_source_paths(Path::new("/repo/llama-cpp-bindings-sys")).len()
149            ]
150        );
151    }
152
153    #[test]
154    fn the_compiler_standard_and_fault_injection_lead_the_command_line() {
155        let commands = database_for("/unused").commands();
156
157        assert_eq!(
158            commands
159                .first()
160                .map(|command| command
161                    .arguments
162                    .iter()
163                    .take(3)
164                    .cloned()
165                    .collect::<Vec<String>>())
166                .unwrap_or_default(),
167            vec![
168                "c++".to_owned(),
169                "-std=c++17".to_owned(),
170                "-DLLAMA_RS_FAULT_INJECTION".to_owned()
171            ]
172        );
173    }
174
175    #[test]
176    fn creating_the_database_under_a_missing_directory_reports_the_path() {
177        assert_eq!(
178            database_for("/nonexistent-directory/compile_commands.json")
179                .write()
180                .err()
181                .map(|error| error.to_string()),
182            Some(
183                "compilation database file /nonexistent-directory/compile_commands.json could \
184                 not be created: No such file or directory (os error 2)"
185                    .to_owned()
186            )
187        );
188    }
189
190    #[cfg(target_os = "linux")]
191    #[test]
192    fn a_destination_that_cannot_absorb_the_bytes_reports_the_path() {
193        assert_eq!(
194            database_for("/dev/full")
195                .write()
196                .err()
197                .map(|error| error.to_string()),
198            Some(
199                "compilation database could not be written to /dev/full: No space left on \
200                 device (os error 28)"
201                    .to_owned()
202            )
203        );
204    }
205}