@@ -6,7 +6,7 @@ use rustc_errors::Applicability;
6
6
use rustc_lexer:: unescape:: { self , EscapeError } ;
7
7
use rustc_lint:: { EarlyContext , EarlyLintPass } ;
8
8
use rustc_parse:: parser;
9
- use rustc_session:: { declare_lint_pass , declare_tool_lint } ;
9
+ use rustc_session:: { declare_tool_lint , impl_lint_pass } ;
10
10
use rustc_span:: symbol:: Symbol ;
11
11
use rustc_span:: { BytePos , Span } ;
12
12
use syntax:: ast:: * ;
@@ -175,7 +175,12 @@ declare_clippy_lint! {
175
175
"writing a literal with a format string"
176
176
}
177
177
178
- declare_lint_pass ! ( Write => [
178
+ #[ derive( Default ) ]
179
+ pub struct Write {
180
+ in_debug_impl : bool ,
181
+ }
182
+
183
+ impl_lint_pass ! ( Write => [
179
184
PRINT_WITH_NEWLINE ,
180
185
PRINTLN_EMPTY_STRING ,
181
186
PRINT_STDOUT ,
@@ -187,10 +192,34 @@ declare_lint_pass!(Write => [
187
192
] ) ;
188
193
189
194
impl EarlyLintPass for Write {
195
+ fn check_item ( & mut self , _: & EarlyContext < ' _ > , item : & Item ) {
196
+ if let ItemKind :: Impl {
197
+ of_trait : Some ( trait_ref) ,
198
+ ..
199
+ } = & item. kind
200
+ {
201
+ let trait_name = trait_ref
202
+ . path
203
+ . segments
204
+ . iter ( )
205
+ . last ( )
206
+ . expect ( "path has at least one segment" )
207
+ . ident
208
+ . name ;
209
+ if trait_name == sym ! ( Debug ) {
210
+ self . in_debug_impl = true ;
211
+ }
212
+ }
213
+ }
214
+
215
+ fn check_item_post ( & mut self , _: & EarlyContext < ' _ > , _: & Item ) {
216
+ self . in_debug_impl = false ;
217
+ }
218
+
190
219
fn check_mac ( & mut self , cx : & EarlyContext < ' _ > , mac : & Mac ) {
191
220
if mac. path == sym ! ( println) {
192
221
span_lint ( cx, PRINT_STDOUT , mac. span ( ) , "use of `println!`" ) ;
193
- if let ( Some ( fmt_str) , _) = check_tts ( cx, & mac. args . inner_tokens ( ) , false ) {
222
+ if let ( Some ( fmt_str) , _) = self . check_tts ( cx, & mac. args . inner_tokens ( ) , false ) {
194
223
if fmt_str. symbol == Symbol :: intern ( "" ) {
195
224
span_lint_and_sugg (
196
225
cx,
@@ -205,7 +234,7 @@ impl EarlyLintPass for Write {
205
234
}
206
235
} else if mac. path == sym ! ( print) {
207
236
span_lint ( cx, PRINT_STDOUT , mac. span ( ) , "use of `print!`" ) ;
208
- if let ( Some ( fmt_str) , _) = check_tts ( cx, & mac. args . inner_tokens ( ) , false ) {
237
+ if let ( Some ( fmt_str) , _) = self . check_tts ( cx, & mac. args . inner_tokens ( ) , false ) {
209
238
if check_newlines ( & fmt_str) {
210
239
span_lint_and_then (
211
240
cx,
@@ -226,7 +255,7 @@ impl EarlyLintPass for Write {
226
255
}
227
256
}
228
257
} else if mac. path == sym ! ( write) {
229
- if let ( Some ( fmt_str) , _) = check_tts ( cx, & mac. args . inner_tokens ( ) , true ) {
258
+ if let ( Some ( fmt_str) , _) = self . check_tts ( cx, & mac. args . inner_tokens ( ) , true ) {
230
259
if check_newlines ( & fmt_str) {
231
260
span_lint_and_then (
232
261
cx,
@@ -247,7 +276,7 @@ impl EarlyLintPass for Write {
247
276
}
248
277
}
249
278
} else if mac. path == sym ! ( writeln) {
250
- if let ( Some ( fmt_str) , expr) = check_tts ( cx, & mac. args . inner_tokens ( ) , true ) {
279
+ if let ( Some ( fmt_str) , expr) = self . check_tts ( cx, & mac. args . inner_tokens ( ) , true ) {
251
280
if fmt_str. symbol == Symbol :: intern ( "" ) {
252
281
let mut applicability = Applicability :: MachineApplicable ;
253
282
let suggestion = expr. map_or_else (
@@ -273,6 +302,138 @@ impl EarlyLintPass for Write {
273
302
}
274
303
}
275
304
305
+ impl Write {
306
+ /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
307
+ /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
308
+ /// the contents of the string, whether it's a raw string, and the span of the literal in the
309
+ /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
310
+ /// `format_str` should be written to.
311
+ ///
312
+ /// Example:
313
+ ///
314
+ /// Calling this function on
315
+ /// ```rust
316
+ /// # use std::fmt::Write;
317
+ /// # let mut buf = String::new();
318
+ /// # let something = "something";
319
+ /// writeln!(buf, "string to write: {}", something);
320
+ /// ```
321
+ /// will return
322
+ /// ```rust,ignore
323
+ /// (Some("string to write: {}"), Some(buf))
324
+ /// ```
325
+ #[ allow( clippy:: too_many_lines) ]
326
+ fn check_tts < ' a > (
327
+ & self ,
328
+ cx : & EarlyContext < ' a > ,
329
+ tts : & TokenStream ,
330
+ is_write : bool ,
331
+ ) -> ( Option < StrLit > , Option < Expr > ) {
332
+ use fmt_macros:: * ;
333
+ let tts = tts. clone ( ) ;
334
+
335
+ let mut parser = parser:: Parser :: new ( & cx. sess . parse_sess , tts, None , false , false , None ) ;
336
+ let mut expr: Option < Expr > = None ;
337
+ if is_write {
338
+ expr = match parser. parse_expr ( ) . map_err ( |mut err| err. cancel ( ) ) {
339
+ Ok ( p) => Some ( p. into_inner ( ) ) ,
340
+ Err ( _) => return ( None , None ) ,
341
+ } ;
342
+ // might be `writeln!(foo)`
343
+ if parser. expect ( & token:: Comma ) . map_err ( |mut err| err. cancel ( ) ) . is_err ( ) {
344
+ return ( None , expr) ;
345
+ }
346
+ }
347
+
348
+ let fmtstr = match parser. parse_str_lit ( ) {
349
+ Ok ( fmtstr) => fmtstr,
350
+ Err ( _) => return ( None , expr) ,
351
+ } ;
352
+ let tmp = fmtstr. symbol . as_str ( ) ;
353
+ let mut args = vec ! [ ] ;
354
+ let mut fmt_parser = Parser :: new ( & tmp, None , Vec :: new ( ) , false ) ;
355
+ while let Some ( piece) = fmt_parser. next ( ) {
356
+ if !fmt_parser. errors . is_empty ( ) {
357
+ return ( None , expr) ;
358
+ }
359
+ if let Piece :: NextArgument ( arg) = piece {
360
+ if !self . in_debug_impl && arg. format . ty == "?" {
361
+ // FIXME: modify rustc's fmt string parser to give us the current span
362
+ span_lint ( cx, USE_DEBUG , parser. prev_span , "use of `Debug`-based formatting" ) ;
363
+ }
364
+ args. push ( arg) ;
365
+ }
366
+ }
367
+ let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL } ;
368
+ let mut idx = 0 ;
369
+ loop {
370
+ const SIMPLE : FormatSpec < ' _ > = FormatSpec {
371
+ fill : None ,
372
+ align : AlignUnknown ,
373
+ flags : 0 ,
374
+ precision : CountImplied ,
375
+ precision_span : None ,
376
+ width : CountImplied ,
377
+ width_span : None ,
378
+ ty : "" ,
379
+ ty_span : None ,
380
+ } ;
381
+ if !parser. eat ( & token:: Comma ) {
382
+ return ( Some ( fmtstr) , expr) ;
383
+ }
384
+ let token_expr = if let Ok ( expr) = parser. parse_expr ( ) . map_err ( |mut err| err. cancel ( ) ) {
385
+ expr
386
+ } else {
387
+ return ( Some ( fmtstr) , None ) ;
388
+ } ;
389
+ match & token_expr. kind {
390
+ ExprKind :: Lit ( _) => {
391
+ let mut all_simple = true ;
392
+ let mut seen = false ;
393
+ for arg in & args {
394
+ match arg. position {
395
+ ArgumentImplicitlyIs ( n) | ArgumentIs ( n) => {
396
+ if n == idx {
397
+ all_simple &= arg. format == SIMPLE ;
398
+ seen = true ;
399
+ }
400
+ } ,
401
+ ArgumentNamed ( _) => { } ,
402
+ }
403
+ }
404
+ if all_simple && seen {
405
+ span_lint ( cx, lint, token_expr. span , "literal with an empty format string" ) ;
406
+ }
407
+ idx += 1 ;
408
+ } ,
409
+ ExprKind :: Assign ( lhs, rhs, _) => {
410
+ if let ExprKind :: Lit ( _) = rhs. kind {
411
+ if let ExprKind :: Path ( _, p) = & lhs. kind {
412
+ let mut all_simple = true ;
413
+ let mut seen = false ;
414
+ for arg in & args {
415
+ match arg. position {
416
+ ArgumentImplicitlyIs ( _) | ArgumentIs ( _) => { } ,
417
+ ArgumentNamed ( name) => {
418
+ if * p == name {
419
+ seen = true ;
420
+ all_simple &= arg. format == SIMPLE ;
421
+ }
422
+ } ,
423
+ }
424
+ }
425
+ if all_simple && seen {
426
+ span_lint ( cx, lint, rhs. span , "literal with an empty format string" ) ;
427
+ }
428
+ }
429
+ }
430
+ } ,
431
+ _ => idx += 1 ,
432
+ }
433
+ }
434
+ }
435
+ }
436
+
276
437
/// Given a format string that ends in a newline and its span, calculates the span of the
277
438
/// newline.
278
439
fn newline_span ( fmtstr : & StrLit ) -> Span {
@@ -296,131 +457,6 @@ fn newline_span(fmtstr: &StrLit) -> Span {
296
457
sp. with_lo ( newline_sp_hi - newline_sp_len) . with_hi ( newline_sp_hi)
297
458
}
298
459
299
- /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
300
- /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
301
- /// the contents of the string, whether it's a raw string, and the span of the literal in the
302
- /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
303
- /// `format_str` should be written to.
304
- ///
305
- /// Example:
306
- ///
307
- /// Calling this function on
308
- /// ```rust
309
- /// # use std::fmt::Write;
310
- /// # let mut buf = String::new();
311
- /// # let something = "something";
312
- /// writeln!(buf, "string to write: {}", something);
313
- /// ```
314
- /// will return
315
- /// ```rust,ignore
316
- /// (Some("string to write: {}"), Some(buf))
317
- /// ```
318
- #[ allow( clippy:: too_many_lines) ]
319
- fn check_tts < ' a > ( cx : & EarlyContext < ' a > , tts : & TokenStream , is_write : bool ) -> ( Option < StrLit > , Option < Expr > ) {
320
- use fmt_macros:: * ;
321
- let tts = tts. clone ( ) ;
322
-
323
- let mut parser = parser:: Parser :: new ( & cx. sess . parse_sess , tts, None , false , false , None ) ;
324
- let mut expr: Option < Expr > = None ;
325
- if is_write {
326
- expr = match parser. parse_expr ( ) . map_err ( |mut err| err. cancel ( ) ) {
327
- Ok ( p) => Some ( p. into_inner ( ) ) ,
328
- Err ( _) => return ( None , None ) ,
329
- } ;
330
- // might be `writeln!(foo)`
331
- if parser. expect ( & token:: Comma ) . map_err ( |mut err| err. cancel ( ) ) . is_err ( ) {
332
- return ( None , expr) ;
333
- }
334
- }
335
-
336
- let fmtstr = match parser. parse_str_lit ( ) {
337
- Ok ( fmtstr) => fmtstr,
338
- Err ( _) => return ( None , expr) ,
339
- } ;
340
- let tmp = fmtstr. symbol . as_str ( ) ;
341
- let mut args = vec ! [ ] ;
342
- let mut fmt_parser = Parser :: new ( & tmp, None , Vec :: new ( ) , false ) ;
343
- while let Some ( piece) = fmt_parser. next ( ) {
344
- if !fmt_parser. errors . is_empty ( ) {
345
- return ( None , expr) ;
346
- }
347
- if let Piece :: NextArgument ( arg) = piece {
348
- if arg. format . ty == "?" {
349
- // FIXME: modify rustc's fmt string parser to give us the current span
350
- span_lint ( cx, USE_DEBUG , parser. prev_span , "use of `Debug`-based formatting" ) ;
351
- }
352
- args. push ( arg) ;
353
- }
354
- }
355
- let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL } ;
356
- let mut idx = 0 ;
357
- loop {
358
- const SIMPLE : FormatSpec < ' _ > = FormatSpec {
359
- fill : None ,
360
- align : AlignUnknown ,
361
- flags : 0 ,
362
- precision : CountImplied ,
363
- precision_span : None ,
364
- width : CountImplied ,
365
- width_span : None ,
366
- ty : "" ,
367
- ty_span : None ,
368
- } ;
369
- if !parser. eat ( & token:: Comma ) {
370
- return ( Some ( fmtstr) , expr) ;
371
- }
372
- let token_expr = if let Ok ( expr) = parser. parse_expr ( ) . map_err ( |mut err| err. cancel ( ) ) {
373
- expr
374
- } else {
375
- return ( Some ( fmtstr) , None ) ;
376
- } ;
377
- match & token_expr. kind {
378
- ExprKind :: Lit ( _) => {
379
- let mut all_simple = true ;
380
- let mut seen = false ;
381
- for arg in & args {
382
- match arg. position {
383
- ArgumentImplicitlyIs ( n) | ArgumentIs ( n) => {
384
- if n == idx {
385
- all_simple &= arg. format == SIMPLE ;
386
- seen = true ;
387
- }
388
- } ,
389
- ArgumentNamed ( _) => { } ,
390
- }
391
- }
392
- if all_simple && seen {
393
- span_lint ( cx, lint, token_expr. span , "literal with an empty format string" ) ;
394
- }
395
- idx += 1 ;
396
- } ,
397
- ExprKind :: Assign ( lhs, rhs, _) => {
398
- if let ExprKind :: Lit ( _) = rhs. kind {
399
- if let ExprKind :: Path ( _, p) = & lhs. kind {
400
- let mut all_simple = true ;
401
- let mut seen = false ;
402
- for arg in & args {
403
- match arg. position {
404
- ArgumentImplicitlyIs ( _) | ArgumentIs ( _) => { } ,
405
- ArgumentNamed ( name) => {
406
- if * p == name {
407
- seen = true ;
408
- all_simple &= arg. format == SIMPLE ;
409
- }
410
- } ,
411
- }
412
- }
413
- if all_simple && seen {
414
- span_lint ( cx, lint, rhs. span , "literal with an empty format string" ) ;
415
- }
416
- }
417
- }
418
- } ,
419
- _ => idx += 1 ,
420
- }
421
- }
422
- }
423
-
424
460
/// Checks if the format string contains a single newline that terminates it.
425
461
///
426
462
/// Literal and escaped newlines are both checked (only literal for raw strings).
0 commit comments