forked from AliceO2Group/O2Physics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patho2_linter.py
More file actions
1812 lines (1555 loc) · 69.9 KB
/
o2_linter.py
File metadata and controls
1812 lines (1555 loc) · 69.9 KB
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
#!/usr/bin/env python3
# Copyright 2019-2020 CERN and copyright holders of ALICE O2.
# See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
# All rights not expressly granted are reserved.
#
# This software is distributed under the terms of the GNU General Public
# License v3 (GPL Version 3), copied verbatim in the file "COPYING".
#
# In applying this license CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization
# or submit itself to any jurisdiction.
"""!
@brief O2 linter (Find O2-specific issues in O2 code)
@author Vít Kučera <vit.kucera@cern.ch>, Inha University
@date 2024-07-14
"""
import argparse
import os
import re
import sys
from enum import Enum
from pathlib import Path
from typing import Union
github_mode = False # GitHub mode
prefix_disable = "o2-linter: disable=" # prefix for disabling tests
file_config = "o2linter_config" # name of the configuration file (applied per directory)
# If this file exists in the path of the tested file,
# failures of tests listed in this file will not make the linter fail.
# issue severity levels
class Severity(Enum):
WARNING = 1
ERROR = 2
DEFAULT = ERROR
# strings for error messages
message_levels = {
Severity.WARNING: "warning",
Severity.ERROR: "error",
}
class Reference(Enum):
O2 = 1
ISO_CPP = 2
LLVM = 3
GOOGLE = 4
LINTER = 5
PWG_HF = 6
PY_ZEN = 7
PY_PEP8 = 8
references_list: "list[tuple[Reference, str, str]]" = [
(Reference.O2, "ALICE O2 Coding Guidelines", "https://github.com/AliceO2Group/CodingGuidelines"),
(Reference.ISO_CPP, "C++ Core Guidelines", "https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines"),
(Reference.LLVM, "LLVM Coding Standards", "https://llvm.org/docs/CodingStandards.html"),
(Reference.GOOGLE, "Google C++ Style Guide", "https://google.github.io/styleguide/cppguide.html"),
(
Reference.LINTER,
"Proposal of the O2 linter",
"https://indico.cern.ch/event/1482467/#29-development-of-the-o2-linte",
),
(
Reference.PWG_HF,
"PWG-HF guidelines",
"https://aliceo2group.github.io/analysis-framework/docs/advanced-specifics/pwghf.html#contribute",
),
(Reference.PY_ZEN, "The Zen of Python", "https://peps.python.org/pep-0020/"),
(Reference.PY_PEP8, "Style Guide for Python Code", "https://peps.python.org/pep-0008/"),
]
references: "dict[Reference, dict]" = {name: {"title": title, "url": url} for name, title, url in references_list}
def is_camel_case(name: str) -> bool:
"""forExample or ForExample"""
return "_" not in name and "-" not in name and " " not in name
def is_upper_camel_case(name: str) -> bool:
"""ForExample"""
if not name:
return False
return name[0].isupper() and is_camel_case(name)
def is_lower_camel_case(name: str) -> bool:
"""forExample"""
if not name:
return False
return name[0].islower() and is_camel_case(name)
def is_kebab_case(name: str) -> bool:
"""for-example"""
if not name:
return False
return name.islower() and "_" not in name and " " not in name
def is_snake_case(name: str) -> bool:
"""for_example"""
if not name:
return False
return name.islower() and "-" not in name and " " not in name
def is_screaming_snake_case(name: str) -> bool:
"""FOR_EXAMPLE"""
if not name:
return False
return name.isupper() and "-" not in name and " " not in name
def kebab_case_to_camel_case_u(line: str) -> str:
"""Convert kebab-case string to UpperCamelCase string."""
return "".join([w.title() if w[0].isnumeric() else w.capitalize() for w in line.split("-")])
def kebab_case_to_camel_case_l(line: str) -> str:
"""Convert kebab-case string to lowerCamelCase string."""
new_line = kebab_case_to_camel_case_u(line)
return f"{new_line[0].lower()}{new_line[1:]}" # start with lowercase letter
def camel_case_to_kebab_case(line: str) -> str:
"""Convert CamelCase string to kebab-case string.
As done in O2/Framework/Foundation/include/Framework/TypeIdHelpers.h:type_to_task_name
"""
if not line.strip():
return line
new_line = []
for i, c in enumerate(line):
if i > 0 and c.isupper() and line[i - 1] != "-":
new_line.append("-")
new_line.append(c.lower())
return "".join(new_line)
def is_comment_cpp(line: str) -> bool:
"""Test whether a line is a C++ comment."""
return line.strip().startswith(("//", "/*"))
def remove_comment_cpp(line: str) -> str:
"""Remove C++ comments from the end of a line."""
for keyword in ("//", "/*"):
if keyword in line:
line = line[: line.index(keyword)]
return line.strip()
def block_ranges(line: str, char_open: str, char_close: str) -> "list[list[int]]":
"""Get list of index ranges of longest blocks opened with char_open and closed with char_close."""
# print(f"Looking for {char_open}{char_close} blocks in \"{line}\".")
# print(line)
list_ranges: list[list[int]] = []
if not all((line, len(char_open) == 1, len(char_close) == 1)):
return list_ranges
def direction(char: str) -> int:
if char == char_open:
return 1
if char == char_close:
return -1
return 0
list_levels = [] # list of block levels (net number of opened blocks)
level_sum = 0 # current block level (sum of previous directions)
for char in line:
list_levels.append(level_sum := level_sum + direction(char))
level_min = min(list_levels) # minimum level (!= 0 if line has opened blocks)
# Look for openings (level_min + 1) and closings (level_min).
index_start = -1
is_opened = False
# print(list_levels)
for i, level in enumerate(list_levels):
if not is_opened and level > level_min:
is_opened = True
index_start = i
# print(f"Opening at {i}")
elif is_opened and (level == level_min or i == len(list_levels) - 1):
is_opened = False
list_ranges.append([index_start, i])
# print(f"Closing at {i}")
# print(f"block_ranges: Found {len(list_ranges)} blocks: {list_ranges}.")
if is_opened:
print("block_ranges: Block left opened.")
return list_ranges
def get_tolerated_tests(path: str) -> "list[str]":
"""Get the list of tolerated tests.
Looks for the configuration file.
Starts in the test file directory and iterates through parents.
"""
tests: list[str] = []
for directory in Path(path).resolve().parents:
path_tests = directory / file_config
if path_tests.is_file():
with path_tests.open() as content:
tests = [line.strip() for line in content.readlines() if line.strip()]
print(f"{path}:1: info: Tolerating tests from {path_tests}. {tests}")
break
return tests
class TestSpec:
"""Prototype of a test class"""
name: str = "test-template" # short name of the test
message: str = "Test failed" # error message
rationale: str = "Rationale missing" # brief rationale explanation
references: "list[Reference]" = [] # list of references relevant for this rule
severity_default: Severity = Severity.DEFAULT
severity_current: Severity = Severity.DEFAULT
suffixes: "list[str]" = [] # suffixes of files to test
per_line: bool = True # Test lines separately one by one.
tolerated: bool = False # flag for tolerating issues
n_issues: int = 0 # issue counter
n_disabled: int = 0 # counter of disabled issues
n_tolerated: int = 0 # counter of tolerated issues
def file_matches(self, path: str) -> bool:
"""Test whether the path matches the pattern for files to test."""
return path.endswith(tuple(self.suffixes)) if self.suffixes else True
def is_disabled(self, line: str, prefix_comment="//") -> bool:
"""Detect whether the test is explicitly disabled."""
for prefix in [prefix_comment, prefix_disable]:
if prefix not in line:
return False
line = line[(line.index(prefix) + len(prefix)) :] # Strip away part before prefix.
if self.name in line:
self.n_disabled += 1
# Look for a comment with a reason for disabling.
if re.search(r" \([\w\s]{3,}\)", line):
return True
return False
def print_error(self, path: str, line: Union[int, None], message: str):
"""Format and print error message."""
# return # Use to suppress error messages.
line = line or 1
# terminal format
print(f"{path}:{line}: {message_levels[self.severity_current]}: {message} [{self.name}]")
if github_mode and not self.tolerated: # Annotate only not tolerated issues.
# GitHub annotation format
print(f"::{message_levels[self.severity_current]} file={path},line={line},title=[{self.name}]::{message}")
def test_line(self, line: str) -> bool:
"""Test a line."""
raise NotImplementedError()
def test_file(self, path: str, content) -> bool:
"""Test a file in a way that cannot be done line by line."""
raise NotImplementedError()
def run(self, path: str, content: "list[str]") -> bool:
"""Run the test."""
# print(content)
passed = True
self.severity_current = Severity.WARNING if self.tolerated else self.severity_default
if not self.file_matches(path):
return passed
# print(f"Running test {self.name} for {path} with {len(content)} lines")
if self.per_line:
for i, line in enumerate(content):
if not isinstance(self, TestUsingDirective): # Keep the indentation if needed.
line = line.strip()
if not line:
continue
# print(i + 1, line)
if self.is_disabled(line):
continue
if not self.test_line(line):
passed = False
if self.tolerated:
self.n_tolerated += 1
else:
self.n_issues += 1
self.print_error(path, i + 1, self.message)
else:
passed = self.test_file(path, content)
if not passed:
if self.tolerated:
self.n_tolerated += 1
else:
self.n_issues += 1
self.print_error(path, None, self.message)
return passed or self.tolerated
##########################
# Implementations of tests
##########################
# Bad practice
class TestIoStream(TestSpec):
"""Detect included iostream."""
name = "include-iostream"
message = "Do not include iostream. Use O2 logging instead."
rationale = "Performance. Avoid injection of static constructors. Consistent logging."
references = [Reference.LLVM, Reference.LINTER]
suffixes = [".h", ".cxx"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
return not line.startswith("#include <iostream>")
class TestUsingStd(TestSpec):
"""Detect importing names from the std namespace."""
name = "import-std-name"
message = "Do not import names from the std namespace in headers."
rationale = "Code safety. Avoid namespace pollution with common names."
references = [Reference.LINTER]
suffixes = [".h"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
return not line.startswith("using std::")
class TestUsingDirective(TestSpec):
"""Detect using directives in headers."""
name = "using-directive"
message = "Do not put using directives at global scope in headers."
rationale = "Code safety. Avoid namespace pollution."
references = [Reference.O2, Reference.ISO_CPP, Reference.LLVM, Reference.GOOGLE, Reference.LINTER]
suffixes = [".h"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
return not line.startswith("using namespace")
class TestStdPrefix(TestSpec):
"""Detect missing std:: prefix for common names from the std namespace."""
name = "std-prefix"
message = "Use std:: prefix for names from the std namespace."
rationale = "Code clarity, safety and portability. Avoid ambiguity (e.g. abs)."
references = [Reference.LLVM, Reference.LINTER]
suffixes = [".h", ".cxx", ".C"]
prefix_bad = r"[^\w:\.\"]"
patterns = [
r"vector<",
r"array[<\{\(]",
r"f?abs\(",
r"sqrt\(",
r"pow\(",
r"min\(",
r"max\(",
r"log(2|10)?\(",
r"exp\(",
r"a?(sin|cos|tan)h?\(",
r"atan2\(",
r"erfc?\(",
r"hypot\(",
]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
for pattern in self.patterns:
iterators = re.finditer(rf"{self.prefix_bad}{pattern}", line)
matches = [(it.start(), it.group()) for it in iterators]
if not matches:
continue
if '"' not in line: # Found a match which cannot be inside a string.
return False
# Ignore matches inside strings.
for match in matches:
n_quotes_before = line.count('"', 0, match[0]) # Count quotation marks before the match.
if not n_quotes_before % 2: # If even, we are not inside a string and this match is valid.
return False
return True
class TestRootEntity(TestSpec):
"""Detect unnecessary use of ROOT entities."""
name = "root/entity"
message = "Replace ROOT entities with equivalents from standard C++ or from O2."
rationale = "Code simplicity and maintainability. O2 is not a ROOT code."
references = [Reference.ISO_CPP, Reference.LINTER, Reference.PY_ZEN]
suffixes = [".h", ".cxx"]
def file_matches(self, path: str) -> bool:
return super().file_matches(path) and "Macros/" not in path
def test_line(self, line: str) -> bool:
pattern = (
r"TMath::(Abs|Sqrt|Power|Min|Max|Log(2|10)?|Exp|A?(Sin|Cos|Tan)H?|ATan2|Erfc?|Hypot)\(|"
r"(U?(Int|Char|Short)|Double(32)?|Float(16)?|U?Long(64)?|Bool)_t"
)
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
return re.search(pattern, line) is None
class TestRootLorentzVector(TestSpec):
"""Detect use of TLorentzVector."""
name = "root/lorentz-vector"
message = (
"Do not use the TLorentzVector legacy class. "
"Use std::array with RecoDecay methods or the ROOT::Math::LorentzVector template instead."
)
rationale = "Performance. Use up-to-date tools."
references = []
suffixes = [".h", ".cxx"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
return "TLorentzVector" not in line
class TestPi(TestSpec):
"""Detect use of external pi."""
name = "external-pi"
message = "Use the PI constant (and its multiples and fractions) defined in o2::constants::math."
rationale = "Code maintainability."
references = [Reference.LINTER, Reference.PY_ZEN]
suffixes = [".h", ".cxx"]
def file_matches(self, path: str) -> bool:
return super().file_matches(path) and "Macros/" not in path
def test_line(self, line: str) -> bool:
pattern = r"[^\w]M_PI|TMath::(Two)?Pi"
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
return re.search(pattern, line) is None
class TestTwoPiAddSubtract(TestSpec):
"""Detect adding/subtracting of 2 pi."""
name = "two-pi-add-subtract"
message = "Use RecoDecay::constrainAngle to restrict angle to a given range."
rationale = "Code maintainability and safety. Use existing tools."
references = [Reference.ISO_CPP, Reference.LINTER, Reference.PY_ZEN]
suffixes = [".h", ".cxx"]
def test_line(self, line: str) -> bool:
pattern_two_pi = (
r"(2(\.0*f?)? \* (M_PI|TMath::Pi\(\)|(((o2::)?constants::)?math::)?PI)|"
r"(((o2::)?constants::)?math::)?TwoPI|TMath::TwoPi\(\))"
)
pattern = rf"[\+-]=? {pattern_two_pi}"
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
return re.search(pattern, line) is None
class TestPiMultipleFraction(TestSpec):
"""Detect multiples/fractions of pi for existing equivalent constants."""
name = "pi-multiple-fraction"
message = "Use multiples/fractions of PI defined in o2::constants::math."
rationale = "Code maintainability."
references = [Reference.LINTER, Reference.PY_ZEN]
suffixes = [".h", ".cxx"]
def test_line(self, line: str) -> bool:
pattern_pi = r"(M_PI|TMath::(Two)?Pi\(\)|(((o2::)?constants::)?math::)?(Two)?PI)"
pattern_multiple = r"(2(\.0*f?)?|0\.2?5f?) \* " # * 2, 0.25, 0.5
pattern_fraction = r" / ((2|3|4)([ ,;\)]|\.0*f?))" # / 2, 3, 4
pattern = rf"{pattern_multiple}{pattern_pi}[^\w]|{pattern_pi}{pattern_fraction}"
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
return re.search(pattern, line) is None
class TestPdgDatabase(TestSpec):
"""Detect use of TDatabasePDG."""
name = "pdg/database"
message = (
"Do not use TDatabasePDG directly. "
"Use o2::constants::physics::Mass... or Service<o2::framework::O2DatabasePDG> instead."
)
rationale = "Performance."
references = [Reference.LINTER]
suffixes = [".h", ".cxx"]
def file_matches(self, path: str) -> bool:
return super().file_matches(path) and "Macros/" not in path
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
return "TDatabasePDG" not in line
class TestPdgExplicitCode(TestSpec):
"""Detect hard-coded PDG codes."""
name = "pdg/explicit-code"
message = "Avoid hard-coded PDG codes. Use named values from PDG_t or o2::constants::physics::Pdg instead."
rationale = "Code comprehensibility, readability, maintainability and safety."
references = [Reference.O2, Reference.ISO_CPP, Reference.LINTER]
suffixes = [".h", ".cxx", ".C"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
if re.search(r"->(GetParticle|Mass)\([+-]?[0-9]+\)", line):
return False
match = re.search(r"[Pp][Dd][Gg].* !?={1,2} [+-]?([0-9]+)", line)
if match:
code = match.group(1)
if code not in ("0", "1", "999"):
return False
return True
class TestPdgExplicitMass(TestSpec):
"""Detect hard-coded particle masses."""
name = "pdg/explicit-mass"
message = "Avoid hard-coded particle masses. Use o2::constants::physics::Mass... instead."
rationale = "Code comprehensibility, readability, maintainability and safety."
references = [Reference.O2, Reference.ISO_CPP, Reference.LINTER]
suffixes = [".h", ".cxx"]
masses: "list[str]" = [] # list of mass values to detect
def __init__(self) -> None:
super().__init__()
# List of masses of commonly used particles
self.masses.append(r"0\.000511") # e
self.masses.append(r"0\.105") # μ
self.masses.append(r"0\.139") # π+
self.masses.append(r"0\.493") # K+
self.masses.append(r"0\.497") # K0
self.masses.append(r"0\.938") # p
self.masses.append(r"0\.939") # n
self.masses.append(r"1\.115") # Λ
self.masses.append(r"1\.864") # D0
self.masses.append(r"2\.286") # Λc
self.masses.append(r"3\.096") # J/ψ
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
iterators = re.finditer(rf"(^|\D)({'|'.join(self.masses)})", line)
matches = [(it.start(), it.group(2)) for it in iterators]
if not matches:
return True
if '"' not in line: # Found a match which cannot be inside a string.
return False
# Ignore matches inside strings.
for match in matches:
n_quotes_before = line.count('"', 0, match[0]) # Count quotation marks before the match.
if not n_quotes_before % 2: # If even, we are not inside a string and this match is valid.
return False
return True
class TestPdgKnownMass(TestSpec):
"""Detect unnecessary call of Mass() for a known PDG code."""
name = "pdg/known-mass"
message = "Use o2::constants::physics::Mass... instead of calling a database method for a known PDG code."
rationale = "Performance."
references = [Reference.LINTER]
suffixes = [".h", ".cxx", ".C"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
pattern_pdg_code = r"[+-]?(k[A-Z][a-zA-Z0-9]*|[0-9]+)"
if re.search(rf"->GetParticle\({pattern_pdg_code}\)->Mass\(\)", line):
return False
return not re.search(rf"->Mass\({pattern_pdg_code}\)", line)
class TestLogging(TestSpec):
"""Detect non-O2 logging."""
name = "logging"
message = "Use O2 logging (LOG, LOGF, LOGP)."
rationale = "Logs easy to read and process."
references = [Reference.LINTER]
suffixes = [".h", ".cxx"]
def file_matches(self, path: str) -> bool:
return super().file_matches(path) and "Macros/" not in path
def test_line(self, line: str) -> bool:
pattern = r"^([Pp]rintf\(|(std::)?cout <)"
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
return re.search(pattern, line) is None
class TestConstRefInForLoop(TestSpec):
"""Test const refs in range-based for loops."""
name = "const-ref-in-for-loop"
message = "Use constant references for non-modified iterators in range-based for loops."
rationale = "Performance, code comprehensibility and safety."
references = [Reference.O2, Reference.ISO_CPP, Reference.LLVM]
suffixes = [".h", ".cxx", ".C"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
if not re.match(r"for \(.* :", line):
return True
line = line[: line.index(" :")] # keep only the iterator part
return re.search(r"(\w const|const \w+)& ", line) is not None
class TestConstRefInSubscription(TestSpec):
"""Test const refs in process function subscriptions.
Test only top-level process functions (called process() or has PROCESS_SWITCH).
"""
name = "const-ref-in-process"
message = "Use constant references for table subscriptions in process functions."
rationale = "Performance, code comprehensibility and safety."
references = [Reference.O2, Reference.ISO_CPP, Reference.LINTER]
suffixes = [".cxx"]
per_line = False
def test_file(self, path: str, content) -> bool:
passed = True
n_parens_opened = 0 # number of opened parentheses
arguments = "" # process function arguments
line_process = 0 # line number of the process function
# Find names of all top-level process functions.
names_functions = ["process"] # names of allowed process functions to test
for i, line in enumerate(content):
line = line.strip()
if is_comment_cpp(line):
continue
if not line.startswith("PROCESS_SWITCH"):
continue
words = line.split()
if len(words) < 2:
passed = False
self.print_error(
path,
i + 1,
"Failed to get the process function name. Keep it on the same line as the switch.",
)
continue
names_functions.append(words[1][:-1]) # Remove the trailing comma.
# self.print_error(path, i + 1, f"Got process function name {words[1][:-1]}.")
# Test process functions.
for i, line in enumerate(content):
line = line.strip()
if is_comment_cpp(line):
continue
if self.is_disabled(line):
continue
if "//" in line: # Remove comment. (Ignore /* to avoid truncating at /*parameter*/.)
line = line[: line.index("//")]
if (match := re.match(r"void (process[\w]*)\(", line)) and match.group(1) in names_functions:
line_process = i + 1
i_closing = line.rfind(")")
i_start = line.index("(") + 1
i_end = i_closing if i_closing != -1 else len(line)
arguments = line[i_start:i_end] # get arguments between parentheses
n_parens_opened = line.count("(") - line.count(")")
elif n_parens_opened > 0:
i_closing = line.rfind(")")
i_start = 0
i_end = i_closing if i_closing != -1 else len(line)
arguments += " " + line[i_start:i_end] # get arguments between parentheses
n_parens_opened += line.count("(") - line.count(")")
if line_process > 0 and n_parens_opened == 0:
# Process arguments.
# Sanitise arguments with spaces between <>.
for start, end in block_ranges(arguments, "<", ">"):
arg = arguments[start : (end + 1)]
# print(f"Found argument \"{arg}\" in [{start}, {end}]")
if ", " in arg:
arguments = arguments.replace(arg, arg.replace(", ", "__"))
# Extract arguments.
words = arguments.split(", ")
# Test each argument.
for arg in words:
if not re.search(r"([\w>] const|const [\w<>:]+)&", arg):
passed = False
self.print_error(path, i + 1, f"Argument {arg} is not const&.")
line_process = 0
return passed
class TestWorkflowOptions(TestSpec):
"""Detect usage of workflow options in defineDataProcessing. (Not supported on AliHyperloop.)"""
name = "o2-workflow-options"
message = (
"Do not use workflow options to customise workflow topology composition in defineDataProcessing. "
"Use process function switches or metadata instead."
)
rationale = "Not supported on AliHyperloop."
references = [Reference.LINTER]
suffixes = [".cxx"]
per_line = False
def test_file(self, path: str, content) -> bool:
is_inside_define = False # Are we inside defineDataProcessing?
for _i, line in enumerate(content): # pylint: disable=unused-variable
if not line.strip():
continue
if self.is_disabled(line):
continue
if is_comment_cpp(line):
continue
line = remove_comment_cpp(line)
# Wait for defineDataProcessing.
if not is_inside_define:
if not re.match(r"((o2::)?framework::)?WorkflowSpec defineDataProcessing\(", line):
continue
# print(f"{i + 1}: Entering define.")
is_inside_define = True
# Return at the end of defineDataProcessing.
if is_inside_define and line[0] == "}":
# print(f"{i + 1}: Exiting define.")
break
# Detect options.
if ".options()" in line:
return False
return True
class TestMagicNumber(TestSpec):
"""Detect magic numbers."""
name = "magic-number"
message = "Avoid magic numbers in expressions. Assign the value to a clearly named variable or constant."
rationale = "Code comprehensibility, maintainability and safety."
references = [Reference.O2, Reference.ISO_CPP]
suffixes = [".h", ".cxx", ".C"]
pattern_compare = r"([<>]=?|[!=]=)"
pattern_number = r"[\+-]?([\d\.]+)f?"
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
iterators = re.finditer(
rf" {self.pattern_compare} {self.pattern_number}|\W{self.pattern_number} {self.pattern_compare} ", line
)
matches = [(it.start(), it.group(2), it.group(3)) for it in iterators]
if not matches:
return True
# Ignore matches inside strings.
for match in matches:
n_quotes_before = line.count('"', 0, match[0]) # Count quotation marks before the match.
if n_quotes_before % 2: # If odd, we are inside a string and we should ignore this match.
continue
# We are not inside a string and this match is valid.
for match_n in (match[1], match[2]):
# Accept only 0 or 1 (int or float).
if (match_n is not None) and (re.match(r"[01](\.0?)?$", match_n) is None):
return False
return True
# Documentation
# Reference: https://rawgit.com/AliceO2Group/CodingGuidelines/master/comments_guidelines.html
class TestDocumentationFile(TestSpec):
"""Test mandatory documentation of C++ files."""
name = "doc/file"
message = "Provide mandatory file documentation."
rationale = "Code comprehensibility. Collaboration."
references = [Reference.O2, Reference.LINTER]
suffixes = [".h", ".cxx", ".C"]
per_line = False
def test_file(self, path: str, content) -> bool:
passed = False
doc_items = []
doc_items.append({"keyword": "file", "pattern": rf"{os.path.basename(path)}$", "found": False})
doc_items.append({"keyword": "brief", "pattern": r"\w.* \w", "found": False}) # at least two words
doc_items.append({"keyword": "author", "pattern": r"[\w]+", "found": False})
doc_prefix = "///"
n_lines_copyright = 11
last_doc_line = n_lines_copyright
for i, line in enumerate(content):
if i < n_lines_copyright: # Skip copyright lines.
continue
if line.strip() and not line.startswith(doc_prefix): # Stop at the first non-empty non-doc line.
break
if line.startswith(doc_prefix):
last_doc_line = i + 1
for item in doc_items:
if re.search(rf"^{doc_prefix} [\\@]{item['keyword']} +{item['pattern']}", line):
item["found"] = True
# self.print_error(path, i + 1, f"Found \{item['keyword']}.")
break
if all(item["found"] for item in doc_items): # All items have been found.
passed = True
break
if not passed:
for item in doc_items:
if not item["found"]:
self.print_error(
path,
last_doc_line,
f"Documentation for \\{item['keyword']} is missing, incorrect or misplaced.",
)
return passed
# Naming conventions
# Reference: https://rawgit.com/AliceO2Group/CodingGuidelines/master/naming_formatting.html
rationale_names = "Code readability, comprehensibility and searchability."
references_names = [Reference.O2, Reference.LINTER]
class TestNameFunctionVariable(TestSpec):
"""Test names of functions and of most variables.
Might report false positives.
Does not detect multiple variable declarations, i.e. "type name1, name2;"
Does not detect function arguments on the same line as the function declaration.
Does not detect multi-line declarations.
Does not check capitalisation for constexpr because of special rules for constants. See TestNameConstant.
"""
name = "name/function-variable"
message = "Use lowerCamelCase for names of functions and variables."
rationale = rationale_names
references = references_names
suffixes = [".h", ".cxx", ".C"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
# Look for declarations of functions and variables.
# Strip away irrelevant remainders of the line after the object name.
# For functions, stripping after "(" is enough but this way we also identify many declarations of variables.
for keyword in ("(", "{", ";", " = ", "//", "/*"):
if keyword in line:
line = line[: line.index(keyword)]
# Check the words.
words = line.split()
# number of words
if len(words) < 2:
return True
# First word starts with a letter.
if not words[0][0].isalpha():
return True
# Reject false positives with same structure.
if words[0] in (
"return",
"if",
"else",
"new",
"delete",
"delete[]",
"case",
"typename",
"using",
"typedef",
"enum",
"namespace",
"struct",
"class",
"explicit",
"concept",
"throw",
):
return True
if len(words) > 2 and words[1] in ("typename", "class", "struct"):
return True
# Identify the position of the name for cases "name[n + m]".
funval_name = words[-1] # expecting the name in the last word
if (
funval_name.endswith("]") and "[" not in funval_name
): # it's an array and we do not have the name before "[" here
opens_brackets = ["[" in w for w in words]
if not any(opens_brackets): # The opening "[" is not on this line. We have to give up.
return True
index_name = opens_brackets.index(True) # the name is in the first element with "["
funval_name = words[index_name]
words = words[: (index_name + 1)] # Strip away words after the name.
if len(words) < 2: # Check the adjusted number of words.
return True
# All words before the name start with an alphanumeric character (underscores not allowed).
# Rejects expressions, e.g. * = += << }, but accepts numbers in array declarations.
if not all(w[0].isalnum() for w in words[:-1]):
return True
# Extract function/variable name.
if "[" in funval_name: # Remove brackets for arrays.
funval_name = funval_name[: funval_name.index("[")]
if "::" in funval_name: # Remove the class prefix for methods.
funval_name = funval_name.split("::")[-1]
# Check the name candidate.
# Names of variables and functions are identifiers.
if not funval_name.isidentifier(): # should be same as ^[\w]+$
return True
# print(f"{line} -> {funval_name}")
# return True
# The actual test comes here.
if "constexpr" in words[:-1]:
return is_camel_case(funval_name)
return is_lower_camel_case(funval_name)
class TestNameMacro(TestSpec):
"""Test macro names."""
name = "name/macro"
message = "Use SCREAMING_SNAKE_CASE for names of macros. Leading and double underscores are not allowed."
rationale = rationale_names
references = references_names
suffixes = [".h", ".cxx", ".C"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
if not line.startswith("#define "):
return True
# Extract macro name.
macro_name = line.split()[1]
if "(" in macro_name:
macro_name = macro_name.split("(")[0]
# The actual test comes here.
if macro_name.startswith("_"):
return False
if "__" in macro_name:
return False
return is_screaming_snake_case(macro_name)
class TestNameConstant(TestSpec):
"""Test constexpr constant names."""
name = "name/constexpr-constant"
message = (
'Use UpperCamelCase for names of constexpr constants. Names of special constants may be prefixed with "k".'
)
rationale = rationale_names
references = references_names
suffixes = [".h", ".cxx", ".C"]
def test_line(self, line: str) -> bool:
if is_comment_cpp(line):
return True
line = remove_comment_cpp(line)
words = line.split()
if "constexpr" not in words or "=" not in words:
return True
# Extract constant name.
words = words[: words.index("=")] # keep only words before "="