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