You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@netbeans.apache.org by db...@apache.org on 2021/01/10 13:48:59 UTC

[netbeans] branch master updated: LSP codeAction fixes. (#2660)

This is an automated email from the ASF dual-hosted git repository.

dbalek pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/netbeans.git


The following commit(s) were added to refs/heads/master by this push:
     new 78a9ced  LSP codeAction fixes. (#2660)
78a9ced is described below

commit 78a9cedc8ac66e6cb6fabfd637b8139d9c28ea14
Author: Dusan Balek <du...@oracle.com>
AuthorDate: Sun Jan 10 14:48:30 2021 +0100

    LSP codeAction fixes. (#2660)
    
    * Introduce Field & Constant replaces all occurrences in all classes in single .java file - fixed.
    * Illegal state exception thrown from CreateOuterClassFix - fixed.
---
 .../modules/java/hints/errors/CreateClassFix.java  | 64 +++++++++++++++++++---
 .../IntroduceExpressionBasedMethodFix.java         |  2 +-
 .../java/hints/introduce/IntroduceFieldFix.java    | 10 +++-
 .../java/hints/introduce/IntroduceMethodFix.java   |  2 +-
 .../server/protocol/TextDocumentServiceImpl.java   |  3 +-
 .../org/netbeans/api/java/source/TreeMaker.java    |  4 ++
 6 files changed, 72 insertions(+), 13 deletions(-)

diff --git a/java/java.hints/src/org/netbeans/modules/java/hints/errors/CreateClassFix.java b/java/java.hints/src/org/netbeans/modules/java/hints/errors/CreateClassFix.java
index 46469b8..fe031d7 100644
--- a/java/java.hints/src/org/netbeans/modules/java/hints/errors/CreateClassFix.java
+++ b/java/java.hints/src/org/netbeans/modules/java/hints/errors/CreateClassFix.java
@@ -75,9 +75,9 @@ public abstract class CreateClassFix extends CreateFixBase implements EnhancedFi
     protected List<TypeMirrorHandle> argumentTypes; //if a specific constructor should be created
     protected List<String> argumentNames; //dtto.
     private Integer prio;
-    private List<TypeMirrorHandle> superTypes;
+    protected List<TypeMirrorHandle> superTypes;
     protected ElementKind kind;
-    private int numTypeParameters;
+    protected int numTypeParameters;
     protected List<? extends TypeMirror> argumentTypeMirrors;
     
     public CreateClassFix(CompilationInfo info, Set<Modifier> modifiers, List<? extends TypeMirror> argumentTypes, List<String> argumentNames, TypeMirror superType, ElementKind kind, int numTypeParameters) {
@@ -303,26 +303,72 @@ public abstract class CreateClassFix extends CreateFixBase implements EnhancedFi
                 public void run(final WorkingCopy working) throws IOException {
                     working.toPhase(Phase.RESOLVED);
                     TreeMaker make = working.getTreeMaker();
+                    List<Tree> members = new ArrayList<>();
+                    if (argumentNames != null) {
+                        List<VariableTree>         argTypes = new ArrayList<VariableTree>();
+                        Iterator<TypeMirrorHandle> typeIt   = argumentTypes.iterator();
+                        Iterator<String>           nameIt   = argumentNames.iterator();
+                        while (typeIt.hasNext() && nameIt.hasNext()) {
+                            TypeMirrorHandle tmh = typeIt.next();
+                            String           argName = nameIt.next();
+                            argTypes.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), argName, make.Type(tmh.resolve(working)), null));
+                        }
+                        members.add(make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC/*!!!*/)), "<init>", null, Collections.<TypeParameterTree>emptyList(), argTypes, Collections.<ExpressionTree>emptyList(), "{}" /*XXX*/, null)); // NOI18N
+                    }
+                    Tree extendsClause = null;
+                    List<Tree> implementsClause = Collections.<Tree>emptyList();
+                    if (superTypes != null) {
+                        DeclaredType extendsType = null;
+                        List<DeclaredType> implementsTypes = new LinkedList<DeclaredType>();
+                        for (TypeMirrorHandle h : superTypes) {
+                            TypeMirror tm = h.resolve(working);
+                            if (tm == null) {
+                                continue;
+                            }
+                            if (tm.getKind() != TypeKind.DECLARED) {
+                                continue;
+                            }
+                            DeclaredType dt = (DeclaredType) tm;
+                            if (dt.asElement().getKind().isClass()) {
+                                extendsType = dt;
+                            } else {
+                                implementsTypes.add(dt);
+                            }
+                        }
+                        if (extendsType != null && !"java.lang.Object".equals(((TypeElement) extendsType.asElement()).getQualifiedName().toString())) { // NOI18N
+                            extendsClause = make.Type(extendsType);
+                        }
+                        if (!implementsTypes.isEmpty()) {
+                            implementsClause = new LinkedList<Tree>();
+                            for (DeclaredType dt : implementsTypes) {
+                                implementsClause.add(make.Type(dt));
+                            }
+                        }
+                    }
+                    ModifiersTree nueModifiers = make.Modifiers(modifiers);
+                    List<TypeParameterTree> typeParameters = new LinkedList<TypeParameterTree>();
+                    for (int cntr = 0; cntr < numTypeParameters; cntr++) {
+                        typeParameters.add(make.TypeParameter(numTypeParameters == 1 ? "T" : "T" + cntr, Collections.<ExpressionTree>emptyList())); // NOI18N
+                    }
                     ClassTree source;
                     switch (kind) {
                         case CLASS:
-                            source = make.Class(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), simpleName, Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList());
+                            source = make.Class(nueModifiers, simpleName, typeParameters, extendsClause, implementsClause, members);
                             break;
                         case INTERFACE:
