Skip to content

Commit

Permalink
[ContractHandler] Handle @contract with empty value. (#450)
Browse files Browse the repository at this point in the history
The IntelliJ `@Contract` annotation has two fields, `value`
and `pure`. When `pure = true`, `value` can be left empty.
As such, the following is a valid `@Contract` annotation:

```
@contract(
  pure = true
)
```

See. https://www.jetbrains.com/help/idea/contract-annotations.html

Here, retriving the annotation value produces an empty
string.

However, existing ContractHandler logic expects `value` to
either be `null` or a properly formated string in
IntelliJ contract syntax (`"[...] -> [...]; [...]"`).

Previous to this change, NullAway would report an error
AND crash when seeing the `@Contract` annotation above,
rather than ignore it. This patch fixes this.
  • Loading branch information
lazaroclapp authored Feb 22, 2021
1 parent af24db1 commit 875cf56
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public NullnessHint onDataflowVisitMethodInvocation(
Preconditions.checkNotNull(callee);
// Check to see if this method has an @Contract annotation
String contractString = NullabilityUtil.getAnnotationValue(callee, CONTRACT_ANNOTATION_NAME);
if (contractString != null) {
if (contractString != null && contractString.trim().length() > 0) {
// Found a contract, lets parse it.
String[] clauses = contractString.split(";");
for (String clause : clauses) {
Expand Down
40 changes: 40 additions & 0 deletions nullaway/src/test/java/com/uber/nullaway/NullAwayTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,46 @@ public void contractNonVarArg() {
.doTest();
}

@Test
public void contractPureOnlyIgnored() {
compilationHelper
.setArgs(
Arrays.asList(
"-d",
temporaryFolder.getRoot().getAbsolutePath(),
"-XepOpt:NullAway:AnnotatedPackages=com.uber"))
.addSourceLines(
"PureLibrary.java",
"package com.example.library;",
"import org.jetbrains.annotations.Contract;",
"public class PureLibrary {",
" @Contract(",
" pure = true",
" )",
" public static String pi() {",
" // Meh, close enough...",
" return Double.toString(3.14);",
" }",
"}")
.addSourceLines(
"Test.java",
"package com.uber;",
"import com.example.library.PureLibrary;",
"import javax.annotation.Nullable;",
"class Test {",
" String piValue() {",
" String pi = PureLibrary.pi();",
" // Note: we must trigger dataflow to ensure that",
" // ContractHandler.onDataflowVisitMethodInvocation is called",
" if (pi != null) {",
" return pi;",
" }",
" return Integer.toString(3);",
" }",
"}")
.doTest();
}

@Test
public void testEnumInit() {
compilationHelper
Expand Down

0 comments on commit 875cf56

Please sign in to comment.