1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Lints built in to rustc.
//!
//! This is a sibling of `lint::context` in order to ensure that
//! lints implemented here use the same public API as lint plugins.
//!
//! To add a new lint to rustc, declare it here using `declare_lint!()`.
//! Then add code to emit the new lint in the appropriate circumstances.
//! You can do that in an existing `LintPass` if it makes sense, or in
//! a new `LintPass`, or using `Session::add_lint` elsewhere in the
//! compiler. Only do the latter if the check can't be written cleanly
//! as a `LintPass`.
//!
//! If you define a new `LintPass`, you will also need to add it to the
//! `add_builtin!` or `add_builtin_with_new!` invocation in `context.rs`.
//! Use the former for unit-like structs and the latter for structs with
//! a `pub fn new()`.
use self::MethodContext::*;

use metadata::csearch;
use middle::def::*;
use middle::subst::Substs;
use middle::ty::{mod, Ty};
use middle::{def, pat_util, stability};
use middle::const_eval::{eval_const_expr_partial, const_int, const_uint};
use util::ppaux::{ty_to_string};
use util::nodemap::{FnvHashMap, NodeSet};
use lint::{Context, LintPass, LintArray};

use std::{cmp, slice};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::num::SignedInt;
use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
use syntax::{abi, ast, ast_map};
use syntax::ast_util::is_shift_binop;
use syntax::attr::{mod, AttrMetaMethods};
use syntax::codemap::{Span, DUMMY_SP};
use syntax::parse::token;
use syntax::ast::{TyI, TyU, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
use syntax::ast_util;
use syntax::ptr::P;
use syntax::visit::{mod, Visitor};

declare_lint! {
    WHILE_TRUE,
    Warn,
    "suggest using `loop { }` instead of `while true { }`"
}

#[deriving(Copy)]
pub struct WhileTrue;

impl LintPass for WhileTrue {
    fn get_lints(&self) -> LintArray {
        lint_array!(WHILE_TRUE)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        if let ast::ExprWhile(ref cond, _, _) = e.node {
            if let ast::ExprLit(ref lit) = cond.node {
                if let ast::LitBool(true) = lit.node {
                    cx.span_lint(WHILE_TRUE, e.span,
                                 "denote infinite loops with loop { ... }");
                }
            }
        }
    }
}

declare_lint! {
    UNUSED_TYPECASTS,
    Allow,
    "detects unnecessary type casts that can be removed"
}

#[deriving(Copy)]
pub struct UnusedCasts;

impl LintPass for UnusedCasts {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_TYPECASTS)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        if let ast::ExprCast(ref expr, ref ty) = e.node {
            let t_t = ty::expr_ty(cx.tcx, e);
            if ty::expr_ty(cx.tcx, &**expr) == t_t {
                cx.span_lint(UNUSED_TYPECASTS, ty.span, "unnecessary type cast");
            }
        }
    }
}

declare_lint! {
    UNSIGNED_NEGATION,
    Warn,
    "using an unary minus operator on unsigned type"
}

declare_lint! {
    UNUSED_COMPARISONS,
    Warn,
    "comparisons made useless by limits of the types involved"
}

declare_lint! {
    OVERFLOWING_LITERALS,
    Warn,
    "literal out of range for its type"
}

declare_lint! {
    EXCEEDING_BITSHIFTS,
    Deny,
    "shift exceeds the type's number of bits"
}

#[deriving(Copy)]
pub struct TypeLimits {
    /// Id of the last visited negated expression
    negated_expr_id: ast::NodeId,
}

impl TypeLimits {
    pub fn new() -> TypeLimits {
        TypeLimits {
            negated_expr_id: -1,
        }
    }
}

