Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

JDT Core/Null Analysis

< JDT Core
Revision as of 18:25, 10 August 2011 by Stephan.cs.tu-berlin.de (Talk | contribs) (Cleaning up)

This page discusses a proposed improvement in the static null analysis of the JDT compiler.

See also bug 186342.


Introduction

The static analysis of the JDT compiler detects many potential programming problems related to the null-ness of variables: dereferencing a null value (-> NPE), redundant null checks etc.

However, the current analysis is restricted to flow analysis within one method. No assumptions can be made about

  • arguments flowing into a method
  • return values from method calls and
  • field reads.

In order to include these elements in the analysis one could either

  • use whole program analysis (very expensive - not feasible for a (incremental) compiler)
  • explicit contracts via an extended type system or annotations

The second option is well explored in research and some existing tools (like the Checker Framework, JML, FindBugs) already introduce specific annotations to this end.

One could argue that advanced analysis should be left to specialized tools but having something like this in the JDT compiler should show two benefits:

  • feedback is more immediate and it is available for all JDT users without installing more software
  • analysis might be more precise than some existing tools provide, because the actual flow analysis in the JDT compiler is already pretty strong (unproven claim).

A preparatory discussion of the design space can be found here: /Brainstorming.


Actual Strategy in the JDT

Disclaimer: this is work in progress. No promise is made that this particular feature will be part of any particular release of the JDT.

By default the JDT does not support inter-procedural null analysis, however, a prototype exists allowing the JDT to be configured to use annotations for extended null checking. The prototypical implementation is currently based on the OT/Equinox technology for better maintainability at this stage. This particular prototype is known to have negative impact on the compiler performance, which is however no indication about how the final in-place implementation will perform.

Specifying nullness

Null annotations in method signatures can be interpreted as null contracts, however, a more general approach considers null annotations as an extension of the type system. Eventually - that is once JSR 308 can be used - all type references should either include or exclude null, which allows for complete checking of any possible dereferencing of null. In other words, a fully annotated program which passes the type checker will never raise an NPE at runtime.

To achieve this guarantee two annotations are used. The specific annotations can be selected as a preference, but the following defaults are provided (see #Compiler configuration explained):

For any variable who's type is annotated with @NonNull (or the configured equivalent) the following rules apply:

  • It is illegal to bind null or a value that can be null to the variable. (For fields and local variables this applies to initialization and assignments, for method argument binding a value means to pass an actual argument in a method call).
  • It is legal and safe to dereference such a variable for accessing a field or a method of the bound object.

For any variable who's type is annotated with @Nullable (or the configured equivalent) the following rules apply:

  • It is legal to bind null or a value that can be null to the variable (see details above).
  • It is illegal to dereference such a variable for either field or method access.

The above rules imply that the value from a @NonNull variable can be bound to a variable annotated with @Nullable, but the opposite direction is generally illegal. Only immediately after an explicit null check can a @Nullable variable be treated as being @NonNull for the sake of binding to another @NonNull variable or for dereferencing.

For interaction with inheritance see Null Contract Inheritance.

Installing the prototype

The code is hosted at

svn://dev.eclipse.org/svnroot/tools/org.eclipse.objectteams/trunk/plugins/org.eclipse.objectteams.jdt.nullity

Browse it at

http://dev.eclipse.org/viewcvs/viewvc.cgi/trunk/plugins/org.eclipse.objectteams.jdt.nullity/?root=TOOLS_OBJECTTEAMS

Example usage

In order to try the prototype against any existing Java project the following steps should help (I tried it using the JDT/Core as an example):

  • Prepare the following compiler configuration
    • enable compliance 1.5 or higher
    • enable all null-related warnings
    • (disable warnings regarding generics if the project doesn't use generics — don't spam the problems view)
  • Import the example annotation types (source) from http://download.eclipse.org/objectteams/contrib/org.eclipse.jdt.annotations.zip
  • Since there isn't yet any UI for the new compiler preferences the following line should be added manually into .settings/org.eclipse.jdt.core.prefs
org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
  • Define @NonNull as the default at the granularity of your choice (project/package/type):
    • project: add one more line to .settings/org.eclipse.jdt.core.prefs:
      org.eclipse.jdt.core.compiler.annotation.nulldefault=nonnull
    • package: add a file package-info.java with contents like this:
      @org.eclipse.jdt.annotation.NonNullByDefault package org.my.pack.age;
    • type: add @org.eclipse.jdt.annotation.NonNullByDefault to the type declaration.
  • Build (Project > Clean)
    • At this point you should see plenty of new errors and warnings
    • If problems are not reported immediately, please try a full build (if this makes a difference please drop a note in bug 186342).

Cleaning up

The sheer number of new problems may look intimidating but that's where quickfixes will come to the rescue. Currently the following problems offer a quickfix:

  • Quickfix error obj.gif Type mismatch: required '@NonNull Foo' but the provided value is null
  • Quickfix error obj.gif Type mismatch: required '@NonNull Foo' but the provided value can be null
  • Quickfix warning obj.gif Potential type mismatch: required '@NonNull Foo' but nullness of the provided value is unknown
    Fixable for these locations: return statements:
    Note that the mentioned @NonNull declaration may be implicit via an applicable default
    In cases 2) and 3) use only with care: the compiler has no clear indication if @Nullable was actually intended or not
    The fix is:
    Correction change.gif Declare method return as @Nullable
  • Quickfix error obj.gif Redundant null check: The variable foo cannot be null at this location
  • Quickfix error obj.gif Null comparison always yields false: The variable bar cannot be null at this location
    Fixable for these locations: read access to a method parameter
    The fix is:
    Correction change.gif Declare method parameter as @Nullable
    Otherwise a null check may indeed be unnecessary and should be deleted.
  • Quickfix error obj.gif The return type is incompatible with the @NonNull return from SuperFoo.foo()
    Location: declaration of an overriding method
    Note again that the mentioned @NonNull declaration may be due to a default.
    Possible fixes are:
    Correction change.gif Declare method return as @NonNull
    Correction change.gif Adjust overridden method from SuperFoo, mark as returning @Nullable
  • Quickfix error obj.gif Illegal redefinition of parameter a, inherited method from SuperFoo declares this parameter as @Nullable
  • Quickfix error obj.gif Illegal redefinition of parameter a, inherited method from SuperFoo does not constrain this parameter.
    Location: Parameter declaration of an overriding method
    The second form occurs when no null default applies at the scope of the super method.
    Possible fixes are:
    Correction change.gif Declare method parameter as @Nullable
    Correction change.gif Adjust overridden method from SuperFoo, mark parameter as @NonNull

