Skip to content

Commit 7f80b44

Browse files
committedFeb 5, 2024
new lint: manual_c_str_literals
1 parent 8baeb26 commit 7f80b44

12 files changed

+444
-3
lines changed
 

‎CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5340,6 +5340,7 @@ Released 2018-09-13
53405340
[`manual_assert`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_assert
53415341
[`manual_async_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_async_fn
53425342
[`manual_bits`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits
5343+
[`manual_c_str_literals`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_c_str_literals
53435344
[`manual_clamp`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_clamp
53445345
[`manual_filter`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_filter
53455346
[`manual_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_filter_map

‎book/src/lint_configuration.md

+1
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ The minimum rust version that the project supports. Defaults to the `rust-versio
151151
* [`manual_try_fold`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_try_fold)
152152
* [`manual_hash_one`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_hash_one)
153153
* [`iter_kv_map`](https://rust-lang.github.io/rust-clippy/master/index.html#iter_kv_map)
154+
* [`manual_c_str_literals`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_c_str_literals)
154155

155156

156157
## `cognitive-complexity-threshold`

‎clippy_config/src/conf.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ define_Conf! {
260260
///
261261
/// Suppress lints whenever the suggested change would cause breakage for other crates.
262262
(avoid_breaking_exported_api: bool = true),
263-
/// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, OPTION_MAP_UNWRAP_OR, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS, TUPLE_ARRAY_CONVERSIONS, MANUAL_TRY_FOLD, MANUAL_HASH_ONE, ITER_KV_MAP.
263+
/// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, OPTION_MAP_UNWRAP_OR, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS, TUPLE_ARRAY_CONVERSIONS, MANUAL_TRY_FOLD, MANUAL_HASH_ONE, ITER_KV_MAP, MANUAL_C_STR_LITERALS.
264264
///
265265
/// The minimum rust version that the project supports. Defaults to the `rust-version` field in `Cargo.toml`
266266
#[default_text = ""]

‎clippy_config/src/msrvs.rs

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ macro_rules! msrv_aliases {
1717

1818
// names may refer to stabilized feature flags or library items
1919
msrv_aliases! {
20+
1,77,0 { C_STR_LITERALS }
2021
1,76,0 { PTR_FROM_REF }
2122
1,71,0 { TUPLE_ARRAY_CONVERSIONS, BUILD_HASHER_HASH_ONE }
2223
1,70,0 { OPTION_RESULT_IS_VARIANT_AND, BINARY_HEAP_RETAIN }

‎clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
387387
crate::methods::ITER_SKIP_ZERO_INFO,
388388
crate::methods::ITER_WITH_DRAIN_INFO,
389389
crate::methods::JOIN_ABSOLUTE_PATHS_INFO,
390+
crate::methods::MANUAL_C_STR_LITERALS_INFO,
390391
crate::methods::MANUAL_FILTER_MAP_INFO,
391392
crate::methods::MANUAL_FIND_MAP_INFO,
392393
crate::methods::MANUAL_IS_VARIANT_AND_INFO,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
use clippy_config::msrvs::{self, Msrv};
2+
use clippy_utils::diagnostics::span_lint_and_sugg;
3+
use clippy_utils::get_parent_expr;
4+
use clippy_utils::source::snippet;
5+
use rustc_ast::{LitKind, StrStyle};
6+
use rustc_errors::Applicability;
7+
use rustc_hir::{Expr, ExprKind, Node, QPath, TyKind};
8+
use rustc_lint::LateContext;
9+
use rustc_span::{sym, Span, Symbol};
10+
11+
use super::MANUAL_C_STR_LITERALS;
12+
13+
/// Checks:
14+
/// - `b"...".as_ptr()`
15+
/// - `b"...".as_ptr().cast()`
16+
/// - `"...".as_ptr()`
17+
/// - `"...".as_ptr().cast()`
18+
///
19+
/// Iff the parent call of `.cast()` isn't `CStr::from_ptr`, to avoid linting twice.
20+
pub(super) fn check_as_ptr<'tcx>(
21+
cx: &LateContext<'tcx>,
22+
expr: &'tcx Expr<'tcx>,
23+
receiver: &'tcx Expr<'tcx>,
24+
msrv: &Msrv,
25+
) {
26+
if let ExprKind::Lit(lit) = receiver.kind
27+
&& let LitKind::ByteStr(_, StrStyle::Cooked) | LitKind::Str(_, StrStyle::Cooked) = lit.node
28+
&& let casts_removed = peel_ptr_cast_ancestors(cx, expr)
29+
&& !get_parent_expr(cx, casts_removed).is_some_and(
30+
|parent| matches!(parent.kind, ExprKind::Call(func, _) if is_c_str_function(cx, func).is_some()),
31+
)
32+
&& let Some(sugg) = rewrite_as_cstr(cx, lit.span)
33+
&& msrv.meets(msrvs::C_STR_LITERALS)
34+
{
35+
span_lint_and_sugg(
36+
cx,
37+
MANUAL_C_STR_LITERALS,
38+
receiver.span,
39+
"manually constructing a nul-terminated string",
40+
r#"use a `c""` literal"#,
41+
sugg,
42+
// an additional cast may be needed, since the type of `CStr::as_ptr` and
43+
// `"".as_ptr()` can differ and is platform dependent
44+
Applicability::HasPlaceholders,
45+
);
46+
}
47+
}
48+
49+
/// Checks if the callee is a "relevant" `CStr` function considered by this lint.
50+
/// Returns the function name.
51+
fn is_c_str_function(cx: &LateContext<'_>, func: &Expr<'_>) -> Option<Symbol> {
52+
if let ExprKind::Path(QPath::TypeRelative(cstr, fn_name)) = &func.kind
53+
&& let TyKind::Path(QPath::Resolved(_, ty_path)) = &cstr.kind
54+
&& cx.tcx.lang_items().c_str() == ty_path.res.opt_def_id()
55+
{
56+
Some(fn_name.ident.name)
57+
} else {
58+
None
59+
}
60+
}
61+
62+
/// Checks calls to the `CStr` constructor functions:
63+
/// - `CStr::from_bytes_with_nul(..)`
64+
/// - `CStr::from_bytes_with_nul_unchecked(..)`
65+
/// - `CStr::from_ptr(..)`
66+
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, func: &Expr<'_>, args: &[Expr<'_>], msrv: &Msrv) {
67+
if let Some(fn_name) = is_c_str_function(cx, func)
68+
&& let [arg] = args
69+
&& msrv.meets(msrvs::C_STR_LITERALS)
70+
{
71+
match fn_name.as_str() {
72+
name @ ("from_bytes_with_nul" | "from_bytes_with_nul_unchecked")
73+
if !arg.span.from_expansion()
74+
&& let ExprKind::Lit(lit) = arg.kind
75+
&& let LitKind::ByteStr(_, StrStyle::Cooked) | LitKind::Str(_, StrStyle::Cooked) = lit.node =>
76+
{
77+
check_from_bytes(cx, expr, arg, name);
78+
},
79+
"from_ptr" => check_from_ptr(cx, expr, arg),
80+
_ => {},
81+
}
82+
}
83+
}
84+
85+
/// Checks `CStr::from_ptr(b"foo\0".as_ptr().cast())`
86+
fn check_from_ptr(cx: &LateContext<'_>, expr: &Expr<'_>, arg: &Expr<'_>) {
87+
if let ExprKind::MethodCall(method, lit, ..) = peel_ptr_cast(arg).kind
88+
&& method.ident.name == sym::as_ptr
89+
&& !lit.span.from_expansion()
90+
&& let ExprKind::Lit(lit) = lit.kind
91+
&& let LitKind::ByteStr(_, StrStyle::Cooked) = lit.node
92+
&& let Some(sugg) = rewrite_as_cstr(cx, lit.span)
93+
{
94+
span_lint_and_sugg(
95+
cx,
96+
MANUAL_C_STR_LITERALS,
97+
expr.span,
98+
"calling `CStr::from_ptr` with a byte string literal",
99+
r#"use a `c""` literal"#,
100+
sugg,
101+
Applicability::MachineApplicable,
102+
);
103+
}
104+
}
105+
/// Checks `CStr::from_bytes_with_nul(b"foo\0")`
106+
fn check_from_bytes(cx: &LateContext<'_>, expr: &Expr<'_>, arg: &Expr<'_>, method: &str) {
107+
let (span, applicability) = if let Some(parent) = get_parent_expr(cx, expr)
108+
&& let ExprKind::MethodCall(method, ..) = parent.kind
109+
&& [sym::unwrap, sym::expect].contains(&method.ident.name)
110+
{
111+
(parent.span, Applicability::MachineApplicable)
112+
} else if method == "from_bytes_with_nul_unchecked" {
113+
// `*_unchecked` returns `&CStr` directly, nothing needs to be changed
114+
(expr.span, Applicability::MachineApplicable)
115+
} else {
116+
// User needs to remove error handling, can't be machine applicable
117+
(expr.span, Applicability::HasPlaceholders)
118+
};
119+
120+
let Some(sugg) = rewrite_as_cstr(cx, arg.span) else {
121+
return;
122+
};
123+
124+
span_lint_and_sugg(
125+
cx,
126+
MANUAL_C_STR_LITERALS,
127+
span,
128+
"calling `CStr::new` with a byte string literal",
129+
r#"use a `c""` literal"#,
130+
sugg,
131+
applicability,
132+
);
133+
}
134+
135+
/// Rewrites a byte string literal to a c-str literal.
136+
/// `b"foo\0"` -> `c"foo"`
137+
///
138+
/// Returns `None` if it doesn't end in a NUL byte.
139+
fn rewrite_as_cstr(cx: &LateContext<'_>, span: Span) -> Option<String> {
140+
let mut sugg = String::from("c") + snippet(cx, span.source_callsite(), "..").trim_start_matches('b');
141+
142+
// NUL byte should always be right before the closing quote.
143+
if let Some(quote_pos) = sugg.rfind('"') {
144+
// Possible values right before the quote:
145+
// - literal NUL value
146+
if sugg.as_bytes()[quote_pos - 1] == b'\0' {
147+
sugg.remove(quote_pos - 1);
148+
}
149+
// - \x00
150+
else if sugg[..quote_pos].ends_with("\\x00") {
151+
sugg.replace_range(quote_pos - 4..quote_pos, "");
152+
}
153+
// - \0
154+
else if sugg[..quote_pos].ends_with("\\0") {
155+
sugg.replace_range(quote_pos - 2..quote_pos, "");
156+
}
157+
// No known suffix, so assume it's not a C-string.
158+
else {
159+
return None;
160+
}
161+
}
162+
163+
Some(sugg)
164+
}
165+
166+
fn get_cast_target<'tcx>(e: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
167+
match &e.kind {
168+
ExprKind::MethodCall(method, receiver, [], _) if method.ident.as_str() == "cast" => Some(receiver),
169+
ExprKind::Cast(expr, _) => Some(expr),
170+
_ => None,
171+
}
172+
}
173+
174+
/// `x.cast()` -> `x`
175+
/// `x as *const _` -> `x`
176+
/// `x` -> `x` (returns the same expression for non-cast exprs)
177+
fn peel_ptr_cast<'tcx>(e: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
178+
get_cast_target(e).map_or(e, peel_ptr_cast)
179+
}
180+
181+
/// Same as `peel_ptr_cast`, but the other way around, by walking up the ancestor cast expressions:
182+
///
183+
/// `foo(x.cast() as *const _)`
184+
/// ^ given this `x` expression, returns the `foo(...)` expression
185+
fn peel_ptr_cast_ancestors<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
186+
let mut prev = e;
187+
for (_, node) in cx.tcx.hir().parent_iter(e.hir_id) {
188+
if let Node::Expr(e) = node
189+
&& get_cast_target(e).is_some()
190+
{
191+
prev = e;
192+
} else {
193+
break;
194+
}
195+
}
196+
prev
197+
}

‎clippy_lints/src/methods/mod.rs

+37
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ mod iter_skip_zero;
5151
mod iter_with_drain;
5252
mod iterator_step_by_zero;
5353
mod join_absolute_paths;
54+
mod manual_c_str_literals;
5455
mod manual_is_variant_and;
5556
mod manual_next_back;
5657
mod manual_ok_or;
@@ -3977,6 +3978,39 @@ declare_clippy_lint! {
39773978
"making no use of the \"map closure\" when calling `.map_or_else(|err| handle_error(err), |n| n)`"
39783979
}
39793980

3981+
declare_clippy_lint! {
3982+
/// Checks for the manual creation of C strings (a string with a `NUL` byte at the end), either
3983+
/// through one of the `CStr` constructor functions, or more plainly by calling `.as_ptr()`
3984+
/// on a (byte) string literal with a hardcoded `\0` byte at the end.
3985+
///
3986+
/// ### Why is this bad?
3987+
/// This can be written more concisely using `c"str"` literals and is also less error-prone,
3988+
/// because the compiler checks for interior `NUL` bytes and the terminating `NUL` byte is inserted automatically.
3989+
///
3990+
/// ### Example
3991+
/// ```no_run
3992+
/// # use std::ffi::CStr;
3993+
/// # mod libc { pub unsafe fn puts(_: *const i8) {} }
3994+
/// fn needs_cstr(_: &CStr) {}
3995+
///
3996+
/// needs_cstr(CStr::from_bytes_with_nul(b"Hello\0").unwrap());
3997+
/// unsafe { libc::puts("World\0".as_ptr().cast()) }
3998+
/// ```
3999+
/// Use instead:
4000+
/// ```no_run
4001+
/// # use std::ffi::CStr;
4002+
/// # mod libc { pub unsafe fn puts(_: *const i8) {} }
4003+
/// fn needs_cstr(_: &CStr) {}
4004+
///
4005+
/// needs_cstr(c"Hello");
4006+
/// unsafe { libc::puts(c"World".as_ptr()) }
4007+
/// ```
4008+
#[clippy::version = "1.76.0"]
4009+
pub MANUAL_C_STR_LITERALS,
4010+
pedantic,
4011+
r#"creating a `CStr` through functions when `c""` literals can be used"#
4012+
}
4013+
39804014
pub struct Methods {
39814015
avoid_breaking_exported_api: bool,
39824016
msrv: Msrv,
@@ -4136,6 +4170,7 @@ impl_lint_pass!(Methods => [
41364170
STR_SPLIT_AT_NEWLINE,
41374171
OPTION_AS_REF_CLONED,
41384172
UNNECESSARY_RESULT_MAP_OR_ELSE,
4173+
MANUAL_C_STR_LITERALS,
41394174
]);
41404175

41414176
/// Extracts a method call name, args, and `Span` of the method name.
@@ -4163,6 +4198,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
41634198
hir::ExprKind::Call(func, args) => {
41644199
from_iter_instead_of_collect::check(cx, expr, args, func);
41654200
unnecessary_fallible_conversions::check_function(cx, expr, func);
4201+
manual_c_str_literals::check(cx, expr, func, args, &self.msrv);
41664202
},
41674203
hir::ExprKind::MethodCall(method_call, receiver, args, _) => {
41684204
let method_span = method_call.ident.span;
@@ -4381,6 +4417,7 @@ impl Methods {
43814417
}
43824418
},
43834419
("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
4420+
("as_ptr", []) => manual_c_str_literals::check_as_ptr(cx, expr, recv, &self.msrv),
43844421
("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
43854422
("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
43864423
("cloned", []) => {

‎tests/ui/manual_c_str_literals.fixed

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#![warn(clippy::manual_c_str_literals)]
2+
#![allow(clippy::no_effect)]
3+
4+
use std::ffi::CStr;
5+
6+
macro_rules! cstr {
7+
($s:literal) => {
8+
CStr::from_bytes_with_nul(concat!($s, "\0").as_bytes()).unwrap()
9+
};
10+
}
11+
12+
macro_rules! macro_returns_c_str {
13+
() => {
14+
CStr::from_bytes_with_nul(b"foo\0").unwrap();
15+
};
16+
}
17+
18+
macro_rules! macro_returns_byte_string {
19+
() => {
20+
b"foo\0"
21+
};
22+
}
23+
24+
#[clippy::msrv = "1.76.0"]
25+
fn pre_stabilization() {
26+
CStr::from_bytes_with_nul(b"foo\0");
27+
}
28+
29+
#[clippy::msrv = "1.77.0"]
30+
fn post_stabilization() {
31+
c"foo";
32+
}
33+
34+
fn main() {
35+
c"foo";
36+
c"foo";
37+
c"foo";
38+
c"foo\\0sdsd";
39+
CStr::from_bytes_with_nul(br"foo\\0sdsd\0").unwrap();
40+
CStr::from_bytes_with_nul(br"foo\x00").unwrap();
41+
CStr::from_bytes_with_nul(br##"foo#a\0"##).unwrap();
42+
43+
unsafe { c"foo" };
44+
unsafe { c"foo" };
45+
let _: *const _ = c"foo".as_ptr();
46+
let _: *const _ = c"foo".as_ptr();
47+
let _: *const _ = "foo".as_ptr(); // not a C-string
48+
let _: *const _ = "".as_ptr();
49+
let _: *const _ = c"foo".as_ptr().cast::<i8>();
50+
let _ = "电脑".as_ptr();
51+
let _ = "电脑\\".as_ptr();
52+
let _ = c"电脑\\".as_ptr();
53+
let _ = c"电脑".as_ptr();
54+
let _ = c"电脑".as_ptr();
55+
56+
// Macro cases, don't lint:
57+
cstr!("foo");
58+
macro_returns_c_str!();
59+
CStr::from_bytes_with_nul(macro_returns_byte_string!()).unwrap();
60+
}

‎tests/ui/manual_c_str_literals.rs

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#![warn(clippy::manual_c_str_literals)]
2+
#![allow(clippy::no_effect)]
3+
4+
use std::ffi::CStr;
5+
6+
macro_rules! cstr {
7+
($s:literal) => {
8+
CStr::from_bytes_with_nul(concat!($s, "\0").as_bytes()).unwrap()
9+
};
10+
}
11+
12+
macro_rules! macro_returns_c_str {
13+
() => {
14+
CStr::from_bytes_with_nul(b"foo\0").unwrap();
15+
};
16+
}
17+
18+
macro_rules! macro_returns_byte_string {
19+
() => {
20+
b"foo\0"
21+
};
22+
}
23+
24+
#[clippy::msrv = "1.76.0"]
25+
fn pre_stabilization() {
26+
CStr::from_bytes_with_nul(b"foo\0");
27+
}
28+
29+
#[clippy::msrv = "1.77.0"]
30+
fn post_stabilization() {
31+
CStr::from_bytes_with_nul(b"foo\0");
32+
}
33+
34+
fn main() {
35+
CStr::from_bytes_with_nul(b"foo\0");
36+
CStr::from_bytes_with_nul(b"foo\x00");
37+
CStr::from_bytes_with_nul(b"foo\0").unwrap();
38+
CStr::from_bytes_with_nul(b"foo\\0sdsd\0").unwrap();
39+
CStr::from_bytes_with_nul(br"foo\\0sdsd\0").unwrap();
40+
CStr::from_bytes_with_nul(br"foo\x00").unwrap();
41+
CStr::from_bytes_with_nul(br##"foo#a\0"##).unwrap();
42+
43+
unsafe { CStr::from_ptr(b"foo\0".as_ptr().cast()) };
44+
unsafe { CStr::from_ptr(b"foo\0".as_ptr() as *const _) };
45+
let _: *const _ = b"foo\0".as_ptr();
46+
let _: *const _ = "foo\0".as_ptr();
47+
let _: *const _ = "foo".as_ptr(); // not a C-string
48+
let _: *const _ = "".as_ptr();
49+
let _: *const _ = b"foo\0".as_ptr().cast::<i8>();
50+
let _ = "电脑".as_ptr();
51+
let _ = "电脑\\".as_ptr();
52+
let _ = "电脑\\\0".as_ptr();
53+
let _ = "电脑\0".as_ptr();
54+
let _ = "电脑\x00".as_ptr();
55+
56+
// Macro cases, don't lint:
57+
cstr!("foo");
58+
macro_returns_c_str!();
59+
CStr::from_bytes_with_nul(macro_returns_byte_string!()).unwrap();
60+
}

‎tests/ui/manual_c_str_literals.stderr

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
error: calling `CStr::new` with a byte string literal
2+
--> $DIR/manual_c_str_literals.rs:31:5
3+
|
4+
LL | CStr::from_bytes_with_nul(b"foo\0");
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use a `c""` literal: `c"foo"`
6+
|
7+
= note: `-D clippy::manual-c-str-literals` implied by `-D warnings`
8+
= help: to override `-D warnings` add `#[allow(clippy::manual_c_str_literals)]`
9+
10+
error: calling `CStr::new` with a byte string literal
11+
--> $DIR/manual_c_str_literals.rs:35:5
12+
|
13+
LL | CStr::from_bytes_with_nul(b"foo\0");
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use a `c""` literal: `c"foo"`
15+
16+
error: calling `CStr::new` with a byte string literal
17+
--> $DIR/manual_c_str_literals.rs:36:5
18+
|
19+
LL | CStr::from_bytes_with_nul(b"foo\x00");
20+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use a `c""` literal: `c"foo"`
21+
22+
error: calling `CStr::new` with a byte string literal
23+
--> $DIR/manual_c_str_literals.rs:37:5
24+
|
25+
LL | CStr::from_bytes_with_nul(b"foo\0").unwrap();
26+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use a `c""` literal: `c"foo"`
27+
28+
error: calling `CStr::new` with a byte string literal
29+
--> $DIR/manual_c_str_literals.rs:38:5
30+
|
31+
LL | CStr::from_bytes_with_nul(b"foo\\0sdsd\0").unwrap();
32+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use a `c""` literal: `c"foo\\0sdsd"`
33+
34+
error: calling `CStr::from_ptr` with a byte string literal
35+
--> $DIR/manual_c_str_literals.rs:43:14
36+
|
37+
LL | unsafe { CStr::from_ptr(b"foo\0".as_ptr().cast()) };
38+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use a `c""` literal: `c"foo"`
39+
40+
error: calling `CStr::from_ptr` with a byte string literal
41+
--> $DIR/manual_c_str_literals.rs:44:14
42+
|
43+
LL | unsafe { CStr::from_ptr(b"foo\0".as_ptr() as *const _) };
44+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use a `c""` literal: `c"foo"`
45+
46+
error: manually constructing a nul-terminated string
47+
--> $DIR/manual_c_str_literals.rs:45:23
48+
|
49+
LL | let _: *const _ = b"foo\0".as_ptr();
50+
| ^^^^^^^^ help: use a `c""` literal: `c"foo"`
51+
52+
error: manually constructing a nul-terminated string
53+
--> $DIR/manual_c_str_literals.rs:46:23
54+
|
55+
LL | let _: *const _ = "foo\0".as_ptr();
56+
| ^^^^^^^ help: use a `c""` literal: `c"foo"`
57+
58+
error: manually constructing a nul-terminated string
59+
--> $DIR/manual_c_str_literals.rs:49:23
60+
|
61+
LL | let _: *const _ = b"foo\0".as_ptr().cast::<i8>();
62+
| ^^^^^^^^ help: use a `c""` literal: `c"foo"`
63+
64+
error: manually constructing a nul-terminated string
65+
--> $DIR/manual_c_str_literals.rs:52:13
66+
|
67+
LL | let _ = "电脑\\\0".as_ptr();
68+
| ^^^^^^^^^^ help: use a `c""` literal: `c"电脑\\"`
69+
70+
error: manually constructing a nul-terminated string
71+
--> $DIR/manual_c_str_literals.rs:53:13
72+
|
73+
LL | let _ = "电脑\0".as_ptr();
74+
| ^^^^^^^^ help: use a `c""` literal: `c"电脑"`
75+
76+
error: manually constructing a nul-terminated string
77+
--> $DIR/manual_c_str_literals.rs:54:13
78+
|
79+
LL | let _ = "电脑\x00".as_ptr();
80+
| ^^^^^^^^^^ help: use a `c""` literal: `c"电脑"`
81+
82+
error: aborting due to 13 previous errors
83+

‎tests/ui/strlen_on_c_strings.fixed

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#![warn(clippy::strlen_on_c_strings)]
2-
#![allow(dead_code)]
2+
#![allow(dead_code, clippy::manual_c_str_literals)]
33
#![feature(rustc_private)]
44
extern crate libc;
55

‎tests/ui/strlen_on_c_strings.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#![warn(clippy::strlen_on_c_strings)]
2-
#![allow(dead_code)]
2+
#![allow(dead_code, clippy::manual_c_str_literals)]
33
#![feature(rustc_private)]
44
extern crate libc;
55

0 commit comments

Comments
 (0)
Please sign in to comment.