mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 19:41:36 -05:00
Merge pull request #10757 from dotCooCoo/fix/doc-tests-unsafe-code
Doc tests: unsafe code is denied in doc tests too
This commit is contained in:
@@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator-
|
||||
For the crates you changed: `cargo fmt`, `cargo clippy -p <crate> --all-targets`, `cargo xtask test` or `cargo nextest run -p <crate>`. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`.
|
||||
|
||||
### Paths and conventions
|
||||
- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`.
|
||||
- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it.
|
||||
- Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns.
|
||||
- Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty.
|
||||
- Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so
|
||||
//! the corpus tests and fuzz targets under it, and the CI job that runs them, still build.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub use craft_affinity::*;
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
//!
|
||||
//! The crate knows no command and depends on no other VectorCraft crate.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
use std::fmt;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it
|
||||
//! returns (caching them per node) and `object.expandBrush` inserts them as real objects.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
mod calli;
|
||||
mod colorize;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
#![doc(test(attr(deny(unsafe_code))))]
|
||||
|
||||
mod aci;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB),
|
||||
//! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`].
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod blend;
|
||||
pub mod cms;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node.
|
||||
//! Keeping the previous `Document` value around is therefore a cheap undo snapshot.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod appearance;
|
||||
pub mod assets;
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
//! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells,
|
||||
//! anchored at the object's centre.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod addons;
|
||||
mod adjust;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and
|
||||
//! reduce to commands, so every gesture is journaled and replayable.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod cmd;
|
||||
pub mod file_access;
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
//! - `ai_graph`: the records of a live graph those two write around its group.
|
||||
//! - `gradient_key`: the key those two find gradient definitions by.
|
||||
//! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing.
|
||||
#![doc(test(attr(deny(unsafe_code))))]
|
||||
|
||||
mod ai_editing;
|
||||
mod ai_graph;
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
//! already; [`save_with`] writes a version 1 document with them negated back for an older file
|
||||
//! version ([`vectorcraft_doc::twist`]).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod atomic;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//!
|
||||
//! Coordinates are document points (1/72 in), y pointing down.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod anchors;
|
||||
pub mod arc;
|
||||
|
||||
@@ -131,6 +131,7 @@
|
||||
//! `await` (ECMA-262 2017 section 25.5, <https://262.ecma-international.org/8.0/#sec-async-function-objects>).
|
||||
//! An `await` suspends its function's frame until the value settles, and a promise job resumes it.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod ast;
|
||||
mod builtins;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//!
|
||||
//! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
mod backend;
|
||||
mod headless;
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
//! formats.
|
||||
//!
|
||||
//! The app walks its document and maps its drawing operations to the shared writers.
|
||||
#![doc(test(attr(deny(unsafe_code))))]
|
||||
|
||||
#[cfg(test)]
|
||||
mod bytes;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few
|
||||
//! anchors. See the crate README for the API overview.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod addons;
|
||||
mod boolean;
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
//! security handler, the algorithm following the compatibility ([`Encryption`]); either password
|
||||
//! opens an encrypted file.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
mod editing;
|
||||
mod encrypt;
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each
|
||||
//! run, with the same input, output, permissions and budgets.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod deferred;
|
||||
pub mod dialog;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups,
|
||||
//! gradients, images and text (via `vectorcraft-text` glyph outlines).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod addons;
|
||||
mod brush_fx;
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
//! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the
|
||||
//! input's size, and no input can overflow the stack.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
mod analyze;
|
||||
mod catalog;
|
||||
|
||||
@@ -100,6 +100,7 @@
|
||||
//! letter and word spacing become character attributes (line breaks, kerning, baseline shift,
|
||||
//! rotation and style names).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
use craft_svg::tree::usvg;
|
||||
mod css;
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
// apply here.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod ai;
|
||||
pub mod ase;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//!
|
||||
//! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
mod bitmap;
|
||||
mod colr;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//!
|
||||
//! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod fold;
|
||||
mod solid;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable
|
||||
//! by the control channel and MCP, and keeps tools testable without a UI.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod addons;
|
||||
pub mod bbox;
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
//! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color
|
||||
//! left out stays a hole.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
mod centerline;
|
||||
mod contour;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! (view/window) here and everything else to the engine. The same entry point serves menus,
|
||||
//! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
/// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update
|
||||
/// prompt shows both, and an AppImage's menu entry gets the icon.
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
//! Every library's doc tests deny unsafe code.
|
||||
//!
|
||||
//! Rustdoc compiles each doc test as a crate of its own, without the workspace's `[lints]` table
|
||||
//! and without the library's own `#![forbid(unsafe_code)]`, so an `unsafe` block in a doc comment
|
||||
//! passes `cargo test --doc`. Rustdoc adds the attributes in `#![doc(test(attr(...)))]` to every
|
||||
//! doc test, so each library root carries `#![doc(test(attr(forbid(unsafe_code))))]`, or
|
||||
//! `deny` where the library itself relies on the workspace's `deny`. `cargo xtask layers` runs
|
||||
//! this check.
|
||||
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// Crate roots larger than this are reported instead of read.
|
||||
const MAX_ROOT_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
/// The problems found in the workspace's library roots, one line each.
|
||||
pub fn check(meta: &Value) -> Result<Vec<String>, String> {
|
||||
let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?;
|
||||
let root = Path::new(meta["workspace_root"].as_str().unwrap_or_default());
|
||||
let mut out = Vec::new();
|
||||
for p in pkgs {
|
||||
let name = p["name"].as_str().ok_or("package without name")?;
|
||||
for t in p["targets"].as_array().into_iter().flatten() {
|
||||
let kinds: Vec<&str> = t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
let doc_tested = t["doctest"].as_bool() == Some(true) && kinds.iter().any(|k| matches!(*k, "lib" | "rlib" | "proc-macro"));
|
||||
if !doc_tested {
|
||||
continue;
|
||||
}
|
||||
let path = t["src_path"].as_str().ok_or_else(|| format!("{name}: library target without src_path"))?;
|
||||
if let Some(problem) = check_root(name, root, Path::new(path))? {
|
||||
out.push(problem);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn check_root(name: &str, root: &Path, path: &Path) -> Result<Option<String>, String> {
|
||||
let shown = path.strip_prefix(root).unwrap_or(path).display();
|
||||
let len = std::fs::metadata(path).map_err(|e| format!("{shown}: {e}"))?.len();
|
||||
if len > MAX_ROOT_BYTES {
|
||||
return Ok(Some(format!("{name}: {shown} is larger than {MAX_ROOT_BYTES} bytes")));
|
||||
}
|
||||
let src = std::fs::read_to_string(path).map_err(|e| format!("{shown}: {e}"))?;
|
||||
Ok(problem(&src).map(|p| format!("{name}: {shown}: {p}")))
|
||||
}
|
||||
|
||||
/// What a library root is missing, or `None` when its doc tests deny unsafe code at least as
|
||||
/// strictly as the library does.
|
||||
fn problem(src: &str) -> Option<&'static str> {
|
||||
let attrs = inner_attributes(src);
|
||||
let forbids = attrs.iter().any(|a| sets_level(a, &["forbid"]));
|
||||
match doc_test_level(&attrs) {
|
||||
Some(Level::Forbid) => None,
|
||||
_ if forbids => Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]"),
|
||||
Some(Level::Deny) => None,
|
||||
_ => Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A lint level that rustdoc can add to every doc test.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Level {
|
||||
Allow,
|
||||
Deny,
|
||||
Forbid,
|
||||
}
|
||||
|
||||
/// The lint attributes that set a level, and the level each one sets for this check.
|
||||
const LEVELS: [(&str, Level); 5] =
|
||||
[("forbid", Level::Forbid), ("deny", Level::Deny), ("allow", Level::Allow), ("warn", Level::Allow), ("expect", Level::Allow)];
|
||||
|
||||
/// The `unsafe_code` level that the `#![doc(test(attr(...)))]` attributes leave in force, read in
|
||||
/// order. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and nothing lowers a
|
||||
/// `forbid`. The check does not evaluate `cfg_attr` conditions: a `deny` or `forbid` inside
|
||||
/// `cfg_attr(...)` does not count, and an `allow`, `warn` or `expect` inside one lowers the level.
|
||||
fn doc_test_level(attrs: &[String]) -> Option<Level> {
|
||||
let mut level = None;
|
||||
for doc in attrs.iter().filter_map(|a| args(a, "doc")) {
|
||||
for test in items(doc).into_iter().filter_map(|i| args(i, "test")) {
|
||||
for attr in items(test).into_iter().filter_map(|i| args(i, "attr")) {
|
||||
for lint in items(attr) {
|
||||
let direct = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l));
|
||||
let next = direct.or_else(|| sets_level(lint, &["allow", "warn", "expect"]).then_some(Level::Allow));
|
||||
if let Some(next) = next
|
||||
&& level != Some(Level::Forbid)
|
||||
{
|
||||
level = Some(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
level
|
||||
}
|
||||
|
||||
/// Whether `attr` is one of the lint attributes `names` applied to `unsafe_code`, directly or
|
||||
/// inside `cfg_attr(...)`, whatever its condition.
|
||||
fn sets_level(attr: &str, names: &[&str]) -> bool {
|
||||
if names.iter().any(|name| args(attr, name).is_some_and(names_unsafe_code)) {
|
||||
return true;
|
||||
}
|
||||
args(attr, "cfg_attr").is_some_and(|inner| items(inner).into_iter().skip(1).any(|a| sets_level(a, names)))
|
||||
}
|
||||
|
||||
/// The argument list of `item` when it is exactly `name(...)`.
|
||||
fn args<'a>(item: &'a str, name: &str) -> Option<&'a str> {
|
||||
let rest = item.strip_prefix(name)?.strip_prefix('(')?.strip_suffix(')')?;
|
||||
let mut depth = 0usize;
|
||||
for ch in rest.chars() {
|
||||
match ch {
|
||||
'(' => depth += 1,
|
||||
')' if depth == 0 => return None,
|
||||
')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(depth == 0).then_some(rest)
|
||||
}
|
||||
|
||||
/// The comma-separated items of a list such as `deny(warnings),forbid(unsafe_code)`, split only
|
||||
/// at the top level.
|
||||
fn items(list: &str) -> Vec<&str> {
|
||||
let mut out = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
let mut item_start = 0;
|
||||
for (k, ch) in list.char_indices().chain(std::iter::once((list.len(), ','))) {
|
||||
match ch {
|
||||
'(' => depth += 1,
|
||||
')' => depth = depth.saturating_sub(1),
|
||||
',' if depth == 0 => {
|
||||
if k > item_start {
|
||||
out.push(&list[item_start..k]);
|
||||
}
|
||||
item_start = k + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body of every crate-level `#![...]` attribute in `src`, without whitespace, read across
|
||||
/// line breaks. Attributes inside braces (a module, a function) are skipped, comments are
|
||||
/// skipped, and string and character literals are read as empty.
|
||||
fn inner_attributes(src: &str) -> Vec<String> {
|
||||
let code: Vec<char> = code_only(src).chars().filter(|c| !c.is_whitespace()).collect();
|
||||
let mut out = Vec::new();
|
||||
let mut braces = 0usize;
|
||||
let mut i = 0;
|
||||
while i + 2 < code.len() {
|
||||
if code[i] == '{' {
|
||||
braces += 1;
|
||||
} else if code[i] == '}' {
|
||||
braces = braces.saturating_sub(1);
|
||||
}
|
||||
if braces > 0 || code[i] != '#' || code[i + 1] != '!' || code[i + 2] != '[' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let start = i + 3;
|
||||
let mut depth = 1usize;
|
||||
let mut j = start;
|
||||
while j < code.len() && depth > 0 {
|
||||
match code[j] {
|
||||
'[' => depth += 1,
|
||||
']' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if depth > 0 {
|
||||
break;
|
||||
}
|
||||
out.push(code[start..j - 1].iter().collect());
|
||||
i = j;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `src` with line and (nested) block comments replaced by a space, and the contents of string,
|
||||
/// raw string (including raw byte and raw C string) and character literals removed.
|
||||
fn code_only(src: &str) -> String {
|
||||
let c: Vec<char> = src.chars().collect();
|
||||
let mut out = String::with_capacity(src.len());
|
||||
let mut i = 0;
|
||||
while i < c.len() {
|
||||
let next = c.get(i + 1).copied();
|
||||
let ident_before = i > 0 && (c[i - 1].is_alphanumeric() || c[i - 1] == '_');
|
||||
match c[i] {
|
||||
'/' if next == Some('/') => {
|
||||
while i < c.len() && c[i] != '\n' {
|
||||
i += 1;
|
||||
}
|
||||
out.push(' ');
|
||||
}
|
||||
'/' if next == Some('*') => {
|
||||
let mut depth = 0usize;
|
||||
while i < c.len() {
|
||||
if c[i] == '/' && c.get(i + 1) == Some(&'*') {
|
||||
depth += 1;
|
||||
i += 2;
|
||||
} else if c[i] == '*' && c.get(i + 1) == Some(&'/') {
|
||||
depth = depth.saturating_sub(1);
|
||||
i += 2;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out.push(' ');
|
||||
}
|
||||
'r' | 'b' | 'c' if !ident_before && raw_string_hashes(&c, i).is_some() => {
|
||||
let (open, hashes) = raw_string_hashes(&c, i).unwrap_or((i, 0));
|
||||
let mut j = open + 1;
|
||||
while j < c.len() && !(c[j] == '"' && (1..=hashes).all(|k| c.get(j + k) == Some(&'#'))) {
|
||||
j += 1;
|
||||
}
|
||||
out.push_str("\"\"");
|
||||
i = j + 1 + hashes;
|
||||
}
|
||||
'"' => {
|
||||
let mut j = i + 1;
|
||||
while j < c.len() && c[j] != '"' {
|
||||
j += if c[j] == '\\' { 2 } else { 1 };
|
||||
}
|
||||
out.push_str("\"\"");
|
||||
i = j + 1;
|
||||
}
|
||||
'\'' if next == Some('\\') => {
|
||||
let mut j = i + 3;
|
||||
while j < c.len() && c[j] != '\'' {
|
||||
j += 1;
|
||||
}
|
||||
out.push_str("''");
|
||||
i = j + 1;
|
||||
}
|
||||
'\'' if c.get(i + 2) == Some(&'\'') => {
|
||||
out.push_str("''");
|
||||
i += 3;
|
||||
}
|
||||
ch => {
|
||||
out.push(ch);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For a raw string literal starting at `i` (`r"`, `r#"`, `br"`, `cr"`...), the index of its
|
||||
/// opening quote and its number of `#`s.
|
||||
fn raw_string_hashes(c: &[char], i: usize) -> Option<(usize, usize)> {
|
||||
let mut j = i;
|
||||
if matches!(c.get(j), Some('b' | 'c')) {
|
||||
j += 1;
|
||||
}
|
||||
if c.get(j) != Some(&'r') {
|
||||
return None;
|
||||
}
|
||||
j += 1;
|
||||
let hashes = c[j..].iter().take_while(|&&ch| ch == '#').count();
|
||||
(c.get(j + hashes) == Some(&'"')).then_some((j + hashes, hashes))
|
||||
}
|
||||
|
||||
/// Whether a lint list such as `unsafe_code,unused_must_use` names `unsafe_code`.
|
||||
fn names_unsafe_code(list: &str) -> bool {
|
||||
items(list).contains(&"unsafe_code")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::problem;
|
||||
|
||||
const NEEDS_DENY: Option<&str> = Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]");
|
||||
const NEEDS_FORBID: Option<&str> = Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]");
|
||||
|
||||
#[test]
|
||||
fn a_forbidding_library_needs_forbid_in_its_doc_tests() {
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n"), NEEDS_FORBID);
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_on_the_workspace_deny_needs_deny_or_forbid() {
|
||||
assert_eq!(problem("//! Docs.\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
|
||||
assert_eq!(problem("#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
|
||||
assert_eq!(problem("//! Docs.\npub fn f() {}\n"), NEEDS_DENY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_other_lints_and_allow_do_not_count() {
|
||||
assert_eq!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![doc(test(attr(allow(unsafe_code))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![doc(test(attr(deny(warnings))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![deny(unsafe_code)]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("// #![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n// #![doc(test(attr(forbid(unsafe_code))))]\n"), NEEDS_FORBID);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_inside_a_module_do_not_count() {
|
||||
assert_eq!(problem("mod tests {\n #![doc(test(attr(deny(unsafe_code))))]\n}\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\nmod a { #![doc(test(attr(forbid(unsafe_code))))] }\n"), NEEDS_FORBID);
|
||||
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a { #![forbid(unsafe_code)] }\n"), None);
|
||||
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a {\n fn f() {}\n}\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacing_and_other_attributes_in_the_list_are_accepted() {
|
||||
assert_eq!(problem("#![doc(test(attr(deny(warnings), forbid( unsafe_code ))))]\n#![forbid(unsafe_code)]\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_comments_and_string_literals_do_not_count() {
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n"), NEEDS_FORBID);
|
||||
assert_eq!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nconst S: &CStr = cr#\"\" #![forbid(unsafe_code)] \"#;\n"), None);
|
||||
assert_eq!(problem("const Q: char = '\\'';\nconst S: &str = \"/*\";\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_may_span_several_lines() {
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(\n forbid(unsafe_code)\n)))]\n"), None);
|
||||
assert_eq!(problem("#![forbid(\n unsafe_code\n)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_lint_lists_are_read_item_by_item() {
|
||||
let grouped = "#![forbid(unsafe_code, unused_must_use)]\n";
|
||||
assert_eq!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")), NEEDS_FORBID);
|
||||
assert_eq!(problem(&format!("{grouped}#![doc(test(attr(forbid(unused_must_use, unsafe_code))))]\n")), None);
|
||||
assert_eq!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
|
||||
assert_eq!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n"), NEEDS_DENY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lint_inside_cfg_attr_does_not_count() {
|
||||
assert_eq!(problem("#![doc(test(attr(cfg_attr(any(), deny(unsafe_code)))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(cfg_attr(any(), forbid(unsafe_code)))))]\n"), NEEDS_FORBID);
|
||||
assert_eq!(problem("#![doc(test(no_crate_inject, attr(deny(unsafe_code))))]\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cfg_attr_can_only_lower_the_doc_tests_or_raise_the_library() {
|
||||
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(all(), allow(unsafe_code)))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(test, cfg_attr(all(), warn(unsafe_code))))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID);
|
||||
assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None);
|
||||
assert_eq!(problem("#![cfg_attr(forbid, deny(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_allow_lowers_deny_but_not_forbid() {
|
||||
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\n#![doc(test(attr(warn(unsafe_code))))]\n"), NEEDS_DENY);
|
||||
assert_eq!(problem("#![doc(test(attr(allow(unsafe_code), deny(unsafe_code))))]\n"), None);
|
||||
assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code), allow(unsafe_code))))]\n"), None);
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -9,6 +9,7 @@ mod brands;
|
||||
mod bundle;
|
||||
mod cache_units;
|
||||
mod cursors;
|
||||
mod doc_tests;
|
||||
mod grant_sites;
|
||||
mod ico;
|
||||
mod layers;
|
||||
@@ -200,7 +201,8 @@ pub fn metadata() -> Result<serde_json::Value, String> {
|
||||
}
|
||||
|
||||
fn cmd_layers() -> Result<(), String> {
|
||||
let crates = layers::from_metadata(&metadata()?)?;
|
||||
let meta = metadata()?;
|
||||
let crates = layers::from_metadata(&meta)?;
|
||||
println!("Dependency layering (plan/architecture.md §3)\n");
|
||||
println!("{:<28} {:<14} workspace deps", "crate", "layer");
|
||||
for c in &crates {
|
||||
@@ -219,17 +221,18 @@ fn cmd_layers() -> Result<(), String> {
|
||||
.collect();
|
||||
println!("{:<28} {:<14} {}", c.name, layers::describe(layers::classify(&c.name)), ws.join(", "));
|
||||
}
|
||||
let violations = layers::check(&crates);
|
||||
let mut violations: Vec<String> = layers::check(&crates).iter().map(ToString::to_string).collect();
|
||||
violations.extend(doc_tests::check(&meta)?);
|
||||
println!();
|
||||
if violations.is_empty() {
|
||||
println!("OK: {} crates, no layering violations.", crates.len());
|
||||
println!("OK: {} crates, no layering violations, and every library's doc tests deny unsafe code.", crates.len());
|
||||
Ok(())
|
||||
} else {
|
||||
println!("{} violation(s):", violations.len());
|
||||
for v in &violations {
|
||||
println!(" - {v}");
|
||||
}
|
||||
Err(format!("{} layering violation(s)", violations.len()))
|
||||
Err(format!("{} violation(s)", violations.len()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user