forked from mozilla-mobile/gradle-apilint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apilint.py
2189 lines (1777 loc) · 80.8 KB
/
apilint.py
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 (C) 2014 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Enforces common Android public API design patterns. It ignores lint messages from
a previous API level, if provided.
Usage: apilint.py current.txt
Usage: apilint.py current.txt previous.txt
You can also splice in blame details like this:
$ git blame api/current.txt -t -e > /tmp/currentblame.txt
$ apilint.py /tmp/currentblame.txt previous.txt --no-color
"""
import os, re, sys, collections, traceback, argparse, json
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
ALLOW_GOOGLE = False
USE_COLOR = True
DEPRECATED_ANNOTATION = "java.lang.Deprecated"
DEPRECATION_SCHEDULE_ANNOTATION = None
LIBRARY_VERSION = None
PRIMITIVE_TYPES = ["boolean", "byte", "char", "short", "int", "long", "float",
"double"]
def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False):
# manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes
if not USE_COLOR: return ""
codes = []
if reset: codes.append("0")
else:
if not fg is None: codes.append("3%d" % (fg))
if not bg is None:
if not bright: codes.append("4%d" % (bg))
else: codes.append("10%d" % (bg))
if bold: codes.append("1")
elif dim: codes.append("2")
else: codes.append("22")
return "\033[%sm" % (";".join(codes))
def ident(raw):
"""Strips superficial signature changes, giving us a strong key that
can be used to identify members across API levels."""
raw = raw.replace(" deprecated ", " ")
raw = raw.replace(" synchronized ", " ")
raw = raw.replace(" final ", " ")
raw = re.sub("<.+?>", "", raw)
if " throws " in raw:
raw = raw[:raw.index(" throws ")]
return raw
class Annotation():
def parse_line(self, line):
line = line.strip()
arg_begin = line.find('(')
arg_end = line.find(')')
if arg_begin == -1 or arg_end == -1:
return (line, [])
raw = line[:arg_begin]
arguments = collect_chunks(line[arg_begin+1:arg_end], ",")
return (raw, arguments)
def parse_value(self, value):
# Remove surrounding quotes
if value.startswith('"'):
return value[1:-1]
return value
def parse_arguments(self, arguments):
parsed = {}
for argument in arguments:
equal_sign = argument.find('=')
parsed[argument[:equal_sign]] = self.parse_value(argument[equal_sign+1:])
return parsed
def __init__(self, clazz, source, location, raw, blame, imports):
self.raw = raw[1:]
(raw, arguments) = self.parse_line(raw)
self.clazz = clazz
self.location = location
self.typ = Type(clazz, self, raw[1:], location, blame, imports)
self.blame = blame
self.source = source
self.arguments = self.parse_arguments(arguments)
self.ident = self.typ.name + str(self.arguments)
def __hash__(self):
return hash(self.raw)
def __repr__(self):
return self.raw
class Field():
def __init__(self, clazz, location, raw, blame, imports):
self.clazz = clazz
self.location = location
self.raw = raw.strip(" {;")
self.blame = blame
self.source = None
raw = collect_chunks(raw, "[\s;]")
self.split = list(raw)
for r in ["field", "enum_constant", "volatile", "transient", "public", "protected", "static", "final", "deprecated"]:
while r in raw: raw.remove(r)
self.annotations = [
Annotation(clazz, self, location, a, blame, imports) for a in raw if a.startswith("@")]
raw = [x for x in raw if not x.startswith("@")]
self.typ = Type(clazz, self, raw[0], location, blame, imports)
self.name = raw[1].strip(";")
if len(raw) >= 4 and raw[2] == "=":
self.value = raw[3].strip(';"')
else:
self.value = None
self.ident = "field %s %s = %s;" % (self.typ.ident(), self.name, self.value)
def __hash__(self):
return hash(self.raw)
def __repr__(self):
return self.raw
class Argument():
def __init__(self, clazz, source, raw, location, blame, imports):
raw = collect_chunks(raw, "\s")
self.annotations = [
Annotation(clazz, self, location, a, blame, imports) for a in raw if a.startswith("@")]
raw = [x for x in raw if not x.startswith("@")]
self.typ = Type(clazz, source, " ".join(raw), location, blame, imports)
self.location = location
self.blame = blame
self.clazz = clazz
self.source = source
def __repr__(self):
return (" ".join("@" + repr(x) for x in self.annotations) + " " + repr(self.typ)).strip()
def collect_chunks(line, separator, separator_len=1):
chunks = []
unparsed = line.strip()
while unparsed != "":
chunk, unparsed = find_next_chunk(unparsed, separator, separator_len)
unparsed = unparsed.strip()
chunks.append(chunk.strip())
return chunks
# Finds the next chunk in line, considers everything between '<' and '>', '('
# and ')' to be part of the same chunk, so e.g. "TestClass<A extends B>" or
# "function(int a)" is considered one chunk
def find_next_chunk(unparsed, separator, separator_len=1):
caret = 0
parens = 0
for i in range(1, len(unparsed) + 1):
if unparsed[i-1] == '<':
caret += 1
elif unparsed[i-1] == '>':
caret -= 1
elif unparsed[i-1] == '(':
parens += 1
elif unparsed[i-1] == ')':
parens -= 1
elif (i >= separator_len and
re.match(separator, unparsed[i-separator_len:i]) and
caret == 0 and parens == 0):
return (unparsed[0:i-separator_len], unparsed[i:].strip())
# only one chunk
return (unparsed, "")
class Method():
def arguments(self, raw):
line = " ".join(raw)
arg_begin = line.find('(')
arg_end = line.find(')')
arguments = collect_chunks(line[arg_begin+1:arg_end], ",")
return arguments
def __init__(self, clazz, location, raw, blame, imports):
self.clazz = clazz
self.location = location
self.raw = raw.strip(" {;")
self.blame = blame
self.source = None
raw = collect_chunks(raw, "\s")
for r in ["", ";"]:
while r in raw: raw.remove(r)
self.split = list(raw)
if raw[0] == "method":
raw = raw[1:]
for r in ["public", "protected", "static", "final", "synchronized", "deprecated", "abstract", "default"]:
while r in raw: raw.remove(r)
self.annotations = [
Annotation(clazz, self, location, a, blame, imports) for a in raw if a.startswith("@")]
raw = [x for x in raw if not x.startswith("@")]
if raw[0].startswith("<"):
self.generics = Type(clazz, self, raw[0], location, blame, imports).generics
raw = raw[1:]
else:
self.generics = []
typ_name = raw[0] if raw[0] != "ctor" else clazz.fullname
self.typ = Type(clazz, self, typ_name, location, blame, imports)
self.name = raw[1]
self.args = []
self.throws = []
#TODO: throws
for r in self.arguments(raw):
self.args.append(Argument(clazz, self, r, location, blame, imports))
self.ident = "method %s %s(%s);" % (self.typ.ident(), self.name,
", ".join(x.typ.ident() for x in self.args))
def __hash__(self):
return hash(self.raw)
def __repr__(self):
return self.raw
class Type():
def __init__(self, clazz, source, raw, location, blame, imports):
self.location = location
self.blame = blame
self.source = source
self.raw = raw
raw = collect_chunks(raw, "extends", len("extends"))
if len(raw) > 1:
extends = collect_chunks(raw[1], "&")
self.extends = [Type(clazz, self, e, location, blame, imports) for e in extends]
else:
self.extends = []
raw = raw[0]
if "<" in raw:
generics_string = raw[raw.find("<")+1:raw.rfind(">")]
self.generics = [Type(clazz, self, x, location, blame, imports)
for x in collect_chunks(generics_string, ",")]
raw = raw[:raw.find("<")]
else:
self.generics = []
self.is_array = False
self.is_var_arg = False
if raw.endswith("[]"):
while raw.endswith("[]"):
raw = raw[:-2]
self.name = self.resolve(raw, imports)
self.is_array = True
elif raw.endswith("..."):
self.name = self.resolve(raw[:-3], imports)
self.is_var_arg = True
else:
self.name = self.resolve(raw, imports)
def resolve(self, name, imports):
# Never resolve primitive types
if name in PRIMITIVE_TYPES:
return name
split = name.split(".")
if split[0] in imports:
resolved = ".".join([imports[split[0]]] + split[1:])
return resolved
return name
def ident(self):
result = self.name
if self.generics:
result += "<" + ", ".join(x.ident() for x in self.generics) + ">"
if self.extends:
result += " extends " + " & ".join(x.ident() for x in self.extends)
return result
def __repr__(self):
return self.ident()
class Location():
def __init__(self, fileName, line, column):
self.fileName = fileName
self.line = line
self.column = column
def __repr__(self):
return os.path.relpath(self.fileName) + ":" + str(self.line) + ":" + str(self.column)
class Class():
def __init__(self, pkg, location, raw, blame, imports):
self.pkg = pkg
self.location = location
self.raw = raw.strip(" {;")
self.blame = blame
self.ctors = []
self.fields = []
self.methods = []
self.source = None
raw = collect_chunks(self.raw, "\s")
self.split = list(raw)
self.isEnum = False
if "class" in raw:
self.fullname = raw[raw.index("class")+1]
elif "interface" in raw:
self.fullname = raw[raw.index("interface")+1]
elif "enum" in raw:
self.fullname = raw[raw.index("enum")+1]
self.isEnum = True
else:
raise ValueError("Funky class type %s" % (self.raw))
if "extends" in raw:
self.extends = Type(self, None, raw[raw.index("extends")+1], location,
blame, imports)
self.extends_path = collect_chunks(self.extends.name, "\.")
else:
self.extends = None
self.extends_path = []
if "implements" in raw:
self.implements = [Type(self, None, r, location, blame, imports) for r in raw[raw.index("implements")+1:]]
else:
self.implements = []
self.annotations = [
Annotation(self, None, location, a, blame, imports) for a in raw if a.startswith("@")]
if "<" in self.fullname:
self.generics = Type(self, None, self.fullname, location, blame,
imports).generics
self.fullname = re.sub("<.+?>", "", self.fullname)
else:
self.generics = []
self.fullname = self.pkg.name + "." + self.fullname
self.fullname_path = self.fullname.split(".")
self.name = self.fullname[self.fullname.rindex(".")+1:]
def __hash__(self):
return hash((self.raw, tuple(self.ctors), tuple(self.fields), tuple(self.methods)))
def __repr__(self):
return self.raw
class Package():
def __init__(self, location, raw, blame):
self.location = location
self.raw = raw.strip(" {;")
self.blame = blame
self.source = None
raw = raw.split()
self.name = raw[raw.index("package")+1]
self.name_path = self.name.split(".")
def __repr__(self):
return self.raw
def _parse_stream(f, api_map, clazz_cb=None):
line = 0
api = {}
pkg = None
clazz = None
blame = None
imports = {}
re_blame = re.compile("^([a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
for raw in f:
line += 1
raw = raw.rstrip()
match = re_blame.match(raw)
if match is not None:
blame = match.groups()[0:2]
raw = match.groups()[2]
else:
blame = None
location = read_map(api_map, line)
if raw.startswith("import"):
imp = raw[raw.index("import")+7:-1]
imports[imp.split(".")[-1]] = imp
elif raw.startswith("package"):
pkg = Package(location, raw, blame)
elif raw.startswith(" ") and raw.endswith("{"):
# When provided with class callback, we treat as incremental
# parse and don't build up entire API
if clazz and clazz_cb:
clazz_cb(clazz)
clazz = Class(pkg, location, raw, blame, imports)
api[clazz.fullname] = clazz
elif raw.startswith(" ctor"):
clazz.ctors.append(Method(clazz, location, raw, blame, imports))
elif raw.startswith(" method"):
clazz.methods.append(Method(clazz, location, raw, blame, imports))
elif raw.startswith(" field"):
clazz.fields.append(Field(clazz, location, raw, blame, imports))
elif raw.startswith(" enum_constant"):
clazz.fields.append(Field(clazz, location, raw, blame, imports))
# Handle last trailing class
if clazz and clazz_cb:
clazz_cb(clazz)
return api
class Failure():
def __init__(self, sig, clazz, detail, error, rule, msg):
self.sig = sig
self.error = error
self.rule = rule
self.msg = msg
self.clazz = clazz
self.detail = detail
if error:
self.head = "Error %s" % (rule) if rule else "Error"
dump = "%s%s:%s %s" % (format(fg=RED, bg=BLACK, bold=True), self.head, format(reset=True), msg)
else:
self.head = "Warning %s" % (rule) if rule else "Warning"
dump = "%s%s:%s %s" % (format(fg=YELLOW, bg=BLACK, bold=True), self.head, format(reset=True), msg)
self.location = clazz.location
blame = clazz.blame
if detail is not None:
self.location = detail.location
blame = detail.blame
while detail is not None:
dump += "\n in " + repr(detail)
detail = detail.source
dump += "\n in " + repr(clazz)
dump += "\n in " + repr(clazz.pkg)
dump += "\n at line " + repr(self.location)
if blame is not None:
dump += "\n last modified by %s in %s" % (blame[1], blame[0])
self.dump = dump
def __repr__(self):
return self.dump
def json(self):
return {
'rule': self.rule,
'msg': self.msg,
'error': self.error,
'detail': repr(self.detail),
'file': self.location.fileName,
'line': int(self.location.line),
'column': int(self.location.column),
'class': repr(self.clazz),
'pkg': repr(self.clazz.pkg),
}
def read_map(api_map, lineNumber):
if api_map is None or (lineNumber - 1) >= len(api_map):
return Location("api.txt", lineNumber, 0)
mapString = api_map[lineNumber-1].strip()
if not mapString:
return Location("api.txt", lineNumber, 0)
[fileName,line,column] = mapString.split(":")
return Location(fileName, line, column)
failures = {}
def _fail(clazz, detail, error, rule, msg):
"""Records an API failure to be processed later."""
global failures
sig = "%s-%s-%s" % (clazz.fullname, repr(detail), msg)
sig = sig.replace(" deprecated ", " ")
failures[sig] = Failure(sig, clazz, detail, error, rule, msg)
def warn(clazz, detail, rule, msg):
_fail(clazz, detail, False, rule, msg)
def error(clazz, detail, rule, msg):
_fail(clazz, detail, True, rule, msg)
noticed = {}
def notice(clazz):
global noticed
noticed[clazz.fullname] = clazz
def verify_constants(clazz):
"""All static final constants must be FOO_NAME style."""
if re.match("android\.R\.[a-z]+", clazz.fullname): return
if clazz.fullname.startswith("android.os.Build"): return
if clazz.fullname == "android.system.OsConstants": return
req = ["java.lang.String","byte","short","int","long","float","double","boolean","char"]
for f in clazz.fields:
if "static" in f.split and "final" in f.split:
if re.match("[A-Z0-9_]+", f.name) is None:
error(clazz, f, "C2", "Constant field names must be FOO_NAME")
if f.typ != "java.lang.String":
if f.name.startswith("MIN_") or f.name.startswith("MAX_"):
warn(clazz, f, "C8", "If min/max could change in future, make them dynamic methods")
if f.typ in req and f.value is None:
error(clazz, f, None, "All constants must be defined at compile time")
def verify_enums(clazz):
"""Enums are bad, mmkay?"""
if "extends java.lang.Enum" in clazz.raw:
error(clazz, None, "F5", "Enums are not allowed")
def verify_class_names(clazz):
"""Try catching malformed class names like myMtp or MTPUser."""
if clazz.fullname.startswith("android.opengl"): return
if clazz.fullname.startswith("android.renderscript"): return
if re.match("android\.R\.[a-z]+", clazz.fullname): return
if re.search("[A-Z]{2,}", clazz.name) is not None:
warn(clazz, None, "S1", "Class names with acronyms should be Mtp not MTP")
if re.match("[^A-Z]", clazz.name):
error(clazz, None, "S1", "Class must start with uppercase char")
if clazz.name.endswith("Impl"):
error(clazz, None, None, "Don't expose your implementation details")
def verify_method_names(clazz):
"""Try catching malformed method names, like Foo() or getMTU()."""
if clazz.fullname.startswith("android.opengl"): return
if clazz.fullname.startswith("android.renderscript"): return
if clazz.fullname == "android.system.OsConstants": return
for m in clazz.methods:
if re.search("[A-Z]{2,}", m.name) is not None:
warn(clazz, m, "S1", "Method names with acronyms should be getMtu() instead of getMTU()")
if re.match("[^a-z]", m.name):
error(clazz, m, "S1", "Method name must start with lowercase char")
def verify_callbacks(clazz):
"""Verify Callback classes.
All callback classes must be abstract.
All methods must follow onFoo() naming style."""
if clazz.fullname == "android.speech.tts.SynthesisCallback": return
if clazz.name.endswith("Callbacks"):
error(clazz, None, "L1", "Callback class names should be singular")
if clazz.name.endswith("Observer"):
warn(clazz, None, "L1", "Class should be named FooCallback")
if clazz.name.endswith("Callback"):
if "interface" in clazz.split:
error(clazz, None, "CL3", "Callbacks must be abstract class to enable extension in future API levels")
for m in clazz.methods:
if not re.match("on[A-Z][a-z]*", m.name):
error(clazz, m, "L1", "Callback method names must be onFoo() style")
def verify_listeners(clazz):
"""Verify Listener classes.
All Listener classes must be interface.
All methods must follow onFoo() naming style.
If only a single method, it must match class name:
interface OnFooListener { void onFoo() }"""
if clazz.name.endswith("Listener"):
if " abstract class " in clazz.raw:
error(clazz, None, "L1", "Listeners should be an interface, or otherwise renamed Callback")
for m in clazz.methods:
if not re.match("on[A-Z][a-z]*", m.name):
error(clazz, m, "L1", "Listener method names must be onFoo() style")
if len(clazz.methods) == 1 and clazz.name.startswith("On"):
m = clazz.methods[0]
if (m.name + "Listener").lower() != clazz.name.lower():
error(clazz, m, "L1", "Single listener method name must match class name")
def verify_actions(clazz):
"""Verify intent actions.
All action names must be named ACTION_FOO.
All action values must be scoped by package and match name:
package android.foo {
String ACTION_BAR = "android.foo.action.BAR";
}"""
for f in clazz.fields:
if f.value is None: continue
if f.name.startswith("EXTRA_"): continue
if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": continue
if "INTERACTION" in f.name: continue
if "static" in f.split and "final" in f.split and f.typ.name == "java.lang.String":
if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
if not f.name.startswith("ACTION_"):
error(clazz, f, "C3", "Intent action constant name must be ACTION_FOO")
else:
if clazz.fullname == "android.content.Intent":
prefix = "android.intent.action"
elif clazz.fullname == "android.provider.Settings":
prefix = "android.settings"
elif clazz.fullname == "android.app.admin.DevicePolicyManager" or clazz.fullname == "android.app.admin.DeviceAdminReceiver":
prefix = "android.app.action"
else:
prefix = clazz.pkg.name + ".action"
expected = prefix + "." + f.name[7:]
if f.value != expected:
error(clazz, f, "C4", "Inconsistent action value; expected '%s'" % (expected))
def verify_extras(clazz):
"""Verify intent extras.
All extra names must be named EXTRA_FOO.
All extra values must be scoped by package and match name:
package android.foo {
String EXTRA_BAR = "android.foo.extra.BAR";
}"""
if clazz.fullname == "android.app.Notification": return
if clazz.fullname == "android.appwidget.AppWidgetManager": return
for f in clazz.fields:
if f.value is None: continue
if f.name.startswith("ACTION_"): continue
if "static" in f.split and "final" in f.split and f.typ.name == "java.lang.String":
if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
if not f.name.startswith("EXTRA_"):
error(clazz, f, "C3", "Intent extra must be EXTRA_FOO")
else:
if clazz.pkg.name == "android.content" and clazz.name == "Intent":
prefix = "android.intent.extra"
elif clazz.pkg.name == "android.app.admin":
prefix = "android.app.extra"
else:
prefix = clazz.pkg.name + ".extra"
expected = prefix + "." + f.name[6:]
if f.value != expected:
error(clazz, f, "C4", "Inconsistent extra value; expected '%s'" % (expected))
def verify_equals(clazz):
"""Verify that equals() and hashCode() must be overridden together."""
eq = False
hc = False
for m in clazz.methods:
if " static " in m.raw: continue
if "boolean equals(java.lang.Object)" in m.raw: eq = True
if "int hashCode()" in m.raw: hc = True
if eq != hc:
error(clazz, None, "M8", "Must override both equals and hashCode; missing one")
def verify_parcelable(clazz):
"""Verify that Parcelable objects aren't hiding required bits."""
if "implements android.os.Parcelable" in clazz.raw:
creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
describe = [ i for i in clazz.methods if i.name == "describeContents" ]
if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
error(clazz, None, "FW3", "Parcelable requires CREATOR, writeToParcel, and describeContents; missing one")
if ((" final class " not in clazz.raw) and
(" final deprecated class " not in clazz.raw)):
error(clazz, None, "FW8", "Parcelable classes must be final")
for c in clazz.ctors:
if len(c.args) == 1 and c.args[0].typ.name == "android.os.Parcel":
error(clazz, c, "FW3", "Parcelable inflation is exposed through CREATOR, not raw constructors")
def verify_protected(clazz):
"""Verify that no protected methods or fields are allowed."""
for m in clazz.methods:
if "protected" in m.split:
error(clazz, m, "M7", "Protected methods not allowed; must be public")
for f in clazz.fields:
if "protected" in f.split:
error(clazz, f, "M7", "Protected fields not allowed; must be public")
def verify_final_fields_only_class(clazz):
if clazz.methods or not clazz.fields:
# Not a final field-only class
return
for f in clazz.fields:
if "final" not in f.split:
# Not a final field-only class
return
if not clazz.ctors:
error(clazz, None, "GV1", "Field-only classes need at least one constructor for mocking.")
if "final" in clazz.split:
error(clazz, None, "GV2", "Field-only classes should not be final for mocking.")
def verify_threading_annotations(clazz):
THREADING_ANNOTATIONS = [
"android.support.annotation.MainThread",
"android.support.annotation.UiThread",
"android.support.annotation.WorkerThread",
"android.support.annotation.BinderThread",
"android.support.annotation.AnyThread",
"androidx.annotation.MainThread",
"androidx.annotation.UiThread",
"androidx.annotation.WorkerThread",
"androidx.annotation.BinderThread",
"androidx.annotation.AnyThread",
]
# If the annotation is on the class than it applies to every method
for a in clazz.annotations:
if a.typ.name in THREADING_ANNOTATIONS:
return []
# Otherwise check all methods
for f in clazz.methods:
has_annotation = False
for a in f.annotations:
if a.typ.name in THREADING_ANNOTATIONS:
has_annotation = True
if not has_annotation:
error(clazz, f, "GV3", "Method missing threading annotation. Needs "
"one of: @MainThread, @UiThread, @WorkerThread, @BinderThread, "
"@AnyThread.")
def verify_nullability_annotations(clazz):
NULLABILITY_ANNOTATIONS = [
"android.support.annotation.NonNull",
"android.support.annotation.Nullable",
"androidx.annotation.NonNull",
"androidx.annotation.Nullable",
]
if clazz.isEnum:
# Enum's have methods which are not under the developer control.
return
def has_nullability_annotation(subject):
# We don't need nullability annotations for primitive types or void
if not subject.typ.is_array and (subject.typ.name == "void" or
subject.typ.name in PRIMITIVE_TYPES):
return True
for a in subject.annotations:
if a.typ.name in NULLABILITY_ANNOTATIONS:
return True
return False
methods = []
for f in clazz.methods:
if not has_nullability_annotation(f):
error(clazz, f, "GV4", "Missing return type nullability "
"annotation. Needs one of @Nullable, @NonNull.")
for a in f.args:
if not has_nullability_annotation(a):
error(clazz, a, "GV5", "Missing argument type nullability "
"annotation. Needs one of @Nullable, @NonNull.")
for f in clazz.fields:
if "final" in f.split and "static" in f.split:
# We don't need nullability annotation if the value can't change
continue
if not has_nullability_annotation(f):
error(clazz, f, "GV4", "Missing field type nullability "
"annotation. Needs one of @Nullable, @NonNull.")
def verify_default_impl(clazz):
if "interface" not in clazz.split:
return
if len(clazz.methods) == 1:
# Interfaces with just one method are "functional interfaces" and need
# to be abstract
return
for f in clazz.methods:
if "default" not in f.split and "static" not in f.split:
error(clazz, f, "GV6", "All interface methods should have a default "
"implementation for backwards compatibility")
def verify_fields(clazz):
"""Verify that all exposed fields are final.
Exposed fields must follow myName style.
Catch internal mFoo objects being exposed."""
for f in clazz.fields:
if re.match("[ms][A-Z]", f.name):
error(clazz, f, "F1", "Internal objects must not be exposed")
if re.match("[A-Z_]+", f.name):
if "static" not in f.split or "final" not in f.split:
error(clazz, f, "C2", "Constants must be marked static final")
def verify_register(clazz):
"""Verify parity of registration methods.
Callback objects use register/unregister methods.
Listener objects use add/remove methods."""
methods = [ m.name for m in clazz.methods ]
for m in clazz.methods:
if "Callback" in m.raw:
if m.name.startswith("register"):
other = "unregister" + m.name[8:]
if other not in methods:
error(clazz, m, "L2", "Missing unregister method")
if m.name.startswith("unregister"):
other = "register" + m.name[10:]
if other not in methods:
error(clazz, m, "L2", "Missing register method")
if m.name.startswith("add") or m.name.startswith("remove"):
error(clazz, m, "L3", "Callback methods should be named register/unregister")
if "Listener" in m.raw:
if m.name.startswith("add"):
other = "remove" + m.name[3:]
if other not in methods:
error(clazz, m, "L2", "Missing remove method")
if m.name.startswith("remove") and not m.name.startswith("removeAll"):
other = "add" + m.name[6:]
if other not in methods:
error(clazz, m, "L2", "Missing add method")
if m.name.startswith("register") or m.name.startswith("unregister"):
error(clazz, m, "L3", "Listener methods should be named add/remove")
def verify_sync(clazz):
"""Verify synchronized methods aren't exposed."""
for m in clazz.methods:
if "synchronized" in m.split:
error(clazz, m, "M5", "Internal locks must not be exposed")
def verify_intent_builder(clazz):
"""Verify that Intent builders are createFooIntent() style."""
if clazz.name == "Intent": return
for m in clazz.methods:
if m.typ.name == "android.content.Intent":
if m.name.startswith("create") and m.name.endswith("Intent"):
pass
else:
warn(clazz, m, "FW1", "Methods creating an Intent should be named createFooIntent()")
def verify_helper_classes(clazz):
"""Verify that helper classes are named consistently with what they extend.
All developer extendable methods should be named onFoo()."""
test_methods = False
if "extends android.app.Service" in clazz.raw:
test_methods = True
if not clazz.name.endswith("Service"):
error(clazz, None, "CL4", "Inconsistent class name; should be FooService")
found = False
for f in clazz.fields:
if f.name == "SERVICE_INTERFACE":
found = True
if f.value != clazz.fullname:
error(clazz, f, "C4", "Inconsistent interface constant; expected '%s'" % (clazz.fullname))
if "extends android.content.ContentProvider" in clazz.raw:
test_methods = True
if not clazz.name.endswith("Provider"):
error(clazz, None, "CL4", "Inconsistent class name; should be FooProvider")
found = False
for f in clazz.fields:
if f.name == "PROVIDER_INTERFACE":
found = True
if f.value != clazz.fullname:
error(clazz, f, "C4", "Inconsistent interface constant; expected '%s'" % (clazz.fullname))
if "extends android.content.BroadcastReceiver" in clazz.raw:
test_methods = True
if not clazz.name.endswith("Receiver"):
error(clazz, None, "CL4", "Inconsistent class name; should be FooReceiver")
if "extends android.app.Activity" in clazz.raw:
test_methods = True
if not clazz.name.endswith("Activity"):
error(clazz, None, "CL4", "Inconsistent class name; should be FooActivity")
if test_methods:
for m in clazz.methods:
if "final" in m.split: continue
if not re.match("on[A-Z]", m.name):
if "abstract" in m.split:
warn(clazz, m, None, "Methods implemented by developers should be named onFoo()")
else:
warn(clazz, m, None, "If implemented by developer, should be named onFoo(); otherwise consider marking final")
def verify_builder(clazz):
"""Verify builder classes.
Methods should return the builder to enable chaining."""
if " extends " in clazz.raw: return
if not clazz.name.endswith("Builder"): return
if clazz.name != "Builder":
warn(clazz, None, None, "Builder should be defined as inner class")
has_build = False
for m in clazz.methods:
if m.name == "build":
has_build = True
continue
if m.name.startswith("get"): continue
if m.name.startswith("clear"): continue
if m.name.startswith("with"):
warn(clazz, m, None, "Builder methods names should use setFoo() style")
if m.name.startswith("set"):
if not m.typ.name.endswith(clazz.fullname):
warn(clazz, m, "M4", "Methods must return the builder object")
if not has_build:
warn(clazz, None, None, "Missing build() method")
def verify_aidl(clazz):
"""Catch people exposing raw AIDL."""
if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
error(clazz, None, None, "Raw AIDL interfaces must not be exposed")
def verify_internal(clazz):
"""Catch people exposing internal classes."""
if clazz.pkg.name.startswith("com.android"):
error(clazz, None, None, "Internal classes must not be exposed")
def verify_layering(clazz):
"""Catch package layering violations.
For example, something in android.os depending on android.app."""
ranking = [
["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
"android.app",
"android.widget",
"android.view",
"android.animation",
"android.provider",
["android.content","android.graphics.drawable"],
"android.database",
"android.graphics",
"android.text",
"android.os",
"android.util"
]
def rank(p):
for i in range(len(ranking)):
if isinstance(ranking[i], list):
for j in ranking[i]:
if p.startswith(j): return i