impl LintPass for TypeLimits {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNSIGNED_NEGATION, UNUSED_COMPARISONS, OVERFLOWING_LITERALS,
                    EXCEEDING_BITSHIFTS)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        match e.node {
            ast::ExprUnary(ast::UnNeg, ref expr) => {
                match expr.node  {
                    ast::ExprLit(ref lit) => {
                        match lit.node {
                            ast::LitInt(_, ast::UnsignedIntLit(_)) => {
                                cx.span_lint(UNSIGNED_NEGATION, e.span,
                                             "negation of unsigned int literal may \
                                             be unintentional");
                            },
                            _ => ()
                        }
                    },
                    _ => {
                        let t = ty::expr_ty(cx.tcx, &**expr);
                        match t.sty {
                            ty::ty_uint(_) => {
                                cx.span_lint(UNSIGNED_NEGATION, e.span,
                                             "negation of unsigned int variable may \
                                             be unintentional");
                            },
                            _ => ()
                        }
                    }
                };
                // propagate negation, if the negation itself isn't negated
                if self.negated_expr_id != e.id {
                    self.negated_expr_id = expr.id;
                }
            },
            ast::ExprParen(ref expr) if self.negated_expr_id == e.id => {
                self.negated_expr_id = expr.id;
            },
            ast::ExprBinary(binop, ref l, ref r) => {
                if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
                    cx.span_lint(UNUSED_COMPARISONS, e.span,
                                 "comparison is useless due to type limits");
                }

                if is_shift_binop(binop) {
                    let opt_ty_bits = match ty::expr_ty(cx.tcx, &**l).sty {
                        ty::ty_int(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
                        ty::ty_uint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
                        _ => None
                    };

                    if let Some(bits) = opt_ty_bits {
                        let exceeding = if let ast::ExprLit(ref lit) = r.node {
                            if let ast::LitInt(shift, _) = lit.node { shift >= bits }
                            else { false }
                        } else {
                            match eval_const_expr_partial(cx.tcx, &**r) {
                                Ok(const_int(shift)) => { shift as u64 >= bits },
                                Ok(const_uint(shift)) => { shift >= bits },
                                _ => { false }
                            }
                        };
                        if exceeding {
                            cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
                                         "bitshift exceeds the type's number of bits");
                        }
                    };
                }
            },
            ast::ExprLit(ref lit) => {
                match ty::expr_ty(cx.tcx, e).sty {
                    ty::ty_int(t) => {
                        match lit.node {
                            ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
                            ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
                                let int_type = if t == ast::TyI {
                                    cx.sess().target.int_type
                                } else { t };
                                let (min, max) = int_ty_range(int_type);
                                let negative = self.negated_expr_id == e.id;

                                if (negative && v > (min.abs() as u64)) ||
                                   (!negative && v > (max.abs() as u64)) {
                                    cx.span_lint(OVERFLOWING_LITERALS, e.span,
                                                 "literal out of range for its type");
                                    return;
                                }
                            }
                            _ => panic!()
                        };
                    },
                    ty::ty_uint(t) => {
                        let uint_type = if t == ast::TyU {
                            cx.sess().target.uint_type
                        } else { t };
                        let (min, max) = uint_ty_range(uint_type);
                        let lit_val: u64 = match lit.node {
                            ast::LitByte(_v) => return,  // _v is u8, within range by definition
                            ast::LitInt(v, _) => v,
                            _ => panic!()
                        };
                        if  lit_val < min || lit_val > max {
                            cx.span_lint(OVERFLOWING_LITERALS, e.span,
                                         "literal out of range for its type");
                        }
                    },
                    ty::ty_float(t) => {
                        let (min, max) = float_ty_range(t);
                        let lit_val: f64 = match lit.node {
                            ast::LitFloat(ref v, _) |
                            ast::LitFloatUnsuffixed(ref v) => {
                                match v.parse() {
                                    Some(f) => f,
                                    None => return
                                }
                            }
                            _ => panic!()
                        };
                        if lit_val < min || lit_val > max {
                            cx.span_lint(OVERFLOWING_LITERALS, e.span,
                                         "literal out of range for its type");
                        }
                    },
                    _ => ()
                };
            },
            _ => ()
        };

        fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
                                min: T, max: T) -> bool {
            match binop {
                ast::BiLt => v >  min && v <= max,
                ast::BiLe => v >= min && v <  max,
                ast::BiGt => v >= min && v <  max,
                ast::BiGe => v >  min && v <= max,
                ast::BiEq | ast::BiNe => v >= min && v <= max,
                _ => panic!()
            }
        }

        fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
            match binop {
                ast::BiLt => ast::BiGt,
                ast::BiLe => ast::BiGe,
                ast::BiGt => ast::BiLt,
                ast::BiGe => ast::BiLe,
                _ => binop
            }
        }

        // for int & uint, be conservative with the warnings, so that the
        // warnings are consistent between 32- and 64-bit platforms
        fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
            match int_ty {
                ast::TyI =>    (i64::MIN,        i64::MAX),
                ast::TyI8 =>   (i8::MIN  as i64, i8::MAX  as i64),
                ast::TyI16 =>  (i16::MIN as i64, i16::MAX as i64),
                ast::TyI32 =>  (i32::MIN as i64, i32::MAX as i64),
                ast::TyI64 =>  (i64::MIN,        i64::MAX)
            }
        }

        fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
            match uint_ty {
                ast::TyU =>   (u64::MIN,         u64::MAX),
                ast::TyU8 =>  (u8::MIN   as u64, u8::MAX   as u64),
                ast::TyU16 => (u16::MIN  as u64, u16::MAX  as u64),
                ast::TyU32 => (u32::MIN  as u64, u32::MAX  as u64),
                ast::TyU64 => (u64::MIN,         u64::MAX)
            }
        }

        fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
            match float_ty {
                ast::TyF32  => (f32::MIN_VALUE as f64, f32::MAX_VALUE as f64),
                ast::TyF64  => (f64::MIN_VALUE,        f64::MAX_VALUE)
            }
        }

        fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
            match int_ty {
                ast::TyI =>    int_ty_bits(target_int_ty, target_int_ty),
                ast::TyI8 =>   i8::BITS  as u64,
                ast::TyI16 =>  i16::BITS as u64,
                ast::TyI32 =>  i32::BITS as u64,
                ast::TyI64 =>  i64::BITS as u64
            }
        }

        fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
            match uint_ty {
                ast::TyU =>    uint_ty_bits(target_uint_ty, target_uint_ty),
                ast::TyU8 =>   u8::BITS  as u64,
                ast::TyU16 =>  u16::BITS as u64,
                ast::TyU32 =>  u32::BITS as u64,
                ast::TyU64 =>  u64::BITS as u64
            }
        }

        fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
                        l: &ast::Expr, r: &ast::Expr) -> bool {
            let (lit, expr, swap) = match (&l.node, &r.node) {
                (&ast::ExprLit(_), _) => (l, r, true),
                (_, &ast::ExprLit(_)) => (r, l, false),
                _ => return true
            };
            // Normalize the binop so that the literal is always on the RHS in
            // the comparison
            let norm_binop = if swap { rev_binop(binop) } else { binop };
            match ty::expr_ty(tcx, expr).sty {
                ty::ty_int(int_ty) => {
                    let (min, max) = int_ty_range(int_ty);
                    let lit_val: i64 = match lit.node {
                        ast::ExprLit(ref li) => match li.node {
                            ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
                            ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
                            ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
                            ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
                            _ => return true
                        },
                        _ => panic!()
                    };
                    is_valid(norm_binop, lit_val, min, max)
                }
                ty::ty_uint(uint_ty) => {
                    let (min, max): (u64, u64) = uint_ty_range(uint_ty);
                    let lit_val: u64 = match lit.node {
                        ast::ExprLit(ref li) => match li.node {
                            ast::LitInt(v, _) => v,
                            _ => return true
                        },
                        _ => panic!()
                    };
                    is_valid(norm_binop, lit_val, min, max)
                }
                _ => true
            }
        }

        fn is_comparison(binop: ast::BinOp) -> bool {
            match binop {
                ast::BiEq | ast::BiLt | ast::BiLe |
                ast::BiNe | ast::BiGe | ast::BiGt => true,
                _ => false
            }
        }
    }
}

declare_lint! {
    IMPROPER_CTYPES,
    Warn,
    "proper use of libc types in foreign modules"
}

struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
    cx: &'a Context<'a, 'tcx>
}

impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
    fn check_def(&mut self, sp: Span, ty_id: ast::NodeId, path_id: ast::NodeId) {
        match self.cx.tcx.def_map.borrow()[path_id].clone() {
            def::DefPrimTy(ast::TyInt(ast::TyI)) => {
                self.cx.span_lint(IMPROPER_CTYPES, sp,
                                  "found rust type `int` in foreign module, while \
                                   libc::c_int or libc::c_long should be used");
            }
            def::DefPrimTy(ast::TyUint(ast::TyU)) => {
                self.cx.span_lint(IMPROPER_CTYPES, sp,
                                  "found rust type `uint` in foreign module, while \
                                   libc::c_uint or libc::c_ulong should be used");
            }
            def::DefTy(..) => {
                let tty = match self.cx.tcx.ast_ty_to_ty_cache.borrow().get(&ty_id) {
                    Some(&ty::atttce_resolved(t)) => t,
                    _ => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
                };

                if !ty::is_ffi_safe(self.cx.tcx, tty) {
                    self.cx.span_lint(IMPROPER_CTYPES, sp,
                                      "found type without foreign-function-safe
                                      representation annotation in foreign module, consider \
                                      adding a #[repr(...)] attribute to the type");
                }
            }
            _ => ()
        }
    }
}

impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
    fn visit_ty(&mut self, ty: &ast::Ty) {
        match ty.node {
            ast::TyPath(_, id) => self.check_def(ty.span, ty.id, id),
            _ => (),
        }
        visit::walk_ty(self, ty);
    }
}

#[deriving(Copy)]
pub struct ImproperCTypes;

impl LintPass for ImproperCTypes {
    fn get_lints(&self) -> LintArray {
        lint_array!(IMPROPER_CTYPES)
    }

    fn check_item(&mut self, cx: &Context, it: &ast::Item) {
        fn check_ty(cx: &Context, ty: &ast::Ty) {
            let mut vis = ImproperCTypesVisitor { cx: cx };
            vis.visit_ty(ty);
        }

        fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
            for input in decl.inputs.iter() {
                check_ty(cx, &*input.ty);
            }
            if let ast::Return(ref ret_ty) = decl.output {
                check_ty(cx, &**ret_ty);
            }
        }

        match it.node {
            ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
                for ni in nmod.items.iter() {
                    match ni.node {
                        ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
                        ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
                    }
                }
            }
            _ => (),
        }
    }
}

declare_lint! {
    BOX_POINTERS,
    Allow,
    "use of owned (Box type) heap memory"
}

#[deriving(Copy)]
pub struct BoxPointers;

impl BoxPointers {
    fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
                                 span: Span, ty: Ty<'tcx>) {
        let mut n_uniq = 0i;
        ty::fold_ty(cx.tcx, ty, |t| {
            match t.sty {
                ty::ty_uniq(_) |
                ty::ty_closure(box ty::ClosureTy {
                    store: ty::UniqTraitStore,
                    ..
                }) => {
                    n_uniq += 1;
                }

                _ => ()
            };
            t
        });

        if n_uniq > 0 {
            let s = ty_to_string(cx.tcx, ty);
            let m = format!("type uses owned (Box type) pointers: {}", s);
            cx.span_lint(BOX_POINTERS, span, m[]);
        }
    }
}

impl LintPass for BoxPointers {
    fn get_lints(&self) -> LintArray {
        lint_array!(BOX_POINTERS)
    }

    fn check_item(&mut self, cx: &Context, it: &ast::Item) {
        match it.node {
            ast::ItemFn(..) |
            ast::ItemTy(..) |
            ast::ItemEnum(..) |
            ast::ItemStruct(..) =>
                self.check_heap_type(cx, it.span,
                                     ty::node_id_to_type(cx.tcx, it.id)),
            _ => ()
        }

        // If it's a struct, we also have to check the fields' types
        match it.node {
            ast::ItemStruct(ref struct_def, _) => {
                for struct_field in struct_def.fields.iter() {
                    self.check_heap_type(cx, struct_field.span,
                                         ty::node_id_to_type(cx.tcx, struct_field.node.id));
                }
            }
            _ => ()
        }
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        let ty = ty::expr_ty(cx.tcx, e);
        self.check_heap_type(cx, e.span, ty);
    }
}

declare_lint! {
    RAW_POINTER_DERIVING,
    Warn,
    "uses of #[deriving] with raw pointers are rarely correct"
}

struct RawPtrDerivingVisitor<'a, 'tcx: 'a> {
    cx: &'a Context<'a, 'tcx>
}

impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDerivingVisitor<'a, 'tcx> {
    fn visit_ty(&mut self, ty: &ast::Ty) {
        static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
        if let ast::TyPtr(..) = ty.node {
            self.cx.span_lint(RAW_POINTER_DERIVING, ty.span, MSG);
        }
        visit::walk_ty(self, ty);
    }
    // explicit override to a no-op to reduce code bloat
    fn visit_expr(&mut self, _: &ast::Expr) {}
    fn visit_block(&mut self, _: &ast::Block) {}
}

pub struct RawPointerDeriving {
    checked_raw_pointers: NodeSet,
}

impl RawPointerDeriving {
    pub fn new() -> RawPointerDeriving {
        RawPointerDeriving {
            checked_raw_pointers: NodeSet::new(),
        }
    }
}

impl LintPass for RawPointerDeriving {
    fn get_lints(&self) -> LintArray {
        lint_array!(RAW_POINTER_DERIVING)
    }

    fn check_item(&mut self, cx: &Context, item: &ast::Item) {
        if !attr::contains_name(item.attrs[], "automatically_derived") {
            return
        }
        let did = match item.node {
            ast::ItemImpl(..) => {
                match ty::node_id_to_type(cx.tcx, item.id).sty {
                    ty::ty_enum(did, _) => did,
                    ty::ty_struct(did, _) => did,
                    _ => return,
                }
            }
            _ => return,
        };
        if !ast_util::is_local(did) { return }
        let item = match cx.tcx.map.find(did.node) {
            Some(ast_map::NodeItem(item)) => item,
            _ => return,
        };
        if !self.checked_raw_pointers.insert(item.id) { return }
        match item.node {
            ast::ItemStruct(..) | ast::ItemEnum(..) => {
                let mut visitor = RawPtrDerivingVisitor { cx: cx };
                visit::walk_item(&mut visitor, &*item);
            }
            _ => {}
        }
    }
}

declare_lint! {
    UNUSED_ATTRIBUTES,
    Warn,
    "detects attributes that were not used by the compiler"
}

#[deriving(Copy)]
pub struct UnusedAttributes;

impl LintPass for UnusedAttributes {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_ATTRIBUTES)
    }

    fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
        static ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
            // FIXME: #14408 whitelist docs since rustdoc looks at them
            "doc",

            // FIXME: #14406 these are processed in trans, which happens after the
            // lint pass
            "cold",
            "export_name",
            "inline",
            "link",
            "link_name",
            "link_section",
            "linkage",
            "no_builtins",
            "no_mangle",
            "no_split_stack",
            "no_stack_check",
            "packed",
            "static_assert",
            "thread_local",
            "no_debug",
            "omit_gdb_pretty_printer_section",
            "unsafe_no_drop_flag",

            // used in resolve
            "prelude_import",

            // FIXME: #14407 these are only looked at on-demand so we can't
            // guarantee they'll have already been checked
            "deprecated",
            "experimental",
            "frozen",
            "locked",
            "must_use",
            "stable",
            "unstable",
        ];

        static CRATE_ATTRS: &'static [&'static str] = &[
            "crate_name",
            "crate_type",
            "feature",
            "no_start",
            "no_main",
            "no_std",
            "no_builtins",
        ];

        for &name in ATTRIBUTE_WHITELIST.iter() {
            if attr.check_name(name) {
                break;
            }
        }

        if !attr::is_used(attr) {
            cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
            if CRATE_ATTRS.contains(&attr.name().get()) {
                let msg = match attr.node.style {
                    ast::AttrOuter => "crate-level attribute should be an inner \
                                       attribute: add an exclamation mark: #![foo]",
                    ast::AttrInner => "crate-level attribute should be in the \
                                       root module",
                };
                cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
            }
        }
    }
}

declare_lint! {
    pub PATH_STATEMENTS,
    Warn,
    "path statements with no effect"
}

#[deriving(Copy)]
pub struct PathStatements;

impl LintPass for PathStatements {
    fn get_lints(&self) -> LintArray {
        lint_array!(PATH_STATEMENTS)
    }

    fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
        match s.node {
            ast::StmtSemi(ref expr, _) => {
                match expr.node {
                    ast::ExprPath(_) => cx.span_lint(PATH_STATEMENTS, s.span,
                                                     "path statement with no effect"),
                    _ => ()
                }
            }
            _ => ()
        }
    }
}

declare_lint! {
    pub UNUSED_MUST_USE,
    Warn,
    "unused result of a type flagged as #[must_use]"
}

declare_lint! {
    pub UNUSED_RESULTS,
    Allow,
    "unused result of an expression in a statement"
}

#[deriving(Copy)]
pub struct UnusedResults;

impl LintPass for UnusedResults {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
    }

    fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
        let expr = match s.node {
            ast::StmtSemi(ref expr, _) => &**expr,
            _ => return
        };

        if let ast::ExprRet(..) = expr.node {
            return;
        }

        let t = ty::expr_ty(cx.tcx, expr);
        let mut warned = false;
        match t.sty {
            ty::ty_tup(ref tys) if tys.is_empty() => return,
            ty::ty_bool => return,
            ty::ty_struct(did, _) |
            ty::ty_enum(did, _) => {
                if ast_util::is_local(did) {
                    if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
                        warned |= check_must_use(cx, it.attrs[], s.span);
                    }
                } else {
                    csearch::get_item_attrs(&cx.sess().cstore, did, |attrs| {
                        warned |= check_must_use(cx, attrs[], s.span);
                    });
                }
            }
            _ => {}
        }
        if !warned {
            cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
        }

        fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
            for attr in attrs.iter() {
                if attr.check_name("must_use") {
                    let mut msg = "unused result which must be used".to_string();
                    // check for #[must_use="..."]
                    match attr.value_str() {
                        None => {}
                        Some(s) => {
                            msg.push_str(": ");
                            msg.push_str(s.get());
                        }
                    }
                    cx.span_lint(UNUSED_MUST_USE, sp, msg[]);
                    return true;
                }
            }
            false
        }
    }
}

declare_lint! {
    pub NON_CAMEL_CASE_TYPES,
    Warn,
    "types, variants, traits and type parameters should have camel case names"
}

#[deriving(Copy)]
pub struct NonCamelCaseTypes;

impl NonCamelCaseTypes {
    fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
        fn is_camel_case(ident: ast::Ident) -> bool {
            let ident = token::get_ident(ident);
            if ident.get().is_empty() { return true; }
            let ident = ident.get().trim_matches('_');

            // start with a non-lowercase letter rather than non-uppercase
            // ones (some scripts don't have a concept of upper/lowercase)
            ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
        }

        fn to_camel_case(s: &str) -> String {
            s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
                if i == 0 { c.to_uppercase() }
                else { c }
            )).collect()
        }

        let s = token::get_ident(ident);

        if !is_camel_case(ident) {
            let c = to_camel_case(s.get());
            let m = if c.is_empty() {
                format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
            } else {
                format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
            };
            cx.span_lint(NON_CAMEL_CASE_TYPES, span, m[]);
        }
    }
}

impl LintPass for NonCamelCaseTypes {
    fn get_lints(&self) -> LintArray {
        lint_array!(NON_CAMEL_CASE_TYPES)
    }

    fn check_item(&mut self, cx: &Context, it: &ast::Item) {
        let has_extern_repr = it.attrs.iter().map(|attr| {
            attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
                .any(|r| r == &attr::ReprExtern)
        }).any(|x| x);
        if has_extern_repr { return }

        match it.node {
            ast::ItemTy(..) | ast::ItemStruct(..) => {
                self.check_case(cx, "type", it.ident, it.span)
            }
            ast::ItemTrait(..) => {
                self.check_case(cx, "trait", it.ident, it.span)
            }
            ast::ItemEnum(ref enum_definition, _) => {
                if has_extern_repr { return }
                self.check_case(cx, "type", it.ident, it.span);
                for variant in enum_definition.variants.iter() {
                    self.check_case(cx, "variant", variant.node.name, variant.span);
                }
            }
            _ => ()
        }
    }

    fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
        for gen in it.ty_params.iter() {
            self.check_case(cx, "type parameter", gen.ident, gen.span);
        }
    }
}

#[deriving(PartialEq)]
enum MethodContext {
    TraitDefaultImpl,
    TraitImpl,
    PlainImpl
}

fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
    let did = ast::DefId {
        krate: ast::LOCAL_CRATE,
        node: m.id
    };

    match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
        None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
        Some(md) => {
            match md {
                ty::MethodTraitItem(md) => {
                    match md.container {
                        ty::TraitContainer(..) => TraitDefaultImpl,
                        ty::ImplContainer(cid) => {
                            match ty::impl_trait_ref(cx.tcx, cid) {
                                Some(..) => TraitImpl,
                                None => PlainImpl
                            }
                        }
                    }
                }
                ty::TypeTraitItem(typedef) => {
                    match typedef.container {
                        ty::TraitContainer(..) => TraitDefaultImpl,
                        ty::ImplContainer(cid) => {
                            match ty::impl_trait_ref(cx.tcx, cid) {
                                Some(..) => TraitImpl,
                                None => PlainImpl
                            }
                        }
                    }
                }
            }
        }
    }
}

declare_lint! {
    pub NON_SNAKE_CASE,
    Warn,
    "methods, functions, lifetime parameters and modules should have snake case names"
}

#[deriving(Copy)]
pub struct NonSnakeCase;

impl NonSnakeCase {
    fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
        fn is_snake_case(ident: ast::Ident) -> bool {
            let ident = token::get_ident(ident);
            if ident.get().is_empty() { return true; }
            let ident = ident.get().trim_left_matches('\'');
            let ident = ident.trim_matches('_');

            let mut allow_underscore = true;
            ident.chars().all(|c| {
                allow_underscore = match c {
                    c if c.is_lowercase() || c.is_numeric() => true,
                    '_' if allow_underscore => false,
                    _ => return false,
                };
                true
            })
        }

        fn to_snake_case(str: &str) -> String {
            let mut words = vec![];
            for s in str.split('_') {
                let mut last_upper = false;
                let mut buf = String::new();
                if s.is_empty() { continue; }
                for ch in s.chars() {
                    if !buf.is_empty() && buf != "'"
                                       && ch.is_uppercase()
                                       && !last_upper {
                        words.push(buf);
                        buf = String::new();
                    }
                    last_upper = ch.is_uppercase();
                    buf.push(ch.to_lowercase());
                }
                words.push(buf);
            }
            words.connect("_")
        }

        let s = token::get_ident(ident);

        if !is_snake_case(ident) {
            cx.span_lint(NON_SNAKE_CASE, span,
                format!("{} `{}` should have a snake case name such as `{}`",
                        sort, s, to_snake_case(s.get()))[]);
        }
    }
}

impl LintPass for NonSnakeCase {
    fn get_lints(&self) -> LintArray {
        lint_array!(NON_SNAKE_CASE)
    }

    fn check_fn(&mut self, cx: &Context,
                fk: visit::FnKind, _: &ast::FnDecl,
                _: &ast::Block, span: Span, _: ast::NodeId) {
        match fk {
            visit::FkMethod(ident, _, m) => match method_context(cx, m) {
                PlainImpl
                    => self.check_snake_case(cx, "method", ident, span),
                TraitDefaultImpl
                    => self.check_snake_case(cx, "trait method", ident, span),
                _ => (),
            },
            visit::FkItemFn(ident, _, _, _)
                => self.check_snake_case(cx, "function", ident, span),
            _ => (),
        }
    }

    fn check_item(&mut self, cx: &Context, it: &ast::Item) {
        if let ast::ItemMod(_) = it.node {
            self.check_snake_case(cx, "module", it.ident, it.span);
        }
    }

    fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
        self.check_snake_case(cx, "trait method", t.ident, t.span);
    }

    fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
        self.check_snake_case(cx, "lifetime", t.lifetime.name.ident(), t.lifetime.span);
    }

    fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
        if let &ast::PatIdent(_, ref path1, _) = &p.node {
            if let Some(&def::DefLocal(_)) = cx.tcx.def_map.borrow().get(&p.id) {
                self.check_snake_case(cx, "variable", path1.node, p.span);
            }
        }
    }

    fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
            _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
        for sf in s.fields.iter() {
            if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
                self.check_snake_case(cx, "structure field", ident, sf.span);
            }
        }
    }
}

declare_lint! {
    pub NON_UPPER_CASE_GLOBALS,
    Warn,
    "static constants should have uppercase identifiers"
}

#[deriving(Copy)]
pub struct NonUpperCaseGlobals;

impl LintPass for NonUpperCaseGlobals {
    fn get_lints(&self) -> LintArray {
        lint_array!(NON_UPPER_CASE_GLOBALS)
    }

    fn check_item(&mut self, cx: &Context, it: &ast::Item) {
        match it.node {
            // only check static constants
            ast::ItemStatic(_, ast::MutImmutable, _) |
            ast::ItemConst(..) => {
                let s = token::get_ident(it.ident);
                // check for lowercase letters rather than non-uppercase
                // ones (some scripts don't have a concept of
                // upper/lowercase)
                if s.get().chars().any(|c| c.is_lowercase()) {
                    cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span,
                        format!("static constant `{}` should have an uppercase name \
                                 such as `{}`",
                                s.get(), s.get().chars().map(|c| c.to_uppercase())
                                .collect::<String>()[])[]);
                }
            }
            _ => {}
        }
    }

    fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
        // Lint for constants that look like binding identifiers (#7526)
        match (&p.node, cx.tcx.def_map.borrow().get(&p.id)) {
            (&ast::PatIdent(_, ref path1, _), Some(&def::DefConst(..))) => {
                let s = token::get_ident(path1.node);
                if s.get().chars().any(|c| c.is_lowercase()) {
                    cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span,
                        format!("static constant in pattern `{}` should have an uppercase \
                                 name such as `{}`",
                                s.get(), s.get().chars().map(|c| c.to_uppercase())
                                    .collect::<String>()[])[]);
                }
            }
            _ => {}
        }
    }
}

declare_lint! {
    UNUSED_PARENS,
    Warn,
    "`if`, `match`, `while` and `return` do not need parentheses"
}

#[deriving(Copy)]
pub struct UnusedParens;

impl UnusedParens {
    fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
                                     struct_lit_needs_parens: bool) {
        if let ast::ExprParen(ref inner) = value.node {
            let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
            if !necessary {
                cx.span_lint(UNUSED_PARENS, value.span,
                             format!("unnecessary parentheses around {}",
                                     msg)[])
            }
        }

        /// Expressions that syntactically contain an "exterior" struct
        /// literal i.e. not surrounded by any parens or other
        /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
        /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
        /// y: 1 }) == foo` does not.
        fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
            match value.node {
                ast::ExprStruct(..) => true,

                ast::ExprAssign(ref lhs, ref rhs) |
                ast::ExprAssignOp(_, ref lhs, ref rhs) |
                ast::ExprBinary(_, ref lhs, ref rhs) => {
                    // X { y: 1 } + X { y: 2 }
                    contains_exterior_struct_lit(&**lhs) ||
                        contains_exterior_struct_lit(&**rhs)
                }
                ast::ExprUnary(_, ref x) |
                ast::ExprCast(ref x, _) |
                ast::ExprField(ref x, _) |
                ast::ExprTupField(ref x, _) |
                ast::ExprIndex(ref x, _) => {
                    // &X { y: 1 }, X { y: 1 }.y
                    contains_exterior_struct_lit(&**x)
                }

                ast::ExprMethodCall(_, _, ref exprs) => {
                    // X { y: 1 }.bar(...)
                    contains_exterior_struct_lit(&*exprs[0])
                }

                _ => false
            }
        }
    }
}

