You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@netbeans.apache.org by GitBox <gi...@apache.org> on 2018/04/03 15:36:07 UTC

[GitHub] geertjanw closed pull request #463: netbeans-479: Added ConvertToVarHint to replace explicit type with var

geertjanw closed pull request #463: netbeans-479: Added ConvertToVarHint to replace explicit type with var
URL: https://github.com/apache/incubator-netbeans/pull/463
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

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 837598e40..df353775d 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 000000000..e5d13e21b
--- /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/src/org/netbeans/modules/java/hints/suggestions/Tiny.java b/java.hints/src/org/netbeans/modules/java/hints/suggestions/Tiny.java
index 9cd0bf660..670dbe24f 100644
--- a/java.hints/src/org/netbeans/modules/java/hints/suggestions/Tiny.java
+++ b/java.hints/src/org/netbeans/modules/java/hints/suggestions/Tiny.java
@@ -222,6 +222,10 @@ public static ErrorDescription splitDeclaration(HintContext ctx) {
         Tree.Kind parentKind = ctx.getPath().getParentPath().getLeaf().getKind();
 
         if (parentKind != Tree.Kind.BLOCK && parentKind != Tree.Kind.CASE) return null;
+        
+        if(ctx.getInfo().getTreeUtilities().isVarType(ctx.getPath())){
+            return null; // hints discarded for var keyword
+        }      
 
         String displayName = NbBundle.getMessage(Tiny.class, "ERR_splitDeclaration");
         Fix fix = new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix();
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 000000000..408bcc631
--- /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"
+                        + "}");
+    }
+}
diff --git a/java.hints/test/unit/src/org/netbeans/modules/java/hints/suggestions/TinyTest.java b/java.hints/test/unit/src/org/netbeans/modules/java/hints/suggestions/TinyTest.java
index 94a2f0a21..c9683027c 100644
--- a/java.hints/test/unit/src/org/netbeans/modules/java/hints/suggestions/TinyTest.java
+++ b/java.hints/test/unit/src/org/netbeans/modules/java/hints/suggestions/TinyTest.java
@@ -268,6 +268,86 @@ public void testSplitDeclaration3() throws Exception {
                               "}\n");
     }
 
+    public void testSplitDeclarationForVar1() throws Exception {
+        HintTest
+                .create()
+                .setCaretMarker('|')
+                .input("package test;\n" +
+                       "public class Test {\n" +
+                       "    void m1(){\n" +
+                       "        var v =| 10; \n" +
+                       "    }\n" +
+                       "}\n")
+                .sourceLevel("1.10")
+                .run(Tiny.class)
+                .assertNotContainsWarnings("ERR_splitDeclaration");
+    }
+    
+    public void testSplitDeclarationForVar2() throws Exception {
+        HintTest
+                .create()
+                .setCaretMarker('|')
+                .input("package test;\n" +
+                       "public class Test {\n" +
+                       "    void m1(){\n" +
+                       "        final var i =| 10; \n" +
+                       "    }\n" +
+                       "}\n")
+                .sourceLevel("1.10")
+                .run(Tiny.class)
+                .assertNotContainsWarnings("ERR_splitDeclaration");
+    }
+    
+    public void testSplitDeclarationForVar3() throws Exception {
+        HintTest
+                .create()
+                .setCaretMarker('|')
+                .input("package test;\n" +
+                       "public class Test {\n" +
+                       "    void m1(){\n" +
+                       "        final/*comment*/var x =| 1.5; \n" +
+                       "    }\n" +
+                       "}\n")
+                .sourceLevel("1.10")
+                .run(Tiny.class)
+                .assertNotContainsWarnings("ERR_splitDeclaration");
+    }
+    
+    public void testSplitDeclarationForVar4() throws Exception {
+        HintTest
+                .create()
+                .setCaretMarker('|')
+                .input("package test;\n" +
+                       "public class Test {\n" +
+                       "    void m1(){\n" +
+                       "        var/*comment*/y =| 100; \n" +
+                       "    }\n" +
+                       "}\n")
+                .sourceLevel("1.10")
+                .run(Tiny.class)
+                .assertNotContainsWarnings("ERR_splitDeclaration");
+    }
+    
+    public void testSplitDeclarationForVar5() 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" +
+                       "        var v = 10; \n" +
+                       "        } \n" +
+                       "      }; \n" +
+                       "    }\n" +
+                       "}\n")
+                .sourceLevel("1.10")
+                .run(Tiny.class)
+                .findWarning("3:20-3:20:hint:ERR_splitDeclaration");
+    }
+ 
     public void testFillSwitch1() throws Exception {
         HintTest
                 .create()
@@ -451,4 +531,4 @@ public void testFillSwitchTypeVar222372() throws Exception {
                 .run(Tiny.class)
                 .assertWarnings();
     }
-}
\ No newline at end of file
+}
diff --git a/java.source.base/apichanges.xml b/java.source.base/apichanges.xml
index efe4cd72d..6c3399692 100644
--- a/java.source.base/apichanges.xml
+++ b/java.source.base/apichanges.xml
@@ -25,6 +25,18 @@
     <apidef name="javasource_base">Java Source API</apidef>
 </apidefs>
 <changes>
