summaryrefslogtreecommitdiff
path: root/pylint/lint/pylinter.py
blob: 1619159c6de85fcfe405b87688a357fc54294128 (plain)
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
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE

import collections
import contextlib
import functools
import operator
import os
import sys
import tokenize
import traceback
import warnings
from io import TextIOWrapper
from typing import (
    Any,
    DefaultDict,
    Dict,
    Iterable,
    Iterator,
    List,
    Optional,
    Sequence,
    Set,
    Tuple,
    Type,
    Union,
)

import astroid
from astroid import AstroidError, nodes

from pylint import checkers, config, exceptions, interfaces, reporters
from pylint.constants import (
    MAIN_CHECKER_NAME,
    MSG_STATE_CONFIDENCE,
    MSG_STATE_SCOPE_CONFIG,
    MSG_STATE_SCOPE_MODULE,
    MSG_TYPES,
    MSG_TYPES_LONG,
    MSG_TYPES_STATUS,
)
from pylint.lint.expand_modules import expand_modules
from pylint.lint.parallel import check_parallel
from pylint.lint.report_functions import (
    report_messages_by_module_stats,
    report_messages_stats,
    report_total_messages_stats,
)
from pylint.lint.utils import (
    fix_import_path,
    get_fatal_error_message,
    prepare_crash_report,
)
from pylint.message import Message, MessageDefinition, MessageDefinitionStore
from pylint.reporters.text import TextReporter
from pylint.reporters.ureports import nodes as report_nodes
from pylint.typing import (
    FileItem,
    ManagedMessage,
    MessageLocationTuple,
    ModuleDescriptionDict,
)
from pylint.utils import ASTWalker, FileState, LinterStats, get_global_option, utils
from pylint.utils.pragma_parser import (
    OPTION_PO,
    InvalidPragmaError,
    UnRecognizedOptionError,
    parse_pragma,
)

if sys.version_info >= (3, 8):
    from typing import Literal
else:
    from typing_extensions import Literal

OptionDict = Dict[str, Union[str, bool, int, Iterable[Union[str, int]]]]

MANAGER = astroid.MANAGER


def _read_stdin():
    # https://mail.python.org/pipermail/python-list/2012-November/634424.html
    sys.stdin = TextIOWrapper(sys.stdin.detach(), encoding="utf-8")
    return sys.stdin.read()


def _load_reporter_by_class(reporter_class: str) -> type:
    qname = reporter_class
    module_part = astroid.modutils.get_module_part(qname)
    module = astroid.modutils.load_module_from_name(module_part)
    class_name = qname.split(".")[-1]
    return getattr(module, class_name)


# Python Linter class #########################################################

MSGS = {
    "F0001": (
        "%s",
        "fatal",
        "Used when an error occurred preventing the analysis of a \
              module (unable to find it for instance).",
    ),
    "F0002": (
        "%s: %s",
        "astroid-error",
        "Used when an unexpected error occurred while building the "
        "Astroid  representation. This is usually accompanied by a "
        "traceback. Please report such errors !",
    ),
    "F0010": (
        "error while code parsing: %s",
        "parse-error",
        "Used when an exception occurred while building the Astroid "
        "representation which could be handled by astroid.",
    ),
    "F0011": (
        "error while parsing the configuration: %s",
        "config-parse-error",
        "Used when an exception occurred while parsing a pylint configuration file.",
    ),
    "I0001": (
        "Unable to run raw checkers on built-in module %s",
        "raw-checker-failed",
        "Used to inform that a built-in module has not been checked "
        "using the raw checkers.",
    ),
    "I0010": (
        "Unable to consider inline option %r",
        "bad-inline-option",
        "Used when an inline option is either badly formatted or can't "
        "be used inside modules.",
    ),
    "I0011": (
        "Locally disabling %s (%s)",
        "locally-disabled",
        "Used when an inline option disables a message or a messages category.",
    ),
    "I0013": (
        "Ignoring entire file",
        "file-ignored",
        "Used to inform that the file will not be checked",
    ),
    "I0020": (
        "Suppressed %s (from line %d)",
        "suppressed-message",
        "A message was triggered on a line, but suppressed explicitly "
        "by a disable= comment in the file. This message is not "
        "generated for messages that are ignored due to configuration "
        "settings.",
    ),
    "I0021": (
        "Useless suppression of %s",
        "useless-suppression",
        "Reported when a message is explicitly disabled for a line or "
        "a block of code, but never triggered.",
    ),
    "I0022": (
        'Pragma "%s" is deprecated, use "%s" instead',
        "deprecated-pragma",
        "Some inline pylint options have been renamed or reworked, "
        "only the most recent form should be used. "
        "NOTE:skip-all is only available with pylint >= 0.26",
        {"old_names": [("I0014", "deprecated-disable-all")]},
    ),
    "E0001": ("%s", "syntax-error", "Used when a syntax error is raised for a module."),
    "E0011": (
        "Unrecognized file option %r",
        "unrecognized-inline-option",
        "Used when an unknown inline option is encountered.",
    ),
    "E0012": (
        "Bad option value %r",
        "bad-option-value",
        "Used when a bad value for an inline option is encountered.",
    ),
    "E0013": (
        "Plugin '%s' is impossible to load, is it installed ? ('%s')",
        "bad-plugin-value",
        "Used when a bad value is used in 'load-plugins'.",
    ),
    "E0014": (
        "Out-of-place setting encountered in top level configuration-section '%s' : '%s'",
        "bad-configuration-section",
        "Used when we detect a setting in the top level of a toml configuration that shouldn't be there.",
    ),
}


