├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .rustfmt.toml ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── clippy.toml ├── src └── lib.rs └── tests ├── workspace_deps.rs └── workspace_deps ├── Cargo.toml ├── my-cool-dep ├── Cargo.toml └── src │ └── lib.rs ├── src └── lib.rs └── test-crate ├── Cargo.toml └── src └── lib.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | test: 14 | name: cargo test 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v2 18 | - uses: dtolnay/rust-toolchain@stable 19 | - run: cargo test --all 20 | msrv: 21 | name: "Check MSRV: 1.67.0" 22 | runs-on: ubuntu-latest 23 | steps: 24 | - name: Checkout repository 25 | uses: actions/checkout@v4 26 | - name: Install Rust 27 | uses: dtolnay/rust-toolchain@stable 28 | with: 29 | toolchain: 1.67.0 # MSRV 30 | - uses: Swatinem/rust-cache@v2 31 | - name: Default features 32 | run: cargo test --all 33 | rustfmt: 34 | name: rustfmt 35 | runs-on: ubuntu-latest 36 | steps: 37 | - name: Checkout repository 38 | uses: actions/checkout@v4 39 | - name: Install Rust 40 | uses: dtolnay/rust-toolchain@nightly 41 | with: 42 | toolchain: nightly 43 | components: rustfmt 44 | - uses: Swatinem/rust-cache@v2 45 | - name: Check formatting 46 | run: cargo fmt --all -- --check 47 | clippy: 48 | name: cargo clippy (forbidden methods) 49 | runs-on: ubuntu-latest 50 | steps: 51 | - uses: actions/checkout@v2 52 | - uses: dtolnay/rust-toolchain@stable 53 | # We just use clippy to spot forbidden methods. 54 | # We disable the default lint set which has much questionable output. 55 | - run: cargo clippy --all -- -A clippy::all -D clippy::disallowed_methods 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | default.nix 2 | .envrc 3 | .direnv 4 | target 5 | Cargo.lock 6 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | edition = "2021" 3 | max_width = 100 4 | use_small_heuristics = "Max" 5 | # Imports 6 | imports_granularity = "Crate" 7 | reorder_imports = true 8 | # Consistency 9 | newline_style = "Unix" 10 | # Misc 11 | chain_width = 80 12 | spaces_around_ranges = false 13 | binop_separator = "Back" 14 | reorder_impl_items = false 15 | match_arm_leading_pipes = "Preserve" 16 | match_arm_blocks = false 17 | match_block_trailing_comma = true 18 | trailing_comma = "Vertical" 19 | trailing_semicolon = false 20 | use_field_init_shorthand = true 21 | # Format comments 22 | comment_width = 100 23 | wrap_comments = true 24 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | cache: cargo 4 | 5 | rust: 6 | - stable 7 | - beta 8 | - nightly 9 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "proc-macro-crate" 3 | version = "3.3.0" 4 | authors = ["Bastian Köcher "] 5 | edition = "2021" 6 | categories = ["development-tools::procedural-macro-helpers"] 7 | documentation = "https://docs.rs/proc-macro-crate" 8 | repository = "https://github.com/bkchr/proc-macro-crate" 9 | keywords = ["macro-rules", "crate", "macro", "proc-macro"] 10 | license = "MIT OR Apache-2.0" 11 | description = """ 12 | Replacement for crate (macro_rules keyword) in proc-macros 13 | """ 14 | readme = "./README.md" 15 | rust-version = "1.67.0" 16 | 17 | [dependencies] 18 | toml_edit = { version = "0.22.24", default-features = false, features = [ 19 | "parse", 20 | ] } 21 | 22 | [dev-dependencies] 23 | quote = "1.0.39" 24 | syn = "2.0.99" 25 | proc-macro2 = "1.0.94" 26 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://www.apache.org/licenses/LICENSE-2.0 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | https://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # proc-macro-crate 2 | 3 | 4 | [![](https://docs.rs/proc-macro-crate/badge.svg)](https://docs.rs/proc-macro-crate/) [![](https://img.shields.io/crates/v/proc-macro-crate.svg)](https://crates.io/crates/proc-macro-crate) [![](https://img.shields.io/crates/d/proc-macro-crate.png)](https://crates.io/crates/proc-macro-crate) [![Build Status](https://travis-ci.org/bkchr/proc-macro-crate.png?branch=master)](https://travis-ci.org/bkchr/proc-macro-crate) 5 | 6 | Providing support for `$crate` in procedural macros. 7 | 8 | * [Introduction](#introduction) 9 | * [Example](#example) 10 | * [License](#license) 11 | 12 | ### Introduction 13 | 14 | In `macro_rules!` `$crate` is used to get the path of the crate where a macro is declared in. In 15 | procedural macros there is currently no easy way to get this path. A common hack is to import the 16 | desired crate with a know name and use this. However, with rust edition 2018 and dropping 17 | `extern crate` declarations from `lib.rs`, people start to rename crates in `Cargo.toml` directly. 18 | However, this breaks importing the crate, as the proc-macro developer does not know the renamed 19 | name of the crate that should be imported. 20 | 21 | This crate provides a way to get the name of a crate, even if it renamed in `Cargo.toml`. For this 22 | purpose a single function `crate_name` is provided. This function needs to be called in the context 23 | of a proc-macro with the name of the desired crate. `CARGO_MANIFEST_DIR` will be used to find the 24 | current active `Cargo.toml` and this `Cargo.toml` is searched for the desired crate. 25 | 26 | ### Example 27 | 28 | ```rust 29 | use quote::quote; 30 | use syn::Ident; 31 | use proc_macro2::Span; 32 | use proc_macro_crate::{crate_name, FoundCrate}; 33 | 34 | fn import_my_crate() { 35 | let found_crate = crate_name("my-crate").expect("my-crate is present in `Cargo.toml`"); 36 | 37 | match found_crate { 38 | FoundCrate::Itself => quote!( crate::Something ), 39 | FoundCrate::Name(name) => { 40 | let ident = Ident::new(&name, Span::call_site()); 41 | quote!( #ident::Something ) 42 | } 43 | }; 44 | } 45 | 46 | ``` 47 | 48 | ### Edge cases 49 | 50 | There are multiple edge cases when it comes to determining the correct crate. If you for example 51 | import a crate as its own dependency, like this: 52 | 53 | ```toml 54 | [package] 55 | name = "my_crate" 56 | 57 | [dev-dependencies] 58 | my_crate = { version = "0.1", features = [ "test-feature" ] } 59 | ``` 60 | 61 | The crate will return `FoundCrate::Itself` and you will not be able to find the other instance 62 | of your crate in `dev-dependencies`. Other similar cases are when one crate is imported multiple 63 | times: 64 | 65 | ```toml 66 | [package] 67 | name = "my_crate" 68 | 69 | [dependencies] 70 | some-crate = { version = "0.5" } 71 | some-crate-old = { package = "some-crate", version = "0.1" } 72 | ``` 73 | 74 | When searching for `some-crate` in this `Cargo.toml` it will return `FoundCrate::Name("some_old_crate")`, 75 | aka the last definition of the crate in the `Cargo.toml`. 76 | 77 | ### License 78 | 79 | Licensed under either of 80 | 81 | * [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) 82 | 83 | * [MIT license](https://opensource.org/licenses/MIT) 84 | 85 | at your option. 86 | 87 | License: MIT OR Apache-2.0 88 | -------------------------------------------------------------------------------- /clippy.toml: -------------------------------------------------------------------------------- 1 | disallowed-methods = [ 2 | # Avoid a repeat of https://github.com/bkchr/proc-macro-crate/issues/57 3 | { path = "toml_edit::Item::as_table", reason = "Use .as_table_like instead!" }, 4 | { path = "toml_edit::Item::is_table", reason = "Use .is_table_like instead!" }, 5 | ] 6 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | 3 | [![](https://docs.rs/proc-macro-crate/badge.svg)](https://docs.rs/proc-macro-crate/) [![](https://img.shields.io/crates/v/proc-macro-crate.svg)](https://crates.io/crates/proc-macro-crate) [![](https://img.shields.io/crates/d/proc-macro-crate.png)](https://crates.io/crates/proc-macro-crate) [![Build Status](https://travis-ci.org/bkchr/proc-macro-crate.png?branch=master)](https://travis-ci.org/bkchr/proc-macro-crate) 4 | 5 | Providing support for `$crate` in procedural macros. 6 | 7 | * [Introduction](#introduction) 8 | * [Example](#example) 9 | * [License](#license) 10 | 11 | ## Introduction 12 | 13 | In `macro_rules!` `$crate` is used to get the path of the crate where a macro is declared in. In 14 | procedural macros there is currently no easy way to get this path. A common hack is to import the 15 | desired crate with a know name and use this. However, with rust edition 2018 and dropping 16 | `extern crate` declarations from `lib.rs`, people start to rename crates in `Cargo.toml` directly. 17 | However, this breaks importing the crate, as the proc-macro developer does not know the renamed 18 | name of the crate that should be imported. 19 | 20 | This crate provides a way to get the name of a crate, even if it renamed in `Cargo.toml`. For this 21 | purpose a single function `crate_name` is provided. This function needs to be called in the context 22 | of a proc-macro with the name of the desired crate. `CARGO_MANIFEST_DIR` will be used to find the 23 | current active `Cargo.toml` and this `Cargo.toml` is searched for the desired crate. 24 | 25 | ## Example 26 | 27 | ``` 28 | use quote::quote; 29 | use syn::Ident; 30 | use proc_macro2::Span; 31 | use proc_macro_crate::{crate_name, FoundCrate}; 32 | 33 | fn import_my_crate() { 34 | let found_crate = crate_name("my-crate").expect("my-crate is present in `Cargo.toml`"); 35 | 36 | match found_crate { 37 | FoundCrate::Itself => quote!( crate::Something ), 38 | FoundCrate::Name(name) => { 39 | let ident = Ident::new(&name, Span::call_site()); 40 | quote!( #ident::Something ) 41 | } 42 | }; 43 | } 44 | 45 | # fn main() {} 46 | ``` 47 | 48 | ## Edge cases 49 | 50 | There are multiple edge cases when it comes to determining the correct crate. If you for example 51 | import a crate as its own dependency, like this: 52 | 53 | ```toml 54 | [package] 55 | name = "my_crate" 56 | 57 | [dev-dependencies] 58 | my_crate = { version = "0.1", features = [ "test-feature" ] } 59 | ``` 60 | 61 | The crate will return `FoundCrate::Itself` and you will not be able to find the other instance 62 | of your crate in `dev-dependencies`. Other similar cases are when one crate is imported multiple 63 | times: 64 | 65 | ```toml 66 | [package] 67 | name = "my_crate" 68 | 69 | [dependencies] 70 | some-crate = { version = "0.5" } 71 | some-crate-old = { package = "some-crate", version = "0.1" } 72 | ``` 73 | 74 | When searching for `some-crate` in this `Cargo.toml` it will return `FoundCrate::Name("some_old_crate")`, 75 | aka the last definition of the crate in the `Cargo.toml`. 76 | 77 | ## License 78 | 79 | Licensed under either of 80 | 81 | * [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) 82 | 83 | * [MIT license](https://opensource.org/licenses/MIT) 84 | 85 | at your option. 86 | */ 87 | 88 | use std::{ 89 | collections::btree_map::{self, BTreeMap}, 90 | env, fmt, fs, io, 91 | path::{Path, PathBuf}, 92 | process::Command, 93 | sync::Mutex, 94 | time::SystemTime, 95 | }; 96 | 97 | use toml_edit::{DocumentMut, Item, TableLike, TomlError}; 98 | 99 | /// Error type used by this crate. 100 | pub enum Error { 101 | NotFound(PathBuf), 102 | CargoManifestDirNotSet, 103 | FailedGettingWorkspaceManifestPath, 104 | CouldNotRead { path: PathBuf, source: io::Error }, 105 | InvalidToml { source: TomlError }, 106 | CrateNotFound { crate_name: String, path: PathBuf }, 107 | } 108 | 109 | impl std::error::Error for Error { 110 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { 111 | match self { 112 | Error::CouldNotRead { source, .. } => Some(source), 113 | Error::InvalidToml { source } => Some(source), 114 | _ => None, 115 | } 116 | } 117 | } 118 | 119 | impl fmt::Debug for Error { 120 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 121 | fmt::Display::fmt(self, f) 122 | } 123 | } 124 | 125 | impl fmt::Display for Error { 126 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 127 | match self { 128 | Error::NotFound(path) => 129 | write!(f, "Could not find `Cargo.toml` in manifest dir: `{}`.", path.display()), 130 | Error::CargoManifestDirNotSet => 131 | f.write_str("`CARGO_MANIFEST_DIR` env variable not set."), 132 | Error::CouldNotRead { path, .. } => write!(f, "Could not read `{}`.", path.display()), 133 | Error::InvalidToml { .. } => f.write_str("Invalid toml file."), 134 | Error::CrateNotFound { crate_name, path } => write!( 135 | f, 136 | "Could not find `{}` in `dependencies` or `dev-dependencies` in `{}`!", 137 | crate_name, 138 | path.display(), 139 | ), 140 | Error::FailedGettingWorkspaceManifestPath => 141 | f.write_str("Failed to get the path of the workspace manifest path."), 142 | } 143 | } 144 | } 145 | 146 | /// The crate as found by [`crate_name`]. 147 | #[derive(Debug, PartialEq, Clone, Eq)] 148 | pub enum FoundCrate { 149 | /// The searched crate is this crate itself. 150 | Itself, 151 | /// The searched crate was found with this name. 152 | Name(String), 153 | } 154 | 155 | // In a rustc invocation, there will only ever be one entry in this map, since every crate is 156 | // compiled with its own rustc process. However, the same is not (currently) the case for 157 | // rust-analyzer. 158 | type Cache = BTreeMap; 159 | 160 | struct CacheEntry { 161 | manifest_ts: SystemTime, 162 | workspace_manifest_ts: SystemTime, 163 | workspace_manifest_path: PathBuf, 164 | crate_names: CrateNames, 165 | } 166 | 167 | type CrateNames = BTreeMap; 168 | 169 | /// Find the crate name for the given `orig_name` in the current `Cargo.toml`. 170 | /// 171 | /// `orig_name` should be the original name of the searched crate. 172 | /// 173 | /// The current `Cargo.toml` is determined by taking `CARGO_MANIFEST_DIR/Cargo.toml`. 174 | /// 175 | /// # Returns 176 | /// 177 | /// - `Ok(FoundCrate::Itself)` the searched crate is the current crate being compiled. 178 | /// - `Ok(FoundCrate::Name(new_name))` the searched create was found with the given name in the `Cargo.toml`. 179 | /// - `Err` if an error occurred. See [`Error`]. 180 | /// 181 | /// The returned crate name is sanitized in such a way that it is a valid rust identifier. Thus, 182 | /// it is ready to be used in `extern crate` as identifier. 183 | pub fn crate_name(orig_name: &str) -> Result { 184 | let manifest_dir = env::var("CARGO_MANIFEST_DIR").map_err(|_| Error::CargoManifestDirNotSet)?; 185 | let manifest_path = Path::new(&manifest_dir).join("Cargo.toml"); 186 | 187 | let manifest_ts = cargo_toml_timestamp(&manifest_path)?; 188 | 189 | static CACHE: Mutex = Mutex::new(BTreeMap::new()); 190 | let mut cache = CACHE.lock().unwrap(); 191 | 192 | let crate_names = match cache.entry(manifest_dir) { 193 | btree_map::Entry::Occupied(entry) => { 194 | let cache_entry = entry.into_mut(); 195 | let workspace_manifest_path = cache_entry.workspace_manifest_path.as_path(); 196 | let workspace_manifest_ts = cargo_toml_timestamp(&workspace_manifest_path)?; 197 | 198 | // Timestamp changed, rebuild this cache entry. 199 | if manifest_ts != cache_entry.manifest_ts || 200 | workspace_manifest_ts != cache_entry.workspace_manifest_ts 201 | { 202 | *cache_entry = read_cargo_toml( 203 | &manifest_path, 204 | &workspace_manifest_path, 205 | manifest_ts, 206 | workspace_manifest_ts, 207 | )?; 208 | } 209 | 210 | &cache_entry.crate_names 211 | }, 212 | btree_map::Entry::Vacant(entry) => { 213 | // If `workspace_manifest_path` returns `None`, we are probably in a vendored deps 214 | // folder and cargo complaining that we have some package inside a workspace, that isn't 215 | // part of the workspace. In this case we just use the `manifest_path` as the 216 | // `workspace_manifest_path`. 217 | let workspace_manifest_path = 218 | workspace_manifest_path(&manifest_path)?.unwrap_or_else(|| manifest_path.clone()); 219 | let workspace_manifest_ts = cargo_toml_timestamp(&workspace_manifest_path)?; 220 | 221 | let cache_entry = entry.insert(read_cargo_toml( 222 | &manifest_path, 223 | &workspace_manifest_path, 224 | manifest_ts, 225 | workspace_manifest_ts, 226 | )?); 227 | &cache_entry.crate_names 228 | }, 229 | }; 230 | 231 | Ok(crate_names 232 | .get(orig_name) 233 | .ok_or_else(|| Error::CrateNotFound { 234 | crate_name: orig_name.to_owned(), 235 | path: manifest_path, 236 | })? 237 | .clone()) 238 | } 239 | 240 | fn workspace_manifest_path(cargo_toml_manifest: &Path) -> Result, Error> { 241 | let Ok(cargo) = env::var("CARGO") else { 242 | return Ok(None); 243 | }; 244 | 245 | let stdout = Command::new(cargo) 246 | .arg("locate-project") 247 | .args(&["--workspace", "--message-format=plain"]) 248 | .arg(format!("--manifest-path={}", cargo_toml_manifest.display())) 249 | .output() 250 | .map_err(|_| Error::FailedGettingWorkspaceManifestPath)? 251 | .stdout; 252 | 253 | String::from_utf8(stdout) 254 | .map_err(|_| Error::FailedGettingWorkspaceManifestPath) 255 | .map(|s| { 256 | let path = s.trim(); 257 | 258 | if path.is_empty() { 259 | None 260 | } else { 261 | Some(path.into()) 262 | } 263 | }) 264 | } 265 | 266 | fn cargo_toml_timestamp(manifest_path: &Path) -> Result { 267 | fs::metadata(manifest_path).and_then(|meta| meta.modified()).map_err(|source| { 268 | if source.kind() == io::ErrorKind::NotFound { 269 | Error::NotFound(manifest_path.to_owned()) 270 | } else { 271 | Error::CouldNotRead { path: manifest_path.to_owned(), source } 272 | } 273 | }) 274 | } 275 | 276 | fn read_cargo_toml( 277 | manifest_path: &Path, 278 | workspace_manifest_path: &Path, 279 | manifest_ts: SystemTime, 280 | workspace_manifest_ts: SystemTime, 281 | ) -> Result { 282 | let manifest = open_cargo_toml(manifest_path)?; 283 | 284 | let workspace_dependencies = if manifest_path != workspace_manifest_path { 285 | let workspace_manifest = open_cargo_toml(workspace_manifest_path)?; 286 | extract_workspace_dependencies(&workspace_manifest)? 287 | } else { 288 | extract_workspace_dependencies(&manifest)? 289 | }; 290 | 291 | let crate_names = extract_crate_names(&manifest, workspace_dependencies)?; 292 | 293 | Ok(CacheEntry { 294 | manifest_ts, 295 | workspace_manifest_ts, 296 | crate_names, 297 | workspace_manifest_path: workspace_manifest_path.to_path_buf(), 298 | }) 299 | } 300 | 301 | /// Extract all `[workspace.dependencies]`. 302 | /// 303 | /// Returns a hash map that maps from dep name to the package name. Dep name 304 | /// and package name can be the same if there doesn't exist any rename. 305 | fn extract_workspace_dependencies( 306 | workspace_toml: &DocumentMut, 307 | ) -> Result, Error> { 308 | Ok(workspace_dep_tables(&workspace_toml) 309 | .into_iter() 310 | .map(|t| t.iter()) 311 | .flatten() 312 | .map(move |(dep_name, dep_value)| { 313 | let pkg_name = dep_value.get("package").and_then(|i| i.as_str()).unwrap_or(dep_name); 314 | 315 | (dep_name.to_owned(), pkg_name.to_owned()) 316 | }) 317 | .collect()) 318 | } 319 | 320 | /// Return an iterator over all `[workspace.dependencies]` 321 | fn workspace_dep_tables(cargo_toml: &DocumentMut) -> Option<&dyn TableLike> { 322 | cargo_toml 323 | .get("workspace") 324 | .and_then(|w| w.as_table_like()?.get("dependencies")?.as_table_like()) 325 | } 326 | 327 | /// Make sure that the given crate name is a valid rust identifier. 328 | fn sanitize_crate_name>(name: S) -> String { 329 | name.as_ref().replace('-', "_") 330 | } 331 | 332 | /// Open the given `Cargo.toml` and parse it into a hashmap. 333 | fn open_cargo_toml(path: &Path) -> Result { 334 | let content = fs::read_to_string(path) 335 | .map_err(|e| Error::CouldNotRead { source: e, path: path.into() })?; 336 | content.parse::().map_err(|e| Error::InvalidToml { source: e }) 337 | } 338 | 339 | /// Extract all crate names from the given `Cargo.toml` by checking the `dependencies` and 340 | /// `dev-dependencies`. 341 | fn extract_crate_names( 342 | cargo_toml: &DocumentMut, 343 | workspace_dependencies: BTreeMap, 344 | ) -> Result { 345 | let package_name = extract_package_name(cargo_toml); 346 | let root_pkg = package_name.as_ref().map(|name| { 347 | let cr = match env::var_os("CARGO_TARGET_TMPDIR") { 348 | // We're running for a library/binary crate 349 | None => FoundCrate::Itself, 350 | // We're running for an integration test 351 | Some(_) => FoundCrate::Name(sanitize_crate_name(name)), 352 | }; 353 | 354 | (name.to_string(), cr) 355 | }); 356 | 357 | let dep_tables = dep_tables(cargo_toml.as_table()).chain(target_dep_tables(cargo_toml)); 358 | let dep_pkgs = 359 | dep_tables.map(|t| t.iter()).flatten().filter_map(move |(dep_name, dep_value)| { 360 | let pkg_name = dep_value.get("package").and_then(|i| i.as_str()).unwrap_or(dep_name); 361 | 362 | // We already handle this via `root_pkg` above. 363 | if package_name.as_ref().map_or(false, |n| *n == pkg_name) { 364 | return None 365 | } 366 | 367 | // Check if this is a workspace dependency. 368 | let workspace = 369 | dep_value.get("workspace").and_then(|w| w.as_bool()).unwrap_or_default(); 370 | 371 | let pkg_name = workspace 372 | .then(|| workspace_dependencies.get(pkg_name).map(|p| p.as_ref())) 373 | .flatten() 374 | .unwrap_or(pkg_name); 375 | 376 | let cr = FoundCrate::Name(sanitize_crate_name(dep_name)); 377 | 378 | Some((pkg_name.to_owned(), cr)) 379 | }); 380 | 381 | Ok(root_pkg.into_iter().chain(dep_pkgs).collect()) 382 | } 383 | 384 | fn extract_package_name(cargo_toml: &DocumentMut) -> Option<&str> { 385 | cargo_toml.get("package")?.get("name")?.as_str() 386 | } 387 | 388 | fn target_dep_tables(cargo_toml: &DocumentMut) -> impl Iterator { 389 | cargo_toml 390 | .get("target") 391 | .into_iter() 392 | .filter_map(Item::as_table_like) 393 | .flat_map(|t| { 394 | t.iter() 395 | .map(|(_, value)| value) 396 | .filter_map(Item::as_table_like) 397 | .flat_map(dep_tables) 398 | }) 399 | } 400 | 401 | fn dep_tables(table: &dyn TableLike) -> impl Iterator { 402 | table 403 | .get("dependencies") 404 | .into_iter() 405 | .chain(table.get("dev-dependencies")) 406 | .filter_map(Item::as_table_like) 407 | } 408 | 409 | #[cfg(test)] 410 | mod tests { 411 | use super::*; 412 | 413 | macro_rules! create_test { 414 | ( 415 | $name:ident, 416 | $cargo_toml:expr, 417 | $workspace_toml:expr, 418 | $( $result:tt )* 419 | ) => { 420 | #[test] 421 | fn $name() { 422 | let cargo_toml = $cargo_toml.parse::() 423 | .expect("Parses `Cargo.toml`"); 424 | let workspace_cargo_toml = $workspace_toml.parse::() 425 | .expect("Parses workspace `Cargo.toml`"); 426 | 427 | let workspace_deps = extract_workspace_dependencies(&workspace_cargo_toml) 428 | .expect("Extracts workspace dependencies"); 429 | 430 | match extract_crate_names(&cargo_toml, workspace_deps) 431 | .map(|mut map| map.remove("my_crate")) 432 | { 433 | $( $result )* => (), 434 | o => panic!("Invalid result: {:?}", o), 435 | } 436 | } 437 | }; 438 | } 439 | 440 | create_test! { 441 | deps_with_crate, 442 | r#" 443 | [dependencies] 444 | my_crate = "0.1" 445 | "#, 446 | "", 447 | Ok(Some(FoundCrate::Name(name))) if name == "my_crate" 448 | } 449 | 450 | // forbidding toml_edit::Item::as_table ought to mean this is OK, but let's have a test too 451 | create_test! { 452 | deps_with_crate_inline_table, 453 | r#" 454 | dependencies = { my_crate = "0.1" } 455 | "#, 456 | "", 457 | Ok(Some(FoundCrate::Name(name))) if name == "my_crate" 458 | } 459 | 460 | create_test! { 461 | dev_deps_with_crate, 462 | r#" 463 | [dev-dependencies] 464 | my_crate = "0.1" 465 | "#, 466 | "", 467 | Ok(Some(FoundCrate::Name(name))) if name == "my_crate" 468 | } 469 | 470 | create_test! { 471 | deps_with_crate_renamed, 472 | r#" 473 | [dependencies] 474 | cool = { package = "my_crate", version = "0.1" } 475 | "#, 476 | "", 477 | Ok(Some(FoundCrate::Name(name))) if name == "cool" 478 | } 479 | 480 | create_test! { 481 | deps_with_crate_renamed_second, 482 | r#" 483 | [dependencies.cool] 484 | package = "my_crate" 485 | version = "0.1" 486 | "#, 487 | "", 488 | Ok(Some(FoundCrate::Name(name))) if name == "cool" 489 | } 490 | 491 | create_test! { 492 | deps_empty, 493 | r#" 494 | [dependencies] 495 | "#, 496 | "", 497 | Ok(None) 498 | } 499 | 500 | create_test! { 501 | crate_not_found, 502 | r#" 503 | [dependencies] 504 | serde = "1.0" 505 | "#, 506 | "", 507 | Ok(None) 508 | } 509 | 510 | create_test! { 511 | target_dependency, 512 | r#" 513 | [target.'cfg(target_os="android")'.dependencies] 514 | my_crate = "0.1" 515 | "#, 516 | "", 517 | Ok(Some(FoundCrate::Name(name))) if name == "my_crate" 518 | } 519 | 520 | create_test! { 521 | target_dependency2, 522 | r#" 523 | [target.x86_64-pc-windows-gnu.dependencies] 524 | my_crate = "0.1" 525 | "#, 526 | "", 527 | Ok(Some(FoundCrate::Name(name))) if name == "my_crate" 528 | } 529 | 530 | create_test! { 531 | own_crate, 532 | r#" 533 | [package] 534 | name = "my_crate" 535 | "#, 536 | "", 537 | Ok(Some(FoundCrate::Itself)) 538 | } 539 | 540 | create_test! { 541 | own_crate_and_in_deps, 542 | r#" 543 | [package] 544 | name = "my_crate" 545 | 546 | [dev-dependencies] 547 | my_crate = "0.1" 548 | "#, 549 | "", 550 | Ok(Some(FoundCrate::Itself)) 551 | } 552 | 553 | create_test! { 554 | multiple_times, 555 | r#" 556 | [dependencies] 557 | my_crate = { version = "0.5" } 558 | my-crate-old = { package = "my_crate", version = "0.1" } 559 | "#, 560 | "", 561 | Ok(Some(FoundCrate::Name(name))) if name == "my_crate_old" 562 | } 563 | 564 | create_test! { 565 | workspace_deps, 566 | r#" 567 | [dependencies] 568 | my_crate_cool = { workspace = true } 569 | "#, 570 | r#" 571 | [workspace.dependencies] 572 | my_crate_cool = { package = "my_crate" } 573 | "#, 574 | Ok(Some(FoundCrate::Name(name))) if name == "my_crate_cool" 575 | } 576 | } 577 | -------------------------------------------------------------------------------- /tests/workspace_deps.rs: -------------------------------------------------------------------------------- 1 | use std::{path::PathBuf, process::Command}; 2 | 3 | #[test] 4 | fn workspace_deps_working() { 5 | let manifest_dir = 6 | PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/workspace_deps/Cargo.toml"); 7 | 8 | assert!(Command::new("cargo") 9 | .arg("build") 10 | .arg("--all") 11 | .arg(format!("--manifest-path={}", manifest_dir.display())) 12 | .spawn() 13 | .unwrap() 14 | .wait() 15 | .unwrap() 16 | .success()); 17 | } 18 | -------------------------------------------------------------------------------- /tests/workspace_deps/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test-workspace-root-crate" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [workspace] 7 | members = ["my-cool-dep", "test-crate"] 8 | resolver = "2" 9 | 10 | 11 | [workspace.dependencies] 12 | my-cool-dep = { package = "my-cool-dep-real-name", path = "my-cool-dep" } 13 | proc-macro-crate = { path = "../.." } 14 | 15 | [dependencies] 16 | my-cool-dep = { workspace = true } 17 | -------------------------------------------------------------------------------- /tests/workspace_deps/my-cool-dep/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "my-cool-dep-real-name" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | proc-macro = true 8 | 9 | [dependencies] 10 | proc-macro-crate = { workspace = true } 11 | -------------------------------------------------------------------------------- /tests/workspace_deps/my-cool-dep/src/lib.rs: -------------------------------------------------------------------------------- 1 | use proc_macro::TokenStream; 2 | 3 | #[proc_macro] 4 | pub fn do_something(input: TokenStream) -> TokenStream { 5 | let found_crate = 6 | proc_macro_crate::crate_name("my-cool-dep-real-name").expect("Couldn't find the crate"); 7 | 8 | assert_eq!(proc_macro_crate::FoundCrate::Name("my_cool_dep".into()), found_crate); 9 | 10 | input 11 | } 12 | -------------------------------------------------------------------------------- /tests/workspace_deps/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn use_it() { 2 | my_cool_dep::do_something!() 3 | } 4 | -------------------------------------------------------------------------------- /tests/workspace_deps/test-crate/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test-crate" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | my-cool-dep = { workspace = true } 8 | -------------------------------------------------------------------------------- /tests/workspace_deps/test-crate/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn use_it() { 2 | my_cool_dep::do_something!() 3 | } 4 | --------------------------------------------------------------------------------