+    <change id="TreeUtilities.isVarType">
+        <api name="javasource_base"/>
+        <summary>Check the var type variable in given tree path.</summary>
+        <version major="1" minor="2.31"/>
+        <date day="27" month="3" year="2018"/>
+        <author login="vikasprabhakar"/>
+        <compatibility addition="yes" binary="compatible" source="compatible"/>
+        <description>
+            Check the var type variable in given tree path.
+        </description>
+        <class name="TreeUtilities" package="org.netbeans.api.java.source"/>
+    </change>
     <change id="ElementHandle.createModuleElementHandle">
         <api name="javasource_base"/>
         <summary>Added a method to create an <code>ElementHandle</code> for module</summary>
diff --git a/java.source.base/nbproject/project.properties b/java.source.base/nbproject/project.properties
index a97ce2287..406c43054 100644
--- a/java.source.base/nbproject/project.properties
+++ b/java.source.base/nbproject/project.properties
@@ -23,7 +23,7 @@ javadoc.name=Java Source Base
 javadoc.title=Java Source Base
 javadoc.arch=${basedir}/arch.xml
 javadoc.apichanges=${basedir}/apichanges.xml
-spec.version.base=2.30.0
+spec.version.base=2.31.0
 test.qa-functional.cp.extra=${refactoring.java.dir}/modules/ext/nb-javac-api.jar
 test.unit.run.cp.extra=${o.n.core.dir}/core/core.jar:\
     ${o.n.core.dir}/lib/boot.jar:\
diff --git a/java.source.base/src/org/netbeans/api/java/source/TreeUtilities.java b/java.source.base/src/org/netbeans/api/java/source/TreeUtilities.java
index d616476d0..01438ca8d 100644
--- a/java.source.base/src/org/netbeans/api/java/source/TreeUtilities.java
+++ b/java.source.base/src/org/netbeans/api/java/source/TreeUtilities.java
@@ -1850,7 +1850,24 @@ public boolean isCompileTimeConstantExpression(TreePath expression) {
         
         return ref.paramTypes;
     }
-    
+   
+    /**Check the var type variable in given tree path {@link TreePath}.
+     * 
+     * @param path the path of tree {@link TreePath}
+     * @return the true if tree contains var keyword else return false
+     * @since 2.31.0
+     */
+    public boolean isVarType(@NonNull TreePath path) {
+        TokenSequence<JavaTokenId> tokenSequence = tokensFor(path.getLeaf());
+        tokenSequence.moveStart();
+        while(tokenSequence.moveNext() && tokenSequence.token().id() != JavaTokenId.EQ){
+            if(tokenSequence.token().id() == JavaTokenId.VAR){
+                return true;
+            }
+        }
+        return false;
+    }
+ 
     private static final class NBScope implements Scope {
 
         private final JavacScope delegate;


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@netbeans.apache.org
For additional commands, e-mail: notifications-help@netbeans.apache.org

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists