This is an automated email from the ASF dual-hosted git repository.
geertjan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-netbeans.git
The following commit(s) were added to refs/heads/master by this push:
new f469723 netbeans-479: Added ConvertToVarHint to replace explicit type
with var (#463)
f469723 is described below
commit f4697239478179eb89a5834f9c4a97e3eb894d4d
Author: Arunava Sinha <[email protected]>
AuthorDate: Tue Apr 3 21:06:05 2018 +0530
netbeans-479: Added ConvertToVarHint to replace explicit type with var
(#463)
* netbeans-479: Added ConvertToVarHint to replace explicit type with var
* netbeans-479: Refactored code of ConvertToVarHint
* Split into declaration and assignment issue for var type (#453)
* Split into declaration and assignment issue
* Add review comment
* Add space after var keyword
* Add Jan comments
* Add missing imports
* Add JavaTokenId enum
* Add anonymous method test case
* Add anonymous method test case
* add method in utilities class
* add method in utilities class
* add review request comment
* add review request comment
* Add api in apichanges.xml
* netbeans-479: Implemented pull request(#463)review comments
---
.../modules/java/hints/jdk/Bundle.properties | 3 +
.../modules/java/hints/jdk/ConvertToVarHint.java | 163 ++++++++++
.../java/hints/jdk/ConvertToVarHintTest.java | 358 +++++++++++++++++++++
3 files changed, 524 insertions(+)
diff --git
a/java.hints/src/org/netbeans/modules/java/hints/jdk/Bundle.properties
b/java.hints/src/org/netbeans/modules/java/hints/jdk/Bundle.properties
index 837598e..df35377 100644
--- a/java.hints/src/org/netbeans/modules/java/hints/jdk/Bundle.properties
+++ b/java.hints/src/org/netbeans/modules/java/hints/jdk/Bundle.properties
@@ -99,3 +99,6 @@
LBL_org.netbeans.modules.java.hints.jdk.ConvertToStringSwitch.KEY_THRESHOLD=Mini
TP_org.netbeans.modules.java.hints.jdk.ConvertToStringSwitch.KEY_THRESHOLD=The
hint will appear only when if-statement chain contains at least this number of
branches
OPT_ConvertIfToSwitch_EmptyDefault=Generate empty default
DESC_ConvertIfToSwitch_EmptyDefault=If checked, the hint will generate an
empty default even if no final `else'' was present
+
+DN_CanUseVarForExplicitType=Convert Explicit Type to Var
+DESC_CanUseVarForExplicitType=Converts explicit type of local variable to var.
diff --git
a/java.hints/src/org/netbeans/modules/java/hints/jdk/ConvertToVarHint.java
b/java.hints/src/org/netbeans/modules/java/hints/jdk/ConvertToVarHint.java
new file mode 100644
index 0000000..e5d13e2
--- /dev/null
+++ b/java.hints/src/org/netbeans/modules/java/hints/jdk/ConvertToVarHint.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.netbeans.modules.java.hints.jdk;
+
+import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.Scope;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.VariableTree;
+import com.sun.source.util.TreePath;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.netbeans.api.java.source.CompilationInfo;
+import org.netbeans.api.java.source.TreeMaker;
+import org.netbeans.api.java.source.WorkingCopy;
+import org.netbeans.spi.editor.hints.ErrorDescription;
+import org.netbeans.spi.java.hints.ErrorDescriptionFactory;
+import org.netbeans.spi.java.hints.Hint;
+import org.netbeans.spi.java.hints.HintContext;
+import org.netbeans.spi.java.hints.JavaFix;
+import org.netbeans.spi.java.hints.JavaFix.TransformationContext;
+import org.netbeans.spi.java.hints.TriggerPattern;
+import org.openide.util.NbBundle.Messages;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.type.TypeMirror;
+import javax.tools.Diagnostic;
+
+/**
+ * Hint will convert explicit type of local variable to 'var'. Supported: JDK
10
+ * or above.
+ *
+ * @author arusinha
+ */
+@Hint(displayName = "#DN_CanUseVarForExplicitType", description =
"#DESC_CanUseVarForExplicitType", category = "rules15", minSourceVersion =
"10") //NOI18N
+@Messages("MSG_ConvertibleToVarType=Explict type can be replaced with 'var'")
//NOI18N
+public class ConvertToVarHint {
+
+ // hint will be disabled for error codes present in SKIPPED_ERROR_CODES.
+ private final static Set<String> SKIPPED_ERROR_CODES =
Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList(
+ "compiler.err.generic.array.creation" //NOI18N
+ )));
+
+ @TriggerPattern("$mods$ $type $var = $init") //NOI18N
+
+ public static ErrorDescription computeExplicitToVarType(HintContext ctx) {
+ if (!preConditionChecker(ctx)) {
+ return null;
+ }
+
+ TreePath treePath = ctx.getPath();
+
+ TreePath initTreePath = ctx.getVariables().get("$init"); //NOI18N
+ ExpressionTree t =
ctx.getInfo().getTreeUtilities().parseExpression(initTreePath.getLeaf().toString(),
null);
+ Scope s = ctx.getInfo().getTrees().getScope(ctx.getPath());
+ TypeMirror initTypeMirror =
ctx.getInfo().getTreeUtilities().attributeTree(t, s);
+
+ TypeMirror VariableTypeMiror =
ctx.getInfo().getTrees().getElement(treePath).asType();
+
+ // variable initializer type should be same as variable type.
+ if (!ctx.getInfo().getTypes().isSameType(VariableTypeMiror,
initTypeMirror)) {
+ return null;
+ }
+
+ return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(),
Bundle.MSG_ConvertibleToVarType(), new JavaFixImpl(ctx.getInfo(),
ctx.getPath()).toEditorFix());
+ }
+
+ /**
+ * Fix for converting explicit type to 'var'
+ *
+ */
+ private static final class JavaFixImpl extends JavaFix {
+
+ public JavaFixImpl(CompilationInfo info, TreePath tp) {
+ super(info, tp);
+ }
+
+ @Override
+ @Messages("FIX_ShowMessage=Replace explicit type with var")
+ protected String getText() {
+ return Bundle.FIX_ShowMessage();
+ }
+
+ @Override
+ protected void performRewrite(TransformationContext tc) throws
Exception {
+
+ WorkingCopy wc = tc.getWorkingCopy();
+ TreePath statementPath = tc.getPath();
+ TreeMaker make = wc.getTreeMaker();
+
+ if (statementPath.getLeaf().getKind() == Tree.Kind.VARIABLE) {
+ VariableTree oldVariableTree = (VariableTree)
statementPath.getLeaf();
+
+ VariableTree newVariableTree = make.Variable(
+ oldVariableTree.getModifiers(),
+ oldVariableTree.getName(),
+ make.Type("var"),
+ oldVariableTree.getInitializer()
+ );
+ tc.getWorkingCopy().rewrite(oldVariableTree, newVariableTree);
+ }
+ }
+
+ }
+
+ /**
+ *
+ * @param ctx : HintContext
+ * @return true if pre-conditions for hint to be enable is meet
+ */
+ private static boolean preConditionChecker(HintContext ctx) {
+
+ CompilationInfo info = ctx.getInfo();
+
+ // hint will be enable only for JDK-10 or above.
+ if (info.getSourceVersion().compareTo(SourceVersion.RELEASE_9) < 1) {
+ return false;
+ }
+
+ TreePath treePath = ctx.getPath();
+
+ // variable should have local scope
+ if (info.getTrees().getElement(treePath).getKind() !=
ElementKind.LOCAL_VARIABLE) {
+ return false;
+ }
+
+ if (isDiagnosticCodeTobeSkipped(ctx.getInfo())) {
+ return false;
+ }
+
+ // hint is not applicable for variable declaration where type is
already 'var'
+ return !info.getTreeUtilities().isVarType(treePath);
+ }
+
+ /**
+ *
+ * @param info : compilationInfo
+ * @return true if Diagnostic Code is present in SKIPPED_ERROR_CODES
+ */
+ private static boolean isDiagnosticCodeTobeSkipped(CompilationInfo info) {
+ List<Diagnostic> diagnosticsList = info.getDiagnostics();
+ return diagnosticsList.stream().anyMatch((d) ->
(SKIPPED_ERROR_CODES.contains(d.getCode())));
+ }
+}
diff --git
a/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToVarHintTest.java
b/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToVarHintTest.java
new file mode 100644
index 0000000..408bcc6
--- /dev/null
+++
b/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertToVarHintTest.java
@@ -0,0 +1,358 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.netbeans.modules.java.hints.jdk;
+
+import org.netbeans.modules.java.hints.jdk.ConvertToVarHint;
+import org.junit.Test;
+import org.netbeans.modules.java.hints.test.api.HintTest;
+
+/**
+ *
+ * @author arusinha
+ */
+public class ConvertToVarHintTest {
+
+ private static final String VAR_CONV_DESC = "Explict type can be replaced
with 'var'"; //NOI18N
+ private static final String VAR_CONV_WARNING = "verifier:" +
VAR_CONV_DESC; //NOI18N
+
+ @Test
+ public void testIntLiteralRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " final int i = 10^;\n"
+ + " }\n"
+ + "}\n")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("3:8-3:25:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " final var i = 10;\n"
+ + " }\n"
+ + "}\n");
+ }
+
+ @Test
+ public void testStringLiteralRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " String str = \"Hello\"^;\n"
+ + " }\n"
+ + "}\n")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("3:8-3:29:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " var str = \"Hello\";\n"
+ + " }\n"
+ + "}\n");
+ }
+
+ @Test
+ public void testLocalRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "import java.util.HashMap;\n"
+ + "public class Test {\n"
+ + " {\n"
+ + " final HashMap<String,String> map = new
HashMap<String,String>()^;\n"
+ + " }\n"
+ + "}\n")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("4:8-4:72:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "import java.util.HashMap;\n"
+ + "public class Test {\n"
+ + " {\n"
+ + " final var map = new
HashMap<String,String>();\n"
+ + " }\n"
+ + "}\n");
+ }
+
+ @Test
+ public void testLambdaExprRefToVar() throws Exception {
+
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m2() {\n"
+ + " Runnable r = () ->^ {\n"
+ + " };\n"
+ + " r.run();\n"
+ + " }\n"
+ + "}\n")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .assertNotContainsWarnings(VAR_CONV_DESC);
+
+ }
+
+ @Test
+ public void testAnonymusObjRefToVar() throws Exception {
+
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " Runnable r = new Runnable()^ {\n"
+ + " @Override\n"
+ + " public void run() {\n"
+ + " }\n"
+ + " };\n"
+ + " }\n"
+ + "}\n")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .assertNotContainsWarnings(VAR_CONV_DESC);
+
+ }
+
+ @Test
+ public void testObjRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m1(){\n"
+ + " Obj^ect obj = new Object();\n"
+ + " }\n"
+ + "}")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("3:8-3:34:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "public class Test {\n"
+ + " void m1(){\n"
+ + " var obj = new Object();\n"
+ + " }\n"
+ + "}");
+ }
+
+ @Test
+ public void testArrayRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m1(){\n"
+ + " int[][] arr = new int[4][]^;\n"
+ + " }\n"
+ + "}")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("3:8-3:35:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "public class Test {\n"
+ + " void m1(){\n"
+ + " var arr = new int[4][];\n"
+ + " }\n"
+ + "}");
+ }
+
+ @Test
+ public void testDiamondInterfaceRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "import java.util.HashMap;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " final HashMap<String, String> map = new
HashMap<>^();\n"
+ + " }\n"
+ + "}")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .assertNotContainsWarnings(VAR_CONV_DESC);
+ }
+
+ @Test
+ public void testLiteralInitToVarRefInsideLoop() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m2() {\n"
+ + " for (int i = 0^; i < 10; i++) {\n"
+ + " i = i + 2;\n"
+ + " }\n"
+ + " }\n"
+ + "}\n")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("3:13-3:22:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "public class Test {\n"
+ + " void m2() {\n"
+ + " for (var i = 0; i < 10; i++) {\n"
+ + " i = i + 2;\n"
+ + " }\n"
+ + " }\n"
+ + "}\n");
+ }
+
+ @Test
+ public void testHintForVarType() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + "void m1(){\n"
+ + " var k = 20^;\n"
+ + "}\n"
+ + "}\n")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .assertNotContainsWarnings(VAR_CONV_DESC);
+ }
+
+ @Test
+ public void testSuperTypeRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "import java.util.ArrayList;\n"
+ + "import java.util.List;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " List<String> list1 = new
ArrayList<String>^();\n"
+ + " }\n"
+ + "}")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .assertNotContainsWarnings(VAR_CONV_DESC);
+
+ }
+
+ @Test
+ public void testSupportedSourceLevel() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " void m1() {\n"
+ + " final int i = 10^;\n"
+ + " }\n"
+ + "}\n")
+ .sourceLevel("1.9")
+ .run(ConvertToVarHint.class)
+ .assertNotContainsWarnings(VAR_CONV_DESC);
+
+ }
+
+ @Test
+ public void testClassMemberRefToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "public class Test {\n"
+ + " int i =10 ^;\n"
+ + "}")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .assertNotContainsWarnings(VAR_CONV_DESC);
+
+ }
+
+ @Test
+ public void testMethodAssignToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "import java.util.ArrayList;\n"
+ + "public class Test {\n"
+ + " public static void main(String[] args) {\n"
+ + " Object obj = m1()^;\n"
+ + " }\n"
+ + " static Object m1()\n"
+ + " {\n"
+ + " return new ArrayList<String>();\n"
+ + " }\n"
+ + "}")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("4:8-4:26:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "import java.util.ArrayList;\n"
+ + "public class Test {\n"
+ + " public static void main(String[] args) {\n"
+ + " var obj = m1();\n"
+ + " }\n"
+ + " static Object m1()\n"
+ + " {\n"
+ + " return new ArrayList<String>();\n"
+ + " }\n"
+ + "}");
+ }
+
+ @Test
+ public void testMethod2AssignToVar() throws Exception {
+ HintTest.create()
+ .setCaretMarker('^')
+ .input("package test;\n"
+ + "import java.util.Collections;\n"
+ + "import java.util.List;\n"
+ + "import java.util.ArrayList;\n"
+ + "public class Test {\n"
+ + " public static void main(String[] args) {\n"
+ + " List<String> list =
Collections.unmodifiableList(new ArrayList<String>())^;\n"
+ + " }\n"
+ + "}")
+ .sourceLevel("1.10")
+ .run(ConvertToVarHint.class)
+ .findWarning("6:8-6:82:" + VAR_CONV_WARNING)
+ .applyFix()
+ .assertCompilable()
+ .assertVerbatimOutput("package test;\n"
+ + "import java.util.Collections;\n"
+ + "import java.util.List;\n"
+ + "import java.util.ArrayList;\n"
+ + "public class Test {\n"
+ + " public static void main(String[] args) {\n"
+ + " var list = Collections.unmodifiableList(new
ArrayList<String>());\n"
+ + " }\n"
+ + "}");
+ }
+}
--
To stop receiving notification emails like this one, please contact
[email protected].
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists