blob: b8eaa2da9d2ef0a2aede5d953e8b89a5ac96f87f [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 Sharkey9f64d5c62015-02-14 17:03:47 -0800256 error(clazz, f, "C2", "Constant field names should 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800272 warn(clazz, None, "S1", "Class name style 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800285 warn(clazz, m, "S1", "Method name style 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800297 error(clazz, None, "L1", "Class name must not be plural")
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 Sharkey9f64d5c62015-02-14 17:03:47 -0800303 error(clazz, None, "CL3", "Callback 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800319 error(clazz, None, "L1", "Listener should be an interface, 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800328 error(clazz, m, "L1", "Single listener method name should 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800415 error(clazz, m, "M7", "No protected methods; must be public")
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700416 for f in clazz.fields:
417 if "protected" in f.split:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800418 error(clazz, f, "M7", "No protected fields; 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800452 error(clazz, f, "S1", "Non-static fields must be named with 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800455 error(clazz, f, "F1", "Don't expose your internal objects")
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 Sharkey9f64d5c62015-02-14 17:03:47 -0800499 error(clazz, m, "M5", "Internal lock 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800511 error(clazz, m, "FW1", "Methods creating an Intent should 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800540 error(clazz, f, "C4", "Inconsistent interface name; 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 Sharkeyb46a9692015-02-17 17:19:41 -0800581 warn(clazz, m, None, "Builder methods names should follow 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 Sharkey9f64d5c62015-02-14 17:03:47 -0800585 warn(clazz, m, "M4", "Methods should return the builder")
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 Sharkey9f64d5c62015-02-14 17:03:47 -0800594 error(clazz, None, None, "Exposing raw AIDL interface")
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 Sharkey9f64d5c62015-02-14 17:03:47 -0800600 error(clazz, None, None, "Exposing internal class")
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 Sharkey294f0de2014-08-29 17:41:43 -0700648 """Catches people returning boolean from getFoo() style methods.
649 Ignores when matching setFoo() is present."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700650
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700651 methods = [ m.name for m in clazz.methods ]
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700652
653 builder = clazz.fullname + ".Builder"
654 builder_methods = []
655 if builder in api:
656 builder_methods = [ m.name for m in api[builder].methods ]
657
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700658 for m in clazz.methods:
659 if m.typ == "boolean" and m.name.startswith("get") and m.name != "get" and len(m.args) == 0:
660 setter = "set" + m.name[3:]
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700661 if setter in methods:
662 pass
663 elif builder is not None and setter in builder_methods:
664 pass
665 else:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800666 warn(clazz, m, None, "Methods returning boolean should be named isFoo, hasFoo, areFoo")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700667
668
669def verify_collections(clazz):
670 """Verifies that collection types are interfaces."""
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700671 if clazz.fullname == "android.os.Bundle": return
672
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700673 bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
674 "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
675 for m in clazz.methods:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700676 if m.typ in bad:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800677 error(clazz, m, "CL2", "Return type is concrete collection; should be interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700678 for arg in m.args:
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700679 if arg in bad:
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800680 error(clazz, m, "CL2", "Argument is concrete collection; should be interface")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700681
682
683def verify_flags(clazz):
684 """Verifies that flags are non-overlapping."""
685 known = collections.defaultdict(int)
686 for f in clazz.fields:
687 if "FLAG_" in f.name:
688 try:
689 val = int(f.value)
690 except:
691 continue
692
693 scope = f.name[0:f.name.index("FLAG_")]
694 if val & known[scope]:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800695 warn(clazz, f, "C1", "Found overlapping flag constant value")
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700696 known[scope] |= val
697
698
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800699def verify_exception(clazz):
700 """Verifies that methods don't throw generic exceptions."""
701 for m in clazz.methods:
702 if "throws java.lang.Exception" in m.raw or "throws java.lang.Throwable" in m.raw or "throws java.lang.Error" in m.raw:
703 error(clazz, m, "S1", "Methods must not throw generic exceptions")
704
705
706def verify_google(clazz):
707 """Verifies that APIs never reference Google."""
708
709 if re.search("google", clazz.raw, re.IGNORECASE):
710 error(clazz, None, None, "Must never reference Google")
711
712 test = []
713 test.extend(clazz.ctors)
714 test.extend(clazz.fields)
715 test.extend(clazz.methods)
716
717 for t in test:
718 if re.search("google", t.raw, re.IGNORECASE):
719 error(clazz, t, None, "Must never reference Google")
720
721
722def verify_bitset(clazz):
723 """Verifies that we avoid using heavy BitSet."""
724
725 for f in clazz.fields:
726 if f.typ == "java.util.BitSet":
727 error(clazz, f, None, "Field type must not be heavy BitSet")
728
729 for m in clazz.methods:
730 if m.typ == "java.util.BitSet":
731 error(clazz, m, None, "Return type must not be heavy BitSet")
732 for arg in m.args:
733 if arg == "java.util.BitSet":
734 error(clazz, m, None, "Argument type must not be heavy BitSet")
735
736
737def verify_manager(clazz):
738 """Verifies that FooManager is only obtained from Context."""
739
740 if not clazz.name.endswith("Manager"): return
741
742 for c in clazz.ctors:
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800743 error(clazz, c, None, "Managers should always be obtained from Context")
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800744
745
746def verify_boxed(clazz):
747 """Verifies that methods avoid boxed primitives."""
748
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800749 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 -0800750
751 for c in clazz.ctors:
752 for arg in c.args:
753 if arg in boxed:
754 error(clazz, c, None, "Must avoid boxed primitives")
755
756 for f in clazz.fields:
757 if f.typ in boxed:
758 error(clazz, f, None, "Must avoid boxed primitives")
759
760 for m in clazz.methods:
761 if m.typ in boxed:
762 error(clazz, m, None, "Must avoid boxed primitives")
763 for arg in m.args:
764 if arg in boxed:
765 error(clazz, m, None, "Must avoid boxed primitives")
766
767
768def verify_static_utils(clazz):
769 """Verifies that helper classes can't be constructed."""
770 if clazz.fullname.startswith("android.opengl"): return
771 if re.match("android\.R\.[a-z]+", clazz.fullname): return
772
773 if len(clazz.fields) > 0: return
774 if len(clazz.methods) == 0: return
775
776 for m in clazz.methods:
777 if "static" not in m.split:
778 return
779
780 # At this point, we have no fields, and all methods are static
781 if len(clazz.ctors) > 0:
782 error(clazz, None, None, "Fully-static utility classes must not have constructor")
783
784
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800785def verify_overload_args(clazz):
786 """Verifies that method overloads add new arguments at the end."""
787 if clazz.fullname.startswith("android.opengl"): return
788
789 overloads = collections.defaultdict(list)
790 for m in clazz.methods:
791 if "deprecated" in m.split: continue
792 overloads[m.name].append(m)
793
794 for name, methods in overloads.iteritems():
795 if len(methods) <= 1: continue
796
797 # Look for arguments common across all overloads
798 def cluster(args):
799 count = collections.defaultdict(int)
800 res = set()
801 for i in range(len(args)):
802 a = args[i]
803 res.add("%s#%d" % (a, count[a]))
804 count[a] += 1
805 return res
806
807 common_args = cluster(methods[0].args)
808 for m in methods:
809 common_args = common_args & cluster(m.args)
810
811 if len(common_args) == 0: continue
812
813 # Require that all common arguments are present at start of signature
814 locked_sig = None
815 for m in methods:
816 sig = m.args[0:len(common_args)]
817 if not common_args.issubset(cluster(sig)):
818 warn(clazz, m, "M2", "Expected common arguments [%s] at beginning of overloaded method" % (", ".join(common_args)))
819 elif not locked_sig:
820 locked_sig = sig
821 elif locked_sig != sig:
822 error(clazz, m, "M2", "Expected consistent argument ordering between overloads: %s..." % (", ".join(locked_sig)))
823
824
825def verify_callback_handlers(clazz):
826 """Verifies that methods adding listener/callback have overload
827 for specifying delivery thread."""
828
829 # Ignore UI components which deliver things on main thread
830 skip = [
831 "android.animation",
832 "android.view",
833 "android.graphics",
834 "android.transition",
835 "android.widget",
836 "android.webkit",
837 ]
838 for s in skip:
839 if clazz.fullname.startswith(s): return
840 if clazz.extends and clazz.extends.startswith(s): return
841
842 skip = [
843 "android.app.ActionBar",
844 "android.app.AlertDialog",
845 "android.app.AlertDialog.Builder",
846 "android.app.Application",
847 "android.app.Activity",
848 "android.app.Dialog",
849 "android.app.Fragment",
850 "android.app.FragmentManager",
851 "android.app.LoaderManager",
852 "android.app.ListActivity",
853 "android.app.AlertDialog.Builder"
854 "android.content.Loader",
855 ]
856 for s in skip:
857 if clazz.fullname == s or clazz.extends == s: return
858
859 found = {}
860 by_name = collections.defaultdict(list)
861 for m in clazz.methods:
862 if m.name.startswith("unregister"): continue
863 if m.name.startswith("remove"): continue
864 if re.match("on[A-Z]+", m.name): continue
865
866 by_name[m.name].append(m)
867
868 for a in m.args:
869 if a.endswith("Listener") or a.endswith("Callback") or a.endswith("Callbacks"):
870 found[m.name] = m
871
872 for f in found.values():
873 takes_handler = False
874 for m in by_name[f.name]:
875 if "android.os.Handler" in m.args:
876 takes_handler = True
877 if not takes_handler:
878 error(clazz, f, "L1", "Registration methods should have overload that accepts delivery Handler")
879
880
881def verify_context_first(clazz):
882 """Verifies that methods accepting a Context keep it the first argument."""
883 for m in clazz.ctors:
884 if len(m.args) > 1:
885 if "android.content.Context" in m.args[1:]:
886 error(clazz, m, "M3", "Context is distinct, so it must be the first argument")
887
888 for m in clazz.methods:
889 if len(m.args) > 1:
890 if "android.content.Context" in m.args[1:]:
891 error(clazz, m, "M3", "Context is distinct, so it must be the first argument")
892
893
Jeff Sharkey037458a2014-09-04 15:46:20 -0700894def verify_style(api):
895 """Find all style issues in the given API level."""
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700896 global failures
897
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700898 failures = {}
899 for key in sorted(api.keys()):
900 clazz = api[key]
901
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700902 if clazz.pkg.name.startswith("java"): continue
903 if clazz.pkg.name.startswith("junit"): continue
904 if clazz.pkg.name.startswith("org.apache"): continue
905 if clazz.pkg.name.startswith("org.xml"): continue
906 if clazz.pkg.name.startswith("org.json"): continue
907 if clazz.pkg.name.startswith("org.w3c"): continue
908
909 verify_constants(clazz)
910 verify_enums(clazz)
911 verify_class_names(clazz)
912 verify_method_names(clazz)
913 verify_callbacks(clazz)
914 verify_listeners(clazz)
915 verify_actions(clazz)
916 verify_extras(clazz)
917 verify_equals(clazz)
918 verify_parcelable(clazz)
919 verify_protected(clazz)
920 verify_fields(clazz)
921 verify_register(clazz)
922 verify_sync(clazz)
923 verify_intent_builder(clazz)
924 verify_helper_classes(clazz)
925 verify_builder(clazz)
926 verify_aidl(clazz)
Jeff Sharkey932a07c2014-08-28 16:16:02 -0700927 verify_internal(clazz)
928 verify_layering(clazz)
Jeff Sharkey1498f9c2014-09-04 12:45:33 -0700929 verify_boolean(clazz, api)
Jeff Sharkey294f0de2014-08-29 17:41:43 -0700930 verify_collections(clazz)
931 verify_flags(clazz)
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800932 verify_exception(clazz)
933 verify_google(clazz)
934 verify_bitset(clazz)
935 verify_manager(clazz)
936 verify_boxed(clazz)
937 verify_static_utils(clazz)
Jeff Sharkeyb46a9692015-02-17 17:19:41 -0800938 verify_overload_args(clazz)
939 verify_callback_handlers(clazz)
940 verify_context_first(clazz)
Jeff Sharkey8190f4882014-08-28 12:24:07 -0700941
942 return failures
943
944
Jeff Sharkey037458a2014-09-04 15:46:20 -0700945def verify_compat(cur, prev):
946 """Find any incompatible API changes between two levels."""
947 global failures
948
949 def class_exists(api, test):
950 return test.fullname in api
951
952 def ctor_exists(api, clazz, test):
953 for m in clazz.ctors:
954 if m.ident == test.ident: return True
955 return False
956
957 def all_methods(api, clazz):
958 methods = list(clazz.methods)
959 if clazz.extends is not None:
960 methods.extend(all_methods(api, api[clazz.extends]))
961 return methods
962
963 def method_exists(api, clazz, test):
964 methods = all_methods(api, clazz)
965 for m in methods:
966 if m.ident == test.ident: return True
967 return False
968
969 def field_exists(api, clazz, test):
970 for f in clazz.fields:
971 if f.ident == test.ident: return True
972 return False
973
974 failures = {}
975 for key in sorted(prev.keys()):
976 prev_clazz = prev[key]
977
978 if not class_exists(cur, prev_clazz):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800979 error(prev_clazz, None, None, "Class removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -0700980 continue
981
982 cur_clazz = cur[key]
983
984 for test in prev_clazz.ctors:
985 if not ctor_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800986 error(prev_clazz, prev_ctor, None, "Constructor removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -0700987
988 methods = all_methods(prev, prev_clazz)
989 for test in methods:
990 if not method_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800991 error(prev_clazz, test, None, "Method removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -0700992
993 for test in prev_clazz.fields:
994 if not field_exists(cur, cur_clazz, test):
Jeff Sharkey9f64d5c62015-02-14 17:03:47 -0800995 error(prev_clazz, test, None, "Field removed or incompatible change")
Jeff Sharkey037458a2014-09-04 15:46:20 -0700996
997 return failures
998
999
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001000if __name__ == "__main__":
1001 cur = parse_api_file(sys.argv[1])
1002 cur_fail = verify_style(cur)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001003
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001004 if len(sys.argv) > 2:
1005 prev = parse_api_file(sys.argv[2])
1006 prev_fail = verify_style(prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001007
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001008 # ignore errors from previous API level
1009 for p in prev_fail:
1010 if p in cur_fail:
1011 del cur_fail[p]
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001012
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001013 # look for compatibility issues
1014 compat_fail = verify_compat(cur, prev)
Jeff Sharkey8190f4882014-08-28 12:24:07 -07001015
Jeff Sharkeyed6aaf02015-01-30 13:31:45 -07001016 print "%s API compatibility issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1017 for f in sorted(compat_fail):
1018 print compat_fail[f]
1019 print
1020
1021
1022 print "%s API style issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
1023 for f in sorted(cur_fail):
1024 print cur_fail[f]
Jeff Sharkey037458a2014-09-04 15:46:20 -07001025 print