blob: 54525ad95d5d40b0f96945d4c052bd2976b2981d [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 Sharkeyed6aaf02015-01-30 13:31:45 -0700158def parse_api(f):
159 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 Sharkeyed6aaf02015-01-30 13:31:45 -0700166 for raw in f.readlines():
167 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("{"):
179 clazz = Class(pkg, line, raw, blame)
180 api[clazz.fullname] = clazz
181 elif raw.startswith(" ctor"):
182 clazz.ctors.append(Method(clazz, line, raw, blame))
183 elif raw.startswith(" method"):
184 clazz.methods.append(Method(clazz, line, raw, blame))
185 elif raw.startswith(" field"):
186 clazz.fields.append(Field(clazz, line, raw, blame))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700187
188 return api
189
190
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700191def parse_api_file(fn):
192 with open(fn) as f:
193 return parse_api(f)
194
195
196class Failure():
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800197 def __init__(self, sig, clazz, detail, error, rule, msg):
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700198 self.sig = sig
199 self.clazz = clazz
200 self.detail = detail
201 self.error = error
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800202 self.rule = rule
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700203 self.msg = msg
204
205 if error:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800206 self.head = "Error %s" % (rule) if rule else "Error"
207 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 -0700208 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800209 self.head = "Warning %s" % (rule) if rule else "Warning"
210 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 -0700211
212 self.line = clazz.line
213 blame = clazz.blame
214 if detail is not None:
215 dump += "\n in " + repr(detail)
216 self.line = detail.line
217 blame = detail.blame
218 dump += "\n in " + repr(clazz)
219 dump += "\n in " + repr(clazz.pkg)
220 dump += "\n at line " + repr(self.line)
221 if blame is not None:
222 dump += "\n last modified by %s in %s" % (blame[1], blame[0])
223
224 self.dump = dump
225
226 def __repr__(self):
227 return self.dump
228
229
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700230failures = {}
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700231
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800232def _fail(clazz, detail, error, rule, msg):
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700233 """Records an API failure to be processed later."""
234 global failures
235
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700236 sig = "%s-%s-%s" % (clazz.fullname, repr(detail), msg)
237 sig = sig.replace(" deprecated ", " ")
238
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800239 failures[sig] = Failure(sig, clazz, detail, error, rule, msg)
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -0700240
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700241
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800242def warn(clazz, detail, rule, msg):
243 _fail(clazz, detail, False, rule, msg)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700244
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800245def error(clazz, detail, rule, msg):
246 _fail(clazz, detail, True, rule, msg)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700247
248
249def verify_constants(clazz):
250 """All static final constants must be FOO_NAME style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700251 if re.match("android\.R\.[a-z]+", clazz.fullname): return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700252
253 for f in clazz.fields:
254 if "static" in f.split and "final" in f.split:
255 if re.match("[A-Z0-9_]+", f.name) is None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800256 error(clazz, f, "C2", "Constant field names must be FOO_NAME")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700257
258
259def verify_enums(clazz):
260 """Enums are bad, mmkay?"""
261 if "extends java.lang.Enum" in clazz.raw:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800262 error(clazz, None, "F5", "Enums are not allowed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700263
264
265def verify_class_names(clazz):
266 """Try catching malformed class names like myMtp or MTPUser."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700267 if clazz.fullname.startswith("android.opengl"): return
268 if clazz.fullname.startswith("android.renderscript"): return
269 if re.match("android\.R\.[a-z]+", clazz.fullname): return
270
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700271 if re.search("[A-Z]{2,}", clazz.name) is not None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800272 warn(clazz, None, "S1", "Class names with acronyms should be Mtp not MTP")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700273 if re.match("[^A-Z]", clazz.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800274 error(clazz, None, "S1", "Class must start with uppercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700275
276
277def verify_method_names(clazz):
278 """Try catching malformed method names, like Foo() or getMTU()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700279 if clazz.fullname.startswith("android.opengl"): return
280 if clazz.fullname.startswith("android.renderscript"): return
281 if clazz.fullname == "android.system.OsConstants": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700282
283 for m in clazz.methods:
284 if re.search("[A-Z]{2,}", m.name) is not None:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800285 warn(clazz, m, "S1", "Method names with acronyms should be getMtu() instead of getMTU()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700286 if re.match("[^a-z]", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800287 error(clazz, m, "S1", "Method name must start with lowercase char")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700288
289
290def verify_callbacks(clazz):
291 """Verify Callback classes.
292 All callback classes must be abstract.
293 All methods must follow onFoo() naming style."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700294 if clazz.fullname == "android.speech.tts.SynthesisCallback": return
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700295
296 if clazz.name.endswith("Callbacks"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800297 error(clazz, None, "L1", "Callback class names should be singular")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700298 if clazz.name.endswith("Observer"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800299 warn(clazz, None, "L1", "Class should be named FooCallback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700300
301 if clazz.name.endswith("Callback"):
302 if "interface" in clazz.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800303 error(clazz, None, "CL3", "Callbacks must be abstract class to enable extension in future API levels")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700304
305 for m in clazz.methods:
306 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800307 error(clazz, m, "L1", "Callback method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700308
309
310def verify_listeners(clazz):
311 """Verify Listener classes.
312 All Listener classes must be interface.
313 All methods must follow onFoo() naming style.
314 If only a single method, it must match class name:
315 interface OnFooListener { void onFoo() }"""
316
317 if clazz.name.endswith("Listener"):
318 if " abstract class " in clazz.raw:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800319 error(clazz, None, "L1", "Listeners should be an interface, or otherwise renamed Callback")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700320
321 for m in clazz.methods:
322 if not re.match("on[A-Z][a-z]*", m.name):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800323 error(clazz, m, "L1", "Listener method names must be onFoo() style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700324
325 if len(clazz.methods) == 1 and clazz.name.startswith("On"):
326 m = clazz.methods[0]
327 if (m.name + "Listener").lower() != clazz.name.lower():
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800328 error(clazz, m, "L1", "Single listener method name must match class name")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700329
330
331def verify_actions(clazz):
332 """Verify intent actions.
333 All action names must be named ACTION_FOO.
334 All action values must be scoped by package and match name:
335 package android.foo {
336 String ACTION_BAR = "android.foo.action.BAR";
337 }"""
338 for f in clazz.fields:
339 if f.value is None: continue
340 if f.name.startswith("EXTRA_"): continue
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700341 if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": continue
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700342
343 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
344 if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
345 if not f.name.startswith("ACTION_"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800346 error(clazz, f, "C3", "Intent action constant name must be ACTION_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700347 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700348 if clazz.fullname == "android.content.Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700349 prefix = "android.intent.action"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700350 elif clazz.fullname == "android.provider.Settings":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700351 prefix = "android.settings"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700352 elif clazz.fullname == "android.app.admin.DevicePolicyManager" or clazz.fullname == "android.app.admin.DeviceAdminReceiver":
353 prefix = "android.app.action"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700354 else:
355 prefix = clazz.pkg.name + ".action"
356 expected = prefix + "." + f.name[7:]
357 if f.value != expected:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800358 error(clazz, f, "C4", "Inconsistent action value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700359
360
361def verify_extras(clazz):
362 """Verify intent extras.
363 All extra names must be named EXTRA_FOO.
364 All extra values must be scoped by package and match name:
365 package android.foo {
366 String EXTRA_BAR = "android.foo.extra.BAR";
367 }"""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700368 if clazz.fullname == "android.app.Notification": return
369 if clazz.fullname == "android.appwidget.AppWidgetManager": return
370
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700371 for f in clazz.fields:
372 if f.value is None: continue
373 if f.name.startswith("ACTION_"): continue
374
375 if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
376 if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
377 if not f.name.startswith("EXTRA_"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800378 error(clazz, f, "C3", "Intent extra must be EXTRA_FOO")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700379 else:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700380 if clazz.pkg.name == "android.content" and clazz.name == "Intent":
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700381 prefix = "android.intent.extra"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700382 elif clazz.pkg.name == "android.app.admin":
383 prefix = "android.app.extra"
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700384 else:
385 prefix = clazz.pkg.name + ".extra"
386 expected = prefix + "." + f.name[6:]
387 if f.value != expected:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800388 error(clazz, f, "C4", "Inconsistent extra value; expected %s" % (expected))
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700389
390
391def verify_equals(clazz):
392 """Verify that equals() and hashCode() must be overridden together."""
393 methods = [ m.name for m in clazz.methods ]
394 eq = "equals" in methods
395 hc = "hashCode" in methods
396 if eq != hc:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800397 error(clazz, None, "M8", "Must override both equals and hashCode; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700398
399
400def verify_parcelable(clazz):
401 """Verify that Parcelable objects aren't hiding required bits."""
402 if "implements android.os.Parcelable" in clazz.raw:
403 creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
404 write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
405 describe = [ i for i in clazz.methods if i.name == "describeContents" ]
406
407 if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800408 error(clazz, None, "FW3", "Parcelable requires CREATOR, writeToParcel, and describeContents; missing one")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700409
410
411def verify_protected(clazz):
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800412 """Verify that no protected methods or fields are allowed."""
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700413 for m in clazz.methods:
414 if "protected" in m.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800415 error(clazz, m, "M7", "Protected methods not allowed; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700416 for f in clazz.fields:
417 if "protected" in f.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800418 error(clazz, f, "M7", "Protected fields not allowed; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700419
420
421def verify_fields(clazz):
422 """Verify that all exposed fields are final.
423 Exposed fields must follow myName style.
424 Catch internal mFoo objects being exposed."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700425
426 IGNORE_BARE_FIELDS = [
427 "android.app.ActivityManager.RecentTaskInfo",
428 "android.app.Notification",
429 "android.content.pm.ActivityInfo",
430 "android.content.pm.ApplicationInfo",
431 "android.content.pm.FeatureGroupInfo",
432 "android.content.pm.InstrumentationInfo",
433 "android.content.pm.PackageInfo",
434 "android.content.pm.PackageItemInfo",
435 "android.os.Message",
436 "android.system.StructPollfd",
437 ]
438
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700439 for f in clazz.fields:
440 if not "final" in f.split:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700441 if clazz.fullname in IGNORE_BARE_FIELDS:
442 pass
443 elif clazz.fullname.endswith("LayoutParams"):
444 pass
445 elif clazz.fullname.startswith("android.util.Mutable"):
446 pass
447 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800448 error(clazz, f, "F2", "Bare fields must be marked final, or add accessors if mutable")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700449
450 if not "static" in f.split:
451 if not re.match("[a-z]([a-zA-Z]+)?", f.name):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800452 error(clazz, f, "S1", "Non-static fields must be named using myField style")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700453
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700454 if re.match("[ms][A-Z]", f.name):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800455 error(clazz, f, "F1", "Internal objects must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700456
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700457 if re.match("[A-Z_]+", f.name):
458 if "static" not in f.split or "final" not in f.split:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800459 error(clazz, f, "C2", "Constants must be marked static final")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700460
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700461
462def verify_register(clazz):
463 """Verify parity of registration methods.
464 Callback objects use register/unregister methods.
465 Listener objects use add/remove methods."""
466 methods = [ m.name for m in clazz.methods ]
467 for m in clazz.methods:
468 if "Callback" in m.raw:
469 if m.name.startswith("register"):
470 other = "unregister" + m.name[8:]
471 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800472 error(clazz, m, "L2", "Missing unregister method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700473 if m.name.startswith("unregister"):
474 other = "register" + m.name[10:]
475 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800476 error(clazz, m, "L2", "Missing register method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700477
478 if m.name.startswith("add") or m.name.startswith("remove"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800479 error(clazz, m, "L3", "Callback methods should be named register/unregister")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700480
481 if "Listener" in m.raw:
482 if m.name.startswith("add"):
483 other = "remove" + m.name[3:]
484 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800485 error(clazz, m, "L2", "Missing remove method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700486 if m.name.startswith("remove") and not m.name.startswith("removeAll"):
487 other = "add" + m.name[6:]
488 if other not in methods:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800489 error(clazz, m, "L2", "Missing add method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700490
491 if m.name.startswith("register") or m.name.startswith("unregister"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800492 error(clazz, m, "L3", "Listener methods should be named add/remove")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700493
494
495def verify_sync(clazz):
496 """Verify synchronized methods aren't exposed."""
497 for m in clazz.methods:
498 if "synchronized" in m.split:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800499 error(clazz, m, "M5", "Internal locks must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700500
501
502def verify_intent_builder(clazz):
503 """Verify that Intent builders are createFooIntent() style."""
504 if clazz.name == "Intent": return
505
506 for m in clazz.methods:
507 if m.typ == "android.content.Intent":
508 if m.name.startswith("create") and m.name.endswith("Intent"):
509 pass
510 else:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800511 error(clazz, m, "FW1", "Methods creating an Intent must be named createFooIntent()")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700512
513
514def verify_helper_classes(clazz):
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700515 """Verify that helper classes are named consistently with what they extend.
516 All developer extendable methods should be named onFoo()."""
517 test_methods = False
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700518 if "extends android.app.Service" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700519 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700520 if not clazz.name.endswith("Service"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800521 error(clazz, None, "CL4", "Inconsistent class name; should be FooService")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700522
523 found = False
524 for f in clazz.fields:
525 if f.name == "SERVICE_INTERFACE":
526 found = True
527 if f.value != clazz.fullname:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800528 error(clazz, f, "C4", "Inconsistent interface constant; expected %s" % (clazz.fullname))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700529
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700530 if "extends android.content.ContentProvider" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700531 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700532 if not clazz.name.endswith("Provider"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800533 error(clazz, None, "CL4", "Inconsistent class name; should be FooProvider")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700534
535 found = False
536 for f in clazz.fields:
537 if f.name == "PROVIDER_INTERFACE":
538 found = True
539 if f.value != clazz.fullname:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800540 error(clazz, f, "C4", "Inconsistent interface constant; expected %s" % (clazz.fullname))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700541
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700542 if "extends android.content.BroadcastReceiver" in clazz.raw:
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700543 test_methods = True
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700544 if not clazz.name.endswith("Receiver"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800545 error(clazz, None, "CL4", "Inconsistent class name; should be FooReceiver")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700546
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700547 if "extends android.app.Activity" in clazz.raw:
548 test_methods = True
549 if not clazz.name.endswith("Activity"):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800550 error(clazz, None, "CL4", "Inconsistent class name; should be FooActivity")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700551
552 if test_methods:
553 for m in clazz.methods:
554 if "final" in m.split: continue
555 if not re.match("on[A-Z]", m.name):
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700556 if "abstract" in m.split:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800557 warn(clazz, m, None, "Methods implemented by developers should be named onFoo()")
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700558 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800559 warn(clazz, m, None, "If implemented by developer, should be named onFoo(); otherwise consider marking final")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700560
561
562def verify_builder(clazz):
563 """Verify builder classes.
564 Methods should return the builder to enable chaining."""
565 if " extends " in clazz.raw: return
566 if not clazz.name.endswith("Builder"): return
567
568 if clazz.name != "Builder":
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800569 warn(clazz, None, None, "Builder should be defined as inner class")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700570
571 has_build = False
572 for m in clazz.methods:
573 if m.name == "build":
574 has_build = True
575 continue
576
577 if m.name.startswith("get"): continue
578 if m.name.startswith("clear"): continue
579
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700580 if m.name.startswith("with"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800581 warn(clazz, m, None, "Builder methods names should use setFoo() style")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700582
583 if m.name.startswith("set"):
584 if not m.typ.endswith(clazz.fullname):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800585 warn(clazz, m, "M4", "Methods must return the builder object")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700586
587 if not has_build:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800588 warn(clazz, None, None, "Missing build() method")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700589
590
591def verify_aidl(clazz):
592 """Catch people exposing raw AIDL."""
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700593 if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800594 error(clazz, None, None, "Raw AIDL interfaces must not be exposed")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700595
596
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700597def verify_internal(clazz):
598 """Catch people exposing internal classes."""
599 if clazz.pkg.name.startswith("com.android"):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800600 error(clazz, None, None, "Internal classes must not be exposed")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700601
602
603def verify_layering(clazz):
604 """Catch package layering violations.
605 For example, something in android.os depending on android.app."""
606 ranking = [
607 ["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
608 "android.app",
609 "android.widget",
610 "android.view",
611 "android.animation",
612 "android.provider",
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700613 ["android.content","android.graphics.drawable"],
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700614 "android.database",
615 "android.graphics",
616 "android.text",
617 "android.os",
618 "android.util"
619 ]
620
621 def rank(p):
622 for i in range(len(ranking)):
623 if isinstance(ranking[i], list):
624 for j in ranking[i]:
625 if p.startswith(j): return i
626 else:
627 if p.startswith(ranking[i]): return i
628
629 cr = rank(clazz.pkg.name)
630 if cr is None: return
631
632 for f in clazz.fields:
633 ir = rank(f.typ)
634 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800635 warn(clazz, f, "FW6", "Field type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700636
637 for m in clazz.methods:
638 ir = rank(m.typ)
639 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800640 warn(clazz, m, "FW6", "Method return type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700641 for arg in m.args:
642 ir = rank(arg)
643 if ir and ir < cr:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800644 warn(clazz, m, "FW6", "Method argument type violates package layering")
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700645
646
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700647def verify_boolean(clazz, api):
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800648 """Verifies that boolean accessors are named correctly.
649 For example, hasFoo() and setHasFoo()."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700650
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800651 def is_get(m): return len(m.args) == 0 and m.typ == "boolean"
652 def is_set(m): return len(m.args) == 1 and m.args[0] == "boolean"
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700653
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800654 gets = [ m for m in clazz.methods if is_get(m) ]
655 sets = [ m for m in clazz.methods if is_set(m) ]
656
657 def error_if_exists(methods, trigger, expected, actual):
658 for m in methods:
659 if m.name == actual:
660 error(clazz, m, "M6", "Symmetric method for %s must be named %s" % (trigger, expected))
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700661
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700662 for m in clazz.methods:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800663 if is_get(m):
664 if re.match("is[A-Z]", m.name):
665 target = m.name[2:]
666 expected = "setIs" + target
667 error_if_exists(sets, m.name, expected, "setHas" + target)
668 elif re.match("has[A-Z]", m.name):
669 target = m.name[3:]
670 expected = "setHas" + target
671 error_if_exists(sets, m.name, expected, "setIs" + target)
672 error_if_exists(sets, m.name, expected, "set" + target)
673 elif re.match("get[A-Z]", m.name):
674 target = m.name[3:]
675 expected = "set" + target
676 error_if_exists(sets, m.name, expected, "setIs" + target)
677 error_if_exists(sets, m.name, expected, "setHas" + target)
678
679 if is_set(m):
680 if re.match("set[A-Z]", m.name):
681 target = m.name[3:]
682 expected = "get" + target
683 error_if_exists(sets, m.name, expected, "is" + target)
684 error_if_exists(sets, m.name, expected, "has" + target)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700685
686
687def verify_collections(clazz):
688 """Verifies that collection types are interfaces."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700689 if clazz.fullname == "android.os.Bundle": return
690
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700691 bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
692 "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
693 for m in clazz.methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700694 if m.typ in bad:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800695 error(clazz, m, "CL2", "Return type is concrete collection; must be higher-level interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700696 for arg in m.args:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700697 if arg in bad:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800698 error(clazz, m, "CL2", "Argument is concrete collection; must be higher-level interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700699
700
701def verify_flags(clazz):
702 """Verifies that flags are non-overlapping."""
703 known = collections.defaultdict(int)
704 for f in clazz.fields:
705 if "FLAG_" in f.name:
706 try:
707 val = int(f.value)
708 except:
709 continue
710
711 scope = f.name[0:f.name.index("FLAG_")]
712 if val & known[scope]:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800713 warn(clazz, f, "C1", "Found overlapping flag constant value")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700714 known[scope] |= val
715
716
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800717def verify_exception(clazz):
718 """Verifies that methods don't throw generic exceptions."""
719 for m in clazz.methods:
720 if "throws java.lang.Exception" in m.raw or "throws java.lang.Throwable" in m.raw or "throws java.lang.Error" in m.raw:
721 error(clazz, m, "S1", "Methods must not throw generic exceptions")
722
723
724def verify_google(clazz):
725 """Verifies that APIs never reference Google."""
726
727 if re.search("google", clazz.raw, re.IGNORECASE):
728 error(clazz, None, None, "Must never reference Google")
729
730 test = []
731 test.extend(clazz.ctors)
732 test.extend(clazz.fields)
733 test.extend(clazz.methods)
734
735 for t in test:
736 if re.search("google", t.raw, re.IGNORECASE):
737 error(clazz, t, None, "Must never reference Google")
738
739
740def verify_bitset(clazz):
741 """Verifies that we avoid using heavy BitSet."""
742
743 for f in clazz.fields:
744 if f.typ == "java.util.BitSet":
745 error(clazz, f, None, "Field type must not be heavy BitSet")
746
747 for m in clazz.methods:
748 if m.typ == "java.util.BitSet":
749 error(clazz, m, None, "Return type must not be heavy BitSet")
750 for arg in m.args:
751 if arg == "java.util.BitSet":
752 error(clazz, m, None, "Argument type must not be heavy BitSet")
753
754
755def verify_manager(clazz):
756 """Verifies that FooManager is only obtained from Context."""
757
758 if not clazz.name.endswith("Manager"): return
759
760 for c in clazz.ctors:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800761 error(clazz, c, None, "Managers must always be obtained from Context")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800762
763
764def verify_boxed(clazz):
765 """Verifies that methods avoid boxed primitives."""
766
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800767 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 -0800768
769 for c in clazz.ctors:
770 for arg in c.args:
771 if arg in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800772 error(clazz, c, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800773
774 for f in clazz.fields:
775 if f.typ in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800776 error(clazz, f, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800777
778 for m in clazz.methods:
779 if m.typ in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800780 error(clazz, m, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800781 for arg in m.args:
782 if arg in boxed:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800783 error(clazz, m, "M11", "Must avoid boxed primitives")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800784
785
786def verify_static_utils(clazz):
787 """Verifies that helper classes can't be constructed."""
788 if clazz.fullname.startswith("android.opengl"): return
789 if re.match("android\.R\.[a-z]+", clazz.fullname): return
790
791 if len(clazz.fields) > 0: return
792 if len(clazz.methods) == 0: return
793
794 for m in clazz.methods:
795 if "static" not in m.split:
796 return
797
798 # At this point, we have no fields, and all methods are static
799 if len(clazz.ctors) > 0:
800 error(clazz, None, None, "Fully-static utility classes must not have constructor")
801
802
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800803def verify_overload_args(clazz):
804 """Verifies that method overloads add new arguments at the end."""
805 if clazz.fullname.startswith("android.opengl"): return
806
807 overloads = collections.defaultdict(list)
808 for m in clazz.methods:
809 if "deprecated" in m.split: continue
810 overloads[m.name].append(m)
811
812 for name, methods in overloads.iteritems():
813 if len(methods) <= 1: continue
814
815 # Look for arguments common across all overloads
816 def cluster(args):
817 count = collections.defaultdict(int)
818 res = set()
819 for i in range(len(args)):
820 a = args[i]
821 res.add("%s#%d" % (a, count[a]))
822 count[a] += 1
823 return res
824
825 common_args = cluster(methods[0].args)
826 for m in methods:
827 common_args = common_args & cluster(m.args)
828
829 if len(common_args) == 0: continue
830
831 # Require that all common arguments are present at start of signature
832 locked_sig = None
833 for m in methods:
834 sig = m.args[0:len(common_args)]
835 if not common_args.issubset(cluster(sig)):
836 warn(clazz, m, "M2", "Expected common arguments [%s] at beginning of overloaded method" % (", ".join(common_args)))
837 elif not locked_sig:
838 locked_sig = sig
839 elif locked_sig != sig:
840 error(clazz, m, "M2", "Expected consistent argument ordering between overloads: %s..." % (", ".join(locked_sig)))
841
842
843def verify_callback_handlers(clazz):
844 """Verifies that methods adding listener/callback have overload
845 for specifying delivery thread."""
846
847 # Ignore UI components which deliver things on main thread
848 skip = [
849 "android.animation",
850 "android.view",
851 "android.graphics",
852 "android.transition",
853 "android.widget",
854 "android.webkit",
855 ]
856 for s in skip:
857 if clazz.fullname.startswith(s): return
858 if clazz.extends and clazz.extends.startswith(s): return
859
860 skip = [
861 "android.app.ActionBar",
862 "android.app.AlertDialog",
863 "android.app.AlertDialog.Builder",
864 "android.app.Application",
865 "android.app.Activity",
866 "android.app.Dialog",
867 "android.app.Fragment",
868 "android.app.FragmentManager",
869 "android.app.LoaderManager",
870 "android.app.ListActivity",
871 "android.app.AlertDialog.Builder"
872 "android.content.Loader",
873 ]
874 for s in skip:
875 if clazz.fullname == s or clazz.extends == s: return
876
877 found = {}
878 by_name = collections.defaultdict(list)
879 for m in clazz.methods:
880 if m.name.startswith("unregister"): continue
881 if m.name.startswith("remove"): continue
882 if re.match("on[A-Z]+", m.name): continue
883
884 by_name[m.name].append(m)
885
886 for a in m.args:
887 if a.endswith("Listener") or a.endswith("Callback") or a.endswith("Callbacks"):
888 found[m.name] = m
889
890 for f in found.values():
891 takes_handler = False
892 for m in by_name[f.name]:
893 if "android.os.Handler" in m.args:
894 takes_handler = True
895 if not takes_handler:
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800896 warn(clazz, f, "L1", "Registration methods should have overload that accepts delivery Handler")
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800897
898
899def verify_context_first(clazz):
900 """Verifies that methods accepting a Context keep it the first argument."""
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800901 examine = clazz.ctors + clazz.methods
902 for m in examine:
903 if len(m.args) > 1 and m.args[0] != "android.content.Context":
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800904 if "android.content.Context" in m.args[1:]:
905 error(clazz, m, "M3", "Context is distinct, so it must be the first argument")
906
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800907
908def verify_listener_last(clazz):
909 """Verifies that methods accepting a Listener or Callback keep them as last arguments."""
910 examine = clazz.ctors + clazz.methods
911 for m in examine:
912 if "Listener" in m.name or "Callback" in m.name: continue
913 found = False
914 for a in m.args:
915 if a.endswith("Callback") or a.endswith("Callbacks") or a.endswith("Listener"):
916 found = True
917 elif found and a != "android.os.Handler":
918 warn(clazz, m, "M3", "Listeners should always be at end of argument list")
919
920
921def verify_resource_names(clazz):
922 """Verifies that resource names have consistent case."""
923 if not re.match("android\.R\.[a-z]+", clazz.fullname): return
924
925 # Resources defined by files are foo_bar_baz
926 if clazz.name in ["anim","animator","color","dimen","drawable","interpolator","layout","transition","menu","mipmap","string","plurals","raw","xml"]:
927 for f in clazz.fields:
928 if re.match("[a-z1-9_]+$", f.name): continue
929 error(clazz, f, None, "Expected resource name in this class to be foo_bar_baz style")
930
931 # Resources defined inside files are fooBarBaz
932 if clazz.name in ["array","attr","id","bool","fraction","integer"]:
933 for f in clazz.fields:
934 if re.match("config_[a-z][a-zA-Z1-9]*$", f.name): continue
935 if re.match("layout_[a-z][a-zA-Z1-9]*$", f.name): continue
936 if re.match("state_[a-z_]*$", f.name): continue
937
938 if re.match("[a-z][a-zA-Z1-9]*$", f.name): continue
939 error(clazz, f, "C7", "Expected resource name in this class to be fooBarBaz style")
940
941 # Styles are FooBar_Baz
942 if clazz.name in ["style"]:
943 for f in clazz.fields:
944 if re.match("[A-Z][A-Za-z1-9]+(_[A-Z][A-Za-z1-9]+?)*$", f.name): continue
945 error(clazz, f, "C7", "Expected resource name in this class to be FooBar_Baz style")
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800946
947
Jeff Sharkey037458a2014-09-04 15:46:20 -0700948def verify_style(api):
949 """Find all style issues in the given API level."""
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700950 global failures
951
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700952 failures = {}
953 for key in sorted(api.keys()):
954 clazz = api[key]
955
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700956 if clazz.pkg.name.startswith("java"): continue
957 if clazz.pkg.name.startswith("junit"): continue
958 if clazz.pkg.name.startswith("org.apache"): continue
959 if clazz.pkg.name.startswith("org.xml"): continue
960 if clazz.pkg.name.startswith("org.json"): continue
961 if clazz.pkg.name.startswith("org.w3c"): continue
962
963 verify_constants(clazz)
964 verify_enums(clazz)
965 verify_class_names(clazz)
966 verify_method_names(clazz)
967 verify_callbacks(clazz)
968 verify_listeners(clazz)
969 verify_actions(clazz)
970 verify_extras(clazz)
971 verify_equals(clazz)
972 verify_parcelable(clazz)
973 verify_protected(clazz)
974 verify_fields(clazz)
975 verify_register(clazz)
976 verify_sync(clazz)
977 verify_intent_builder(clazz)
978 verify_helper_classes(clazz)
979 verify_builder(clazz)
980 verify_aidl(clazz)
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700981 verify_internal(clazz)
982 verify_layering(clazz)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700983 verify_boolean(clazz, api)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700984 verify_collections(clazz)
985 verify_flags(clazz)
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800986 verify_exception(clazz)
987 verify_google(clazz)
988 verify_bitset(clazz)
989 verify_manager(clazz)
990 verify_boxed(clazz)
991 verify_static_utils(clazz)
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800992 verify_overload_args(clazz)
993 verify_callback_handlers(clazz)
994 verify_context_first(clazz)
Jeff Sharkey90b547b2015-02-18 16:45:54 -0800995 verify_listener_last(clazz)
996 verify_resource_names(clazz)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700997
998 return failures
999
1000
Jeff Sharkey037458a2014-09-04 15:46:20 -07001001def verify_compat(cur, prev):
1002 """Find any incompatible API changes between two levels."""
1003 global failures
1004
1005 def class_exists(api, test):
1006 return test.fullname in api
1007
1008 def ctor_exists(api, clazz, test):
1009 for m in clazz.ctors:
1010 if m.ident == test.ident: return True
1011 return False
1012
1013 def all_methods(api, clazz):
1014 methods = list(clazz.methods)
1015 if clazz.extends is not None:
1016 methods.extend(all_methods(api, api[clazz.extends]))
1017 return methods
1018
1019 def method_exists(api, clazz, test):
1020 methods = all_methods(api, clazz)
1021 for m in methods:
1022 if m.ident == test.ident: return True
1023 return False
1024
1025 def field_exists(api, clazz, test):
1026 for f in clazz.fields:
1027 if f.ident == test.ident: return True
1028 return False
1029
1030 failures = {}
1031 for key in sorted(prev.keys()):
1032 prev_clazz = prev[key]
1033
1034 if not class_exists(cur, prev_clazz):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001035 error(prev_clazz, None, None, "Class removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001036 continue
1037
1038 cur_clazz = cur[key]
1039
1040 for test in prev_clazz.ctors:
1041 if not ctor_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001042 error(prev_clazz, prev_ctor, None, "Constructor removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001043
1044 methods = all_methods(prev, prev_clazz)
1045 for test in methods:
1046 if not method_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001047 error(prev_clazz, test, None, "Method removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001048
1049 for test in prev_clazz.fields:
1050 if not field_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -08001051 error(prev_clazz, test, None, "Field removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -07001052
1053 return failures
1054
1055
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001056if __name__ == "__main__":
1057 cur = parse_api_file(sys.argv[1])
1058 cur_fail = verify_style(cur)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001059
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001060 if len(sys.argv) > 2:
1061 prev = parse_api_file(sys.argv[2])
1062 prev_fail = verify_style(prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001063
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001064 # ignore errors from previous API level
1065 for p in prev_fail:
1066 if p in cur_fail:
1067 del cur_fail[p]
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001068
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001069 # look for compatibility issues
1070 compat_fail = verify_compat(cur, prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001071
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001072 print "%s API compatibility issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1073 for f in sorted(compat_fail):
1074 print compat_fail[f]
1075 print
1076
1077
1078 print "%s API style issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1079 for f in sorted(cur_fail):
1080 print cur_fail[f]
Jeff Sharkey037458a2014-09-04 15:46:20 -07001081 print