# pylint: disable=too-many-instance-attributes,too-many-public-methods
class PyLinter(
    config.OptionsManagerMixIn,
    reporters.ReportsHandlerMixIn,
    checkers.BaseTokenChecker,
):
    """lint Python modules using external checkers.

    This is the main checker controlling the other ones and the reports
    generation. It is itself both a raw checker and an astroid checker in order
    to:
    * handle message activation / deactivation at the module level
    * handle some basic but necessary stats'data (number of classes, methods...)

    IDE plugin developers: you may have to call
    `astroid.builder.MANAGER.astroid_cache.clear()` across runs if you want
    to ensure the latest code version is actually checked.

    This class needs to support pickling for parallel linting to work. The exception
    is reporter member; see check_parallel function for more details.
    """

    __implements__ = (interfaces.ITokenChecker,)

    name = MAIN_CHECKER_NAME
    priority = 0
    level = 0
    msgs = MSGS
    # Will be used like this : datetime.now().strftime(crash_file_path)
    crash_file_path: str = "pylint-crash-%Y-%m-%d-%H.txt"

    @staticmethod
    def make_options() -> Tuple[Tuple[str, OptionDict], ...]:
        return (
            (
                "ignore",
                {
                    "type": "csv",
                    "metavar": "<file>[,<file>...]",
                    "dest": "black_list",
                    "default": ("CVS",),
                    "help": "Files or directories to be skipped. "
                    "They should be base names, not paths.",
                },
            ),
            (
                "ignore-patterns",
                {
                    "type": "regexp_csv",
                    "metavar": "<pattern>[,<pattern>...]",
                    "dest": "black_list_re",
                    "default": (r"^\.#",),
                    "help": "Files or directories matching the regex patterns are"
                    " skipped. The regex matches against base names, not paths. The default value "
                    "ignores emacs file locks",
                },
            ),
            (
                "ignore-paths",
                {
                    "type": "regexp_paths_csv",
                    "metavar": "<pattern>[,<pattern>...]",
                    "default": [],
                    "help": "Add files or directories matching the regex patterns to the "
                    "ignore-list. The regex matches against paths and can be in "
                    "Posix or Windows format.",
                },
            ),
            (
                "persistent",
                {
                    "default": True,
                    "type": "yn",
                    "metavar": "<y or n>",
                    "level": 1,
                    "help": "Pickle collected data for later comparisons.",
                },
            ),
            (
                "load-plugins",
                {
                    "type": "csv",
                    "metavar": "<modules>",
                    "default": (),
                    "level": 1,
                    "help": "List of plugins (as comma separated values of "
                    "python module names) to load, usually to register "
                    "additional checkers.",
                },
            ),
            (
                "output-format",
                {
                    "default": "text",
                    "type": "string",
                    "metavar": "<format>",
                    "short": "f",
                    "group": "Reports",
                    "help": "Set the output format. Available formats are text,"
                    " parseable, colorized, json and msvs (visual studio)."
                    " You can also give a reporter class, e.g. mypackage.mymodule."
                    "MyReporterClass.",
                },
            ),
            (
                "reports",
                {
                    "default": False,
                    "type": "yn",
                    "metavar": "<y or n>",
                    "short": "r",
                    "group": "Reports",
                    "help": "Tells whether to display a full report or only the "
                    "messages.",
                },
            ),
            (
                "evaluation",
                {
                    "type": "string",
                    "metavar": "<python_expression>",
                    "group": "Reports",
                    "level": 1,
                    "default": "0 if fatal else 10.0 - ((float(5 * error + warning + refactor + "
                    "convention) / statement) * 10)",
                    "help": "Python expression which should return a score less "
                    "than or equal to 10. You have access to the variables 'fatal', "
                    "'error', 'warning', 'refactor', 'convention', and 'info' which "
                    "contain the number of messages in each category, as well as "
                    "'statement' which is the total number of statements "
                    "analyzed. This score is used by the global "
                    "evaluation report (RP0004).",
                },
            ),
            (
                "score",
                {
                    "default": True,
                    "type": "yn",
                    "metavar": "<y or n>",
                    "short": "s",
                    "group": "Reports",
                    "help": "Activate the evaluation score.",
                },
            ),
            (
                "fail-under",
                {
                    "default": 10,
                    "type": "float",
                    "metavar": "<score>",
                    "help": "Specify a score threshold to be exceeded before program exits with error.",
                },
            ),
            (
                "fail-on",
                {
                    "default": "",
                    "type": "csv",
                    "metavar": "<msg ids>",
                    "help": "Return non-zero exit code if any of these messages/categories are detected,"
                    " even if score is above --fail-under value. Syntax same as enable."
                    " Messages specified are enabled, while categories only check already-enabled messages.",
                },
            ),
            (
                "confidence",
                {
                    "type": "multiple_choice",
                    "metavar": "<levels>",
                    "default": "",
                    "choices": [c.name for c in interfaces.CONFIDENCE_LEVELS],
                    "group": "Messages control",
                    "help": "Only show warnings with the listed confidence levels."
                    f" Leave empty to show all. Valid levels: {', '.join(c.name for c in interfaces.CONFIDENCE_LEVELS)}.",
                },
            ),
            (
                "enable",
                {
                    "type": "csv",
                    "metavar": "<msg ids>",
                    "short": "e",
                    "group": "Messages control",
                    "help": "Enable the message, report, category or checker with the "
                    "given id(s). You can either give multiple identifier "
                    "separated by comma (,) or put this option multiple time "
                    "(only on the command line, not in the configuration file "
                    "where it should appear only once). "
                    'See also the "--disable" option for examples.',
                },
            ),
            (
                "disable",
                {
                    "type": "csv",
                    "metavar": "<msg ids>",
                    "short": "d",
                    "group": "Messages control",
                    "help": "Disable the message, report, category or checker "
                    "with the given id(s). You can either give multiple identifiers "
                    "separated by comma (,) or put this option multiple times "
                    "(only on the command line, not in the configuration file "
                    "where it should appear only once). "
                    'You can also use "--disable=all" to disable everything first '
                    "and then re-enable specific checks. For example, if you want "
                    "to run only the similarities checker, you can use "
                    '"--disable=all --enable=similarities". '
                    "If you want to run only the classes checker, but have no "
                    "Warning level messages displayed, use "
                    '"--disable=all --enable=classes --disable=W".',
                },
            ),
            (
                "msg-template",
                {
                    "type": "string",
                    "metavar": "<template>",
                    "group": "Reports",
                    "help": (
                        "Template used to display messages. "
                        "This is a python new-style format string "
                        "used to format the message information. "
                        "See doc for all details."
                    ),
                },
            ),
            (
                "jobs",
                {
                    "type": "int",
                    "metavar": "<n-processes>",
                    "short": "j",
                    "default": 1,
                    "help": "Use multiple processes to speed up Pylint. Specifying 0 will "
                    "auto-detect the number of processors available to use.",
                },
            ),
            (
                "unsafe-load-any-extension",
                {
                    "type": "yn",
                    "metavar": "<y or n>",
                    "default": False,
                    "hide": True,
                    "help": (
                        "Allow loading of arbitrary C extensions. Extensions"
                        " are imported into the active Python interpreter and"
                        " may run arbitrary code."
                    ),
                },
            ),
            (
                "limit-inference-results",
                {
                    "type": "int",
                    "metavar": "<number-of-results>",
                    "default": 100,
                    "help": (
                        "Control the amount of potential inferred values when inferring "
                        "a single object. This can help the performance when dealing with "
                        "large functions or complex, nested conditions. "
                    ),
                },
            ),
            (
                "extension-pkg-allow-list",
                {
                    "type": "csv",
                    "metavar": "<pkg[,pkg]>",
                    "default": [],
                    "help": (
                        "A comma-separated list of package or module names"
                        " from where C extensions may be loaded. Extensions are"
                        " loading into the active Python interpreter and may run"
                        " arbitrary code."
                    ),
                },
            ),
            (
                "extension-pkg-whitelist",
                {
                    "type": "csv",
                    "metavar": "<pkg[,pkg]>",
                    "default": [],
                    "help": (
                        "A comma-separated list of package or module names"
                        " from where C extensions may be loaded. Extensions are"
                        " loading into the active Python interpreter and may run"
                        " arbitrary code. (This is an alternative name to"
                        " extension-pkg-allow-list for backward compatibility.)"
                    ),
                },
            ),
            (
                "suggestion-mode",
                {
                    "type": "yn",
                    "metavar": "<y or n>",
                    "default": True,
                    "help": (
                        "When enabled, pylint would attempt to guess common "
                        "misconfiguration and emit user-friendly hints instead "
                        "of false-positive error messages."
                    ),
                },
            ),
            (
                "exit-zero",
                {
                    "action": "store_true",
                    "help": (
                        "Always return a 0 (non-error) status code, even if "
                        "lint errors are found. This is primarily useful in "
                        "continuous integration scripts."
                    ),
                },
            ),
            (
                "from-stdin",
                {
                    "action": "store_true",
                    "help": (
                        "Interpret the stdin as a python script, whose filename "
                        "needs to be passed as the module_or_package argument."
                    ),
                },
            ),
            (
                "py-version",
                {
                    "default": sys.version_info[:2],
                    "type": "py_version",
                    "metavar": "<py_version>",
                    "help": (
                        "Minimum Python version to use for version dependent checks. "
                        "Will default to the version used to run pylint."
                    ),
                },
            ),
        )

    base_option_groups = (
        ("Messages control", "Options controlling analysis messages"),
        ("Reports", "Options related to output formatting and reporting"),
    )

    def __init__(
        self,
        options=(),
        reporter=None,
        option_groups=(),
        pylintrc=None,
    ):
        """Some stuff has to be done before ancestors initialization...
        messages store / checkers / reporter / astroid manager"""
        # Attributes for reporters
        self.reporter: Union[reporters.BaseReporter, reporters.MultiReporter]
        if reporter:
            self.set_reporter(reporter)
        else:
            self.set_reporter(TextReporter())
        self._reporters: Dict[str, Type[reporters.BaseReporter]] = {}
        """Dictionary of possible but non-initialized reporters"""

        # Attributes for checkers and plugins
        self._checkers: DefaultDict[
            str, List[checkers.BaseChecker]
        ] = collections.defaultdict(list)
        """Dictionary of registered and initialized checkers"""
        self._dynamic_plugins: Set[str] = set()
        """Set of loaded plugin names"""

        # Attributes related to visiting files
        self.file_state = FileState()
        self.current_name: Optional[str] = None
        self.current_file: Optional[str] = None
        self._ignore_file = False
        self._pragma_lineno: Dict[str, int] = {}

        # Attributes related to stats
        self.stats = LinterStats()

        # Attributes related to (command-line) options and their parsing
        # pylint: disable-next=fixme
        # TODO: Make these implicitly typing when typing for __init__ parameter is added
        self._external_opts: Tuple[Tuple[str, OptionDict], ...] = options
        self.options: Tuple[Tuple[str, OptionDict], ...] = (
            options + PyLinter.make_options()
        )
        self.option_groups: Tuple[Tuple[str, str], ...] = (
            option_groups + PyLinter.base_option_groups
        )
        self._options_methods = {
            "enable": self.enable,
            "disable": self.disable,
            "disable-next": self.disable_next,
        }
        self._bw_options_methods = {
            "disable-msg": self._options_methods["disable"],
            "enable-msg": self._options_methods["enable"],
        }
        self.fail_on_symbols: List[str] = []
        """List of message symbols on which pylint should fail, set by --fail-on"""
        self._error_mode = False

        # Attributes related to messages (states) and their handling
        self.msgs_store = MessageDefinitionStore()
        self.msg_status = 0
        self._msgs_state: Dict[str, bool] = {}
        self._by_id_managed_msgs: List[ManagedMessage] = []

        reporters.ReportsHandlerMixIn.__init__(self)
        super().__init__(
            usage=__doc__,
            config_file=pylintrc or next(config.find_default_config_files(), None),
        )
        checkers.BaseTokenChecker.__init__(self)
        # provided reports
        self.reports = (
            ("RP0001", "Messages by category", report_total_messages_stats),
            (
                "RP0002",
                "% errors / warnings by module",
                report_messages_by_module_stats,
            ),
            ("RP0003", "Messages", report_messages_stats),
        )
        self.register_checker(self)
        self.load_provider_defaults()

    def load_default_plugins(self):
        checkers.initialize(self)
        reporters.initialize(self)

    def load_plugin_modules(self, modnames):
        """take a list of module names which are pylint plugins and load
        and register them
        """
        for modname in modnames:
            if modname in self._dynamic_plugins:
                continue
            self._dynamic_plugins.add(modname)
            try:
                module = astroid.modutils.load_module_from_name(modname)
                module.register(self)
            except ModuleNotFoundError:
                pass

    def load_plugin_configuration(self):
        """Call the configuration hook for plugins

        This walks through the list of plugins, grabs the "load_configuration"
        hook, if exposed, and calls it to allow plugins to configure specific
        settings.
        """
        for modname in self._dynamic_plugins:
            try:
                module = astroid.modutils.load_module_from_name(modname)
                if hasattr(module, "load_configuration"):
                    module.load_configuration(self)
            except ModuleNotFoundError as e:
                self.add_message("bad-plugin-value", args=(modname, e), line=0)

    def _load_reporters(self, reporter_names: str) -> None:
        """Load the reporters if they are available on _reporters"""
        if not self._reporters:
            return
        sub_reporters = []
        output_files = []
        with contextlib.ExitStack() as stack:
            for reporter_name in reporter_names.split(","):
                reporter_name, *reporter_output = reporter_name.split(":", 1)

                reporter = self._load_reporter_by_name(reporter_name)
                sub_reporters.append(reporter)
                if reporter_output:
                    output_file = stack.enter_context(
                        open(reporter_output[0], "w", encoding="utf-8")
                    )
                    reporter.out = output_file
                    output_files.append(output_file)

            # Extend the lifetime of all opened output files
            close_output_files = stack.pop_all().close

        if len(sub_reporters) > 1 or output_files:
            self.set_reporter(
                reporters.MultiReporter(
                    sub_reporters,
                    close_output_files,
                )
            )
        else:
            self.set_reporter(sub_reporters[0])

    def _load_reporter_by_name(self, reporter_name: str) -> reporters.BaseReporter:
        name = reporter_name.lower()
        if name in self._reporters:
            return self._reporters[name]()

        try:
            reporter_class = _load_reporter_by_class(reporter_name)
        except (ImportError, AttributeError) as e:
            raise exceptions.InvalidReporterError(name) from e
        else:
            return reporter_class()

    def set_reporter(
        self, reporter: Union[reporters.BaseReporter, reporters.MultiReporter]
    ) -> None:
        """set the reporter used to display messages and reports"""
        self.reporter = reporter
        reporter.linter = self

    def set_option(self, optname, value, action=None, optdict=None):
        """overridden from config.OptionsProviderMixin to handle some
        special options
        """
        if optname in self._options_methods or optname in self._bw_options_methods:
            if value:
                try:
                    meth = self._options_methods[optname]
                except KeyError:
                    meth = self._bw_options_methods[optname]
                    warnings.warn(
                        f"{optname} is deprecated, replace it by {optname.split('-')[0]}",
                        DeprecationWarning,
                    )
                value = utils._check_csv(value)
                if isinstance(value, (list, tuple)):
                    for _id in value:
                        meth(_id, ignore_unknown=True)
                else:
                    meth(value)
                return  # no need to call set_option, disable/enable methods do it
        elif optname == "output-format":
            assert isinstance(
                value, str
            ), "'output-format' should be a comma separated string of reporters"
            self._load_reporters(value)
        try:
            checkers.BaseTokenChecker.set_option(self, optname, value, action, optdict)
        except config.UnsupportedAction:
            print(f"option {optname} can't be read from config file", file=sys.stderr)

    def register_reporter(self, reporter_class: Type[reporters.BaseReporter]) -> None:
        """Registers a reporter class on the _reporters attribute."""
        self._reporters[reporter_class.name] = reporter_class

    def report_order(self):
        reports = sorted(self._reports, key=lambda x: getattr(x, "name", ""))
        try:
            # Remove the current reporter and add it
            # at the end of the list.
            reports.pop(reports.index(self))
        except ValueError:
            pass
        else:
            reports.append(self)
        return reports

    # checkers manipulation methods ############################################

    def register_checker(self, checker: checkers.BaseChecker) -> None:
        """register a new checker

        checker is an object implementing IRawChecker or / and IAstroidChecker
        """
        assert checker.priority <= 0, "checker priority can't be >= 0"
        self._checkers[checker.name].append(checker)
        for r_id, r_title, r_cb in checker.reports:
            self.register_report(r_id, r_title, r_cb, checker)
        self.register_options_provider(checker)
        if hasattr(checker, "msgs"):
            self.msgs_store.register_messages_from_checker(checker)
        checker.load_defaults()

        # Register the checker, but disable all of its messages.
        if not getattr(checker, "enabled", True):
            self.disable(checker.name)

    def enable_fail_on_messages(self):
        """enable 'fail on' msgs

        Convert values in config.fail_on (which might be msg category, msg id,
        or symbol) to specific msgs, then enable and flag them for later.
        """
        fail_on_vals = self.config.fail_on
        if not fail_on_vals:
            return

        fail_on_cats = set()
        fail_on_msgs = set()
        for val in fail_on_vals:
            # If value is a category, add category, else add message
            if val in MSG_TYPES:
                fail_on_cats.add(val)
            else:
                fail_on_msgs.add(val)

        # For every message in every checker, if cat or msg flagged, enable check
        for all_checkers in self._checkers.values():
            for checker in all_checkers:
                for msg in checker.messages:
                    if msg.msgid in fail_on_msgs or msg.symbol in fail_on_msgs:
                        # message id/symbol matched, enable and flag it
                        self.enable(msg.msgid)
                        self.fail_on_symbols.append(msg.symbol)
                    elif msg.msgid[0] in fail_on_cats:
                        # message starts with a category value, flag (but do not enable) it
                        self.fail_on_symbols.append(msg.symbol)

    def any_fail_on_issues(self):
        return self.stats and any(
            x in self.fail_on_symbols for x in self.stats.by_msg.keys()
        )

    def disable_noerror_messages(self):
        for msgcat, msgids in self.msgs_store._msgs_by_category.items():
            # enable only messages with 'error' severity and above ('fatal')
            if msgcat in {"E", "F"}:
                for msgid in msgids:
                    self.enable(msgid)
            else:
                for msgid in msgids:
                    self.disable(msgid)

    def disable_reporters(self):
        """disable all reporters"""
        for _reporters in self._reports.values():
            for report_id, _, _ in _reporters:
                self.disable_report(report_id)

    def error_mode(self):
        """error mode: enable only errors; no reports, no persistent"""
        self._error_mode = True
        self.disable_noerror_messages()
        self.disable("miscellaneous")
        self.set_option("reports", False)
        self.set_option("persistent", False)
        self.set_option("score", False)

    def list_messages_enabled(self):
        emittable, non_emittable = self.msgs_store.find_emittable_messages()
        enabled = []
        disabled = []
        for message in emittable:
            if self.is_message_enabled(message.msgid):
                enabled.append(f"  {message.symbol} ({message.msgid})")
            else:
                disabled.append(f"  {message.symbol} ({message.msgid})")
        print("Enabled messages:")
        for msg in enabled:
            print(msg)
        print("\nDisabled messages:")
        for msg in disabled:
            print(msg)
        print("\nNon-emittable messages with current interpreter:")
        for msg in non_emittable:
            print(f"  {msg.symbol} ({msg.msgid})")
        print("")

    # block level option handling #############################################
    # see func_block_disable_msg.py test case for expected behaviour

    def process_tokens(self, tokens):
        """Process tokens from the current module to search for module/block level
        options."""
        control_pragmas = {"disable", "disable-next", "enable"}
        prev_line = None
        saw_newline = True
        seen_newline = True
        for (tok_type, content, start, _, _) in tokens:
            if prev_line and prev_line != start[0]:
                saw_newline = seen_newline
                seen_newline = False

            prev_line = start[0]
            if tok_type in (tokenize.NL, tokenize.NEWLINE):
                seen_newline = True

            if tok_type != tokenize.COMMENT:
                continue
            match = OPTION_PO.search(content)
            if match is None:
                continue
            try:
                for pragma_repr in parse_pragma(match.group(2)):
                    if pragma_repr.action in {"disable-all", "skip-file"}:
                        if pragma_repr.action == "disable-all":
                            self.add_message(
                                "deprecated-pragma",
                                line=start[0],
                                args=("disable-all", "skip-file"),
                            )
                        self.add_message("file-ignored", line=start[0])
                        self._ignore_file = True
                        return
                    try:
                        meth = self._options_methods[pragma_repr.action]
                    except KeyError:
                        meth = self._bw_options_methods[pragma_repr.action]
                        # found a "(dis|en)able-msg" pragma deprecated suppression
                        self.add_message(
                            "deprecated-pragma",
                            line=start[0],
                            args=(
                                pragma_repr.action,
                                pragma_repr.action.replace("-msg", ""),
                            ),
                        )
                    for msgid in pragma_repr.messages:
                        # Add the line where a control pragma was encountered.
                        if pragma_repr.action in control_pragmas:
                            self._pragma_lineno[msgid] = start[0]

                        if (pragma_repr.action, msgid) == ("disable", "all"):
                            self.add_message(
                                "deprecated-pragma",
                                line=start[0],
                                args=("disable=all", "skip-file"),
                            )
                            self.add_message("file-ignored", line=start[0])
                            self._ignore_file = True
                            return
                            # If we did not see a newline between the previous line and now,
                            # we saw a backslash so treat the two lines as one.
                        l_start = start[0]
                        if not saw_newline:
                            l_start -= 1
                        try:
                            meth(msgid, "module", l_start)
                        except exceptions.UnknownMessageError:
                            self.add_message(
                                "bad-option-value", args=msgid, line=start[0]
                            )
            except UnRecognizedOptionError as err:
                self.add_message(
                    "unrecognized-inline-option", args=err.token, line=start[0]
                )
                continue
            except InvalidPragmaError as err:
                self.add_message("bad-inline-option", args=err.token, line=start[0])
                continue

    # code checking methods ###################################################

    def get_checkers(self):
        """return all available checkers as a list"""
        return [self] + [
            c
            for _checkers in self._checkers.values()
            for c in _checkers
            if c is not self
        ]

    def get_checker_names(self):
        """Get all the checker names that this linter knows about."""
        current_checkers = self.get_checkers()
        return sorted(
            {
                checker.name
                for checker in current_checkers
                if checker.name != MAIN_CHECKER_NAME
            }
        )

    def prepare_checkers(self):
        """return checkers needed for activated messages and reports"""
        if not self.config.reports:
            self.disable_reporters()
        # get needed checkers
        needed_checkers = [self]
        for checker in self.get_checkers()[1:]:
            messages = {msg for msg in checker.msgs if self.is_message_enabled(msg)}
            if messages or any(self.report_is_enabled(r[0]) for r in checker.reports):
                needed_checkers.append(checker)
        # Sort checkers by priority
        needed_checkers = sorted(
            needed_checkers, key=operator.attrgetter("priority"), reverse=True
        )
        return needed_checkers

    # pylint: disable=unused-argument
    @staticmethod
    def should_analyze_file(modname, path, is_argument=False):
        """Returns whether or not a module should be checked.

        This implementation returns True for all python source file, indicating
        that all files should be linted.

        Subclasses may override this method to indicate that modules satisfying
        certain conditions should not be linted.

        :param str modname: The name of the module to be checked.
        :param str path: The full path to the source code of the module.
        :param bool is_argument: Whether the file is an argument to pylint or not.
                                 Files which respect this property are always
                                 checked, since the user requested it explicitly.
        :returns: True if the module should be checked.
        :rtype: bool
        """
        if is_argument:
            return True
        return path.endswith(".py")

    # pylint: enable=unused-argument

    def initialize(self):
        """Initialize linter for linting

        This method is called before any linting is done.
        """
        # initialize msgs_state now that all messages have been registered into
        # the store
        for msg in self.msgs_store.messages:
            if not msg.may_be_emitted():
                self._msgs_state[msg.msgid] = False

    def check(self, files_or_modules: Union[Sequence[str], str]) -> None:
        """main checking entry: check a list of files or modules from their name.

        files_or_modules is either a string or list of strings presenting modules to check.
        """
        self.initialize()
        if not isinstance(files_or_modules, (list, tuple)):
            # pylint: disable-next=fixme
            # TODO: Update typing and docstring for 'files_or_modules' when removing the deprecation
            warnings.warn(
                "In pylint 3.0, the checkers check function will only accept sequence of string",
                DeprecationWarning,
            )
            files_or_modules = (files_or_modules,)  # type: ignore[assignment]
        if self.config.from_stdin:
            if len(files_or_modules) != 1:
                raise exceptions.InvalidArgsError(
                    "Missing filename required for --from-stdin"
                )

            filepath = files_or_modules[0]
            with fix_import_path(files_or_modules):
                self._check_files(
                    functools.partial(self.get_ast, data=_read_stdin()),
                    [self._get_file_descr_from_stdin(filepath)],
                )
        elif self.config.jobs == 1:
            with fix_import_path(files_or_modules):
                self._check_files(
                    self.get_ast, self._iterate_file_descrs(files_or_modules)
                )
        else:
            check_parallel(
                self,
                self.config.jobs,
                self._iterate_file_descrs(files_or_modules),
                files_or_modules,
            )

    def check_single_file(self, name: str, filepath: str, modname: str) -> None:
        warnings.warn(
            "In pylint 3.0, the checkers check_single_file function will be removed. "
            "Use check_single_file_item instead.",
            DeprecationWarning,
        )
        self.check_single_file_item(FileItem(name, filepath, modname))

    def check_single_file_item(self, file: FileItem) -> None:
        """Check single file item

        The arguments are the same that are documented in _check_files

        The initialize() method should be called before calling this method
        """
        with self._astroid_module_checker() as check_astroid_module:
            self._check_file(self.get_ast, check_astroid_module, file)

    def _check_files(
        self,
        get_ast,
        file_descrs: Iterable[FileItem],
    ) -> None:
        """Check all files from file_descrs"""
        with self._astroid_module_checker() as check_astroid_module:
            for file in file_descrs:
                try:
                    self._check_file(get_ast, check_astroid_module, file)
                except Exception as ex:  # pylint: disable=broad-except
                    template_path = prepare_crash_report(
                        ex, file.filepath, self.crash_file_path
                    )
                    msg = get_fatal_error_message(file.filepath, template_path)
                    if isinstance(ex, AstroidError):
                        symbol = "astroid-error"
                        self.add_message(symbol, args=(file.filepath, msg))
                    else:
                        symbol = "fatal"
                        self.add_message(symbol, args=msg)

    def _check_file(self, get_ast, check_astroid_module, file: FileItem):
        """Check a file using the passed utility functions (get_ast and check_astroid_module)

        :param callable get_ast: callable returning AST from defined file taking the following arguments
        - filepath: path to the file to check
        - name: Python module name
        :param callable check_astroid_module: callable checking an AST taking the following arguments
        - ast: AST of the module
        :param FileItem file: data about the file
        """
        self.set_current_module(file.name, file.filepath)
        # get the module representation
        ast_node = get_ast(file.filepath, file.name)
        if ast_node is None:
            return

        self._ignore_file = False

        self.file_state = FileState(file.modpath)
        # fix the current file (if the source file was not available or
        # if it's actually a c extension)
        self.current_file = ast_node.file
        check_astroid_module(ast_node)
        # warn about spurious inline messages handling
        spurious_messages = self.file_state.iter_spurious_suppression_messages(
            self.msgs_store
        )
        for msgid, line, args in spurious_messages:
            self.add_message(msgid, line, None, args)

    @staticmethod
    def _get_file_descr_from_stdin(filepath: str) -> FileItem:
        """Return file description (tuple of module name, file path, base name) from given file path

        This method is used for creating suitable file description for _check_files when the
        source is standard input.
        """
        try:
            # Note that this function does not really perform an
            # __import__ but may raise an ImportError exception, which
            # we want to catch here.
            modname = ".".join(astroid.modutils.modpath_from_file(filepath))
        except ImportError:
            modname = os.path.splitext(os.path.basename(filepath))[0]

        return FileItem(modname, filepath, filepath)

    def _iterate_file_descrs(self, files_or_modules) -> Iterator[FileItem]:
        """Return generator yielding file descriptions (tuples of module name, file path, base name)

        The returned generator yield one item for each Python module that should be linted.
        """
        for descr in self._expand_files(files_or_modules):
            name, filepath, is_arg = descr["name"], descr["path"], descr["isarg"]
            if self.should_analyze_file(name, filepath, is_argument=is_arg):
                yield FileItem(name, filepath, descr["basename"])

    def _expand_files(self, modules) -> List[ModuleDescriptionDict]:
        """get modules and errors from a list of modules and handle errors"""
        result, errors = expand_modules(
            modules,
            self.config.black_list,
            self.config.black_list_re,
            self._ignore_paths,
        )
        for error in errors:
            message = modname = error["mod"]
            key = error["key"]
            self.set_current_module(modname)
            if key == "fatal":
                message = str(error["ex"]).replace(os.getcwd() + os.sep, "")
            self.add_message(key, args=message)
        return result

    def set_current_module(self, modname, filepath: Optional[str] = None):
        """set the name of the currently analyzed module and
        init statistics for it
        """
        if not modname and filepath is None:
            return
        self.reporter.on_set_current_module(modname, filepath)
        self.current_name = modname
        self.current_file = filepath or modname
        self.stats.init_single_module(modname)

    @contextlib.contextmanager
    def _astroid_module_checker(self):
        """Context manager for checking ASTs

        The value in the context is callable accepting AST as its only argument.
        """
        walker = ASTWalker(self)
        _checkers = self.prepare_checkers()
        tokencheckers = [
            c
            for c in _checkers
            if interfaces.implements(c, interfaces.ITokenChecker) and c is not self
        ]
        rawcheckers = [
            c for c in _checkers if interfaces.implements(c, interfaces.IRawChecker)
        ]
        # notify global begin
        for checker in _checkers:
            checker.open()
            if interfaces.implements(checker, interfaces.IAstroidChecker):
                walker.add_checker(checker)

        yield functools.partial(
            self.check_astroid_module,
            walker=walker,
            tokencheckers=tokencheckers,
            rawcheckers=rawcheckers,
        )

        # notify global end
        self.stats.statement = walker.nbstatements
        for checker in reversed(_checkers):
            checker.close()

    def get_ast(self, filepath, modname, data=None):
        """Return an ast(roid) representation of a module or a string.

        :param str filepath: path to checked file.
        :param str modname: The name of the module to be checked.
        :param str data: optional contents of the checked file.
        :returns: the AST
        :rtype: astroid.nodes.Module
        """
        try:
            if data is None:
                return MANAGER.ast_from_file(filepath, modname, source=True)
            return astroid.builder.AstroidBuilder(MANAGER).string_build(
                data, modname, filepath
            )
        except astroid.AstroidSyntaxError as ex:
            # pylint: disable=no-member
            self.add_message(
                "syntax-error",
                line=getattr(ex.error, "lineno", 0),
                col_offset=getattr(ex.error, "offset", None),
                args=str(ex.error),
            )
        except astroid.AstroidBuildingException as ex:
            self.add_message("parse-error", args=ex)
        except Exception as ex:  # pylint: disable=broad-except
            traceback.print_exc()
            self.add_message("astroid-error", args=(ex.__class__, ex))
        return None

    def check_astroid_module(self, ast_node, walker, rawcheckers, tokencheckers):
        """Check a module from its astroid representation.

        For return value see _check_astroid_module
        """
        before_check_statements = walker.nbstatements

        retval = self._check_astroid_module(
            ast_node, walker, rawcheckers, tokencheckers
        )

        self.stats.by_module[self.current_name]["statement"] = (
            walker.nbstatements - before_check_statements
        )

        return retval

    def _check_astroid_module(
        self, node: nodes.Module, walker, rawcheckers, tokencheckers
    ):
        """Check given AST node with given walker and checkers

        :param astroid.nodes.Module node: AST node of the module to check
        :param pylint.utils.ast_walker.ASTWalker walker: AST walker
        :param list rawcheckers: List of token checkers to use
        :param list tokencheckers: List of raw checkers to use

        :returns: True if the module was checked, False if ignored,
            None if the module contents could not be parsed
        :rtype: bool
        """
        try:
            tokens = utils.tokenize_module(node)
        except tokenize.TokenError as ex:
            self.add_message("syntax-error", line=ex.args[1][0], args=ex.args[0])
            return None

        if not node.pure_python:
            self.add_message("raw-checker-failed", args=node.name)
        else:
            # assert astroid.file.endswith('.py')
            # invoke ITokenChecker interface on self to fetch module/block
            # level options
            self.process_tokens(tokens)
            if self._ignore_file:
                return False
            # walk ast to collect line numbers
            self.file_state.collect_block_lines(self.msgs_store, node)
            # run raw and tokens checkers
            for checker in rawcheckers:
                checker.process_module(node)
            for checker in tokencheckers:
                checker.process_tokens(tokens)
        # generate events to astroid checkers
        walker.walk(node)
        return True

    # IAstroidChecker interface #################################################

    def open(self):
        """initialize counters"""
        self.stats = LinterStats()
        MANAGER.always_load_extensions = self.config.unsafe_load_any_extension
        MANAGER.max_inferable_values = self.config.limit_inference_results
        MANAGER.extension_package_whitelist.update(self.config.extension_pkg_allow_list)
        if self.config.extension_pkg_whitelist:
            MANAGER.extension_package_whitelist.update(
                self.config.extension_pkg_whitelist
            )
        self.stats.reset_message_count()
        self._ignore_paths = get_global_option(self, "ignore-paths")

    def generate_reports(self):
        """close the whole package /module, it's time to make reports !

        if persistent run, pickle results for later comparison
        """
        # Display whatever messages are left on the reporter.
        self.reporter.display_messages(report_nodes.Section())

        if self.file_state.base_name is not None:
            # load previous results if any
            previous_stats = config.load_results(self.file_state.base_name)
            self.reporter.on_close(self.stats, previous_stats)
            if self.config.reports:
                sect = self.make_reports(self.stats, previous_stats)
            else:
                sect = report_nodes.Section()

            if self.config.reports:
                self.reporter.display_reports(sect)
            score_value = self._report_evaluation()
            # save results if persistent run
            if self.config.persistent:
                config.save_results(self.stats, self.file_state.base_name)
        else:
            self.reporter.on_close(self.stats, LinterStats())
            score_value = None
        return score_value

    def _report_evaluation(self):
        """make the global evaluation report"""
        # check with at least check 1 statements (usually 0 when there is a
        # syntax error preventing pylint from further processing)
        note = None
        previous_stats = config.load_results(self.file_state.base_name)
        if self.stats.statement == 0:
            return note

        # get a global note for the code
        evaluation = self.config.evaluation
        try:
            stats_dict = {
                "fatal": self.stats.fatal,
                "error": self.stats.error,
                "warning": self.stats.warning,
                "refactor": self.stats.refactor,
                "convention": self.stats.convention,
                "statement": self.stats.statement,
                "info": self.stats.info,
            }
            note = eval(evaluation, {}, stats_dict)  # pylint: disable=eval-used
        except Exception as ex:  # pylint: disable=broad-except
            msg = f"An exception occurred while rating: {ex}"
        else:
            self.stats.global_note = note
            msg = f"Your code has been rated at {note:.2f}/10"
            if previous_stats:
                pnote = previous_stats.global_note
                if pnote is not None:
                    msg += f" (previous run: {pnote:.2f}/10, {note - pnote:+.2f})"

        if self.config.score:
            sect = report_nodes.EvaluationSection(msg)
            self.reporter.display_reports(sect)
        return note

    # Adding (ignored) messages to the Message Reporter

    def _get_message_state_scope(
        self,
        msgid: str,
        line: Optional[int] = None,
        confidence: Optional[interfaces.Confidence] = None,
    ) -> Optional[Literal[0, 1, 2]]:
        """Returns the scope at which a message was enabled/disabled."""
        if confidence is None:
            confidence = interfaces.UNDEFINED
        if self.config.confidence and confidence.name not in self.config.confidence:
            return MSG_STATE_CONFIDENCE  # type: ignore[return-value] # mypy does not infer Literal correctly
        try:
            if line in self.file_state._module_msgs_state[msgid]:
                return MSG_STATE_SCOPE_MODULE  # type: ignore[return-value]
        except (KeyError, TypeError):
            return MSG_STATE_SCOPE_CONFIG  # type: ignore[return-value]
        return None

    def _is_one_message_enabled(self, msgid: str, line: Optional[int]) -> bool:
        """Checks state of a single message"""
        if line is None:
            return self._msgs_state.get(msgid, True)
        try:
            return self.file_state._module_msgs_state[msgid][line]
        except KeyError:
            # Check if the message's line is after the maximum line existing in ast tree.
            # This line won't appear in the ast tree and won't be referred in
            # self.file_state._module_msgs_state
            # This happens for example with a commented line at the end of a module.
            max_line_number = self.file_state.get_effective_max_line_number()
            if max_line_number and line > max_line_number:
                fallback = True
                lines = self.file_state._raw_module_msgs_state.get(msgid, {})

                # Doesn't consider scopes, as a disable can be in a different scope
                # than that of the current line.
                closest_lines = reversed(
                    [
                        (message_line, enable)
                        for message_line, enable in lines.items()
                        if message_line <= line
                    ]
                )
                _, fallback_iter = next(closest_lines, (None, None))
                if fallback_iter is not None:
                    fallback = fallback_iter

                return self._msgs_state.get(msgid, fallback)
            return self._msgs_state.get(msgid, True)

    def is_message_enabled(
        self,
        msg_descr: str,
        line: Optional[int] = None,
        confidence: Optional[interfaces.Confidence] = None,
    ) -> bool:
        """return whether the message associated to the given message id is
        enabled

        msgid may be either a numeric or symbolic message id.
        """
        if self.config.confidence and confidence:
            if confidence.name not in self.config.confidence:
                return False
        try:
            message_definitions = self.msgs_store.get_message_definitions(msg_descr)
            msgids = [md.msgid for md in message_definitions]
        except exceptions.UnknownMessageError:
            # The linter checks for messages that are not registered
            # due to version mismatch, just treat them as message IDs
            # for now.
            msgids = [msg_descr]
        return any(self._is_one_message_enabled(msgid, line) for msgid in msgids)

    def _add_one_message(
        self,
        message_definition: MessageDefinition,
        line: Optional[int],
        node: Optional[nodes.NodeNG],
        args: Optional[Any],
        confidence: Optional[interfaces.Confidence],
        col_offset: Optional[int],
        end_lineno: Optional[int],
        end_col_offset: Optional[int],
    ) -> None:
        """After various checks have passed a single Message is
        passed to the reporter and added to stats"""
        message_definition.check_message_definition(line, node)

        # Look up "location" data of node if not yet supplied
        if node:
            if not line:
                line = node.fromlineno
            # pylint: disable=fixme
            # TODO: Initialize col_offset on every node (can be None) -> astroid
            if not col_offset and hasattr(node, "col_offset"):
                col_offset = node.col_offset
            # pylint: disable=fixme
            # TODO: Initialize end_lineno on every node (can be None) -> astroid
            # See https://github.com/PyCQA/astroid/issues/1273
            if not end_lineno and hasattr(node, "end_lineno"):
                end_lineno = node.end_lineno
            # pylint: disable=fixme
            # TODO: Initialize end_col_offset on every node (can be None) -> astroid
            if not end_col_offset and hasattr(node, "end_col_offset"):
                end_col_offset = node.end_col_offset

        # should this message be displayed
        if not self.is_message_enabled(message_definition.msgid, line, confidence):
            self.file_state.handle_ignored_message(
                self._get_message_state_scope(
                    message_definition.msgid, line, confidence
                ),
                message_definition.msgid,
                line,
            )
            return

        # update stats
        msg_cat = MSG_TYPES[message_definition.msgid[0]]
        self.msg_status |= MSG_TYPES_STATUS[message_definition.msgid[0]]
        self.stats.increase_single_message_count(msg_cat, 1)
        self.stats.increase_single_module_message_count(self.current_name, msg_cat, 1)
        try:
            self.stats.by_msg[message_definition.symbol] += 1
        except KeyError:
            self.stats.by_msg[message_definition.symbol] = 1
        # Interpolate arguments into message string
        msg = message_definition.msg
        if args:
            msg %= args
        # get module and object
        if node is None:
            module, obj = self.current_name, ""
            abspath = self.current_file
        else:
            module, obj = utils.get_module_and_frameid(node)
            abspath = node.root().file
        if abspath is not None:
            path = abspath.replace(self.reporter.path_strip_prefix, "", 1)
        else:
            path = "configuration"
        # add the message
        self.reporter.handle_message(
            Message(
                message_definition.msgid,
                message_definition.symbol,
                MessageLocationTuple(
                    abspath or "",
                    path,
                    module or "",
                    obj,
                    line or 1,
                    col_offset or 0,
                    end_lineno,
                    end_col_offset,
                ),
                msg,
                confidence,
            )
        )

    def add_message(
        self,
        msgid: str,
        line: Optional[int] = None,
        node: Optional[nodes.NodeNG] = None,
        args: Optional[Any] = None,
        confidence: Optional[interfaces.Confidence] = None,
        col_offset: Optional[int] = None,
        end_lineno: Optional[int] = None,
        end_col_offset: Optional[int] = None,
    ) -> None:
        """Adds a message given by ID or name.

        If provided, the message string is expanded using args.

        AST checkers must provide the node argument (but may optionally
        provide line if the line number is different), raw and token checkers
        must provide the line argument.
        """
        if confidence is None:
            confidence = interfaces.UNDEFINED
        message_definitions = self.msgs_store.get_message_definitions(msgid)
        for message_definition in message_definitions:
            self._add_one_message(
                message_definition,
                line,
                node,
                args,
                confidence,
                col_offset,
                end_lineno,
                end_col_offset,
            )

    def add_ignored_message(
        self,
        msgid: str,
        line: int,
        node: Optional[nodes.NodeNG] = None,
        confidence: Optional[interfaces.Confidence] = interfaces.UNDEFINED,
    ) -> None:
        """Prepares a message to be added to the ignored message storage

        Some checks return early in special cases and never reach add_message(),
        even though they would normally issue a message.
        This creates false positives for useless-suppression.
        This function avoids this by adding those message to the ignored msgs attribute
        """
        message_definitions = self.msgs_store.get_message_definitions(msgid)
        for message_definition in message_definitions:
            message_definition.check_message_definition(line, node)
            self.file_state.handle_ignored_message(
                self._get_message_state_scope(
                    message_definition.msgid, line, confidence
                ),
                message_definition.msgid,
                line,
            )

    # Setting the state (disabled/enabled) of messages and registering them

    def _message_symbol(self, msgid: str) -> List[str]:
        """Get the message symbol of the given message id

        Return the original message id if the message does not
        exist.
        """
        try:
            return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)]
        except exceptions.UnknownMessageError:
            return [msgid]

    def _set_one_msg_status(
        self, scope: str, msg: MessageDefinition, line: Optional[int], enable: bool
    ) -> None:
        """Set the status of an individual message"""
        if scope == "module":
            self.file_state.set_msg_status(msg, line, enable)
            if not enable and msg.symbol != "locally-disabled":
                self.add_message(
                    "locally-disabled", line=line, args=(msg.symbol, msg.msgid)
                )
        else:
            msgs = self._msgs_state
            msgs[msg.msgid] = enable
            # sync configuration object
            self.config.enable = [
                self._message_symbol(mid) for mid, val in sorted(msgs.items()) if val
            ]
            self.config.disable = [
                self._message_symbol(mid)
                for mid, val in sorted(msgs.items())
                if not val
            ]

    def _set_msg_status(
        self,
        msgid: str,
        enable: bool,
        scope: str = "package",
        line: Optional[int] = None,
        ignore_unknown: bool = False,
    ) -> None:
        """Do some tests and then iterate over message definitions to set state"""
        assert scope in {"package", "module"}
        if msgid == "all":
            for _msgid in MSG_TYPES:
                self._set_msg_status(_msgid, enable, scope, line, ignore_unknown)
            return

        # msgid is a category?
        category_id = msgid.upper()
        if category_id not in MSG_TYPES:
            category_id_formatted = MSG_TYPES_LONG.get(category_id)
        else:
            category_id_formatted = category_id
        if category_id_formatted is not None:
            for _msgid in self.msgs_store._msgs_by_category.get(category_id_formatted):
                self._set_msg_status(_msgid, enable, scope, line)
            return

        # msgid is a checker name?
        if msgid.lower() in self._checkers:
            for checker in self._checkers[msgid.lower()]:
                for _msgid in checker.msgs:
                    self._set_msg_status(_msgid, enable, scope, line)
            return

        # msgid is report id?
        if msgid.lower().startswith("rp"):
            if enable:
                self.enable_report(msgid)
            else:
                self.disable_report(msgid)
            return

        try:
            # msgid is a symbolic or numeric msgid.
            message_definitions = self.msgs_store.get_message_definitions(msgid)
        except exceptions.UnknownMessageError:
            if ignore_unknown:
                return
            raise
        for message_definition in message_definitions:
            self._set_one_msg_status(scope, message_definition, line, enable)

    def _register_by_id_managed_msg(
        self, msgid_or_symbol: str, line: Optional[int], is_disabled: bool = True
    ) -> None:
        """If the msgid is a numeric one, then register it to inform the user
        it could furnish instead a symbolic msgid."""
        if msgid_or_symbol[1:].isdigit():
            try:
                symbol = self.msgs_store.message_id_store.get_symbol(
                    msgid=msgid_or_symbol
                )
            except exceptions.UnknownMessageError:
                return
            managed = ManagedMessage(
                self.current_name, msgid_or_symbol, symbol, line, is_disabled
            )
            self._by_id_managed_msgs.append(managed)

    def disable(
        self,
        msgid: str,
        scope: str = "package",
        line: Optional[int] = None,
        ignore_unknown: bool = False,
    ) -> None:
        """Disable a message for a scope"""
        self._set_msg_status(
            msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown
        )
        self._register_by_id_managed_msg(msgid, line)

    def disable_next(
        self,
        msgid: str,
        scope: str = "package",
        line: Optional[int] = None,
        ignore_unknown: bool = False,
    ) -> None:
        """Disable a message for the next line"""
        if not line:
            raise exceptions.NoLineSuppliedError
        self._set_msg_status(
            msgid,
            enable=False,
            scope=scope,
            line=line + 1,
            ignore_unknown=ignore_unknown,
        )
        self._register_by_id_managed_msg(msgid, line + 1)

    def enable(
        self,
        msgid: str,
        scope: str = "package",
        line: Optional[int] = None,
        ignore_unknown: bool = False,
    ) -> None:
        """Enable a message for a scope"""
        self._set_msg_status(
            msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown
        )
        self._register_by_id_managed_msg(msgid, line, is_disabled=False)