You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@netbeans.apache.org by jl...@apache.org on 2018/07/03 04:17:45 UTC
[incubator-netbeans] 05/05: [NETBEANS-895] Fixing adding imports
when completing field initializer.
This is an automated email from the ASF dual-hosted git repository.
jlahoda pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-netbeans.git
commit 90c92b2e2b63d498ae220b49ec59316d5a93ac7f
Author: Jan Lahoda <jl...@netbeans.org>
AuthorDate: Sat Jun 30 22:01:19 2018 +0200
[NETBEANS-895] Fixing adding imports when completing field initializer.
---
.../java/completion/JavaCompletionTask.java | 2 +-
.../java/completion/CompletionTestBase.java | 240 +--------------------
.../java/completion/CompletionTestBaseBase.java | 212 +++++++-----------
java.editor/nbproject/project.xml | 6 +
.../1.8/testAnnotation.pass2 | 10 +
.../1.8/testFieldInitializer.pass2 | 10 +
.../java/editor/completion/data/Annotation.java | 8 +
.../java/editor/completion/data/FieldSet.java | 9 +
.../java/editor/completion/CompletionTestBase.java | 234 +-------------------
.../completion/JavaCompletionItemPerformTest.java | 39 ++++
.../org/netbeans/api/java/source/SourceUtils.java | 12 +-
.../netbeans/api/java/source/TreeUtilities.java | 3 +
.../api/java/source/TreeUtilitiesTest.java | 34 +++
13 files changed, 224 insertions(+), 595 deletions(-)
diff --git a/java.completion/src/org/netbeans/modules/java/completion/JavaCompletionTask.java b/java.completion/src/org/netbeans/modules/java/completion/JavaCompletionTask.java
index 24c1223..0805251 100644
--- a/java.completion/src/org/netbeans/modules/java/completion/JavaCompletionTask.java
+++ b/java.completion/src/org/netbeans/modules/java/completion/JavaCompletionTask.java
@@ -1205,7 +1205,7 @@ public final class JavaCompletionTask<T> extends BaseTask {
if (annTypeElement != null && annTypeElement.getKind() == ANNOTATION_TYPE) {
HashSet<String> names = new HashSet<>();
for (ExpressionTree arg : ann.getArguments()) {
- if (arg.getKind() == Tree.Kind.ASSIGNMENT && sourcePositions.getEndPosition(root, arg) < offset) {
+ if (arg.getKind() == Tree.Kind.ASSIGNMENT && sourcePositions.getEndPosition(root, ((AssignmentTree) arg).getExpression()) < offset) {
ExpressionTree var = ((AssignmentTree) arg).getVariable();
if (var.getKind() == Tree.Kind.IDENTIFIER) {
names.add(((IdentifierTree) var).getName().toString());
diff --git a/java.completion/test/unit/src/org/netbeans/modules/java/completion/CompletionTestBase.java b/java.completion/test/unit/src/org/netbeans/modules/java/completion/CompletionTestBase.java
index 47a095f..9ba6021 100644
--- a/java.completion/test/unit/src/org/netbeans/modules/java/completion/CompletionTestBase.java
+++ b/java.completion/test/unit/src/org/netbeans/modules/java/completion/CompletionTestBase.java
@@ -20,18 +20,10 @@
package org.netbeans.modules.java.completion;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
import java.io.Writer;
-import java.net.MalformedURLException;
-import java.net.URL;
import java.util.*;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.prefs.Preferences;
import javax.lang.model.element.*;
import javax.lang.model.type.ArrayType;
@@ -40,184 +32,28 @@ import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
-import javax.swing.JEditorPane;
import javax.swing.text.Document;
-import junit.framework.Assert;
-
-import org.netbeans.api.editor.mimelookup.MimeLookup;
-import org.netbeans.api.java.classpath.ClassPath;
-import org.netbeans.api.java.classpath.JavaClassPathConstants;
import org.netbeans.api.java.lexer.JavaTokenId;
import org.netbeans.api.java.source.*;
import org.netbeans.api.java.source.support.ReferencesCount;
import org.netbeans.api.lexer.Language;
-import org.netbeans.core.startup.Main;
-import org.netbeans.junit.NbTestCase;
-import org.netbeans.modules.java.JavaDataLoader;
-import org.netbeans.modules.java.source.BootClassPathUtil;
-import org.netbeans.modules.java.source.TestUtil;
-import org.netbeans.modules.java.source.indexing.TransactionContext;
-import org.netbeans.modules.java.source.usages.BinaryAnalyser;
-import org.netbeans.modules.java.source.usages.ClassIndexImpl;
-import org.netbeans.modules.java.source.usages.ClassIndexManager;
-import org.netbeans.modules.java.source.usages.IndexUtil;
import org.netbeans.modules.parsing.api.ParserManager;
import org.netbeans.modules.parsing.api.Source;
-import org.netbeans.spi.java.classpath.ClassPathProvider;
-import org.netbeans.spi.java.classpath.support.ClassPathSupport;
-import org.netbeans.spi.java.queries.SourceLevelQueryImplementation;
import org.openide.LifecycleManager;
import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
-import org.openide.util.Lookup;
-import org.openide.util.SharedClassObject;
-import org.openide.util.lookup.Lookups;
-import org.openide.util.lookup.ProxyLookup;
/**
*
* @author Dusan Balek, Jan Lahoda
*/
-public class CompletionTestBase extends NbTestCase {
-
- static {
- JavaCompletionTaskBasicTest.class.getClassLoader().setDefaultAssertionStatus(true);
- SourceUtilsTestUtil2.disableArtificalParameterNames();
- System.setProperty("org.netbeans.modules.java.source.parsing.JavacParser.no_parameter_names", "true");
- }
-
- static final int FINISH_OUTTIME = 5 * 60 * 1000;
-
- public static class Lkp extends ProxyLookup {
-
- private static Lkp DEFAULT;
-
- public Lkp() {
- Assert.assertNull(DEFAULT);
- DEFAULT = this;
- }
-
- public static void initLookups(Object[] objs) throws Exception {
- ClassLoader l = Lkp.class.getClassLoader();
- DEFAULT.setLookups(new Lookup [] {
- Lookups.fixed(objs),
- Lookups.metaInfServices(l),
- Lookups.singleton(l)
- });
- }
- }
+public class CompletionTestBase extends CompletionTestBaseBase {
public CompletionTestBase(String testName) {
- super(testName);
- }
-
- private final AtomicReference<String> sourceLevel = new AtomicReference<>();
-
- @Override
- protected void setUp() throws Exception {
- ClassPathProvider cpp = new ClassPathProvider() {
- volatile ClassPath bootCache;
- volatile ClassPath moduleBootCache;
- @Override
- public ClassPath findClassPath(FileObject file, String type) {
- try {
- if (type.equals(ClassPath.SOURCE)) {
- return ClassPathSupport.createClassPath(new FileObject[]{FileUtil.toFileObject(getWorkDir())});
- }
- if (type.equals(ClassPath.COMPILE)) {
- return ClassPathSupport.createClassPath(new FileObject[0]);
- }
- if (type.equals(ClassPath.BOOT)) {
- ClassPath cp = bootCache;
- if (cp == null) {
- bootCache = cp = BootClassPathUtil.getBootClassPath();
- }
- return cp;
- }
- if (type.equals(JavaClassPathConstants.MODULE_BOOT_PATH)) {
- ClassPath cp = moduleBootCache;
- if (cp == null) {
- moduleBootCache = cp = BootClassPathUtil.getModuleBootPath();
- }
- return cp;
- }
- } catch (IOException ex) {}
- return null;
- }
- };
- SharedClassObject loader = JavaDataLoader.findObject(JavaDataLoader.class, true);
- SourceLevelQueryImplementation slq = new SourceLevelQueryImplementation() {
- @Override public String getSourceLevel(FileObject javaFile) {
- return sourceLevel.get();
- }
- };
- SourceUtilsTestUtil.prepareTest(new String[] {
- "META-INF/generated-layer.xml",
- "org/netbeans/modules/java/editor/resources/layer.xml",
- "org/netbeans/modules/defaults/mf-layer.xml"
- }, new Object[] {loader, cpp, slq});
- File cacheFolder = new File(getWorkDir(), "var/cache/index");
- cacheFolder.mkdirs();
- IndexUtil.setCacheFolder(cacheFolder);
- JEditorPane.registerEditorKitForContentType("text/x-java", "org.netbeans.modules.editor.java.JavaKit");
- final ClassPath sourcePath = ClassPathSupport.createClassPath(new FileObject[] {FileUtil.toFileObject(getDataDir())});
- final ClassIndexManager mgr = ClassIndexManager.getDefault();
- for (ClassPath.Entry entry : sourcePath.entries()) {
- TransactionContext tx = TransactionContext.beginStandardTransaction(entry.getURL(), true, ()->true, false);
- try {
- mgr.createUsagesQuery(entry.getURL(), true);
- } finally {
- tx.commit();
- }
- }
- final ClassPath bootPath = cpp.findClassPath(FileUtil.toFileObject(getWorkDir()), ClassPath.BOOT);
- final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, ClassPathSupport.createClassPath(new URL[0]), sourcePath);
- assertNotNull(cpInfo);
- final JavaSource js = JavaSource.create(cpInfo);
- assertNotNull(js);
- js.runUserActionTask(new Task<CompilationController>() {
- @Override
- public void run(CompilationController parameter) throws Exception {
- for (ClassPath.Entry entry : bootPath.entries()) {
- final URL url = entry.getURL();
- TransactionContext.beginStandardTransaction(entry.getURL(), false, ()->true, false);
- try {
- final ClassIndexImpl cii = mgr.createUsagesQuery(url, false);
- BinaryAnalyser ba = cii.getBinaryAnalyser();
- ba.analyse(url);
- } finally {
- TransactionContext.get().commit();
- }
- }
- }
- }, true);
- Main.initializeURLFactory();
- Preferences preferences = MimeLookup.getLookup(JavaTokenId.language().mimeType()).lookup(Preferences.class);
- preferences.putBoolean("completion-case-sensitive", true);
- }
-
- private URL[] prepareLayers(String... paths) throws IOException {
- List<URL> layers = new LinkedList<>();
-
- for (int cntr = 0; cntr < paths.length; cntr++) {
- boolean found = false;
-
- for (Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(paths[cntr]); en.hasMoreElements(); ) {
- found = true;
- layers.add(en.nextElement());
- }
-
- Assert.assertTrue(paths[cntr], found);
- }
-
- return layers.toArray(new URL[0]);
- }
-
- @Override
- protected void tearDown() throws Exception {
+ super(testName, "org/netbeans/modules/java/completion/JavaCompletionTaskTest");
}
protected void performTest(String source, int caretPos, String textToInsert, String goldenFileName) throws Exception {
@@ -264,83 +100,13 @@ public class CompletionTestBase extends NbTestCase {
}
- File goldenFile = null;
- String version = System.getProperty("java.specification.version");
- for (String variant : computeVersionVariantsFor(version)) {
- goldenFile = new File(getDataDir(), "/goldenfiles/org/netbeans/modules/java/completion/JavaCompletionTaskTest/" + variant + "/" + goldenFileName);
- if (goldenFile.exists())
- break;
- }
- assertNotNull(goldenFile);
+ File goldenFile = getGoldenFile(goldenFileName);
File diffFile = new File(getWorkDir(), getName() + ".diff");
assertFile(output, goldenFile, diffFile);
LifecycleManager.getDefault().saveAll();
}
- private List<String> computeVersionVariantsFor(String version) {
- int dot = version.indexOf('.');
- version = version.substring(dot + 1);
- int versionNum = Integer.parseInt(version);
- List<String> versions = new ArrayList<>();
-
- for (int v = versionNum; v >= 8; v--) {
- versions.add(v != 8 ? "" + v : "1." + v);
- }
-
- return versions;
- }
-
- private void copyToWorkDir(File resource, File toFile) throws IOException {
- InputStream is = new FileInputStream(resource);
- OutputStream outs = new FileOutputStream(toFile);
- int read;
- while ((read = is.read()) != (-1)) {
- outs.write(read);
- }
- outs.close();
- is.close();
- }
-
- private static ClassPath createClassPath(String classpath) {
- StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
- List list = new ArrayList();
- while (tokenizer.hasMoreTokens()) {
- String item = tokenizer.nextToken();
- File f = FileUtil.normalizeFile(new File(item));
- URL url = getRootURL(f);
- if (url!=null) {
- list.add(ClassPathSupport.createResource(url));
- }
- }
- return ClassPathSupport.createClassPath(list);
- }
-
- // XXX this method could probably be removed... use standard FileUtil stuff
- private static URL getRootURL (File f) {
- URL url = null;
- try {
- if (isArchiveFile(f)) {
- url = FileUtil.getArchiveRoot(f.toURI().toURL());
- } else {
- url = f.toURI().toURL();
- String surl = url.toExternalForm();
- if (!surl.endsWith("/")) {
- url = new URL(surl+"/");
- }
- }
- } catch (MalformedURLException e) {
- throw new AssertionError(e);
- }
- return url;
- }
-
- private static boolean isArchiveFile(File f) {
- // the f might not exist and so you cannot use e.g. f.isFile() here
- String fileName = f.getName().toLowerCase();
- return fileName.endsWith(".jar") || fileName.endsWith(".zip"); //NOI18N
- }
-
private static class CIFactory implements JavaCompletionTask.ModuleItemFactory<CI> {
private static final int SMART_TYPE = 1000;
diff --git a/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/CompletionTestBase.java b/java.completion/test/unit/src/org/netbeans/modules/java/completion/CompletionTestBaseBase.java
similarity index 56%
copy from java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/CompletionTestBase.java
copy to java.completion/test/unit/src/org/netbeans/modules/java/completion/CompletionTestBaseBase.java
index 2f788d7..3e71573 100644
--- a/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/CompletionTestBase.java
+++ b/java.completion/test/unit/src/org/netbeans/modules/java/completion/CompletionTestBaseBase.java
@@ -17,73 +17,43 @@
* under the License.
*/
-package org.netbeans.modules.java.editor.completion;
+package org.netbeans.modules.java.completion;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.StringTokenizer;
+import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.prefs.Preferences;
-import java.util.regex.Pattern;
import javax.swing.JEditorPane;
-import javax.swing.text.Document;
import junit.framework.Assert;
import org.netbeans.api.editor.mimelookup.MimeLookup;
-import org.netbeans.api.editor.mimelookup.MimePath;
import org.netbeans.api.java.classpath.ClassPath;
+import org.netbeans.api.java.classpath.JavaClassPathConstants;
import org.netbeans.api.java.lexer.JavaTokenId;
-import org.netbeans.api.java.source.ClasspathInfo;
-import org.netbeans.api.java.source.CompilationController;
-import org.netbeans.api.java.source.JavaSource;
-import org.netbeans.api.java.source.SourceUtilsTestUtil2;
-import org.netbeans.api.java.source.Task;
-import org.netbeans.api.java.source.gen.WhitespaceIgnoringDiff;
-import org.netbeans.api.lexer.Language;
+import org.netbeans.api.java.source.*;
import org.netbeans.core.startup.Main;
import org.netbeans.junit.NbTestCase;
-import org.netbeans.modules.editor.completion.CompletionItemComparator;
-import org.netbeans.modules.editor.java.JavaCompletionProvider;
-import org.netbeans.modules.editor.java.JavaKit;
import org.netbeans.modules.java.JavaDataLoader;
+import org.netbeans.modules.java.source.BootClassPathUtil;
import org.netbeans.modules.java.source.indexing.TransactionContext;
-import org.netbeans.modules.java.source.parsing.JavacParserFactory;
import org.netbeans.modules.java.source.usages.BinaryAnalyser;
import org.netbeans.modules.java.source.usages.ClassIndexImpl;
import org.netbeans.modules.java.source.usages.ClassIndexManager;
import org.netbeans.modules.java.source.usages.IndexUtil;
-import org.netbeans.modules.parsing.api.Source;
-import org.netbeans.spi.editor.completion.CompletionItem;
-import org.netbeans.spi.editor.completion.CompletionProvider;
-import org.netbeans.spi.editor.mimelookup.MimeDataProvider;
import org.netbeans.spi.java.classpath.ClassPathProvider;
import org.netbeans.spi.java.classpath.support.ClassPathSupport;
import org.netbeans.spi.java.queries.SourceLevelQueryImplementation;
-import org.openide.LifecycleManager;
-
-import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
-import org.openide.filesystems.FileSystem;
import org.openide.filesystems.FileUtil;
-import org.openide.filesystems.MultiFileSystem;
-import org.openide.filesystems.Repository;
-import org.openide.filesystems.XMLFileSystem;
-import org.openide.loaders.DataObject;
import org.openide.util.Lookup;
import org.openide.util.SharedClassObject;
import org.openide.util.lookup.Lookups;
@@ -93,27 +63,25 @@ import org.openide.util.lookup.ProxyLookup;
*
* @author Dusan Balek, Jan Lahoda
*/
-public class CompletionTestBase extends NbTestCase {
-
- static {
- JavaCompletionItemElementCreatingTest.class.getClassLoader().setDefaultAssertionStatus(true);
- System.setProperty("org.openide.util.Lookup", Lkp.class.getName());
- Assert.assertEquals(Lkp.class, Lookup.getDefault().getClass());
+public class CompletionTestBaseBase extends NbTestCase {
+ static {
+ JavaCompletionTaskBasicTest.class.getClassLoader().setDefaultAssertionStatus(true);
SourceUtilsTestUtil2.disableArtificalParameterNames();
+ System.setProperty("org.netbeans.modules.java.source.parsing.JavacParser.no_parameter_names", "true");
}
static final int FINISH_OUTTIME = 5 * 60 * 1000;
-
+
public static class Lkp extends ProxyLookup {
-
+
private static Lkp DEFAULT;
-
+
public Lkp() {
Assert.assertNull(DEFAULT);
DEFAULT = this;
}
-
+
public static void initLookups(Object[] objs) throws Exception {
ClassLoader l = Lkp.class.getClassLoader();
DEFAULT.setLookups(new Lookup [] {
@@ -123,50 +91,59 @@ public class CompletionTestBase extends NbTestCase {
});
}
}
-
- public CompletionTestBase(String testName) {
+
+ protected final AtomicReference<String> sourceLevel = new AtomicReference<>();
+ private final String goldenFilePath;
+
+ public CompletionTestBaseBase(String testName, String goldenFilePath) {
super(testName);
+ this.goldenFilePath = goldenFilePath;
}
-
- private final AtomicReference<String> sourceLevel = new AtomicReference<String>();
-
+
+
+ @Override
protected void setUp() throws Exception {
-// this call did not do anything
-// GlobalSourcePathTestUtil.setUseLibraries (false);
- XMLFileSystem system = new XMLFileSystem();
- system.setXmlUrls(prepareLayers("META-INF/generated-layer.xml",
- "org/netbeans/modules/java/editor/resources/layer.xml",
- "org/netbeans/modules/defaults/mf-layer.xml"));
- Repository repository = new Repository(new MultiFileSystem(new FileSystem[] {FileUtil.createMemoryFileSystem(), system}));
- final ClassPath bootPath = createClassPath(System.getProperty("sun.boot.class.path"));
ClassPathProvider cpp = new ClassPathProvider() {
+ volatile ClassPath bootCache;
+ volatile ClassPath moduleBootCache;
+ @Override
public ClassPath findClassPath(FileObject file, String type) {
try {
- if (type == ClassPath.SOURCE) {
+ if (type.equals(ClassPath.SOURCE)) {
return ClassPathSupport.createClassPath(new FileObject[]{FileUtil.toFileObject(getWorkDir())});
}
- if (type == ClassPath.COMPILE) {
+ if (type.equals(ClassPath.COMPILE)) {
return ClassPathSupport.createClassPath(new FileObject[0]);
}
- if (type == ClassPath.BOOT) {
- return bootPath;
+ if (type.equals(ClassPath.BOOT)) {
+ ClassPath cp = bootCache;
+ if (cp == null) {
+ bootCache = cp = BootClassPathUtil.getBootClassPath();
+ }
+ return cp;
+ }
+ if (type.equals(JavaClassPathConstants.MODULE_BOOT_PATH)) {
+ ClassPath cp = moduleBootCache;
+ if (cp == null) {
+ moduleBootCache = cp = BootClassPathUtil.getModuleBootPath();
+ }
+ return cp;
}
} catch (IOException ex) {}
return null;
}
};
SharedClassObject loader = JavaDataLoader.findObject(JavaDataLoader.class, true);
- MimeDataProvider mdp = new MimeDataProvider() {
- public Lookup getLookup(MimePath mimePath) {
- return Lookups.fixed(new JavaKit(), new JavacParserFactory());
- }
- };
SourceLevelQueryImplementation slq = new SourceLevelQueryImplementation() {
@Override public String getSourceLevel(FileObject javaFile) {
return sourceLevel.get();
}
};
- Lkp.initLookups(new Object[] {repository, loader, cpp, mdp, slq});
+ SourceUtilsTestUtil.prepareTest(new String[] {
+ "META-INF/generated-layer.xml",
+ "org/netbeans/modules/java/editor/resources/layer.xml",
+ "org/netbeans/modules/defaults/mf-layer.xml"
+ }, new Object[] {loader, cpp, slq});
File cacheFolder = new File(getWorkDir(), "var/cache/index");
cacheFolder.mkdirs();
IndexUtil.setCacheFolder(cacheFolder);
@@ -181,11 +158,13 @@ public class CompletionTestBase extends NbTestCase {
tx.commit();
}
}
+ final ClassPath bootPath = cpp.findClassPath(FileUtil.toFileObject(getWorkDir()), ClassPath.BOOT);
final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, ClassPathSupport.createClassPath(new URL[0]), sourcePath);
assertNotNull(cpInfo);
final JavaSource js = JavaSource.create(cpInfo);
assertNotNull(js);
js.runUserActionTask(new Task<CompilationController>() {
+ @Override
public void run(CompilationController parameter) throws Exception {
for (ClassPath.Entry entry : bootPath.entries()) {
final URL url = entry.getURL();
@@ -204,10 +183,10 @@ public class CompletionTestBase extends NbTestCase {
Preferences preferences = MimeLookup.getLookup(JavaTokenId.language().mimeType()).lookup(Preferences.class);
preferences.putBoolean("completion-case-sensitive", true);
}
-
+
private URL[] prepareLayers(String... paths) throws IOException {
- List<URL> layers = new LinkedList<URL>();
-
+ List<URL> layers = new LinkedList<>();
+
for (int cntr = 0; cntr < paths.length; cntr++) {
boolean found = false;
@@ -218,72 +197,40 @@ public class CompletionTestBase extends NbTestCase {
Assert.assertTrue(paths[cntr], found);
}
-
+
return layers.toArray(new URL[0]);
}
-
+
+ @Override
protected void tearDown() throws Exception {
}
-
- protected void performTest(String source, int caretPos, String textToInsert, String toPerformItemRE, String goldenFileName) throws Exception {
- performTest(source, caretPos, textToInsert, toPerformItemRE, goldenFileName, null);
- }
-
- protected void performTest(String source, int caretPos, String textToInsert, String toPerformItemRE, String goldenFileName, String sourceLevel) throws Exception {
- this.sourceLevel.set(sourceLevel);
- File testSource = new File(getWorkDir(), "test/Test.java");
- testSource.getParentFile().mkdirs();
- copyToWorkDir(new File(getDataDir(), "org/netbeans/modules/java/editor/completion/data/" + source + ".java"), testSource);
- FileObject testSourceFO = FileUtil.toFileObject(testSource);
- assertNotNull(testSourceFO);
- DataObject testSourceDO = DataObject.find(testSourceFO);
- assertNotNull(testSourceDO);
- EditorCookie ec = (EditorCookie) testSourceDO.getCookie(EditorCookie.class);
- assertNotNull(ec);
- final Document doc = ec.openDocument();
- assertNotNull(doc);
- doc.putProperty(Language.class, JavaTokenId.language());
- doc.putProperty("mimeType", "text/x-java");
- int textToInsertLength = textToInsert != null ? textToInsert.length() : 0;
- if (textToInsertLength > 0)
- doc.insertString(caretPos, textToInsert, null);
- Source s = Source.create(doc);
- List<? extends CompletionItem> items = JavaCompletionProvider.query(s, CompletionProvider.COMPLETION_QUERY_TYPE, caretPos + textToInsertLength, caretPos + textToInsertLength);
- Collections.sort(items, CompletionItemComparator.BY_PRIORITY);
-
- String version = System.getProperty("java.specification.version") + "/";
-
- assertNotNull(goldenFileName);
- Pattern p = Pattern.compile(toPerformItemRE);
- CompletionItem item = null;
- for (CompletionItem i : items) {
- if (p.matcher(i.toString()).find()) {
- item = i;
+ public File getGoldenFile(String goldenFileName) {
+ File goldenFile = null;
+ String version = System.getProperty("java.specification.version");
+ for (String variant : computeVersionVariantsFor(version)) {
+ goldenFile = new File(getDataDir(), "/goldenfiles/" + goldenFilePath + "/" + variant + "/" + goldenFileName);
+ if (goldenFile.exists())
break;
- }
- }
- assertNotNull(item);
-
- JEditorPane editor = new JEditorPane();
- editor.setDocument(doc);
- editor.setCaretPosition(caretPos + textToInsertLength);
- item.defaultAction(editor);
+ }
+ assertNotNull(goldenFile);
+ return goldenFile;
+ }
- File output = new File(getWorkDir(), getName() + ".out2");
- Writer out = new FileWriter(output);
- out.write(doc.getText(0, doc.getLength()));
- out.close();
+ private List<String> computeVersionVariantsFor(String version) {
+ int dot = version.indexOf('.');
+ version = version.substring(dot + 1);
+ int versionNum = Integer.parseInt(version);
+ List<String> versions = new ArrayList<>();
- File goldenFile = new File(getDataDir(), "/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/" + version + goldenFileName);
- File diffFile = new File(getWorkDir(), getName() + ".diff");
+ for (int v = versionNum; v >= 8; v--) {
+ versions.add(v != 8 ? "" + v : "1." + v);
+ }
- assertFile(output, goldenFile, diffFile, new WhitespaceIgnoringDiff());
-
- LifecycleManager.getDefault().saveAll();
+ return versions;
}
- private void copyToWorkDir(File resource, File toFile) throws IOException {
+ protected void copyToWorkDir(File resource, File toFile) throws IOException {
InputStream is = new FileInputStream(resource);
OutputStream outs = new FileOutputStream(toFile);
int read;
@@ -293,10 +240,10 @@ public class CompletionTestBase extends NbTestCase {
outs.close();
is.close();
}
-
- private static ClassPath createClassPath(String classpath) {
+
+ protected static ClassPath createClassPath(String classpath) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
- List/*<PathResourceImplementation>*/ list = new ArrayList();
+ List list = new ArrayList();
while (tokenizer.hasMoreTokens()) {
String item = tokenizer.nextToken();
File f = FileUtil.normalizeFile(new File(item));
@@ -307,7 +254,7 @@ public class CompletionTestBase extends NbTestCase {
}
return ClassPathSupport.createClassPath(list);
}
-
+
// XXX this method could probably be removed... use standard FileUtil stuff
private static URL getRootURL (File f) {
URL url = null;
@@ -326,10 +273,11 @@ public class CompletionTestBase extends NbTestCase {
}
return url;
}
-
+
private static boolean isArchiveFile(File f) {
// the f might not exist and so you cannot use e.g. f.isFile() here
String fileName = f.getName().toLowerCase();
return fileName.endsWith(".jar") || fileName.endsWith(".zip"); //NOI18N
- }
+ }
+
}
diff --git a/java.editor/nbproject/project.xml b/java.editor/nbproject/project.xml
index 98e7858..427bf0d 100644
--- a/java.editor/nbproject/project.xml
+++ b/java.editor/nbproject/project.xml
@@ -525,6 +525,11 @@
<test/>
</test-dependency>
<test-dependency>
+ <code-name-base>org.netbeans.modules.java.completion</code-name-base>
+ <compile-dependency/>
+ <test/>
+ </test-dependency>
+ <test-dependency>
<code-name-base>org.netbeans.modules.java.editor</code-name-base>
<recursive/>
<compile-dependency/>
@@ -536,6 +541,7 @@
</test-dependency>
<test-dependency>
<code-name-base>org.netbeans.modules.java.j2seplatform</code-name-base>
+ <recursive/>
<compile-dependency/>
</test-dependency>
<test-dependency>
diff --git a/java.editor/test/unit/data/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/1.8/testAnnotation.pass2 b/java.editor/test/unit/data/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/1.8/testAnnotation.pass2
new file mode 100644
index 0000000..0d63d9d
--- /dev/null
+++ b/java.editor/test/unit/data/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/1.8/testAnnotation.pass2
@@ -0,0 +1,10 @@
+package test;
+
+import java.util.Set;
+
+@Annotation(Set.class)
+public @interface Annotation {
+
+ public Class<java.util.Set> value();
+
+}
diff --git a/java.editor/test/unit/data/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/1.8/testFieldInitializer.pass2 b/java.editor/test/unit/data/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/1.8/testFieldInitializer.pass2
new file mode 100644
index 0000000..8ad5577
--- /dev/null
+++ b/java.editor/test/unit/data/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/1.8/testFieldInitializer.pass2
@@ -0,0 +1,10 @@
+package test;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class FieldSet {
+
+ public Set<String> field = new HashSet<String>;
+
+}
diff --git a/java.editor/test/unit/data/org/netbeans/modules/java/editor/completion/data/Annotation.java b/java.editor/test/unit/data/org/netbeans/modules/java/editor/completion/data/Annotation.java
new file mode 100644
index 0000000..afd0330
--- /dev/null
+++ b/java.editor/test/unit/data/org/netbeans/modules/java/editor/completion/data/Annotation.java
@@ -0,0 +1,8 @@
+package test;
+
+@Annotation()
+public @interface Annotation {
+
+ public Class<java.util.Set> value();
+
+}
diff --git a/java.editor/test/unit/data/org/netbeans/modules/java/editor/completion/data/FieldSet.java b/java.editor/test/unit/data/org/netbeans/modules/java/editor/completion/data/FieldSet.java
new file mode 100644
index 0000000..559abf2
--- /dev/null
+++ b/java.editor/test/unit/data/org/netbeans/modules/java/editor/completion/data/FieldSet.java
@@ -0,0 +1,9 @@
+package test;
+
+import java.util.Set;
+
+public class FieldSet {
+
+ public Set<String> field;
+
+}
diff --git a/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/CompletionTestBase.java b/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/CompletionTestBase.java
index 2f788d7..1505d18 100644
--- a/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/CompletionTestBase.java
+++ b/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/CompletionTestBase.java
@@ -20,209 +20,41 @@
package org.netbeans.modules.java.editor.completion;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
import java.io.Writer;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
import java.util.Collections;
-import java.util.Enumeration;
-import java.util.LinkedList;
import java.util.List;
-import java.util.StringTokenizer;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import javax.swing.JEditorPane;
+import javax.swing.SwingUtilities;
import javax.swing.text.Document;
-import junit.framework.Assert;
-
-import org.netbeans.api.editor.mimelookup.MimeLookup;
-import org.netbeans.api.editor.mimelookup.MimePath;
-import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.lexer.JavaTokenId;
-import org.netbeans.api.java.source.ClasspathInfo;
-import org.netbeans.api.java.source.CompilationController;
-import org.netbeans.api.java.source.JavaSource;
-import org.netbeans.api.java.source.SourceUtilsTestUtil2;
-import org.netbeans.api.java.source.Task;
import org.netbeans.api.java.source.gen.WhitespaceIgnoringDiff;
import org.netbeans.api.lexer.Language;
-import org.netbeans.core.startup.Main;
-import org.netbeans.junit.NbTestCase;
import org.netbeans.modules.editor.completion.CompletionItemComparator;
import org.netbeans.modules.editor.java.JavaCompletionProvider;
import org.netbeans.modules.editor.java.JavaKit;
-import org.netbeans.modules.java.JavaDataLoader;
-import org.netbeans.modules.java.source.indexing.TransactionContext;
-import org.netbeans.modules.java.source.parsing.JavacParserFactory;
-import org.netbeans.modules.java.source.usages.BinaryAnalyser;
-import org.netbeans.modules.java.source.usages.ClassIndexImpl;
-import org.netbeans.modules.java.source.usages.ClassIndexManager;
-import org.netbeans.modules.java.source.usages.IndexUtil;
+import org.netbeans.modules.java.completion.CompletionTestBaseBase;
import org.netbeans.modules.parsing.api.Source;
import org.netbeans.spi.editor.completion.CompletionItem;
import org.netbeans.spi.editor.completion.CompletionProvider;
-import org.netbeans.spi.editor.mimelookup.MimeDataProvider;
-import org.netbeans.spi.java.classpath.ClassPathProvider;
-import org.netbeans.spi.java.classpath.support.ClassPathSupport;
-import org.netbeans.spi.java.queries.SourceLevelQueryImplementation;
import org.openide.LifecycleManager;
import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
-import org.openide.filesystems.FileSystem;
import org.openide.filesystems.FileUtil;
-import org.openide.filesystems.MultiFileSystem;
-import org.openide.filesystems.Repository;
-import org.openide.filesystems.XMLFileSystem;
import org.openide.loaders.DataObject;
-import org.openide.util.Lookup;
-import org.openide.util.SharedClassObject;
-import org.openide.util.lookup.Lookups;
-import org.openide.util.lookup.ProxyLookup;
/**
*
* @author Dusan Balek, Jan Lahoda
*/
-public class CompletionTestBase extends NbTestCase {
-
- static {
- JavaCompletionItemElementCreatingTest.class.getClassLoader().setDefaultAssertionStatus(true);
- System.setProperty("org.openide.util.Lookup", Lkp.class.getName());
- Assert.assertEquals(Lkp.class, Lookup.getDefault().getClass());
-
- SourceUtilsTestUtil2.disableArtificalParameterNames();
- }
-
- static final int FINISH_OUTTIME = 5 * 60 * 1000;
-
- public static class Lkp extends ProxyLookup {
-
- private static Lkp DEFAULT;
-
- public Lkp() {
- Assert.assertNull(DEFAULT);
- DEFAULT = this;
- }
-
- public static void initLookups(Object[] objs) throws Exception {
- ClassLoader l = Lkp.class.getClassLoader();
- DEFAULT.setLookups(new Lookup [] {
- Lookups.fixed(objs),
- Lookups.metaInfServices(l),
- Lookups.singleton(l)
- });
- }
- }
+public class CompletionTestBase extends CompletionTestBaseBase {
public CompletionTestBase(String testName) {
- super(testName);
- }
-
- private final AtomicReference<String> sourceLevel = new AtomicReference<String>();
-
- protected void setUp() throws Exception {
-// this call did not do anything
-// GlobalSourcePathTestUtil.setUseLibraries (false);
- XMLFileSystem system = new XMLFileSystem();
- system.setXmlUrls(prepareLayers("META-INF/generated-layer.xml",
- "org/netbeans/modules/java/editor/resources/layer.xml",
- "org/netbeans/modules/defaults/mf-layer.xml"));
- Repository repository = new Repository(new MultiFileSystem(new FileSystem[] {FileUtil.createMemoryFileSystem(), system}));
- final ClassPath bootPath = createClassPath(System.getProperty("sun.boot.class.path"));
- ClassPathProvider cpp = new ClassPathProvider() {
- public ClassPath findClassPath(FileObject file, String type) {
- try {
- if (type == ClassPath.SOURCE) {
- return ClassPathSupport.createClassPath(new FileObject[]{FileUtil.toFileObject(getWorkDir())});
- }
- if (type == ClassPath.COMPILE) {
- return ClassPathSupport.createClassPath(new FileObject[0]);
- }
- if (type == ClassPath.BOOT) {
- return bootPath;
- }
- } catch (IOException ex) {}
- return null;
- }
- };
- SharedClassObject loader = JavaDataLoader.findObject(JavaDataLoader.class, true);
- MimeDataProvider mdp = new MimeDataProvider() {
- public Lookup getLookup(MimePath mimePath) {
- return Lookups.fixed(new JavaKit(), new JavacParserFactory());
- }
- };
- SourceLevelQueryImplementation slq = new SourceLevelQueryImplementation() {
- @Override public String getSourceLevel(FileObject javaFile) {
- return sourceLevel.get();
- }
- };
- Lkp.initLookups(new Object[] {repository, loader, cpp, mdp, slq});
- File cacheFolder = new File(getWorkDir(), "var/cache/index");
- cacheFolder.mkdirs();
- IndexUtil.setCacheFolder(cacheFolder);
- JEditorPane.registerEditorKitForContentType("text/x-java", "org.netbeans.modules.editor.java.JavaKit");
- final ClassPath sourcePath = ClassPathSupport.createClassPath(new FileObject[] {FileUtil.toFileObject(getDataDir())});
- final ClassIndexManager mgr = ClassIndexManager.getDefault();
- for (ClassPath.Entry entry : sourcePath.entries()) {
- TransactionContext tx = TransactionContext.beginStandardTransaction(entry.getURL(), true, ()->true, false);
- try {
- mgr.createUsagesQuery(entry.getURL(), true);
- } finally {
- tx.commit();
- }
- }
- final ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, ClassPathSupport.createClassPath(new URL[0]), sourcePath);
- assertNotNull(cpInfo);
- final JavaSource js = JavaSource.create(cpInfo);
- assertNotNull(js);
- js.runUserActionTask(new Task<CompilationController>() {
- public void run(CompilationController parameter) throws Exception {
- for (ClassPath.Entry entry : bootPath.entries()) {
- final URL url = entry.getURL();
- TransactionContext.beginStandardTransaction(entry.getURL(), false, ()->true, false);
- try {
- final ClassIndexImpl cii = mgr.createUsagesQuery(url, false);
- BinaryAnalyser ba = cii.getBinaryAnalyser();
- ba.analyse(url);
- } finally {
- TransactionContext.get().commit();
- }
- }
- }
- }, true);
- Main.initializeURLFactory();
- Preferences preferences = MimeLookup.getLookup(JavaTokenId.language().mimeType()).lookup(Preferences.class);
- preferences.putBoolean("completion-case-sensitive", true);
- }
-
- private URL[] prepareLayers(String... paths) throws IOException {
- List<URL> layers = new LinkedList<URL>();
-
- for (int cntr = 0; cntr < paths.length; cntr++) {
- boolean found = false;
-
- for (Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(paths[cntr]); en.hasMoreElements(); ) {
- found = true;
- layers.add(en.nextElement());
- }
-
- Assert.assertTrue(paths[cntr], found);
- }
-
- return layers.toArray(new URL[0]);
- }
-
- protected void tearDown() throws Exception {
+ super(testName, "org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest");
}
protected void performTest(String source, int caretPos, String textToInsert, String toPerformItemRE, String goldenFileName) throws Exception {
@@ -251,8 +83,6 @@ public class CompletionTestBase extends NbTestCase {
List<? extends CompletionItem> items = JavaCompletionProvider.query(s, CompletionProvider.COMPLETION_QUERY_TYPE, caretPos + textToInsertLength, caretPos + textToInsertLength);
Collections.sort(items, CompletionItemComparator.BY_PRIORITY);
- String version = System.getProperty("java.specification.version") + "/";
-
assertNotNull(goldenFileName);
Pattern p = Pattern.compile(toPerformItemRE);
@@ -266,16 +96,21 @@ public class CompletionTestBase extends NbTestCase {
assertNotNull(item);
JEditorPane editor = new JEditorPane();
+ SwingUtilities.invokeAndWait(() -> {
+ editor.setEditorKit(new JavaKit());
+ });
editor.setDocument(doc);
editor.setCaretPosition(caretPos + textToInsertLength);
item.defaultAction(editor);
+ SwingUtilities.invokeAndWait(() -> {});
+
File output = new File(getWorkDir(), getName() + ".out2");
Writer out = new FileWriter(output);
out.write(doc.getText(0, doc.getLength()));
out.close();
- File goldenFile = new File(getDataDir(), "/goldenfiles/org/netbeans/modules/java/editor/completion/JavaCompletionProviderTest/" + version + goldenFileName);
+ File goldenFile = getGoldenFile(goldenFileName);
File diffFile = new File(getWorkDir(), getName() + ".diff");
assertFile(output, goldenFile, diffFile, new WhitespaceIgnoringDiff());
@@ -283,53 +118,4 @@ public class CompletionTestBase extends NbTestCase {
LifecycleManager.getDefault().saveAll();
}
- private void copyToWorkDir(File resource, File toFile) throws IOException {
- InputStream is = new FileInputStream(resource);
- OutputStream outs = new FileOutputStream(toFile);
- int read;
- while ((read = is.read()) != (-1)) {
- outs.write(read);
- }
- outs.close();
- is.close();
- }
-
- private static ClassPath createClassPath(String classpath) {
- StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
- List/*<PathResourceImplementation>*/ list = new ArrayList();
- while (tokenizer.hasMoreTokens()) {
- String item = tokenizer.nextToken();
- File f = FileUtil.normalizeFile(new File(item));
- URL url = getRootURL(f);
- if (url!=null) {
- list.add(ClassPathSupport.createResource(url));
- }
- }
- return ClassPathSupport.createClassPath(list);
- }
-
- // XXX this method could probably be removed... use standard FileUtil stuff
- private static URL getRootURL (File f) {
- URL url = null;
- try {
- if (isArchiveFile(f)) {
- url = FileUtil.getArchiveRoot(f.toURI().toURL());
- } else {
- url = f.toURI().toURL();
- String surl = url.toExternalForm();
- if (!surl.endsWith("/")) {
- url = new URL(surl+"/");
- }
- }
- } catch (MalformedURLException e) {
- throw new AssertionError(e);
- }
- return url;
- }
-
- private static boolean isArchiveFile(File f) {
- // the f might not exist and so you cannot use e.g. f.isFile() here
- String fileName = f.getName().toLowerCase();
- return fileName.endsWith(".jar") || fileName.endsWith(".zip"); //NOI18N
- }
}
diff --git a/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/JavaCompletionItemPerformTest.java b/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/JavaCompletionItemPerformTest.java
new file mode 100644
index 0000000..778d4b0
--- /dev/null
+++ b/java.editor/test/unit/src/org/netbeans/modules/java/editor/completion/JavaCompletionItemPerformTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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.editor.completion;
+
+/**
+ *
+ * @author Jan Lahoda, Dusan Balek
+ */
+public class JavaCompletionItemPerformTest extends CompletionTestBase {
+
+ public JavaCompletionItemPerformTest(String testName) {
+ super(testName);
+ }
+
+ public void testFieldInitializer() throws Exception {
+ performTest("FieldSet", 91, " = new HashS", "HashSet", "testFieldInitializer.pass2");
+ }
+
+ public void testAnnotation() throws Exception {
+ performTest("Annotation", 27, "Se", "Set", "testAnnotation.pass2");
+ }
+}
\ No newline at end of file
diff --git a/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java b/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java
index 9ff0e2c..2e82805 100644
--- a/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java
+++ b/java.source.base/src/org/netbeans/api/java/source/SourceUtils.java
@@ -424,7 +424,17 @@ public class SourceUtils {
importScope.prependSubScope(((PackageSymbol)toImport).members());
unit.starImportScope = importScope;
} else {
- NamedImportScope importScope = new NamedImportScope(unit.packge, unit.toplevelScope);
+ Class<NamedImportScope> nisClazz = NamedImportScope.class;
+ NamedImportScope importScope;
+ try {
+ importScope = nisClazz.getConstructor(Symbol.class, com.sun.tools.javac.code.Scope.class).newInstance(unit.packge, unit.toplevelScope);
+ } catch (ReflectiveOperationException ex) {
+ try {
+ importScope = nisClazz.getConstructor(Symbol.class).newInstance(unit.packge);
+ } catch (ReflectiveOperationException ex2) {
+ throw new IllegalStateException(ex2);
+ }
+ }
for (Symbol symbol : unit.namedImportScope.getSymbols()) {
importScope.importType(symbol.owner.members(), symbol.owner.members(), symbol);
}
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 3fe8b71..804ddf3 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
@@ -872,6 +872,9 @@ public final class TreeUtilities {
Env<AttrContext> env = getEnv(scope);
if (tree instanceof JCExpression)
return attr.attribExpr((JCTree) tree,env, Type.noType);
+ if (env.tree != null && env.tree.getKind() == Kind.VARIABLE) {
+ env = env.next;
+ }
return attr.attribStat((JCTree) tree,env);
} finally {
// cacheContext.leave();
diff --git a/java.source.base/test/unit/src/org/netbeans/api/java/source/TreeUtilitiesTest.java b/java.source.base/test/unit/src/org/netbeans/api/java/source/TreeUtilitiesTest.java
index 7bbbf5e..f555807 100644
--- a/java.source.base/test/unit/src/org/netbeans/api/java/source/TreeUtilitiesTest.java
+++ b/java.source.base/test/unit/src/org/netbeans/api/java/source/TreeUtilitiesTest.java
@@ -25,6 +25,7 @@ import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Scope;
+import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
@@ -41,6 +42,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
+import javax.lang.model.element.Element;
import javax.lang.model.type.TypeMirror;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.source.Comment.Style;
@@ -585,6 +587,38 @@ public class TreeUtilitiesTest extends NbTestCase {
}, true);
}
+ public void testAttributingVar() throws Exception {
+ ClassPath boot = ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0]));
+ FileObject testFile = FileUtil.createData(FileUtil.createMemoryFileSystem().getRoot(), "Test.java");
+ try (Writer w = new OutputStreamWriter(testFile.getOutputStream())) {
+ w.append("public class Test { private static int I; }");
+ }
+ JavaSource js = JavaSource.create(ClasspathInfo.create(boot, ClassPath.EMPTY, ClassPath.EMPTY), testFile);
+ js.runUserActionTask(new Task<CompilationController>() {
+ @Override
+ public void run(CompilationController parameter) throws Exception {
+ parameter.toPhase(Phase.RESOLVED);
+ TreePath clazzPath = new TreePath(new TreePath(new TreePath(parameter.getCompilationUnit()),
+ parameter.getCompilationUnit().getTypeDecls().get(0)),
+ ((ClassTree) parameter.getCompilationUnit().getTypeDecls().get(0)).getMembers().get(1));
+ Scope scope = parameter.getTrees().getScope(clazzPath);
+ StatementTree st = parameter.getTreeUtilities().parseStatement("{ String s; }", new SourcePositions[1]);
+ assertEquals(Kind.BLOCK, st.getKind());
+ StatementTree var = st.getKind() == Kind.BLOCK ? ((BlockTree) st).getStatements().get(0) : st;
+ parameter.getTreeUtilities().attributeTree(st, scope);
+ checkType(parameter, clazzPath, var);
+ }
+ }, true);
+ }
+
+ private void checkType(CompilationInfo info, TreePath base, StatementTree st) {
+ TreePath tp = new TreePath(base, st);
+ Element el = info.getTrees().getElement(tp);
+
+ assertNotNull(el);
+ assertEquals("s", el.toString());
+ }
+
public void testIsEndOfCompoundVariableDeclaration() throws Exception {
prepareTest("Test", "package test; public class Test {public Test(){int i = 10, j = 11;}}");
TreePath tp = info.getTreeUtilities().pathFor(47);
---------------------------------------------------------------------
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