impl LintPass for UnusedParens {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_PARENS)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        let (value, msg, struct_lit_needs_parens) = match e.node {
            ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
            ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
            ast::ExprMatch(ref head, _, source) => match source {
                ast::MatchSource::Normal => (head, "`match` head expression", true),
                ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
                ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
            },
            ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
            ast::ExprAssign(_, ref value) => (value, "assigned value", false),
            ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
            _ => return
        };
        self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
    }

    fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
        let (value, msg) = match s.node {
            ast::StmtDecl(ref decl, _) => match decl.node {
                ast::DeclLocal(ref local) => match local.init {
                    Some(ref value) => (value, "assigned value"),
                    None => return
                },
                _ => return
            },
            _ => return
        };
        self.check_unused_parens_core(cx, &**value, msg, false);
    }
}

declare_lint! {
    UNUSED_IMPORT_BRACES,
    Allow,
    "unnecessary braces around an imported item"
}

#[deriving(Copy)]
pub struct UnusedImportBraces;

impl LintPass for UnusedImportBraces {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_IMPORT_BRACES)
    }

    fn check_view_item(&mut self, cx: &Context, view_item: &ast::ViewItem) {
        match view_item.node {
            ast::ViewItemUse(ref view_path) => {
                match view_path.node {
                    ast::ViewPathList(_, ref items, _) => {
                        if items.len() == 1 {
                            match items[0].node {
                                ast::PathListIdent {ref name, ..} => {
                                    let m = format!("braces around {} is unnecessary",
                                                    token::get_ident(*name).get());
                                    cx.span_lint(UNUSED_IMPORT_BRACES, view_item.span,
                                                 m[]);
                                },
                                _ => ()
                            }
                        }
                    }
                    _ => ()
                }
            },
            _ => ()
        }
    }
}

declare_lint! {
    NON_SHORTHAND_FIELD_PATTERNS,
    Warn,
    "using `Struct { x: x }` instead of `Struct { x }`"
}

#[deriving(Copy)]
pub struct NonShorthandFieldPatterns;

impl LintPass for NonShorthandFieldPatterns {
    fn get_lints(&self) -> LintArray {
        lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
    }

    fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
        let def_map = cx.tcx.def_map.borrow();
        if let ast::PatStruct(_, ref v, _) = pat.node {
            for fieldpat in v.iter()
                             .filter(|fieldpat| !fieldpat.node.is_shorthand)
                             .filter(|fieldpat| def_map.get(&fieldpat.node.pat.id)
                                                == Some(&def::DefLocal(fieldpat.node.pat.id))) {
                if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
                    if ident.node.as_str() == fieldpat.node.ident.as_str() {
                        cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
                                     format!("the `{}:` in this pattern is redundant and can \
                                              be removed", ident.node.as_str())[])
                    }
                }
            }
        }
    }
}

declare_lint! {
    pub UNUSED_UNSAFE,
    Warn,
    "unnecessary use of an `unsafe` block"
}

#[deriving(Copy)]
pub struct UnusedUnsafe;

impl LintPass for UnusedUnsafe {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_UNSAFE)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        if let ast::ExprBlock(ref blk) = e.node {
            // Don't warn about generated blocks, that'll just pollute the output.
            if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
                !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
                    cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
            }
        }
    }
}

declare_lint! {
    UNSAFE_BLOCKS,
    Allow,
    "usage of an `unsafe` block"
}

#[deriving(Copy)]
pub struct UnsafeBlocks;

impl LintPass for UnsafeBlocks {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNSAFE_BLOCKS)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        if let ast::ExprBlock(ref blk) = e.node {
            // Don't warn about generated blocks, that'll just pollute the output.
            if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
                cx.span_lint(UNSAFE_BLOCKS, blk.span, "usage of an `unsafe` block");
            }
        }
    }
}

declare_lint! {
    pub UNUSED_MUT,
    Warn,
    "detect mut variables which don't need to be mutable"
}

#[deriving(Copy)]
pub struct UnusedMut;

impl UnusedMut {
    fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
        // collect all mutable pattern and group their NodeIDs by their Identifier to
        // avoid false warnings in match arms with multiple patterns

        let mut mutables = FnvHashMap::new();
        for p in pats.iter() {
            pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
                let ident = path1.node;
                if let ast::BindByValue(ast::MutMutable) = mode {
                    if !token::get_ident(ident).get().starts_with("_") {
                        match mutables.entry(ident.name.uint()) {
                            Vacant(entry) => { entry.set(vec![id]); },
                            Occupied(mut entry) => { entry.get_mut().push(id); },
                        }
                    }
                }
            });
        }

        let used_mutables = cx.tcx.used_mut_nodes.borrow();
        for (_, v) in mutables.iter() {
            if !v.iter().any(|e| used_mutables.contains(e)) {
                cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
                             "variable does not need to be mutable");
            }
        }
    }
}

impl LintPass for UnusedMut {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_MUT)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        if let ast::ExprMatch(_, ref arms, _) = e.node {
            for a in arms.iter() {
                self.check_unused_mut_pat(cx, a.pats[])
            }
        }
    }

    fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
        if let ast::StmtDecl(ref d, _) = s.node {
            if let ast::DeclLocal(ref l) = d.node {
                self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
            }
        }
    }

    fn check_fn(&mut self, cx: &Context,
                _: visit::FnKind, decl: &ast::FnDecl,
                _: &ast::Block, _: Span, _: ast::NodeId) {
        for a in decl.inputs.iter() {
            self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
        }
    }
}

declare_lint! {
    UNUSED_ALLOCATION,
    Warn,
    "detects unnecessary allocations that can be eliminated"
}

#[deriving(Copy)]
pub struct UnusedAllocation;

impl LintPass for UnusedAllocation {
    fn get_lints(&self) -> LintArray {
        lint_array!(UNUSED_ALLOCATION)
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        match e.node {
            ast::ExprUnary(ast::UnUniq, _) => (),
            _ => return
        }

        if let Some(adjustment) = cx.tcx.adjustments.borrow().get(&e.id) {
            if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
                match autoref {
                    &Some(ty::AutoPtr(_, ast::MutImmutable, None)) => {
                        cx.span_lint(UNUSED_ALLOCATION, e.span,
                                     "unnecessary allocation, use & instead");
                    }
                    &Some(ty::AutoPtr(_, ast::MutMutable, None)) => {
                        cx.span_lint(UNUSED_ALLOCATION, e.span,
                                     "unnecessary allocation, use &mut instead");
                    }
                    _ => ()
                }
            }
        }
    }
}

