Skip to content

Commit 982124a

Browse files
committed
Add new lint octal_escapes
This checks for sequences in strings that would be octal character escapes in C, but are not supported in Rust. It suggests either to use the `\x00` escape, or an equivalent hex escape if the octal was intended.
1 parent 38bd251 commit 982124a

8 files changed

+216
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3056,6 +3056,7 @@ Released 2018-09-13
30563056
[`nonsensical_open_options`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonsensical_open_options
30573057
[`nonstandard_macro_braces`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonstandard_macro_braces
30583058
[`not_unsafe_ptr_arg_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#not_unsafe_ptr_arg_deref
3059+
[`octal_escapes`]: https://rust-lang.github.io/rust-clippy/master/index.html#octal_escapes
30593060
[`ok_expect`]: https://rust-lang.github.io/rust-clippy/master/index.html#ok_expect
30603061
[`op_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
30613062
[`option_as_ref_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref

clippy_lints/src/lib.register_all.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
219219
LintId::of(non_expressive_names::JUST_UNDERSCORES_AND_DIGITS),
220220
LintId::of(non_octal_unix_permissions::NON_OCTAL_UNIX_PERMISSIONS),
221221
LintId::of(non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY),
222+
LintId::of(octal_escapes::OCTAL_ESCAPES),
222223
LintId::of(open_options::NONSENSICAL_OPEN_OPTIONS),
223224
LintId::of(option_env_unwrap::OPTION_ENV_UNWRAP),
224225
LintId::of(overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL),

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@ store.register_lints(&[
380380
non_octal_unix_permissions::NON_OCTAL_UNIX_PERMISSIONS,
381381
non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY,
382382
nonstandard_macro_braces::NONSTANDARD_MACRO_BRACES,
383+
octal_escapes::OCTAL_ESCAPES,
383384
open_options::NONSENSICAL_OPEN_OPTIONS,
384385
option_env_unwrap::OPTION_ENV_UNWRAP,
385386
option_if_let_else::OPTION_IF_LET_ELSE,

clippy_lints/src/lib.register_suspicious.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec!
1616
LintId::of(methods::SUSPICIOUS_MAP),
1717
LintId::of(mut_key::MUTABLE_KEY_TYPE),
1818
LintId::of(non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY),
19+
LintId::of(octal_escapes::OCTAL_ESCAPES),
1920
LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
2021
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
2122
])

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ mod non_expressive_names;
312312
mod non_octal_unix_permissions;
313313
mod non_send_fields_in_send_ty;
314314
mod nonstandard_macro_braces;
315+
mod octal_escapes;
315316
mod open_options;
316317
mod option_env_unwrap;
317318
mod option_if_let_else;
@@ -849,6 +850,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
849850
store.register_late_pass(|| Box::new(match_str_case_mismatch::MatchStrCaseMismatch));
850851
store.register_late_pass(move || Box::new(format_args::FormatArgs));
851852
store.register_late_pass(|| Box::new(trailing_empty_array::TrailingEmptyArray));
853+
store.register_early_pass(|| Box::new(octal_escapes::OctalEscapes));
852854
// add lints here, do not remove this comment, it's used in `new_lint`
853855
}
854856

clippy_lints/src/octal_escapes.rs

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use rustc_ast::ast::{Expr, ExprKind};
3+
use rustc_ast::token::{Lit, LitKind};
4+
use rustc_errors::Applicability;
5+
use rustc_lint::{EarlyContext, EarlyLintPass};
6+
use rustc_middle::lint::in_external_macro;
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
use rustc_span::Span;
9+
10+
declare_clippy_lint! {
11+
/// ### What it does
12+
/// Checks for `\0` escapes in string and byte literals that look like octal character
13+
/// escapes in C
14+
///
15+
/// ### Why is this bad?
16+
/// Rust does not support octal notation for character escapes. `\0` is always a
17+
/// null byte/character, and any following digits do not form part of the escape
18+
/// sequence.
19+
///
20+
/// ### Known problems
21+
/// The actual meaning can be the intended one. `\x00` can be used in these
22+
/// cases to be unambigious.
23+
///
24+
/// # Example
25+
/// ```rust
26+
/// // Bad
27+
/// let one = "\033[1m Bold? \033[0m"; // \033 intended as escape
28+
/// let two = "\033\0"; // \033 intended as null-3-3
29+
///
30+
/// // Good
31+
/// let one = "\x1b[1mWill this be bold?\x1b[0m";
32+
/// let two = "\x0033\x00";
33+
/// ```
34+
#[clippy::version = "1.58.0"]
35+
pub OCTAL_ESCAPES,
36+
suspicious,
37+
"string escape sequences looking like octal characters"
38+
}
39+
40+
declare_lint_pass!(OctalEscapes => [OCTAL_ESCAPES]);
41+
42+
impl EarlyLintPass for OctalEscapes {
43+
fn check_expr(&mut self, cx: &EarlyContext<'tcx>, expr: &Expr) {
44+
if in_external_macro(cx.sess, expr.span) {
45+
return;
46+
}
47+
48+
if let ExprKind::Lit(lit) = &expr.kind {
49+
if matches!(lit.token.kind, LitKind::Str) {
50+
check_lit(cx, &lit.token, lit.span, true);
51+
} else if matches!(lit.token.kind, LitKind::ByteStr) {
52+
check_lit(cx, &lit.token, lit.span, false);
53+
}
54+
}
55+
}
56+
}
57+
58+
fn check_lit(cx: &EarlyContext<'tcx>, lit: &Lit, span: Span, is_string: bool) {
59+
let contents = lit.symbol.as_str();
60+
let mut iter = contents.char_indices();
61+
62+
// go through the string, looking for \0[0-7]
63+
while let Some((from, ch)) = iter.next() {
64+
if ch == '\\' {
65+
if let Some((mut to, '0')) = iter.next() {
66+
// collect all further potentially octal digits
67+
while let Some((j, '0'..='7')) = iter.next() {
68+
to = j + 1;
69+
}
70+
// if it's more than just `\0` we have a match
71+
if to > from + 2 {
72+
emit(cx, &contents, from, to, span, is_string);
73+
return;
74+
}
75+
}
76+
}
77+
}
78+
}
79+
80+
fn emit(cx: &EarlyContext<'tcx>, contents: &str, from: usize, to: usize, span: Span, is_string: bool) {
81+
// construct a replacement escape for that case that octal was intended
82+
let escape = &contents[from + 1..to];
83+
let literal_suggestion = if is_string {
84+
u32::from_str_radix(escape, 8).ok().and_then(|n| {
85+
if n < 256 {
86+
Some(format!("\\x{:02x}", n))
87+
} else if n <= std::char::MAX as u32 {
88+
Some(format!("\\u{{{:x}}}", n))
89+
} else {
90+
None
91+
}
92+
})
93+
} else {
94+
u8::from_str_radix(escape, 8).ok().map(|n| format!("\\x{:02x}", n))
95+
};
96+
97+
span_lint_and_then(
98+
cx,
99+
OCTAL_ESCAPES,
100+
span,
101+
&format!(
102+
"octal-looking escape in {} literal",
103+
if is_string { "string" } else { "byte string" }
104+
),
105+
|diag| {
106+
diag.help(&format!(
107+
"octal escapes are not supported, `\\0` is always a null {}",
108+
if is_string { "character" } else { "byte" }
109+
));
110+
// suggestion 1: equivalent hex escape
111+
if let Some(sugg) = literal_suggestion {
112+
diag.span_suggestion(
113+
span,
114+
"if an octal escape is intended, use",
115+
format!("\"{}{}{}\"", &contents[..from], sugg, &contents[to..]),
116+
Applicability::MaybeIncorrect,
117+
);
118+
}
119+
// suggestion 2: unambiguous null byte
120+
diag.span_suggestion(
121+
span,
122+
&format!(
123+
"if the null {} is intended, disambiguate using",
124+
if is_string { "character" } else { "byte" }
125+
),
126+
format!("\"{}\\x00{}\"", &contents[..from], &contents[from + 2..]),
127+
Applicability::MaybeIncorrect,
128+
);
129+
},
130+
);
131+
}

tests/ui/octal_escapes.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#![warn(clippy::octal_escapes)]
2+
3+
fn main() {
4+
let _bad1 = "\033[0m";
5+
let _bad2 = b"\033[0m";
6+
let _bad3 = "\\\033[0m";
7+
let _bad4 = "\01234567";
8+
let _bad5 = "\0\03";
9+
10+
let _good1 = "\\033[0m";
11+
let _good2 = "\0\\0";
12+
}

tests/ui/octal_escapes.stderr

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
error: octal-looking escape in string literal
2+
--> $DIR/octal_escapes.rs:4:17
3+
|
4+
LL | let _bad1 = "/033[0m";
5+
| ^^^^^^^^^
6+
|
7+
= note: `-D clippy::octal-escapes` implied by `-D warnings`
8+
= help: octal escapes are not supported, `/0` is always a null character
9+
help: if an octal escape is intended, use
10+
|
11+
LL | let _bad1 = "/x1b[0m";
12+
| ~~~~~~~~~
13+
help: if the null character is intended, disambiguate using
14+
|
15+
LL | let _bad1 = "/x0033[0m";
16+
| ~~~~~~~~~~~
17+
18+
error: octal-looking escape in byte string literal
19+
--> $DIR/octal_escapes.rs:5:17
20+
|
21+
LL | let _bad2 = b"/033[0m";
22+
| ^^^^^^^^^^
23+
|
24+
= help: octal escapes are not supported, `/0` is always a null byte
25+
help: if an octal escape is intended, use
26+
|
27+
LL | let _bad2 = "/x1b[0m";
28+
| ~~~~~~~~~
29+
help: if the null byte is intended, disambiguate using
30+
|
31+
LL | let _bad2 = "/x0033[0m";
32+
| ~~~~~~~~~~~
33+
34+
error: octal-looking escape in string literal
35+
--> $DIR/octal_escapes.rs:6:17
36+
|
37+
LL | let _bad3 = "//033[0m";
38+
| ^^^^^^^^^^^
39+
|
40+
= help: octal escapes are not supported, `/0` is always a null character
41+
help: if an octal escape is intended, use
42+
|
43+
LL | let _bad3 = "//x1b[0m";
44+
| ~~~~~~~~~~~
45+
help: if the null character is intended, disambiguate using
46+
|
47+
LL | let _bad3 = "//x0033[0m";
48+
| ~~~~~~~~~~~~~
49+
50+
error: octal-looking escape in string literal
51+
--> $DIR/octal_escapes.rs:7:17
52+
|
53+
LL | let _bad4 = "/01234567";
54+
| ^^^^^^^^^^^
55+
|
56+
= help: octal escapes are not supported, `/0` is always a null character
57+
help: if an octal escape is intended, use
58+
|
59+
LL | let _bad4 = "/u{53977}";
60+
| ~~~~~~~~~~~
61+
help: if the null character is intended, disambiguate using
62+
|
63+
LL | let _bad4 = "/x001234567";
64+
| ~~~~~~~~~~~~~
65+
66+
error: aborting due to 4 previous errors
67+

0 commit comments

Comments
 (0)