blob: 6bb28e15fea72aca4c93bf45decb0ba6e42ef368 [file] [log] [blame]
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001#!/usr/bin/env python
2
3# Copyright (C) 2014 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the 'License');
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an 'AS IS' BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Enforces common Android public API design patterns. It ignores lint messages from
19a previous API level, if provided.
20
21Usage: apilint.py current.txt
22Usage: apilint.py current.txt previous.txt
23"""
24
Jeff Sharkey294f0de2014-08-29 17:41:43 -070025import re, sys, collections
Jeff Sharkey8190f4882014-08-28 12:24:07 -070026
27
28BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
29
30def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False):
31 # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes
32 codes = []
33 if reset: codes.append("0")
34 else:
35 if not fg is None: codes.append("3%d" % (fg))
36 if not bg is None:
37 if not bright: codes.append("4%d" % (bg))
38 else: codes.append("10%d" % (bg))
39 if bold: codes.append("1")
40 elif dim: codes.append("2")
41 else: codes.append("22")
42 return "\033[%sm" % (";".join(codes))
43
44
45class Field():
46 def __init__(self, clazz, raw):
47 self.clazz = clazz
48 self.raw = raw.strip(" {;")
49
50 raw = raw.split()
51 self.split = list(raw)
52
53 for r in ["field", "volatile", "transient", "public", "protected", "static", "final", "deprecated"]:
54 while r in raw: raw.remove(r)
55
56 self.typ = raw[0]
57 self.name = raw[1].strip(";")
58 if len(raw) >= 4 and raw[2] == "=":
59 self.value = raw[3].strip(';"')
60 else:
61 self.value = None
62
63 def __repr__(self):
64 return self.raw
65
66
67class Method():
68 def __init__(self, clazz, raw):
69 self.clazz = clazz
70 self.raw = raw.strip(" {;")
71
72 raw = re.split("[\s(),;]+", raw)
73 for r in ["", ";"]:
74 while r in raw: raw.remove(r)
75 self.split = list(raw)
76
77 for r in ["method", "public", "protected", "static", "final", "deprecated", "abstract"]:
78 while r in raw: raw.remove(r)
79
80 self.typ = raw[0]
81 self.name = raw[1]
82 self.args = []
83 for r in raw[2:]:
84 if r == "throws": break
85 self.args.append(r)
86
87 def __repr__(self):
88 return self.raw
89
90
91class Class():
92 def __init__(self, pkg, raw):
93 self.pkg = pkg
94 self.raw = raw.strip(" {;")
95 self.ctors = []
96 self.fields = []
97 self.methods = []
98
99 raw = raw.split()
100 self.split = list(raw)
101 if "class" in raw:
102 self.fullname = raw[raw.index("class")+1]
103 elif "interface" in raw:
104 self.fullname = raw[raw.index("interface")+1]
105
106 if "." in self.fullname:
107 self.name = self.fullname[self.fullname.rindex(".")+1:]
108 else:
109 self.name = self.fullname
110
111 def __repr__(self):
112 return self.raw
113
114
115class Package():
116 def __init__(self, raw):
117 self.raw = raw.strip(" {;")
118
119 raw = raw.split()
120 self.name = raw[raw.index("package")+1]
121
122 def __repr__(self):
123 return self.raw
124
125
126def parse_api(fn):
127 api = []
128 pkg = None
129 clazz = None
130
131 with open(fn) as f:
132 for raw in f.readlines():
133 raw = raw.rstrip()
134
135 if raw.startswith("package"):
136 pkg = Package(raw)
137 elif raw.startswith(" ") and raw.endswith("{"):
138 clazz = Class(pkg, raw)
139 api.append(clazz)
140 elif raw.startswith(" ctor"):
141 clazz.ctors.append(Method(clazz, raw))
142 elif raw.startswith(" method"):
143 clazz.methods.append(Method(clazz, raw))
144 elif raw.startswith(" field"):
145 clazz.fields.append(Field(clazz, raw))
146
147 return api
148
149
150failures = []
151
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700152def filter_dupe(s):
153 return s.replace(" deprecated ", " ")
154
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700155def _fail(clazz, detail, msg):
156 """Records an API failure to be processed later."""
157 global failures
158
159 res = msg
160 if detail is not None:
161 res += "\n in " + repr(detail)
162 res += "\n in " + repr(clazz)
163 res += "\n in " + repr(clazz.pkg)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700164 failures.append(filter_dupe(res))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700165
166def warn(clazz, detail, msg):
167 _fail(clazz, detail, "%sWarning:%s %s" % (format(fg=YELLOW, bg=BLACK), format(reset=True), msg))
168
169def error(clazz, detail, msg):
170 _fail(clazz, detail, "%sError:%s %s" % (format(fg=RED, bg=BLACK), format(reset=True), msg))
171
172
173def verify_constants(clazz):
174 """All static final constants must be FOO_NAME style."""
175 if re.match("R\.[a-z]+", clazz.fullname): return
176
177 for f in clazz.fields:
178 if "static" in f.split and "final" in f.split:
179 if re.match("[A-Z0-9_]+", f.name) is None:
180 error(clazz, f, "Constant field names should be FOO_NAME")
181
182
183def verify_enums(clazz):
184 """Enums are bad, mmkay?"""
185 if "extends java.lang.Enum" in clazz.raw:
186 error(clazz, None, "Enums are not allowed")
187
188
189def verify_class_names(clazz):
190 """Try catching malformed class names like myMtp or MTPUser."""
191 if re.search("[A-Z]{2,}", clazz.name) is not None:
192 warn(clazz, None, "Class name style should be Mtp not MTP")
193 if re.match("[^A-Z]", clazz.name):
194 error(clazz, None, "Class must start with uppercase char")
195
196
197def verify_method_names(clazz):
198 """Try catching malformed method names, like Foo() or getMTU()."""
199 if clazz.pkg.name == "android.opengl": return
200
201 for m in clazz.methods:
202 if re.search("[A-Z]{2,}", m.name) is not None:
203 warn(clazz, m, "Method name style should be getMtu() instead of getMTU()")
204 if re.match("[^a-z]", m.name):
205 error(clazz, None, "Method name must start with lowercase char")
206
207
208def verify_callbacks(clazz):
209 """Verify Callback classes.
210 All callback classes must be abstract.
211 All methods must follow onFoo() naming style."""
212
213 if clazz.name.endswith("Callbacks"):
214 error(clazz, None, "Class must be named exactly Callback")
215 if clazz.name.endswith("Observer"):
216 warn(clazz, None, "Class should be named Callback")
217
218 if clazz.name.endswith("Callback"):
219 if "interface" in clazz.split:
220 error(clazz, None, "Callback must be abstract class")
221
222 for m in clazz.methods:
223 if not re.match("on[A-Z][a-z]*", m.name):
224 error(clazz, m, "Callback method names must be onFoo style")
225
226
227def verify_listeners(clazz):
228 """Verify Listener classes.
229 All Listener classes must be interface.
230 All methods must follow onFoo() naming style.
231 If only a single method, it must match class name:
232 interface OnFooListener { void onFoo() }"""
233
234 if clazz.name.endswith("Listener"):
235 if " abstract class " in clazz.raw:
236 error(clazz, None, "Listener should be interface")
237
238 for m in clazz.methods:
239 if not re.match("on[A-Z][a-z]*", m.name):
240 error(clazz, m, "Listener method names must be onFoo style")
241
242 if len(clazz.methods) == 1 and clazz.name.startswith("On"):
243 m = clazz.methods[0]
244 if (m.name + "Listener").lower() != clazz.name.lower():
245 error(clazz, m, "Single method name should match class name")
246
247
248def verify_actions(clazz):
249 """Verify intent actions.
250 All action names must be named ACTION_FOO.
251 All action values must be scoped by package and match name:
252 package android.foo {
253 String ACTION_BAR = "android.foo.action.BAR";
254 }"""
255 for f in clazz.fields:
256 if f.value is None: continue
257 if f.name.startswith("EXTRA_"): continue
258
259 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
260 if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
261 if not f.name.startswith("ACTION_"):
262 error(clazz, f, "Intent action must be ACTION_FOO")
263 else:
264 if clazz.name == "Intent":
265 prefix = "android.intent.action"
266 elif clazz.name == "Settings":
267 prefix = "android.settings"
268 else:
269 prefix = clazz.pkg.name + ".action"
270 expected = prefix + "." + f.name[7:]
271 if f.value != expected:
272 error(clazz, f, "Inconsistent action value")
273
274
275def verify_extras(clazz):
276 """Verify intent extras.
277 All extra names must be named EXTRA_FOO.
278 All extra values must be scoped by package and match name:
279 package android.foo {
280 String EXTRA_BAR = "android.foo.extra.BAR";
281 }"""
282 for f in clazz.fields:
283 if f.value is None: continue
284 if f.name.startswith("ACTION_"): continue
285
286 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
287 if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
288 if not f.name.startswith("EXTRA_"):
289 error(clazz, f, "Intent extra must be EXTRA_FOO")
290 else:
291 if clazz.name == "Intent":
292 prefix = "android.intent.extra"
293 else:
294 prefix = clazz.pkg.name + ".extra"
295 expected = prefix + "." + f.name[6:]
296 if f.value != expected:
297 error(clazz, f, "Inconsistent extra value")
298
299
300def verify_equals(clazz):
301 """Verify that equals() and hashCode() must be overridden together."""
302 methods = [ m.name for m in clazz.methods ]
303 eq = "equals" in methods
304 hc = "hashCode" in methods
305 if eq != hc:
306 error(clazz, None, "Must override both equals and hashCode")
307
308
309def verify_parcelable(clazz):
310 """Verify that Parcelable objects aren't hiding required bits."""
311 if "implements android.os.Parcelable" in clazz.raw:
312 creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
313 write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
314 describe = [ i for i in clazz.methods if i.name == "describeContents" ]
315
316 if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
317 error(clazz, None, "Parcelable requires CREATOR, writeToParcel, and describeContents")
318
319
320def verify_protected(clazz):
321 """Verify that no protected methods are allowed."""
322 for m in clazz.methods:
323 if "protected" in m.split:
324 error(clazz, m, "Protected method")
325 for f in clazz.fields:
326 if "protected" in f.split:
327 error(clazz, f, "Protected field")
328
329
330def verify_fields(clazz):
331 """Verify that all exposed fields are final.
332 Exposed fields must follow myName style.
333 Catch internal mFoo objects being exposed."""
334 for f in clazz.fields:
335 if not "final" in f.split:
336 error(clazz, f, "Bare fields must be final; consider adding accessors")
337
338 if not "static" in f.split:
339 if not re.match("[a-z]([a-zA-Z]+)?", f.name):
340 error(clazz, f, "Non-static fields must be myName")
341
342 if re.match("[m][A-Z]", f.name):
343 error(clazz, f, "Don't expose your internal objects")
344
345
346def verify_register(clazz):
347 """Verify parity of registration methods.
348 Callback objects use register/unregister methods.
349 Listener objects use add/remove methods."""
350 methods = [ m.name for m in clazz.methods ]
351 for m in clazz.methods:
352 if "Callback" in m.raw:
353 if m.name.startswith("register"):
354 other = "unregister" + m.name[8:]
355 if other not in methods:
356 error(clazz, m, "Missing unregister")
357 if m.name.startswith("unregister"):
358 other = "register" + m.name[10:]
359 if other not in methods:
360 error(clazz, m, "Missing register")
361
362 if m.name.startswith("add") or m.name.startswith("remove"):
363 error(clazz, m, "Callback should be register/unregister")
364
365 if "Listener" in m.raw:
366 if m.name.startswith("add"):
367 other = "remove" + m.name[3:]
368 if other not in methods:
369 error(clazz, m, "Missing remove")
370 if m.name.startswith("remove") and not m.name.startswith("removeAll"):
371 other = "add" + m.name[6:]
372 if other not in methods:
373 error(clazz, m, "Missing add")
374
375 if m.name.startswith("register") or m.name.startswith("unregister"):
376 error(clazz, m, "Listener should be add/remove")
377
378
379def verify_sync(clazz):
380 """Verify synchronized methods aren't exposed."""
381 for m in clazz.methods:
382 if "synchronized" in m.split:
383 error(clazz, m, "Lock exposed")
384
385
386def verify_intent_builder(clazz):
387 """Verify that Intent builders are createFooIntent() style."""
388 if clazz.name == "Intent": return
389
390 for m in clazz.methods:
391 if m.typ == "android.content.Intent":
392 if m.name.startswith("create") and m.name.endswith("Intent"):
393 pass
394 else:
395 warn(clazz, m, "Should be createFooIntent()")
396
397
398def verify_helper_classes(clazz):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700399 """Verify that helper classes are named consistently with what they extend.
400 All developer extendable methods should be named onFoo()."""
401 test_methods = False
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700402 if "extends android.app.Service" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700403 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700404 if not clazz.name.endswith("Service"):
405 error(clazz, None, "Inconsistent class name")
406 if "extends android.content.ContentProvider" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700407 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700408 if not clazz.name.endswith("Provider"):
409 error(clazz, None, "Inconsistent class name")
410 if "extends android.content.BroadcastReceiver" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700411 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700412 if not clazz.name.endswith("Receiver"):
413 error(clazz, None, "Inconsistent class name")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700414 if "extends android.app.Activity" in clazz.raw:
415 test_methods = True
416 if not clazz.name.endswith("Activity"):
417 error(clazz, None, "Inconsistent class name")
418
419 if test_methods:
420 for m in clazz.methods:
421 if "final" in m.split: continue
422 if not re.match("on[A-Z]", m.name):
423 error(clazz, m, "Extendable methods should be onFoo() style, otherwise final")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700424
425
426def verify_builder(clazz):
427 """Verify builder classes.
428 Methods should return the builder to enable chaining."""
429 if " extends " in clazz.raw: return
430 if not clazz.name.endswith("Builder"): return
431
432 if clazz.name != "Builder":
433 warn(clazz, None, "Should be standalone Builder class")
434
435 has_build = False
436 for m in clazz.methods:
437 if m.name == "build":
438 has_build = True
439 continue
440
441 if m.name.startswith("get"): continue
442 if m.name.startswith("clear"): continue
443
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700444 if m.name.startswith("with"):
445 error(clazz, m, "Builder methods must be setFoo()")
446
447 if m.name.startswith("set"):
448 if not m.typ.endswith(clazz.fullname):
449 warn(clazz, m, "Should return the builder")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700450
451 if not has_build:
452 warn(clazz, None, "Missing build() method")
453
454
455def verify_aidl(clazz):
456 """Catch people exposing raw AIDL."""
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700457 if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700458 error(clazz, None, "Exposing raw AIDL interface")
459
460
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700461def verify_internal(clazz):
462 """Catch people exposing internal classes."""
463 if clazz.pkg.name.startswith("com.android"):
464 error(clazz, None, "Exposing internal class")
465
466
467def verify_layering(clazz):
468 """Catch package layering violations.
469 For example, something in android.os depending on android.app."""
470 ranking = [
471 ["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
472 "android.app",
473 "android.widget",
474 "android.view",
475 "android.animation",
476 "android.provider",
477 "android.content",
478 "android.database",
479 "android.graphics",
480 "android.text",
481 "android.os",
482 "android.util"
483 ]
484
485 def rank(p):
486 for i in range(len(ranking)):
487 if isinstance(ranking[i], list):
488 for j in ranking[i]:
489 if p.startswith(j): return i
490 else:
491 if p.startswith(ranking[i]): return i
492
493 cr = rank(clazz.pkg.name)
494 if cr is None: return
495
496 for f in clazz.fields:
497 ir = rank(f.typ)
498 if ir and ir < cr:
499 warn(clazz, f, "Field type violates package layering")
500
501 for m in clazz.methods:
502 ir = rank(m.typ)
503 if ir and ir < cr:
504 warn(clazz, m, "Method return type violates package layering")
505 for arg in m.args:
506 ir = rank(arg)
507 if ir and ir < cr:
508 warn(clazz, m, "Method argument type violates package layering")
509
510
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700511def verify_boolean(clazz):
512 """Catches people returning boolean from getFoo() style methods.
513 Ignores when matching setFoo() is present."""
514 methods = [ m.name for m in clazz.methods ]
515 for m in clazz.methods:
516 if m.typ == "boolean" and m.name.startswith("get") and m.name != "get" and len(m.args) == 0:
517 setter = "set" + m.name[3:]
518 if setter not in methods:
519 error(clazz, m, "Methods returning boolean should be isFoo or hasFoo")
520
521
522def verify_collections(clazz):
523 """Verifies that collection types are interfaces."""
524 bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
525 "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
526 for m in clazz.methods:
527 filt = re.sub("<.+>", "", m.typ)
528 if filt in bad:
529 error(clazz, m, "Return type is concrete collection")
530 for arg in m.args:
531 filt = re.sub("<.+>", "", arg)
532 if filt in bad:
533 error(clazz, m, "Argument is concrete collection")
534
535
536def verify_flags(clazz):
537 """Verifies that flags are non-overlapping."""
538 known = collections.defaultdict(int)
539 for f in clazz.fields:
540 if "FLAG_" in f.name:
541 try:
542 val = int(f.value)
543 except:
544 continue
545
546 scope = f.name[0:f.name.index("FLAG_")]
547 if val & known[scope]:
548 warn(clazz, f, "Found overlapping flag")
549 known[scope] |= val
550
551
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700552def verify_all(api):
553 global failures
554
555 failures = []
556 for clazz in api:
557 if clazz.pkg.name.startswith("java"): continue
558 if clazz.pkg.name.startswith("junit"): continue
559 if clazz.pkg.name.startswith("org.apache"): continue
560 if clazz.pkg.name.startswith("org.xml"): continue
561 if clazz.pkg.name.startswith("org.json"): continue
562 if clazz.pkg.name.startswith("org.w3c"): continue
563
564 verify_constants(clazz)
565 verify_enums(clazz)
566 verify_class_names(clazz)
567 verify_method_names(clazz)
568 verify_callbacks(clazz)
569 verify_listeners(clazz)
570 verify_actions(clazz)
571 verify_extras(clazz)
572 verify_equals(clazz)
573 verify_parcelable(clazz)
574 verify_protected(clazz)
575 verify_fields(clazz)
576 verify_register(clazz)
577 verify_sync(clazz)
578 verify_intent_builder(clazz)
579 verify_helper_classes(clazz)
580 verify_builder(clazz)
581 verify_aidl(clazz)
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700582 verify_internal(clazz)
583 verify_layering(clazz)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700584 verify_boolean(clazz)
585 verify_collections(clazz)
586 verify_flags(clazz)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700587
588 return failures
589
590
591cur = parse_api(sys.argv[1])
592cur_fail = verify_all(cur)
593
594if len(sys.argv) > 2:
595 prev = parse_api(sys.argv[2])
596 prev_fail = verify_all(prev)
597
598 # ignore errors from previous API level
599 for p in prev_fail:
600 if p in cur_fail:
601 cur_fail.remove(p)
602
603
604for f in cur_fail:
605 print f
606 print