declare_lint! {
    MISSING_DOCS,
    Allow,
    "detects missing documentation for public members"
}

pub struct MissingDoc {
    /// Stack of IDs of struct definitions.
    struct_def_stack: Vec<ast::NodeId>,

    /// True if inside variant definition
    in_variant: bool,

    /// Stack of whether #[doc(hidden)] is set
    /// at each level which has lint attributes.
    doc_hidden_stack: Vec<bool>,
}

impl MissingDoc {
    pub fn new() -> MissingDoc {
        MissingDoc {
            struct_def_stack: vec!(),
            in_variant: false,
            doc_hidden_stack: vec!(false),
        }
    }

    fn doc_hidden(&self) -> bool {
        *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
    }

    fn check_missing_docs_attrs(&self,
                               cx: &Context,
                               id: Option<ast::NodeId>,
                               attrs: &[ast::Attribute],
                               sp: Span,
                               desc: &'static str) {
        // If we're building a test harness, then warning about
        // documentation is probably not really relevant right now.
        if cx.sess().opts.test { return }

        // `#[doc(hidden)]` disables missing_docs check.
        if self.doc_hidden() { return }

        // Only check publicly-visible items, using the result from the privacy pass.
        // It's an option so the crate root can also use this function (it doesn't
        // have a NodeId).
        if let Some(ref id) = id {
            if !cx.exported_items.contains(id) {
                return;
            }
        }

        let has_doc = attrs.iter().any(|a| {
            match a.node.value.node {
                ast::MetaNameValue(ref name, _) if *name == "doc" => true,
                _ => false
            }
        });
        if !has_doc {
            cx.span_lint(MISSING_DOCS, sp,
                format!("missing documentation for {}", desc)[]);
        }
    }
}

impl LintPass for MissingDoc {
    fn get_lints(&self) -> LintArray {
        lint_array!(MISSING_DOCS)
    }

    fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
        let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
            attr.check_name("doc") && match attr.meta_item_list() {
                None => false,
                Some(l) => attr::contains_name(l[], "hidden"),
            }
        });
        self.doc_hidden_stack.push(doc_hidden);
    }

    fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
        self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
    }

    fn check_struct_def(&mut self, _: &Context,
        _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
        self.struct_def_stack.push(id);
    }

    fn check_struct_def_post(&mut self, _: &Context,
        _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
        let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
        assert!(popped == id);
    }

    fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
        self.check_missing_docs_attrs(cx, None, krate.attrs[],
                                     krate.span, "crate");
    }

    fn check_item(&mut self, cx: &Context, it: &ast::Item) {
        let desc = match it.node {
            ast::ItemFn(..) => "a function",
            ast::ItemMod(..) => "a module",
            ast::ItemEnum(..) => "an enum",
            ast::ItemStruct(..) => "a struct",
            ast::ItemTrait(..) => "a trait",
            ast::ItemTy(..) => "a type alias",
            _ => return
        };
        self.check_missing_docs_attrs(cx, Some(it.id), it.attrs[],
                                     it.span, desc);
    }

    fn check_fn(&mut self, cx: &Context,
            fk: visit::FnKind, _: &ast::FnDecl,
            _: &ast::Block, _: Span, _: ast::NodeId) {
        if let visit::FkMethod(_, _, m) = fk {
            // If the method is an impl for a trait, don't doc.
            if method_context(cx, m) == TraitImpl { return; }

            // Otherwise, doc according to privacy. This will also check
            // doc for default methods defined on traits.
            self.check_missing_docs_attrs(cx, Some(m.id), m.attrs[],
                                          m.span, "a method");
        }
    }

    fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
        self.check_missing_docs_attrs(cx, Some(tm.id), tm.attrs[],
                                     tm.span, "a type method");
    }

    fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
        if let ast::NamedField(_, vis) = sf.node.kind {
            if vis == ast::Public || self.in_variant {
                let cur_struct_def = *self.struct_def_stack.last()
                    .expect("empty struct_def_stack");
                self.check_missing_docs_attrs(cx, Some(cur_struct_def),
                                              sf.node.attrs[], sf.span,
                                              "a struct field")
            }
        }
    }

    fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
        self.check_missing_docs_attrs(cx, Some(v.node.id), v.node.attrs[],
                                     v.span, "a variant");
        assert!(!self.in_variant);
        self.in_variant = true;
    }

    fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
        assert!(self.in_variant);
        self.in_variant = false;
    }
}

#[deriving(Copy)]
pub struct MissingCopyImplementations;

impl LintPass for MissingCopyImplementations {
    fn get_lints(&self) -> LintArray {
        lint_array!(MISSING_COPY_IMPLEMENTATIONS)
    }

    fn check_item(&mut self, cx: &Context, item: &ast::Item) {
        if !cx.exported_items.contains(&item.id) {
            return
        }
        if cx.tcx
             .destructor_for_type
             .borrow()
             .contains_key(&ast_util::local_def(item.id)) {
            return
        }
        let ty = match item.node {
            ast::ItemStruct(_, ref ast_generics) => {
                if ast_generics.is_parameterized() {
                    return
                }
                ty::mk_struct(cx.tcx,
                              ast_util::local_def(item.id),
                              cx.tcx.mk_substs(Substs::empty()))
            }
            ast::ItemEnum(_, ref ast_generics) => {
                if ast_generics.is_parameterized() {
                    return
                }
                ty::mk_enum(cx.tcx,
                            ast_util::local_def(item.id),
                            cx.tcx.mk_substs(Substs::empty()))
            }
            _ => return,
        };
        let parameter_environment = ty::empty_parameter_environment();
        if !ty::type_moves_by_default(cx.tcx,
                                      ty,
                                      &parameter_environment) {
            return
        }
        if ty::can_type_implement_copy(cx.tcx,
                                       ty,
                                       &parameter_environment).is_ok() {
            cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
                         item.span,
                         "type could implement `Copy`; consider adding `impl \
                          Copy`")
        }
    }
}

declare_lint! {
    DEPRECATED,
    Warn,
    "detects use of #[deprecated] items"
}

// FIXME #6875: Change to Warn after std library stabilization is complete
declare_lint! {
    EXPERIMENTAL,
    Allow,
    "detects use of #[experimental] items"
}

declare_lint! {
    UNSTABLE,
    Allow,
    "detects use of #[unstable] items (incl. items with no stability attribute)"
}

/// Checks for use of items with `#[deprecated]`, `#[experimental]` and
/// `#[unstable]` attributes, or no stability attribute.
#[deriving(Copy)]
pub struct Stability;

