Skip to content

Commit 9656fdc

Browse files
Integrate mypy part 2
1 parent a14dff8 commit 9656fdc

20 files changed

Lines changed: 94 additions & 53 deletions

File tree

analyzer/codechecker_analyzer/analysis_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from functools import lru_cache
2020
from threading import Timer
2121

22-
import multiprocess
22+
import multiprocess # type: ignore
2323

2424
from codechecker_common.logger import get_logger
2525
from codechecker_common.process import kill_process_tree

analyzer/codechecker_analyzer/analyzer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import sys
1919
import time
2020

21-
from multiprocess.managers import SyncManager
21+
from multiprocess.managers import SyncManager # type: ignore
2222

2323
from codechecker_common.logger import get_logger, DEBUG
2424
from codechecker_common.review_status_handler import ReviewStatusHandler

analyzer/codechecker_analyzer/analyzers/analyzer_base.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,13 @@ def get_analyzer_checkers(cls):
151151
"""
152152
raise NotImplementedError("Subclasses should implement this!")
153153

154+
@classmethod
155+
def analyzer_binary(cls) -> str:
156+
"""
157+
Return path to the analyzer binary.
158+
"""
159+
raise NotImplementedError("Subclasses should implement this!")
160+
154161
@classmethod
155162
def get_analyzer_config(cls) -> List[AnalyzerConfig]:
156163
return []

analyzer/codechecker_analyzer/analyzers/clangsa/analyzer.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ def get_analyzer_checkers(
361361
cls,
362362
alpha: bool = True,
363363
debug: bool = False
364-
) -> List[str]:
364+
) -> List[Tuple[str, str]]:
365365
"""
366366
Return the list of the supported checkers.
367367
@@ -425,7 +425,8 @@ def get_checker_config(cls) -> List[analyzer_base.CheckerConfig]:
425425

426426
result = []
427427
for cfg, doc in parse_clang_help_page(command, 'OPTIONS:'):
428-
result.append(analyzer_base.CheckerConfig(*cfg.split(':', 1), doc))
428+
checker, opt = cfg.split(':', 1)
429+
result.append(analyzer_base.CheckerConfig(checker, opt, doc))
429430

430431
return result
431432

@@ -439,11 +440,11 @@ def get_analyzer_config(cls) -> List[analyzer_base.AnalyzerConfig]:
439440
command.append("-analyzer-config-help")
440441

441442
native_config = parse_clang_help_page(command, 'OPTIONS:')
442-
native_config = map(
443+
analyzer_config_list: List[analyzer_base.AnalyzerConfig] = list(map(
443444
lambda cfg: analyzer_base.AnalyzerConfig(cfg[0], cfg[1], str),
444-
native_config)
445+
native_config))
445446

446-
return list(native_config) + list(cls.__additional_analyzer_config)
447+
return analyzer_config_list + list(cls.__additional_analyzer_config)
447448

448449
def post_analyze(self, result_handler):
449450
"""

analyzer/codechecker_analyzer/analyzers/clangtidy/analyzer.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,8 @@ def get_checker_config(cls) -> List[analyzer_base.CheckerConfig]:
351351

352352
result = []
353353
for cfg, doc in parse_checker_config(help_page):
354-
result.append(analyzer_base.CheckerConfig(*cfg.split(':', 1), doc))
354+
checker, opt = cfg.split(':', 1)
355+
result.append(analyzer_base.CheckerConfig(checker, opt, doc))
355356

356357
return result
357358

analyzer/codechecker_analyzer/analyzers/cppcheck/result_handler.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
from codechecker_common.skiplist_handler import SkipListHandlers
2222
from codechecker_common.review_status_handler import ReviewStatusHandler
2323

24+
from codechecker_analyzer.analyzers.cppcheck.analyzer import Cppcheck
25+
2426
from ..result_handler_base import ResultHandler
2527

2628
LOG = get_logger('analyzer.cppcheck')
@@ -31,6 +33,10 @@ class CppcheckResultHandler(ResultHandler):
3133
Create analyzer result file for Cppcheck output.
3234
"""
3335

36+
# This attribute is set dynamically when constructing
37+
# this class.
38+
analyzer: Cppcheck
39+
3440
def __init__(self, *args, **kwargs):
3541
self.analyzer_info = AnalyzerInfo(name=AnalyzerResult.TOOL_NAME)
3642

analyzer/codechecker_analyzer/buildlog/host_check.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def check_intercept(env) -> bool:
3232
stdout=subprocess.DEVNULL,
3333
stderr=subprocess.DEVNULL,
3434
encoding="utf-8",
35-
errors="ignore")
35+
errors="ignore") # type: ignore
3636

3737
if not res:
3838
return True
@@ -74,4 +74,4 @@ def check_ldlogger(env) -> bool:
7474
alternative_logger_lib_dir_path = os.path.join(
7575
lib_dir_path, 'codechecker_analyzer', 'ld_logger', 'lib', '**',
7676
'ldlogger.so')
77-
return glob.glob(alternative_logger_lib_dir_path, recursive=True)
77+
return bool(glob.glob(alternative_logger_lib_dir_path, recursive=True))