-                            source = make.Interface(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), simpleName, Collections.<TypeParameterTree>emptyList(), Collections.<Tree>emptyList(), Collections.<Tree>emptyList());
+                            source = make.Interface(nueModifiers, simpleName, typeParameters, implementsClause, members);
                             break;
                         case ANNOTATION_TYPE:
-                            source = make.AnnotationType(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), simpleName, Collections.<Tree>emptyList());
+                            source = make.AnnotationType(nueModifiers, simpleName, members);
                             break;
                         case ENUM:
-                            source = make.Enum(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), simpleName, Collections.<Tree>emptyList(), Collections.<Tree>emptyList());
+                            source = make.Enum(nueModifiers, simpleName, implementsClause, members);
                             break;
-                        default: throw new IllegalStateException();
+                        default:
+                            throw new IllegalStateException();
                     }
                     CompilationUnitTree cut = make.CompilationUnit(targetSourceRoot, packageName.replace('.', '/') + '/' + simpleName + ".java", Collections.<ImportTree>emptyList(), Collections.singletonList(source));
-                    ClassTree nue = createConstructor(working, new TreePath(new TreePath(cut), source));
                     working.rewrite(null, cut);
-                    working.rewrite(source, nue);
                 }
             });
         }
diff --git a/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceExpressionBasedMethodFix.java b/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceExpressionBasedMethodFix.java
index d5aa9e4..452ee25 100644
--- a/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceExpressionBasedMethodFix.java
+++ b/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceExpressionBasedMethodFix.java
@@ -265,7 +265,7 @@ final class IntroduceExpressionBasedMethodFix extends IntroduceFixBase implement
                     //handle duplicates
                     Document doc = copy.getDocument();
                     Pattern p = Pattern.createPatternWithRemappableVariables(expression, parameters, true);