These quickfixes can be applied...

  • individually (Ctrl-1)
  • all occurrences per file (via the hover)
  • all occurrences (via context menu in the Problems view)

Note, that some quickfixes require to modify another compilation unit (file) than the one where the problem was observed. For these quickfixes the current implementation doesn't support fixing several equal issues in bulk (for the technical background see bug 337977).

Compiler configuration explained

By default the JDT does not recognize any null annotations but it can be configured to do so. For this purpose these options are proposed:

Previous versions of this proposal contained emulation and default import of annotation types, which may, however, not be supported by the final solution. See older versions of this page for details (≤ 20110226).
  1. Enable annotation based null analysis (enabled/disabled per project or workspace global).
    This is the master switch for everything described in this wiki page.
    The built-in default for this option is:
    org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
  2. Specify the names of annotation types to be used for marking nullable vs. nonnull types as well as for defining the default per type or per package.
    Use this if you want to achieve compatibility with annotations defined by some other tool (or a future standard, should one be defined eventually).
    The built-in default values for these options are:
    org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
    org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
    org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
    org.eclipse.jdt.core.compiler.annotation.nullablebydefault=org.eclipse.jdt.annotation.NullableByDefault
  3. Define a global default for un-annotated entities (nonnull/nullable/unspecified)
    Use this if your code has a bias to either @NonNull or @Nullable. By defining a global default you save the effort of adding annotations to the majority of locations.
    There is no built-in default for this option. The option name is
    org.eclipse.jdt.core.compiler.annotation.nulldefault

It is the user's responsibility to make the required annotation types available on the build path.

Defaults at different levels

If no null annotations are used, the compiler uses the original Java semantics, where the following is legal for all variables of reference types:

  • assign null, and
  • dereference without check.

The above mentioned preference (org.eclipse.jdt.core.compiler.annotation.nulldefault) allows to globally change this so that any declaration to which no null annotation applies will be considered as either nullable or nonnull, depending on that specific setting.

For more fine-grained control two additional annotations can be used. The qualified type names of these annotations can be configured using these preferences:

org.eclipse.jdt.core.compiler.annotation.nullablebydefault
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault

The built-in values for these preferences are org.eclipse.jdt.annotation.NullableByDefault and org.eclipse.jdt.annotation.NonNullByDefault.

These annotations can be applied to any Java type or package and affect all method returns and parameters with undefined null status within their scope. (More locations will be supported in the future).

A default declared at an outer scope can be overridden by a different default at an inner scope. However, no means are provided for canceling a default (as to re-establish the original Java semantics).

Future

The following bugzillas address future improvements of the above strategy (order roughly by priority):

  • bug 334455 - UI for new preferences regarding null annotations
  • bug 337977 - Progress.gif [quick fix] Add quickfixes for null annotations
  • bug 334457 - [compiler][null] check compatibility of inherited null contracts
  • bug 331647 - Progress.gif [compiler][null] support flexible default mechanism for null-annotations
  • bug 331651 - [compiler][null] Support nullity profiles for libraries
  • bug 331649 - [compiler][null] consider null annotations for fields

Back to the top