blob: d9d571ad0f508da5db6a98230aa62926d53bdb71 [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
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070023
24You can also splice in blame details like this:
25$ git blame api/current.txt -t -e > /tmp/currentblame.txt
26$ apilint.py /tmp/currentblame.txt previous.txt --no-color
Jeff Sharkey8190f4882014-08-28 12:24:07 -070027"""
28
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070029import re, sys, collections, traceback
Jeff Sharkey8190f4882014-08-28 12:24:07 -070030
31
32BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
33
34def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False):
35 # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070036 if "--no-color" in sys.argv: return ""
Jeff Sharkey8190f4882014-08-28 12:24:07 -070037 codes = []
38 if reset: codes.append("0")
39 else:
40 if not fg is None: codes.append("3%d" % (fg))
41 if not bg is None:
42 if not bright: codes.append("4%d" % (bg))
43 else: codes.append("10%d" % (bg))
44 if bold: codes.append("1")
45 elif dim: codes.append("2")
46 else: codes.append("22")
47 return "\033[%sm" % (";".join(codes))
48
49
50class Field():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070051 def __init__(self, clazz, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -070052 self.clazz = clazz
53 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070054 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -070055
56 raw = raw.split()
57 self.split = list(raw)
58
59 for r in ["field", "volatile", "transient", "public", "protected", "static", "final", "deprecated"]:
60 while r in raw: raw.remove(r)
61
62 self.typ = raw[0]
63 self.name = raw[1].strip(";")
64 if len(raw) >= 4 and raw[2] == "=":
65 self.value = raw[3].strip(';"')
66 else:
67 self.value = None
68
69 def __repr__(self):
70 return self.raw
71
72
73class Method():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070074 def __init__(self, clazz, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -070075 self.clazz = clazz
76 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070077 self.blame = blame
78
79 # drop generics for now
80 raw = re.sub("<.+?>", "", raw)
Jeff Sharkey8190f4882014-08-28 12:24:07 -070081
82 raw = re.split("[\s(),;]+", raw)
83 for r in ["", ";"]:
84 while r in raw: raw.remove(r)
85 self.split = list(raw)
86
87 for r in ["method", "public", "protected", "static", "final", "deprecated", "abstract"]:
88 while r in raw: raw.remove(r)
89
90 self.typ = raw[0]
91 self.name = raw[1]
92 self.args = []
93 for r in raw[2:]:
94 if r == "throws": break
95 self.args.append(r)
96
97 def __repr__(self):
98 return self.raw
99
100
101class Class():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700102 def __init__(self, pkg, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700103 self.pkg = pkg
104 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700105 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700106 self.ctors = []
107 self.fields = []
108 self.methods = []
109
110 raw = raw.split()
111 self.split = list(raw)
112 if "class" in raw:
113 self.fullname = raw[raw.index("class")+1]
114 elif "interface" in raw:
115 self.fullname = raw[raw.index("interface")+1]
116
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700117 self.fullname = self.pkg.name + "." + self.fullname
118 self.name = self.fullname[self.fullname.rindex(".")+1:]
119
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700120
121 def __repr__(self):
122 return self.raw
123
124
125class Package():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700126 def __init__(self, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700127 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700128 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700129
130 raw = raw.split()
131 self.name = raw[raw.index("package")+1]
132
133 def __repr__(self):
134 return self.raw
135
136
137def parse_api(fn):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700138 api = {}
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700139 pkg = None
140 clazz = None
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700141 blame = None
142
143 re_blame = re.compile("^([a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700144
145 with open(fn) as f:
146 for raw in f.readlines():
147 raw = raw.rstrip()
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700148 match = re_blame.match(raw)
149 if match is not None:
150 blame = match.groups()[0:2]
151 raw = match.groups()[2]
152 else:
153 blame = None
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700154
155 if raw.startswith("package"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700156 pkg = Package(raw, blame)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700157 elif raw.startswith(" ") and raw.endswith("{"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700158 clazz = Class(pkg, raw, blame)
159 api[clazz.fullname] = clazz
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700160 elif raw.startswith(" ctor"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700161 clazz.ctors.append(Method(clazz, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700162 elif raw.startswith(" method"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700163 clazz.methods.append(Method(clazz, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700164 elif raw.startswith(" field"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700165 clazz.fields.append(Field(clazz, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700166
167 return api
168
169
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700170failures = {}
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700171
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700172def _fail(clazz, detail, msg):
173 """Records an API failure to be processed later."""
174 global failures
175
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700176 sig = "%s-%s-%s" % (clazz.fullname, repr(detail), msg)
177 sig = sig.replace(" deprecated ", " ")
178
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700179 res = msg
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700180 blame = clazz.blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700181 if detail is not None:
182 res += "\n in " + repr(detail)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700183 blame = detail.blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700184 res += "\n in " + repr(clazz)
185 res += "\n in " + repr(clazz.pkg)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700186 if blame is not None:
187 res += "\n last modified by %s in %s" % (blame[1], blame[0])
188 failures[sig] = res
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700189
190def warn(clazz, detail, msg):
191 _fail(clazz, detail, "%sWarning:%s %s" % (format(fg=YELLOW, bg=BLACK), format(reset=True), msg))
192
193def error(clazz, detail, msg):
194 _fail(clazz, detail, "%sError:%s %s" % (format(fg=RED, bg=BLACK), format(reset=True), msg))
195
196
197def verify_constants(clazz):
198 """All static final constants must be FOO_NAME style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700199 if re.match("android\.R\.[a-z]+", clazz.fullname): return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700200
201 for f in clazz.fields:
202 if "static" in f.split and "final" in f.split:
203 if re.match("[A-Z0-9_]+", f.name) is None:
204 error(clazz, f, "Constant field names should be FOO_NAME")
205
206
207def verify_enums(clazz):
208 """Enums are bad, mmkay?"""
209 if "extends java.lang.Enum" in clazz.raw:
210 error(clazz, None, "Enums are not allowed")
211
212
213def verify_class_names(clazz):
214 """Try catching malformed class names like myMtp or MTPUser."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700215 if clazz.fullname.startswith("android.opengl"): return
216 if clazz.fullname.startswith("android.renderscript"): return
217 if re.match("android\.R\.[a-z]+", clazz.fullname): return
218
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700219 if re.search("[A-Z]{2,}", clazz.name) is not None:
220 warn(clazz, None, "Class name style should be Mtp not MTP")
221 if re.match("[^A-Z]", clazz.name):
222 error(clazz, None, "Class must start with uppercase char")
223
224
225def verify_method_names(clazz):
226 """Try catching malformed method names, like Foo() or getMTU()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700227 if clazz.fullname.startswith("android.opengl"): return
228 if clazz.fullname.startswith("android.renderscript"): return
229 if clazz.fullname == "android.system.OsConstants": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700230
231 for m in clazz.methods:
232 if re.search("[A-Z]{2,}", m.name) is not None:
233 warn(clazz, m, "Method name style should be getMtu() instead of getMTU()")
234 if re.match("[^a-z]", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700235 error(clazz, m, "Method name must start with lowercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700236
237
238def verify_callbacks(clazz):
239 """Verify Callback classes.
240 All callback classes must be abstract.
241 All methods must follow onFoo() naming style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700242 if clazz.fullname == "android.speech.tts.SynthesisCallback": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700243
244 if clazz.name.endswith("Callbacks"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700245 error(clazz, None, "Class name must not be plural")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700246 if clazz.name.endswith("Observer"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700247 warn(clazz, None, "Class should be named FooCallback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700248
249 if clazz.name.endswith("Callback"):
250 if "interface" in clazz.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700251 error(clazz, None, "Callback must be abstract class to enable extension in future API levels")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700252
253 for m in clazz.methods:
254 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700255 error(clazz, m, "Callback method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700256
257
258def verify_listeners(clazz):
259 """Verify Listener classes.
260 All Listener classes must be interface.
261 All methods must follow onFoo() naming style.
262 If only a single method, it must match class name:
263 interface OnFooListener { void onFoo() }"""
264
265 if clazz.name.endswith("Listener"):
266 if " abstract class " in clazz.raw:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700267 error(clazz, None, "Listener should be an interface, otherwise renamed Callback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700268
269 for m in clazz.methods:
270 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700271 error(clazz, m, "Listener method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700272
273 if len(clazz.methods) == 1 and clazz.name.startswith("On"):
274 m = clazz.methods[0]
275 if (m.name + "Listener").lower() != clazz.name.lower():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700276 error(clazz, m, "Single listener method name should match class name")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700277
278
279def verify_actions(clazz):
280 """Verify intent actions.
281 All action names must be named ACTION_FOO.
282 All action values must be scoped by package and match name:
283 package android.foo {
284 String ACTION_BAR = "android.foo.action.BAR";
285 }"""
286 for f in clazz.fields:
287 if f.value is None: continue
288 if f.name.startswith("EXTRA_"): continue
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700289 if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": continue
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700290
291 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
292 if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
293 if not f.name.startswith("ACTION_"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700294 error(clazz, f, "Intent action constant name must be ACTION_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700295 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700296 if clazz.fullname == "android.content.Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700297 prefix = "android.intent.action"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700298 elif clazz.fullname == "android.provider.Settings":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700299 prefix = "android.settings"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700300 elif clazz.fullname == "android.app.admin.DevicePolicyManager" or clazz.fullname == "android.app.admin.DeviceAdminReceiver":
301 prefix = "android.app.action"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700302 else:
303 prefix = clazz.pkg.name + ".action"
304 expected = prefix + "." + f.name[7:]
305 if f.value != expected:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700306 error(clazz, f, "Inconsistent action value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700307
308
309def verify_extras(clazz):
310 """Verify intent extras.
311 All extra names must be named EXTRA_FOO.
312 All extra values must be scoped by package and match name:
313 package android.foo {
314 String EXTRA_BAR = "android.foo.extra.BAR";
315 }"""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700316 if clazz.fullname == "android.app.Notification": return
317 if clazz.fullname == "android.appwidget.AppWidgetManager": return
318
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700319 for f in clazz.fields:
320 if f.value is None: continue
321 if f.name.startswith("ACTION_"): continue
322
323 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
324 if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
325 if not f.name.startswith("EXTRA_"):
326 error(clazz, f, "Intent extra must be EXTRA_FOO")
327 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700328 if clazz.pkg.name == "android.content" and clazz.name == "Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700329 prefix = "android.intent.extra"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700330 elif clazz.pkg.name == "android.app.admin":
331 prefix = "android.app.extra"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700332 else:
333 prefix = clazz.pkg.name + ".extra"
334 expected = prefix + "." + f.name[6:]
335 if f.value != expected:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700336 error(clazz, f, "Inconsistent extra value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700337
338
339def verify_equals(clazz):
340 """Verify that equals() and hashCode() must be overridden together."""
341 methods = [ m.name for m in clazz.methods ]
342 eq = "equals" in methods
343 hc = "hashCode" in methods
344 if eq != hc:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700345 error(clazz, None, "Must override both equals and hashCode; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700346
347
348def verify_parcelable(clazz):
349 """Verify that Parcelable objects aren't hiding required bits."""
350 if "implements android.os.Parcelable" in clazz.raw:
351 creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
352 write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
353 describe = [ i for i in clazz.methods if i.name == "describeContents" ]
354
355 if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700356 error(clazz, None, "Parcelable requires CREATOR, writeToParcel, and describeContents; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700357
358
359def verify_protected(clazz):
360 """Verify that no protected methods are allowed."""
361 for m in clazz.methods:
362 if "protected" in m.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700363 error(clazz, m, "No protected methods; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700364 for f in clazz.fields:
365 if "protected" in f.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700366 error(clazz, f, "No protected fields; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700367
368
369def verify_fields(clazz):
370 """Verify that all exposed fields are final.
371 Exposed fields must follow myName style.
372 Catch internal mFoo objects being exposed."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700373
374 IGNORE_BARE_FIELDS = [
375 "android.app.ActivityManager.RecentTaskInfo",
376 "android.app.Notification",
377 "android.content.pm.ActivityInfo",
378 "android.content.pm.ApplicationInfo",
379 "android.content.pm.FeatureGroupInfo",
380 "android.content.pm.InstrumentationInfo",
381 "android.content.pm.PackageInfo",
382 "android.content.pm.PackageItemInfo",
383 "android.os.Message",
384 "android.system.StructPollfd",
385 ]
386
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700387 for f in clazz.fields:
388 if not "final" in f.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700389 if clazz.fullname in IGNORE_BARE_FIELDS:
390 pass
391 elif clazz.fullname.endswith("LayoutParams"):
392 pass
393 elif clazz.fullname.startswith("android.util.Mutable"):
394 pass
395 else:
396 error(clazz, f, "Bare fields must be marked final; consider adding accessors")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700397
398 if not "static" in f.split:
399 if not re.match("[a-z]([a-zA-Z]+)?", f.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700400 error(clazz, f, "Non-static fields must be named with myField style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700401
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700402 if re.match("[ms][A-Z]", f.name):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700403 error(clazz, f, "Don't expose your internal objects")
404
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700405 if re.match("[A-Z_]+", f.name):
406 if "static" not in f.split or "final" not in f.split:
407 error(clazz, f, "Constants must be marked static final")
408
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700409
410def verify_register(clazz):
411 """Verify parity of registration methods.
412 Callback objects use register/unregister methods.
413 Listener objects use add/remove methods."""
414 methods = [ m.name for m in clazz.methods ]
415 for m in clazz.methods:
416 if "Callback" in m.raw:
417 if m.name.startswith("register"):
418 other = "unregister" + m.name[8:]
419 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700420 error(clazz, m, "Missing unregister method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700421 if m.name.startswith("unregister"):
422 other = "register" + m.name[10:]
423 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700424 error(clazz, m, "Missing register method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700425
426 if m.name.startswith("add") or m.name.startswith("remove"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700427 error(clazz, m, "Callback methods should be named register/unregister")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700428
429 if "Listener" in m.raw:
430 if m.name.startswith("add"):
431 other = "remove" + m.name[3:]
432 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700433 error(clazz, m, "Missing remove method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700434 if m.name.startswith("remove") and not m.name.startswith("removeAll"):
435 other = "add" + m.name[6:]
436 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700437 error(clazz, m, "Missing add method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700438
439 if m.name.startswith("register") or m.name.startswith("unregister"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700440 error(clazz, m, "Listener methods should be named add/remove")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700441
442
443def verify_sync(clazz):
444 """Verify synchronized methods aren't exposed."""
445 for m in clazz.methods:
446 if "synchronized" in m.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700447 error(clazz, m, "Internal lock exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700448
449
450def verify_intent_builder(clazz):
451 """Verify that Intent builders are createFooIntent() style."""
452 if clazz.name == "Intent": return
453
454 for m in clazz.methods:
455 if m.typ == "android.content.Intent":
456 if m.name.startswith("create") and m.name.endswith("Intent"):
457 pass
458 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700459 error(clazz, m, "Methods creating an Intent should be named createFooIntent()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700460
461
462def verify_helper_classes(clazz):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700463 """Verify that helper classes are named consistently with what they extend.
464 All developer extendable methods should be named onFoo()."""
465 test_methods = False
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700466 if "extends android.app.Service" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700467 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700468 if not clazz.name.endswith("Service"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700469 error(clazz, None, "Inconsistent class name; should be FooService")
470
471 found = False
472 for f in clazz.fields:
473 if f.name == "SERVICE_INTERFACE":
474 found = True
475 if f.value != clazz.fullname:
476 error(clazz, f, "Inconsistent interface constant; expected %s" % (clazz.fullname))
477
478 if not found:
479 warn(clazz, None, "Missing SERVICE_INTERFACE constant")
480
481 if "abstract" in clazz.split and not clazz.fullname.startswith("android.service."):
482 warn(clazz, None, "Services extended by developers should be under android.service")
483
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700484 if "extends android.content.ContentProvider" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700485 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700486 if not clazz.name.endswith("Provider"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700487 error(clazz, None, "Inconsistent class name; should be FooProvider")
488
489 found = False
490 for f in clazz.fields:
491 if f.name == "PROVIDER_INTERFACE":
492 found = True
493 if f.value != clazz.fullname:
494 error(clazz, f, "Inconsistent interface name; expected %s" % (clazz.fullname))
495
496 if not found:
497 warn(clazz, None, "Missing PROVIDER_INTERFACE constant")
498
499 if "abstract" in clazz.split and not clazz.fullname.startswith("android.provider."):
500 warn(clazz, None, "Providers extended by developers should be under android.provider")
501
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700502 if "extends android.content.BroadcastReceiver" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700503 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700504 if not clazz.name.endswith("Receiver"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700505 error(clazz, None, "Inconsistent class name; should be FooReceiver")
506
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700507 if "extends android.app.Activity" in clazz.raw:
508 test_methods = True
509 if not clazz.name.endswith("Activity"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700510 error(clazz, None, "Inconsistent class name; should be FooActivity")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700511
512 if test_methods:
513 for m in clazz.methods:
514 if "final" in m.split: continue
515 if not re.match("on[A-Z]", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700516 if "abstract" in m.split:
517 error(clazz, m, "Methods implemented by developers must be named onFoo()")
518 else:
519 warn(clazz, m, "If implemented by developer, should be named onFoo(); otherwise consider marking final")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700520
521
522def verify_builder(clazz):
523 """Verify builder classes.
524 Methods should return the builder to enable chaining."""
525 if " extends " in clazz.raw: return
526 if not clazz.name.endswith("Builder"): return
527
528 if clazz.name != "Builder":
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700529 warn(clazz, None, "Builder should be defined as inner class")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700530
531 has_build = False
532 for m in clazz.methods:
533 if m.name == "build":
534 has_build = True
535 continue
536
537 if m.name.startswith("get"): continue
538 if m.name.startswith("clear"): continue
539
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700540 if m.name.startswith("with"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700541 error(clazz, m, "Builder methods names must follow setFoo() style")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700542
543 if m.name.startswith("set"):
544 if not m.typ.endswith(clazz.fullname):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700545 warn(clazz, m, "Methods should return the builder")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700546
547 if not has_build:
548 warn(clazz, None, "Missing build() method")
549
550
551def verify_aidl(clazz):
552 """Catch people exposing raw AIDL."""
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700553 if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700554 error(clazz, None, "Exposing raw AIDL interface")
555
556
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700557def verify_internal(clazz):
558 """Catch people exposing internal classes."""
559 if clazz.pkg.name.startswith("com.android"):
560 error(clazz, None, "Exposing internal class")
561
562
563def verify_layering(clazz):
564 """Catch package layering violations.
565 For example, something in android.os depending on android.app."""
566 ranking = [
567 ["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
568 "android.app",
569 "android.widget",
570 "android.view",
571 "android.animation",
572 "android.provider",
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700573 ["android.content","android.graphics.drawable"],
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700574 "android.database",
575 "android.graphics",
576 "android.text",
577 "android.os",
578 "android.util"
579 ]
580
581 def rank(p):
582 for i in range(len(ranking)):
583 if isinstance(ranking[i], list):
584 for j in ranking[i]:
585 if p.startswith(j): return i
586 else:
587 if p.startswith(ranking[i]): return i
588
589 cr = rank(clazz.pkg.name)
590 if cr is None: return
591
592 for f in clazz.fields:
593 ir = rank(f.typ)
594 if ir and ir < cr:
595 warn(clazz, f, "Field type violates package layering")
596
597 for m in clazz.methods:
598 ir = rank(m.typ)
599 if ir and ir < cr:
600 warn(clazz, m, "Method return type violates package layering")
601 for arg in m.args:
602 ir = rank(arg)
603 if ir and ir < cr:
604 warn(clazz, m, "Method argument type violates package layering")
605
606
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700607def verify_boolean(clazz, api):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700608 """Catches people returning boolean from getFoo() style methods.
609 Ignores when matching setFoo() is present."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700610
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700611 methods = [ m.name for m in clazz.methods ]
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700612
613 builder = clazz.fullname + ".Builder"
614 builder_methods = []
615 if builder in api:
616 builder_methods = [ m.name for m in api[builder].methods ]
617
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700618 for m in clazz.methods:
619 if m.typ == "boolean" and m.name.startswith("get") and m.name != "get" and len(m.args) == 0:
620 setter = "set" + m.name[3:]
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700621 if setter in methods:
622 pass
623 elif builder is not None and setter in builder_methods:
624 pass
625 else:
626 warn(clazz, m, "Methods returning boolean should be named isFoo, hasFoo, areFoo")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700627
628
629def verify_collections(clazz):
630 """Verifies that collection types are interfaces."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700631 if clazz.fullname == "android.os.Bundle": return
632
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700633 bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
634 "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
635 for m in clazz.methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700636 if m.typ in bad:
637 error(clazz, m, "Return type is concrete collection; should be interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700638 for arg in m.args:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700639 if arg in bad:
640 error(clazz, m, "Argument is concrete collection; should be interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700641
642
643def verify_flags(clazz):
644 """Verifies that flags are non-overlapping."""
645 known = collections.defaultdict(int)
646 for f in clazz.fields:
647 if "FLAG_" in f.name:
648 try:
649 val = int(f.value)
650 except:
651 continue
652
653 scope = f.name[0:f.name.index("FLAG_")]
654 if val & known[scope]:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700655 warn(clazz, f, "Found overlapping flag constant value")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700656 known[scope] |= val
657
658
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700659def verify_all(api):
660 global failures
661
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700662 failures = {}
663 for key in sorted(api.keys()):
664 clazz = api[key]
665
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700666 if clazz.pkg.name.startswith("java"): continue
667 if clazz.pkg.name.startswith("junit"): continue
668 if clazz.pkg.name.startswith("org.apache"): continue
669 if clazz.pkg.name.startswith("org.xml"): continue
670 if clazz.pkg.name.startswith("org.json"): continue
671 if clazz.pkg.name.startswith("org.w3c"): continue
672
673 verify_constants(clazz)
674 verify_enums(clazz)
675 verify_class_names(clazz)
676 verify_method_names(clazz)
677 verify_callbacks(clazz)
678 verify_listeners(clazz)
679 verify_actions(clazz)
680 verify_extras(clazz)
681 verify_equals(clazz)
682 verify_parcelable(clazz)
683 verify_protected(clazz)
684 verify_fields(clazz)
685 verify_register(clazz)
686 verify_sync(clazz)
687 verify_intent_builder(clazz)
688 verify_helper_classes(clazz)
689 verify_builder(clazz)
690 verify_aidl(clazz)
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700691 verify_internal(clazz)
692 verify_layering(clazz)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700693 verify_boolean(clazz, api)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700694 verify_collections(clazz)
695 verify_flags(clazz)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700696
697 return failures
698
699
700cur = parse_api(sys.argv[1])
701cur_fail = verify_all(cur)
702
703if len(sys.argv) > 2:
704 prev = parse_api(sys.argv[2])
705 prev_fail = verify_all(prev)
706
707 # ignore errors from previous API level
708 for p in prev_fail:
709 if p in cur_fail:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700710 del cur_fail[p]
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700711
712
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700713for f in sorted(cur_fail):
714 print cur_fail[f]
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700715 print