-                    for (Occurrence desc : Matcher.create(copy).setCancel(new AtomicBoolean()).match(p)) {
+                    for (Occurrence desc : Matcher.create(copy).setSearchRoot(pathToClass).setCancel(new AtomicBoolean()).match(p)) {
                         TreePath firstLeaf = desc.getOccurrenceRoot();
                         int startOff = (int) copy.getTrees().getSourcePositions().getStartPosition(copy.getCompilationUnit(), firstLeaf.getLeaf());
                         int endOff = (int) copy.getTrees().getSourcePositions().getEndPosition(copy.getCompilationUnit(), firstLeaf.getLeaf());
diff --git a/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceFieldFix.java b/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceFieldFix.java
index 2392f07..21d0fd0 100644
--- a/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceFieldFix.java
+++ b/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceFieldFix.java
@@ -133,6 +133,14 @@ class IntroduceFieldFix extends IntroduceFixBase implements Fix {
         return pathToClass;
     }
 
+    private TreePath findOutermostClass(WorkingCopy copy, TreePath resolved) {
+        TreePath pathToClass = resolved;
+        while (pathToClass != null && (!TreeUtilities.CLASS_TREE_KINDS.contains(pathToClass.getLeaf().getKind()) || pathToClass.getParentPath().getLeaf().getKind() != Tree.Kind.COMPILATION_UNIT)) {
+            pathToClass = pathToClass.getParentPath();
+        }
+        return pathToClass;
+    }
+
     @Override
     public ChangeInfo implement() throws IOException, BadLocationException {
         JButton btnOk = new JButton(NbBundle.getMessage(IntroduceHint.class, "LBL_Ok"));
@@ -300,7 +308,7 @@ class IntroduceFieldFix extends IntroduceFixBase implements Fix {
             allNewUses.add(resolved.getLeaf());
             Collection<TreePath> duplicates = new ArrayList<>();
             if (replaceAll) {
-                for (TreePath p : SourceUtils.computeDuplicates(parameter, resolved, new TreePath(parameter.getCompilationUnit()), new AtomicBoolean())) {
+                for (TreePath p : SourceUtils.computeDuplicates(parameter, resolved, findOutermostClass(parameter, resolved), new AtomicBoolean())) {
                     if (variableRewrite) {
                         IntroduceHint.removeFromParent(parameter, p);
                     } else {
diff --git a/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceMethodFix.java b/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceMethodFix.java
index 0eefbb2..0e4fc7c 100644
--- a/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceMethodFix.java
+++ b/java/java.hints/src/org/netbeans/modules/java/hints/introduce/IntroduceMethodFix.java
@@ -835,7 +835,7 @@ public final class IntroduceMethodFix extends IntroduceFixBase implements Fix {
                     statementsPaths.add(new TreePath(firstStatement.getParentPath(), t));
                 }
                 Pattern p = Pattern.createPatternWithRemappableVariables(statementsPaths, parameters, true);
-                List<? extends Occurrence> occurrences = new ArrayList<Occurrence>(Matcher.create(copy).setCancel(new AtomicBoolean()).match(p));
+                List<? extends Occurrence> occurrences = new ArrayList<Occurrence>(Matcher.create(copy).setSearchRoot(pathToClass).setCancel(new AtomicBoolean()).match(p));
                 Collections.sort(occurrences, new OccurrencePositionComparator(copy.getCompilationUnit(), copy.getTrees().getSourcePositions()));
                 for (Occurrence desc :occurrences ) {
                     TreePath firstLeaf = desc.getOccurrenceRoot();
diff --git a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java
index 608c789..ea529ea 100644
--- a/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java
+++ b/java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/TextDocumentServiceImpl.java
@@ -1214,7 +1214,7 @@ public class TextDocumentServiceImpl implements TextDocumentService, LanguageCli
                             newFilePath = newFile.getPath();
                             documentChanges.add(Either.forRight(new CreateFile(newFilePath)));
                         }
-                        for (FileObject fileObject : changes.getModifiedFileObjects()) {
+                        outer: for (FileObject fileObject : changes.getModifiedFileObjects()) {
                             List<? extends ModificationResult.Difference> diffs = changes.getDifferences(fileObject);
                             if (diffs != null) {
                                 List<TextEdit> edits = new ArrayList<>();
@@ -1226,6 +1226,7 @@ public class TextDocumentServiceImpl implements TextDocumentService, LanguageCli
                                                     Collections.singletonList(new TextEdit(new Range(Utils.createPosition(fileObject, 0), Utils.createPosition(fileObject, 0)),
                                                             newText != null ? newText : "")))));
                                         }
+                                        continue outer;
                                     } else {
                                         edits.add(new TextEdit(new Range(Utils.createPosition(fileObject, diff.getStartPosition().getOffset()),
                                                                          Utils.createPosition(fileObject, diff.getEndPosition().getOffset())),
diff --git a/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java b/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java
index 7e2baa0..baef5da 100644
--- a/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java
+++ b/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java
@@ -3356,6 +3356,10 @@ public final class TreeMaker {
     }
     
     private void mapComments(BlockTree block, String inputText, WorkingCopy copy, CommentHandler comments, SourcePositions positions) {
+        if (copy.getFileObject() == null) {
+            // prevent IllegalStateException thrown form AssignComments constructor below
+            return;
+        }
         TokenSequence<JavaTokenId> seq = TokenHierarchy.create(inputText, JavaTokenId.language()).tokenSequence(JavaTokenId.language());
         AssignComments ti = new AssignComments(copy, block, seq, positions);
         ti.scan(block, null);


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

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