compile_commands-0.3.0/.cargo_vcs_info.json0000644000000001360000000000100143450ustar { "git": { "sha1": "920061ab3848a439814e3b90152477606838ddeb" }, "path_in_vcs": "" }compile_commands-0.3.0/.github/workflows/audit.yml000064400000000000000000000010631046102023000203630ustar 00000000000000name: Security audit on: workflow_call: workflow_dispatch: schedule: - cron: "0 0 * * *" push: paths: - "**/Cargo.toml" - "**/Cargo.lock" pull_request: branches: ["main"] paths: - "**/Cargo.toml" - "**/Cargo.lock" jobs: audit: name: Security Audit runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 name: Checkout - uses: taiki-e/install-action@cargo-deny name: Install cargo-deny - name: Scan for vulnerabilities run: cargo deny check advisories compile_commands-0.3.0/.github/workflows/build.yml000064400000000000000000000011471046102023000203570ustar 00000000000000name: Build Cargo Workspace on: workflow_call: workflow_dispatch: push: branches: - "*" pull_request: branches: ["main"] env: CARGO_TERM_COLOR: always jobs: build: name: Build Cargo Workspace runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: toolchain: stable override: true - uses: Swatinem/rust-cache@v2 name: Cache dependencies - uses: actions-rs/cargo@v1 name: Build crate with: command: build args: --verbose --all-features compile_commands-0.3.0/.github/workflows/lint_and_test.yml000064400000000000000000000022731046102023000221100ustar 00000000000000name: Lint Code / Run Tests on: workflow_call: workflow_dispatch: push: branches: - "*" pull_request: branches: ["main"] concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} cancel-in-progress: true env: CARGO_TERM_COLOR: always jobs: tests: name: Run Unit Tests runs-on: ${{ matrix.os }} continue-on-error: ${{ matrix.rust == 'nightly' }} strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] rust: [1.70.0, stable, beta, nightly] steps: - name: Checkout repository uses: actions/checkout@v4 - run: rustup toolchain install ${{ matrix.rust }} --profile minimal - uses: Swatinem/rust-cache@v2 - uses: actions/setup-python@v3 - name: Set up Ruby on Windows if: runner.os == 'Windows' uses: ruby/setup-ruby@v1 with: ruby-version: '3.1' msys2: true - name: Install pre-commit dependencies run: python -m pip install pre-commit - uses: pre-commit/action@v3.0.1 name: Run pre-commit hooks - name: Run Rust tests run: cargo test compile_commands-0.3.0/.gitignore000064400000000000000000000006361046102023000151320ustar 00000000000000# Generated by Cargo # will have compiled files and executables debug/ target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk # MSVC Windows builds of rustc generate these, which store debugging information *.pdb compile_commands-0.3.0/.markdown-link-check.json000064400000000000000000000000031046102023000177270ustar 00000000000000{} compile_commands-0.3.0/.pre-commit-config.yaml000064400000000000000000000023771046102023000174270ustar 00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: "v4.4.0" hooks: - id: check-added-large-files - id: check-merge-conflict - id: check-toml - id: detect-private-key - id: end-of-file-fixer - id: mixed-line-ending - id: trailing-whitespace - repo: https://github.com/tcort/markdown-link-check rev: "v3.10.3" hooks: # https://github.com/tcort/markdown-link-check#config-file-format - id: markdown-link-check args: ["--progress", "--config", ".markdown-link-check.json"] - repo: https://github.com/markdownlint/markdownlint rev: "v0.12.0" hooks: - id: markdownlint exclude: ^.github/ entry: mdl -r ~MD033,~MD013,~MD034,~MD029,~MD007 - repo: https://github.com/python-jsonschema/check-jsonschema rev: "0.27.0" hooks: - id: check-github-workflows args: ["--verbose", "--builtin-schema", "vendor.github-workflows"] files: ^\.github/workflows/ types: [yaml] - repo: meta hooks: - id: check-hooks-apply - id: check-useless-excludes - repo: https://github.com/doublify/pre-commit-rust rev: v1.0 hooks: - id: fmt - id: cargo-check args: ["--locked"] - id: clippy compile_commands-0.3.0/Cargo.toml0000644000000023450000000000100123470ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "compile_commands" version = "0.3.0" authors = ["Will Lillis"] build = false publish = true autobins = false autoexamples = false autotests = false autobenches = false description = "Work with compile_commands.json and compile_flags.txt in Rust programs." homepage = "https://github.com/WillLillis/compile_commands" documentation = "https://docs.rs/compile_commands/latest/compile_commands/" readme = "README.md" keywords = [ "clang", "llvm", "compile", ] categories = ["development-tools"] license = "Apache-2.0" repository = "https://github.com/WillLillis/compile_commands" [lib] name = "compile_commands" path = "src/lib.rs" [dependencies.serde] version = "1.0.204" features = ["derive"] [dependencies.serde_json] version = "1.0.120" compile_commands-0.3.0/Cargo.toml.orig000064400000000000000000000011471046102023000160270ustar 00000000000000[package] name = "compile_commands" version = "0.3.0" authors = ["Will Lillis"] edition = "2021" description = "Work with compile_commands.json and compile_flags.txt in Rust programs." documentation = "https://docs.rs/compile_commands/latest/compile_commands/" homepage = "https://github.com/WillLillis/compile_commands" repository = "https://github.com/WillLillis/compile_commands" readme = "README.md" keywords = ["clang", "llvm", "compile"] categories = ["development-tools"] publish = true license = "Apache-2.0" [dependencies] serde = { version = "1.0.204", features = ["derive"] } serde_json = "1.0.120" compile_commands-0.3.0/LICENSE000064400000000000000000000261351046102023000141510ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. compile_commands-0.3.0/README.md000064400000000000000000000033051046102023000144150ustar 00000000000000# Use compile_commands.json and compile_flags.txt in Rust Programs ## Goal Provide a thin wrapper type around the [compile_commands.json](https://clang.llvm.org/docs/JSONCompilationDatabase.html#format) and [compile_flags.txt](https://clang.llvm.org/docs/JSONCompilationDatabase.html#alternatives) standards as provided by the LLVM project. ## Sample usage Given the following `compile_commands.json` file: ```json [ { "directory": "/home/user/llvm/build", "arguments": ["/usr/bin/clang++", "-Irelative", "-DSOMEDEF=With spaces, quotes and \\-es.", "-c", "-o", "file.o", "file.cc"], "file": "file.cc" }, { "directory": "/home/user/llvm/build", "command": "/usr/bin/clang++ -Irelative -DSOMEDEF=\"With spaces, quotes and \\-es.\" -c -o file.o file.cc", "file": "file2.cc" } ] ``` Or the following `compile_flags.txt` file: ``` -xc++ -I libwidget/include/ ``` Parse it and use as a type-safe object in your Rust project: ```rust use std::path::PathBuf; use compile_commands::CompilationDatabase; fn main() { // Create a `CompilationDatabase` object directly from a compile_commands.json file let comp_cmds = include_str!("compile_commands.json"); let comp_data = serde_json::from_str::(&comp_cmds).unwrap(); _ = comp_data; // Or create a `CompilationDatabase` object from a compile_flags.txt file let comp_flags = include_str!("compile_flags.txt"); let comp_data = compile_commands::from_compile_flags_txt(&PathBuf::from("~/foo/build"), &comp_flags); _ = comp_data; } ``` ## Usage in the Wild ### [asm-lsp](https://github.com/bergercookie/asm-lsp) Used to provide inline error diagnostics and additional per-project include directories compile_commands-0.3.0/src/lib.rs000064400000000000000000000230611046102023000150420ustar 00000000000000use std::fmt::{self, Display}; use std::path::{Path, PathBuf}; use std::string::ToString; use serde::de::{self, Deserializer, Error as SerdeError, Visitor}; use serde::Deserialize; /// Represents a `compile_commands.json` file pub type CompilationDatabase = Vec; /// `All` if `CompilationDatabase` is generated from a `compile_flags.txt` file, /// otherwise `File()` containing the `file` field from a `compile_commands.json` /// entry #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum SourceFile { All, File(PathBuf), } impl<'de> Deserialize<'de> for SourceFile { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { #[allow(dead_code)] struct SourceFileVisitor; impl<'de> Visitor<'de> for SourceFileVisitor { type Value = SourceFile; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string representing a file path") } fn visit_str(self, value: &str) -> Result where E: SerdeError, { Ok(SourceFile::File(PathBuf::from(value))) } } match serde_json::Value::deserialize(deserializer)? { serde_json::Value::String(s) => Ok(SourceFile::File(PathBuf::from(s))), _ => Err(SerdeError::custom("expected a string")), } } } /// The `arguments` field in a `compile_commands.json` file can be invoked as is, /// whereas the flags from a `compile_flags.txt` file must be invoked with a compiler, /// e.g. gcc @compile_flags.txt. Because the `CompileCommand` struct is used to /// represent both file types, we utilize a tagged union here to differentitate /// between the two files #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum CompileArgs { Arguments(Vec), Flags(Vec), } impl<'de> Deserialize<'de> for CompileArgs { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { #[allow(dead_code)] struct CompileArgVisitor; impl<'de> Visitor<'de> for CompileArgVisitor { type Value = CompileArgs; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string representing a command line argument") } fn visit_seq(self, mut seq: A) -> Result where A: de::SeqAccess<'de>, { let mut args = Vec::new(); while let Some(arg) = seq.next_element::()? { args.push(arg); } Ok(CompileArgs::Arguments(args)) } } deserializer.deserialize_seq(CompileArgVisitor) } } /// Represents a single entry within a `compile_commands.json` file, or a compile_flags.txt file /// Either `arguments` or `command` is required. `arguments` is preferred, as shell (un)escaping /// is a possible source of errors. /// /// See: #[derive(Debug, Clone, Deserialize)] pub struct CompileCommand { /// The working directory of the compilation. All paths specified in the `command` /// or `file` fields must be either absolute or relative to this directory. pub directory: PathBuf, /// The main translation unit source processed by this compilation step. This /// is used by tools as the key into the compilation database. There can be /// multiple command objects for the same file, for example if the same source /// file is compiled with different configurations. pub file: SourceFile, /// The compile command argv as list of strings. This should run the compilation /// step for the translation unit file. arguments[0] should be the executable /// name, such as clang++. Arguments should not be escaped, but ready to pass /// to execvp(). pub arguments: Option, /// The compile command as a single shell-escaped string. Arguments may be /// shell quoted and escaped following platform conventions, with ‘"’ and ‘\’ /// being the only special characters. Shell expansion is not supported. pub command: Option, /// The name of the output created by this compilation step. This field is optional. /// It can be used to distinguish different processing modes of the same input /// file. pub output: Option, } impl Display for CompileCommand { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "{{ \"directory\": \"{}\",", self.directory.display())?; match &self.arguments { Some(CompileArgs::Arguments(arguments)) => { write!(f, "\"arguments\": [")?; if arguments.is_empty() { writeln!(f, "],")?; } else { for arg in arguments.iter().take(arguments.len() - 1) { writeln!(f, "\"{arg}\", ")?; } writeln!(f, "\"{}\"],", arguments[arguments.len() - 1])?; } } Some(CompileArgs::Flags(flags)) => { write!(f, "\"flags\": [")?; if flags.is_empty() { writeln!(f, "],")?; } else { for flag in flags.iter().take(flags.len() - 1) { writeln!(f, "\"{flag}\", ")?; } writeln!(f, "\"{}\"],", flags[flags.len() - 1])?; } } None => {} } if let Some(command) = &self.command { write!(f, "\"command\": \"{command}\"")?; } if let Some(output) = &self.output { writeln!(f, "\"output\": \"{}\"", output.display())?; } match &self.file { SourceFile::All => write!(f, "\"file\": all }}")?, SourceFile::File(file) => write!(f, "\"file\": \"{}\" }}", file.display())?, } Ok(()) } } impl CompileCommand { /// Transforms the command field, if present, into a `Vec` of equivalent /// arguments /// /// Replaces escaped '"' and '\' characters with their respective literals pub fn args_from_cmd(&self) -> Option> { let escaped = if let Some(ref cmd) = self.command { // "Arguments may be shell quoted and escaped following platform conventions, // with ‘"’ and ‘\’ being the only special characters." cmd.trim().replace("\\\\", "\\").replace("\\\"", "\"") } else { return None; }; let mut args = Vec::new(); let mut start: usize = 0; let mut end: usize = 0; let mut in_quotes = false; for c in escaped.chars() { if c == '"' { in_quotes = !in_quotes; end += 1; } else if c.is_whitespace() && !in_quotes && start != end { args.push(escaped[start..end].to_string()); end += 1; start = end; } else { end += 1; } } if start != end { args.push(escaped[start..end].to_string()); } Some(args) } } /// For simple projects, Clang tools also recognize a `compile_flags.txt` file. /// This should contain one argument per line. The same flags will be used to /// compile any file. /// /// See: /// /// This helper allows you to translate the contents of a `compile_flags.txt` file /// to a `CompilationDatabase` object #[must_use] pub fn from_compile_flags_txt(directory: &Path, contents: &str) -> CompilationDatabase { let args = CompileArgs::Flags(contents.lines().map(ToString::to_string).collect()); vec![CompileCommand { directory: directory.to_path_buf(), file: SourceFile::All, arguments: Some(args), command: None, output: None, }] } #[cfg(test)] mod tests { use super::*; fn test_args_from_cmd(comp_cmd: &CompileCommand, expected_args: &Vec<&str>) { let translated_args = comp_cmd.args_from_cmd().unwrap(); assert!(expected_args.len() == translated_args.len()); for (expected, actual) in expected_args.iter().zip(translated_args.iter()) { assert!(expected == actual); } } #[test] fn it_translates_args_from_empty_cmd() { let comp_cmd = CompileCommand { directory: PathBuf::new(), file: SourceFile::All, arguments: None, command: Some(String::from("")), output: None, }; let expected_args: Vec<&str> = Vec::new(); test_args_from_cmd(&comp_cmd, &expected_args); } #[test] fn it_translates_args_from_cmd_1() { let comp_cmd = CompileCommand { directory: PathBuf::new(), file: SourceFile::All, arguments: None, command: Some(String::from( r#"/usr/bin/clang++ -Irelative -DSOMEDEF=\"With spaces, quotes and \\-es.\" -c -o file.o file.cc"#, )), output: None, }; let expected_args: Vec<&str> = vec![ "/usr/bin/clang++", "-Irelative", r#"-DSOMEDEF="With spaces, quotes and \-es.""#, "-c", "-o", "file.o", "file.cc", ]; test_args_from_cmd(&comp_cmd, &expected_args); } }