impl Stability {
    fn lint(&self, cx: &Context, id: ast::DefId, span: Span) {
        let stability = stability::lookup(cx.tcx, id);
        let cross_crate = !ast_util::is_local(id);

        // stability attributes are promises made across crates; only
        // check DEPRECATED for crate-local usage.
        let (lint, label) = match stability {
            // no stability attributes == Unstable
            None if cross_crate => (UNSTABLE, "unmarked"),
            Some(attr::Stability { level: attr::Unstable, .. }) if cross_crate =>
                (UNSTABLE, "unstable"),
            Some(attr::Stability { level: attr::Experimental, .. }) if cross_crate =>
                (EXPERIMENTAL, "experimental"),
            Some(attr::Stability { level: attr::Deprecated, .. }) =>
                (DEPRECATED, "deprecated"),
            _ => return
        };

        let msg = match stability {
            Some(attr::Stability { text: Some(ref s), .. }) => {
                format!("use of {} item: {}", label, *s)
            }
            _ => format!("use of {} item", label)
        };

        cx.span_lint(lint, span, msg[]);
    }

    fn is_internal(&self, cx: &Context, span: Span) -> bool {
        cx.tcx.sess.codemap().span_is_internal(span)
    }
}

impl LintPass for Stability {
    fn get_lints(&self) -> LintArray {
        lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE)
    }

    fn check_view_item(&mut self, cx: &Context, item: &ast::ViewItem) {
        // compiler-generated `extern crate` statements have a dummy span.
        if item.span == DUMMY_SP { return }

        let id = match item.node {
            ast::ViewItemExternCrate(_, _, id) => id,
            ast::ViewItemUse(..) => return,
        };
        let cnum = match cx.tcx.sess.cstore.find_extern_mod_stmt_cnum(id) {
            Some(cnum) => cnum,
            None => return,
        };
        let id = ast::DefId { krate: cnum, node: ast::CRATE_NODE_ID };
        self.lint(cx, id, item.span);
    }

    fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
        if self.is_internal(cx, e.span) { return; }

        let mut span = e.span;

        let id = match e.node {
            ast::ExprPath(..) | ast::ExprStruct(..) => {
                match cx.tcx.def_map.borrow().get(&e.id) {
                    Some(&def) => def.def_id(),
                    None => return
                }
            }
            ast::ExprMethodCall(i, _, _) => {
                span = i.span;
                let method_call = ty::MethodCall::expr(e.id);
                match cx.tcx.method_map.borrow().get(&method_call) {
                    Some(method) => {
                        match method.origin {
                            ty::MethodStatic(def_id) => {
                                def_id
                            }
                            ty::MethodStaticUnboxedClosure(def_id) => {
                                def_id
                            }
                            ty::MethodTypeParam(ty::MethodParam {
                                ref trait_ref,
                                method_num: index,
                                ..
                            }) |
                            ty::MethodTraitObject(ty::MethodObject {
                                ref trait_ref,
                                method_num: index,
                                ..
                            }) => {
                                ty::trait_item(cx.tcx, trait_ref.def_id, index).def_id()
                            }
                        }
                    }
                    None => return
                }
            }
            _ => return
        };
        self.lint(cx, id, span);
    }

    fn check_item(&mut self, cx: &Context, item: &ast::Item) {
        if self.is_internal(cx, item.span) { return }

        match item.node {
            ast::ItemTrait(_, _, ref supertraits, _) => {
                for t in supertraits.iter() {
                    if let ast::TraitTyParamBound(ref t, _) = *t {
                        let id = ty::trait_ref_to_def_id(cx.tcx, &t.trait_ref);
                        self.lint(cx, id, t.trait_ref.path.span);
                    }
                }
            }
            ast::ItemImpl(_, _, Some(ref t), _, _) => {
                let id = ty::trait_ref_to_def_id(cx.tcx, t);
                self.lint(cx, id, t.path.span);
            }
            _ => (/* pass */)
        }
    }
}

declare_lint! {
    pub UNUSED_IMPORTS,
    Warn,
    "imports that are never used"
}

declare_lint! {
    pub UNUSED_EXTERN_CRATES,
    Allow,
    "extern crates that are never used"
}

declare_lint! {
    pub UNUSED_QUALIFICATIONS,
    Allow,
    "detects unnecessarily qualified names"
}

declare_lint! {
    pub UNKNOWN_LINTS,
    Warn,
    "unrecognized lint attribute"
}

declare_lint! {
    pub UNUSED_VARIABLES,
    Warn,
    "detect variables which are not used in any way"
}

declare_lint! {
    pub UNUSED_ASSIGNMENTS,
    Warn,
    "detect assignments that will never be read"
}

declare_lint! {
    pub DEAD_CODE,
    Warn,
    "detect unused, unexported items"
}

declare_lint! {
    pub UNREACHABLE_CODE,
    Warn,
    "detects unreachable code paths"
}

declare_lint! {
    pub WARNINGS,
    Warn,
    "mass-change the level for lints which produce warnings"
}

declare_lint! {
    pub UNKNOWN_FEATURES,
    Deny,
    "unknown features found in crate-level #[feature] directives"
}

declare_lint! {
    pub UNKNOWN_CRATE_TYPES,
    Deny,
    "unknown crate type found in #[crate_type] directive"
}

declare_lint! {
    pub VARIANT_SIZE_DIFFERENCES,
    Allow,
    "detects enums with widely varying variant sizes"
}

declare_lint! {
    pub FAT_PTR_TRANSMUTES,
    Allow,
    "detects transmutes of fat pointers"
}

declare_lint!{
    pub MISSING_COPY_IMPLEMENTATIONS,
    Warn,
    "detects potentially-forgotten implementations of `Copy`"
}

/// Does nothing as a lint pass, but registers some `Lint`s
/// which are used by other parts of the compiler.
#[deriving(Copy)]
pub struct HardwiredLints;

impl LintPass for HardwiredLints {
    fn get_lints(&self) -> LintArray {
        lint_array!(
            UNUSED_IMPORTS,
            UNUSED_EXTERN_CRATES,
            UNUSED_QUALIFICATIONS,
            UNKNOWN_LINTS,
            UNUSED_VARIABLES,
            UNUSED_ASSIGNMENTS,
            DEAD_CODE,
            UNREACHABLE_CODE,
            WARNINGS,
            UNKNOWN_FEATURES,
            UNKNOWN_CRATE_TYPES,
            VARIANT_SIZE_DIFFERENCES,
            FAT_PTR_TRANSMUTES
        )
    }
}