http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/indexing/VanillaCompileWorker.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/indexing/VanillaCompileWorker.java b/java.source.base/src/org/netbeans/modules/java/source/indexing/VanillaCompileWorker.java new file mode 100644 index 0000000..b329e4f --- /dev/null +++ b/java.source.base/src/org/netbeans/modules/java/source/indexing/VanillaCompileWorker.java @@ -0,0 +1,357 @@ +/** + * 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.source.indexing; + +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.PackageTree; +import com.sun.source.tree.Tree; +import com.sun.source.util.TreePath; +import com.sun.source.util.Trees; +import com.sun.tools.javac.api.JavacTaskImpl; +import com.sun.tools.javac.code.Symbol.ClassSymbol; +import com.sun.tools.javac.code.Symbol.TypeSymbol; +import com.sun.tools.javac.comp.AttrContext; +import com.sun.tools.javac.comp.CompileStates.CompileState; +import com.sun.tools.javac.comp.Enter; +import com.sun.tools.javac.comp.Env; +import com.sun.tools.javac.comp.Modules; +import com.sun.tools.javac.main.JavaCompiler; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCModuleDecl; +import com.sun.tools.javac.tree.JCTree.JCPackageDecl; +import org.netbeans.lib.nbjavac.services.CancelAbort; +import org.netbeans.lib.nbjavac.services.CancelService; +import com.sun.tools.javac.util.FatalError; +import com.sun.tools.javac.util.Log; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.Future; +import java.util.logging.Level; +import java.util.stream.Collectors; +import javax.annotation.processing.Processor; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.ModuleElement; +import javax.lang.model.element.TypeElement; +import javax.tools.JavaFileObject; +import org.netbeans.api.java.classpath.ClassPath; +import org.netbeans.api.java.queries.CompilerOptionsQuery; +import org.netbeans.api.java.source.ClasspathInfo; +import org.netbeans.api.java.source.ElementHandle; +import org.netbeans.modules.java.source.indexing.JavaCustomIndexer.CompileTuple; +import org.netbeans.modules.java.source.parsing.FileManagerTransaction; +import org.netbeans.modules.java.source.parsing.FileObjects; +import org.netbeans.modules.java.source.parsing.JavacParser; +import org.netbeans.modules.java.source.parsing.OutputFileManager; +import org.netbeans.modules.java.source.usages.ExecutableFilesIndex; +import org.netbeans.modules.parsing.spi.indexing.Context; +import org.netbeans.modules.parsing.spi.indexing.Indexable; +import org.netbeans.modules.parsing.spi.indexing.SuspendStatus; +import org.openide.filesystems.FileSystem; +import org.openide.filesystems.FileUtil; +import org.openide.util.Exceptions; + +/** + * + * @author Dusan Balek + */ +final class VanillaCompileWorker extends CompileWorker { + + @Override + protected ParsingOutput compile( + final ParsingOutput previous, + final Context context, + final JavaParsingContext javaContext, + final Collection<? extends CompileTuple> files) { + final Map<JavaFileObject, List<String>> file2FQNs = previous != null ? previous.file2FQNs : new HashMap<>(); + final Set<ElementHandle<TypeElement>> addedTypes = previous != null ? previous.addedTypes : new HashSet<>(); + final Set<ElementHandle<ModuleElement>> addedModules = previous != null ? previous.addedModules : new HashSet<>(); + final Set<File> createdFiles = previous != null ? previous.createdFiles : new HashSet<>(); + final Set<Indexable> finished = previous != null ? previous.finishedFiles : new HashSet<>(); + final Set<ElementHandle<TypeElement>> modifiedTypes = previous != null ? previous.modifiedTypes : new HashSet<>(); + final Set<javax.tools.FileObject> aptGenerated = previous != null ? previous.aptGenerated : new HashSet<>(); + + final DiagnosticListenerImpl dc = new DiagnosticListenerImpl(); + final LinkedList<CompilationUnitTree> trees = new LinkedList<CompilationUnitTree>(); + Map<CompilationUnitTree, CompileTuple> units = new IdentityHashMap<CompilationUnitTree, CompileTuple>(); + JavacTaskImpl jt = null; + + boolean nop = true; + final SuspendStatus suspendStatus = context.getSuspendStatus(); + final SourcePrefetcher sourcePrefetcher = SourcePrefetcher.create(files, suspendStatus); + Map<JavaFileObject, CompileTuple> fileObjects = new IdentityHashMap<>(); + try { + final boolean flm[] = {true}; + while (sourcePrefetcher.hasNext()) { + final CompileTuple tuple = sourcePrefetcher.next(); + try { + if (tuple != null) { + nop = false; + if (context.isCancelled()) { + return null; + } + fileObjects.put(tuple.jfo, tuple); + } + } finally { + sourcePrefetcher.remove(); + } + } + } finally { + try { + sourcePrefetcher.close(); + } catch (IOException ex) { + Exceptions.printStackTrace(ex); + } + } + ModuleName moduleName = new ModuleName(javaContext.getModuleName()); + if (nop) { + return ParsingOutput.success(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } + try { + jt = JavacParser.createJavacTask( + javaContext.getClasspathInfo(), + dc, + javaContext.getSourceLevel(), + javaContext.getProfile(), + javaContext.getFQNs(), + new CancelService() { + public @Override boolean isCanceled() { + return context.isCancelled() || isLowMemory(null); + } + }, + fileObjects.values().iterator().next().aptGenerated ? null : APTUtils.get(context.getRoot()), + CompilerOptionsQuery.getOptions(context.getRoot()), + fileObjects.keySet()); + for (CompilationUnitTree cut : jt.parse()) { + trees.add(cut); + CompileTuple tuple = fileObjects.get(cut.getSourceFile()); + units.put(cut, tuple); + computeFQNs(file2FQNs, cut, tuple); + } + Log.instance(jt.getContext()).nerrors = 0; + } catch (CancelAbort ca) { + if (context.isCancelled() && JavaIndex.LOG.isLoggable(Level.FINEST)) { + JavaIndex.LOG.log(Level.FINEST, "SuperOnePassCompileWorker was canceled in root: " + FileUtil.getFileDisplayName(context.getRoot()), ca); //NOI18N + } + } catch (Throwable t) { + if (JavaIndex.LOG.isLoggable(Level.WARNING)) { + final ClassPath bootPath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.BOOT); + final ClassPath classPath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.COMPILE); + final ClassPath sourcePath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE); + final String message = String.format("SuperOnePassCompileWorker caused an exception\nFile: %s\nRoot: %s\nBootpath: %s\nClasspath: %s\nSourcepath: %s", //NOI18N + fileObjects.values().iterator().next().indexable.getURL().toString(), + FileUtil.getFileDisplayName(context.getRoot()), + bootPath == null ? null : bootPath.toString(), + classPath == null ? null : classPath.toString(), + sourcePath == null ? null : sourcePath.toString() + ); + JavaIndex.LOG.log(Level.WARNING, message, t); //NOI18N + } + if (t instanceof ThreadDeath) { + throw (ThreadDeath) t; + } else { + jt = null; + units = null; + dc.cleanDiagnostics(); + freeMemory(false); + } + } + if (jt == null || units == null || JavaCustomIndexer.NO_ONE_PASS_COMPILE_WORKER) { + return ParsingOutput.failure(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } + if (context.isCancelled()) { + return null; + } + if (isLowMemory(null)) { + return ParsingOutput.lowMemory(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } + boolean aptEnabled = true; + Log log = Log.instance(jt.getContext()); + JavaCompiler compiler = JavaCompiler.instance(jt.getContext()); + Set<JavaFileObject> haveErrors = new HashSet<>(); + try { + final Iterable<? extends Element> types = jt.enter(trees); + if (context.isCancelled()) { + return null; + } + if (isLowMemory(null)) { + return ParsingOutput.lowMemory(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } + final Map<Element, CompileTuple> clazz2Tuple = new IdentityHashMap<Element, CompileTuple>(); + Enter enter = Enter.instance(jt.getContext()); + for (Element type : types) { + if (type.getKind().isClass() || type.getKind().isInterface() || type.getKind() == ElementKind.MODULE) { + Env<AttrContext> typeEnv = enter.getEnv((TypeSymbol) type); + if (typeEnv == null) { + JavaIndex.LOG.log(Level.FINE, "No Env for: {0}", ((TypeSymbol) type).getQualifiedName()); + continue; + } + clazz2Tuple.put(type, units.get(typeEnv.toplevel)); + } + } + jt.analyze(types); + if (context.isCancelled()) { + return null; + } + if (isLowMemory(null)) { + return ParsingOutput.lowMemory(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } + for (Entry<CompilationUnitTree, CompileTuple> unit : units.entrySet()) { + CompileTuple active = unit.getValue(); + if (aptEnabled) { + JavaCustomIndexer.addAptGenerated(context, javaContext, active, aptGenerated); + } + List<Element> activeTypes = new ArrayList<>(); + if (unit.getValue().jfo.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE)) { + final PackageTree pt = unit.getKey().getPackage(); + if (pt instanceof JCPackageDecl) { + final Element sym = ((JCPackageDecl)pt).packge; + if (sym != null) + activeTypes.add(sym); + } + } else { + for (Tree tree : unit.getKey().getTypeDecls()) { + if (tree instanceof JCTree) { + final JCTree jct = (JCTree)tree; + if (jct.getTag() == JCTree.Tag.CLASSDEF) { + final Element sym = ((JCClassDecl)tree).sym; + if (sym != null) + activeTypes.add(sym); + } else if (jct.getTag() == JCTree.Tag.MODULEDEF) { + final Element sym = ((JCModuleDecl)tree).sym; + if (sym != null) + activeTypes.add(sym); + } + } + } + } + javaContext.getFQNs().set(activeTypes, active.indexable.getURL()); + boolean[] main = new boolean[1]; + if (javaContext.getCheckSums().checkAndSet( + active.indexable.getURL(), + activeTypes.stream() + .filter((e) -> e.getKind().isClass() || e.getKind().isInterface()) + .map ((e) -> (TypeElement)e) + .collect(Collectors.toList()), + jt.getElements()) || context.isSupplementaryFilesIndexing()) { + javaContext.analyze(Collections.singleton(unit.getKey()), jt, active, addedTypes, addedModules, main); + } else { + final Set<ElementHandle<TypeElement>> aTypes = new HashSet<>(); + javaContext.analyze(Collections.singleton(unit.getKey()), jt, active, aTypes, addedModules, main); + addedTypes.addAll(aTypes); + modifiedTypes.addAll(aTypes); + } + ExecutableFilesIndex.DEFAULT.setMainClass(context.getRoot().toURL(), active.indexable.getURL(), main[0]); + if (!dc.getDiagnostics(active.jfo).isEmpty()) + haveErrors.add(active.jfo); + JavaCustomIndexer.setErrors(context, active, dc); + } + if (context.isCancelled()) { + return null; + } + if (isLowMemory(null)) { + return ParsingOutput.lowMemory(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } + final JavacTaskImpl jtFin = jt; + final Future<Void> done = FileManagerTransaction.runConcurrent(new FileSystem.AtomicAction() { + @Override + public void run() throws IOException { + Modules modules = Modules.instance(jtFin.getContext()); + compiler.shouldStopPolicyIfError = CompileState.FLOW; + for (Element type : types) { + TreePath tp = Trees.instance(jtFin).getPath(type); + assert tp != null; + log.nerrors = haveErrors.contains(tp.getCompilationUnit().getSourceFile()) ? 1 : 0; + Iterable<? extends JavaFileObject> generatedFiles = jtFin.generate(Collections.singletonList(type)); + CompileTuple unit = clazz2Tuple.get(type); + if (unit == null || !unit.virtual) { + for (JavaFileObject generated : generatedFiles) { + if (generated instanceof FileObjects.FileBase) { + createdFiles.add(((FileObjects.FileBase) generated).getFile()); + } else { + // presumably should not happen + } + } + } + } + if (!moduleName.assigned) { + ModuleElement module = !trees.isEmpty() ? + ((JCTree.JCCompilationUnit)trees.getFirst()).modle : + null; + if (module == null) { + module = modules.getDefaultModule(); + } + moduleName.name = module == null || module.isUnnamed() ? + null : + module.getQualifiedName().toString(); + moduleName.assigned = true; + } + } + }); + for (Entry<CompilationUnitTree, CompileTuple> unit : units.entrySet()) { + finished.add(unit.getValue().indexable); + } + done.get(); + return ParsingOutput.success(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } catch (OutputFileManager.InvalidSourcePath isp) { + //Deleted project - log & ignore + if (JavaIndex.LOG.isLoggable(Level.FINEST)) { + final ClassPath bootPath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.BOOT); + final ClassPath classPath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.COMPILE); + final ClassPath sourcePath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE); + final String message = String.format("SuperOnePassCompileWorker caused an exception\nRoot: %s\nBootpath: %s\nClasspath: %s\nSourcepath: %s", //NOI18N + FileUtil.getFileDisplayName(context.getRoot()), + bootPath == null ? null : bootPath.toString(), + classPath == null ? null : classPath.toString(), + sourcePath == null ? null : sourcePath.toString() + ); + JavaIndex.LOG.log(Level.FINEST, message, isp); + } + } catch (CancelAbort ca) { + if (isLowMemory(null)) { + return ParsingOutput.lowMemory(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } else if (JavaIndex.LOG.isLoggable(Level.FINEST)) { + JavaIndex.LOG.log(Level.FINEST, "SuperOnePassCompileWorker was canceled in root: " + FileUtil.getFileDisplayName(context.getRoot()), ca); //NOI18N + } + } catch (Throwable t) { + if (t instanceof ThreadDeath) { + throw (ThreadDeath) t; + } else { + Level level = t instanceof FatalError ? Level.FINEST : Level.WARNING; + if (JavaIndex.LOG.isLoggable(level)) { + final ClassPath bootPath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.BOOT); + final ClassPath classPath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.COMPILE); + final ClassPath sourcePath = javaContext.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE); + final String message = String.format("SuperOnePassCompileWorker caused an exception\nRoot: %s\nBootpath: %s\nClasspath: %s\nSourcepath: %s", //NOI18N + FileUtil.getFileDisplayName(context.getRoot()), + bootPath == null ? null : bootPath.toString(), + classPath == null ? null : classPath.toString(), + sourcePath == null ? null : sourcePath.toString() + ); + JavaIndex.LOG.log(level, message, t); //NOI18N + } + } + } + return ParsingOutput.failure(moduleName.name, file2FQNs, addedTypes, addedModules, createdFiles, finished, modifiedTypes, aptGenerated); + } +}
http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/matching/CopyFinder.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/matching/CopyFinder.java b/java.source.base/src/org/netbeans/modules/java/source/matching/CopyFinder.java index 9f99014..ab9af13 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/matching/CopyFinder.java +++ b/java.source.base/src/org/netbeans/modules/java/source/matching/CopyFinder.java @@ -71,7 +71,7 @@ import com.sun.source.tree.WhileLoopTree; import com.sun.source.tree.WildcardTree; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePath; -import com.sun.source.util.TreeScanner; +import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -105,7 +105,7 @@ import org.netbeans.api.java.source.CompilationInfo; * * @author Jan Lahoda */ -public class CopyFinder extends TreeScanner<Boolean, TreePath> { +public class CopyFinder extends ErrorAwareTreeScanner<Boolean, TreePath> { private final TreePath searchingFor; private final CompilationInfo info; http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/AbstractSourceFileObject.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/AbstractSourceFileObject.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/AbstractSourceFileObject.java index b60a657..8b7710e 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/AbstractSourceFileObject.java +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/AbstractSourceFileObject.java @@ -76,12 +76,13 @@ public abstract class AbstractSourceFileObject implements PrefetchableJavaFileOb protected AbstractSourceFileObject ( @NonNull final Handle handle, - @NullAllowed final JavaFileFilterImplementation filter) { + @NullAllowed final JavaFileFilterImplementation filter, + boolean hasContent) { //TODO: if has a content, then Kind.SOURCE, right?? Parameters.notNull("handle", handle); //NOI18N this.handle = handle; this.filter = filter; final String ext = this.handle.getExt(); - this.kind = filter == null ? + this.kind = filter == null && !hasContent ? FileObjects.getKind(ext) : Kind.SOURCE; //#141411 } http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/BasicSourceFileObject.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/BasicSourceFileObject.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/BasicSourceFileObject.java index 766957e..97a7534 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/BasicSourceFileObject.java +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/BasicSourceFileObject.java @@ -74,7 +74,7 @@ public class BasicSourceFileObject extends AbstractSourceFileObject implements D @NullAllowed final JavaFileFilterImplementation filter, @NullAllowed final CharSequence content, final boolean renderNow) throws IOException { - super(handle, filter); + super(handle, filter, content != null); this.hasFilter = filter != null; if (content != null || renderNow) { update(content); http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/CompilationInfoImpl.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/CompilationInfoImpl.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/CompilationInfoImpl.java index 6ce3c87..62bf92b 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/CompilationInfoImpl.java +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/CompilationInfoImpl.java @@ -163,7 +163,7 @@ public final class CompilationInfoImpl { this.isDetached = false; } - void update (final Snapshot snapshot) throws IOException { + public void update (final Snapshot snapshot) throws IOException { assert snapshot != null; this.jfo.update(snapshot.getText()); this.snapshot = snapshot; @@ -354,7 +354,7 @@ public final class CompilationInfoImpl { if (currentPhase.compareTo(phase)<0) { setPhase(phase); if (currentPhase == JavaSource.Phase.MODIFIED) - getJavacTask().analyze(); // Ensure proper javac initialization + getJavacTask().getElements().getTypeElement("java.lang.Object"); // Ensure proper javac initialization } return phase; } else { @@ -372,7 +372,7 @@ public final class CompilationInfoImpl { if (javacTask == null) { diagnosticListener = new DiagnosticListenerImpl(this.root, this.jfo, this.cpInfo); javacTask = JavacParser.createJavacTask(this.file, this.root, this.cpInfo, - this.parser, diagnosticListener, null, isDetached); + this.parser, diagnosticListener, isDetached); } return javacTask; } @@ -413,7 +413,7 @@ public final class CompilationInfoImpl { * Returns current {@link DiagnosticListener} * @return listener */ - DiagnosticListener<JavaFileObject> getDiagnosticListener() { + public DiagnosticListener<JavaFileObject> getDiagnosticListener() { return diagnosticListener; } @@ -452,7 +452,7 @@ public final class CompilationInfoImpl { // Innerclasses ------------------------------------------------------------ @Trusted - static class DiagnosticListenerImpl implements DiagnosticListener<JavaFileObject> { + public static class DiagnosticListenerImpl implements DiagnosticListener<JavaFileObject> { private final Map<JavaFileObject, Diagnostics> source2Errors; private final FileObject root; @@ -517,12 +517,12 @@ public final class CompilationInfoImpl { return errors; } - final boolean hasPartialReparseErrors () { + public final boolean hasPartialReparseErrors () { // #236654: warnings should not stop processing of the reparsed method return this.partialReparseErrors != null && partialReparseRealErrors; } - final void startPartialReparse (int from, int to) { + public final void startPartialReparse (int from, int to) { if (partialReparseErrors == null) { partialReparseErrors = new ArrayList<>(); Diagnostics errors = getErrors(jfo); @@ -562,7 +562,7 @@ public final class CompilationInfoImpl { partialReparseRealErrors = false; } - final void endPartialReparse (final int delta) { + public final void endPartialReparse (final int delta) { this.currentDelta+=delta; } @@ -602,27 +602,18 @@ public final class CompilationInfoImpl { @Override public long getPosition() { long ret = this.delegate.getPosition(); - if (delegate.hasFixedPositions()) { - ret+=currentDelta; - } return ret; } @Override public long getStartPosition() { long ret = this.delegate.getStartPosition(); - if (delegate.hasFixedPositions()) { - ret+=currentDelta; - } return ret; } @Override public long getEndPosition() { long ret = this.delegate.getEndPosition(); - if (delegate.hasFixedPositions()) { - ret+=currentDelta; - } return ret; } http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/FileManagerTransaction.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/FileManagerTransaction.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/FileManagerTransaction.java index f214d7b..ca35183 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/FileManagerTransaction.java +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/FileManagerTransaction.java @@ -18,7 +18,6 @@ */ package org.netbeans.modules.java.source.parsing; -import com.sun.tools.javac.model.LazyTreeLoader; import java.io.*; import java.net.URL; import java.nio.channels.CompletionHandler; @@ -37,7 +36,6 @@ import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.annotations.common.NullAllowed; import org.netbeans.modules.java.preprocessorbridge.spi.JavaFileFilterImplementation; -import org.netbeans.modules.java.source.TreeLoader; import org.netbeans.modules.java.source.indexing.JavaIndexerWorker; import org.netbeans.modules.java.source.indexing.TransactionContext; import org.openide.filesystems.FileSystem; @@ -375,9 +373,7 @@ public abstract class FileManagerTransaction extends TransactionContext.Service @NonNull private FileManagerTransaction getDelegate() { - return TreeLoader.isTreeLoading() ? - writeThrough : - nullWrite; + return nullWrite; } } http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/FindAnonymousVisitor.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/FindAnonymousVisitor.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/FindAnonymousVisitor.java deleted file mode 100644 index 5d84b2a..0000000 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/FindAnonymousVisitor.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * 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.source.parsing; - -import com.sun.source.tree.ClassTree; -import com.sun.source.tree.MethodTree; -import com.sun.source.tree.Tree; -import com.sun.source.tree.VariableTree; -import com.sun.source.util.TreeScanner; -import com.sun.tools.javac.tree.JCTree.JCClassDecl; -import java.util.HashSet; -import java.util.Set; -import org.netbeans.lib.nbjavac.services.NBTreeMaker.IndexedClassDecl; - -/** - * Partial reparse helper visitor. - * Finds anonymous and local classes in given method tree. - * @author Tomas Zezula - */ -class FindAnonymousVisitor extends TreeScanner<Void,Void> { - - private static enum Mode {COLLECT, CHECK}; - - int firstInner = -1; - int noInner; - boolean hasLocalClass; - final Set<Tree> docOwners = new HashSet<Tree>(); - private Mode mode = Mode.COLLECT; - - public final void reset () { - this.firstInner = -1; - this.noInner = 0; - this.hasLocalClass = false; - this.mode = Mode.CHECK; - } - - @Override - public Void visitClass(ClassTree node, Void p) { - if (firstInner == -1) { - firstInner = ((IndexedClassDecl)node).index; - } - if (node.getSimpleName().length() != 0) { - hasLocalClass = true; - } - noInner++; - handleDoc(node); - return super.visitClass(node, p); - } - - @Override - public Void visitMethod(MethodTree node, Void p) { - handleDoc(node); - return super.visitMethod(node, p); - } - - @Override - public Void visitVariable(VariableTree node, Void p) { - handleDoc(node); - return super.visitVariable(node, p); - } - - private void handleDoc (final Tree tree) { - if (mode == Mode.COLLECT) { - docOwners.add(tree); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacFlowListener.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacFlowListener.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacFlowListener.java index f28c7f1..8354821 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacFlowListener.java +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacFlowListener.java @@ -36,7 +36,7 @@ import org.openide.filesystems.FileObject; * * @author Tomas Zezula */ -class JavacFlowListener { +public class JavacFlowListener { protected static final Context.Key<JavacFlowListener> flowListenerKey = new Context.Key<JavacFlowListener>(); @@ -58,7 +58,7 @@ class JavacFlowListener { jti.setTaskListener(new TaskListenerImpl()); } - final boolean hasFlowCompleted (final FileObject fo) { + public final boolean hasFlowCompleted (final FileObject fo) { if (fo == null) { return false; } http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java index 5975abf..e044b86 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java @@ -19,33 +19,18 @@ package org.netbeans.modules.java.source.parsing; -import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.MethodTree; -import com.sun.source.tree.Tree; -import com.sun.source.util.TreePath; +import com.sun.source.util.JavacTask; import com.sun.source.util.Trees; -import com.sun.tools.javac.api.ClassNamesForFileOraculum; -import com.sun.tools.javac.api.DuplicateClassChecker; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.api.JavacTool; -import com.sun.tools.javac.api.JavacTrees; -import com.sun.tools.javac.parser.LazyDocCommentTable; -import com.sun.tools.javac.tree.EndPosTable; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.JCBlock; -import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; -import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.util.Abort; import org.netbeans.lib.nbjavac.services.CancelAbort; import org.netbeans.lib.nbjavac.services.CancelService; import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.CouplingAbort; -import com.sun.tools.javac.util.Log; -import com.sun.tools.javac.util.Options; -import com.sun.tools.javac.util.Position.LineMapImpl; import com.sun.tools.javadoc.main.JavadocClassFinder; import java.io.File; @@ -62,7 +47,6 @@ import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; @@ -80,7 +64,6 @@ import javax.annotation.processing.Processor; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.Document; -import javax.tools.Diagnostic; import javax.tools.DiagnosticListener; import javax.tools.JavaFileObject; @@ -94,7 +77,6 @@ import org.netbeans.api.java.source.ClasspathInfo.PathKind; import org.netbeans.api.java.source.JavaParserResultTask; import org.netbeans.api.java.source.JavaSource; import org.netbeans.api.java.source.JavaSource.Phase; -import org.netbeans.api.java.source.SourceUtils; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.netbeans.lib.editor.util.swing.PositionRegion; @@ -103,7 +85,6 @@ import org.netbeans.modules.java.source.JavaFileFilterQuery; import org.netbeans.modules.java.source.JavaSourceAccessor; import org.netbeans.modules.java.source.JavadocEnv; import org.netbeans.modules.java.source.PostFlowAnalysis; -import org.netbeans.modules.java.source.TreeLoader; import org.netbeans.modules.java.source.indexing.APTUtils; import org.netbeans.modules.java.source.indexing.FQN2Files; import org.netbeans.lib.nbjavac.services.NBAttr; @@ -118,7 +99,6 @@ import org.netbeans.lib.nbjavac.services.NBJavacTrees; import org.netbeans.lib.nbjavac.services.NBMessager; import org.netbeans.lib.nbjavac.services.NBResolve; import org.netbeans.lib.nbjavac.services.NBTreeMaker; -import org.netbeans.lib.nbjavac.services.PartialReparser; import org.netbeans.modules.java.source.indexing.JavaIndex; import org.netbeans.modules.java.source.tasklist.CompilerSettings; import org.netbeans.modules.java.source.usages.ClassIndexImpl; @@ -137,8 +117,10 @@ import org.openide.filesystems.FileUtil; import org.openide.modules.SpecificationVersion; import org.openide.util.ChangeSupport; import org.openide.util.Exceptions; +import org.openide.util.Lookup; import org.openide.util.Pair; import org.openide.util.WeakListeners; +import org.openide.util.lookup.ServiceProvider; /** * Provides Parsing API parser built atop Javac (using JSR 199). @@ -159,7 +141,7 @@ public class JavacParser extends Parser { private static final int MAX_DUMPS = Integer.getInteger("org.netbeans.modules.java.source.parsing.JavacParser.maxDumps", 255); //NOI18N //Command line switch disabling partial reparse private static final boolean DISABLE_PARTIAL_REPARSE = Boolean.getBoolean("org.netbeans.modules.java.source.parsing.JavacParser.no_reparse"); //NOI18N - private static final String LOMBOK_DETECTED = "lombokDetected"; + public static final String LOMBOK_DETECTED = "lombokDetected"; /** * Helper map mapping the {@link Phase} to message for performance logger @@ -200,6 +182,7 @@ public class JavacParser extends Parser { private final FilterListener filterListener; //ClasspathInfo Listener private final ChangeListener cpInfoListener; + private final SequentialParsing sequentialParsing; //Cached javac impl private CompilationInfoImpl ciImpl; //State of the parser, used only for single source parser, otherwise don't care. @@ -240,6 +223,7 @@ public class JavacParser extends Parser { } } }); + this.sequentialParsing = Lookup.getDefault().lookup(SequentialParsing.class); } private void init (final Snapshot snapshot, final Task task, final boolean singleSource) { @@ -401,12 +385,14 @@ public class JavacParser extends Parser { final Pair<DocPositionRegion,MethodTree> _changedMethod = changedMethod.getAndSet(null); if (_changedMethod != null && ciImpl != null) { LOGGER.log(Level.FINE, "\t:trying partial reparse:\n{0}", _changedMethod.first().getText()); //NOI18N - needsFullReparse = !reparseMethod(ciImpl, snapshot, _changedMethod.second(), _changedMethod.first().getText()); + PartialReparser reparser = Lookup.getDefault().lookup(PartialReparser.class); + needsFullReparse = !reparser.reparseMethod(ciImpl, snapshot, _changedMethod.second(), _changedMethod.first().getText()); if (!needsFullReparse) { ciImpl.setChangedMethod(_changedMethod); } } } + System.err.println("needsFullReparse=" + needsFullReparse); if (needsFullReparse) { positions.clear(); ciImpl = createCurrentInfo (this, file, root, snapshot, null, null); @@ -416,8 +402,8 @@ public class JavacParser extends Parser { default: init (snapshot, task, false); ciImpl = createCurrentInfo(this, file, root, snapshot, - ciImpl == null ? null : ciImpl.getJavacTask(), - ciImpl == null ? null : ciImpl.getDiagnosticListener()); + sequentialParsing != null && ciImpl == null ? null : ciImpl.getJavacTask(), + sequentialParsing != null && ciImpl == null ? null : ciImpl.getDiagnosticListener()); } success = true; } finally { @@ -582,7 +568,12 @@ public class JavacParser extends Parser { } long start = System.currentTimeMillis(); // XXX - this might be with wrong encoding - Iterable<? extends CompilationUnitTree> trees = currentInfo.getJavacTask().parse(new JavaFileObject[] {currentInfo.jfo}); + Iterable<? extends CompilationUnitTree> trees; + if (sequentialParsing != null) { + trees = sequentialParsing.parse(currentInfo.getJavacTask(), currentInfo.jfo); + } else { + trees = currentInfo.getJavacTask().parse(); + } if (trees == null) { LOGGER.log( Level.INFO, "Did not parse anything for: {0}", currentInfo.jfo.toUri()); //NOI18N return Phase.MODIFIED; @@ -638,18 +629,11 @@ public class JavacParser extends Parser { if (currentPhase == Phase.RESOLVED && phase.compareTo(Phase.UP_TO_DATE)>=0) { currentPhase = Phase.UP_TO_DATE; } - } catch (CouplingAbort a) { - TreeLoader.dumpCouplingAbort(a, null); - return currentPhase; } catch (CancelAbort ca) { currentPhase = Phase.MODIFIED; invalidate(false); } catch (Abort abort) { parserError = currentPhase; - } catch (IOException ex) { - currentInfo.parserCrashed = currentPhase; - dumpSource(currentInfo, ex); - throw ex; } catch (RuntimeException | Error ex) { parserError = currentPhase; dumpSource(currentInfo, ex); @@ -681,17 +665,16 @@ public class JavacParser extends Parser { final ClasspathInfo cpInfo, final JavacParser parser, final DiagnosticListener<? super JavaFileObject> diagnosticListener, - final ClassNamesForFileOraculum oraculum, final boolean detached) { if (file != null) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.log(Level.FINER, "Created new JavacTask for: {0}", FileUtil.getFileDisplayName(file)); } } - FQN2Files dcc = null; + FQN2Files fqn2Files = null; if (root != null) { try { - dcc = FQN2Files.forRoot(root.toURL()); + fqn2Files = FQN2Files.forRoot(root.toURL()); } catch (IOException ex) { LOGGER.log(Level.FINE, null, ex); } @@ -744,14 +727,16 @@ public class JavacParser extends Parser { sourceLevel != null ? sourceLevel.getSourceLevel() : null, sourceLevel != null ? sourceLevel.getProfile() : null, flags, - oraculum, - dcc, + fqn2Files, parser == null ? null : new DefaultCancelService(parser), APTUtils.get(root), compilerOptions, - additionalModules); - Context context = javacTask.getContext(); - TreeLoader.preRegister(context, cpInfo, detached); + additionalModules, + file != null ? Arrays.asList(FileObjects.sourceFileObject(file, root)) : Collections.emptyList()); + Lookup.getDefault() + .lookupAll(TreeLoaderRegistry.class) + .stream() + .forEach(r -> r.enhance(javacTask.getContext(), cpInfo, detached)); return javacTask; } } @@ -761,23 +746,23 @@ public class JavacParser extends Parser { @NullAllowed final DiagnosticListener<? super JavaFileObject> diagnosticListener, @NullAllowed final String sourceLevel, @NullAllowed final SourceLevelQuery.Profile sourceProfile, - @NullAllowed final ClassNamesForFileOraculum cnih, - @NullAllowed final DuplicateClassChecker dcc, + @NullAllowed FQN2Files fqn2Files, @NullAllowed final CancelService cancelService, @NullAllowed final APTUtils aptUtils, - @NullAllowed final CompilerOptionsQuery.Result compilerOptions) { + @NullAllowed final CompilerOptionsQuery.Result compilerOptions, + @NonNull Iterable<? extends JavaFileObject> files) { return createJavacTask( cpInfo, diagnosticListener, sourceLevel, sourceProfile, EnumSet.of(ConfigFlags.BACKGROUND_COMPILATION, ConfigFlags.MULTI_SOURCE), - cnih, - dcc, + fqn2Files, cancelService, aptUtils, compilerOptions, - Collections.emptySet()); + Collections.emptySet(), + files); } private static enum ConfigFlags { @@ -792,12 +777,12 @@ public class JavacParser extends Parser { @NullAllowed final String sourceLevel, @NullAllowed SourceLevelQuery.Profile sourceProfile, @NonNull final Set<? extends ConfigFlags> flags, - @NullAllowed final ClassNamesForFileOraculum cnih, - @NullAllowed final DuplicateClassChecker dcc, + @NullAllowed FQN2Files fqn2Files, @NullAllowed final CancelService cancelService, @NullAllowed final APTUtils aptUtils, @NullAllowed final CompilerOptionsQuery.Result compilerOptions, - @NonNull final Collection<? extends String> additionalModules) { + @NonNull final Collection<? extends String> additionalModules, + @NonNull Iterable<? extends JavaFileObject> files) { final boolean backgroundCompilation = flags.contains(ConfigFlags.BACKGROUND_COMPILATION); final boolean multiSource = flags.contains(ConfigFlags.MULTI_SOURCE); final List<String> options = new ArrayList<>(); @@ -883,19 +868,18 @@ public class JavacParser extends Parser { NBMessager.preRegister(context, null, DEV_NULL, DEV_NULL, DEV_NULL); JavacTaskImpl task = (JavacTaskImpl)JavacTool.create().getTask(null, ClasspathInfoAccessor.getINSTANCE().createFileManager(cpInfo, validatedSourceLevel.name), - diagnosticListener, options, null, Collections.<JavaFileObject>emptySet(), + diagnosticListener, options, files.iterator().hasNext() ? null : Arrays.asList("java.lang.Object"), files, context); if (aptEnabled) { task.setProcessors(processors); } NBClassReader.preRegister(context); - JavadocClassFinder.preRegister(context, !backgroundCompilation); - if (cnih != null) { - context.put(ClassNamesForFileOraculum.class, cnih); - } - if (dcc != null) { - context.put(DuplicateClassChecker.class, dcc); - } + if (!backgroundCompilation) + JavadocClassFinder.preRegister(context); + Lookup.getDefault() + .lookupAll(DuplicateClassRegistry.class) + .stream() + .forEach(r -> r.enhance(context, fqn2Files)); if (cancelService != null) { DefaultCancelService.preRegister(context, cancelService); } @@ -1077,7 +1061,7 @@ public class JavacParser extends Parser { return false; } - private static void logTime (FileObject source, Phase phase, long time) { + public static void logTime (FileObject source, Phase phase, long time) { assert source != null && phase != null; String message = phase2Message.get(phase); assert message != null; @@ -1091,7 +1075,7 @@ public class JavacParser extends Parser { * @param info CompilationInfo for which the error occurred. * @param exc exception to write to the end of dump file */ - private static void dumpSource(CompilationInfoImpl info, Throwable exc) { + public static void dumpSource(CompilationInfoImpl info, Throwable exc) { String userDir = System.getProperty("netbeans.user"); if (userDir == null) { return; @@ -1154,168 +1138,6 @@ public class JavacParser extends Parser { } } - private static boolean reparseMethod (final CompilationInfoImpl ci, - final Snapshot snapshot, - final MethodTree orig, - final String newBody) throws IOException { - assert ci != null; - final FileObject fo = ci.getFileObject(); - if (LOGGER.isLoggable(Level.FINER)) { - LOGGER.log(Level.FINER, "Reparse method in: {0}", fo); //NOI18N - } - if (((JCMethodDecl)orig).localEnv == null) { - //We are seeing interface method or abstract or native method with body. - //Don't do any optimalization of this broken code - has no attr env. - return false; - } - final Phase currentPhase = ci.getPhase(); - if (Phase.PARSED.compareTo(currentPhase) > 0) { - return false; - } - try { - final CompilationUnitTree cu = ci.getCompilationUnit(); - if (cu == null || newBody == null) { - return false; - } - final JavacTaskImpl task = ci.getJavacTask(); - if (Options.instance(task.getContext()).isSet(LOMBOK_DETECTED)) { - return false; - } - PartialReparser pr = PartialReparser.instance(task.getContext()); - final JavacTrees jt = JavacTrees.instance(task); - final int origStartPos = (int) jt.getSourcePositions().getStartPosition(cu, orig.getBody()); - final int origEndPos = (int) jt.getSourcePositions().getEndPosition(cu, orig.getBody()); - if (origStartPos < 0) { - LOGGER.log(Level.WARNING, "Javac returned startpos: {0} < 0", new Object[]{origStartPos}); //NOI18N - return false; - } - if (origStartPos > origEndPos) { - LOGGER.log(Level.WARNING, "Javac returned startpos: {0} > endpos: {1}", new Object[]{origStartPos, origEndPos}); //NOI18N - return false; - } - final FindAnonymousVisitor fav = new FindAnonymousVisitor(); - fav.scan(orig.getBody(), null); - if (fav.hasLocalClass) { - if (LOGGER.isLoggable(Level.FINER)) { - LOGGER.log(Level.FINER, "Skeep reparse method (old local classes): {0}", fo); //NOI18N - } - return false; - } - final int firstInner = fav.firstInner; - final int noInner = fav.noInner; - final Context ctx = task.getContext(); - final TreeLoader treeLoader = TreeLoader.instance(ctx); - if (treeLoader != null) { - treeLoader.startPartialReparse(); - } - try { - final Log l = Log.instance(ctx); - l.startPartialReparse(); - final JavaFileObject prevLogged = l.useSource(cu.getSourceFile()); - JCBlock block; - try { - DiagnosticListener dl = ci.getDiagnosticListener(); - assert dl instanceof CompilationInfoImpl.DiagnosticListenerImpl; - ((CompilationInfoImpl.DiagnosticListenerImpl)dl).startPartialReparse(origStartPos, origEndPos); - long start = System.currentTimeMillis(); - Map<JCTree,LazyDocCommentTable.Entry> docComments = new HashMap<>(); - block = pr.reparseMethodBody(cu, orig, newBody + " ", firstInner, docComments); - LOGGER.log(Level.FINER, "Reparsed method in: {0}", fo); //NOI18N - if (block == null) { - LOGGER.log( - Level.FINER, - "Skeep reparse method, invalid position, newBody: ", //NOI18N - newBody); - return false; - } - final int newEndPos = (int) jt.getSourcePositions().getEndPosition(cu, block); - if (newEndPos != origStartPos + newBody.length()) { - return false; - } - fav.reset(); - fav.scan(block, null); - final int newNoInner = fav.noInner; - if (fav.hasLocalClass || noInner != newNoInner) { - if (LOGGER.isLoggable(Level.FINER)) { - LOGGER.log(Level.FINER, "Skeep reparse method (new local classes): {0}", fo); //NOI18N - } - return false; - } - ((LazyDocCommentTable) ((JCTree.JCCompilationUnit)cu).docComments).table.keySet().removeAll(fav.docOwners); - ((LazyDocCommentTable) ((JCTree.JCCompilationUnit)cu).docComments).table.putAll(docComments); - long end = System.currentTimeMillis(); - if (fo != null) { - logTime (fo,Phase.PARSED,(end-start)); - } - final int delta = newEndPos - origEndPos; - final EndPosTable endPos = ((JCCompilationUnit)cu).endPositions; - final TranslatePositionsVisitor tpv = new TranslatePositionsVisitor(orig, endPos, delta); - tpv.scan(cu, null); - ((JCMethodDecl)orig).body = block; - if (Phase.RESOLVED.compareTo(currentPhase)<=0) { - start = System.currentTimeMillis(); - pr.reattrMethodBody(orig, block); - if (LOGGER.isLoggable(Level.FINER)) { - LOGGER.log(Level.FINER, "Resolved method in: {0}", fo); //NOI18N - } - if (!((CompilationInfoImpl.DiagnosticListenerImpl)dl).hasPartialReparseErrors()) { - final JavacFlowListener fl = JavacFlowListener.instance(ctx); - if (fl != null && fl.hasFlowCompleted(fo)) { - if (LOGGER.isLoggable(Level.FINER)) { - final List<? extends Diagnostic> diag = ci.getDiagnostics(); - if (!diag.isEmpty()) { - LOGGER.log(Level.FINER, "Reflow with errors: {0} {1}", new Object[]{fo, diag}); //NOI18N - } - } - TreePath tp = TreePath.getPath(cu, orig); //todo: store treepath in changed method => improve speed - Tree t = tp.getParentPath().getLeaf(); - pr.reflowMethodBody(cu, (ClassTree) t, orig); - if (LOGGER.isLoggable(Level.FINER)) { - LOGGER.log(Level.FINER, "Reflowed method in: {0}", fo); //NOI18N - } - } - } - end = System.currentTimeMillis(); - if (fo != null) { - logTime (fo, Phase.ELEMENTS_RESOLVED,0L); - logTime (fo,Phase.RESOLVED,(end-start)); - } - } - - //fix CompilationUnitTree.getLineMap: - long startM = System.currentTimeMillis(); - char[] chars = snapshot.getText().toString().toCharArray(); - ((LineMapImpl) cu.getLineMap()).build(chars, chars.length); - LOGGER.log(Level.FINER, "Rebuilding LineMap took: {0}", System.currentTimeMillis() - startM); - - ((CompilationInfoImpl.DiagnosticListenerImpl)dl).endPartialReparse (delta); - } finally { - l.endPartialReparse(); - l.useSource(prevLogged); - } - ci.update(snapshot); - } finally { - if (treeLoader != null) { - treeLoader.endPartialReparse(); - } - } - } catch (CouplingAbort ca) { - //Needs full reparse - return false; - } catch (Throwable t) { - if (t instanceof ThreadDeath) { - throw (ThreadDeath) t; - } - boolean a = false; - assert a = true; - if (a) { - dumpSource(ci, t); - } - return false; - } - return true; - } - //Helper classes private static class DefaultCancelService extends CancelService { @@ -1396,4 +1218,33 @@ public class JavacParser extends Parser { listeners.fireChange(); } } + + public static interface PartialReparser { + public boolean reparseMethod (final CompilationInfoImpl ci, + final Snapshot snapshot, + final MethodTree orig, + final String newBody) throws IOException; + } + + @ServiceProvider(service = PartialReparser.class, position = 1000) + public static class DefaultPartialReparser implements PartialReparser { + + @Override + public boolean reparseMethod(CompilationInfoImpl ci, Snapshot snapshot, MethodTree orig, String newBody) throws IOException { + return false; + } + + } + + public static interface TreeLoaderRegistry { + public void enhance(Context context, ClasspathInfo cpInfo, boolean detached); + } + + public static interface DuplicateClassRegistry { + public void enhance(Context context, FQN2Files fqn2Files); + } + + public static interface SequentialParsing { + public Iterable<? extends CompilationUnitTree> parse(JavacTask task, JavaFileObject file) throws IOException; + } } http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/ModuleOraculum.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/ModuleOraculum.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/ModuleOraculum.java index 45cd52a..364b467 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/ModuleOraculum.java +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/ModuleOraculum.java @@ -182,7 +182,6 @@ public final class ModuleOraculum implements CompilerOptionsQueryImplementation, @NonNull private static String parsePackage(FileObject file) { String pkg = ""; //NOI18N - try { final JavacTaskImpl jt = JavacParser.createJavacTask( new ClasspathInfo.Builder(ClassPath.EMPTY).build(), null, @@ -192,22 +191,16 @@ public final class ModuleOraculum implements CompilerOptionsQueryImplementation, null, null, null, - null); - final CompilationUnitTree cu = jt.parse(FileObjects.fileObjectFileObject( + Collections.singletonList(FileObjects.fileObjectFileObject( file, file.getParent(), null, - FileEncodingQuery.getEncoding(file))).iterator().next(); + FileEncodingQuery.getEncoding(file)))); + final CompilationUnitTree cu = jt.parse().iterator().next(); pkg = Optional.ofNullable(cu.getPackage()) .map((pt) -> pt.getPackageName()) .map((xt) -> xt.toString()) .orElse(pkg); - } catch (IOException ioe) { - LOG.log( - Level.INFO, - "Cannot parse: {0}", - FileUtil.getFileDisplayName(file)); - } return pkg; } @@ -253,7 +246,7 @@ public final class ModuleOraculum implements CompilerOptionsQueryImplementation, R(@NonNull final String moduleName) { Parameters.notNull("moduleName", moduleName); //NOI18N this.ops = Collections.singletonList(String.format( - "-Xmodule:%s", //NOI18N + "-XD-Xmodule:%s", //NOI18N moduleName)); } http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/ParsingUtils.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/ParsingUtils.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/ParsingUtils.java new file mode 100644 index 0000000..e478405 --- /dev/null +++ b/java.source.base/src/org/netbeans/modules/java/source/parsing/ParsingUtils.java @@ -0,0 +1,53 @@ +/** + * 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.source.parsing; + +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.util.JavacTask; +import com.sun.tools.javac.api.JavacTaskImpl; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.util.Log; +import java.io.IOException; +import javax.tools.JavaFileObject; + +/** + * + * @author lahvac + */ +public class ParsingUtils { + + public static CompilationUnitTree parseArbitrarySource(JavacTask task, JavaFileObject file) throws IOException { + JavacTaskImpl taskImpl = (JavacTaskImpl) task; + com.sun.tools.javac.util.Context context = taskImpl.getContext(); + Log log = Log.instance(context); + JavaFileObject prevSource = log.useSource(file); + try { + ParserFactory fac = ParserFactory.instance(context); + JCCompilationUnit cut = fac.newParser(file.getCharContent(true), true, true, true).parseCompilationUnit(); + + cut.sourcefile = file; + + return cut; + } finally { + log.useSource(prevSource); + } + } + +} http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/parsing/TranslatePositionsVisitor.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/parsing/TranslatePositionsVisitor.java b/java.source.base/src/org/netbeans/modules/java/source/parsing/TranslatePositionsVisitor.java deleted file mode 100644 index c0119f7..0000000 --- a/java.source.base/src/org/netbeans/modules/java/source/parsing/TranslatePositionsVisitor.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * 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.source.parsing; - -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.tree.MethodTree; -import com.sun.source.tree.Tree; -import com.sun.source.tree.VariableTree; -import com.sun.source.util.TreeScanner; -import com.sun.tools.javac.tree.EndPosTable; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.JCVariableDecl; -import org.netbeans.lib.nbjavac.services.NBParserFactory.NBJavacParser.EndPosTableImpl; - -/** - * Helper visitor for partial reparse. - * Updates tree positions by the given delta. - * @author Tomas Zezula - */ -class TranslatePositionsVisitor extends TreeScanner<Void,Void> { - - private final MethodTree changedMethod; - private final EndPosTable endPos; - private final int delta; - boolean active; - boolean inMethod; - - public TranslatePositionsVisitor (final MethodTree changedMethod, final EndPosTable endPos, final int delta) { - assert changedMethod != null; - assert endPos != null; - this.changedMethod = changedMethod; - this.endPos = endPos; - this.delta = delta; - } - - - @Override - public Void scan(Tree node, Void p) { - if (active && node != null) { - if (((JCTree)node).pos >= 0) { - ((JCTree)node).pos+=delta; - } - } - Void result = super.scan(node, p); - if (inMethod && node != null) { - endPos.replaceTree((JCTree) node, null);//remove - } - if (active && node != null) { - Integer pos = endPos.replaceTree((JCTree) node, null);//remove - if (pos != null) { - int newPos; - if (pos < 0) { - newPos = pos; - } - else { - newPos = pos+delta; - } - ((EndPosTableImpl) endPos).storeEnd((JCTree)node,newPos); - } - } - return result; - } - - @Override - public Void visitCompilationUnit(CompilationUnitTree node, Void p) { - return scan (node.getTypeDecls(), p); - } - - - @Override - public Void visitMethod(MethodTree node, Void p) { - if (active || inMethod) { - scan(node.getModifiers(), p); - scan(node.getReturnType(), p); - scan(node.getTypeParameters(), p); - scan(node.getParameters(), p); - scan(node.getThrows(), p); - } - if (node == changedMethod) { - inMethod = true; - } - if (active || inMethod) { - scan(node.getBody(), p); - } - if (inMethod) { - active = inMethod; - inMethod = false; - } - if (active || inMethod) { - scan(node.getDefaultValue(), p); - } - return null; - } - - @Override - public Void visitVariable(VariableTree node, Void p) { - JCVariableDecl varDecl = (JCVariableDecl) node; - if (varDecl.sym != null && active && varDecl.sym.pos >= 0) { - varDecl.sym.pos += delta; - } - return super.visitVariable(node, p); - } - - -} http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/pretty/ImportAnalysis2.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/pretty/ImportAnalysis2.java b/java.source.base/src/org/netbeans/modules/java/source/pretty/ImportAnalysis2.java index e2b01cf..6335f4a 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/pretty/ImportAnalysis2.java +++ b/java.source.base/src/org/netbeans/modules/java/source/pretty/ImportAnalysis2.java @@ -27,7 +27,7 @@ import com.sun.source.tree.ImportTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; -import com.sun.source.util.TreeScanner; +import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.tools.javac.comp.Modules; import com.sun.tools.javac.model.JavacElements; import com.sun.tools.javac.util.Context; @@ -178,7 +178,7 @@ public class ImportAnalysis2 { private String getFQN(Tree expression) { final StringBuffer result = new StringBuffer(); - new TreeScanner<Void, Void>() { + new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitMemberSelect(MemberSelectTree tree, Void p) { @@ -402,7 +402,7 @@ public class ImportAnalysis2 { usedImplicitlyImportedClassesCache = new HashMap<String, Element>(); - new TreeScanner<Void, Void>() { + new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void p) { Element e = overlay.wrap(model, elements, model.getElement(node)); http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java b/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java index 5b23f72..58367b9 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java +++ b/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java @@ -32,7 +32,7 @@ import static com.sun.source.tree.Tree.*; import com.sun.source.tree.VariableTree; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePath; -import com.sun.source.util.TreeScanner; +import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.source.doctree.AttributeTree; import com.sun.source.doctree.AttributeTree.ValueKind; @@ -496,7 +496,7 @@ public final class VeryPretty extends JCTree.Visitor implements DocTreeVisitor<V final int newStart = out.length() + initialOffset; final int[] realEnd = {endPos(lastTree)}; - new TreeScanner<Void, Void>() { + new ErrorAwareTreeScanner<Void, Void>() { @Override public Void scan(Tree node, Void p) { if (node != null) { @@ -2564,7 +2564,7 @@ public final class VeryPretty extends JCTree.Visitor implements DocTreeVisitor<V return null; } - private final class Linearize extends TreeScanner<Boolean, java.util.List<Tree>> { + private final class Linearize extends ErrorAwareTreeScanner<Boolean, java.util.List<Tree>> { @Override public Boolean scan(Tree node, java.util.List<Tree> p) { p.add(node); @@ -2577,7 +2577,7 @@ public final class VeryPretty extends JCTree.Visitor implements DocTreeVisitor<V } } - private final class CopyTags extends TreeScanner<Void, java.util.List<Tree>> { + private final class CopyTags extends ErrorAwareTreeScanner<Void, java.util.List<Tree>> { private final CompilationUnitTree fake; private final SourcePositions sp; public CopyTags(CompilationUnitTree fake, SourcePositions sp) { @@ -2607,20 +2607,16 @@ public final class VeryPretty extends JCTree.Visitor implements DocTreeVisitor<V return; //nothing to copy } - try { ClassPath empty = ClassPathSupport.createClassPath(new URL[0]); ClasspathInfo cpInfo = ClasspathInfo.create(JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries(), empty, empty); - JavacTaskImpl javacTask = JavacParser.createJavacTask(cpInfo, null, null, null, null, null, null, null, null); + JavacTaskImpl javacTask = JavacParser.createJavacTask(cpInfo, null, null, null, null, null, null, null, Arrays.asList(FileObjects.memoryFileObject("", "Scratch.java", code))); com.sun.tools.javac.util.Context ctx = javacTask.getContext(); JavaCompiler.instance(ctx).genEndPos = true; - CompilationUnitTree tree = javacTask.parse(FileObjects.memoryFileObject("", "", code)).iterator().next(); //NOI18N + CompilationUnitTree tree = javacTask.parse().iterator().next(); //NOI18N SourcePositions sp = JavacTrees.instance(ctx).getSourcePositions(); ClassTree clazz = (ClassTree) tree.getTypeDecls().get(0); new CopyTags(tree, sp).scan(clazz.getModifiers().getAnnotations(), linearized); - } catch (IOException ex) { - Exceptions.printStackTrace(ex); - } } private boolean reallyPrintAnnotations; http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java b/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java index 3fec5af..b1e91bd 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java +++ b/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java @@ -26,7 +26,7 @@ import com.sun.source.tree.Tree.Kind; import com.sun.source.util.DocSourcePositions; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePath; -import com.sun.source.util.TreeScanner; +import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.*; import static com.sun.tools.javac.code.Flags.*; @@ -487,6 +487,16 @@ public class CasualDiff { // TODO: the package name actually ends at the end of the name, so the semicolon could be treated as part // of the diffed list int start = td.oldTopLevel.getPackage() != null ? td.endPos(td.oldTopLevel.getPackage()) : 0; + + //XXX: no-javac-patch: + td.tokenSequence.move(start); + + while (td.tokenSequence.movePrevious()) { + if (td.isNoop(td.tokenSequence.token().id())) { + start = td.tokenSequence.offset(); + } + } + //XXX: no-javac-patch end List<JCImport> originalJC = new LinkedList<JCImport>(); List<JCImport> nueJC = new LinkedList<JCImport>(); @@ -1597,6 +1607,18 @@ public class CasualDiff { } } + private boolean isNoop(JavaTokenId tid) { + switch (tid) { + case LINE_COMMENT: + case BLOCK_COMMENT: + case JAVADOC_COMMENT: + case WHITESPACE: + return true; + default: + return false; + } + } + private int dimension(JCTree t, int afterPos) { if (t.getKind() != Kind.ARRAY_TYPE) { return 0; @@ -5055,7 +5077,7 @@ public class CasualDiff { } private int getPosAfterTreeComments(JCTree t, int end) { - class Scn extends TreeScanner<Void, Void> { + class Scn extends ErrorAwareTreeScanner<Void, Void> { int max = -1; @Override @@ -5675,7 +5697,7 @@ public class CasualDiff { private int getCommentCorrectedEndPos(JCTree tree) { final int[] res = new int[] {endPos(tree)}; - new TreeScanner<Void, Void>() { + new ErrorAwareTreeScanner<Void, Void>() { @Override public Void scan(Tree node, Void p) { if (node != null) { CommentSet ch = comments.getComments(node); http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/save/Reformatter.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/save/Reformatter.java b/java.source.base/src/org/netbeans/modules/java/source/save/Reformatter.java index f91046f..d1b19d2 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/save/Reformatter.java +++ b/java.source.base/src/org/netbeans/modules/java/source/save/Reformatter.java @@ -44,6 +44,7 @@ import org.netbeans.api.java.lexer.JavadocTokenId; import org.netbeans.api.java.platform.JavaPlatformManager; import org.netbeans.api.java.source.*; import org.netbeans.api.java.source.CodeStyle.WrapStyle; +import org.netbeans.api.java.source.support.ErrorAwareTreePathScanner; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenHierarchy; import org.netbeans.api.lexer.TokenSequence; @@ -105,13 +106,12 @@ public class Reformatter implements ReformatTask { public static String reformat(String text, CodeStyle style, int rightMargin) { StringBuilder sb = new StringBuilder(text); - try { ClassPath empty = ClassPathSupport.createClassPath(new URL[0]); ClasspathInfo cpInfo = ClasspathInfo.create(JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries(), empty, empty); - JavacTaskImpl javacTask = JavacParser.createJavacTask(cpInfo, null, null, null, null, null, null, null, null); + JavacTaskImpl javacTask = JavacParser.createJavacTask(cpInfo, null, null, null, null, null, null, null, Arrays.asList(FileObjects.memoryFileObject("","Scratch.java", text))); com.sun.tools.javac.util.Context ctx = javacTask.getContext(); JavaCompiler.instance(ctx).genEndPos = true; - CompilationUnitTree tree = javacTask.parse(FileObjects.memoryFileObject("","", text)).iterator().next(); //NOI18N + CompilationUnitTree tree = javacTask.parse().iterator().next(); //NOI18N SourcePositions sp = JavacTrees.instance(ctx).getSourcePositions(); TokenSequence<JavaTokenId> tokens = TokenHierarchy.create(text, JavaTokenId.language()).tokenSequence(JavaTokenId.language()); for (Diff diff : Pretty.reformat(text, tokens, new TreePath(tree), sp, style, rightMargin)) { @@ -124,8 +124,6 @@ public class Reformatter implements ReformatTask { } } - } catch (IOException ioe) { - } return sb.toString(); } @@ -391,7 +389,7 @@ public class Reformatter implements ReformatTask { } } - private static class Pretty extends TreePathScanner<Boolean, Void> { + private static class Pretty extends ErrorAwareTreePathScanner<Boolean, Void> { private static final String OPERATOR = "operator"; //NOI18N private static final String EMPTY = ""; //NOI18N http://git-wip-us.apache.org/repos/asf/incubator-netbeans/blob/ffc0de5a/java.source.base/src/org/netbeans/modules/java/source/save/Reindenter.java ---------------------------------------------------------------------- diff --git a/java.source.base/src/org/netbeans/modules/java/source/save/Reindenter.java b/java.source.base/src/org/netbeans/modules/java/source/save/Reindenter.java index 91fb6bf..b8bf792 100644 --- a/java.source.base/src/org/netbeans/modules/java/source/save/Reindenter.java +++ b/java.source.base/src/org/netbeans/modules/java/source/save/Reindenter.java @@ -43,7 +43,7 @@ import com.sun.source.tree.TryTree; import com.sun.source.tree.VariableTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.SourcePositions; -import com.sun.source.util.TreeScanner; +import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.api.JavacTrees; @@ -63,6 +63,8 @@ import java.util.Set; import javax.swing.text.BadLocationException; import javax.tools.JavaFileObject; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.util.Log; import org.netbeans.api.java.lexer.JavaTokenId; import org.netbeans.api.java.source.CodeStyle; import org.netbeans.api.lexer.TokenHierarchy; @@ -73,6 +75,8 @@ import org.netbeans.modules.editor.indent.spi.ExtraLock; import org.netbeans.modules.editor.indent.spi.IndentTask; import org.netbeans.modules.java.source.parsing.FileObjects; import org.netbeans.modules.java.source.parsing.JavacParser; +import org.netbeans.modules.java.source.parsing.ParsingUtils; +import org.netbeans.modules.java.source.parsing.PrefetchableJavaFileObject; import org.netbeans.modules.parsing.impl.Utilities; import org.openide.filesystems.FileObject; @@ -218,24 +222,25 @@ public class Reindenter implements IndentTask { text = context.document().getText(currentEmbeddingStartOffset, currentEmbeddingLength); if (JavacParser.MIME_TYPE.equals(context.mimePath())) { FileObject fo = Utilities.getFileObject(context.document()); - cut = javacTask.parse(FileObjects.memoryFileObject("", fo != null ? fo.getNameExt() : "", text)).iterator().next(); //NOI18N + cut = ParsingUtils.parseArbitrarySource(javacTask, FileObjects.memoryFileObject("", fo != null ? fo.getNameExt() : "", text)); parsedTree = cut; sp = JavacTrees.instance(ctx).getSourcePositions(); } else { - final SourcePositions[] psp = new SourcePositions[1]; - cut = null; - parsedTree = javacTask.parseStatement("{" + text + "}", psp); - sp = new SourcePositions() { - @Override - public long getStartPosition(CompilationUnitTree file, Tree tree) { - return currentEmbeddingStartOffset + psp[0].getStartPosition(file, tree) - 1; - } - - @Override - public long getEndPosition(CompilationUnitTree file, Tree tree) { - return currentEmbeddingStartOffset + psp[0].getEndPosition(file, tree) - 1; - } - }; +// final SourcePositions[] psp = new SourcePositions[1]; +// cut = null; +// parsedTree = javacTask.parseStatement("{" + text + "}", psp); +// sp = new SourcePositions() { +// @Override +// public long getStartPosition(CompilationUnitTree file, Tree tree) { +// return currentEmbeddingStartOffset + psp[0].getStartPosition(file, tree) - 1; +// } +// +// @Override +// public long getEndPosition(CompilationUnitTree file, Tree tree) { +// return currentEmbeddingStartOffset + psp[0].getEndPosition(file, tree) - 1; +// } +// }; + throw new UnsupportedOperationException("TODO"); } } catch (Exception ex) { return false; @@ -831,7 +836,7 @@ public class Reindenter implements IndentTask { ts.token().id().primaryCategory().equals("literal")) //NOI18N ? ts.offset() : startOffset; - new TreeScanner<Void, Void>() { + new ErrorAwareTreeScanner<Void, Void>() { @Override public Void scan(Tree node, Void p) {