blob: 3fedea2cc08ad053a7d723cedea80d76b12763d6 [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
Adam Metcalf1c7e70a2015-03-27 16:11:23 -070029import re, sys, collections, traceback, argparse
Jeff Sharkey8190f4882014-08-28 12:24:07 -070030
31
32BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
33
Adam Metcalf1c7e70a2015-03-27 16:11:23 -070034ALLOW_GOOGLE = False
35USE_COLOR = True
36
Jeff Sharkey8190f4882014-08-28 12:24:07 -070037def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False):
38 # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes
Adam Metcalf1c7e70a2015-03-27 16:11:23 -070039 if not USE_COLOR: return ""
Jeff Sharkey8190f4882014-08-28 12:24:07 -070040 codes = []
41 if reset: codes.append("0")
42 else:
43 if not fg is None: codes.append("3%d" % (fg))
44 if not bg is None:
45 if not bright: codes.append("4%d" % (bg))
46 else: codes.append("10%d" % (bg))
47 if bold: codes.append("1")
48 elif dim: codes.append("2")
49 else: codes.append("22")
50 return "\033[%sm" % (";".join(codes))
51
52
53class Field():
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -070054 def __init__(self, clazz, line, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -070055 self.clazz = clazz
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -070056 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -070057 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070058 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -070059
60 raw = raw.split()
61 self.split = list(raw)
62
63 for r in ["field", "volatile", "transient", "public", "protected", "static", "final", "deprecated"]:
64 while r in raw: raw.remove(r)
65
66 self.typ = raw[0]
67 self.name = raw[1].strip(";")
68 if len(raw) >= 4 and raw[2] == "=":
69 self.value = raw[3].strip(';"')
70 else:
71 self.value = None
72
Jeff Sharkey037458a2014-09-04 15:46:20 -070073 self.ident = self.raw.replace(" deprecated ", " ")
74
Jeff Sharkey8190f4882014-08-28 12:24:07 -070075 def __repr__(self):
76 return self.raw
77
78
79class Method():
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -070080 def __init__(self, clazz, line, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -070081 self.clazz = clazz
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -070082 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -070083 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -070084 self.blame = blame
85
86 # drop generics for now
87 raw = re.sub("<.+?>", "", raw)
Jeff Sharkey8190f4882014-08-28 12:24:07 -070088
89 raw = re.split("[\s(),;]+", raw)
90 for r in ["", ";"]:
91 while r in raw: raw.remove(r)
92 self.split = list(raw)
93
Filip Pavlisdb234ef2016-11-29 19:06:17 +000094 for r in ["method", "public", "protected", "static", "final", "deprecated", "abstract", "default"]:
Jeff Sharkey8190f4882014-08-28 12:24:07 -070095 while r in raw: raw.remove(r)
96
97 self.typ = raw[0]
98 self.name = raw[1]
99 self.args = []
100 for r in raw[2:]:
101 if r == "throws": break
102 self.args.append(r)
103
Jeff Sharkey037458a2014-09-04 15:46:20 -0700104 # identity for compat purposes
105 ident = self.raw
106 ident = ident.replace(" deprecated ", " ")
107 ident = ident.replace(" synchronized ", " ")
108 ident = re.sub("<.+?>", "", ident)
109 if " throws " in ident:
110 ident = ident[:ident.index(" throws ")]
111 self.ident = ident
112
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700113 def __repr__(self):
114 return self.raw
115
116
117class Class():
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700118 def __init__(self, pkg, line, raw, blame):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700119 self.pkg = pkg
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700120 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700121 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700122 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700123 self.ctors = []
124 self.fields = []
125 self.methods = []
126
127 raw = raw.split()
128 self.split = list(raw)
129 if "class" in raw:
130 self.fullname = raw[raw.index("class")+1]
131 elif "interface" in raw:
132 self.fullname = raw[raw.index("interface")+1]
Jeff Sharkey037458a2014-09-04 15:46:20 -0700133 else:
134 raise ValueError("Funky class type %s" % (self.raw))
135
136 if "extends" in raw:
137 self.extends = raw[raw.index("extends")+1]
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800138 self.extends_path = self.extends.split(".")
Jeff Sharkey037458a2014-09-04 15:46:20 -0700139 else:
140 self.extends = None
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800141 self.extends_path = []
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700142
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700143 self.fullname = self.pkg.name + "." + self.fullname
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800144 self.fullname_path = self.fullname.split(".")
145
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700146 self.name = self.fullname[self.fullname.rindex(".")+1:]
147
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700148 def __repr__(self):
149 return self.raw
150
151
152class Package():
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700153 def __init__(self, line, raw, blame):
154 self.line = line
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700155 self.raw = raw.strip(" {;")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700156 self.blame = blame
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700157
158 raw = raw.split()
159 self.name = raw[raw.index("package")+1]
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800160 self.name_path = self.name.split(".")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700161
162 def __repr__(self):
163 return self.raw
164
165
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800166def _parse_stream(f, clazz_cb=None):
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700167 line = 0
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700168 api = {}
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700169 pkg = None
170 clazz = None
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700171 blame = None
172
173 re_blame = re.compile("^([a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800174 for raw in f:
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700175 line += 1
176 raw = raw.rstrip()
177 match = re_blame.match(raw)
178 if match is not None:
179 blame = match.groups()[0:2]
180 raw = match.groups()[2]
181 else:
182 blame = None
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700183
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700184 if raw.startswith("package"):
185 pkg = Package(line, raw, blame)
186 elif raw.startswith(" ") and raw.endswith("{"):
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800187 # When provided with class callback, we treat as incremental
188 # parse and don't build up entire API
189 if clazz and clazz_cb:
190 clazz_cb(clazz)
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700191 clazz = Class(pkg, line, raw, blame)
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800192 if not clazz_cb:
193 api[clazz.fullname] = clazz
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700194 elif raw.startswith(" ctor"):
195 clazz.ctors.append(Method(clazz, line, raw, blame))
196 elif raw.startswith(" method"):
197 clazz.methods.append(Method(clazz, line, raw, blame))
198 elif raw.startswith(" field"):
199 clazz.fields.append(Field(clazz, line, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700200
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800201 # Handle last trailing class
202 if clazz and clazz_cb:
203 clazz_cb(clazz)
204
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700205 return api
206
207
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700208class Failure():
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800209 def __init__(self, sig, clazz, detail, error, rule, msg):
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700210 self.sig = sig
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700211 self.error = error
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800212 self.rule = rule
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700213 self.msg = msg
214
215 if error:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800216 self.head = "Error %s" % (rule) if rule else "Error"
217 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 -0700218 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800219 self.head = "Warning %s" % (rule) if rule else "Warning"
220 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 -0700221
222 self.line = clazz.line
223 blame = clazz.blame
224 if detail is not None:
225 dump += "\n in " + repr(detail)
226 self.line = detail.line
227 blame = detail.blame
228 dump += "\n in " + repr(clazz)
229 dump += "\n in " + repr(clazz.pkg)
230 dump += "\n at line " + repr(self.line)
231 if blame is not None:
232 dump += "\n last modified by %s in %s" % (blame[1], blame[0])
233
234 self.dump = dump
235
236 def __repr__(self):
237 return self.dump
238
239
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700240failures = {}
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700241
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800242def _fail(clazz, detail, error, rule, msg):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700243 """Records an API failure to be processed later."""
244 global failures
245
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700246 sig = "%s-%s-%s" % (clazz.fullname, repr(detail), msg)
247 sig = sig.replace(" deprecated ", " ")
248
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800249 failures[sig] = Failure(sig, clazz, detail, error, rule, msg)
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700250
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700251
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800252def warn(clazz, detail, rule, msg):
253 _fail(clazz, detail, False, rule, msg)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700254
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800255def error(clazz, detail, rule, msg):
256 _fail(clazz, detail, True, rule, msg)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700257
258
259def verify_constants(clazz):
260 """All static final constants must be FOO_NAME style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700261 if re.match("android\.R\.[a-z]+", clazz.fullname): return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700262
263 for f in clazz.fields:
264 if "static" in f.split and "final" in f.split:
265 if re.match("[A-Z0-9_]+", f.name) is None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800266 error(clazz, f, "C2", "Constant field names must be FOO_NAME")
Jeff Sharkey331279b2016-02-29 16:02:02 -0700267 elif f.typ != "java.lang.String":
268 if f.name.startswith("MIN_") or f.name.startswith("MAX_"):
269 warn(clazz, f, "C8", "If min/max could change in future, make them dynamic methods")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700270
271
272def verify_enums(clazz):
273 """Enums are bad, mmkay?"""
274 if "extends java.lang.Enum" in clazz.raw:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800275 error(clazz, None, "F5", "Enums are not allowed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700276
277
278def verify_class_names(clazz):
279 """Try catching malformed class names like myMtp or MTPUser."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700280 if clazz.fullname.startswith("android.opengl"): return
281 if clazz.fullname.startswith("android.renderscript"): return
282 if re.match("android\.R\.[a-z]+", clazz.fullname): return
283
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700284 if re.search("[A-Z]{2,}", clazz.name) is not None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800285 warn(clazz, None, "S1", "Class names with acronyms should be Mtp not MTP")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700286 if re.match("[^A-Z]", clazz.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800287 error(clazz, None, "S1", "Class must start with uppercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700288
289
290def verify_method_names(clazz):
291 """Try catching malformed method names, like Foo() or getMTU()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700292 if clazz.fullname.startswith("android.opengl"): return
293 if clazz.fullname.startswith("android.renderscript"): return
294 if clazz.fullname == "android.system.OsConstants": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700295
296 for m in clazz.methods:
297 if re.search("[A-Z]{2,}", m.name) is not None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800298 warn(clazz, m, "S1", "Method names with acronyms should be getMtu() instead of getMTU()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700299 if re.match("[^a-z]", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800300 error(clazz, m, "S1", "Method name must start with lowercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700301
302
303def verify_callbacks(clazz):
304 """Verify Callback classes.
305 All callback classes must be abstract.
306 All methods must follow onFoo() naming style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700307 if clazz.fullname == "android.speech.tts.SynthesisCallback": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700308
309 if clazz.name.endswith("Callbacks"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800310 error(clazz, None, "L1", "Callback class names should be singular")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700311 if clazz.name.endswith("Observer"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800312 warn(clazz, None, "L1", "Class should be named FooCallback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700313
314 if clazz.name.endswith("Callback"):
315 if "interface" in clazz.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800316 error(clazz, None, "CL3", "Callbacks must be abstract class to enable extension in future API levels")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700317
318 for m in clazz.methods:
319 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800320 error(clazz, m, "L1", "Callback method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700321
322
323def verify_listeners(clazz):
324 """Verify Listener classes.
325 All Listener classes must be interface.
326 All methods must follow onFoo() naming style.
327 If only a single method, it must match class name:
328 interface OnFooListener { void onFoo() }"""
329
330 if clazz.name.endswith("Listener"):
331 if " abstract class " in clazz.raw:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800332 error(clazz, None, "L1", "Listeners should be an interface, or otherwise renamed Callback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700333
334 for m in clazz.methods:
335 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800336 error(clazz, m, "L1", "Listener method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700337
338 if len(clazz.methods) == 1 and clazz.name.startswith("On"):
339 m = clazz.methods[0]
340 if (m.name + "Listener").lower() != clazz.name.lower():
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800341 error(clazz, m, "L1", "Single listener method name must match class name")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700342
343
344def verify_actions(clazz):
345 """Verify intent actions.
346 All action names must be named ACTION_FOO.
347 All action values must be scoped by package and match name:
348 package android.foo {
349 String ACTION_BAR = "android.foo.action.BAR";
350 }"""
351 for f in clazz.fields:
352 if f.value is None: continue
353 if f.name.startswith("EXTRA_"): continue
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700354 if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": continue
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700355
356 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
357 if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
358 if not f.name.startswith("ACTION_"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800359 error(clazz, f, "C3", "Intent action constant name must be ACTION_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700360 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700361 if clazz.fullname == "android.content.Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700362 prefix = "android.intent.action"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700363 elif clazz.fullname == "android.provider.Settings":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700364 prefix = "android.settings"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700365 elif clazz.fullname == "android.app.admin.DevicePolicyManager" or clazz.fullname == "android.app.admin.DeviceAdminReceiver":
366 prefix = "android.app.action"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700367 else:
368 prefix = clazz.pkg.name + ".action"
369 expected = prefix + "." + f.name[7:]
370 if f.value != expected:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800371 error(clazz, f, "C4", "Inconsistent action value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700372
373
374def verify_extras(clazz):
375 """Verify intent extras.
376 All extra names must be named EXTRA_FOO.
377 All extra values must be scoped by package and match name:
378 package android.foo {
379 String EXTRA_BAR = "android.foo.extra.BAR";
380 }"""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700381 if clazz.fullname == "android.app.Notification": return
382 if clazz.fullname == "android.appwidget.AppWidgetManager": return
383
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700384 for f in clazz.fields:
385 if f.value is None: continue
386 if f.name.startswith("ACTION_"): continue
387
388 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
389 if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
390 if not f.name.startswith("EXTRA_"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800391 error(clazz, f, "C3", "Intent extra must be EXTRA_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700392 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700393 if clazz.pkg.name == "android.content" and clazz.name == "Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700394 prefix = "android.intent.extra"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700395 elif clazz.pkg.name == "android.app.admin":
396 prefix = "android.app.extra"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700397 else:
398 prefix = clazz.pkg.name + ".extra"
399 expected = prefix + "." + f.name[6:]
400 if f.value != expected:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800401 error(clazz, f, "C4", "Inconsistent extra value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700402
403
404def verify_equals(clazz):
405 """Verify that equals() and hashCode() must be overridden together."""
Jeff Sharkey40d623e2016-12-21 13:46:33 -0700406 eq = False
407 hc = False
408 for m in clazz.methods:
409 if " static " in m.raw: continue
410 if "boolean equals(java.lang.Object)" in m.raw: eq = True
411 if "int hashCode()" in m.raw: hc = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700412 if eq != hc:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800413 error(clazz, None, "M8", "Must override both equals and hashCode; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700414
415
416def verify_parcelable(clazz):
417 """Verify that Parcelable objects aren't hiding required bits."""
418 if "implements android.os.Parcelable" in clazz.raw:
419 creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
420 write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
421 describe = [ i for i in clazz.methods if i.name == "describeContents" ]
422
423 if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800424 error(clazz, None, "FW3", "Parcelable requires CREATOR, writeToParcel, and describeContents; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700425
Jeff Sharkey331279b2016-02-29 16:02:02 -0700426 if " final class " not in clazz.raw:
427 error(clazz, None, "FW8", "Parcelable classes must be final")
428
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700429
430def verify_protected(clazz):
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800431 """Verify that no protected methods or fields are allowed."""
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700432 for m in clazz.methods:
433 if "protected" in m.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800434 error(clazz, m, "M7", "Protected methods not allowed; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700435 for f in clazz.fields:
436 if "protected" in f.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800437 error(clazz, f, "M7", "Protected fields not allowed; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700438
439
440def verify_fields(clazz):
441 """Verify that all exposed fields are final.
442 Exposed fields must follow myName style.
443 Catch internal mFoo objects being exposed."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700444
445 IGNORE_BARE_FIELDS = [
446 "android.app.ActivityManager.RecentTaskInfo",
447 "android.app.Notification",
448 "android.content.pm.ActivityInfo",
449 "android.content.pm.ApplicationInfo",
450 "android.content.pm.FeatureGroupInfo",
451 "android.content.pm.InstrumentationInfo",
452 "android.content.pm.PackageInfo",
453 "android.content.pm.PackageItemInfo",
454 "android.os.Message",
455 "android.system.StructPollfd",
456 ]
457
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700458 for f in clazz.fields:
459 if not "final" in f.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700460 if clazz.fullname in IGNORE_BARE_FIELDS:
461 pass
462 elif clazz.fullname.endswith("LayoutParams"):
463 pass
464 elif clazz.fullname.startswith("android.util.Mutable"):
465 pass
466 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800467 error(clazz, f, "F2", "Bare fields must be marked final, or add accessors if mutable")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700468
469 if not "static" in f.split:
470 if not re.match("[a-z]([a-zA-Z]+)?", f.name):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800471 error(clazz, f, "S1", "Non-static fields must be named using myField style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700472
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700473 if re.match("[ms][A-Z]", f.name):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800474 error(clazz, f, "F1", "Internal objects must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700475
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700476 if re.match("[A-Z_]+", f.name):
477 if "static" not in f.split or "final" not in f.split:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800478 error(clazz, f, "C2", "Constants must be marked static final")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700479
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700480
481def verify_register(clazz):
482 """Verify parity of registration methods.
483 Callback objects use register/unregister methods.
484 Listener objects use add/remove methods."""
485 methods = [ m.name for m in clazz.methods ]
486 for m in clazz.methods:
487 if "Callback" in m.raw:
488 if m.name.startswith("register"):
489 other = "unregister" + m.name[8:]
490 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800491 error(clazz, m, "L2", "Missing unregister method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700492 if m.name.startswith("unregister"):
493 other = "register" + m.name[10:]
494 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800495 error(clazz, m, "L2", "Missing register method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700496
497 if m.name.startswith("add") or m.name.startswith("remove"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800498 error(clazz, m, "L3", "Callback methods should be named register/unregister")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700499
500 if "Listener" in m.raw:
501 if m.name.startswith("add"):
502 other = "remove" + m.name[3:]
503 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800504 error(clazz, m, "L2", "Missing remove method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700505 if m.name.startswith("remove") and not m.name.startswith("removeAll"):
506 other = "add" + m.name[6:]
507 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800508 error(clazz, m, "L2", "Missing add method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700509
510 if m.name.startswith("register") or m.name.startswith("unregister"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800511 error(clazz, m, "L3", "Listener methods should be named add/remove")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700512
513
514def verify_sync(clazz):
515 """Verify synchronized methods aren't exposed."""
516 for m in clazz.methods:
517 if "synchronized" in m.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800518 error(clazz, m, "M5", "Internal locks must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700519
520
521def verify_intent_builder(clazz):
522 """Verify that Intent builders are createFooIntent() style."""
523 if clazz.name == "Intent": return
524
525 for m in clazz.methods:
526 if m.typ == "android.content.Intent":
527 if m.name.startswith("create") and m.name.endswith("Intent"):
528 pass
529 else:
Adam Powell539ea122015-04-10 13:01:37 -0700530 warn(clazz, m, "FW1", "Methods creating an Intent should be named createFooIntent()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700531
532
533def verify_helper_classes(clazz):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700534 """Verify that helper classes are named consistently with what they extend.
535 All developer extendable methods should be named onFoo()."""
536 test_methods = False
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700537 if "extends android.app.Service" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700538 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700539 if not clazz.name.endswith("Service"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800540 error(clazz, None, "CL4", "Inconsistent class name; should be FooService")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700541
542 found = False
543 for f in clazz.fields:
544 if f.name == "SERVICE_INTERFACE":
545 found = True
546 if f.value != clazz.fullname:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800547 error(clazz, f, "C4", "Inconsistent interface constant; expected %s" % (clazz.fullname))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700548
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700549 if "extends android.content.ContentProvider" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700550 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700551 if not clazz.name.endswith("Provider"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800552 error(clazz, None, "CL4", "Inconsistent class name; should be FooProvider")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700553
554 found = False
555 for f in clazz.fields:
556 if f.name == "PROVIDER_INTERFACE":
557 found = True
558 if f.value != clazz.fullname:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800559 error(clazz, f, "C4", "Inconsistent interface constant; expected %s" % (clazz.fullname))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700560
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700561 if "extends android.content.BroadcastReceiver" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700562 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700563 if not clazz.name.endswith("Receiver"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800564 error(clazz, None, "CL4", "Inconsistent class name; should be FooReceiver")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700565
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700566 if "extends android.app.Activity" in clazz.raw:
567 test_methods = True
568 if not clazz.name.endswith("Activity"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800569 error(clazz, None, "CL4", "Inconsistent class name; should be FooActivity")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700570
571 if test_methods:
572 for m in clazz.methods:
573 if "final" in m.split: continue
574 if not re.match("on[A-Z]", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700575 if "abstract" in m.split:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800576 warn(clazz, m, None, "Methods implemented by developers should be named onFoo()")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700577 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800578 warn(clazz, m, None, "If implemented by developer, should be named onFoo(); otherwise consider marking final")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700579
580
581def verify_builder(clazz):
582 """Verify builder classes.
583 Methods should return the builder to enable chaining."""
584 if " extends " in clazz.raw: return
585 if not clazz.name.endswith("Builder"): return
586
587 if clazz.name != "Builder":
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800588 warn(clazz, None, None, "Builder should be defined as inner class")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700589
590 has_build = False
591 for m in clazz.methods:
592 if m.name == "build":
593 has_build = True
594 continue
595
596 if m.name.startswith("get"): continue
597 if m.name.startswith("clear"): continue
598
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700599 if m.name.startswith("with"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800600 warn(clazz, m, None, "Builder methods names should use setFoo() style")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700601
602 if m.name.startswith("set"):
603 if not m.typ.endswith(clazz.fullname):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800604 warn(clazz, m, "M4", "Methods must return the builder object")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700605
606 if not has_build:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800607 warn(clazz, None, None, "Missing build() method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700608
609
610def verify_aidl(clazz):
611 """Catch people exposing raw AIDL."""
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700612 if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800613 error(clazz, None, None, "Raw AIDL interfaces must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700614
615
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700616def verify_internal(clazz):
617 """Catch people exposing internal classes."""
618 if clazz.pkg.name.startswith("com.android"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800619 error(clazz, None, None, "Internal classes must not be exposed")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700620
621
622def verify_layering(clazz):
623 """Catch package layering violations.
624 For example, something in android.os depending on android.app."""
625 ranking = [
626 ["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
627 "android.app",
628 "android.widget",
629 "android.view",
630 "android.animation",
631 "android.provider",
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700632 ["android.content","android.graphics.drawable"],
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700633 "android.database",
634 "android.graphics",
635 "android.text",
636 "android.os",
637 "android.util"
638 ]
639
640 def rank(p):
641 for i in range(len(ranking)):
642 if isinstance(ranking[i], list):
643 for j in ranking[i]:
644 if p.startswith(j): return i
645 else:
646 if p.startswith(ranking[i]): return i
647
648 cr = rank(clazz.pkg.name)
649 if cr is None: return
650
651 for f in clazz.fields:
652 ir = rank(f.typ)
653 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800654 warn(clazz, f, "FW6", "Field type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700655
656 for m in clazz.methods:
657 ir = rank(m.typ)
658 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800659 warn(clazz, m, "FW6", "Method return type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700660 for arg in m.args:
661 ir = rank(arg)
662 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800663 warn(clazz, m, "FW6", "Method argument type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700664
665
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800666def verify_boolean(clazz):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800667 """Verifies that boolean accessors are named correctly.
668 For example, hasFoo() and setHasFoo()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700669
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800670 def is_get(m): return len(m.args) == 0 and m.typ == "boolean"
671 def is_set(m): return len(m.args) == 1 and m.args[0] == "boolean"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700672
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800673 gets = [ m for m in clazz.methods if is_get(m) ]
674 sets = [ m for m in clazz.methods if is_set(m) ]
675
676 def error_if_exists(methods, trigger, expected, actual):
677 for m in methods:
678 if m.name == actual:
679 error(clazz, m, "M6", "Symmetric method for %s must be named %s" % (trigger, expected))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700680
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700681 for m in clazz.methods:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800682 if is_get(m):
683 if re.match("is[A-Z]", m.name):
684 target = m.name[2:]
685 expected = "setIs" + target
686 error_if_exists(sets, m.name, expected, "setHas" + target)
687 elif re.match("has[A-Z]", m.name):
688 target = m.name[3:]
689 expected = "setHas" + target
690 error_if_exists(sets, m.name, expected, "setIs" + target)
691 error_if_exists(sets, m.name, expected, "set" + target)
692 elif re.match("get[A-Z]", m.name):
693 target = m.name[3:]
694 expected = "set" + target
695 error_if_exists(sets, m.name, expected, "setIs" + target)
696 error_if_exists(sets, m.name, expected, "setHas" + target)
697
698 if is_set(m):
699 if re.match("set[A-Z]", m.name):
700 target = m.name[3:]
701 expected = "get" + target
702 error_if_exists(sets, m.name, expected, "is" + target)
703 error_if_exists(sets, m.name, expected, "has" + target)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700704
705
706def verify_collections(clazz):
707 """Verifies that collection types are interfaces."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700708 if clazz.fullname == "android.os.Bundle": return
709
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700710 bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
711 "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
712 for m in clazz.methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700713 if m.typ in bad:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800714 error(clazz, m, "CL2", "Return type is concrete collection; must be higher-level interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700715 for arg in m.args:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700716 if arg in bad:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800717 error(clazz, m, "CL2", "Argument is concrete collection; must be higher-level interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700718
719
720def verify_flags(clazz):
721 """Verifies that flags are non-overlapping."""
722 known = collections.defaultdict(int)
723 for f in clazz.fields:
724 if "FLAG_" in f.name:
725 try:
726 val = int(f.value)
727 except:
728 continue
729
730 scope = f.name[0:f.name.index("FLAG_")]
731 if val & known[scope]:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800732 warn(clazz, f, "C1", "Found overlapping flag constant value")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700733 known[scope] |= val
734
735
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800736def verify_exception(clazz):
737 """Verifies that methods don't throw generic exceptions."""
738 for m in clazz.methods:
739 if "throws java.lang.Exception" in m.raw or "throws java.lang.Throwable" in m.raw or "throws java.lang.Error" in m.raw:
740 error(clazz, m, "S1", "Methods must not throw generic exceptions")
741
Jeff Sharkey331279b2016-02-29 16:02:02 -0700742 if "throws android.os.RemoteException" in m.raw:
743 if clazz.name == "android.content.ContentProviderClient": continue
744 if clazz.name == "android.os.Binder": continue
745 if clazz.name == "android.os.IBinder": continue
746
747 error(clazz, m, "FW9", "Methods calling into system server should rethrow RemoteException as RuntimeException")
748
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800749
750def verify_google(clazz):
751 """Verifies that APIs never reference Google."""
752
753 if re.search("google", clazz.raw, re.IGNORECASE):
754 error(clazz, None, None, "Must never reference Google")
755
756 test = []
757 test.extend(clazz.ctors)
758 test.extend(clazz.fields)
759 test.extend(clazz.methods)
760
761 for t in test:
762 if re.search("google", t.raw, re.IGNORECASE):
763 error(clazz, t, None, "Must never reference Google")
764
765
766def verify_bitset(clazz):
767 """Verifies that we avoid using heavy BitSet."""
768
769 for f in clazz.fields:
770 if f.typ == "java.util.BitSet":
771 error(clazz, f, None, "Field type must not be heavy BitSet")
772
773 for m in clazz.methods:
774 if m.typ == "java.util.BitSet":
775 error(clazz, m, None, "Return type must not be heavy BitSet")
776 for arg in m.args:
777 if arg == "java.util.BitSet":
778 error(clazz, m, None, "Argument type must not be heavy BitSet")
779
780
781def verify_manager(clazz):
782 """Verifies that FooManager is only obtained from Context."""
783
784 if not clazz.name.endswith("Manager"): return
785
786 for c in clazz.ctors:
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800787 error(clazz, c, None, "Managers must always be obtained from Context; no direct constructors")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800788
789
790def verify_boxed(clazz):
791 """Verifies that methods avoid boxed primitives."""
792
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800793 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 -0800794
795 for c in clazz.ctors:
796 for arg in c.args:
797 if arg in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800798 error(clazz, c, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800799
800 for f in clazz.fields:
801 if f.typ in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800802 error(clazz, f, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800803
804 for m in clazz.methods:
805 if m.typ in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800806 error(clazz, m, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800807 for arg in m.args:
808 if arg in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800809 error(clazz, m, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800810
811
812def verify_static_utils(clazz):
813 """Verifies that helper classes can't be constructed."""
814 if clazz.fullname.startswith("android.opengl"): return
815 if re.match("android\.R\.[a-z]+", clazz.fullname): return
816
817 if len(clazz.fields) > 0: return
818 if len(clazz.methods) == 0: return
819
820 for m in clazz.methods:
821 if "static" not in m.split:
822 return
823
824 # At this point, we have no fields, and all methods are static
825 if len(clazz.ctors) > 0:
826 error(clazz, None, None, "Fully-static utility classes must not have constructor")
827
828
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800829def verify_overload_args(clazz):
830 """Verifies that method overloads add new arguments at the end."""
831 if clazz.fullname.startswith("android.opengl"): return
832
833 overloads = collections.defaultdict(list)
834 for m in clazz.methods:
835 if "deprecated" in m.split: continue
836 overloads[m.name].append(m)
837
Jeff Sharkeya18a2e32015-02-22 15:54:32 -0800838 for name, methods in overloads.items():
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800839 if len(methods) <= 1: continue
840
841 # Look for arguments common across all overloads
842 def cluster(args):
843 count = collections.defaultdict(int)
844 res = set()
845 for i in range(len(args)):
846 a = args[i]
847 res.add("%s#%d" % (a, count[a]))
848 count[a] += 1
849 return res
850
851 common_args = cluster(methods[0].args)
852 for m in methods:
853 common_args = common_args & cluster(m.args)
854
855 if len(common_args) == 0: continue
856
857 # Require that all common arguments are present at start of signature
858 locked_sig = None
859 for m in methods:
860 sig = m.args[0:len(common_args)]
861 if not common_args.issubset(cluster(sig)):
862 warn(clazz, m, "M2", "Expected common arguments [%s] at beginning of overloaded method" % (", ".join(common_args)))
863 elif not locked_sig:
864 locked_sig = sig
865 elif locked_sig != sig:
866 error(clazz, m, "M2", "Expected consistent argument ordering between overloads: %s..." % (", ".join(locked_sig)))
867
868
869def verify_callback_handlers(clazz):
870 """Verifies that methods adding listener/callback have overload
871 for specifying delivery thread."""
872
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800873 # Ignore UI packages which assume main thread
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800874 skip = [
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800875 "animation",
876 "view",
877 "graphics",
878 "transition",
879 "widget",
880 "webkit",
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800881 ]
882 for s in skip:
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800883 if s in clazz.pkg.name_path: return
884 if s in clazz.extends_path: return
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800885
Jeff Sharkey047d7f02015-02-25 11:27:55 -0800886 # Ignore UI classes which assume main thread
887 if "app" in clazz.pkg.name_path or "app" in clazz.extends_path:
888 for s in ["ActionBar","Dialog","Application","Activity","Fragment","Loader"]:
889 if s in clazz.fullname: return
890 if "content" in clazz.pkg.name_path or "content" in clazz.extends_path:
891 for s in ["Loader"]:
892 if s in clazz.fullname: return
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800893
894 found = {}
895 by_name = collections.defaultdict(list)
896 for m in clazz.methods:
897 if m.name.startswith("unregister"): continue
898 if m.name.startswith("remove"): continue
899 if re.match("on[A-Z]+", m.name): continue
900
901 by_name[m.name].append(m)
902
903 for a in m.args:
904 if a.endswith("Listener") or a.endswith("Callback") or a.endswith("Callbacks"):
905 found[m.name] = m
906
907 for f in found.values():
908 takes_handler = False
909 for m in by_name[f.name]:
910 if "android.os.Handler" in m.args:
911 takes_handler = True
912 if not takes_handler:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800913 warn(clazz, f, "L1", "Registration methods should have overload that accepts delivery Handler")
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800914
915
916def verify_context_first(clazz):
917 """Verifies that methods accepting a Context keep it the first argument."""
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800918 examine = clazz.ctors + clazz.methods
919 for m in examine:
920 if len(m.args) > 1 and m.args[0] != "android.content.Context":
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800921 if "android.content.Context" in m.args[1:]:
922 error(clazz, m, "M3", "Context is distinct, so it must be the first argument")
923
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800924
925def verify_listener_last(clazz):
926 """Verifies that methods accepting a Listener or Callback keep them as last arguments."""
927 examine = clazz.ctors + clazz.methods
928 for m in examine:
929 if "Listener" in m.name or "Callback" in m.name: continue
930 found = False
931 for a in m.args:
932 if a.endswith("Callback") or a.endswith("Callbacks") or a.endswith("Listener"):
933 found = True
934 elif found and a != "android.os.Handler":
935 warn(clazz, m, "M3", "Listeners should always be at end of argument list")
936
937
938def verify_resource_names(clazz):
939 """Verifies that resource names have consistent case."""
940 if not re.match("android\.R\.[a-z]+", clazz.fullname): return
941
942 # Resources defined by files are foo_bar_baz
943 if clazz.name in ["anim","animator","color","dimen","drawable","interpolator","layout","transition","menu","mipmap","string","plurals","raw","xml"]:
944 for f in clazz.fields:
945 if re.match("[a-z1-9_]+$", f.name): continue
946 error(clazz, f, None, "Expected resource name in this class to be foo_bar_baz style")
947
948 # Resources defined inside files are fooBarBaz
949 if clazz.name in ["array","attr","id","bool","fraction","integer"]:
950 for f in clazz.fields:
951 if re.match("config_[a-z][a-zA-Z1-9]*$", f.name): continue
952 if re.match("layout_[a-z][a-zA-Z1-9]*$", f.name): continue
953 if re.match("state_[a-z_]*$", f.name): continue
954
955 if re.match("[a-z][a-zA-Z1-9]*$", f.name): continue
956 error(clazz, f, "C7", "Expected resource name in this class to be fooBarBaz style")
957
958 # Styles are FooBar_Baz
959 if clazz.name in ["style"]:
960 for f in clazz.fields:
961 if re.match("[A-Z][A-Za-z1-9]+(_[A-Z][A-Za-z1-9]+?)*$", f.name): continue
962 error(clazz, f, "C7", "Expected resource name in this class to be FooBar_Baz style")
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800963
964
Jeff Sharkey331279b2016-02-29 16:02:02 -0700965def verify_files(clazz):
966 """Verifies that methods accepting File also accept streams."""
967
968 has_file = set()
969 has_stream = set()
970
971 test = []
972 test.extend(clazz.ctors)
973 test.extend(clazz.methods)
974
975 for m in test:
976 if "java.io.File" in m.args:
977 has_file.add(m)
978 if "java.io.FileDescriptor" in m.args or "android.os.ParcelFileDescriptor" in m.args or "java.io.InputStream" in m.args or "java.io.OutputStream" in m.args:
979 has_stream.add(m.name)
980
981 for m in has_file:
982 if m.name not in has_stream:
983 warn(clazz, m, "M10", "Methods accepting File should also accept FileDescriptor or streams")
984
985
Jeff Sharkey70168dd2016-03-30 21:47:16 -0600986def verify_manager_list(clazz):
987 """Verifies that managers return List<? extends Parcelable> instead of arrays."""
988
989 if not clazz.name.endswith("Manager"): return
990
991 for m in clazz.methods:
992 if m.typ.startswith("android.") and m.typ.endswith("[]"):
993 warn(clazz, m, None, "Methods should return List<? extends Parcelable> instead of Parcelable[] to support ParceledListSlice under the hood")
994
995
Jeff Sharkey26c80902016-12-21 13:41:17 -0700996def verify_abstract_inner(clazz):
997 """Verifies that abstract inner classes are static."""
998
999 if re.match(".+?\.[A-Z][^\.]+\.[A-Z]", clazz.fullname):
1000 if " abstract " in clazz.raw and " static " not in clazz.raw:
1001 warn(clazz, None, None, "Abstract inner classes should be static to improve testability")
1002
1003
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001004def examine_clazz(clazz):
1005 """Find all style issues in the given class."""
1006 if clazz.pkg.name.startswith("java"): return
1007 if clazz.pkg.name.startswith("junit"): return
1008 if clazz.pkg.name.startswith("org.apache"): return
1009 if clazz.pkg.name.startswith("org.xml"): return
1010 if clazz.pkg.name.startswith("org.json"): return
1011 if clazz.pkg.name.startswith("org.w3c"): return
Jeff Sharkey331279b2016-02-29 16:02:02 -07001012 if clazz.pkg.name.startswith("android.icu."): return
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001013
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001014 verify_constants(clazz)
1015 verify_enums(clazz)
1016 verify_class_names(clazz)
1017 verify_method_names(clazz)
1018 verify_callbacks(clazz)
1019 verify_listeners(clazz)
1020 verify_actions(clazz)
1021 verify_extras(clazz)
1022 verify_equals(clazz)
1023 verify_parcelable(clazz)
1024 verify_protected(clazz)
1025 verify_fields(clazz)
1026 verify_register(clazz)
1027 verify_sync(clazz)
1028 verify_intent_builder(clazz)
1029 verify_helper_classes(clazz)
1030 verify_builder(clazz)
1031 verify_aidl(clazz)
1032 verify_internal(clazz)
1033 verify_layering(clazz)
1034 verify_boolean(clazz)
1035 verify_collections(clazz)
1036 verify_flags(clazz)
1037 verify_exception(clazz)
Adam Metcalf1c7e70a2015-03-27 16:11:23 -07001038 if not ALLOW_GOOGLE: verify_google(clazz)
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001039 verify_bitset(clazz)
1040 verify_manager(clazz)
1041 verify_boxed(clazz)
1042 verify_static_utils(clazz)
1043 verify_overload_args(clazz)
1044 verify_callback_handlers(clazz)
1045 verify_context_first(clazz)
1046 verify_listener_last(clazz)
1047 verify_resource_names(clazz)
Jeff Sharkey331279b2016-02-29 16:02:02 -07001048 verify_files(clazz)
Jeff Sharkey70168dd2016-03-30 21:47:16 -06001049 verify_manager_list(clazz)
Jeff Sharkey26c80902016-12-21 13:41:17 -07001050 verify_abstract_inner(clazz)
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001051
1052
1053def examine_stream(stream):
1054 """Find all style issues in the given API stream."""
1055 global failures
1056 failures = {}
1057 _parse_stream(stream, examine_clazz)
1058 return failures
1059
1060
1061def examine_api(api):
1062 """Find all style issues in the given parsed API."""
1063 global failures
Jeff Sharkey1498f9c2014-09-04 12:45:33 -07001064 failures = {}
1065 for key in sorted(api.keys()):
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001066 examine_clazz(api[key])
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001067 return failures
1068
1069
Jeff Sharkey037458a2014-09-04 15:46:20 -07001070def verify_compat(cur, prev):
1071 """Find any incompatible API changes between two levels."""
1072 global failures
1073
1074 def class_exists(api, test):
1075 return test.fullname in api
1076
1077 def ctor_exists(api, clazz, test):
1078 for m in clazz.ctors:
1079 if m.ident == test.ident: return True
1080 return False
1081
1082 def all_methods(api, clazz):
1083 methods = list(clazz.methods)
1084 if clazz.extends is not None:
1085 methods.extend(all_methods(api, api[clazz.extends]))
1086 return methods
1087
1088 def method_exists(api, clazz, test):
1089 methods = all_methods(api, clazz)
1090 for m in methods:
1091 if m.ident == test.ident: return True
1092 return False
1093
1094 def field_exists(api, clazz, test):
1095 for f in clazz.fields:
1096 if f.ident == test.ident: return True
1097 return False
1098
1099 failures = {}
1100 for key in sorted(prev.keys()):
1101 prev_clazz = prev[key]
1102
1103 if not class_exists(cur, prev_clazz):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001104 error(prev_clazz, None, None, "Class removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001105 continue
1106
1107 cur_clazz = cur[key]
1108
1109 for test in prev_clazz.ctors:
1110 if not ctor_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001111 error(prev_clazz, prev_ctor, None, "Constructor removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001112
1113 methods = all_methods(prev, prev_clazz)
1114 for test in methods:
1115 if not method_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001116 error(prev_clazz, test, None, "Method removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001117
1118 for test in prev_clazz.fields:
1119 if not field_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001120 error(prev_clazz, test, None, "Field removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001121
1122 return failures
1123
1124
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001125if __name__ == "__main__":
Adam Metcalf1c7e70a2015-03-27 16:11:23 -07001126 parser = argparse.ArgumentParser(description="Enforces common Android public API design \
1127 patterns. It ignores lint messages from a previous API level, if provided.")
1128 parser.add_argument("current.txt", type=argparse.FileType('r'), help="current.txt")
1129 parser.add_argument("previous.txt", nargs='?', type=argparse.FileType('r'), default=None,
1130 help="previous.txt")
1131 parser.add_argument("--no-color", action='store_const', const=True,
1132 help="Disable terminal colors")
1133 parser.add_argument("--allow-google", action='store_const', const=True,
1134 help="Allow references to Google")
1135 args = vars(parser.parse_args())
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001136
Adam Metcalf1c7e70a2015-03-27 16:11:23 -07001137 if args['no_color']:
1138 USE_COLOR = False
1139
1140 if args['allow_google']:
1141 ALLOW_GOOGLE = True
1142
1143 current_file = args['current.txt']
1144 previous_file = args['previous.txt']
1145
1146 with current_file as f:
1147 cur_fail = examine_stream(f)
1148 if not previous_file is None:
1149 with previous_file as f:
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001150 prev_fail = examine_stream(f)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001151
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001152 # ignore errors from previous API level
1153 for p in prev_fail:
1154 if p in cur_fail:
1155 del cur_fail[p]
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001156
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001157 """
1158 # NOTE: disabled because of memory pressure
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001159 # look for compatibility issues
1160 compat_fail = verify_compat(cur, prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001161
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001162 print "%s API compatibility issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1163 for f in sorted(compat_fail):
1164 print compat_fail[f]
1165 print
Jeff Sharkeya18a2e32015-02-22 15:54:32 -08001166 """
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001167
1168 print "%s API style issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1169 for f in sorted(cur_fail):
1170 print cur_fail[f]
Jeff Sharkey037458a2014-09-04 15:46:20 -07001171 print