analyzer/codechecker_analyzer/buildlog/log_parser.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import sys
2323
import tempfile
2424
import traceback
25-
from typing import Dict, List, Optional
25+
from typing import Dict, List, Optional, Any
2626

2727
from codechecker_analyzer.analyzers.clangsa.analyzer import ClangSA
2828

@@ -49,7 +49,7 @@
4949
# The compilation flags of which the prefix is any of these regular expressions
5050
# will not be included in the output Clang command.
5151
# These flags should be ignored only in case the original compiler is clang.
52-
IGNORED_OPTIONS_CLANG = [
52+
IGNORED_OPTIONS_LIST_CLANG = [
5353
# Clang gives different warnings than GCC. Thus if these flags are kept,
5454
# '-Werror', '-pedantic-errors' the analysis with Clang can fail even
5555
# if the compilation passes with GCC.
@@ -66,7 +66,7 @@
6666
# The compilation flags of which the prefix is any of these regular expressions
6767
# will not be included in the output Clang command.
6868
# These flags should be ignored only in case the original compiler is gcc.
69-
IGNORED_OPTIONS_GCC = [
69+
IGNORED_OPTIONS_LIST_GCC = [
7070
# --- UNKNOWN BY CLANG --- #
7171
'-fallow-fetchr-insn',
7272
'-fcall-saved-',
@@ -191,8 +191,8 @@
191191
'-mabi'
192192
]
193193

194-
IGNORED_OPTIONS_GCC = re.compile('|'.join(IGNORED_OPTIONS_GCC))
195-
IGNORED_OPTIONS_CLANG = re.compile('|'.join(IGNORED_OPTIONS_CLANG))
194+
IGNORED_OPTIONS_GCC = re.compile('|'.join(IGNORED_OPTIONS_LIST_GCC))
195+
IGNORED_OPTIONS_CLANG = re.compile('|'.join(IGNORED_OPTIONS_LIST_CLANG))
196196

197197
# The compilation flags of which the prefix is any of these regular expressions
198198
# will not be included in the output Clang command. These flags have further
@@ -218,7 +218,7 @@
218218
}
219219

220220

221-
COMPILE_OPTIONS = [
221+
COMPILE_OPTIONS_LIST = [
222222
'-nostdinc',
223223
r'-nostdinc\+\+',
224224
'-pedantic',
@@ -235,9 +235,9 @@
235235
'-pthread'
236236
]
237237

238-
COMPILE_OPTIONS = re.compile('|'.join(COMPILE_OPTIONS))
238+
COMPILE_OPTIONS = re.compile('|'.join(COMPILE_OPTIONS_LIST))
239239

240-
COMPILE_OPTIONS_MERGED = [
240+
COMPILE_OPTIONS_LIST_MERGED = [
241241
'--sysroot',
242242
'-sdkroot',
243243
'--include',
@@ -253,7 +253,7 @@
253253
'-iwithprefixbefore'
254254
]
255255

256-
INCLUDE_OPTIONS_MERGED = [
256+
INCLUDE_OPTIONS_LIST_MERGED = [
257257
'-iquote',
258258
'-[IF]',
259259
'-isystem',
@@ -271,10 +271,10 @@
271271
'-rewrite-objc']
272272

273273
COMPILE_OPTIONS_MERGED = \
274-
re.compile('(' + '|'.join(COMPILE_OPTIONS_MERGED) + ')')
274+
re.compile('(' + '|'.join(COMPILE_OPTIONS_LIST_MERGED) + ')')
275275

276276
INCLUDE_OPTIONS_MERGED = \
277-
re.compile('(' + '|'.join(INCLUDE_OPTIONS_MERGED) + ')')
277+
re.compile('(' + '|'.join(INCLUDE_OPTIONS_LIST_MERGED) + ')')
278278

279279

280280
PRECOMPILATION_OPTION = re.compile('-(E|M[G|T|Q|F|J|P|V|M]*)$')
@@ -344,14 +344,14 @@ def __hash__(self):
344344
(self.compiler, self.language, tuple(self.compiler_flags)))
345345

346346
compiler_info: Dict[ImplicitInfoSpecifierKey, dict] = {}
347-
compiler_isexecutable = {}
347+
compiler_isexecutable: Dict[str, bool] = {}
348348
# Store the already detected compiler version information.
349349
# If the value is False the compiler is not clang otherwise the value
350350
# should be a clang version information object.
351-
compiler_versions = {}
351+
compiler_versions: Dict[str, Any] = {}
352352

353353
@staticmethod
354-
def is_executable_compiler(compiler):
354+
def is_executable_compiler(compiler: str):
355355
if compiler not in ImplicitCompilerInfo.compiler_isexecutable:
356356
ImplicitCompilerInfo.compiler_isexecutable[compiler] = \
357357
which(compiler) is not None
@@ -405,7 +405,7 @@ def __parse_compiler_includes(compile_cmd: List[str]):
405405
start_mark = "#include <...> search starts here:"
406406
end_mark = "End of search list."
407407

408-
include_paths = []
408+
include_paths: List[str] = []
409409
lines = ImplicitCompilerInfo.__get_compiler_err(compile_cmd)
410410

411411
if not lines:
@@ -571,7 +571,7 @@ def load_compiler_info(file_path: str):
571571
for k, v in contents.items():
572572
k = json.loads(k)
573573
ICI.compiler_info[
574-
ICI.ImplicitInfoSpecifierKey(k[0], k[1], tuple(k[2]))] = v
574+
ICI.ImplicitInfoSpecifierKey(k[0], k[1], list(k[2]))] = v
575575

576576
@staticmethod
577577
def set(details, compiler_info_file=None):
@@ -739,7 +739,7 @@ def __get_installed_dir(clang_binary) -> Optional[str]:
739739
if 'clang' not in clang_path.name:
740740
return None
741741

742-
return clang_path.parent
742+
return str(clang_path.parent) if clang_path.parent else None
743743

744744

745745
def __collect_clang_compile_opts(flag_iterator, details):

analyzer/codechecker_analyzer/cli/checkers.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import os
1616
import sys
1717
from collections import defaultdict
18-
from typing import Dict, Iterable, List, Tuple
18+
from typing import Dict, Iterable, List, Tuple, Union
1919

2020
from codechecker_report_converter import twodim
2121

@@ -280,7 +280,7 @@ def __print_profiles(args: argparse.Namespace, cl: CheckerLabels):
280280

281281
if 'details' in args:
282282
header = ['Profile name', 'Description']
283-
rows = cl.get_description('profile').items()
283+
rows: List[Tuple] = list(cl.get_description('profile').items())
284284
else:
285285
header = ['Profile name']
286286
rows = [(key,) for key in cl.get_description('profile')]
@@ -301,7 +301,7 @@ def __print_severities(args: argparse.Namespace, cl: CheckerLabels):
301301

302302
if 'details' in args:
303303
header = ['Severity', 'Description']
304-
rows = cl.get_description('severity').items()
304+
rows: List[Tuple] = list(cl.get_description('severity').items())
305305
else:
306306
header = ['Severity']
307307
rows = [(key,) for key in cl.get_description('severity')]
@@ -330,7 +330,7 @@ def __print_guidelines(args: argparse.Namespace, cl: CheckerLabels):
330330
header = list(map(__uglify, header))
331331

332332
if args.output_format == 'json':
333-
rows = [(g, sorted(list(r))) for g, r in result.items()]
333+
rows: List[Tuple] = [(g, sorted(list(r))) for g, r in result.items()]
334334
else:
335335
rows = [(g, ', '.join(sorted(r))) for g, r in result.items()]
336336

@@ -475,7 +475,7 @@ def __print_checkers(args: argparse.Namespace, cl: CheckerLabels):
475475

476476
checker_info = __get_detailed_checker_info(args, cl)
477477

478-
result = []
478+
result: List[Tuple] = []
479479
for analyzer in args.analyzers:
480480
if labels:
481481
checkers = cl.checkers_by_labels(labels, analyzer)
@@ -501,7 +501,7 @@ def __print_checkers(args: argparse.Namespace, cl: CheckerLabels):
501501

502502
if 'details' in args:
503503
header = ['Status', 'Name', 'Analyzer', 'Description', 'Labels']
504-
rows = list(map(__format_row, result))
504+
rows: Union[List[List], List[Tuple]] = list(map(__format_row, result))
505505
else:
506506
header = ['Name']
507507
rows = [[r[1]] for r in result]
@@ -535,7 +535,7 @@ def __print_checker_config(args: argparse.Namespace):
535535
if args.output_format in ['csv', 'json']:
536536
header = list(map(__uglify, header))
537537

538-
rows = []
538+
rows: List[Tuple] = []
539539
analyzer_failures = []
540540
for analyzer in working_analyzers:
541541
analyzer_class = analyzer_types.supported_analyzers[analyzer]

analyzer/codechecker_analyzer/cli/parse.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import argparse
1515
import os
1616
import sys
17-
from typing import Dict, Optional, Set, List
17+
from typing import Dict, Optional, Set, List, Any
1818
import json
1919
import fnmatch
2020

@@ -285,7 +285,11 @@ def get_report_dir_status(compile_commands: List[dict[str, str]],
285285
report_dir: str,
286286
detailed_flag: bool):
287287

288-
recent, old, failed, missing, analyzed_actions = {}, {}, {}, {}, {}
288+
recent: Dict[str, Dict[str, int]] = {}
289+
old: Dict[str, Dict[str, int]] = {}
290+
failed: Dict[str, Dict[str, int]] = {}
291+
missing: Dict[str, Dict[str, int]] = {}
292+
analyzed_actions: Dict[str, int] = {}
289293

290294
for analyzer in supported_analyzers:
291295
recent[analyzer] = {}
@@ -331,7 +335,7 @@ def get_report_dir_status(compile_commands: List[dict[str, str]],
331335
"failed": failed
332336
}
333337

334-
out_analyzers = {}
338+
out_analyzers: Dict[str, Any] = {}
335339
for analyzer in supported_analyzers:
336340
detailed, summary = {}, {}
337341

0 commit comments

Comments
 (0)