blob: 8af4f507684a70c09f5df2b4ebdf833bf66f0e56 [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 Sharkeyed6aaf02015-01-30 13:31:45 -070051 def __init__(self, clazz, line, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -070052 self.clazz = clazz
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -070053 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -070054 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070055 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -070056
57 raw = raw.split()
58 self.split = list(raw)
59
60 for r in ["field", "volatile", "transient", "public", "protected", "static", "final", "deprecated"]:
61 while r in raw: raw.remove(r)
62
63 self.typ = raw[0]
64 self.name = raw[1].strip(";")
65 if len(raw) >= 4 and raw[2] == "=":
66 self.value = raw[3].strip(';"')
67 else:
68 self.value = None
69
Jeff Sharkey037458a2014-09-04 15:46:20 -070070 self.ident = self.raw.replace(" deprecated ", " ")
71
Jeff Sharkey8190f4882014-08-28 12:24:07 -070072 def __repr__(self):
73 return self.raw
74
75
76class Method():
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -070077 def __init__(self, clazz, line, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -070078 self.clazz = clazz
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -070079 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -070080 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070081 self.blame = blame
82
83 # drop generics for now
84 raw = re.sub("<.+?>", "", raw)
Jeff Sharkey8190f4882014-08-28 12:24:07 -070085
86 raw = re.split("[\s(),;]+", raw)
87 for r in ["", ";"]:
88 while r in raw: raw.remove(r)
89 self.split = list(raw)
90
91 for r in ["method", "public", "protected", "static", "final", "deprecated", "abstract"]:
92 while r in raw: raw.remove(r)
93
94 self.typ = raw[0]
95 self.name = raw[1]
96 self.args = []
97 for r in raw[2:]:
98 if r == "throws": break
99 self.args.append(r)
100
Jeff Sharkey037458a2014-09-04 15:46:20 -0700101 # identity for compat purposes
102 ident = self.raw
103 ident = ident.replace(" deprecated ", " ")
104 ident = ident.replace(" synchronized ", " ")
105 ident = re.sub("<.+?>", "", ident)
106 if " throws " in ident:
107 ident = ident[:ident.index(" throws ")]
108 self.ident = ident
109
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700110 def __repr__(self):
111 return self.raw
112
113
114class Class():
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700115 def __init__(self, pkg, line, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700116 self.pkg = pkg
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700117 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700118 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700119 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700120 self.ctors = []
121 self.fields = []
122 self.methods = []
123
124 raw = raw.split()
125 self.split = list(raw)
126 if "class" in raw:
127 self.fullname = raw[raw.index("class")+1]
128 elif "interface" in raw:
129 self.fullname = raw[raw.index("interface")+1]
Jeff Sharkey037458a2014-09-04 15:46:20 -0700130 else:
131 raise ValueError("Funky class type %s" % (self.raw))
132
133 if "extends" in raw:
134 self.extends = raw[raw.index("extends")+1]
135 else:
136 self.extends = None
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700137
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700138 self.fullname = self.pkg.name + "." + self.fullname
139 self.name = self.fullname[self.fullname.rindex(".")+1:]
140
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700141 def __repr__(self):
142 return self.raw
143
144
145class Package():
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700146 def __init__(self, line, raw, blame):
147 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700148 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700149 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700150
151 raw = raw.split()
152 self.name = raw[raw.index("package")+1]
153
154 def __repr__(self):
155 return self.raw
156
157
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800158def _parse_stream(f, clazz_cb=None):
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700159 line = 0
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700160 api = {}
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700161 pkg = None
162 clazz = None
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700163 blame = None
164
165 re_blame = re.compile("^([a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800166 for raw in f:
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700167 line += 1
168 raw = raw.rstrip()
169 match = re_blame.match(raw)
170 if match is not None:
171 blame = match.groups()[0:2]
172 raw = match.groups()[2]
173 else:
174 blame = None
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700175
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700176 if raw.startswith("package"):
177 pkg = Package(line, raw, blame)
178 elif raw.startswith(" ") and raw.endswith("{"):
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800179 # When provided with class callback, we treat as incremental
180 # parse and don't build up entire API
181 if clazz and clazz_cb:
182 clazz_cb(clazz)
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700183 clazz = Class(pkg, line, raw, blame)
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800184 if not clazz_cb:
185 api[clazz.fullname] = clazz
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700186 elif raw.startswith(" ctor"):
187 clazz.ctors.append(Method(clazz, line, raw, blame))
188 elif raw.startswith(" method"):
189 clazz.methods.append(Method(clazz, line, raw, blame))
190 elif raw.startswith(" field"):
191 clazz.fields.append(Field(clazz, line, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700192
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800193 # Handle last trailing class
194 if clazz and clazz_cb:
195 clazz_cb(clazz)
196
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700197 return api
198
199
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700200class Failure():
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800201 def __init__(self, sig, clazz, detail, error, rule, msg):
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700202 self.sig = sig
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700203 self.error = error
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800204 self.rule = rule
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700205 self.msg = msg
206
207 if error:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800208 self.head = "Error %s" % (rule) if rule else "Error"
209 dump = "%s%s:%s %s" % (format(fg=RED, bg=BLACK, bold=True), self.head, format(reset=True), msg)
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700210 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800211 self.head = "Warning %s" % (rule) if rule else "Warning"
212 dump = "%s%s:%s %s" % (format(fg=YELLOW, bg=BLACK, bold=True), self.head, format(reset=True), msg)
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700213
214 self.line = clazz.line
215 blame = clazz.blame
216 if detail is not None:
217 dump += "\n in " + repr(detail)
218 self.line = detail.line
219 blame = detail.blame
220 dump += "\n in " + repr(clazz)
221 dump += "\n in " + repr(clazz.pkg)
222 dump += "\n at line " + repr(self.line)
223 if blame is not None:
224 dump += "\n last modified by %s in %s" % (blame[1], blame[0])
225
226 self.dump = dump
227
228 def __repr__(self):
229 return self.dump
230
231
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700232failures = {}
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700233
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800234def _fail(clazz, detail, error, rule, msg):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700235 """Records an API failure to be processed later."""
236 global failures
237
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700238 sig = "%s-%s-%s" % (clazz.fullname, repr(detail), msg)
239 sig = sig.replace(" deprecated ", " ")
240
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800241 failures[sig] = Failure(sig, clazz, detail, error, rule, msg)
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700242
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700243
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800244def warn(clazz, detail, rule, msg):
245 _fail(clazz, detail, False, rule, msg)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700246
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800247def error(clazz, detail, rule, msg):
248 _fail(clazz, detail, True, rule, msg)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700249
250
251def verify_constants(clazz):
252 """All static final constants must be FOO_NAME style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700253 if re.match("android\.R\.[a-z]+", clazz.fullname): return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700254
255 for f in clazz.fields:
256 if "static" in f.split and "final" in f.split:
257 if re.match("[A-Z0-9_]+", f.name) is None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800258 error(clazz, f, "C2", "Constant field names must be FOO_NAME")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700259
260
261def verify_enums(clazz):
262 """Enums are bad, mmkay?"""
263 if "extends java.lang.Enum" in clazz.raw:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800264 error(clazz, None, "F5", "Enums are not allowed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700265
266
267def verify_class_names(clazz):
268 """Try catching malformed class names like myMtp or MTPUser."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700269 if clazz.fullname.startswith("android.opengl"): return
270 if clazz.fullname.startswith("android.renderscript"): return
271 if re.match("android\.R\.[a-z]+", clazz.fullname): return
272
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700273 if re.search("[A-Z]{2,}", clazz.name) is not None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800274 warn(clazz, None, "S1", "Class names with acronyms should be Mtp not MTP")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700275 if re.match("[^A-Z]", clazz.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800276 error(clazz, None, "S1", "Class must start with uppercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700277
278
279def verify_method_names(clazz):
280 """Try catching malformed method names, like Foo() or getMTU()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700281 if clazz.fullname.startswith("android.opengl"): return
282 if clazz.fullname.startswith("android.renderscript"): return
283 if clazz.fullname == "android.system.OsConstants": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700284
285 for m in clazz.methods:
286 if re.search("[A-Z]{2,}", m.name) is not None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800287 warn(clazz, m, "S1", "Method names with acronyms should be getMtu() instead of getMTU()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700288 if re.match("[^a-z]", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800289 error(clazz, m, "S1", "Method name must start with lowercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700290
291
292def verify_callbacks(clazz):
293 """Verify Callback classes.
294 All callback classes must be abstract.
295 All methods must follow onFoo() naming style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700296 if clazz.fullname == "android.speech.tts.SynthesisCallback": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700297
298 if clazz.name.endswith("Callbacks"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800299 error(clazz, None, "L1", "Callback class names should be singular")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700300 if clazz.name.endswith("Observer"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800301 warn(clazz, None, "L1", "Class should be named FooCallback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700302
303 if clazz.name.endswith("Callback"):
304 if "interface" in clazz.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800305 error(clazz, None, "CL3", "Callbacks must be abstract class to enable extension in future API levels")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700306
307 for m in clazz.methods:
308 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800309 error(clazz, m, "L1", "Callback method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700310
311
312def verify_listeners(clazz):
313 """Verify Listener classes.
314 All Listener classes must be interface.
315 All methods must follow onFoo() naming style.
316 If only a single method, it must match class name:
317 interface OnFooListener { void onFoo() }"""
318
319 if clazz.name.endswith("Listener"):
320 if " abstract class " in clazz.raw:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800321 error(clazz, None, "L1", "Listeners should be an interface, or otherwise renamed Callback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700322
323 for m in clazz.methods:
324 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800325 error(clazz, m, "L1", "Listener method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700326
327 if len(clazz.methods) == 1 and clazz.name.startswith("On"):
328 m = clazz.methods[0]
329 if (m.name + "Listener").lower() != clazz.name.lower():
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800330 error(clazz, m, "L1", "Single listener method name must match class name")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700331
332
333def verify_actions(clazz):
334 """Verify intent actions.
335 All action names must be named ACTION_FOO.
336 All action values must be scoped by package and match name:
337 package android.foo {
338 String ACTION_BAR = "android.foo.action.BAR";
339 }"""
340 for f in clazz.fields:
341 if f.value is None: continue
342 if f.name.startswith("EXTRA_"): continue
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700343 if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": continue
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700344
345 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
346 if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
347 if not f.name.startswith("ACTION_"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800348 error(clazz, f, "C3", "Intent action constant name must be ACTION_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700349 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700350 if clazz.fullname == "android.content.Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700351 prefix = "android.intent.action"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700352 elif clazz.fullname == "android.provider.Settings":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700353 prefix = "android.settings"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700354 elif clazz.fullname == "android.app.admin.DevicePolicyManager" or clazz.fullname == "android.app.admin.DeviceAdminReceiver":
355 prefix = "android.app.action"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700356 else:
357 prefix = clazz.pkg.name + ".action"
358 expected = prefix + "." + f.name[7:]
359 if f.value != expected:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800360 error(clazz, f, "C4", "Inconsistent action value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700361
362
363def verify_extras(clazz):
364 """Verify intent extras.
365 All extra names must be named EXTRA_FOO.
366 All extra values must be scoped by package and match name:
367 package android.foo {
368 String EXTRA_BAR = "android.foo.extra.BAR";
369 }"""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700370 if clazz.fullname == "android.app.Notification": return
371 if clazz.fullname == "android.appwidget.AppWidgetManager": return
372
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700373 for f in clazz.fields:
374 if f.value is None: continue
375 if f.name.startswith("ACTION_"): continue
376
377 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
378 if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
379 if not f.name.startswith("EXTRA_"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800380 error(clazz, f, "C3", "Intent extra must be EXTRA_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700381 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700382 if clazz.pkg.name == "android.content" and clazz.name == "Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700383 prefix = "android.intent.extra"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700384 elif clazz.pkg.name == "android.app.admin":
385 prefix = "android.app.extra"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700386 else:
387 prefix = clazz.pkg.name + ".extra"
388 expected = prefix + "." + f.name[6:]
389 if f.value != expected:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800390 error(clazz, f, "C4", "Inconsistent extra value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700391
392
393def verify_equals(clazz):
394 """Verify that equals() and hashCode() must be overridden together."""
395 methods = [ m.name for m in clazz.methods ]
396 eq = "equals" in methods
397 hc = "hashCode" in methods
398 if eq != hc:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800399 error(clazz, None, "M8", "Must override both equals and hashCode; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700400
401
402def verify_parcelable(clazz):
403 """Verify that Parcelable objects aren't hiding required bits."""
404 if "implements android.os.Parcelable" in clazz.raw:
405 creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
406 write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
407 describe = [ i for i in clazz.methods if i.name == "describeContents" ]
408
409 if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800410 error(clazz, None, "FW3", "Parcelable requires CREATOR, writeToParcel, and describeContents; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700411
412
413def verify_protected(clazz):
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800414 """Verify that no protected methods or fields are allowed."""
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700415 for m in clazz.methods:
416 if "protected" in m.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800417 error(clazz, m, "M7", "Protected methods not allowed; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700418 for f in clazz.fields:
419 if "protected" in f.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800420 error(clazz, f, "M7", "Protected fields not allowed; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700421
422
423def verify_fields(clazz):
424 """Verify that all exposed fields are final.
425 Exposed fields must follow myName style.
426 Catch internal mFoo objects being exposed."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700427
428 IGNORE_BARE_FIELDS = [
429 "android.app.ActivityManager.RecentTaskInfo",
430 "android.app.Notification",
431 "android.content.pm.ActivityInfo",
432 "android.content.pm.ApplicationInfo",
433 "android.content.pm.FeatureGroupInfo",
434 "android.content.pm.InstrumentationInfo",
435 "android.content.pm.PackageInfo",
436 "android.content.pm.PackageItemInfo",
437 "android.os.Message",
438 "android.system.StructPollfd",
439 ]
440
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700441 for f in clazz.fields:
442 if not "final" in f.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700443 if clazz.fullname in IGNORE_BARE_FIELDS:
444 pass
445 elif clazz.fullname.endswith("LayoutParams"):
446 pass
447 elif clazz.fullname.startswith("android.util.Mutable"):
448 pass
449 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800450 error(clazz, f, "F2", "Bare fields must be marked final, or add accessors if mutable")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700451
452 if not "static" in f.split:
453 if not re.match("[a-z]([a-zA-Z]+)?", f.name):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800454 error(clazz, f, "S1", "Non-static fields must be named using myField style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700455
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700456 if re.match("[ms][A-Z]", f.name):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800457 error(clazz, f, "F1", "Internal objects must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700458
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700459 if re.match("[A-Z_]+", f.name):
460 if "static" not in f.split or "final" not in f.split:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800461 error(clazz, f, "C2", "Constants must be marked static final")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700462
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700463
464def verify_register(clazz):
465 """Verify parity of registration methods.
466 Callback objects use register/unregister methods.
467 Listener objects use add/remove methods."""
468 methods = [ m.name for m in clazz.methods ]
469 for m in clazz.methods:
470 if "Callback" in m.raw:
471 if m.name.startswith("register"):
472 other = "unregister" + m.name[8:]
473 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800474 error(clazz, m, "L2", "Missing unregister method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700475 if m.name.startswith("unregister"):
476 other = "register" + m.name[10:]
477 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800478 error(clazz, m, "L2", "Missing register method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700479
480 if m.name.startswith("add") or m.name.startswith("remove"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800481 error(clazz, m, "L3", "Callback methods should be named register/unregister")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700482
483 if "Listener" in m.raw:
484 if m.name.startswith("add"):
485 other = "remove" + m.name[3:]
486 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800487 error(clazz, m, "L2", "Missing remove method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700488 if m.name.startswith("remove") and not m.name.startswith("removeAll"):
489 other = "add" + m.name[6:]
490 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800491 error(clazz, m, "L2", "Missing add method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700492
493 if m.name.startswith("register") or m.name.startswith("unregister"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800494 error(clazz, m, "L3", "Listener methods should be named add/remove")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700495
496
497def verify_sync(clazz):
498 """Verify synchronized methods aren't exposed."""
499 for m in clazz.methods:
500 if "synchronized" in m.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800501 error(clazz, m, "M5", "Internal locks must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700502
503
504def verify_intent_builder(clazz):
505 """Verify that Intent builders are createFooIntent() style."""
506 if clazz.name == "Intent": return
507
508 for m in clazz.methods:
509 if m.typ == "android.content.Intent":
510 if m.name.startswith("create") and m.name.endswith("Intent"):
511 pass
512 else:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800513 error(clazz, m, "FW1", "Methods creating an Intent must be named createFooIntent()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700514
515
516def verify_helper_classes(clazz):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700517 """Verify that helper classes are named consistently with what they extend.
518 All developer extendable methods should be named onFoo()."""
519 test_methods = False
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700520 if "extends android.app.Service" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700521 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700522 if not clazz.name.endswith("Service"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800523 error(clazz, None, "CL4", "Inconsistent class name; should be FooService")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700524
525 found = False
526 for f in clazz.fields:
527 if f.name == "SERVICE_INTERFACE":
528 found = True
529 if f.value != clazz.fullname:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800530 error(clazz, f, "C4", "Inconsistent interface constant; expected %s" % (clazz.fullname))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700531
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700532 if "extends android.content.ContentProvider" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700533 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700534 if not clazz.name.endswith("Provider"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800535 error(clazz, None, "CL4", "Inconsistent class name; should be FooProvider")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700536
537 found = False
538 for f in clazz.fields:
539 if f.name == "PROVIDER_INTERFACE":
540 found = True
541 if f.value != clazz.fullname:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800542 error(clazz, f, "C4", "Inconsistent interface constant; expected %s" % (clazz.fullname))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700543
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700544 if "extends android.content.BroadcastReceiver" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700545 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700546 if not clazz.name.endswith("Receiver"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800547 error(clazz, None, "CL4", "Inconsistent class name; should be FooReceiver")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700548
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700549 if "extends android.app.Activity" in clazz.raw:
550 test_methods = True
551 if not clazz.name.endswith("Activity"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800552 error(clazz, None, "CL4", "Inconsistent class name; should be FooActivity")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700553
554 if test_methods:
555 for m in clazz.methods:
556 if "final" in m.split: continue
557 if not re.match("on[A-Z]", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700558 if "abstract" in m.split:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800559 warn(clazz, m, None, "Methods implemented by developers should be named onFoo()")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700560 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800561 warn(clazz, m, None, "If implemented by developer, should be named onFoo(); otherwise consider marking final")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700562
563
564def verify_builder(clazz):
565 """Verify builder classes.
566 Methods should return the builder to enable chaining."""
567 if " extends " in clazz.raw: return
568 if not clazz.name.endswith("Builder"): return
569
570 if clazz.name != "Builder":
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800571 warn(clazz, None, None, "Builder should be defined as inner class")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700572
573 has_build = False
574 for m in clazz.methods:
575 if m.name == "build":
576 has_build = True
577 continue
578
579 if m.name.startswith("get"): continue
580 if m.name.startswith("clear"): continue
581
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700582 if m.name.startswith("with"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800583 warn(clazz, m, None, "Builder methods names should use setFoo() style")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700584
585 if m.name.startswith("set"):
586 if not m.typ.endswith(clazz.fullname):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800587 warn(clazz, m, "M4", "Methods must return the builder object")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700588
589 if not has_build:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800590 warn(clazz, None, None, "Missing build() method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700591
592
593def verify_aidl(clazz):
594 """Catch people exposing raw AIDL."""
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700595 if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800596 error(clazz, None, None, "Raw AIDL interfaces must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700597
598
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700599def verify_internal(clazz):
600 """Catch people exposing internal classes."""
601 if clazz.pkg.name.startswith("com.android"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800602 error(clazz, None, None, "Internal classes must not be exposed")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700603
604
605def verify_layering(clazz):
606 """Catch package layering violations.
607 For example, something in android.os depending on android.app."""
608 ranking = [
609 ["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
610 "android.app",
611 "android.widget",
612 "android.view",
613 "android.animation",
614 "android.provider",
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700615 ["android.content","android.graphics.drawable"],
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700616 "android.database",
617 "android.graphics",
618 "android.text",
619 "android.os",
620 "android.util"
621 ]
622
623 def rank(p):
624 for i in range(len(ranking)):
625 if isinstance(ranking[i], list):
626 for j in ranking[i]:
627 if p.startswith(j): return i
628 else:
629 if p.startswith(ranking[i]): return i
630
631 cr = rank(clazz.pkg.name)
632 if cr is None: return
633
634 for f in clazz.fields:
635 ir = rank(f.typ)
636 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800637 warn(clazz, f, "FW6", "Field type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700638
639 for m in clazz.methods:
640 ir = rank(m.typ)
641 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800642 warn(clazz, m, "FW6", "Method return type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700643 for arg in m.args:
644 ir = rank(arg)
645 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800646 warn(clazz, m, "FW6", "Method argument type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700647
648
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800649def verify_boolean(clazz):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800650 """Verifies that boolean accessors are named correctly.
651 For example, hasFoo() and setHasFoo()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700652
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800653 def is_get(m): return len(m.args) == 0 and m.typ == "boolean"
654 def is_set(m): return len(m.args) == 1 and m.args[0] == "boolean"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700655
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800656 gets = [ m for m in clazz.methods if is_get(m) ]
657 sets = [ m for m in clazz.methods if is_set(m) ]
658
659 def error_if_exists(methods, trigger, expected, actual):
660 for m in methods:
661 if m.name == actual:
662 error(clazz, m, "M6", "Symmetric method for %s must be named %s" % (trigger, expected))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700663
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700664 for m in clazz.methods:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800665 if is_get(m):
666 if re.match("is[A-Z]", m.name):
667 target = m.name[2:]
668 expected = "setIs" + target
669 error_if_exists(sets, m.name, expected, "setHas" + target)
670 elif re.match("has[A-Z]", m.name):
671 target = m.name[3:]
672 expected = "setHas" + target
673 error_if_exists(sets, m.name, expected, "setIs" + target)
674 error_if_exists(sets, m.name, expected, "set" + target)
675 elif re.match("get[A-Z]", m.name):
676 target = m.name[3:]
677 expected = "set" + target
678 error_if_exists(sets, m.name, expected, "setIs" + target)
679 error_if_exists(sets, m.name, expected, "setHas" + target)
680
681 if is_set(m):
682 if re.match("set[A-Z]", m.name):
683 target = m.name[3:]
684 expected = "get" + target
685 error_if_exists(sets, m.name, expected, "is" + target)
686 error_if_exists(sets, m.name, expected, "has" + target)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700687
688
689def verify_collections(clazz):
690 """Verifies that collection types are interfaces."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700691 if clazz.fullname == "android.os.Bundle": return
692
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700693 bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
694 "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
695 for m in clazz.methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700696 if m.typ in bad:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800697 error(clazz, m, "CL2", "Return type is concrete collection; must be higher-level interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700698 for arg in m.args:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700699 if arg in bad:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800700 error(clazz, m, "CL2", "Argument is concrete collection; must be higher-level interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700701
702
703def verify_flags(clazz):
704 """Verifies that flags are non-overlapping."""
705 known = collections.defaultdict(int)
706 for f in clazz.fields:
707 if "FLAG_" in f.name:
708 try:
709 val = int(f.value)
710 except:
711 continue
712
713 scope = f.name[0:f.name.index("FLAG_")]
714 if val & known[scope]:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800715 warn(clazz, f, "C1", "Found overlapping flag constant value")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700716 known[scope] |= val
717
718
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800719def verify_exception(clazz):
720 """Verifies that methods don't throw generic exceptions."""
721 for m in clazz.methods:
722 if "throws java.lang.Exception" in m.raw or "throws java.lang.Throwable" in m.raw or "throws java.lang.Error" in m.raw:
723 error(clazz, m, "S1", "Methods must not throw generic exceptions")
724
725
726def verify_google(clazz):
727 """Verifies that APIs never reference Google."""
728
729 if re.search("google", clazz.raw, re.IGNORECASE):
730 error(clazz, None, None, "Must never reference Google")
731
732 test = []
733 test.extend(clazz.ctors)
734 test.extend(clazz.fields)
735 test.extend(clazz.methods)
736
737 for t in test:
738 if re.search("google", t.raw, re.IGNORECASE):
739 error(clazz, t, None, "Must never reference Google")
740
741
742def verify_bitset(clazz):
743 """Verifies that we avoid using heavy BitSet."""
744
745 for f in clazz.fields:
746 if f.typ == "java.util.BitSet":
747 error(clazz, f, None, "Field type must not be heavy BitSet")
748
749 for m in clazz.methods:
750 if m.typ == "java.util.BitSet":
751 error(clazz, m, None, "Return type must not be heavy BitSet")
752 for arg in m.args:
753 if arg == "java.util.BitSet":
754 error(clazz, m, None, "Argument type must not be heavy BitSet")
755
756
757def verify_manager(clazz):
758 """Verifies that FooManager is only obtained from Context."""
759
760 if not clazz.name.endswith("Manager"): return
761
762 for c in clazz.ctors:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800763 error(clazz, c, None, "Managers must always be obtained from Context")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800764
765
766def verify_boxed(clazz):
767 """Verifies that methods avoid boxed primitives."""
768
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800769 boxed = ["java.lang.Number","java.lang.Byte","java.lang.Double","java.lang.Float","java.lang.Integer","java.lang.Long","java.lang.Short"]
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800770
771 for c in clazz.ctors:
772 for arg in c.args:
773 if arg in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800774 error(clazz, c, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800775
776 for f in clazz.fields:
777 if f.typ in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800778 error(clazz, f, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800779
780 for m in clazz.methods:
781 if m.typ in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800782 error(clazz, m, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800783 for arg in m.args:
784 if arg in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800785 error(clazz, m, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800786
787
788def verify_static_utils(clazz):
789 """Verifies that helper classes can't be constructed."""
790 if clazz.fullname.startswith("android.opengl"): return
791 if re.match("android\.R\.[a-z]+", clazz.fullname): return
792
793 if len(clazz.fields) > 0: return
794 if len(clazz.methods) == 0: return
795
796 for m in clazz.methods:
797 if "static" not in m.split:
798 return
799
800 # At this point, we have no fields, and all methods are static
801 if len(clazz.ctors) > 0:
802 error(clazz, None, None, "Fully-static utility classes must not have constructor")
803
804
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800805def verify_overload_args(clazz):
806 """Verifies that method overloads add new arguments at the end."""
807 if clazz.fullname.startswith("android.opengl"): return
808
809 overloads = collections.defaultdict(list)
810 for m in clazz.methods:
811 if "deprecated" in m.split: continue
812 overloads[m.name].append(m)
813
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800814 for name, methods in overloads.items():
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800815 if len(methods) <= 1: continue
816
817 # Look for arguments common across all overloads
818 def cluster(args):
819 count = collections.defaultdict(int)
820 res = set()
821 for i in range(len(args)):
822 a = args[i]
823 res.add("%s#%d" % (a, count[a]))
824 count[a] += 1
825 return res
826
827 common_args = cluster(methods[0].args)
828 for m in methods:
829 common_args = common_args & cluster(m.args)
830
831 if len(common_args) == 0: continue
832
833 # Require that all common arguments are present at start of signature
834 locked_sig = None
835 for m in methods:
836 sig = m.args[0:len(common_args)]
837 if not common_args.issubset(cluster(sig)):
838 warn(clazz, m, "M2", "Expected common arguments [%s] at beginning of overloaded method" % (", ".join(common_args)))
839 elif not locked_sig:
840 locked_sig = sig
841 elif locked_sig != sig:
842 error(clazz, m, "M2", "Expected consistent argument ordering between overloads: %s..." % (", ".join(locked_sig)))
843
844
845def verify_callback_handlers(clazz):
846 """Verifies that methods adding listener/callback have overload
847 for specifying delivery thread."""
848
849 # Ignore UI components which deliver things on main thread
850 skip = [
851 "android.animation",
852 "android.view",
853 "android.graphics",
854 "android.transition",
855 "android.widget",
856 "android.webkit",
857 ]
858 for s in skip:
859 if clazz.fullname.startswith(s): return
860 if clazz.extends and clazz.extends.startswith(s): return
861
862 skip = [
863 "android.app.ActionBar",
864 "android.app.AlertDialog",
865 "android.app.AlertDialog.Builder",
866 "android.app.Application",
867 "android.app.Activity",
868 "android.app.Dialog",
869 "android.app.Fragment",
870 "android.app.FragmentManager",
871 "android.app.LoaderManager",
872 "android.app.ListActivity",
873 "android.app.AlertDialog.Builder"
874 "android.content.Loader",
875 ]
876 for s in skip:
877 if clazz.fullname == s or clazz.extends == s: return
878
879 found = {}
880 by_name = collections.defaultdict(list)
881 for m in clazz.methods:
882 if m.name.startswith("unregister"): continue
883 if m.name.startswith("remove"): continue
884 if re.match("on[A-Z]+", m.name): continue
885
886 by_name[m.name].append(m)
887
888 for a in m.args:
889 if a.endswith("Listener") or a.endswith("Callback") or a.endswith("Callbacks"):
890 found[m.name] = m
891
892 for f in found.values():
893 takes_handler = False
894 for m in by_name[f.name]:
895 if "android.os.Handler" in m.args:
896 takes_handler = True
897 if not takes_handler:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800898 warn(clazz, f, "L1", "Registration methods should have overload that accepts delivery Handler")
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800899
900
901def verify_context_first(clazz):
902 """Verifies that methods accepting a Context keep it the first argument."""
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800903 examine = clazz.ctors + clazz.methods
904 for m in examine:
905 if len(m.args) > 1 and m.args[0] != "android.content.Context":
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800906 if "android.content.Context" in m.args[1:]:
907 error(clazz, m, "M3", "Context is distinct, so it must be the first argument")
908
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800909
910def verify_listener_last(clazz):
911 """Verifies that methods accepting a Listener or Callback keep them as last arguments."""
912 examine = clazz.ctors + clazz.methods
913 for m in examine:
914 if "Listener" in m.name or "Callback" in m.name: continue
915 found = False
916 for a in m.args:
917 if a.endswith("Callback") or a.endswith("Callbacks") or a.endswith("Listener"):
918 found = True
919 elif found and a != "android.os.Handler":
920 warn(clazz, m, "M3", "Listeners should always be at end of argument list")
921
922
923def verify_resource_names(clazz):
924 """Verifies that resource names have consistent case."""
925 if not re.match("android\.R\.[a-z]+", clazz.fullname): return
926
927 # Resources defined by files are foo_bar_baz
928 if clazz.name in ["anim","animator","color","dimen","drawable","interpolator","layout","transition","menu","mipmap","string","plurals","raw","xml"]:
929 for f in clazz.fields:
930 if re.match("[a-z1-9_]+$", f.name): continue
931 error(clazz, f, None, "Expected resource name in this class to be foo_bar_baz style")
932
933 # Resources defined inside files are fooBarBaz
934 if clazz.name in ["array","attr","id","bool","fraction","integer"]:
935 for f in clazz.fields:
936 if re.match("config_[a-z][a-zA-Z1-9]*$", f.name): continue
937 if re.match("layout_[a-z][a-zA-Z1-9]*$", f.name): continue
938 if re.match("state_[a-z_]*$", f.name): continue
939
940 if re.match("[a-z][a-zA-Z1-9]*$", f.name): continue
941 error(clazz, f, "C7", "Expected resource name in this class to be fooBarBaz style")
942
943 # Styles are FooBar_Baz
944 if clazz.name in ["style"]:
945 for f in clazz.fields:
946 if re.match("[A-Z][A-Za-z1-9]+(_[A-Z][A-Za-z1-9]+?)*$", f.name): continue
947 error(clazz, f, "C7", "Expected resource name in this class to be FooBar_Baz style")
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800948
949
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800950def examine_clazz(clazz):
951 """Find all style issues in the given class."""
952 if clazz.pkg.name.startswith("java"): return
953 if clazz.pkg.name.startswith("junit"): return
954 if clazz.pkg.name.startswith("org.apache"): return
955 if clazz.pkg.name.startswith("org.xml"): return
956 if clazz.pkg.name.startswith("org.json"): return
957 if clazz.pkg.name.startswith("org.w3c"): return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700958
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800959 verify_constants(clazz)
960 verify_enums(clazz)
961 verify_class_names(clazz)
962 verify_method_names(clazz)
963 verify_callbacks(clazz)
964 verify_listeners(clazz)
965 verify_actions(clazz)
966 verify_extras(clazz)
967 verify_equals(clazz)
968 verify_parcelable(clazz)
969 verify_protected(clazz)
970 verify_fields(clazz)
971 verify_register(clazz)
972 verify_sync(clazz)
973 verify_intent_builder(clazz)
974 verify_helper_classes(clazz)
975 verify_builder(clazz)
976 verify_aidl(clazz)
977 verify_internal(clazz)
978 verify_layering(clazz)
979 verify_boolean(clazz)
980 verify_collections(clazz)
981 verify_flags(clazz)
982 verify_exception(clazz)
983 verify_google(clazz)
984 verify_bitset(clazz)
985 verify_manager(clazz)
986 verify_boxed(clazz)
987 verify_static_utils(clazz)
988 verify_overload_args(clazz)
989 verify_callback_handlers(clazz)
990 verify_context_first(clazz)
991 verify_listener_last(clazz)
992 verify_resource_names(clazz)
993
994
995def examine_stream(stream):
996 """Find all style issues in the given API stream."""
997 global failures
998 failures = {}
999 _parse_stream(stream, examine_clazz)
1000 return failures
1001
1002
1003def examine_api(api):
1004 """Find all style issues in the given parsed API."""
1005 global failures
Jeff Sharkey1498f9c2014-09-04 12:45:33 -07001006 failures = {}
1007 for key in sorted(api.keys()):
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001008 examine_clazz(api[key])
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001009 return failures
1010
1011
Jeff Sharkey037458a2014-09-04 15:46:20 -07001012def verify_compat(cur, prev):
1013 """Find any incompatible API changes between two levels."""
1014 global failures
1015
1016 def class_exists(api, test):
1017 return test.fullname in api
1018
1019 def ctor_exists(api, clazz, test):
1020 for m in clazz.ctors:
1021 if m.ident == test.ident: return True
1022 return False
1023
1024 def all_methods(api, clazz):
1025 methods = list(clazz.methods)
1026 if clazz.extends is not None:
1027 methods.extend(all_methods(api, api[clazz.extends]))
1028 return methods
1029
1030 def method_exists(api, clazz, test):
1031 methods = all_methods(api, clazz)
1032 for m in methods:
1033 if m.ident == test.ident: return True
1034 return False
1035
1036 def field_exists(api, clazz, test):
1037 for f in clazz.fields:
1038 if f.ident == test.ident: return True
1039 return False
1040
1041 failures = {}
1042 for key in sorted(prev.keys()):
1043 prev_clazz = prev[key]
1044
1045 if not class_exists(cur, prev_clazz):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001046 error(prev_clazz, None, None, "Class removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001047 continue
1048
1049 cur_clazz = cur[key]
1050
1051 for test in prev_clazz.ctors:
1052 if not ctor_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001053 error(prev_clazz, prev_ctor, None, "Constructor removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001054
1055 methods = all_methods(prev, prev_clazz)
1056 for test in methods:
1057 if not method_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001058 error(prev_clazz, test, None, "Method removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001059
1060 for test in prev_clazz.fields:
1061 if not field_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001062 error(prev_clazz, test, None, "Field removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001063
1064 return failures
1065
1066
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001067if __name__ == "__main__":
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001068 with open(sys.argv[1]) as f:
1069 cur_fail = examine_stream(f)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001070
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001071 if len(sys.argv) > 2:
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001072 with open(sys.argv[2]) as f:
1073 prev_fail = examine_stream(f)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001074
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001075 # ignore errors from previous API level
1076 for p in prev_fail:
1077 if p in cur_fail:
1078 del cur_fail[p]
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001079
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001080 """
1081 # NOTE: disabled because of memory pressure
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001082 # look for compatibility issues
1083 compat_fail = verify_compat(cur, prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001084
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001085 print "%s API compatibility issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1086 for f in sorted(compat_fail):
1087 print compat_fail[f]
1088 print
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001089 """
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001090
1091 print "%s API style issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1092 for f in sorted(cur_fail):
1093 print cur_fail[f]
Jeff Sharkey037458a2014-09-04 15:46:20 -07001094 print