Static analyzer
This changeset adds a static analyzer, "lint", which looks for various
potential bugs in Android projects. It has 3 parts:
(1) A library which performs the actual static checks.
This library is standalone: it does not depend on Eclipse.
(Technically the library has two halves: an API half, for use
by third party developers to write additional detectors, and
an actual implementation of a bunch of built-in checks.)
(2) A command line driver, "lint", which runs the static checks and
emits any warnings to standard out. This can be thought of as
a replacement for the layoutopt tool.
(3) Eclipse integration. Lint errors are added to the Problems view as
well as shown as editor annotations. There's an options panel for
controlling which detectors are enabled. There's also a quickfix
for disabling errors directly within the editor and a marker
resolution for disabling them via the Problems view.
The static checks are run on an XML file right after it has been
saved. (This is optional via a toggle on the same preference page
as the detector list.)
The static checks are also run when you export an APK, and if any
fatal errors are found the export is abandoned. (This is also
optional via an option).
Finally you can run a full lint through the Android Tools menu,
and there's also an action to clear all the lint markers there.
There's also a new indicator on the layout editor which shows
whether there are lint errors on the associated file, and when
clicked brings up a dialog listing the specific errors.
This changeset also includes a number of checks:
* An accessibility detector which warns about images missing
contentDescriptions
* A drawable selector detector which warns about state lists where not
all states are reachable (e.g. it is not the case that only the last
item in the list omits a state qualifier)
* A detector finding duplicate ids, not just in the current layout but
across included layouts (transitively) as well
* All the layoutopt ones ported to Java + DOM
* Unit tests for the above.
The focus here is on getting the infrastructure in place, and it
currently focuses on XML resource files and analyzing them
efficiently. See the comment in XmlVisitor for details on that.
Change-Id: Ic5f5f37d92bfb96ff901b959aaac24db33552ff7
diff --git a/lint/cli/.classpath b/lint/cli/.classpath
new file mode 100644
index 0000000..f6efb87
--- /dev/null
+++ b/lint/cli/.classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/lint-api"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/lint-checks"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/lint/cli/.project b/lint/cli/.project
new file mode 100644
index 0000000..2809612
--- /dev/null
+++ b/lint/cli/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>lint-cli</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/lint/cli/.settings/org.eclipse.jdt.core.prefs b/lint/cli/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..e755df2
--- /dev/null
+++ b/lint/cli/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,71 @@
+#Thu Jun 09 12:26:44 PDT 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
+org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
+org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
+org.eclipse.jdt.core.compiler.problem.deadCode=warning
+org.eclipse.jdt.core.compiler.problem.deprecation=warning
+org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
+org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
+org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
+org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
+org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
+org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
+org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
+org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
+org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
+org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
+org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
+org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
+org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
+org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
+org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
+org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
+org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
+org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
+org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
+org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
+org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
+org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
+org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
+org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
+org.eclipse.jdt.core.compiler.problem.nullReference=error
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
+org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
+org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
+org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
+org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
+org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
+org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
+org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
+org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
+org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
+org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
+org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
+org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
+org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
+org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
+org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
+org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
+org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
+org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
+org.eclipse.jdt.core.compiler.problem.unusedImport=warning
+org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
+org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
+org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
+org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
+org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
+org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
+org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
+org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
+org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
diff --git a/lint/cli/Android.mk b/lint/cli/Android.mk
new file mode 100644
index 0000000..5b99dc4
--- /dev/null
+++ b/lint/cli/Android.mk
@@ -0,0 +1,22 @@
+# Copyright 2011 The Android Open Source Project
+#
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_JAVA_RESOURCE_DIRS := src
+
+LOCAL_JAR_MANIFEST := etc/manifest.txt
+
+# If the dependency list is changed, etc/manifest.txt
+LOCAL_JAVA_LIBRARIES := \
+ lint_api \
+ lint_checks
+LOCAL_MODULE := lint
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+
+# Build all sub-directories
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/lint/cli/NOTICE b/lint/cli/NOTICE
new file mode 100644
index 0000000..becc120
--- /dev/null
+++ b/lint/cli/NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2011, The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/lint/cli/etc/Android.mk b/lint/cli/etc/Android.mk
new file mode 100644
index 0000000..987b452
--- /dev/null
+++ b/lint/cli/etc/Android.mk
@@ -0,0 +1,10 @@
+# Copyright 2011 The Android Open Source Project
+#
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_PREBUILT_EXECUTABLES := lint
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_HOST_PREBUILT)
+
diff --git a/lint/cli/etc/lint b/lint/cli/etc/lint
new file mode 100755
index 0000000..2b53df6
--- /dev/null
+++ b/lint/cli/etc/lint
@@ -0,0 +1,72 @@
+#!/bin/bash
+# Copyright 2011, The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Set up prog to be the path of this script, including following symlinks,
+# and set up progdir to be the fully-qualified pathname of its directory.
+prog="$0"
+while [ -h "${prog}" ]; do
+ newProg=`/bin/ls -ld "${prog}"`
+ newProg=`expr "${newProg}" : ".* -> \(.*\)$"`
+ if expr "x${newProg}" : 'x/' >/dev/null; then
+ prog="${newProg}"
+ else
+ progdir=`dirname "${prog}"`
+ prog="${progdir}/${newProg}"
+ fi
+done
+oldwd=`pwd`
+progdir=`dirname "${prog}"`
+cd "${progdir}"
+progdir=`pwd`
+prog="${progdir}"/`basename "${prog}"`
+cd "${oldwd}"
+
+jarfile=lint.jar
+frameworkdir="$progdir"
+libdir="$progdir"
+if [ ! -r "$frameworkdir/$jarfile" ]
+then
+ frameworkdir=`dirname "$progdir"`/tools/lib
+ libdir=`dirname "$progdir"`/tools/lib
+fi
+if [ ! -r "$frameworkdir/$jarfile" ]
+then
+ frameworkdir=`dirname "$progdir"`/framework
+ libdir=`dirname "$progdir"`/lib
+fi
+if [ ! -r "$frameworkdir/$jarfile" ]
+then
+ echo `basename "$prog"`": can't find $jarfile"
+ exit 1
+fi
+
+# Check args.
+if [ debug = "$1" ]; then
+ # add this in for debugging
+ java_debug=-agentlib:jdwp=transport=dt_socket,server=y,address=8050,suspend=y
+ shift 1
+else
+ java_debug=
+fi
+
+javaCmd="java"
+
+jarpath="$frameworkdir/$jarfile"
+
+exec "$javaCmd" \
+ -Xmx256M $os_opts $java_debug \
+ -Dcom.android.tools.lint.bindir="$progdir" \
+ -classpath "$jarpath" \
+ com.android.tools.lint.Main "$@"
diff --git a/lint/cli/etc/lint.bat b/lint/cli/etc/lint.bat
new file mode 100755
index 0000000..41e52d8
--- /dev/null
+++ b/lint/cli/etc/lint.bat
@@ -0,0 +1,55 @@
+@echo off
+rem Copyright (C) 2011 The Android Open Source Project
+rem
+rem Licensed under the Apache License, Version 2.0 (the "License");
+rem you may not use this file except in compliance with the License.
+rem You may obtain a copy of the License at
+rem
+rem http://www.apache.org/licenses/LICENSE-2.0
+rem
+rem Unless required by applicable law or agreed to in writing, software
+rem distributed under the License is distributed on an "AS IS" BASIS,
+rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+rem See the License for the specific language governing permissions and
+rem limitations under the License.
+
+rem don't modify the caller's environment
+setlocal
+
+rem Set up prog to be the path of this script, including following symlinks,
+rem and set up progdir to be the fully-qualified pathname of its directory.
+set prog=%~f0
+
+rem Change current directory and drive to where the script is, to avoid
+rem issues with directories containing whitespaces.
+cd /d %~dp0
+
+rem Get the CWD as a full path with short names only (without spaces)
+for %%i in ("%cd%") do set prog_dir=%%~fsi
+
+rem Check we have a valid Java.exe in the path.
+set java_exe=
+call lib\find_java.bat
+if not defined java_exe goto :EOF
+
+set jarfile=lint.jar
+set frameworkdir=
+
+if exist %frameworkdir%%jarfile% goto JarFileOk
+ set frameworkdir=lib\
+
+if exist %frameworkdir%%jarfile% goto JarFileOk
+ set frameworkdir=..\framework\
+
+:JarFileOk
+
+if debug NEQ "%1" goto NoDebug
+ set java_debug=-agentlib:jdwp=transport=dt_socket,server=y,address=8050,suspend=y
+ shift 1
+:NoDebug
+
+set jarpath=%frameworkdir%%jarfile%
+set javaextdirs=%frameworkdir%
+
+call %java_exe% %java_debug% -Dcom.android.tools.lint.bindir=%prog_dir% -classpath "%jarpath%" com.android.tools.lint.Main %*
+
diff --git a/lint/cli/etc/manifest.txt b/lint/cli/etc/manifest.txt
new file mode 100644
index 0000000..e75087d
--- /dev/null
+++ b/lint/cli/etc/manifest.txt
@@ -0,0 +1,2 @@
+Main-Class: com.android.tools.lint.Main
+Class-Path: lint_api.jar lint_checks.jar
diff --git a/lint/cli/src/com/android/tools/lint/Main.java b/lint/cli/src/com/android/tools/lint/Main.java
new file mode 100644
index 0000000..9e8dc28
--- /dev/null
+++ b/lint/cli/src/com/android/tools/lint/Main.java
@@ -0,0 +1,274 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.lint;
+
+import com.android.tools.lint.api.DetectorRegistry;
+import com.android.tools.lint.api.IDomParser;
+import com.android.tools.lint.api.Lint;
+import com.android.tools.lint.api.ToolContext;
+import com.android.tools.lint.checks.BuiltinDetectorRegistry;
+import com.android.tools.lint.detector.api.Issue;
+import com.android.tools.lint.detector.api.Location;
+import com.android.tools.lint.detector.api.Position;
+import com.android.tools.lint.detector.api.Scope;
+import com.android.tools.lint.detector.api.Severity;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Command line driver for the rules framework
+ * <p>
+ * TODO:
+ * <ul>
+ * <li>Offer priority or category sorting
+ * <li>Offer suppressing violations
+ * </ul>
+ */
+public class Main implements ToolContext {
+ private static final int ERRNO_ERRORS = -1;
+ private static final int ERRNO_USAGE = -2;
+ private static final int ERRNO_EXISTS = -3;
+ private static final int ERRNO_HELP = -4;
+ private static final int ERRNO_INVALIDARGS = -5;
+
+ private Set<String> mSuppress = new HashSet<String>();
+ private Set<String> mEnabled = null;
+ private StringBuilder mOutput = new StringBuilder(2000);
+ private boolean mFatal;
+ private String mCommonPrefix;
+
+ /** Creates a CLI driver */
+ public Main() {
+ }
+
+ /**
+ * Runs the static analysis command line driver
+ *
+ * @param args program arguments
+ */
+ public static void main(String[] args) {
+ new Main().run(args);
+ }
+
+ /**
+ * Runs the static analysis command line driver
+ *
+ * @param args program arguments
+ */
+ private void run(String[] args) {
+ if (args.length < 1) {
+ printUsage();
+ System.exit(ERRNO_USAGE);
+ }
+
+ DetectorRegistry registry = new BuiltinDetectorRegistry();
+
+ List<File> files = new ArrayList<File>();
+ for (int index = 0; index < args.length; index++) {
+ String arg = args[index];
+ if (arg.equals("--help") || arg.equals("-h")) { //$NON-NLS-1$ //$NON-NLS-2$
+ printUsage();
+ System.err.println("\n" +
+ "Run with --suppress <category1[,category2,...]> to suppress categories.");
+ System.exit(ERRNO_HELP);
+ } else if (arg.equals("--suppress")) {
+ if (index == args.length - 1) {
+ System.err.println("Missing categories to suppress");
+ System.exit(ERRNO_INVALIDARGS);
+ }
+ String[] ids = args[++index].split(",");
+ for (String id : ids) {
+ if (!registry.isIssueId(id)) {
+ System.err.println("Invalid id \"" + id + "\".");
+ displayValidIds(registry);
+ System.exit(ERRNO_INVALIDARGS);
+ }
+ mSuppress.add(id);
+ }
+ } else if (arg.equals("--enable")) {
+ if (index == args.length - 1) {
+ System.err.println("Missing categories to enable");
+ System.exit(ERRNO_INVALIDARGS);
+ }
+ String[] ids = args[++index].split(",");
+ mEnabled = new HashSet<String>();
+ for (String id : ids) {
+ if (!registry.isIssueId(id)) {
+ System.err.println("Invalid id \"" + id + "\".");
+ displayValidIds(registry);
+ System.exit(ERRNO_INVALIDARGS);
+ }
+ mEnabled.add(id);
+ }
+ } else {
+ String filename = arg;
+ File file = new File(filename);
+ if (!file.exists()) {
+ System.err.println(String.format("%1$s does not exist.", filename));
+ System.exit(ERRNO_EXISTS);
+ }
+ files.add(file);
+ }
+ // TODO: Add flag to point to a file of specific errors to suppress
+ }
+
+ if (files.size() == 0) {
+ System.err.println("No files to analyze.");
+ System.exit(ERRNO_INVALIDARGS);
+ }
+
+ mCommonPrefix = files.get(0).getPath();
+ for (int i = 1; i < files.size(); i++) {
+ File file = files.get(i);
+ String path = file.getPath();
+ mCommonPrefix = getCommonPrefix(mCommonPrefix, path);
+ }
+
+ Lint analyzer = new Lint(new BuiltinDetectorRegistry(), this, Scope.PROJECT);
+ analyzer.analyze(files);
+ if (mOutput.length() == 0) {
+ System.out.println("No warnings.");
+ System.exit(0); // Success error code
+ } else {
+ System.err.println(mOutput.toString());
+ System.err.println("Run with --suppress to turn off specific types of errors, or this message");
+
+ System.exit(mFatal ? ERRNO_ERRORS : 0);
+ }
+ }
+
+ private void displayValidIds(DetectorRegistry registry) {
+ List<Issue> issues = registry.getIssues();
+ System.err.println("Valid issue ids:");
+ for (Issue issue : issues) {
+ System.err.println("\"" + issue.getId() + "\": " + issue.getDescription());
+ }
+ }
+
+ private static void printUsage() {
+ // TODO: Look up launcher script name!
+ System.err.println("Usage: lint [--suppress ids] [--enable ids] <project | file> ...");
+ }
+
+ private static String getCommonPrefix(String a, String b) {
+ int aLength = a.length();
+ int bLength = b.length();
+ int aIndex = 0, bIndex = 0;
+ for (; aIndex < aLength && bIndex < bLength; aIndex++, bIndex++) {
+ if (a.charAt(aIndex) != b.charAt(bIndex)) {
+ break;
+ }
+ }
+
+ return a.substring(0, aIndex);
+ }
+
+ public void log(Throwable exception, String format, Object... args) {
+ System.err.println(String.format(format, args));
+ if (exception != null) {
+ exception.printStackTrace();
+ }
+ }
+
+ public IDomParser getParser() {
+ return new PositionXmlParser();
+ }
+
+ public boolean isEnabled(Issue issue) {
+ if (mEnabled != null) {
+ return mEnabled.contains(issue.getId());
+ }
+ return !mSuppress.contains(issue.getId());
+ }
+
+ public void report(Issue issue, Location location, String message) {
+ if (!isEnabled(issue)) {
+ return;
+ }
+
+ Severity severity = getSeverity(issue);
+ if (severity == Severity.IGNORE) {
+ return;
+ }
+ if (severity == Severity.ERROR){
+ mFatal = true;
+ }
+
+ int startLength = mOutput.length();
+
+ File file = location.getFile();
+ if (file != null) {
+ String path = file.getPath();
+ if (path.startsWith(mCommonPrefix)) {
+ int chop = mCommonPrefix.length();
+ if (path.length() > chop && path.charAt(chop) == File.separatorChar) {
+ chop++;
+ }
+ path = path.substring(chop);
+ }
+ mOutput.append(path);
+ mOutput.append(':');
+ }
+
+ Position startPosition = location.getStart();
+ if (startPosition != null) {
+ int line = startPosition.getLine();
+ if (line >= 0) {
+ // line is 0-based, should display 1-based
+ mOutput.append(Integer.toString(line + 1));
+ mOutput.append(':');
+ }
+ }
+
+ // Column is not particularly useful here
+ //int column = location.getColumn();
+ //if (column > 0) {
+ // mOutput.append(Integer.toString(column));
+ // mOutput.append(':');
+ //}
+
+ if (startLength < mOutput.length()) {
+ mOutput.append(' ');
+ }
+ mOutput.append(severity.getDescription());
+ mOutput.append(':');
+ mOutput.append(' ');
+
+ mOutput.append(message);
+ if (issue != null) {
+ mOutput.append(' ').append('[');
+ mOutput.append(issue.getId());
+ mOutput.append(']');
+ }
+
+ mOutput.append('\n');
+ }
+
+ public boolean isSuppressed(Issue issue, Location range, String message,
+ Severity severity) {
+ // Not yet supported
+ return false;
+ }
+
+ public Severity getSeverity(Issue issue) {
+ return issue.getDefaultSeverity();
+ }
+}
diff --git a/lint/cli/src/com/android/tools/lint/PositionXmlParser.java b/lint/cli/src/com/android/tools/lint/PositionXmlParser.java
new file mode 100644
index 0000000..0857425
--- /dev/null
+++ b/lint/cli/src/com/android/tools/lint/PositionXmlParser.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tools.lint;
+
+import com.android.tools.lint.api.IDomParser;
+import com.android.tools.lint.detector.api.Context;
+import com.android.tools.lint.detector.api.Position;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.Attributes;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xml.sax.helpers.XMLFilterImpl;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+import java.io.StringReader;
+
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.sax.SAXSource;
+
+/** A simple XML parser which can store and retrieve line:column information for the nodes */
+public class PositionXmlParser implements IDomParser {
+ private static final String ATTR_LOCATION = "location"; //$NON-NLS-1$
+ private static final String PRIVATE_NAMESPACE = "http://tools.android.com"; //$NON-NLS-1$
+ private static final String PRIVATE_PREFIX = "temp"; //$NON-NLS-1$
+
+ public Document parse(Context context) {
+ InputSource input = new InputSource(new StringReader(context.getContents()));
+ try {
+ Filter filter = new Filter(XMLReaderFactory.createXMLReader());
+ Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ DOMResult result = new DOMResult();
+ transformer.transform(new SAXSource(filter, input), result);
+ return (Document) result.getNode();
+ } catch (SAXException e) {
+ // The file doesn't parse: not an exception. Infrastructure will log a warning
+ // that this file was not analyzed.
+ return null;
+ } catch (TransformerConfigurationException e) {
+ context.toolContext.log(e, null);
+ } catch (TransformerException e) {
+ context.toolContext.log(e, null);
+ }
+
+ return null;
+ }
+
+ private static class Filter extends XMLFilterImpl {
+ private Locator mLocator;
+
+ Filter(XMLReader reader) {
+ super(reader);
+ }
+
+ @Override
+ public void setDocumentLocator(Locator locator) {
+ super.setDocumentLocator(locator);
+ this.mLocator = locator;
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String qualifiedName,
+ Attributes attributes) throws SAXException {
+ int lineno = mLocator.getLineNumber();
+ int column = mLocator.getColumnNumber();
+ String location = Integer.toString(lineno) + ':' + Integer.toString(column);
+
+ // Modify attributes parameter to a copy that includes our private attribute
+ AttributesImpl wrapper = new AttributesImpl(attributes);
+ wrapper.addAttribute(PRIVATE_NAMESPACE, ATTR_LOCATION,
+ PRIVATE_PREFIX + ':' + ATTR_LOCATION, "CDATA", location); //$NON-NLS-1$
+
+ super.startElement(uri, localName, qualifiedName, wrapper);
+ }
+ }
+
+ public Position getStartPosition(Context context, Node node) {
+ if (node instanceof Attr) {
+ Attr attr = (Attr) node;
+ node = attr.getOwnerElement();
+ }
+ if (node instanceof Element) {
+ Attr attribute = ((Element) node).getAttributeNodeNS(PRIVATE_NAMESPACE, ATTR_LOCATION);
+ if (attribute != null) {
+ String position = attribute.getValue();
+ int separator = position.indexOf(':');
+ int line = Integer.parseInt(position.substring(0, separator));
+ int column = Integer.parseInt(position.substring(separator + 1));
+ return new OffsetPosition(line, column, -1);
+ }
+ }
+
+ return null;
+ }
+
+ public Position getEndPosition(Context context, Node node) {
+ // TODO: Currently unused
+ return null;
+ }
+
+ private static class OffsetPosition extends Position {
+ /** The line number (0-based where the first line is line 0) */
+ private final int mLine;
+
+ /**
+ * The column number (where the first character on the line is 0), or -1 if
+ * unknown
+ */
+ private final int mColumn;
+
+ /** The character offset */
+ private final int mOffset;
+
+ /**
+ * Creates a new {@link Position}
+ *
+ * @param line the 0-based line number, or -1 if unknown
+ * @param column the 0-based column number, or -1 if unknown
+ * @param offset the offset, or -1 if unknown
+ */
+ public OffsetPosition(int line, int column, int offset) {
+ this.mLine = line;
+ this.mColumn = column;
+ this.mOffset = offset;
+ }
+
+ @Override
+ public int getLine() {
+ return mLine;
+ }
+
+ @Override
+ public int getOffset() {
+ return mOffset;
+ }
+
+ @Override
+ public int getColumn() {
+ return mColumn;
+ }
+ }
+}