OSDN Git Service

am b18fdbb1: am 3703cae1: Merge "Camera2: Check for sequence complete sooner." into...
[android-x86/frameworks-base.git] / tools / apilint / apilint.py
1 #!/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 """
18 Enforces common Android public API design patterns.  It ignores lint messages from
19 a previous API level, if provided.
20
21 Usage: apilint.py current.txt
22 Usage: apilint.py current.txt previous.txt
23
24 You 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
27 """
28
29 import re, sys, collections, traceback
30
31
32 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
33
34 def 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
36     if "--no-color" in sys.argv: return ""
37     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
50 class Field():
51     def __init__(self, clazz, raw, blame):
52         self.clazz = clazz
53         self.raw = raw.strip(" {;")
54         self.blame = blame
55
56         raw = raw.split()
57         self.split = list(raw)
58
59         for r in ["field", "volatile", "transient", "public", "protected", "static", "final", "deprecated"]:
60             while r in raw: raw.remove(r)
61
62         self.typ = raw[0]
63         self.name = raw[1].strip(";")
64         if len(raw) >= 4 and raw[2] == "=":
65             self.value = raw[3].strip(';"')
66         else:
67             self.value = None
68
69         self.ident = self.raw.replace(" deprecated ", " ")
70
71     def __repr__(self):
72         return self.raw
73
74
75 class Method():
76     def __init__(self, clazz, raw, blame):
77         self.clazz = clazz
78         self.raw = raw.strip(" {;")
79         self.blame = blame
80
81         # drop generics for now
82         raw = re.sub("<.+?>", "", raw)
83
84         raw = re.split("[\s(),;]+", raw)
85         for r in ["", ";"]:
86             while r in raw: raw.remove(r)
87         self.split = list(raw)
88
89         for r in ["method", "public", "protected", "static", "final", "deprecated", "abstract"]:
90             while r in raw: raw.remove(r)
91
92         self.typ = raw[0]
93         self.name = raw[1]
94         self.args = []
95         for r in raw[2:]:
96             if r == "throws": break
97             self.args.append(r)
98
99         # identity for compat purposes
100         ident = self.raw
101         ident = ident.replace(" deprecated ", " ")
102         ident = ident.replace(" synchronized ", " ")
103         ident = re.sub("<.+?>", "", ident)
104         if " throws " in ident:
105             ident = ident[:ident.index(" throws ")]
106         self.ident = ident
107
108     def __repr__(self):
109         return self.raw
110
111
112 class Class():
113     def __init__(self, pkg, raw, blame):
114         self.pkg = pkg
115         self.raw = raw.strip(" {;")
116         self.blame = blame
117         self.ctors = []
118         self.fields = []
119         self.methods = []
120
121         raw = raw.split()
122         self.split = list(raw)
123         if "class" in raw:
124             self.fullname = raw[raw.index("class")+1]
125         elif "interface" in raw:
126             self.fullname = raw[raw.index("interface")+1]
127         else:
128             raise ValueError("Funky class type %s" % (self.raw))
129
130         if "extends" in raw:
131             self.extends = raw[raw.index("extends")+1]
132         else:
133             self.extends = None
134
135         self.fullname = self.pkg.name + "." + self.fullname
136         self.name = self.fullname[self.fullname.rindex(".")+1:]
137
138     def __repr__(self):
139         return self.raw
140
141
142 class Package():
143     def __init__(self, raw, blame):
144         self.raw = raw.strip(" {;")
145         self.blame = blame
146
147         raw = raw.split()
148         self.name = raw[raw.index("package")+1]
149
150     def __repr__(self):
151         return self.raw
152
153
154 def parse_api(fn):
155     api = {}
156     pkg = None
157     clazz = None
158     blame = None
159
160     re_blame = re.compile("^([a-z0-9]{7,}) \(<([^>]+)>.+?\) (.+?)$")
161
162     with open(fn) as f:
163         for raw in f.readlines():
164             raw = raw.rstrip()
165             match = re_blame.match(raw)
166             if match is not None:
167                 blame = match.groups()[0:2]
168                 raw = match.groups()[2]
169             else:
170                 blame = None
171
172             if raw.startswith("package"):
173                 pkg = Package(raw, blame)
174             elif raw.startswith("  ") and raw.endswith("{"):
175                 clazz = Class(pkg, raw, blame)
176                 api[clazz.fullname] = clazz
177             elif raw.startswith("    ctor"):
178                 clazz.ctors.append(Method(clazz, raw, blame))
179             elif raw.startswith("    method"):
180                 clazz.methods.append(Method(clazz, raw, blame))
181             elif raw.startswith("    field"):
182                 clazz.fields.append(Field(clazz, raw, blame))
183
184     return api
185
186
187 failures = {}
188
189 def _fail(clazz, detail, msg):
190     """Records an API failure to be processed later."""
191     global failures
192
193     sig = "%s-%s-%s" % (clazz.fullname, repr(detail), msg)
194     sig = sig.replace(" deprecated ", " ")
195
196     res = msg
197     blame = clazz.blame
198     if detail is not None:
199         res += "\n    in " + repr(detail)
200         blame = detail.blame
201     res += "\n    in " + repr(clazz)
202     res += "\n    in " + repr(clazz.pkg)
203     if blame is not None:
204         res += "\n    last modified by %s in %s" % (blame[1], blame[0])
205     failures[sig] = res
206
207 def warn(clazz, detail, msg):
208     _fail(clazz, detail, "%sWarning:%s %s" % (format(fg=YELLOW, bg=BLACK, bold=True), format(reset=True), msg))
209
210 def error(clazz, detail, msg):
211     _fail(clazz, detail, "%sError:%s %s" % (format(fg=RED, bg=BLACK, bold=True), format(reset=True), msg))
212
213
214 def verify_constants(clazz):
215     """All static final constants must be FOO_NAME style."""
216     if re.match("android\.R\.[a-z]+", clazz.fullname): return
217
218     for f in clazz.fields:
219         if "static" in f.split and "final" in f.split:
220             if re.match("[A-Z0-9_]+", f.name) is None:
221                 error(clazz, f, "Constant field names should be FOO_NAME")
222
223
224 def verify_enums(clazz):
225     """Enums are bad, mmkay?"""
226     if "extends java.lang.Enum" in clazz.raw:
227         error(clazz, None, "Enums are not allowed")
228
229
230 def verify_class_names(clazz):
231     """Try catching malformed class names like myMtp or MTPUser."""
232     if clazz.fullname.startswith("android.opengl"): return
233     if clazz.fullname.startswith("android.renderscript"): return
234     if re.match("android\.R\.[a-z]+", clazz.fullname): return
235
236     if re.search("[A-Z]{2,}", clazz.name) is not None:
237         warn(clazz, None, "Class name style should be Mtp not MTP")
238     if re.match("[^A-Z]", clazz.name):
239         error(clazz, None, "Class must start with uppercase char")
240
241
242 def verify_method_names(clazz):
243     """Try catching malformed method names, like Foo() or getMTU()."""
244     if clazz.fullname.startswith("android.opengl"): return
245     if clazz.fullname.startswith("android.renderscript"): return
246     if clazz.fullname == "android.system.OsConstants": return
247
248     for m in clazz.methods:
249         if re.search("[A-Z]{2,}", m.name) is not None:
250             warn(clazz, m, "Method name style should be getMtu() instead of getMTU()")
251         if re.match("[^a-z]", m.name):
252             error(clazz, m, "Method name must start with lowercase char")
253
254
255 def verify_callbacks(clazz):
256     """Verify Callback classes.
257     All callback classes must be abstract.
258     All methods must follow onFoo() naming style."""
259     if clazz.fullname == "android.speech.tts.SynthesisCallback": return
260
261     if clazz.name.endswith("Callbacks"):
262         error(clazz, None, "Class name must not be plural")
263     if clazz.name.endswith("Observer"):
264         warn(clazz, None, "Class should be named FooCallback")
265
266     if clazz.name.endswith("Callback"):
267         if "interface" in clazz.split:
268             error(clazz, None, "Callback must be abstract class to enable extension in future API levels")
269
270         for m in clazz.methods:
271             if not re.match("on[A-Z][a-z]*", m.name):
272                 error(clazz, m, "Callback method names must be onFoo() style")
273
274
275 def verify_listeners(clazz):
276     """Verify Listener classes.
277     All Listener classes must be interface.
278     All methods must follow onFoo() naming style.
279     If only a single method, it must match class name:
280         interface OnFooListener { void onFoo() }"""
281
282     if clazz.name.endswith("Listener"):
283         if " abstract class " in clazz.raw:
284             error(clazz, None, "Listener should be an interface, otherwise renamed Callback")
285
286         for m in clazz.methods:
287             if not re.match("on[A-Z][a-z]*", m.name):
288                 error(clazz, m, "Listener method names must be onFoo() style")
289
290         if len(clazz.methods) == 1 and clazz.name.startswith("On"):
291             m = clazz.methods[0]
292             if (m.name + "Listener").lower() != clazz.name.lower():
293                 error(clazz, m, "Single listener method name should match class name")
294
295
296 def verify_actions(clazz):
297     """Verify intent actions.
298     All action names must be named ACTION_FOO.
299     All action values must be scoped by package and match name:
300         package android.foo {
301             String ACTION_BAR = "android.foo.action.BAR";
302         }"""
303     for f in clazz.fields:
304         if f.value is None: continue
305         if f.name.startswith("EXTRA_"): continue
306         if f.name == "SERVICE_INTERFACE" or f.name == "PROVIDER_INTERFACE": continue
307
308         if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
309             if "_ACTION" in f.name or "ACTION_" in f.name or ".action." in f.value.lower():
310                 if not f.name.startswith("ACTION_"):
311                     error(clazz, f, "Intent action constant name must be ACTION_FOO")
312                 else:
313                     if clazz.fullname == "android.content.Intent":
314                         prefix = "android.intent.action"
315                     elif clazz.fullname == "android.provider.Settings":
316                         prefix = "android.settings"
317                     elif clazz.fullname == "android.app.admin.DevicePolicyManager" or clazz.fullname == "android.app.admin.DeviceAdminReceiver":
318                         prefix = "android.app.action"
319                     else:
320                         prefix = clazz.pkg.name + ".action"
321                     expected = prefix + "." + f.name[7:]
322                     if f.value != expected:
323                         error(clazz, f, "Inconsistent action value; expected %s" % (expected))
324
325
326 def verify_extras(clazz):
327     """Verify intent extras.
328     All extra names must be named EXTRA_FOO.
329     All extra values must be scoped by package and match name:
330         package android.foo {
331             String EXTRA_BAR = "android.foo.extra.BAR";
332         }"""
333     if clazz.fullname == "android.app.Notification": return
334     if clazz.fullname == "android.appwidget.AppWidgetManager": return
335
336     for f in clazz.fields:
337         if f.value is None: continue
338         if f.name.startswith("ACTION_"): continue
339
340         if "static" in f.split and "final" in f.split and f.typ == "java.lang.String":
341             if "_EXTRA" in f.name or "EXTRA_" in f.name or ".extra" in f.value.lower():
342                 if not f.name.startswith("EXTRA_"):
343                     error(clazz, f, "Intent extra must be EXTRA_FOO")
344                 else:
345                     if clazz.pkg.name == "android.content" and clazz.name == "Intent":
346                         prefix = "android.intent.extra"
347                     elif clazz.pkg.name == "android.app.admin":
348                         prefix = "android.app.extra"
349                     else:
350                         prefix = clazz.pkg.name + ".extra"
351                     expected = prefix + "." + f.name[6:]
352                     if f.value != expected:
353                         error(clazz, f, "Inconsistent extra value; expected %s" % (expected))
354
355
356 def verify_equals(clazz):
357     """Verify that equals() and hashCode() must be overridden together."""
358     methods = [ m.name for m in clazz.methods ]
359     eq = "equals" in methods
360     hc = "hashCode" in methods
361     if eq != hc:
362         error(clazz, None, "Must override both equals and hashCode; missing one")
363
364
365 def verify_parcelable(clazz):
366     """Verify that Parcelable objects aren't hiding required bits."""
367     if "implements android.os.Parcelable" in clazz.raw:
368         creator = [ i for i in clazz.fields if i.name == "CREATOR" ]
369         write = [ i for i in clazz.methods if i.name == "writeToParcel" ]
370         describe = [ i for i in clazz.methods if i.name == "describeContents" ]
371
372         if len(creator) == 0 or len(write) == 0 or len(describe) == 0:
373             error(clazz, None, "Parcelable requires CREATOR, writeToParcel, and describeContents; missing one")
374
375
376 def verify_protected(clazz):
377     """Verify that no protected methods are allowed."""
378     for m in clazz.methods:
379         if "protected" in m.split:
380             error(clazz, m, "No protected methods; must be public")
381     for f in clazz.fields:
382         if "protected" in f.split:
383             error(clazz, f, "No protected fields; must be public")
384
385
386 def verify_fields(clazz):
387     """Verify that all exposed fields are final.
388     Exposed fields must follow myName style.
389     Catch internal mFoo objects being exposed."""
390
391     IGNORE_BARE_FIELDS = [
392         "android.app.ActivityManager.RecentTaskInfo",
393         "android.app.Notification",
394         "android.content.pm.ActivityInfo",
395         "android.content.pm.ApplicationInfo",
396         "android.content.pm.FeatureGroupInfo",
397         "android.content.pm.InstrumentationInfo",
398         "android.content.pm.PackageInfo",
399         "android.content.pm.PackageItemInfo",
400         "android.os.Message",
401         "android.system.StructPollfd",
402     ]
403
404     for f in clazz.fields:
405         if not "final" in f.split:
406             if clazz.fullname in IGNORE_BARE_FIELDS:
407                 pass
408             elif clazz.fullname.endswith("LayoutParams"):
409                 pass
410             elif clazz.fullname.startswith("android.util.Mutable"):
411                 pass
412             else:
413                 error(clazz, f, "Bare fields must be marked final; consider adding accessors")
414
415         if not "static" in f.split:
416             if not re.match("[a-z]([a-zA-Z]+)?", f.name):
417                 error(clazz, f, "Non-static fields must be named with myField style")
418
419         if re.match("[ms][A-Z]", f.name):
420             error(clazz, f, "Don't expose your internal objects")
421
422         if re.match("[A-Z_]+", f.name):
423             if "static" not in f.split or "final" not in f.split:
424                 error(clazz, f, "Constants must be marked static final")
425
426
427 def verify_register(clazz):
428     """Verify parity of registration methods.
429     Callback objects use register/unregister methods.
430     Listener objects use add/remove methods."""
431     methods = [ m.name for m in clazz.methods ]
432     for m in clazz.methods:
433         if "Callback" in m.raw:
434             if m.name.startswith("register"):
435                 other = "unregister" + m.name[8:]
436                 if other not in methods:
437                     error(clazz, m, "Missing unregister method")
438             if m.name.startswith("unregister"):
439                 other = "register" + m.name[10:]
440                 if other not in methods:
441                     error(clazz, m, "Missing register method")
442
443             if m.name.startswith("add") or m.name.startswith("remove"):
444                 error(clazz, m, "Callback methods should be named register/unregister")
445
446         if "Listener" in m.raw:
447             if m.name.startswith("add"):
448                 other = "remove" + m.name[3:]
449                 if other not in methods:
450                     error(clazz, m, "Missing remove method")
451             if m.name.startswith("remove") and not m.name.startswith("removeAll"):
452                 other = "add" + m.name[6:]
453                 if other not in methods:
454                     error(clazz, m, "Missing add method")
455
456             if m.name.startswith("register") or m.name.startswith("unregister"):
457                 error(clazz, m, "Listener methods should be named add/remove")
458
459
460 def verify_sync(clazz):
461     """Verify synchronized methods aren't exposed."""
462     for m in clazz.methods:
463         if "synchronized" in m.split:
464             error(clazz, m, "Internal lock exposed")
465
466
467 def verify_intent_builder(clazz):
468     """Verify that Intent builders are createFooIntent() style."""
469     if clazz.name == "Intent": return
470
471     for m in clazz.methods:
472         if m.typ == "android.content.Intent":
473             if m.name.startswith("create") and m.name.endswith("Intent"):
474                 pass
475             else:
476                 error(clazz, m, "Methods creating an Intent should be named createFooIntent()")
477
478
479 def verify_helper_classes(clazz):
480     """Verify that helper classes are named consistently with what they extend.
481     All developer extendable methods should be named onFoo()."""
482     test_methods = False
483     if "extends android.app.Service" in clazz.raw:
484         test_methods = True
485         if not clazz.name.endswith("Service"):
486             error(clazz, None, "Inconsistent class name; should be FooService")
487
488         found = False
489         for f in clazz.fields:
490             if f.name == "SERVICE_INTERFACE":
491                 found = True
492                 if f.value != clazz.fullname:
493                     error(clazz, f, "Inconsistent interface constant; expected %s" % (clazz.fullname))
494
495         if not found:
496             warn(clazz, None, "Missing SERVICE_INTERFACE constant")
497
498         if "abstract" in clazz.split and not clazz.fullname.startswith("android.service."):
499             warn(clazz, None, "Services extended by developers should be under android.service")
500
501     if "extends android.content.ContentProvider" in clazz.raw:
502         test_methods = True
503         if not clazz.name.endswith("Provider"):
504             error(clazz, None, "Inconsistent class name; should be FooProvider")
505
506         found = False
507         for f in clazz.fields:
508             if f.name == "PROVIDER_INTERFACE":
509                 found = True
510                 if f.value != clazz.fullname:
511                     error(clazz, f, "Inconsistent interface name; expected %s" % (clazz.fullname))
512
513         if not found:
514             warn(clazz, None, "Missing PROVIDER_INTERFACE constant")
515
516         if "abstract" in clazz.split and not clazz.fullname.startswith("android.provider."):
517             warn(clazz, None, "Providers extended by developers should be under android.provider")
518
519     if "extends android.content.BroadcastReceiver" in clazz.raw:
520         test_methods = True
521         if not clazz.name.endswith("Receiver"):
522             error(clazz, None, "Inconsistent class name; should be FooReceiver")
523
524     if "extends android.app.Activity" in clazz.raw:
525         test_methods = True
526         if not clazz.name.endswith("Activity"):
527             error(clazz, None, "Inconsistent class name; should be FooActivity")
528
529     if test_methods:
530         for m in clazz.methods:
531             if "final" in m.split: continue
532             if not re.match("on[A-Z]", m.name):
533                 if "abstract" in m.split:
534                     error(clazz, m, "Methods implemented by developers must be named onFoo()")
535                 else:
536                     warn(clazz, m, "If implemented by developer, should be named onFoo(); otherwise consider marking final")
537
538
539 def verify_builder(clazz):
540     """Verify builder classes.
541     Methods should return the builder to enable chaining."""
542     if " extends " in clazz.raw: return
543     if not clazz.name.endswith("Builder"): return
544
545     if clazz.name != "Builder":
546         warn(clazz, None, "Builder should be defined as inner class")
547
548     has_build = False
549     for m in clazz.methods:
550         if m.name == "build":
551             has_build = True
552             continue
553
554         if m.name.startswith("get"): continue
555         if m.name.startswith("clear"): continue
556
557         if m.name.startswith("with"):
558             error(clazz, m, "Builder methods names must follow setFoo() style")
559
560         if m.name.startswith("set"):
561             if not m.typ.endswith(clazz.fullname):
562                 warn(clazz, m, "Methods should return the builder")
563
564     if not has_build:
565         warn(clazz, None, "Missing build() method")
566
567
568 def verify_aidl(clazz):
569     """Catch people exposing raw AIDL."""
570     if "extends android.os.Binder" in clazz.raw or "implements android.os.IInterface" in clazz.raw:
571         error(clazz, None, "Exposing raw AIDL interface")
572
573
574 def verify_internal(clazz):
575     """Catch people exposing internal classes."""
576     if clazz.pkg.name.startswith("com.android"):
577         error(clazz, None, "Exposing internal class")
578
579
580 def verify_layering(clazz):
581     """Catch package layering violations.
582     For example, something in android.os depending on android.app."""
583     ranking = [
584         ["android.service","android.accessibilityservice","android.inputmethodservice","android.printservice","android.appwidget","android.webkit","android.preference","android.gesture","android.print"],
585         "android.app",
586         "android.widget",
587         "android.view",
588         "android.animation",
589         "android.provider",
590         ["android.content","android.graphics.drawable"],
591         "android.database",
592         "android.graphics",
593         "android.text",
594         "android.os",
595         "android.util"
596     ]
597
598     def rank(p):
599         for i in range(len(ranking)):
600             if isinstance(ranking[i], list):
601                 for j in ranking[i]:
602                     if p.startswith(j): return i
603             else:
604                 if p.startswith(ranking[i]): return i
605
606     cr = rank(clazz.pkg.name)
607     if cr is None: return
608
609     for f in clazz.fields:
610         ir = rank(f.typ)
611         if ir and ir < cr:
612             warn(clazz, f, "Field type violates package layering")
613
614     for m in clazz.methods:
615         ir = rank(m.typ)
616         if ir and ir < cr:
617             warn(clazz, m, "Method return type violates package layering")
618         for arg in m.args:
619             ir = rank(arg)
620             if ir and ir < cr:
621                 warn(clazz, m, "Method argument type violates package layering")
622
623
624 def verify_boolean(clazz, api):
625     """Catches people returning boolean from getFoo() style methods.
626     Ignores when matching setFoo() is present."""
627
628     methods = [ m.name for m in clazz.methods ]
629
630     builder = clazz.fullname + ".Builder"
631     builder_methods = []
632     if builder in api:
633         builder_methods = [ m.name for m in api[builder].methods ]
634
635     for m in clazz.methods:
636         if m.typ == "boolean" and m.name.startswith("get") and m.name != "get" and len(m.args) == 0:
637             setter = "set" + m.name[3:]
638             if setter in methods:
639                 pass
640             elif builder is not None and setter in builder_methods:
641                 pass
642             else:
643                 warn(clazz, m, "Methods returning boolean should be named isFoo, hasFoo, areFoo")
644
645
646 def verify_collections(clazz):
647     """Verifies that collection types are interfaces."""
648     if clazz.fullname == "android.os.Bundle": return
649
650     bad = ["java.util.Vector", "java.util.LinkedList", "java.util.ArrayList", "java.util.Stack",
651            "java.util.HashMap", "java.util.HashSet", "android.util.ArraySet", "android.util.ArrayMap"]
652     for m in clazz.methods:
653         if m.typ in bad:
654             error(clazz, m, "Return type is concrete collection; should be interface")
655         for arg in m.args:
656             if arg in bad:
657                 error(clazz, m, "Argument is concrete collection; should be interface")
658
659
660 def verify_flags(clazz):
661     """Verifies that flags are non-overlapping."""
662     known = collections.defaultdict(int)
663     for f in clazz.fields:
664         if "FLAG_" in f.name:
665             try:
666                 val = int(f.value)
667             except:
668                 continue
669
670             scope = f.name[0:f.name.index("FLAG_")]
671             if val & known[scope]:
672                 warn(clazz, f, "Found overlapping flag constant value")
673             known[scope] |= val
674
675
676 def verify_style(api):
677     """Find all style issues in the given API level."""
678     global failures
679
680     failures = {}
681     for key in sorted(api.keys()):
682         clazz = api[key]
683
684         if clazz.pkg.name.startswith("java"): continue
685         if clazz.pkg.name.startswith("junit"): continue
686         if clazz.pkg.name.startswith("org.apache"): continue
687         if clazz.pkg.name.startswith("org.xml"): continue
688         if clazz.pkg.name.startswith("org.json"): continue
689         if clazz.pkg.name.startswith("org.w3c"): continue
690
691         verify_constants(clazz)
692         verify_enums(clazz)
693         verify_class_names(clazz)
694         verify_method_names(clazz)
695         verify_callbacks(clazz)
696         verify_listeners(clazz)
697         verify_actions(clazz)
698         verify_extras(clazz)
699         verify_equals(clazz)
700         verify_parcelable(clazz)
701         verify_protected(clazz)
702         verify_fields(clazz)
703         verify_register(clazz)
704         verify_sync(clazz)
705         verify_intent_builder(clazz)
706         verify_helper_classes(clazz)
707         verify_builder(clazz)
708         verify_aidl(clazz)
709         verify_internal(clazz)
710         verify_layering(clazz)
711         verify_boolean(clazz, api)
712         verify_collections(clazz)
713         verify_flags(clazz)
714
715     return failures
716
717
718 def verify_compat(cur, prev):
719     """Find any incompatible API changes between two levels."""
720     global failures
721
722     def class_exists(api, test):
723         return test.fullname in api
724
725     def ctor_exists(api, clazz, test):
726         for m in clazz.ctors:
727             if m.ident == test.ident: return True
728         return False
729
730     def all_methods(api, clazz):
731         methods = list(clazz.methods)
732         if clazz.extends is not None:
733             methods.extend(all_methods(api, api[clazz.extends]))
734         return methods
735
736     def method_exists(api, clazz, test):
737         methods = all_methods(api, clazz)
738         for m in methods:
739             if m.ident == test.ident: return True
740         return False
741
742     def field_exists(api, clazz, test):
743         for f in clazz.fields:
744             if f.ident == test.ident: return True
745         return False
746
747     failures = {}
748     for key in sorted(prev.keys()):
749         prev_clazz = prev[key]
750
751         if not class_exists(cur, prev_clazz):
752             error(prev_clazz, None, "Class removed or incompatible change")
753             continue
754
755         cur_clazz = cur[key]
756
757         for test in prev_clazz.ctors:
758             if not ctor_exists(cur, cur_clazz, test):
759                 error(prev_clazz, prev_ctor, "Constructor removed or incompatible change")
760
761         methods = all_methods(prev, prev_clazz)
762         for test in methods:
763             if not method_exists(cur, cur_clazz, test):
764                 error(prev_clazz, test, "Method removed or incompatible change")
765
766         for test in prev_clazz.fields:
767             if not field_exists(cur, cur_clazz, test):
768                 error(prev_clazz, test, "Field removed or incompatible change")
769
770     return failures
771
772
773 cur = parse_api(sys.argv[1])
774 cur_fail = verify_style(cur)
775
776 if len(sys.argv) > 2:
777     prev = parse_api(sys.argv[2])
778     prev_fail = verify_style(prev)
779
780     # ignore errors from previous API level
781     for p in prev_fail:
782         if p in cur_fail:
783             del cur_fail[p]
784
785     # look for compatibility issues
786     compat_fail = verify_compat(cur, prev)
787
788     print "%s API compatibility issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
789     for f in sorted(compat_fail):
790         print compat_fail[f]
791         print
792
793
794 print "%s API style issues %s\n" % ((format(fg=WHITE, bg=BLUE, bold=True), format(reset=True)))
795 for f in sorted(cur_fail):
796     print cur_fail[f]
797     print