blob: 393d2ec5d012ae38b5840641153b8ba2de111873 [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
Jeff Sharkey037458a2014-09-04 15:46:20 -070069 self.ident = self.raw.replace(" deprecated ", " ")
70
Jeff Sharkey8190f4882014-08-28 12:24:07 -070071 def __repr__(self):
72 return self.raw
73
74
75class Method():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070076 def __init__(self, clazz, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -070077 self.clazz = clazz
78 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070079 self.blame = blame
80
81 # drop generics for now
82 raw = re.sub("<.+?>", "", raw)
Jeff Sharkey8190f4882014-08-28 12:24:07 -070083
84 raw = re.split("[\s(),;]+", raw)
85 for r in ["", ";"]:
86 while r in raw: raw.remove(r)
87 self.split = list(raw)
88
89 for r in ["method", "public", "protected", "static", "final", "deprecated", "abstract"]:
90 while r in raw: raw.remove(r)
91
92 self.typ = raw[0]
93 self.name = raw[1]
94 self.args = []
95 for r in raw[2:]:
96 if r == "throws": break
97 self.args.append(r)
98
Jeff Sharkey037458a2014-09-04 15:46:20 -070099 # identity for compat purposes
100 ident = self.raw
101 ident = ident.replace(" deprecated ", " ")
102 ident = ident.replace(" synchronized ", " ")
103 ident = re.sub("<.+?>", "", ident)
104 if " throws " in ident:
105 ident = ident[:ident.index(" throws ")]
106 self.ident = ident
107
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700108 def __repr__(self):
109 return self.raw
110
111
112class Class():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700113 def __init__(self, pkg, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700114 self.pkg = pkg
115 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700116 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700117 self.ctors = []
118 self.fields = []
119 self.methods = []
120
121 raw = raw.split()
122 self.split = list(raw)
123 if "class" in raw:
124 self.fullname = raw[raw.index("class")+1]
125 elif "interface" in raw:
126 self.fullname = raw[raw.index("interface")+1]
Jeff Sharkey037458a2014-09-04 15:46:20 -0700127 else:
128 raise ValueError("Funky class type %s" % (self.raw))
129
130 if "extends" in raw:
131 self.extends = raw[raw.index("extends")+1]
132 else:
133 self.extends = None
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700134
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700135 self.fullname = self.pkg.name + "." + self.fullname
136 self.name = self.fullname[self.fullname.rindex(".")+1:]
137
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700138 def __repr__(self):
139 return self.raw
140
141
142class Package():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700143 def __init__(self, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700144 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700145 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700146
147 raw = raw.split()
148 self.name = raw[raw.index("package")+1]
149
150 def __repr__(self):
151 return self.raw
152
153
154def parse_api(fn):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700155 api = {}
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700156 pkg = None
157 clazz = None
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700158 blame = None
159
160 re_blame = re.compile("^([a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700161
162 with open(fn) as f:
163 for raw in f.readlines():
164 raw = raw.rstrip()
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700165 match = re_blame.match(raw)
166 if match is not None:
167 blame = match.groups()[0:2]
168 raw = match.groups()[2]
169 else:
170 blame = None
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700171
172 if raw.startswith("package"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700173 pkg = Package(raw, blame)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700174 elif raw.startswith(" ") and raw.endswith("{"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700175 clazz = Class(pkg, raw, blame)
176 api[clazz.fullname] = clazz
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700177 elif raw.startswith(" ctor"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700178 clazz.ctors.append(Method(clazz, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700179 elif raw.startswith(" method"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700180 clazz.methods.append(Method(clazz, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700181 elif raw.startswith(" field"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700182 clazz.fields.append(Field(clazz, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700183
184 return api
185
186
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700187failures = {}
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700188
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700189def _fail(clazz, detail, msg):
190 """Records an API failure to be processed later."""
191 global failures
192
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700193 sig = "%s-%s-%s" % (clazz.fullname, repr(detail), msg)
194 sig = sig.replace(" deprecated ", " ")
195
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700196 res = msg
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700197 blame = clazz.blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700198 if detail is not None:
199 res += "\n in " + repr(detail)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700200 blame = detail.blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700201 res += "\n in " + repr(clazz)
202 res += "\n in " + repr(clazz.pkg)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700203 if blame is not None:
204 res += "\n last modified by %s in %s" % (blame[1], blame[0])
205 failures[sig] = res
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700206
207def warn(clazz, detail, msg):
Jeff Sharkey037458a2014-09-04 15:46:20 -0700208 _fail(clazz, detail, "%sWarning:%s %s" % (format(fg=YELLOW, bg=BLACK, bold=True), format(reset=True), msg))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700209
210def error(clazz, detail, msg):
Jeff Sharkey037458a2014-09-04 15:46:20 -0700211 _fail(clazz, detail, "%sError:%s %s" % (format(fg=RED, bg=BLACK, bold=True), format(reset=True), msg))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700212
213
214def verify_constants(clazz):
215 """All static final constants must be FOO_NAME style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700216 if re.match("android\.R\.[a-z]+", clazz.fullname): return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700217
218 for f in clazz.fields:
219 if "static" in f.split and "final" in f.split:
220 if re.match("[A-Z0-9_]+", f.name) is None:
221 error(clazz, f, "Constant field names should be FOO_NAME")
222
223
224def verify_enums(clazz):
225 """Enums are bad, mmkay?"""
226 if "extends java.lang.Enum" in clazz.raw:
227 error(clazz, None, "Enums are not allowed")
228
229
230def verify_class_names(clazz):
231 """Try catching malformed class names like myMtp or MTPUser."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700232 if clazz.fullname.startswith("android.opengl"): return
233 if clazz.fullname.startswith("android.renderscript"): return
234 if re.match("android\.R\.[a-z]+", clazz.fullname): return
235
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700236 if re.search("[A-Z]{2,}", clazz.name) is not None:
237 warn(clazz, None, "Class name style should be Mtp not MTP")
238 if re.match("[^A-Z]", clazz.name):
239 error(clazz, None, "Class must start with uppercase char")
240
241
242def verify_method_names(clazz):
243 """Try catching malformed method names, like Foo() or getMTU()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700244 if clazz.fullname.startswith("android.opengl"): return
245 if clazz.fullname.startswith("android.renderscript"): return
246 if clazz.fullname == "android.system.OsConstants": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700247
248 for m in clazz.methods:
249 if re.search("[A-Z]{2,}", m.name) is not None:
250 warn(clazz, m, "Method name style should be getMtu() instead of getMTU()")
251 if re.match("[^a-z]", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700252 error(clazz, m, "Method name must start with lowercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700253
254
255def verify_callbacks(clazz):
256 """Verify Callback classes.
257 All callback classes must be abstract.
258 All methods must follow onFoo() naming style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700259 if clazz.fullname == "android.speech.tts.SynthesisCallback": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700260
261 if clazz.name.endswith("Callbacks"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700262 error(clazz, None, "Class name must not be plural")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700263 if clazz.name.endswith("Observer"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700264 warn(clazz, None, "Class should be named FooCallback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700265
266 if clazz.name.endswith("Callback"):
267 if "interface" in clazz.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700268 error(clazz, None, "Callback must be abstract class to enable extension in future API levels")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700269
270 for m in clazz.methods:
271 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700272 error(clazz, m, "Callback method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700273
274
275def verify_listeners(clazz):
276 """Verify Listener classes.
277 All Listener classes must be interface.
278 All methods must follow onFoo() naming style.
279 If only a single method, it must match class name:
280 interface OnFooListener { void onFoo() }"""
281
282 if clazz.name.endswith("Listener"):
283 if " abstract class " in clazz.raw:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700284 error(clazz, None, "Listener should be an interface, otherwise renamed Callback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700285
286 for m in clazz.methods:
287 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700288 error(clazz, m, "Listener method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700289
290 if len(clazz.methods) == 1 and clazz.name.startswith("On"):
291 m = clazz.methods[0]
292 if (m.name + "Listener").lower() != clazz.name.lower():
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700293 error(clazz, m, "Single listener method name should match class name")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700294
295
296def verify_actions(clazz):
297 """Verify intent actions.
298 All action names must be named ACTION_FOO.
299 All action values must be scoped by package and match name:
300 package android.foo {
301 String ACTION_BAR = "android.foo.action.BAR";
302 }"""
303 for f in clazz.fields:
304 if f.value is None: continue
305 if f.name.startswith("EXTRA_"): continue
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700306 if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": continue
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700307
308 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
309 if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
310 if not f.name.startswith("ACTION_"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700311 error(clazz, f, "Intent action constant name must be ACTION_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700312 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700313 if clazz.fullname == "android.content.Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700314 prefix = "android.intent.action"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700315 elif clazz.fullname == "android.provider.Settings":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700316 prefix = "android.settings"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700317 elif clazz.fullname == "android.app.admin.DevicePolicyManager" or clazz.fullname == "android.app.admin.DeviceAdminReceiver":
318 prefix = "android.app.action"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700319 else:
320 prefix = clazz.pkg.name + ".action"
321 expected = prefix + "." + f.name[7:]
322 if f.value != expected:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700323 error(clazz, f, "Inconsistent action value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700324
325
326def verify_extras(clazz):
327 """Verify intent extras.
328 All extra names must be named EXTRA_FOO.
329 All extra values must be scoped by package and match name:
330 package android.foo {
331 String EXTRA_BAR = "android.foo.extra.BAR";
332 }"""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700333 if clazz.fullname == "android.app.Notification": return
334 if clazz.fullname == "android.appwidget.AppWidgetManager": return
335
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700336 for f in clazz.fields:
337 if f.value is None: continue
338 if f.name.startswith("ACTION_"): continue
339
340 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
341 if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
342 if not f.name.startswith("EXTRA_"):
343 error(clazz, f, "Intent extra must be EXTRA_FOO")
344 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700345 if clazz.pkg.name == "android.content" and clazz.name == "Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700346 prefix = "android.intent.extra"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700347 elif clazz.pkg.name == "android.app.admin":
348 prefix = "android.app.extra"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700349 else:
350 prefix = clazz.pkg.name + ".extra"
351 expected = prefix + "." + f.name[6:]
352 if f.value != expected:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700353 error(clazz, f, "Inconsistent extra value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700354
355
356def verify_equals(clazz):
357 """Verify that equals() and hashCode() must be overridden together."""
358 methods = [ m.name for m in clazz.methods ]
359 eq = "equals" in methods
360 hc = "hashCode" in methods
361 if eq != hc:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700362 error(clazz, None, "Must override both equals and hashCode; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700363
364
365def verify_parcelable(clazz):
366 """Verify that Parcelable objects aren't hiding required bits."""
367 if "implements android.os.Parcelable" in clazz.raw:
368 creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
369 write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
370 describe = [ i for i in clazz.methods if i.name == "describeContents" ]
371
372 if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700373 error(clazz, None, "Parcelable requires CREATOR, writeToParcel, and describeContents; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700374
375
376def verify_protected(clazz):
377 """Verify that no protected methods are allowed."""
378 for m in clazz.methods:
379 if "protected" in m.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700380 error(clazz, m, "No protected methods; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700381 for f in clazz.fields:
382 if "protected" in f.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700383 error(clazz, f, "No protected fields; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700384
385
386def verify_fields(clazz):
387 """Verify that all exposed fields are final.
388 Exposed fields must follow myName style.
389 Catch internal mFoo objects being exposed."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700390
391 IGNORE_BARE_FIELDS = [
392 "android.app.ActivityManager.RecentTaskInfo",
393 "android.app.Notification",
394 "android.content.pm.ActivityInfo",
395 "android.content.pm.ApplicationInfo",
396 "android.content.pm.FeatureGroupInfo",
397 "android.content.pm.InstrumentationInfo",
398 "android.content.pm.PackageInfo",
399 "android.content.pm.PackageItemInfo",
400 "android.os.Message",
401 "android.system.StructPollfd",
402 ]
403
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700404 for f in clazz.fields:
405 if not "final" in f.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700406 if clazz.fullname in IGNORE_BARE_FIELDS:
407 pass
408 elif clazz.fullname.endswith("LayoutParams"):
409 pass
410 elif clazz.fullname.startswith("android.util.Mutable"):
411 pass
412 else:
413 error(clazz, f, "Bare fields must be marked final; consider adding accessors")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700414
415 if not "static" in f.split:
416 if not re.match("[a-z]([a-zA-Z]+)?", f.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700417 error(clazz, f, "Non-static fields must be named with myField style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700418
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700419 if re.match("[ms][A-Z]", f.name):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700420 error(clazz, f, "Don't expose your internal objects")
421
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700422 if re.match("[A-Z_]+", f.name):
423 if "static" not in f.split or "final" not in f.split:
424 error(clazz, f, "Constants must be marked static final")
425
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700426
427def verify_register(clazz):
428 """Verify parity of registration methods.
429 Callback objects use register/unregister methods.
430 Listener objects use add/remove methods."""
431 methods = [ m.name for m in clazz.methods ]
432 for m in clazz.methods:
433 if "Callback" in m.raw:
434 if m.name.startswith("register"):
435 other = "unregister" + m.name[8:]
436 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700437 error(clazz, m, "Missing unregister method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700438 if m.name.startswith("unregister"):
439 other = "register" + m.name[10:]
440 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700441 error(clazz, m, "Missing register method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700442
443 if m.name.startswith("add") or m.name.startswith("remove"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700444 error(clazz, m, "Callback methods should be named register/unregister")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700445
446 if "Listener" in m.raw:
447 if m.name.startswith("add"):
448 other = "remove" + m.name[3:]
449 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700450 error(clazz, m, "Missing remove method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700451 if m.name.startswith("remove") and not m.name.startswith("removeAll"):
452 other = "add" + m.name[6:]
453 if other not in methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700454 error(clazz, m, "Missing add method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700455
456 if m.name.startswith("register") or m.name.startswith("unregister"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700457 error(clazz, m, "Listener methods should be named add/remove")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700458
459
460def verify_sync(clazz):
461 """Verify synchronized methods aren't exposed."""
462 for m in clazz.methods:
463 if "synchronized" in m.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700464 error(clazz, m, "Internal lock exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700465
466
467def verify_intent_builder(clazz):
468 """Verify that Intent builders are createFooIntent() style."""
469 if clazz.name == "Intent": return
470
471 for m in clazz.methods:
472 if m.typ == "android.content.Intent":
473 if m.name.startswith("create") and m.name.endswith("Intent"):
474 pass
475 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700476 error(clazz, m, "Methods creating an Intent should be named createFooIntent()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700477
478
479def verify_helper_classes(clazz):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700480 """Verify that helper classes are named consistently with what they extend.
481 All developer extendable methods should be named onFoo()."""
482 test_methods = False
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700483 if "extends android.app.Service" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700484 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700485 if not clazz.name.endswith("Service"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700486 error(clazz, None, "Inconsistent class name; should be FooService")
487
488 found = False
489 for f in clazz.fields:
490 if f.name == "SERVICE_INTERFACE":
491 found = True
492 if f.value != clazz.fullname:
493 error(clazz, f, "Inconsistent interface constant; expected %s" % (clazz.fullname))
494
495 if not found:
496 warn(clazz, None, "Missing SERVICE_INTERFACE constant")
497
498 if "abstract" in clazz.split and not clazz.fullname.startswith("android.service."):
499 warn(clazz, None, "Services extended by developers should be under android.service")
500
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700501 if "extends android.content.ContentProvider" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700502 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700503 if not clazz.name.endswith("Provider"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700504 error(clazz, None, "Inconsistent class name; should be FooProvider")
505
506 found = False
507 for f in clazz.fields:
508 if f.name == "PROVIDER_INTERFACE":
509 found = True
510 if f.value != clazz.fullname:
511 error(clazz, f, "Inconsistent interface name; expected %s" % (clazz.fullname))
512
513 if not found:
514 warn(clazz, None, "Missing PROVIDER_INTERFACE constant")
515
516 if "abstract" in clazz.split and not clazz.fullname.startswith("android.provider."):
517 warn(clazz, None, "Providers extended by developers should be under android.provider")
518
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700519 if "extends android.content.BroadcastReceiver" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700520 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700521 if not clazz.name.endswith("Receiver"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700522 error(clazz, None, "Inconsistent class name; should be FooReceiver")
523
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700524 if "extends android.app.Activity" in clazz.raw:
525 test_methods = True
526 if not clazz.name.endswith("Activity"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700527 error(clazz, None, "Inconsistent class name; should be FooActivity")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700528
529 if test_methods:
530 for m in clazz.methods:
531 if "final" in m.split: continue
532 if not re.match("on[A-Z]", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700533 if "abstract" in m.split:
534 error(clazz, m, "Methods implemented by developers must be named onFoo()")
535 else:
536 warn(clazz, m, "If implemented by developer, should be named onFoo(); otherwise consider marking final")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700537
538
539def verify_builder(clazz):
540 """Verify builder classes.
541 Methods should return the builder to enable chaining."""
542 if " extends " in clazz.raw: return
543 if not clazz.name.endswith("Builder"): return
544
545 if clazz.name != "Builder":
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700546 warn(clazz, None, "Builder should be defined as inner class")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700547
548 has_build = False
549 for m in clazz.methods:
550 if m.name == "build":
551 has_build = True
552 continue
553
554 if m.name.startswith("get"): continue
555 if m.name.startswith("clear"): continue
556
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700557 if m.name.startswith("with"):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700558 error(clazz, m, "Builder methods names must follow setFoo() style")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700559
560 if m.name.startswith("set"):
561 if not m.typ.endswith(clazz.fullname):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700562 warn(clazz, m, "Methods should return the builder")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700563
564 if not has_build:
565 warn(clazz, None, "Missing build() method")
566
567
568def verify_aidl(clazz):
569 """Catch people exposing raw AIDL."""
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700570 if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700571 error(clazz, None, "Exposing raw AIDL interface")
572
573
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700574def verify_internal(clazz):
575 """Catch people exposing internal classes."""
576 if clazz.pkg.name.startswith("com.android"):
577 error(clazz, None, "Exposing internal class")
578
579
580def verify_layering(clazz):
581 """Catch package layering violations.
582 For example, something in android.os depending on android.app."""
583 ranking = [
584 ["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
585 "android.app",
586 "android.widget",
587 "android.view",
588 "android.animation",
589 "android.provider",
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700590 ["android.content","android.graphics.drawable"],
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700591 "android.database",
592 "android.graphics",
593 "android.text",
594 "android.os",
595 "android.util"
596 ]
597
598 def rank(p):
599 for i in range(len(ranking)):
600 if isinstance(ranking[i], list):
601 for j in ranking[i]:
602 if p.startswith(j): return i
603 else:
604 if p.startswith(ranking[i]): return i
605
606 cr = rank(clazz.pkg.name)
607 if cr is None: return
608
609 for f in clazz.fields:
610 ir = rank(f.typ)
611 if ir and ir < cr:
612 warn(clazz, f, "Field type violates package layering")
613
614 for m in clazz.methods:
615 ir = rank(m.typ)
616 if ir and ir < cr:
617 warn(clazz, m, "Method return type violates package layering")
618 for arg in m.args:
619 ir = rank(arg)
620 if ir and ir < cr:
621 warn(clazz, m, "Method argument type violates package layering")
622
623
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700624def verify_boolean(clazz, api):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700625 """Catches people returning boolean from getFoo() style methods.
626 Ignores when matching setFoo() is present."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700627
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700628 methods = [ m.name for m in clazz.methods ]
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700629
630 builder = clazz.fullname + ".Builder"
631 builder_methods = []
632 if builder in api:
633 builder_methods = [ m.name for m in api[builder].methods ]
634
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700635 for m in clazz.methods:
636 if m.typ == "boolean" and m.name.startswith("get") and m.name != "get" and len(m.args) == 0:
637 setter = "set" + m.name[3:]
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700638 if setter in methods:
639 pass
640 elif builder is not None and setter in builder_methods:
641 pass
642 else:
643 warn(clazz, m, "Methods returning boolean should be named isFoo, hasFoo, areFoo")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700644
645
646def verify_collections(clazz):
647 """Verifies that collection types are interfaces."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700648 if clazz.fullname == "android.os.Bundle": return
649
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700650 bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
651 "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
652 for m in clazz.methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700653 if m.typ in bad:
654 error(clazz, m, "Return type is concrete collection; should be interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700655 for arg in m.args:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700656 if arg in bad:
657 error(clazz, m, "Argument is concrete collection; should be interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700658
659
660def verify_flags(clazz):
661 """Verifies that flags are non-overlapping."""
662 known = collections.defaultdict(int)
663 for f in clazz.fields:
664 if "FLAG_" in f.name:
665 try:
666 val = int(f.value)
667 except:
668 continue
669
670 scope = f.name[0:f.name.index("FLAG_")]
671 if val & known[scope]:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700672 warn(clazz, f, "Found overlapping flag constant value")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700673 known[scope] |= val
674
675
Jeff Sharkey037458a2014-09-04 15:46:20 -0700676def verify_style(api):
677 """Find all style issues in the given API level."""
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700678 global failures
679
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700680 failures = {}
681 for key in sorted(api.keys()):
682 clazz = api[key]
683
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700684 if clazz.pkg.name.startswith("java"): continue
685 if clazz.pkg.name.startswith("junit"): continue
686 if clazz.pkg.name.startswith("org.apache"): continue
687 if clazz.pkg.name.startswith("org.xml"): continue
688 if clazz.pkg.name.startswith("org.json"): continue
689 if clazz.pkg.name.startswith("org.w3c"): continue
690
691 verify_constants(clazz)
692 verify_enums(clazz)
693 verify_class_names(clazz)
694 verify_method_names(clazz)
695 verify_callbacks(clazz)
696 verify_listeners(clazz)
697 verify_actions(clazz)
698 verify_extras(clazz)
699 verify_equals(clazz)
700 verify_parcelable(clazz)
701 verify_protected(clazz)
702 verify_fields(clazz)
703 verify_register(clazz)
704 verify_sync(clazz)
705 verify_intent_builder(clazz)
706 verify_helper_classes(clazz)
707 verify_builder(clazz)
708 verify_aidl(clazz)
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700709 verify_internal(clazz)
710 verify_layering(clazz)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700711 verify_boolean(clazz, api)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700712 verify_collections(clazz)
713 verify_flags(clazz)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700714
715 return failures
716
717
Jeff Sharkey037458a2014-09-04 15:46:20 -0700718def verify_compat(cur, prev):
719 """Find any incompatible API changes between two levels."""
720 global failures
721
722 def class_exists(api, test):
723 return test.fullname in api
724
725 def ctor_exists(api, clazz, test):
726 for m in clazz.ctors:
727 if m.ident == test.ident: return True
728 return False
729
730 def all_methods(api, clazz):
731 methods = list(clazz.methods)
732 if clazz.extends is not None:
733 methods.extend(all_methods(api, api[clazz.extends]))
734 return methods
735
736 def method_exists(api, clazz, test):
737 methods = all_methods(api, clazz)
738 for m in methods:
739 if m.ident == test.ident: return True
740 return False
741
742 def field_exists(api, clazz, test):
743 for f in clazz.fields:
744 if f.ident == test.ident: return True
745 return False
746
747 failures = {}
748 for key in sorted(prev.keys()):
749 prev_clazz = prev[key]
750
751 if not class_exists(cur, prev_clazz):
752 error(prev_clazz, None, "Class removed or incompatible change")
753 continue
754
755 cur_clazz = cur[key]
756
757 for test in prev_clazz.ctors:
758 if not ctor_exists(cur, cur_clazz, test):
759 error(prev_clazz, prev_ctor, "Constructor removed or incompatible change")
760
761 methods = all_methods(prev, prev_clazz)
762 for test in methods:
763 if not method_exists(cur, cur_clazz, test):
764 error(prev_clazz, test, "Method removed or incompatible change")
765
766 for test in prev_clazz.fields:
767 if not field_exists(cur, cur_clazz, test):
768 error(prev_clazz, test, "Field removed or incompatible change")
769
770 return failures
771
772
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700773cur = parse_api(sys.argv[1])
Jeff Sharkey037458a2014-09-04 15:46:20 -0700774cur_fail = verify_style(cur)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700775
776if len(sys.argv) > 2:
777 prev = parse_api(sys.argv[2])
Jeff Sharkey037458a2014-09-04 15:46:20 -0700778 prev_fail = verify_style(prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700779
780 # ignore errors from previous API level
781 for p in prev_fail:
782 if p in cur_fail:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700783 del cur_fail[p]
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700784
Jeff Sharkey037458a2014-09-04 15:46:20 -0700785 # look for compatibility issues
786 compat_fail = verify_compat(cur, prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700787
Jeff Sharkey037458a2014-09-04 15:46:20 -0700788 print "%s API compatibility issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
789 for f in sorted(compat_fail):
790 print compat_fail[f]
791 print
792
793
794print "%s API style issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700795for f in sorted(cur_fail):
796 print cur_fail[f]
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700797 print