| 1 | # Use compile_commands.json and compile_flags.txt in Rust Programs |
| 2 | |
| 3 | ## Goal |
| 4 | |
| 5 | Provide a thin wrapper type around the [compile_commands.json](https://clang.llvm.org/docs/JSONCompilationDatabase.html#format) |
| 6 | and [compile_flags.txt](https://clang.llvm.org/docs/JSONCompilationDatabase.html#alternatives) |
| 7 | standards as provided by the LLVM project. |
| 8 | |
| 9 | ## Sample usage |
| 10 | |
| 11 | Given the following `compile_commands.json` file: |
| 12 | |
| 13 | ```json |
| 14 | [ |
| 15 | { "directory": "/home/user/llvm/build", |
| 16 | "arguments": ["/usr/bin/clang++", "-Irelative", "-DSOMEDEF=With spaces, quotes and \\-es.", "-c", "-o", "file.o", "file.cc"], |
| 17 | "file": "file.cc" }, |
| 18 | |
| 19 | { "directory": "/home/user/llvm/build", |
| 20 | "command": "/usr/bin/clang++ -Irelative -DSOMEDEF=\"With spaces, quotes and \\-es.\" -c -o file.o file.cc", |
| 21 | "file": "file2.cc" } |
| 22 | ] |
| 23 | |
| 24 | ``` |
| 25 | |
| 26 | Or the following `compile_flags.txt` file: |
| 27 | |
| 28 | ``` |
| 29 | -xc++ |
| 30 | -I |
| 31 | libwidget/include/ |
| 32 | ``` |
| 33 | |
| 34 | Parse it and use as a type-safe object in your Rust project: |
| 35 | |
| 36 | ```rust |
| 37 | use std::path::PathBuf; |
| 38 | |
| 39 | use compile_commands::CompilationDatabase; |
| 40 | |
| 41 | fn main() { |
| 42 | // Create a `CompilationDatabase` object directly from a compile_commands.json file |
| 43 | let comp_cmds = include_str!("compile_commands.json"); |
| 44 | let comp_data = serde_json::from_str::<CompilationDatabase>(&comp_cmds).unwrap(); |
| 45 | _ = comp_data; |
| 46 | |
| 47 | // Or create a `CompilationDatabase` object from a compile_flags.txt file |
| 48 | let comp_flags = include_str!("compile_flags.txt"); |
| 49 | let comp_data = |
| 50 | compile_commands::from_compile_flags_txt(&PathBuf::from("~/foo/build"), &comp_flags); |
| 51 | _ = comp_data; |
| 52 | } |
| 53 | ``` |
| 54 | |
| 55 | ## Usage in the Wild |
| 56 | |
| 57 | ### [asm-lsp](https://github.com/bergercookie/asm-lsp) |
| 58 | |
| 59 | Used to provide inline error diagnostics and additional per-project include directories |