rustflags-0.1.7/.cargo_vcs_info.json0000644000000001360000000000100130530ustar { "git": { "sha1": "dba3b018b95e39813785539293716289bd09a94d" }, "path_in_vcs": "" }rustflags-0.1.7/.github/FUNDING.yml000064400000000000000000000000201046102023000150100ustar 00000000000000github: dtolnay rustflags-0.1.7/.github/workflows/ci.yml000064400000000000000000000033711046102023000163620ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: pre_ci: uses: dtolnay/.github/.github/workflows/pre_ci.yml@master test: name: Rust ${{matrix.rust}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.74.0] timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV if: matrix.rust == 'nightly' - run: cargo check - run: cargo test doc: name: Documentation needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 env: RUSTDOCFLAGS: -Dwarnings steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - uses: dtolnay/install@cargo-docs-rs - run: cargo docs-rs clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic miri: name: Miri needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@miri - run: cargo miri setup - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance rustflags-0.1.7/.gitignore000064400000000000000000000000251046102023000136300ustar 00000000000000/target/ /Cargo.lock rustflags-0.1.7/Cargo.lock0000644000000014430000000000100110300ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "cc" version = "1.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" dependencies = [ "shlex", ] [[package]] name = "cmake" version = "0.1.54" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" dependencies = [ "cc", ] [[package]] name = "rustflags" version = "0.1.7" dependencies = [ "cmake", ] [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" rustflags-0.1.7/Cargo.toml0000644000000025610000000000100110550ustar # 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" rust-version = "1.74" name = "rustflags" version = "0.1.7" authors = ["David Tolnay "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Parser for CARGO_ENCODED_RUSTFLAGS" documentation = "https://docs.rs/rustflags" readme = "README.md" categories = ["development-tools::build-utils"] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/rustflags" [package.metadata.docs.rs] rustdoc-args = [ "--generate-link-to-definition", "--extern-html-root-url=core=https://doc.rust-lang.org", "--extern-html-root-url=alloc=https://doc.rust-lang.org", "--extern-html-root-url=std=https://doc.rust-lang.org", ] targets = ["x86_64-unknown-linux-gnu"] [lib] name = "rustflags" path = "src/lib.rs" [[test]] name = "test" path = "tests/test.rs" [dev-dependencies.cmake] version = "0.1" rustflags-0.1.7/Cargo.toml.orig000064400000000000000000000012721046102023000145340ustar 00000000000000[package] name = "rustflags" version = "0.1.7" authors = ["David Tolnay "] categories = ["development-tools::build-utils"] description = "Parser for CARGO_ENCODED_RUSTFLAGS" documentation = "https://docs.rs/rustflags" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/rustflags" rust-version = "1.74" [dev-dependencies] cmake = "0.1" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = [ "--generate-link-to-definition", "--extern-html-root-url=core=https://doc.rust-lang.org", "--extern-html-root-url=alloc=https://doc.rust-lang.org", "--extern-html-root-url=std=https://doc.rust-lang.org", ] rustflags-0.1.7/LICENSE-APACHE000064400000000000000000000227731046102023000136020ustar 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 rustflags-0.1.7/LICENSE-MIT000064400000000000000000000017771046102023000133130ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. rustflags-0.1.7/README.md000064400000000000000000000056041046102023000131270ustar 00000000000000Parser for CARGO_ENCODED_RUSTFLAGS ================================== [github](https://github.com/dtolnay/rustflags) [crates.io](https://crates.io/crates/rustflags) [docs.rs](https://docs.rs/rustflags) [build status](https://github.com/dtolnay/rustflags/actions?query=branch%3Amaster) `CARGO_ENCODED_RUSTFLAGS` is one of the environment variables [provided by Cargo to build scripts][reference]. It synthesizes several sources of flags affecting Cargo's rustc invocations that build scripts might care about: - Flags passed via the RUSTFLAGS environment variable, - Cargo config entries under `target..rustflags` and `target..rustflags` and `build.rustflags`, including from the project-specific Cargo config file and the Cargo config in the user's CARGO_HOME. If a build script needs to make some rustc invocations, or needs to characterize aspects of the upcoming rustc invocation, it likely needs these flags. [reference]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts ```toml [build-dependencies] rustflags = "0.1" ```
## Example This build script uses the `cmake` crate to compile some C code, and must configure it with a particular C preprocessor #define if the Rust build is being performed with sanitizers. ```rust // build.rs use rustflags::Flag; use std::env; use std::path::PathBuf; fn main() { let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); let lib_source_dir = manifest_dir.join("lib"); assert!(lib_source_dir.join("CMakeLists.txt").exists()); let mut builder = cmake::Config::new(lib_source_dir); // Look for -Zsanitizer=address for flag in rustflags::from_env() { if matches!(flag, Flag::Z(z) if z == "sanitizer=address") { builder.define("ENABLE_SANITIZERS", "ON"); builder.define("SANITIZERS", "address"); break; } } builder.build(); } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. rustflags-0.1.7/src/lib.rs000064400000000000000000000324511046102023000135530ustar 00000000000000//! [![github]](https://github.com/dtolnay/rustflags) [![crates-io]](https://crates.io/crates/rustflags) [![docs-rs]](https://docs.rs/rustflags) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! Parser for CARGO_ENCODED_RUSTFLAGS. //! //! This is one of the environment variables [provided by Cargo to build //! scripts][reference]. It synthesizes several sources of flags affecting //! Cargo's rustc invocations that build scripts might care about: //! //! - Flags passed via the RUSTFLAGS environment variable, //! - Cargo config entries under `target..rustflags` and //! `target..rustflags` and `build.rustflags`, including from the //! project-specific Cargo config file and the Cargo config in the user's //! CARGO_HOME. //! //! If a build script needs to make some rustc invocations, or needs to //! characterize aspects of the upcoming rustc invocation, it likely needs these //! flags. //! //! [reference]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts //! //! # Example //! //! This build script uses the `cmake` crate to compile some C code, and must //! configure it with a particular C preprocessor #define if the Rust build is //! being performed with sanitizers. //! //! ```no_run //! // build.rs //! //! use rustflags::Flag; //! use std::env; //! use std::path::PathBuf; //! //! fn main() { //! let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); //! let lib_source_dir = manifest_dir.join("lib"); //! assert!(lib_source_dir.join("CMakeLists.txt").exists()); //! //! let mut builder = cmake::Config::new(lib_source_dir); //! //! // Look for -Zsanitizer=address //! for flag in rustflags::from_env() { //! if matches!(flag, Flag::Z(z) if z == "sanitizer=address") { //! builder.define("ENABLE_SANITIZERS", "ON"); //! builder.define("SANITIZERS", "address"); //! break; //! } //! } //! //! builder.build(); //! } //! ``` #![doc(html_root_url = "https://docs.rs/rustflags/0.1.7")] #![allow( clippy::cast_lossless, clippy::derive_partial_eq_without_eq, clippy::doc_markdown, clippy::items_after_statements, clippy::items_after_test_module, // https://github.com/rust-lang/rust-clippy/issues/10713 clippy::manual_find, clippy::must_use_candidate, clippy::needless_doctest_main, clippy::too_many_lines, clippy::type_complexity, clippy::uninlined_format_args, clippy::unnecessary_wraps )] mod parse; mod render; mod string; mod write; use crate::string::{EnvStr, EnvString}; use std::env; use std::ffi::{OsStr, OsString}; use std::fmt::{self, Display, Write}; use std::path::PathBuf; /// Parse flags from CARGO_ENCODED_RUSTFLAGS environment variable. pub fn from_env() -> RustFlags { let encoded = env::var_os("CARGO_ENCODED_RUSTFLAGS").unwrap_or_default(); RustFlags { encoded: EnvString::new(encoded), pos: 0, repeat: None, short: false, } } /// Parse flags from a string separated with ASCII unit separator ('\x1f'). /// /// This is a valid format for the following environment variables: /// /// - `CARGO_ENCODED_RUSTFLAGS` (Cargo 1.55+) /// - `CARGO_ENCODED_RUSTDOCFLAGS` (Cargo 1.55+) pub fn from_encoded(encoded: &OsStr) -> RustFlags { RustFlags { encoded: EnvString::new(encoded.to_owned()), pos: 0, repeat: None, short: false, } } /// **Iterator of rustc flags** pub struct RustFlags { encoded: EnvString, pos: usize, repeat: Option<(fn(&EnvStr) -> Option<(Flag, usize)>, usize)>, short: bool, } impl Iterator for RustFlags { type Item = Flag; fn next(&mut self) -> Option { parse::parse(self) } } /// **One flag recognized by rustc** #[derive(Debug, PartialEq)] #[non_exhaustive] pub enum Flag { /// `-h`, `--help` /// /// Display help message. Help, /// `--cfg SPEC` /// /// Configure the compilation environment. Cfg { name: String, value: Option }, /// `-L [KIND=]PATH` /// /// Add a directory to the library search path. LibrarySearchPath { kind: LibraryKind, path: PathBuf }, /// `-l [KIND[:MODIFIERS]=]NAME[:RENAME]` /// /// Link the generated crate(s) to the specified native library NAME. /// Optional comma separated MODIFIERS may be specified each with a prefix /// of either '+' to enable or '-' to disable. Link { kind: LinkKind, modifiers: Vec<(LinkModifierPrefix, LinkModifier)>, name: String, rename: Option, }, /// `--crate-type [bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]` /// /// Comma separated list of types of crates for the compiler to emit. CrateType(CrateType), /// `--crate-name NAME` /// /// Specify the name of the crate being built. CrateName(String), /// `--edition 2015|2018|2021` /// /// Specify which edition of the compiler to use when compiling code. Edition(u16), /// `--emit [asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]` /// /// Comma separated list of types of output for the compiler to emit. Emit(Emit), /// `--print [crate-name|file-names|sysroot|target-libdir|cfg|target-list|target-cpus|target-features|relocation-models|code-models|tls-models|target-spec-json|native-static-libs|stack-protector-strategies]` /// /// Compiler information to print on stdout. Print(String), /// `-o FILENAME` /// /// Write output to \. Out(PathBuf), /// `--out-dir DIR` /// /// Write output to compiler-chosen filename in \. OutDir(PathBuf), /// `--explain OPT` /// /// Provide a detailed explanation of an error message. Explain(String), /// `--test` /// /// Build a test harness. Test, /// `--target TARGET` /// /// Target triple for which the code is compiled. Target(String), /// `-A`, `--allow LINT` /// /// Set lint allowed. Allow(String), /// `-W`, `--warn LINT` /// /// Set lint warnings. Warn(String), /// `--force-warn LINT` /// /// Set lint force-warn. ForceWarn(String), /// `-D`, `--deny LINT` /// /// Set lint denied. Deny(String), /// `-F`, `--forbid LINT` /// /// Set lint forbidden. Forbid(String), /// `--cap-lints LEVEL` /// /// Set the most restrictive lint level. More restrictive lints are capped /// at this level. CapLints(LintLevel), /// `-C`, `--codegen OPT[=VALUE]` /// /// Set a codegen option. Codegen { opt: String, value: Option }, /// `-V`, `--version` /// /// Print version info and exit. Version, /// `-v`, `--verbose` /// /// Use verbose output. Verbose, /// `--extern NAME[=PATH]` /// /// Specify where an external rust library is located. Extern { name: String, path: Option }, /// `--extern-location NAME=LOCATION` /// /// Location where an external crate dependency is specified. ExternLocation { name: String, location: OsString }, /// `--sysroot PATH` /// /// Override the system root. Sysroot(PathBuf), /// `-Z FLAG` /// /// Set internal debugging options. Z(String), /// `--error-format human|json|short` /// /// How errors and other messages are produced. ErrorFormat(ErrorFormat), /// `--json CONFIG` /// /// Configure the JSON output of the compiler. Json(String), /// `--color auto|always|never` /// /// Configure coloring of output. Color(Color), /// `--remap-path-prefix FROM=TO` /// /// Remap source names in all output (compiler messages and output files). RemapPathPrefix { from: PathBuf, to: PathBuf }, } /// Argument of `-L` #[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum LibraryKind { /// `dependency` Dependency, /// `crate` Crate, /// `native` Native, /// `framework` Framework, /// `all` (the default) #[default] All, } impl Display for LibraryKind { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { LibraryKind::Dependency => "dependency", LibraryKind::Crate => "crate", LibraryKind::Native => "native", LibraryKind::Framework => "framework", LibraryKind::All => "all", }) } } /// Argument of `-l` #[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum LinkKind { /// `static` Static, /// `framework` Framework, /// `dylib` (the default) #[default] Dylib, } impl Display for LinkKind { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { LinkKind::Static => "static", LinkKind::Framework => "framework", LinkKind::Dylib => "dylib", }) } } /// Argument of `-l` #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum LinkModifierPrefix { /// `+` Enable, /// `-` Disable, } impl Display for LinkModifierPrefix { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_char(match self { LinkModifierPrefix::Enable => '+', LinkModifierPrefix::Disable => '-', }) } } /// Argument of `-l` #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum LinkModifier { /// `bundle` Bundle, /// `verbatim` Verbatim, /// `whole-archive` WholeArchive, /// `as-needed` AsNeeded, } impl Display for LinkModifier { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { LinkModifier::Bundle => "bundle", LinkModifier::Verbatim => "verbatim", LinkModifier::WholeArchive => "whole-archive", LinkModifier::AsNeeded => "as-needed", }) } } /// Argument of `--crate-type` #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum CrateType { /// `bin` Bin, /// `lib` Lib, /// `rlib` Rlib, /// `dylib` Dylib, /// `cdylib` Cdylib, /// `staticlib` Staticlib, /// `proc-macro` ProcMacro, } impl Display for CrateType { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { CrateType::Bin => "bin", CrateType::Lib => "lib", CrateType::Rlib => "rlib", CrateType::Dylib => "dylib", CrateType::Cdylib => "Cdylib", CrateType::Staticlib => "staticlib", CrateType::ProcMacro => "proc-macro", }) } } /// Argument of `--emit` #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum Emit { /// `asm` Asm, /// `llvm-bc` LlvmBc, /// `llvm-ir` LlvmIr, /// `obj` Obj, /// `metadata` Metadata, /// `link` Link, /// `dep-info` DepInfo, /// `mir` Mir, } impl Display for Emit { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { Emit::Asm => "asm", Emit::LlvmBc => "llvm-bc", Emit::LlvmIr => "llvm-ir", Emit::Obj => "obj", Emit::Metadata => "metadata", Emit::Link => "link", Emit::DepInfo => "dep-info", Emit::Mir => "mir", }) } } /// Argument of `--cap-lints` #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum LintLevel { /// `allow` Allow, /// `warn` Warn, /// `deny` Deny, /// `forbid` Forbid, } impl Display for LintLevel { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { LintLevel::Allow => "allow", LintLevel::Warn => "warn", LintLevel::Deny => "deny", LintLevel::Forbid => "forbid", }) } } /// Argument of `--error-format` #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum ErrorFormat { /// `human` Human, /// `json` Json, /// `short` Short, } impl Display for ErrorFormat { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { ErrorFormat::Human => "human", ErrorFormat::Json => "json", ErrorFormat::Short => "short", }) } } /// Argument of `--color` #[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum Color { /// Colorize, if output goes to a tty (default). #[default] Auto, /// Always colorize output. Always, /// Never colorize output. Never, } impl Display for Color { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { Color::Auto => "auto", Color::Always => "always", Color::Never => "never", }) } } rustflags-0.1.7/src/parse.rs000064400000000000000000000440271046102023000141210ustar 00000000000000use crate::string::{EnvChar, EnvStr}; use crate::{Flag, RustFlags}; use std::str; enum FlagConstructor { Flag(Flag), Opt(fn(&EnvStr) -> Option), Repeated(fn(&EnvStr) -> Option<(Flag, usize)>), Unrecognized, } mod opt { use crate::string::EnvStr; use crate::{ Color, CrateType, Emit, ErrorFormat, Flag, LibraryKind, LinkKind, LinkModifier, LinkModifierPrefix, LintLevel, }; use std::ffi::OsString; use std::mem; use std::path::PathBuf; pub(crate) fn cfg(arg: &EnvStr) -> Option { let arg = arg.to_str()?; let (name, value) = match arg.split_once('=') { Some((name, value)) => { let len = value.len(); if len >= 2 && value.starts_with('"') && value[1..].find('"') == Some(len - 2) { (name, Some(&value[1..len - 1])) } else { return None; } } None => (arg, None), }; let name = name.to_owned(); let value = value.map(str::to_owned); Some(Flag::Cfg { name, value }) } pub(crate) fn library_search_path(arg: &EnvStr) -> Option { let (kind, path) = if let Some((kind, path)) = arg.split_once('=') { let kind = match kind.to_str()? { "dependency" => LibraryKind::Dependency, "crate" => LibraryKind::Crate, "native" => LibraryKind::Native, "framework" => LibraryKind::Framework, "all" => LibraryKind::All, _ => return None, }; (kind, path) } else { (LibraryKind::All, arg) }; let path = PathBuf::from(path); Some(Flag::LibrarySearchPath { kind, path }) } pub(crate) fn link(arg: &EnvStr) -> Option { let arg = arg.to_str()?; let mut modifiers = Vec::new(); let (kind, name) = match arg.split_once('=') { Some((mut kind, name)) => { if let Some((modified_kind, comma_separated_modifiers)) = kind.split_once(':') { for modifier in comma_separated_modifiers.split(',') { let prefix = match modifier.chars().next() { Some('+') => LinkModifierPrefix::Enable, Some('-') => LinkModifierPrefix::Disable, _ => continue, }; let modifier = match &modifier[1..] { "bundle" => LinkModifier::Bundle, "verbatim" => LinkModifier::Verbatim, "whole-archive" => LinkModifier::WholeArchive, "as-needed" => LinkModifier::AsNeeded, _ => continue, }; modifiers.push((prefix, modifier)); } kind = modified_kind; } let kind = match kind { "static" => LinkKind::Static, "framework" => LinkKind::Framework, "dylib" => LinkKind::Dylib, _ => return None, }; (kind, name) } None => (LinkKind::Dylib, arg), }; let (name, rename) = match name.split_once(':') { Some((name, rename)) => (name, Some(rename)), None => (name, None), }; let name = name.to_owned(); let rename = rename.map(str::to_owned); Some(Flag::Link { kind, modifiers, name, rename, }) } pub(crate) fn crate_type(mut arg: &EnvStr) -> Option<(Flag, usize)> { while !arg.is_empty() { let first = match arg.split_once(',') { Some((first, rest)) => { arg = rest; first } None => mem::take(&mut arg), }; let Some(first) = first.to_str() else { continue; }; let crate_type = match first { "bin" => CrateType::Bin, "lib" => CrateType::Lib, "rlib" => CrateType::Rlib, "dylib" => CrateType::Dylib, "cdylib" => CrateType::Cdylib, "staticlib" => CrateType::Staticlib, "proc-macro" => CrateType::ProcMacro, _ => continue, }; return Some((Flag::CrateType(crate_type), arg.len())); } None } pub(crate) fn crate_name(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::CrateName(arg.to_owned())) } pub(crate) fn edition(arg: &EnvStr) -> Option { let arg = arg.to_str()?; arg.parse().ok().map(Flag::Edition) } pub(crate) fn emit(mut arg: &EnvStr) -> Option<(Flag, usize)> { while !arg.is_empty() { let first = match arg.split_once(',') { Some((first, rest)) => { arg = rest; first } None => mem::take(&mut arg), }; let Some(first) = first.to_str() else { continue; }; let emit = match first { "asm" => Emit::Asm, "llvm-bc" => Emit::LlvmBc, "llvm-ir" => Emit::LlvmIr, "obj" => Emit::Obj, "metadata" => Emit::Metadata, "link" => Emit::Link, "dep-info" => Emit::DepInfo, "mir" => Emit::Mir, _ => continue, }; return Some((Flag::Emit(emit), arg.len())); } None } pub(crate) fn print(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Print(arg.to_owned())) } pub(crate) fn out(arg: &EnvStr) -> Option { Some(Flag::Out(PathBuf::from(arg))) } pub(crate) fn out_dir(arg: &EnvStr) -> Option { Some(Flag::OutDir(PathBuf::from(arg))) } pub(crate) fn explain(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Explain(arg.to_owned())) } pub(crate) fn target(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Target(arg.to_owned())) } pub(crate) fn allow(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Allow(arg.to_owned())) } pub(crate) fn warn(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Warn(arg.to_owned())) } pub(crate) fn force_warn(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::ForceWarn(arg.to_owned())) } pub(crate) fn deny(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Deny(arg.to_owned())) } pub(crate) fn forbid(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Forbid(arg.to_owned())) } pub(crate) fn cap_lints(arg: &EnvStr) -> Option { let arg = arg.to_str()?; let level = match arg { "allow" => LintLevel::Allow, "warn" => LintLevel::Warn, "deny" => LintLevel::Deny, "forbid" => LintLevel::Forbid, _ => return None, }; Some(Flag::CapLints(level)) } pub(crate) fn codegen(arg: &EnvStr) -> Option { let arg = arg.to_str()?; let (opt, value) = match arg.split_once('=') { Some((opt, value)) => (opt, Some(value)), None => (arg, None), }; let opt = opt.to_owned(); let value = value.map(str::to_owned); Some(Flag::Codegen { opt, value }) } pub(crate) fn extern_(arg: &EnvStr) -> Option { let (name, path) = match arg.split_once('=') { Some((name, path)) => (name, Some(path)), None => (arg, None), }; let name = name.to_str()?.to_owned(); let path = path.map(PathBuf::from); Some(Flag::Extern { name, path }) } pub(crate) fn extern_location(arg: &EnvStr) -> Option { let (name, location) = arg.split_once('=')?; let name = name.to_str()?.to_owned(); let location = OsString::from(location); Some(Flag::ExternLocation { name, location }) } pub(crate) fn sysroot(arg: &EnvStr) -> Option { Some(Flag::Sysroot(PathBuf::from(arg))) } pub(crate) fn z(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Z(arg.to_owned())) } pub(crate) fn error_format(arg: &EnvStr) -> Option { let arg = arg.to_str()?; let format = match arg { "human" => ErrorFormat::Human, "json" => ErrorFormat::Json, "short" => ErrorFormat::Short, _ => return None, }; Some(Flag::ErrorFormat(format)) } pub(crate) fn json(arg: &EnvStr) -> Option { let arg = arg.to_str()?; Some(Flag::Json(arg.to_owned())) } pub(crate) fn color(arg: &EnvStr) -> Option { let arg = arg.to_str()?; let color = match arg { "auto" => Color::Auto, "always" => Color::Always, "never" => Color::Never, _ => return None, }; Some(Flag::Color(color)) } pub(crate) fn remap_path_prefix(arg: &EnvStr) -> Option { let (from, to) = arg.split_once('=')?; let from = PathBuf::from(from); let to = PathBuf::from(to); Some(Flag::RemapPathPrefix { from, to }) } } fn lookup_short(ch: char) -> FlagConstructor { match ch { 'h' => FlagConstructor::Flag(Flag::Help), 'L' => FlagConstructor::Opt(opt::library_search_path), 'l' => FlagConstructor::Opt(opt::link), 'g' => FlagConstructor::Flag(Flag::Codegen { opt: "debuginfo".to_owned(), value: Some("2".to_owned()), }), 'O' => FlagConstructor::Flag(Flag::Codegen { opt: "opt-level".to_owned(), value: Some("2".to_owned()), }), 'o' => FlagConstructor::Opt(opt::out), 'A' => FlagConstructor::Opt(opt::allow), 'W' => FlagConstructor::Opt(opt::warn), 'D' => FlagConstructor::Opt(opt::deny), 'F' => FlagConstructor::Opt(opt::forbid), 'C' => FlagConstructor::Opt(opt::codegen), 'V' => FlagConstructor::Flag(Flag::Version), 'v' => FlagConstructor::Flag(Flag::Verbose), 'Z' => FlagConstructor::Opt(opt::z), _ => FlagConstructor::Unrecognized, } } fn lookup_long(name: &str) -> FlagConstructor { match name { "help" => FlagConstructor::Flag(Flag::Help), "cfg" => FlagConstructor::Opt(opt::cfg), "crate-type" => FlagConstructor::Repeated(opt::crate_type), "crate-name" => FlagConstructor::Opt(opt::crate_name), "edition" => FlagConstructor::Opt(opt::edition), "emit" => FlagConstructor::Repeated(opt::emit), "print" => FlagConstructor::Opt(opt::print), "out-dir" => FlagConstructor::Opt(opt::out_dir), "explain" => FlagConstructor::Opt(opt::explain), "test" => FlagConstructor::Flag(Flag::Test), "target" => FlagConstructor::Opt(opt::target), "allow" => FlagConstructor::Opt(opt::allow), "warn" => FlagConstructor::Opt(opt::warn), "force-warn" => FlagConstructor::Opt(opt::force_warn), "deny" => FlagConstructor::Opt(opt::deny), "forbid" => FlagConstructor::Opt(opt::forbid), "cap-lints" => FlagConstructor::Opt(opt::cap_lints), "codegen" => FlagConstructor::Opt(opt::codegen), "version" => FlagConstructor::Flag(Flag::Version), "verbose" => FlagConstructor::Flag(Flag::Verbose), "extern" => FlagConstructor::Opt(opt::extern_), "extern-location" => FlagConstructor::Opt(opt::extern_location), "sysroot" => FlagConstructor::Opt(opt::sysroot), "error-format" => FlagConstructor::Opt(opt::error_format), "json" => FlagConstructor::Opt(opt::json), "color" => FlagConstructor::Opt(opt::color), "remap-path-prefix" => FlagConstructor::Opt(opt::remap_path_prefix), _ => FlagConstructor::Unrecognized, } } pub(crate) fn parse(f: &mut RustFlags) -> Option { const SEPARATOR: char = '\x1F'; let mut skip = false; while f.pos < f.encoded.len() { if skip { match f.encoded[f.pos..].find(SEPARATOR) { // `nonflag` ... Some(i) => f.pos += i + 1, // `nonflag`$ None => f.pos = f.encoded.len(), } skip = false; continue; } let (constructor, arg) = if let Some((constructor, len)) = f.repeat.take() { let arg = &f.encoded[f.pos..f.pos + len]; f.pos += len; (ConstructorFn::Repeated(constructor), arg) } else if f.short { let ch = match f.encoded[f.pos..].first_char().unwrap() { EnvChar::Valid(ch) => { f.pos += ch.len_utf8(); if ch == SEPARATOR { f.short = false; continue; } ch } EnvChar::Invalid => '\0', }; let constructor = match lookup_short(ch) { FlagConstructor::Flag(flag) => return Some(flag), FlagConstructor::Opt(f) => ConstructorFn::Opt(f), FlagConstructor::Repeated(f) => ConstructorFn::Repeated(f), FlagConstructor::Unrecognized => { f.short = false; skip = true; continue; } }; f.short = false; if f.pos == f.encoded.len() { break; } if f.encoded[f.pos..].starts_with(SEPARATOR) { // `-X` `arg` f.pos += 1; } let arg = if let Some(i) = f.encoded[f.pos..].find(SEPARATOR) { // `-Xarg` ... let arg = &f.encoded[f.pos..f.pos + i]; f.pos += i + 1; arg } else { // `-Xarg`$ let arg = &f.encoded[f.pos..]; f.pos = f.encoded.len(); arg }; (constructor, arg) } else if f.encoded[f.pos..].starts_with('-') { let Some(first_char) = f.encoded[f.pos + 1..].first_char() else { // `-`$ f.pos += 1; continue; }; match first_char { // `-` ... EnvChar::Valid(SEPARATOR) => { f.pos += 2; continue; } EnvChar::Valid('-') => { let flag = match f.encoded[f.pos + 2..].find(SEPARATOR) { // `--` Some(0) => { f.pos = f.encoded.len(); continue; } Some(i) => { let flag = &f.encoded[f.pos + 2..f.pos + 2 + i]; f.pos += i + 3; flag } None => { let flag = &f.encoded[f.pos + 2..]; f.pos = f.encoded.len(); flag } }; let (name, arg) = match flag.split_once('=') { Some((name, arg)) => (name, Some(arg)), None => (flag, None), }; let Some(name) = name.to_str() else { continue; }; let constructor = match lookup_long(name) { // `--flag` FlagConstructor::Flag(flag) if arg.is_none() => return Some(flag), FlagConstructor::Opt(f) => ConstructorFn::Opt(f), FlagConstructor::Repeated(f) => ConstructorFn::Repeated(f), FlagConstructor::Unrecognized | FlagConstructor::Flag(_) => continue, }; let arg = if let Some(arg) = arg { // `--opt=arg` arg } else if let Some(i) = f.encoded[f.pos..].find(SEPARATOR) { // `--opt` `arg` ... let arg = &f.encoded[f.pos..f.pos + i]; f.pos += i + 1; arg } else { // `--opt` `arg`$ let arg = &f.encoded[f.pos..]; f.pos = f.encoded.len(); arg }; (constructor, arg) } // `-X` EnvChar::Valid(_) | EnvChar::Invalid => { f.pos += 1; f.short = true; continue; } } } else { skip = true; continue; }; enum ConstructorFn { Opt(fn(&EnvStr) -> Option), Repeated(fn(&EnvStr) -> Option<(Flag, usize)>), } match constructor { ConstructorFn::Opt(constructor) => { if let Some(flag) = constructor(arg) { return Some(flag); } } ConstructorFn::Repeated(constructor) => { if let Some((flag, repeat)) = constructor(arg) { if repeat > 0 { f.pos -= repeat + f.encoded[..f.pos].ends_with(SEPARATOR) as usize; f.repeat = Some((constructor, repeat)); } return Some(flag); } } } } None } rustflags-0.1.7/src/render.rs000064400000000000000000000162101046102023000142570ustar 00000000000000use crate::write::WriteFmt; use crate::{Flag, LibraryKind, LinkKind}; use std::ffi::{OsStr, OsString}; impl IntoIterator for Flag { type Item = OsString; type IntoIter = iter::Iter; fn into_iter(self) -> Self::IntoIter { let mut flags = Vec::new(); match self { Flag::Help => { flags.push(OsString::from("--help")); } Flag::Cfg { name, value } => { flags.push(OsString::from("--cfg")); if let Some(value) = value { flags.push(OsString::from(format!("{}=\"{}\"", name, value))); } else { flags.push(OsString::from(name)); } } Flag::LibrarySearchPath { kind, path } => { flags.push(OsString::from("-L")); if kind == LibraryKind::All { flags.push(OsString::from(path)); } else { let mut flag = OsString::new(); write!(flag, "{}=", kind); flag.push(path); flags.push(flag); } } Flag::Link { kind, modifiers, name, rename, } => { flags.push(OsString::from("-l")); let mut flag = OsString::new(); if kind != LinkKind::default() || !modifiers.is_empty() { write!(flag, "{}", kind); } for (i, (prefix, modifier)) in modifiers.iter().enumerate() { flag.push(if i == 0 { ":" } else { "," }); write!(flag, "{}{}", prefix, modifier); } if !flag.is_empty() { flag.push("="); } flag.push(name); if let Some(rename) = rename { flag.push(":"); flag.push(rename); } flags.push(flag); } Flag::CrateType(crate_type) => { flags.push(OsString::from("--crate-type")); flags.push(OsString::from(crate_type.to_string())); } Flag::CrateName(crate_name) => { flags.push(OsString::from("--crate-name")); flags.push(OsString::from(crate_name)); } Flag::Edition(edition) => { flags.push(OsString::from("--edition")); flags.push(OsString::from(edition.to_string())); } Flag::Emit(emit) => { flags.push(OsString::from("--emit")); flags.push(OsString::from(emit.to_string())); } Flag::Print(print) => { flags.push(OsString::from("--print")); flags.push(OsString::from(print)); } Flag::Out(filename) => { flags.push(OsString::from("-o")); flags.push(OsString::from(filename)); } Flag::OutDir(dir) => { flags.push(OsString::from("--out-dir")); flags.push(OsString::from(dir)); } Flag::Explain(code) => { flags.push(OsString::from("--explain")); flags.push(OsString::from(code)); } Flag::Test => { flags.push(OsString::from("--test")); } Flag::Target(target) => { flags.push(OsString::from("--target")); flags.push(OsString::from(target)); } Flag::Allow(lint) => { flags.push(OsString::from("--allow")); flags.push(OsString::from(lint)); } Flag::Warn(lint) => { flags.push(OsString::from("--warn")); flags.push(OsString::from(lint)); } Flag::ForceWarn(lint) => { flags.push(OsString::from("--force-warn")); flags.push(OsString::from(lint)); } Flag::Deny(lint) => { flags.push(OsString::from("--deny")); flags.push(OsString::from(lint)); } Flag::Forbid(lint) => { flags.push(OsString::from("--forbid")); flags.push(OsString::from(lint)); } Flag::CapLints(lint_level) => { flags.push(OsString::from("--cap-lints")); flags.push(OsString::from(lint_level.to_string())); } Flag::Codegen { opt, value } => { flags.push(OsString::from("-C")); if let Some(value) = value { flags.push(OsString::from(format!("{}={}", opt, value))); } else { flags.push(OsString::from(opt)); } } Flag::Version => { flags.push(OsString::from("--version")); } Flag::Verbose => { flags.push(OsString::from("--verbose")); } Flag::Extern { name, path } => { flags.push(OsString::from("--extern")); if let Some(path) = path { flags.push(kv(name, path)); } else { flags.push(OsString::from(name)); } } Flag::ExternLocation { name, location } => { flags.push(OsString::from("--extern-location")); flags.push(kv(name, location)); } Flag::Sysroot(sysroot) => { flags.push(OsString::from("--sysroot")); flags.push(OsString::from(sysroot)); } Flag::Z(flag) => { flags.push(OsString::from("-Z")); flags.push(OsString::from(flag)); } Flag::ErrorFormat(error_format) => { flags.push(OsString::from("--error-format")); flags.push(OsString::from(error_format.to_string())); } Flag::Json(json) => { flags.push(OsString::from("--json")); flags.push(OsString::from(json)); } Flag::Color(color) => { flags.push(OsString::from("--color")); flags.push(OsString::from(color.to_string())); } Flag::RemapPathPrefix { from, to } => { flags.push(OsString::from("--remap-path-prefix")); flags.push(kv(from, to)); } } iter::Iter { items: flags.into_iter(), } } } fn kv(k: impl AsRef, v: impl AsRef) -> OsString { let k = k.as_ref(); let v = v.as_ref(); let mut string = OsString::with_capacity(k.len() + 1 + v.len()); string.push(k); string.push("="); string.push(v); string } mod iter { use std::ffi::OsString; use std::vec; pub struct Iter { pub(crate) items: vec::IntoIter, } impl Iterator for Iter { type Item = OsString; fn next(&mut self) -> Option { self.items.next() } } } rustflags-0.1.7/src/string.rs000064400000000000000000000077431046102023000143210ustar 00000000000000use std::cmp; use std::ffi::{OsStr, OsString}; use std::ops::{Deref, Index, Range, RangeFrom, RangeTo}; use std::str; pub(crate) struct EnvString(OsString); #[repr(transparent)] pub(crate) struct EnvStr(OsStr); impl EnvString { pub fn new(encoded: OsString) -> Self { EnvString(encoded) } } impl Deref for EnvString { type Target = EnvStr; fn deref(&self) -> &Self::Target { EnvStr::new(&self.0) } } impl EnvStr { fn new(encoded: &OsStr) -> &Self { unsafe { &*(encoded as *const OsStr as *const EnvStr) } } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn find(&self, ch: char) -> Option { let mut buf = [0u8; 4]; let ch = ch.encode_utf8(&mut buf).as_bytes(); for i in 0..self.0.len() { if self.0.as_encoded_bytes()[i..].starts_with(ch) { return Some(i); } } None } pub fn starts_with(&self, ch: char) -> bool { let mut buf = [0u8; 4]; let ch = ch.encode_utf8(&mut buf).as_bytes(); self.0.as_encoded_bytes().starts_with(ch) } pub fn ends_with(&self, ch: char) -> bool { let mut buf = [0u8; 4]; let ch = ch.encode_utf8(&mut buf).as_bytes(); self.0.as_encoded_bytes().ends_with(ch) } pub fn first_char(&self) -> Option { let encoded = self.0.as_encoded_bytes(); let prefix = cmp::min(encoded.len(), 4); match str::from_utf8(&encoded[..prefix]) { Ok(valid) => valid.chars().next().map(EnvChar::Valid), Err(utf8_error) => { let valid_up_to = utf8_error.valid_up_to(); if valid_up_to == 0 { Some(EnvChar::Invalid) } else { let valid = str::from_utf8(&encoded[..valid_up_to]).unwrap(); Some(EnvChar::Valid(valid.chars().next().unwrap())) } } } } pub fn split_once(&self, ch: char) -> Option<(&EnvStr, &EnvStr)> { let i = self.find(ch)?; Some((&self[..i], &self[i + ch.len_utf8()..])) } pub fn to_str(&self) -> Option<&str> { self.0.to_str() } } impl Index> for EnvStr { type Output = EnvStr; fn index(&self, range: RangeFrom) -> &Self::Output { &self[range.start..self.len()] } } impl Index> for EnvStr { type Output = EnvStr; fn index(&self, range: RangeTo) -> &Self::Output { &self[0..range.end] } } impl Index> for EnvStr { type Output = EnvStr; fn index(&self, range: Range) -> &Self::Output { fn is_utf8(slice: &[u8]) -> bool { str::from_utf8(slice).is_ok() } let encoded = self.0.as_encoded_bytes(); for i in [range.start, range.end] { assert!( i == 0 || i == encoded.len() || encoded.get(i..i.wrapping_add(1)).is_some_and(is_utf8) || encoded.get(i..i.wrapping_add(2)).is_some_and(is_utf8) || encoded.get(i..i.wrapping_add(3)).is_some_and(is_utf8) || encoded.get(i..i.wrapping_add(4)).is_some_and(is_utf8) || encoded.get(i.wrapping_sub(1)..i).is_some_and(is_utf8) || encoded.get(i.wrapping_sub(2)..i).is_some_and(is_utf8) || encoded.get(i.wrapping_sub(3)..i).is_some_and(is_utf8) || encoded.get(i.wrapping_sub(4)..i).is_some_and(is_utf8) ); } let output = &encoded[range]; EnvStr::new(unsafe { OsStr::from_encoded_bytes_unchecked(output) }) } } impl AsRef for EnvStr { fn as_ref(&self) -> &OsStr { &self.0 } } impl Default for &EnvStr { fn default() -> Self { EnvStr::new(OsStr::new("")) } } pub(crate) enum EnvChar { Valid(char), Invalid, } rustflags-0.1.7/src/write.rs000064400000000000000000000004061046102023000141320ustar 00000000000000use std::ffi::OsString; use std::fmt; pub(crate) trait WriteFmt { fn write_fmt(&mut self, args: fmt::Arguments); } impl WriteFmt for OsString { fn write_fmt(&mut self, args: fmt::Arguments) { fmt::Write::write_fmt(self, args).unwrap(); } } rustflags-0.1.7/tests/test.rs000064400000000000000000000205031046102023000143320ustar 00000000000000#![allow(clippy::too_many_lines)] use rustflags::{ Color, CrateType, Emit, ErrorFormat, Flag, LibraryKind, LinkKind, LinkModifier, LinkModifierPrefix, LintLevel, }; use std::ffi::{OsStr, OsString}; use std::path::PathBuf; #[track_caller] fn test(encoded: &str, expected: &[Flag]) { let mut iterator = rustflags::from_encoded(OsStr::new(encoded)); let mut flags = Vec::new(); for expected in expected { let next = iterator.next(); assert_eq!(Some(expected), next.as_ref()); for flag in next.unwrap() { flags.push(flag); } } assert_eq!(None, iterator.next()); let re_encoded = flags.join(OsStr::new("\x1F")); let mut iterator = rustflags::from_encoded(&re_encoded); for expected in expected { assert_eq!(Some(expected), iterator.next().as_ref()); } assert_eq!(None, iterator.next()); } macro_rules! assert_flags { ($string:literal $($more_string:literal)* $(, $expected:expr)* $(,)?) => {{ let encoded = concat!($string $(, '\x1F', $more_string)*); test(encoded, &[$($expected),*]); }}; } #[test] fn test_empty() { assert_flags!(""); } #[test] fn test_individual() { // Flag::Help assert_flags!("-h", Flag::Help); assert_flags!("--help", Flag::Help); // Flag::Cfg assert_flags!( "--cfg=semver_exempt", Flag::Cfg { name: "semver_exempt".to_owned(), value: None, }, ); assert_flags!( "--cfg=feature=\"std\"", Flag::Cfg { name: "feature".to_owned(), value: Some("std".to_owned()), }, ); assert_flags!( "--cfg" "semver_exempt", Flag::Cfg { name: "semver_exempt".to_owned(), value: None, }, ); assert_flags!( "--cfg" "feature=\"std\"", Flag::Cfg { name: "feature".to_owned(), value: Some("std".to_owned()), }, ); // Flag::LibrarySearchPath assert_flags!( "-L" "PATH", Flag::LibrarySearchPath { kind: LibraryKind::All, path: PathBuf::from("PATH"), }, ); assert_flags!( "-L" "native=PATH", Flag::LibrarySearchPath { kind: LibraryKind::Native, path: PathBuf::from("PATH"), }, ); // Flag::Link assert_flags!( "-l" "NAME", Flag::Link { kind: LinkKind::Dylib, modifiers: Vec::new(), name: "NAME".to_owned(), rename: None, }, ); assert_flags!( "-l" "static=NAME", Flag::Link { kind: LinkKind::Static, modifiers: Vec::new(), name: "NAME".to_owned(), rename: None, }, ); assert_flags!( "-l" "static:+bundle,-whole-archive=NAME", Flag::Link { kind: LinkKind::Static, modifiers: vec![ (LinkModifierPrefix::Enable, LinkModifier::Bundle), (LinkModifierPrefix::Disable, LinkModifier::WholeArchive), ], name: "NAME".to_owned(), rename: None, }, ); assert_flags!( "-l" "NAME:RENAME", Flag::Link { kind: LinkKind::Dylib, modifiers: Vec::new(), name: "NAME".to_owned(), rename: Some("RENAME".to_owned()), }, ); // Flag::CrateType assert_flags!("--crate-type" "bin", Flag::CrateType(CrateType::Bin)); assert_flags!( "--crate-type" "lib,staticlib", Flag::CrateType(CrateType::Lib), Flag::CrateType(CrateType::Staticlib), ); // Flag::CrateName assert_flags!("--crate-name" "core", Flag::CrateName("core".to_owned())); // Flag::Edition assert_flags!("--edition" "2021", Flag::Edition(2021)); // Flag::Emit assert_flags!("--emit" "asm", Flag::Emit(Emit::Asm)); assert_flags!( "--emit" "asm,mir", Flag::Emit(Emit::Asm), Flag::Emit(Emit::Mir), ); assert_flags!("--emit" "unrecognized,mir", Flag::Emit(Emit::Mir)); // Flag::Print assert_flags!("--print" "cfg", Flag::Print("cfg".to_owned())); // Flag::Out assert_flags!("-o" "FILENAME", Flag::Out(PathBuf::from("FILENAME"))); // Flag::OutDir assert_flags!("--out-dir" "DIR", Flag::OutDir(PathBuf::from("DIR"))); // Flag::Explain assert_flags!("--explain" "E0282", Flag::Explain("E0282".to_owned())); // Flag::Test assert_flags!("--test", Flag::Test); // Flag::Target assert_flags!( "--target" "x86_64-unknown-linux-gnu", Flag::Target("x86_64-unknown-linux-gnu".to_owned()), ); // Flag::Allow assert_flags!("-A" "dead_code", Flag::Allow("dead_code".to_owned())); assert_flags!("--allow" "dead_code", Flag::Allow("dead_code".to_owned())); // Flag::Warn assert_flags!("-W" "dead_code", Flag::Warn("dead_code".to_owned())); assert_flags!("--warn" "dead_code", Flag::Warn("dead_code".to_owned())); // Flag::ForceWarn assert_flags!( "--force-warn" "dead_code", Flag::ForceWarn("dead_code".to_owned()), ); // Flag::Deny assert_flags!("-D" "dead_code", Flag::Deny("dead_code".to_owned())); assert_flags!("--deny" "dead_code", Flag::Deny("dead_code".to_owned())); // Flag::Forbid assert_flags!("-F" "dead_code", Flag::Forbid("dead_code".to_owned())); assert_flags!("--forbid" "dead_code", Flag::Forbid("dead_code".to_owned())); // Flag::CapLints assert_flags!("--cap-lints=allow", Flag::CapLints(LintLevel::Allow)); // Flag::Codegen assert_flags!( "-C" "embed-bitcode", Flag::Codegen { opt: "embed-bitcode".to_owned(), value: None, }, ); assert_flags!( "-C" "debuginfo=2", Flag::Codegen { opt: "debuginfo".to_owned(), value: Some("2".to_owned()), }, ); assert_flags!( "-g", Flag::Codegen { opt: "debuginfo".to_owned(), value: Some("2".to_owned()), }, ); assert_flags!( "-O", Flag::Codegen { opt: "opt-level".to_owned(), value: Some("2".to_owned()), }, ); // Flag::Version assert_flags!("-V", Flag::Version); assert_flags!("--version", Flag::Version); // Flag::Verbose assert_flags!("-v", Flag::Verbose); assert_flags!("--verbose", Flag::Verbose); // Flag::Extern assert_flags!( "--extern" "serde", Flag::Extern { name: "serde".to_owned(), path: None, }, ); assert_flags!( "--extern" "serde=target/debug/deps/libserde.rmeta", Flag::Extern { name: "serde".to_owned(), path: Some(PathBuf::from("target/debug/deps/libserde.rmeta")), }, ); // Flag::ExternLocation assert_flags!( "--extern-location" r#"serde=json:{"target":"//third-party:serde"}"#, Flag::ExternLocation { name: "serde".to_owned(), location: OsString::from(r#"json:{"target":"//third-party:serde"}"#), }, ); // Flag::Sysroot assert_flags!( "--sysroot" ".rustup/toolchains/nightly", Flag::Sysroot(PathBuf::from(".rustup/toolchains/nightly")), ); // Flag::Z assert_flags!( "-Z" "unstable-options", Flag::Z("unstable-options".to_owned()), ); // Flag::ErrorFormat assert_flags!("--error-format=json", Flag::ErrorFormat(ErrorFormat::Json)); // Flag::Json assert_flags!( "--json" "diagnostic-rendered-ansi", Flag::Json("diagnostic-rendered-ansi".to_owned()), ); // Flag::Color assert_flags!("--color=always", Flag::Color(Color::Always)); // Flag::RemapPathPrefix assert_flags!( "--remap-path-prefix" "FROM=TO", Flag::RemapPathPrefix { from: PathBuf::from("FROM"), to: PathBuf::from("TO"), }, ); } #[test] fn test_unrecognized() { assert_flags!( "-goto", Flag::Codegen { opt: "debuginfo".to_owned(), value: Some("2".to_owned()), }, Flag::Out(PathBuf::from("to")), ); assert_flags!( "-gxvto" "-h", Flag::Codegen { opt: "debuginfo".to_owned(), value: Some("2".to_owned()), }, Flag::Help, ); }