target(compile: "Compile project") {
loadProject()
- bundledJDKs()
projectBuilder.stage("Cleaning up sandbox folder")
forceDelete(paths.sandbox)
projectBuilder.targetFolder = "$out/classes"
projectBuilder.cleanOutput()
+ bundledJDKs()
projectBuilder.buildProduction()
projectBuilder.makeModuleTests(findModule("jps-builders"))
}
layoutMac(args, home, paths)
layoutUnix(args, home, paths)
- buildWinZip("$paths.artifacts/idea${args.buildNumber}.win.zip", [paths.distAll, paths.distWin])
+ buildWinZip("$paths.artifacts/idea${args.buildNumber}.win.zip", [paths.distAll, paths.distWin, "${paths.sandbox}/bundled.win.jdk"])
buildCrossPlatformZip("$paths.artifacts/idea${args.buildNumber}.zip", "${paths.sandbox}/sandbox-ce", [paths.distAll],
paths.distWin, paths.distUnix, paths.distMac)
binding.setVariable("commonJvmArgsForTests", {
def jdwp = "-Xrunjdwp:transport=dt_socket,server=y,suspend=$debugSuspend"
if (debugPort != null) jdwp += ",address=$debugPort"
+
return [
"-ea",
"-Dio.netty.leakDetectionLevel=PARANOID",
requireProperty("jdk.bundled.mac", "1.8")
requireProperty("jdk.custom.mac", "true")
- setProperty("winJDK", getPathToBundledJDK(new File("${home}/build/jdk/win"), "jdk" + p("jdk.bundled.win"), "x32.zip"))
+ if (p("jdk.bundled.win") != "false") {
+ setProperty("winJDK", getPathToBundledJDK(new File("${home}/build/jdk/win"), "jdk" + p("jdk.bundled.win"), "x32.zip"))
+ extractRedistJre(winJDK, "${paths.sandbox}/bundled.win.jdk")
+ }
if (p("jdk.bundled.linux") != "false"){
setProperty("linuxJDK", getPathToBundledJDK(new File("${home}/build/jdk/linux"), "jdk" + p("jdk.bundled.linux"), ".tar"))
extractRedistJre(linuxJDK, "${paths.sandbox}/bundled.linux.jdk")
private Map<Module, ProcessorConfigProfile> myProcessorsProfilesMap = null;
@Nullable
- private String myBytecodeTargetLevel = null; // null means compiler default
+ private String myBytecodeTargetLevel = null; // null means same as effective language level
private final Map<String, String> myModuleBytecodeTarget = new HashMap<String, String>();
public CompilerConfigurationImpl(Project project) {
@Override
public void removeRow(int idx) {
myItems.remove(idx);
+ fireTableRowsDeleted(idx, idx);
}
public void setItems(Map<Module, String> items) {
import org.jetbrains.jps.model.serialization.JpsGlobalLoader;
import javax.swing.*;
-import javax.tools.*;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
import java.awt.*;
import java.io.File;
import java.io.FileFilter;
return pathname.isDirectory() && !TEMP_DIR_NAME.equals(pathname.getName());
}
});
- final Date now = new Date();
- for (File buildDataProjectDir : dirs) {
- final File usageFile = getUsageFile(buildDataProjectDir);
- if (usageFile.exists()) {
- final Pair<Date, File> usageData = readUsageFile(usageFile);
- if (usageData != null) {
- final File projectFile = usageData.second;
- if ((projectFile != null && !projectFile.exists()) || DateFormatUtil.getDifferenceInDays(usageData.first, now) > unusedThresholdDays) {
- LOG.info("Clearing project build data because the project does not exist or was not opened for more than " + unusedThresholdDays + " days: " + buildDataProjectDir.getPath());
- FileUtil.delete(buildDataProjectDir);
+ if (dirs != null) {
+ final Date now = new Date();
+ for (File buildDataProjectDir : dirs) {
+ final File usageFile = getUsageFile(buildDataProjectDir);
+ if (usageFile.exists()) {
+ final Pair<Date, File> usageData = readUsageFile(usageFile);
+ if (usageData != null) {
+ final File projectFile = usageData.second;
+ if ((projectFile != null && !projectFile.exists()) || DateFormatUtil.getDifferenceInDays(usageData.first, now) > unusedThresholdDays) {
+ LOG.info("Clearing project build data because the project does not exist or was not opened for more than " + unusedThresholdDays + " days: " + buildDataProjectDir.getPath());
+ FileUtil.delete(buildDataProjectDir);
+ }
}
}
- }
- else {
- updateUsageFile(null, buildDataProjectDir); // set usage stamp to start countdown
+ else {
+ updateUsageFile(null, buildDataProjectDir); // set usage stamp to start countdown
+ }
}
}
}
return "com.intellij.compiler.server.BuildManager";
}
+ @NotNull
+ public static Pair<Sdk, JavaSdkVersion> getBuildProcessRuntimeSdk(Project project) {
+ Sdk projectJdk = null;
+ int sdkMinorVersion = 0;
+ JavaSdkVersion sdkVersion = null;
+
+ final Set<Sdk> candidates = new HashSet<Sdk>();
+ final Sdk defaultSdk = ProjectRootManager.getInstance(project).getProjectSdk();
+ if (defaultSdk != null && defaultSdk.getSdkType() instanceof JavaSdkType) {
+ candidates.add(defaultSdk);
+ }
+
+ for (Module module : ModuleManager.getInstance(project).getModules()) {
+ final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
+ if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
+ candidates.add(sdk);
+ }
+ }
+
+ // now select the latest version from the sdks that are used in the project, but not older than the internal sdk version
+ final JavaSdk javaSdkType = JavaSdk.getInstance();
+ for (Sdk candidate : candidates) {
+ final String vs = candidate.getVersionString();
+ if (vs != null) {
+ final JavaSdkVersion candidateVersion = javaSdkType.getVersion(vs);
+ if (candidateVersion != null) {
+ final int candidateMinorVersion = getMinorVersion(vs);
+ if (projectJdk == null) {
+ sdkVersion = candidateVersion;
+ sdkMinorVersion = candidateMinorVersion;
+ projectJdk = candidate;
+ }
+ else {
+ final int result = candidateVersion.compareTo(sdkVersion);
+ if (result > 0 || (result == 0 && candidateMinorVersion > sdkMinorVersion)) {
+ sdkVersion = candidateVersion;
+ sdkMinorVersion = candidateMinorVersion;
+ projectJdk = candidate;
+ }
+ }
+ }
+ }
+ }
+
+ final Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
+ if (projectJdk == null || sdkVersion == null || !sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_6)) {
+ projectJdk = internalJdk;
+ sdkVersion = javaSdkType.getVersion(internalJdk);
+ }
+ return Pair.create(projectJdk, sdkVersion);
+ }
+
private Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> launchPreloadedBuildProcess(final Project project, SequentialTaskExecutor projectTaskQueue) throws Exception {
ensureListening();
if (StringUtil.isEmptyOrSpaces(forcedCompiledJdkHome)) {
// choosing sdk with which the build process should be run
- Sdk projectJdk = null;
- int sdkMinorVersion = 0;
-
- final Set<Sdk> candidates = new HashSet<Sdk>();
- final Sdk defaultSdk = ProjectRootManager.getInstance(project).getProjectSdk();
- if (defaultSdk != null && defaultSdk.getSdkType() instanceof JavaSdkType) {
- candidates.add(defaultSdk);
- }
-
- for (Module module : ModuleManager.getInstance(project).getModules()) {
- final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
- if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
- candidates.add(sdk);
- }
- }
-
- // now select the latest version from the sdks that are used in the project, but not older than the internal sdk version
- final JavaSdk javaSdkType = JavaSdk.getInstance();
- for (Sdk candidate : candidates) {
- final String vs = candidate.getVersionString();
- if (vs != null) {
- final JavaSdkVersion candidateVersion = javaSdkType.getVersion(vs);
- if (candidateVersion != null) {
- final int candidateMinorVersion = getMinorVersion(vs);
- if (projectJdk == null) {
- sdkVersion = candidateVersion;
- sdkMinorVersion = candidateMinorVersion;
- projectJdk = candidate;
- }
- else {
- final int result = candidateVersion.compareTo(sdkVersion);
- if (result > 0 || (result == 0 && candidateMinorVersion > sdkMinorVersion)) {
- sdkVersion = candidateVersion;
- sdkMinorVersion = candidateMinorVersion;
- projectJdk = candidate;
- }
- }
- }
- }
- }
+ final Pair<Sdk, JavaSdkVersion> pair = getBuildProcessRuntimeSdk(project);
+ final Sdk projectJdk = pair.first;
+ sdkVersion = pair.second;
final Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
- if (projectJdk == null || sdkVersion == null || !sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_6)) {
- projectJdk = internalJdk;
- }
-
// validate tools.jar presence
final JavaSdkType projectJdkType = (JavaSdkType)projectJdk.getSdkType();
if (FileUtil.pathsEqual(projectJdk.getHomePath(), internalJdk.getHomePath())) {
@Override
public void projectOpened(final Project project) {
+ if (ApplicationManager.getApplication().isUnitTestMode()) return;
final MessageBusConnection conn = project.getMessageBus().connect();
myConnections.put(project, conn);
conn.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() {
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.registry.Registry;
import com.intellij.util.xmlb.XmlSerializerUtil;
@State(
}
public boolean allowAutoMakeWhileRunningApplication() {
- return false;/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/
+ return Registry.is("compiler.automake.allow.when.app.running", false);/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/
}
}
<orderEntry type="module" module-name="xdebugger-impl" />
<orderEntry type="module" module-name="lang-api" />
<orderEntry type="module" module-name="compiler-openapi" />
+ <orderEntry type="module" module-name="compiler-impl" />
<orderEntry type="module" module-name="java-runtime" />
<orderEntry type="module" module-name="jsp-openapi" />
<orderEntry type="module" module-name="java-impl" />
<orderEntry type="module" module-name="platform-impl" />
<orderEntry type="module" module-name="util" />
<orderEntry type="module" module-name="diff-api" />
+ <orderEntry type="module" module-name="jps-builders" />
</component>
<component name="copyright">
<Base>
/*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.debugger.engine.LambdaMethodFilter;
import com.intellij.debugger.engine.MethodFilter;
import com.intellij.debugger.impl.DebuggerSession;
-import com.intellij.openapi.actionSystem.ActionManager;
-import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.fileEditor.TextEditor;
-import com.intellij.openapi.keymap.KeymapUtil;
-import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.ui.awt.RelativePoint;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
-import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.List;
session.stepInto(true, createMethodFilter(chosenTarget));
}
});
- final ListPopup popup = new ListPopupImpl(popupStep) {
- @Override
- protected JComponent createContent() {
- registerExtraHandleShortcuts(XDebuggerActions.STEP_INTO);
- registerExtraHandleShortcuts(XDebuggerActions.SMART_STEP_INTO);
- return super.createContent();
- }
-
- private void registerExtraHandleShortcuts(String actionName) {
- AnAction action = ActionManager.getInstance().getAction(actionName);
- KeyStroke stroke = KeymapUtil.getKeyStroke(action.getShortcutSet());
- if (stroke != null) {
- registerAction("handleSelection " + stroke, stroke, new AbstractAction() {
- @Override
- public void actionPerformed(ActionEvent e) {
- handleSelect(true);
- }
- });
- }
- }
- };
+ ListPopupImpl popup = new ListPopupImpl(popupStep);
+ DebuggerUIUtil.registerExtraHandleShortcuts(popup, XDebuggerActions.STEP_INTO);
+ DebuggerUIUtil.registerExtraHandleShortcuts(popup, XDebuggerActions.SMART_STEP_INTO);
popup.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
popupStep.getScopeHighlighter().dropHighlight();
}
@Nullable
- public static String getClassVMName(PsiClass containingClass) {
+ public static String getClassVMName(@Nullable PsiClass containingClass) {
+ if (containingClass == null) return null;
if (containingClass instanceof PsiAnonymousClass) {
return getClassVMName(PsiTreeUtil.getParentOfType(containingClass, PsiClass.class)) +
JavaAnonymousClassesHelper.getName((PsiAnonymousClass)containingClass);
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.EmptyIterable;
import com.intellij.xdebugger.impl.ui.ExecutionPointHighlighter;
SourcePosition sourcePosition = SourcePosition.createFromLine(psiFile, lineNumber);
int lambdaOrdinal = -1;
if (LambdaMethodFilter.isLambdaName(method.name())) {
- List<Location> lambdas = ContainerUtil.filter(locationsOfLine(location.declaringType(), sourcePosition), new Condition<Location>() {
- @Override
- public boolean value(Location location) {
- return LambdaMethodFilter.isLambdaName(location.method().name());
- }
- });
- if (lambdas.size() > 1) {
- Collections.sort(lambdas, new Comparator<Location>() {
+ Set<Method> lambdas =
+ ContainerUtil.map2SetNotNull(locationsOfLine(location.declaringType(), sourcePosition), new Function<Location, Method>() {
@Override
- public int compare(Location o1, Location o2) {
- return LambdaMethodFilter.getLambdaOrdinal(o1.method().name()) - LambdaMethodFilter.getLambdaOrdinal(o2.method().name());
- }
- });
- lambdaOrdinal = ContainerUtil.indexOf(lambdas, new Condition<Location>() {
- @Override
- public boolean value(Location location) {
- return location.method().equals(method);
+ public Method fun(Location location) {
+ Method method = location.method();
+ if (LambdaMethodFilter.isLambdaName(method.name())) {
+ return method;
+ }
+ return null;
}
});
+ if (lambdas.size() > 1) {
+ ArrayList<Method> lambdasList = new ArrayList<Method>(lambdas);
+ Collections.sort(lambdasList, DebuggerUtilsEx.LAMBDA_ORDINAL_COMPARATOR);
+ lambdaOrdinal = lambdasList.indexOf(method);
}
}
return new JavaSourcePosition(sourcePosition, location.declaringType(), method, lambdaOrdinal);
myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.createClassFilter(psiClass), name);
}
else {
- PsiType type = qualifier.getType();
- if(type == null) {
- throwEvaluateException(DebuggerBundle.message("evaluation.error.qualifier.type.unknown", qualifier.getText()));
- }
-
qualifier.accept(this);
if (myResult == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.evaluate.qualifier", qualifier.getText()));
}
- myResult = new FieldEvaluator(myResult, FieldEvaluator.createClassFilter(type), name);
+ myResult = new FieldEvaluator(myResult, FieldEvaluator.createClassFilter(qualifier.getType()), name);
}
}
else {
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.psi.util.PsiUtil;
import com.sun.jdi.*;
import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FieldEvaluator implements Evaluator {
myTargetClassFilter = filter;
}
- public static TargetClassFilter createClassFilter(PsiType psiType) {
- if(psiType instanceof PsiArrayType) {
+ @NotNull
+ public static TargetClassFilter createClassFilter(@Nullable PsiType psiType) {
+ if(psiType == null || psiType instanceof PsiArrayType) {
return TargetClassFilter.ALL;
}
PsiClass psiClass = PsiUtil.resolveClassInType(psiType);
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.engine.DebuggerUtils;
+import com.intellij.debugger.engine.LambdaMethodFilter;
import com.intellij.debugger.engine.SuspendContextImpl;
import com.intellij.debugger.engine.evaluation.*;
import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilder;
}
return false;
}
+
+ public static final Comparator<Method> LAMBDA_ORDINAL_COMPARATOR = new Comparator<Method>() {
+ @Override
+ public int compare(Method m1, Method m2) {
+ return LambdaMethodFilter.getLambdaOrdinal(m1.name()) - LambdaMethodFilter.getLambdaOrdinal(m2.name());
+ }
+ };
}
import com.intellij.debugger.engine.LambdaMethodFilter;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.requests.RequestManagerImpl;
+import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.sun.jdi.*;
final LambdaMethodFilter lambdaFilter = (LambdaMethodFilter)myFilter;
if (lambdaFilter.getLambdaOrdinal() < methodsFound) {
final Method[] candidates = methods.toArray(new Method[methodsFound]);
- Arrays.sort(candidates, new Comparator<Method>() {
- public int compare(Method m1, Method m2) {
- return LambdaMethodFilter.getLambdaOrdinal(m1.name()) - LambdaMethodFilter.getLambdaOrdinal(m2.name());
- }
- });
+ Arrays.sort(candidates, DebuggerUtilsEx.LAMBDA_ORDINAL_COMPARATOR);
location = candidates[lambdaFilter.getLambdaOrdinal()].location();
}
}
import com.sun.jdi.ClassType;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.jps.incremental.BinaryContent;
+import org.jetbrains.jps.javac.OutputFileObject;
import org.jetbrains.org.objectweb.asm.ClassReader;
import org.jetbrains.org.objectweb.asm.ClassVisitor;
import org.jetbrains.org.objectweb.asm.ClassWriter;
import org.jetbrains.org.objectweb.asm.Opcodes;
-import javax.tools.*;
-import java.io.ByteArrayOutputStream;
-import java.net.URI;
-import java.util.ArrayList;
import java.util.Collection;
/**
ClassLoaderReference classLoader = ClassLoadingUtils.getClassLoader(evaluationContext, process);
String version = ((VirtualMachineProxyImpl)process.getVirtualMachineProxy()).version();
- JavaSdkVersion sdkVersion = JdkVersionUtil.getVersion(version);
- Collection<OutputFileObject> classes = compile(sdkVersion != null ? sdkVersion.getDescription() : null);
+ Collection<OutputFileObject> classes = compile(JdkVersionUtil.getVersion(version));
defineClasses(classes, evaluationContext, process, classLoader);
ClassLoaderReference classLoader) throws EvaluateException {
for (OutputFileObject cls : classes) {
if (cls.getName().contains(GEN_CLASS_NAME)) {
- byte[] bytes = changeSuperToMagicAccessor(cls.toByteArray());
- ClassLoadingUtils.defineClass(cls.myOrigName, bytes, context, process, classLoader);
+ final BinaryContent content = cls.getContent();
+ if (content != null) {
+ byte[] bytes = changeSuperToMagicAccessor(content.toByteArray());
+ ClassLoadingUtils.defineClass(cls.getClassName(), bytes, context, process, classLoader);
+ }
}
}
return (ClassType)process.findClass(context, getGenClassQName(), classLoader);
///////////////// Compiler stuff
@NotNull
- protected abstract Collection<OutputFileObject> compile(String target) throws EvaluateException;
-
- private static URI getUri(String name, JavaFileObject.Kind kind) {
- return URI.create("memo:///" + name.replace('.', '/') + kind.extension);
- }
-
- protected static class SourceFileObject extends SimpleJavaFileObject {
- private final String myContent;
-
- SourceFileObject(String name, Kind kind, String content) {
- super(getUri(name, kind), kind);
- myContent = content;
- }
-
- @Override
- public CharSequence getCharContent(boolean ignore) {
- return myContent;
- }
- }
-
- protected static class OutputFileObject extends SimpleJavaFileObject {
- private final ByteArrayOutputStream myStream = new ByteArrayOutputStream();
- private final String myOrigName;
-
- OutputFileObject(String name, Kind kind) {
- super(getUri(name, kind), kind);
- myOrigName = name;
- }
-
- byte[] toByteArray() {
- return myStream.toByteArray();
- }
-
- @Override
- public ByteArrayOutputStream openOutputStream() {
- return myStream;
- }
- }
-
- protected static class MemoryFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
- protected final Collection<OutputFileObject> classes = new ArrayList<OutputFileObject>();
-
- MemoryFileManager(JavaCompiler compiler) {
- super(compiler.getStandardFileManager(null, null, null));
- }
-
- @Override
- public OutputFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject source) {
- OutputFileObject mc = new OutputFileObject(name, kind);
- classes.add(mc);
- return mc;
- }
- }
+ protected abstract Collection<OutputFileObject> compile(@Nullable JavaSdkVersion debuggeeVersion) throws EvaluateException;
}
*/
package com.intellij.debugger.ui.impl.watch;
+import com.intellij.compiler.server.BuildManager;
+import com.intellij.debugger.engine.DebugProcess;
+import com.intellij.debugger.engine.DebugProcessAdapter;
+import com.intellij.debugger.engine.DebugProcessImpl;
+import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.engine.evaluation.EvaluateException;
+import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
+import com.intellij.openapi.projectRoots.JavaSdkType;
+import com.intellij.openapi.projectRoots.JavaSdkVersion;
+import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.openapi.projectRoots.SdkTypeId;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.Computable;
-import com.intellij.openapi.util.SystemInfo;
+import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
import com.intellij.refactoring.extractMethodObject.ExtractLightMethodObjectHandler;
-import com.intellij.util.PathsList;
+import com.intellij.util.net.NetUtils;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.jps.api.CanceledStatus;
+import org.jetbrains.jps.builders.impl.java.JavacCompilerTool;
+import org.jetbrains.jps.javac.DiagnosticOutputConsumer;
+import org.jetbrains.jps.javac.ExternalJavacManager;
+import org.jetbrains.jps.javac.OutputFileConsumer;
+import org.jetbrains.jps.javac.OutputFileObject;
-import javax.tools.*;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
+import javax.tools.Diagnostic;
+import javax.tools.JavaFileObject;
+import java.io.File;
+import java.io.IOException;
+import java.util.*;
+// todo: consider batching compilations in order not to start a separate process for every class that needs to be compiled
public class CompilingEvaluatorImpl extends CompilingEvaluator {
- public CompilingEvaluatorImpl(@NotNull PsiElement context, @NotNull ExtractLightMethodObjectHandler.ExtractedData data) {
+ private final EvaluationContextImpl myEvaluationContext;
+
+ public CompilingEvaluatorImpl(EvaluationContextImpl evaluationContext, @NotNull PsiElement context, @NotNull ExtractLightMethodObjectHandler.ExtractedData data) {
super(context, data);
+ myEvaluationContext = evaluationContext;
}
@Override
@NotNull
- protected Collection<OutputFileObject> compile(String target) throws EvaluateException {
- if (!SystemInfo.isJavaVersionAtLeast(target)) {
- throw new EvaluateException("Unable to compile for target level " + target + ". Need to run IDEA on java version at least " + target + ", currently running on " + SystemInfo.JAVA_RUNTIME_VERSION);
- }
- JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
- MemoryFileManager manager = new MemoryFileManager(compiler);
- DiagnosticCollector<JavaFileObject> diagnostic = new DiagnosticCollector<JavaFileObject>();
- Module module = ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
+ protected Collection<OutputFileObject> compile(@Nullable JavaSdkVersion debuggeeVersion) throws EvaluateException {
+ final Pair<Sdk, JavaSdkVersion> runtime = BuildManager.getBuildProcessRuntimeSdk(myEvaluationContext.getProject());
+ final Module module = ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
@Override
public Module compute() {
return ModuleUtilCore.findModuleForPsiElement(myPsiContext);
}
});
- List<String> options = new ArrayList<String>();
+ String javaHome = null;
+ final Sdk sdk = runtime.getFirst();
+ final SdkTypeId type = sdk.getSdkType();
+ if (type instanceof JavaSdkType) {
+ javaHome = sdk.getHomePath();
+ }
+ if (javaHome == null) {
+ throw new EvaluateException("Was not able to determine JDK for current evaluation context");
+ }
+ final List<String> options = new ArrayList<String>();
+ options.add("-proc:none"); // for our purposes annotation processing is not needed
+ options.add("-encoding");
+ options.add("UTF-8");
+ final List<File> platformClasspath = new ArrayList<File>();
+ final List<File> classpath = new ArrayList<File>();
if (module != null) {
- options.add("-cp");
- PathsList cp = ModuleRootManager.getInstance(module).orderEntries().compileOnly().recursively().exportedOnly().withoutSdk().getPathsList();
- options.add(cp.getPathsString());
+ final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
+ rootManager.orderEntries().compileOnly().recursively().exportedOnly().withoutSdk().getPathsList().addAllFiles(classpath);
+ rootManager.orderEntries().compileOnly().sdkOnly().getPathsList().addAllFiles(platformClasspath);
}
- if (!StringUtil.isEmpty(target)) {
+
+ final JavaSdkVersion buildRuntimeVersion = runtime.getSecond();
+ // if compiler or debuggee version or both are unknown, let source and target be the compiler's defaults
+ if (buildRuntimeVersion != null && debuggeeVersion != null) {
+ final JavaSdkVersion minVersion = buildRuntimeVersion.ordinal() > debuggeeVersion.ordinal() ? debuggeeVersion : buildRuntimeVersion;
+ final String sourceOption = getSourceOption(minVersion.getMaxLanguageLevel());
options.add("-source");
- options.add(target);
+ options.add(sourceOption);
options.add("-target");
- options.add(target);
+ options.add(sourceOption);
}
+
+ File sourceFile = null;
+ final OutputCollector outputSink = new OutputCollector();
try {
- if (!compiler.getTask(null,
- manager,
- diagnostic,
- options,
- null,
- Collections.singletonList(new SourceFileObject(getMainClassName(), JavaFileObject.Kind.SOURCE, getClassCode()))
- ).call()) {
- StringBuilder res = new StringBuilder("Compilation failed:\n");
+ final ExternalJavacManager javacManager = getJavacManager();
+ if (javacManager == null) {
+ throw new EvaluateException("Cannot compile java code");
+ }
+ sourceFile = generateTempSourceFile(javacManager.getWorkingDir());
+ final File srcDir = sourceFile.getParentFile();
+ final Map<File, Set<File>> output = Collections.singletonMap(srcDir, Collections.singleton(srcDir));
+ DiagnosticCollector diagnostic = new DiagnosticCollector();
+ final List<String> vmOptions = Collections.emptyList();
+ final List<File> sourcePath = Collections.emptyList();
+ final Set<File> sources = Collections.singleton(sourceFile);
+ boolean compiledOK = javacManager.forkJavac(
+ javaHome, -1, vmOptions, options, platformClasspath, classpath, sourcePath, sources, output, diagnostic, outputSink, new JavacCompilerTool(), CanceledStatus.NULL
+ );
+
+ if (!compiledOK) {
+ final StringBuilder res = new StringBuilder("Compilation failed:\n");
for (Diagnostic<? extends JavaFileObject> d : diagnostic.getDiagnostics()) {
- res.append(d);
+ if (d.getKind() == Diagnostic.Kind.ERROR) {
+ res.append(d.getMessage(Locale.US));
+ }
}
throw new EvaluateException(res.toString());
}
}
+ catch (EvaluateException e) {
+ throw e;
+ }
catch (Exception e) {
throw new EvaluateException(e.getMessage());
}
- return manager.classes;
+ finally {
+ if (sourceFile != null) {
+ FileUtil.delete(sourceFile);
+ }
+ }
+ return outputSink.getCompiledClasses();
}
- protected String getClassCode() {
- return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
+ @NotNull
+ private static String getSourceOption(@NotNull LanguageLevel languageLevel) {
+ return "1." + Integer.valueOf(3 + languageLevel.ordinal());
+ }
+
+ private File generateTempSourceFile(File workingDir) throws IOException {
+ final Pair<String, String> fileData = ApplicationManager.getApplication().runReadAction(new Computable<Pair<String, String>>() {
@Override
- public String compute() {
- return myData.getGeneratedInnerClass().getContainingFile().getText();
+ public Pair<String, String> compute() {
+ final PsiFile file = myData.getGeneratedInnerClass().getContainingFile();
+ return Pair.create(file.getName(), file.getText());
}
});
+ if (fileData.first == null) {
+ throw new IOException("Class file name not specified");
+ }
+ if (fileData.second == null) {
+ throw new IOException("Class source code not specified");
+ }
+ final File file = new File(workingDir, "src/"+fileData.first);
+ FileUtil.writeToFile(file, fileData.second);
+ return file;
}
- protected String getMainClassName() {
- return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
- @Override
- public String compute() {
- return FileUtil.getNameWithoutExtension(myData.getGeneratedInnerClass().getContainingFile().getName());
+ private static final Key<ExternalJavacManager> JAVAC_MANAGER_KEY = Key.create("_external_java_compiler_manager_");
+
+ @Nullable
+ private ExternalJavacManager getJavacManager() throws IOException {
+ // need dedicated thread access to be able to cache the manager in the user data
+ DebuggerManagerThreadImpl.assertIsManagerThread();
+
+ final DebugProcessImpl debugProcess = myEvaluationContext.getDebugProcess();
+ ExternalJavacManager manager = JAVAC_MANAGER_KEY.get(debugProcess);
+ if (manager == null && debugProcess.isAttached()) {
+ final File compilerWorkingDir = getCompilerWorkingDir();
+ if (compilerWorkingDir == null) {
+ return null; // should not happen for real projects
}
- });
+ final int listenPort = NetUtils.findAvailableSocketPort();
+ manager = new ExternalJavacManager(compilerWorkingDir);
+ manager.start(listenPort);
+ final ExternalJavacManager _manager = manager;
+ debugProcess.addDebugProcessListener(new DebugProcessAdapter() {
+ public void processDetached(DebugProcess process, boolean closedByUser) {
+ if (process == debugProcess) {
+ _manager.stop();
+ }
+ }
+ });
+ JAVAC_MANAGER_KEY.set(debugProcess, manager);
+ }
+ return manager;
+ }
+
+ @Nullable
+ private File getCompilerWorkingDir() {
+ final File projectBuildDir = BuildManager.getInstance().getProjectSystemDirectory(myEvaluationContext.getProject());
+ if (projectBuildDir == null) {
+ return null;
+ }
+ final File root = new File(projectBuildDir, "debugger");
+ root.mkdirs();
+ return root;
+ }
+
+ private static class DiagnosticCollector implements DiagnosticOutputConsumer {
+ private final List<Diagnostic<? extends JavaFileObject>> myDiagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>();
+ public void outputLineAvailable(String line) {
+ // for debugging purposes uncomment this line
+ //System.out.println(line);
+ }
+
+ public void registerImports(String className, Collection<String> imports, Collection<String> staticImports) {
+ // ignore
+ }
+
+ public void javaFileLoaded(File file) {
+ // ignore
+ }
+
+ public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
+ myDiagnostics.add(diagnostic);
+ }
+
+ public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() {
+ return myDiagnostics;
+ }
+ }
+
+ private static class OutputCollector implements OutputFileConsumer {
+ private List<OutputFileObject> myClasses = new ArrayList<OutputFileObject>();
+
+ public void save(@NotNull OutputFileObject fileObject) {
+ myClasses.add(fileObject);
+ }
+
+ public List<OutputFileObject> getCompiledClasses() {
+ return myClasses;
+ }
}
}
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.Value;
+import org.jetbrains.annotations.Nullable;
/**
* User: lex
return false;
}
- public static PsiExpression substituteThis(PsiExpression expressionWithThis, PsiExpression howToEvaluateThis, Value howToEvaluateThisValue)
+ @Nullable
+ public static PsiExpression substituteThis(@Nullable PsiExpression expressionWithThis, PsiExpression howToEvaluateThis, Value howToEvaluateThisValue)
throws EvaluateException {
+ if (expressionWithThis == null) return null;
PsiExpression result = (PsiExpression)expressionWithThis.copy();
PsiClass thisClass = PsiTreeUtil.getContextOfType(result, PsiClass.class, true);
ExtractLightMethodObjectHandler.ExtractedData data = ExtractLightMethodObjectHandler.extractLightMethodObject(myProject,
psiFile, fragment, CompilingEvaluator.getGeneratedClassName());
if (data != null) {
- return new CompilingEvaluatorImpl(psiContext, data);
+ return new CompilingEvaluatorImpl(evaluationContext, psiContext, data);
}
}
catch (PrepareFailedException e) {
public void setLambdaOrdinal(Integer lambdaOrdinal) {
myLambdaOrdinal = lambdaOrdinal;
}
+
+ @Override
+ public void loadState(JavaLineBreakpointProperties state) {
+ super.loadState(state);
+
+ myLambdaOrdinal = state.myLambdaOrdinal;
+ }
}
import com.intellij.execution.testframework.*;
import com.intellij.execution.testframework.actions.AbstractRerunFailedTestsAction;
import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil;
+import com.intellij.execution.testframework.sm.runner.SMRunnerConsolePropertiesProvider;
import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties;
import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView;
import com.intellij.execution.testframework.sm.runner.ui.SMTestRunnerResultsForm;
import com.intellij.execution.testframework.ui.BaseTestsOutputConsoleView;
-import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.util.JavaParametersUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.rt.execution.CommandLineWrapper;
import com.intellij.util.PathUtil;
import com.intellij.util.ui.UIUtil;
-import jetbrains.buildServer.messages.serviceMessages.ServiceMessageTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.serialization.PathMacroUtil;
import java.net.ServerSocket;
import java.util.Locale;
-public abstract class JavaTestFrameworkRunnableState<T extends ModuleBasedConfiguration<JavaRunConfigurationModule> & CommonJavaRunConfigurationParameters> extends JavaCommandLineState {
+public abstract class JavaTestFrameworkRunnableState<T extends ModuleBasedConfiguration<JavaRunConfigurationModule> & CommonJavaRunConfigurationParameters & SMRunnerConsolePropertiesProvider> extends JavaCommandLineState {
private static final Logger LOG = Logger.getInstance("#" + JavaTestFrameworkRunnableState.class.getName());
protected ServerSocket myServerSocket;
protected File myTempFile;
protected abstract void passTempFile(ParametersList parametersList, String tempFilePath);
- @NotNull protected abstract AbstractRerunFailedTestsAction createRerunFailedTestsAction(TestConsoleProperties testConsoleProperties, ConsoleView consoleView);
-
@NotNull protected abstract T getConfiguration();
@Nullable protected abstract TestSearchScope getScope();
@NotNull protected abstract OSProcessHandler createHandler(Executor executor) throws ExecutionException;
- @NotNull protected abstract SMTRunnerConsoleProperties createTestConsoleProperties(Executor executor);
-
public SearchForTestsTask createSearchingForTestsTask() {
return null;
}
return null;
}
getJavaParameters().getVMParametersList().addProperty("idea." + getFrameworkId() + ".sm_runner");
- getJavaParameters().getClassPath().addFirst(PathUtil.getJarPathForClass(ServiceMessageTypes.class));
final RunnerSettings runnerSettings = getRunnerSettings();
- final TestConsoleProperties testConsoleProperties = createTestConsoleProperties(executor);
+ final SMTRunnerConsoleProperties testConsoleProperties = getConfiguration().createTestConsoleProperties(executor);
testConsoleProperties.setIfUndefined(TestConsoleProperties.HIDE_PASSED_TESTS, false);
- final BaseTestsOutputConsoleView consoleView = SMTestRunnerConnectionUtil.createConsole(getFrameworkName(), testConsoleProperties, getEnvironment());
+ final BaseTestsOutputConsoleView consoleView = SMTestRunnerConnectionUtil.createConsole(getFrameworkName(), testConsoleProperties);
final SMTestRunnerResultsForm viewer = ((SMTRunnerConsoleView)consoleView).getResultsViewer();
Disposer.register(getConfiguration().getProject(), consoleView);
}
});
- AbstractRerunFailedTestsAction rerunFailedTestsAction = createRerunFailedTestsAction(testConsoleProperties, consoleView);
+ AbstractRerunFailedTestsAction rerunFailedTestsAction = testConsoleProperties.createRerunFailedTestsAction(consoleView);
+ LOG.assertTrue(rerunFailedTestsAction != null);
rerunFailedTestsAction.setModelProvider(new Getter<TestFrameworkRunningModel>() {
@Override
public TestFrameworkRunningModel get() {
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.ide.wizard.AbstractWizard;
import com.intellij.ide.wizard.CommitStepException;
+import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
public AbstractProjectWizard(String title, Project project, String defaultPath) {
super(title, project);
- myWizardContext = initContext(project, defaultPath);
+ myWizardContext = initContext(project, defaultPath, getDisposable());
}
public AbstractProjectWizard(String title, Project project, Component dialogParent) {
super(title, dialogParent);
- myWizardContext = initContext(project, null);
+ myWizardContext = initContext(project, null, getDisposable());
}
@Override
public abstract StepSequence getSequence();
- private static WizardContext initContext(@Nullable Project project, @Nullable String defaultPath) {
- WizardContext context = new WizardContext(project);
+ private static WizardContext initContext(@Nullable Project project, @Nullable String defaultPath, Disposable parentDisposable) {
+ WizardContext context = new WizardContext(project, parentDisposable);
if (defaultPath != null) {
context.setProjectFileDirectory(defaultPath);
context.setProjectName(defaultPath.substring(FileUtil.toSystemIndependentName(defaultPath).lastIndexOf("/") + 1));
return myName;
}
- private class ModifiableRootModelInvocationHandler implements InvocationHandler {
+ private class ModifiableRootModelInvocationHandler implements InvocationHandler, ProxyDelegateAccessor {
private final ModifiableRootModel myDelegateModel;
@NonNls private final Set<String> myCheckedNames = new HashSet<String>(
Arrays.asList("addOrderEntry", "addLibraryEntry", "addInvalidLibrary", "addModuleOrderEntry", "addInvalidModuleEntry",
}
}
}
+
+ @Override
+ public Object getDelegate() {
+ return myDelegateModel;
+ }
}
private class LibraryTableInvocationHandler implements InvocationHandler, ProxyDelegateAccessor {
actionGroup.add(myEditButton);
actionGroup.add(myRemoveButton);
actionGroup.add(navigateAction);
+ actionGroup.add(new InlineModuleDependencyAction(this));
actionGroup.add(new MyFindUsagesAction());
actionGroup.add(new AnalyzeDependencyAction());
addChangeLibraryLevelAction(actionGroup, LibraryTablesRegistrar.PROJECT_LEVEL);
--- /dev/null
+/*
+ * Copyright 2000-2015 JetBrains s.r.o.
+ *
+ * Licensed 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 com.intellij.openapi.roots.ui.configuration.classpath;
+
+import com.intellij.openapi.actionSystem.AnAction;
+import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.roots.*;
+import com.intellij.openapi.roots.impl.ClonableOrderEntry;
+import com.intellij.openapi.roots.impl.OrderEntryUtil;
+import com.intellij.openapi.roots.impl.ProjectRootManagerImpl;
+import com.intellij.openapi.roots.impl.RootModelImpl;
+import com.intellij.openapi.roots.ui.configuration.ModuleEditor;
+import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable;
+import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
+import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ModuleProjectStructureElement;
+import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
+
+import java.lang.reflect.Proxy;
+
+/**
+ * @author nik
+ */
+public class InlineModuleDependencyAction extends AnAction {
+ private static final Logger LOG = Logger.getInstance(InlineModuleDependencyAction.class);
+ private final ClasspathPanelImpl myClasspathPanel;
+
+ public InlineModuleDependencyAction(ClasspathPanelImpl classpathPanel) {
+ super("Inline Module Dependency", "Replace dependency on a module without source roots by the list of its dependencies", null);
+ myClasspathPanel = classpathPanel;
+ }
+
+ @Override
+ public void actionPerformed(AnActionEvent e) {
+ OrderEntry selectedEntry = myClasspathPanel.getSelectedEntry();
+ if (!(selectedEntry instanceof ModuleOrderEntry)) return;
+
+ ModuleOrderEntry entryToInline = (ModuleOrderEntry)selectedEntry;
+ Module module = entryToInline.getModule();
+ if (module == null) return;
+
+ ModifiableRootModel model = myClasspathPanel.getRootModel();
+ int toInlineIndex = findModuleEntryIndex(model, module);
+ if (toInlineIndex == -1) return;
+
+ model.removeOrderEntry(entryToInline);
+
+ RootModelImpl modelImpl;
+ if (Proxy.isProxyClass(model.getClass())) {
+ modelImpl = (RootModelImpl)((ModuleEditor.ProxyDelegateAccessor)Proxy.getInvocationHandler(model)).getDelegate();
+ }
+ else {
+ modelImpl = (RootModelImpl)model;
+ }
+ int addedCount = 0;
+ ModuleRootModel otherModel = myClasspathPanel.getModuleConfigurationState().getModulesProvider().getRootModel(module);
+ ProjectRootManagerImpl rootManager = ProjectRootManagerImpl.getInstanceImpl(myClasspathPanel.getProject());
+ VirtualFilePointerManager virtualFilePointerManager = VirtualFilePointerManager.getInstance();
+ for (OrderEntry entry : otherModel.getOrderEntries()) {
+ if (entry instanceof LibraryOrderEntry || entry instanceof ModuleOrderEntry) {
+ LOG.assertTrue(entry instanceof ClonableOrderEntry, entry);
+ ExportableOrderEntry entryToCopy = (ExportableOrderEntry)entry;
+ ExportableOrderEntry cloned = (ExportableOrderEntry)((ClonableOrderEntry)entry).cloneEntry(modelImpl, rootManager, virtualFilePointerManager);
+ cloned.setExported(entryToInline.isExported() && entryToCopy.isExported());
+ cloned.setScope(OrderEntryUtil.intersectScopes(entryToInline.getScope(), entryToCopy.getScope()));
+ model.addOrderEntry(cloned);
+ addedCount++;
+ }
+ }
+
+ OrderEntry[] oldEntries = model.getOrderEntries();
+ OrderEntry[] newEntries = new OrderEntry[oldEntries.length];
+ System.arraycopy(oldEntries, 0, newEntries, 0, toInlineIndex);
+ System.arraycopy(oldEntries, oldEntries.length - addedCount, newEntries, toInlineIndex, addedCount);
+ System.arraycopy(oldEntries, toInlineIndex, newEntries, toInlineIndex + addedCount, oldEntries.length - toInlineIndex - addedCount);
+ model.rearrangeOrderEntries(newEntries);
+
+ StructureConfigurableContext context = ProjectStructureConfigurable.getInstance(myClasspathPanel.getProject()).getContext();
+ context.getDaemonAnalyzer().queueUpdate(new ModuleProjectStructureElement(context, module));
+ }
+
+ private static int findModuleEntryIndex(ModifiableRootModel model, Module module) {
+ OrderEntry[] entries = model.getOrderEntries();
+ for (int i = 0; i < entries.length; i++) {
+ OrderEntry entry = entries[i];
+ if (entry instanceof ModuleOrderEntry && module.equals(((ModuleOrderEntry)entry).getModule())) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public void update(AnActionEvent e) {
+ e.getPresentation().setEnabledAndVisible(isEnabled());
+ }
+
+ private boolean isEnabled() {
+ OrderEntry entry = myClasspathPanel.getSelectedEntry();
+ if (!(entry instanceof ModuleOrderEntry)) return false;
+
+ Module module = ((ModuleOrderEntry)entry).getModule();
+ if (module == null) return false;
+
+ ModuleRootModel model = myClasspathPanel.getModuleConfigurationState().getModulesProvider().getRootModel(module);
+ return model.getSourceRootUrls().length == 0;
+ }
+}
super(false);
setTitle("Manage Project Templates");
final ProjectTemplate[] templates =
- new ArchivedTemplatesFactory().createTemplates(ProjectTemplatesFactory.CUSTOM_GROUP, new WizardContext(null));
+ new ArchivedTemplatesFactory().createTemplates(ProjectTemplatesFactory.CUSTOM_GROUP, new WizardContext(null, getDisposable()));
myTemplatesList = new JBList(new CollectionListModel<ProjectTemplate>(Arrays.asList(templates)) {
@Override
public void remove(int index) {
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
if (isDefault || !isAbstract && superMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
- final String message = isDefault
+ final String message = isDefault && !isAbstract
? " inherits unrelated defaults for "
: " inherits abstract and default for ";
final String inheritUnrelatedDefaultsMessage = HighlightUtil.formatClass(aClass) +
}
@Nullable
- public static HighlightInfo checkOverrideAnnotation(PsiMethod method, final LanguageLevel languageLevel) {
- PsiModifierList list = method.getModifierList();
- final PsiAnnotation overrideAnnotation = list.findAnnotation("java.lang.Override");
- if (overrideAnnotation == null) {
- return null;
- }
+ static HighlightInfo checkOverrideAnnotation(@NotNull PsiMethod method,
+ @NotNull PsiAnnotation overrideAnnotation,
+ @NotNull LanguageLevel languageLevel) {
try {
MethodSignatureBackedByPsiMethod superMethod = SuperMethodsSearch.search(method, null, true, false).findFirst();
if (superMethod != null && method.getContainingClass().isInterface()) {
final PsiMethod psiMethod = superMethod.getMethod();
final PsiClass containingClass = psiMethod.getContainingClass();
- if (containingClass != null &&
+ if (containingClass != null &&
CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName()) &&
psiMethod.hasModifierProperty(PsiModifier.PROTECTED)) {
superMethod = null;
@Nullable
static HighlightInfo checkAmbiguousMethodCallArguments(@NotNull PsiReferenceExpression referenceToMethod,
- @NotNull JavaResolveResult[] resolveResults,
- @NotNull PsiExpressionList list,
- final PsiElement element,
- @NotNull JavaResolveResult resolveResult,
- @NotNull PsiMethodCallExpression methodCall,
- @NotNull PsiResolveHelper resolveHelper) {
+ @NotNull JavaResolveResult[] resolveResults,
+ @NotNull PsiExpressionList list,
+ final PsiElement element,
+ @NotNull JavaResolveResult resolveResult,
+ @NotNull PsiMethodCallExpression methodCall,
+ @NotNull PsiResolveHelper resolveHelper,
+ @NotNull PsiElement elementToHighlight) {
MethodCandidateInfo methodCandidate1 = null;
MethodCandidateInfo methodCandidate2 = null;
for (JavaResolveResult result : resolveResults) {
String description;
String toolTip;
- PsiElement elementToHighlight;
HighlightInfoType highlightInfoType = HighlightInfoType.ERROR;
if (methodCandidate2 != null) {
PsiMethod element1 = methodCandidate1.getElement();
}
description = JavaErrorMessages.message("ambiguous.method.call", m1, m2);
toolTip = createAmbiguousMethodHtmlTooltip(new MethodCandidateInfo[]{methodCandidate1, methodCandidate2});
- elementToHighlight = list;
}
else {
if (element != null && !resolveResult.isAccessible()) {
if (candidates.length == 0) {
return null;
}
- else {
- elementToHighlight = list;
- }
}
toolTip = XmlStringUtil.escapeString(description);
}
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
parent instanceof PsiPrefixExpression &&
((PsiPrefixExpression)parent).getOperationTokenType() == JavaTokenType.MINUS)) {
if (text.equals(PsiLiteralExpressionImpl.HEX_PREFIX)) {
- final String message = JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
if (text.equals(PsiLiteralExpressionImpl.BIN_PREFIX)) {
- final String message = JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
if (value == null || text.equals(PsiLiteralExpressionImpl._2_IN_31)) {
- final String message = JavaErrorMessages.message("integer.number.too.large");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("integer.number.too.large");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
}
else if (type == JavaTokenType.LONG_LITERAL) {
- final String mText = text.endsWith("l") ? text.substring(0, text.length() - 1) : text;
+ String mText = text.endsWith("l") ? text.substring(0, text.length() - 1) : text;
//literal 9223372036854775808L may appear only as the operand of the unary negation operator -.
if (!(mText.equals(PsiLiteralExpressionImpl._2_IN_63) &&
parent instanceof PsiPrefixExpression &&
((PsiPrefixExpression)parent).getOperationTokenType() == JavaTokenType.MINUS)) {
if (mText.equals(PsiLiteralExpressionImpl.HEX_PREFIX)) {
- final String message = JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
if (mText.equals(PsiLiteralExpressionImpl.BIN_PREFIX)) {
- final String message = JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
if (value == null || mText.equals(PsiLiteralExpressionImpl._2_IN_63)) {
- final String message = JavaErrorMessages.message("long.number.too.large");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("long.number.too.large");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
}
else if (isFP) {
if (value == null) {
- final String message = JavaErrorMessages.message("malformed.floating.point.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("malformed.floating.point.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
else if (type == JavaTokenType.CHARACTER_LITERAL) {
- // todo[r.sh] clean this mess up
if (value != null) {
if (!StringUtil.endsWithChar(text, '\'')) {
- final String message = JavaErrorMessages.message("unclosed.char.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("unclosed.char.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
else {
- if (!StringUtil.startsWithChar(text, '\'')) return null;
+ if (!StringUtil.startsWithChar(text, '\'')) {
+ return null;
+ }
if (StringUtil.endsWithChar(text, '\'')) {
if (text.length() == 1) {
- final String message = JavaErrorMessages.message("illegal.line.end.in.character.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("illegal.line.end.in.character.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
text = text.substring(1, text.length() - 1);
}
else {
- final String message = JavaErrorMessages.message("illegal.line.end.in.character.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("illegal.line.end.in.character.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
+
StringBuilder chars = new StringBuilder();
- final boolean success = PsiLiteralExpressionImpl.parseStringCharacters(text, chars, null);
+ boolean success = PsiLiteralExpressionImpl.parseStringCharacters(text, chars, null);
if (!success) {
- final String message = JavaErrorMessages.message("illegal.escape.character.in.character.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("illegal.escape.character.in.character.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
int length = chars.length();
if (length > 1) {
- final String message = JavaErrorMessages.message("too.many.characters.in.character.literal");
- final HighlightInfo info =
- HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("too.many.characters.in.character.literal");
+ HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createConvertToStringLiteralAction());
return info;
}
else if (length == 0) {
- final String message = JavaErrorMessages.message("empty.character.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("empty.character.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
}
else if (type == JavaTokenType.STRING_LITERAL) {
if (value == null) {
- for (final PsiElement element : expression.getChildren()) {
+ for (PsiElement element : expression.getChildren()) {
if (element instanceof OuterLanguageElement) {
return null;
}
if (!StringUtil.startsWithChar(text, '\"')) return null;
if (StringUtil.endsWithChar(text, '\"')) {
if (text.length() == 1) {
- final String message = JavaErrorMessages.message("illegal.line.end.in.string.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("illegal.line.end.in.string.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
text = text.substring(1, text.length() - 1);
}
else {
- final String message = JavaErrorMessages.message("illegal.line.end.in.string.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("illegal.line.end.in.string.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
+
StringBuilder chars = new StringBuilder();
boolean success = PsiLiteralExpressionImpl.parseStringCharacters(text, chars, null);
if (!success) {
- final String message = JavaErrorMessages.message("illegal.escape.character.in.string.literal");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("illegal.escape.character.in.string.literal");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
}
if (value instanceof Float) {
- final Float number = (Float)value;
+ Float number = (Float)value;
if (number.isInfinite()) {
- final String message = JavaErrorMessages.message("floating.point.number.too.large");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("floating.point.number.too.large");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
if (number.floatValue() == 0 && !TypeConversionUtil.isFPZero(text)) {
- final String message = JavaErrorMessages.message("floating.point.number.too.small");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("floating.point.number.too.small");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
else if (value instanceof Double) {
- final Double number = (Double)value;
+ Double number = (Double)value;
if (number.isInfinite()) {
- final String message = JavaErrorMessages.message("floating.point.number.too.large");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("floating.point.number.too.large");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
if (number.doubleValue() == 0 && !TypeConversionUtil.isFPZero(text)) {
- final String message = JavaErrorMessages.message("floating.point.number.too.small");
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
+ String message = JavaErrorMessages.message("floating.point.number.too.small");
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create();
}
}
}
@Nullable
- static HighlightInfo checkExpressionRequired(@NotNull PsiReferenceExpression expression,
- @NotNull JavaResolveResult resultForIncompleteCode) {
+ static HighlightInfo checkExpressionRequired(@NotNull PsiReferenceExpression expression, @NotNull JavaResolveResult resultForIncompleteCode) {
if (expression.getNextSibling() instanceof PsiErrorElement) return null;
+
PsiElement resolved = resultForIncompleteCode.getElement();
- if (resolved == null) return null;
+ if (resolved == null || resolved instanceof PsiVariable) return null;
+
PsiElement parent = expression.getParent();
// String.class or String() are both correct
if (parent instanceof PsiReferenceExpression || parent instanceof PsiMethodCallExpression) return null;
- if (resolved instanceof PsiVariable) return null;
+
String description = JavaErrorMessages.message("expression.expected");
- final HighlightInfo info =
- HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
+ HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
UnresolvedReferenceQuickFixProvider.registerReferenceFixes(expression, new QuickFixActionRegistrarImpl(info));
return info;
}
-
@Nullable
static HighlightInfo checkArrayInitializerApplicable(@NotNull PsiArrayInitializerExpression expression) {
/*
}
String description = JavaErrorMessages.message("array.initializer.not.allowed");
- HighlightInfo info =
- HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
+ HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createAddNewArrayExpressionFix(expression));
return info;
}
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkForeignInnerClassesUsed(annotation));
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkFunctionalInterface(annotation, myLanguageLevel));
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkRepeatableAnnotation(annotation));
+ if (CommonClassNames.JAVA_LANG_OVERRIDE.equals(annotation.getQualifiedName())) {
+ PsiAnnotationOwner owner = annotation.getOwner();
+ PsiElement parent = owner instanceof PsiModifierList ? ((PsiModifierList)owner).getParent() : null;
+ if (parent instanceof PsiMethod) {
+ myHolder.add(GenericsHighlightUtil.checkOverrideAnnotation((PsiMethod)parent, annotation, myLanguageLevel));
+ }
+ }
}
@Override
// this check is for fake expression from JspMethodCallImpl
referenceExpression.getParent() == expression) {
try {
- myHolder.add(HighlightMethodUtil.checkAmbiguousMethodCallArguments(referenceExpression, results, list, resolved, result, expression, myResolveHelper));
+ if (PsiTreeUtil.findChildrenOfType(expression.getArgumentList(), PsiLambdaExpression.class).isEmpty()) {
+ myHolder.add(HighlightMethodUtil.checkAmbiguousMethodCallArguments(referenceExpression, results, list, resolved, result, expression, myResolveHelper, list));
+ }
}
catch (IndexNotReadyException ignored) {
}
if (!myHolder.hasErrorResults()) myHolder.add(HighlightControlFlowUtil.checkUnreachableStatement(method.getBody()));
if (!myHolder.hasErrorResults()) myHolder.add(HighlightMethodUtil.checkConstructorHandleSuperClassExceptions(method));
if (!myHolder.hasErrorResults()) myHolder.add(HighlightMethodUtil.checkRecursiveConstructorInvocation(method));
- if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkOverrideAnnotation(method, myLanguageLevel));
if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkSafeVarargsAnnotation(method, myLanguageLevel));
PsiClass aClass = method.getContainingClass();
PsiExpressionList list = methodCallExpression.getArgumentList();
if (!HighlightMethodUtil.isDummyConstructorCall(methodCallExpression, myResolveHelper, list, expression)) {
try {
- myHolder.add(HighlightMethodUtil.checkAmbiguousMethodCallIdentifier(expression, results, list, resolved, result,
- methodCallExpression, myResolveHelper));
+ myHolder.add(HighlightMethodUtil.checkAmbiguousMethodCallIdentifier(expression, results, list, resolved, result, methodCallExpression, myResolveHelper));
+
+ if (!PsiTreeUtil.findChildrenOfType(methodCallExpression.getArgumentList(), PsiLambdaExpression.class).isEmpty()) {
+ myHolder.add(HighlightMethodUtil
+ .checkAmbiguousMethodCallArguments(expression, results, list, resolved, result, methodCallExpression, myResolveHelper, expression.getReferenceNameElement()));
+ }
}
catch (IndexNotReadyException ignored) {
}
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
PsiTryStatement tryStatement = (PsiTryStatement)element.getParent();
List<PsiClassType> unhandledExceptions = new ArrayList<PsiClassType>(ExceptionUtil.collectUnhandledExceptions(element, null));
+ if (unhandledExceptions.isEmpty()) return;
+
ExceptionUtil.sortExceptionsByHierarchy(unhandledExceptions);
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
import com.intellij.psi.impl.source.jsp.jspJava.JspClassLevelDeclarationStatement;
import com.intellij.psi.impl.source.tree.Factory;
import com.intellij.psi.impl.source.tree.TreeElement;
+import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
class DeclarationMover extends LineMover {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.actions.moveUpDown.DeclarationMover");
private PsiEnumConstant myEnumToInsertSemicolonAfter;
+ private boolean moveEnumConstant = false;
@Override
public void beforeMove(@NotNull final Editor editor, @NotNull final MoveInfo info, final boolean down) {
}
}
+ @Override
+ public void afterMove(@NotNull Editor editor, @NotNull PsiFile file, @NotNull MoveInfo info, boolean down) {
+ super.afterMove(editor, file, info, down);
+ if (moveEnumConstant) {
+ final Document document = editor.getDocument();
+ final CharSequence cs = document.getCharsSequence();
+ int end1 = info.range1.getEndOffset();
+ char c1 = cs.charAt(--end1);
+ while (Character.isWhitespace(c1)) {
+ c1 = cs.charAt(--end1);
+ }
+ int end2 = info.range2.getEndOffset();
+ char c2 = cs.charAt(--end2);
+ while (Character.isWhitespace(c2)) {
+ c2 = cs.charAt(--end2);
+ }
+ if (c1 == c2 || c1 != ',' && c2 != ',') {
+ return;
+ }
+ if (c1 == ';' || c2 == ';') {
+ document.replaceString(end1, end1 + 1, String.valueOf(c2));
+ document.replaceString(end2, end2 + 1, String.valueOf(c1));
+ }
+ else if (c1 == ',') {
+ document.deleteString(end1, end1 + 1);
+ document.insertString(end2 + 1, ",");
+ }
+ else {
+ document.deleteString(end2, end2 + 1);
+ document.insertString(end1 + 1, ",");
+ }
+ }
+ }
+
@Override
public boolean checkAvailable(@NotNull final Editor editor, @NotNull final PsiFile file, @NotNull final MoveInfo info, final boolean down) {
if (!(file instanceof PsiJavaFile)) {
if (psiRange == null) return false;
final PsiMember firstMember = PsiTreeUtil.getParentOfType(psiRange.getFirst(), PsiMember.class, false);
- final PsiMember lastMember = PsiTreeUtil.getParentOfType(psiRange.getSecond(), PsiMember.class, false);
+ PsiElement endElement = psiRange.getSecond();
+ if (firstMember instanceof PsiEnumConstant && endElement instanceof PsiJavaToken) {
+ final IElementType tokenType = ((PsiJavaToken)endElement).getTokenType();
+ if (down && tokenType == JavaTokenType.SEMICOLON) {
+ return info.prohibitMove();
+ }
+ if (tokenType == JavaTokenType.COMMA || tokenType == JavaTokenType.SEMICOLON) {
+ endElement = PsiTreeUtil.skipSiblingsBackward(endElement, PsiWhiteSpace.class);
+ }
+ }
+ final PsiMember lastMember = PsiTreeUtil.getParentOfType(endElement, PsiMember.class, false);
if (firstMember == null || lastMember == null) return false;
LineRange range;
if (firstMember == lastMember) {
+ moveEnumConstant = firstMember instanceof PsiEnumConstant;
range = memberRange(firstMember, editor, oldRange);
if (range == null) return false;
range.firstElement = range.lastElement = firstMember;
PsiElement sibling = down ? range.lastElement.getNextSibling() : range.firstElement.getPrevSibling();
sibling = firstNonWhiteElement(sibling, down);
- if (down && range.lastElement instanceof PsiEnumConstant && sibling instanceof PsiJavaToken) {
- sibling = ((PsiJavaToken)sibling).getTokenType() == JavaTokenType.COMMA ? firstNonWhiteElement(sibling.getNextSibling(), true) : null;
+ if (range.lastElement instanceof PsiEnumConstant && sibling instanceof PsiJavaToken) {
+ final PsiJavaToken token = (PsiJavaToken)sibling;
+ final IElementType tokenType = token.getTokenType();
+ if (down && tokenType == JavaTokenType.SEMICOLON) {
+ return info.prohibitMove();
+ }
+ if (tokenType == JavaTokenType.COMMA) {
+ sibling = down ?
+ PsiTreeUtil.skipSiblingsForward(sibling, PsiWhiteSpace.class) :
+ PsiTreeUtil.skipSiblingsBackward(sibling, PsiWhiteSpace.class);
+ }
}
final boolean areWeMovingClass = range.firstElement instanceof PsiClass;
info.toMove = range;
Float.compare(${classInstanceName}.$field.accessor, $field.accessor) != 0 ##
#end
#end
+#macro(addPrimitiveFieldComparisonConditionDirect $field)
+ $field.accessor == ${classInstanceName}.$field.accessor ##
+#end
+#macro(addDoubleFieldComparisonConditionDirect $field)
+ #if ($field.double)
+ Double.compare(${classInstanceName}.$field.accessor, $field.accessor) == 0 ##
+ #else
+ Float.compare(${classInstanceName}.$field.accessor, $field.accessor) == 0 ##
+ #end
+#end
#set($i = $i + 1)
#if ($field.primitive)
#if ($field.double || $field.float)
- #addDoubleFieldComparisonCondition($field) ##
+ #addDoubleFieldComparisonConditionDirect($field) ##
#else
- #addPrimitiveFieldComparisonCondition($field) ##
+ #addPrimitiveFieldComparisonConditionDirect($field) ##
#end
#elseif ($field.enum)
- #addPrimitiveFieldComparisonCondition($field) ##
+ #addPrimitiveFieldComparisonConditionDirect($field) ##
#else
com.google.common.base.Objects.equal($field.accessor, ${classInstanceName}.$field.accessor)##
#end
#set($i = $i + 1)
#if ($field.primitive)
#if ($field.double || $field.float)
- #addDoubleFieldComparisonCondition($field) ##
+ #addDoubleFieldComparisonConditionDirect($field) ##
#else
- #addPrimitiveFieldComparisonCondition($field) ##
+ #addPrimitiveFieldComparisonConditionDirect($field) ##
#end
#elseif ($field.enum)
- #addPrimitiveFieldComparisonCondition($field) ##
+ #addPrimitiveFieldComparisonConditionDirect($field) ##
#elseif ($field.array)
java.util.Arrays.equals($field.accessor, ${classInstanceName}.$field.accessor)##
#else
return false;
}
- final PsiExpressionStatement statement = PsiTreeUtil.getParentOfType(element,PsiExpressionStatement.class);
+ final PsiExpressionStatement statement = detectExpressionStatement(element);
if (statement == null){
return false;
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
- final PsiExpressionStatement statement = PsiTreeUtil.getParentOfType(element,PsiExpressionStatement.class);
+ final PsiExpressionStatement statement = detectExpressionStatement(element);
if (statement == null){
return;
}
new IntroduceVariableHandler().invoke(project, editor, statement.getExpression());
}
+
+ private static PsiExpressionStatement detectExpressionStatement(@NotNull PsiElement element) {
+ final PsiElement prevSibling = PsiTreeUtil.skipSiblingsBackward(element, PsiWhiteSpace.class);
+ return prevSibling instanceof PsiExpressionStatement ? (PsiExpressionStatement)prevSibling
+ : PsiTreeUtil.getParentOfType(element, PsiExpressionStatement.class);
+ }
}
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.LocalSearchScope;
-import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
public class SurroundAutoCloseableAction extends PsiElementBaseIntentionAction {
@Override
- public boolean isAvailable(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) {
+ public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!element.getLanguage().isKindOf(JavaLanguage.INSTANCE)) return false;
if (!PsiUtil.getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_1_7)) return false;
final PsiElement codeBlock = declaration.getParent();
if (!(codeBlock instanceof PsiCodeBlock)) return false;
- final PsiType type = variable.getType();
- if (!(type instanceof PsiClassType)) return false;
- final PsiClass aClass = ((PsiClassType)type).resolve();
- final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
- final PsiClass autoCloseable = facade.findClass(CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE, ProjectScope.getLibrariesScope(project));
- if (!InheritanceUtil.isInheritorOrSelf(aClass, autoCloseable, true)) return false;
-
- return true;
+ return InheritanceUtil.isInheritor(variable.getType(), CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE);
}
@Override
- public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) throws IncorrectOperationException {
+ public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) {
return;
}
List<PsiElement> toFormat = null;
if (last != null) {
- final PsiElement first = armStatement.getNextSibling();
- if (first != null) {
- toFormat = moveStatements(first, last, armStatement);
- }
+ toFormat = moveStatements(last, armStatement);
}
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
}
}
- private static List<PsiElement> moveStatements(@NotNull PsiElement first, PsiElement last, PsiTryStatement statement) {
+ private static List<PsiElement> moveStatements(PsiElement last, PsiTryStatement statement) {
PsiCodeBlock tryBlock = statement.getTryBlock();
assert tryBlock != null : statement.getText();
PsiElement parent = statement.getParent();
List<PsiElement> toFormat = new SmartList<PsiElement>();
PsiElement stopAt = last.getNextSibling();
- for (PsiElement child = first; child != null && child != stopAt; child = child.getNextSibling()) {
+
+ PsiElement i = statement.getNextSibling();
+ while (i != null && i != stopAt) {
+ PsiElement child = i;
+ i = PsiTreeUtil.skipSiblingsForward(i, PsiWhiteSpace.class, PsiComment.class);
+
if (!(child instanceof PsiDeclarationStatement)) continue;
PsiElement anchor = child;
final int endOffset = last.getTextRange().getEndOffset();
boolean contained = ReferencesSearch.search(declared, new LocalSearchScope(parent)).forEach(new Processor<PsiReference>() {
@Override
- public boolean process(PsiReference reference) {
- return reference.getElement().getTextOffset() <= endOffset;
+ public boolean process(PsiReference ref) {
+ return ref.getElement().getTextOffset() <= endOffset;
}
});
toFormat.add(parent.addBefore(factory.createVariableDeclarationStatement(name, var.getType(), null), statement));
PsiExpression varInit = var.getInitializer();
- assert varInit != null : child.getText();
- String varAssignText = name + " = " + varInit.getText() + ";";
- anchor = parent.addAfter(factory.createStatementFromText(varAssignText, parent), anchor);
+ if (varInit != null) {
+ String varAssignText = name + " = " + varInit.getText() + ";";
+ anchor = parent.addAfter(factory.createStatementFromText(varAssignText, parent), anchor);
+ }
var.delete();
}
}
}
+ PsiElement first = statement.getNextSibling();
tryBlock.addRangeBefore(first, last, tryBlock.getRBrace());
parent.deleteChildRange(first, last);
@Override
@Nullable
public String getExternalDocInfoForElement(@NotNull String docURL, final PsiElement element) throws Exception {
- CharSequence externalDoc = null;
+ String externalDoc = null;
String builtInServer = "http://localhost:" + BuiltInServerOptions.getInstance().getEffectiveBuiltInServerPort() + "/" + myProject.getName() + "/";
if (docURL.startsWith(builtInServer)) {
int refPosition = docURL.lastIndexOf('#');
reader.close();
}
- externalDoc = result;
+ externalDoc = correctDocText(docURL, result);
}
}
DocumentationManager.createHyperlink(buffer, className, className, false);
return matcher.replaceFirst(buffer.append("</h3>").toString());
}
- return externalDoc.toString();
+ return externalDoc;
}
@NotNull
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
package com.intellij.codeInsight.template.impl;
-import org.jetbrains.annotations.NonNls;
-
/**
* @author yole
*/
public class JavaDefaultLiveTemplatesProvider implements DefaultLiveTemplatesProvider {
- private static final @NonNls String[] DEFAULT_TEMPLATES = new String[]{
+ private static final String[] DEFAULT_TEMPLATES = {
"/liveTemplates/iterations",
"/liveTemplates/other",
"/liveTemplates/output",
--- /dev/null
+/*
+ * Copyright 2000-2015 JetBrains s.r.o.
+ *
+ * Licensed 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 com.intellij.codeInsight.template.macro;
+
+import com.intellij.codeInsight.CodeInsightBundle;
+import com.intellij.codeInsight.template.*;
+import com.intellij.psi.PsiExpression;
+import com.intellij.psi.PsiType;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public class ExpressionTypeMacro extends Macro {
+ @Override
+ public String getName() {
+ return "expressionType";
+ }
+
+ @Override
+ public String getPresentableName() {
+ return CodeInsightBundle.message("macro.expression.type");
+ }
+
+ @Nullable
+ @Override
+ public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) {
+ if (params.length == 1) {
+ Result result = params[0].calculateResult(context);
+ if (result != null) {
+ PsiExpression expression = MacroUtil.resultToPsiExpression(result, context);
+ if (expression != null) {
+ PsiType type = expression.getType();
+ if (type != null) {
+ return new PsiTypeResult(type, context.getProject());
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+}
for (SmartPsiElementPointer sortedID : sortedIDs) {
final PsiClass psiClass = (PsiClass)dereferenceInReadAction(sortedID);
if (psiClass == null) continue;
- context.incrementJobDoneAmount(context.getStdJobDescriptors().FIND_EXTERNAL_USAGES, ApplicationManager.getApplication().runReadAction(
- new Computable<String>() {
- @Override
- public String compute() {
- return psiClass.getQualifiedName();
- }
- }
- ));
+ context.incrementJobDoneAmount(context.getStdJobDescriptors().FIND_EXTERNAL_USAGES, getClassPresentableName(psiClass));
final List<DerivedClassesProcessor> processors = myDerivedClassesRequests.get(sortedID);
LOG.assertTrue(processors != null, psiClass.getClass().getName());
final List<UsagesProcessor> processors = myClassUsagesRequests.get(sortedID);
LOG.assertTrue(processors != null, psiClass.getClass().getName());
- context.incrementJobDoneAmount(context.getStdJobDescriptors().FIND_EXTERNAL_USAGES, ApplicationManager.getApplication().runReadAction(
- new Computable<String>() {
- @Override
- public String compute() {
- return psiClass.getQualifiedName();
- }
- }
- ));
+ context.incrementJobDoneAmount(context.getStdJobDescriptors().FIND_EXTERNAL_USAGES, getClassPresentableName(psiClass));
ReferencesSearch.search(psiClass, searchScope, false)
.forEach(new PsiReferenceProcessorAdapter(createReferenceProcessor(processors, context)));
}
}
+ private String getClassPresentableName(final PsiClass psiClass) {
+ return ApplicationManager.getApplication().runReadAction(
+ new Computable<String>() {
+ @Override
+ public String compute() {
+ final String qualifiedName = psiClass.getQualifiedName();
+ return qualifiedName != null ? qualifiedName : psiClass.getName();
+ }
+ }
+ );
+ }
+
private static PsiElement dereferenceInReadAction(final SmartPsiElementPointer sortedID) {
return ApplicationManager.getApplication().runReadAction(new Computable<PsiElement>() {
@Override
/*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// }
//}
final JavaCodeStyleManager codeStyleManagerEx = JavaCodeStyleManager.getInstance(element.getProject());
- codeStyleManagerEx.shortenClassReferences(element, JavaCodeStyleManager.UNCOMPLETE_CODE);
+ codeStyleManagerEx.shortenClassReferences(element, JavaCodeStyleManager.INCOMPLETE_CODE);
}
}
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
if (!SourceTreeToPsiMap.hasTreeElement(element)) return element;
final boolean addImports = (flags & DO_NOT_ADD_IMPORTS) == 0;
- final boolean incompleteCode = (flags & UNCOMPLETE_CODE) != 0;
+ final boolean incompleteCode = (flags & INCOMPLETE_CODE) != 0;
final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage());
if (adjuster != null) {
PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
Presentation presentation = e.getPresentation();
String place = e.getPlace();
- boolean enabled = (file instanceof PsiClassOwner || ActionPlaces.EDITOR_TAB_POPUP.equals(place)) && place != ActionPlaces.EDITOR_POPUP && e.getData(CommonDataKeys.PROJECT) != null;
+ boolean enabled = file != null &&
+ (file instanceof PsiClassOwner || ActionPlaces.EDITOR_TAB_POPUP.equals(place)) &&
+ place != ActionPlaces.EDITOR_POPUP && e.getData(CommonDataKeys.PROJECT) != null;
presentation.setEnabled(enabled);
presentation.setVisible(enabled);
if (enabled) {
});
myVisibilityPanel = createVisibilityPanel();
+ myVisibilityPanel.registerUpDownActionsFor(myNameField);
final JPanel visibilityAndReturnType = new JPanel(new BorderLayout(2, 0));
if (!myTargetClass.isInterface()) {
visibilityAndReturnType.add(myVisibilityPanel, BorderLayout.WEST);
if (endOffset <= startOffset) return null;
PsiElement elementAt = PsiTreeUtil.findCommonParent(elementAtStart, elementAtEnd);
- if (PsiTreeUtil.getParentOfType(elementAt, PsiExpression.class, false) == null) {
+ final PsiExpression containingExpression = PsiTreeUtil.getParentOfType(elementAt, PsiExpression.class, false);
+ if (containingExpression == null || containingExpression instanceof PsiLambdaExpression) {
if (injectedLanguageManager.isInjectedFragment(file)) {
return getSelectionFromInjectedHost(project, file, injectedLanguageManager, startOffset, endOffset);
}
}
}
super.beforeTemplateStart();
+ }
+
+ @Override
+ protected void onRenameTemplateStarted() {
final ResolveSnapshotProvider resolveSnapshotProvider = VariableInplaceRenamer.INSTANCE.forLanguage(myScope.getLanguage());
myConflictResolver = resolveSnapshotProvider != null ? resolveSnapshotProvider.createSnapshot(myScope) : null;
}
oldOne = itemWrapper;
}
}
- if (!fileIndex.isInLibrarySource(oldSelection)) {
+ if (oldSelection == null || !fileIndex.isInLibrarySource(oldSelection)) {
items.add(NULL_WRAPPER);
}
final DirectoryChooser.ItemWrapper selection = chooseSelection(initialTargetDirectorySourceRoot, fileIndex, items, initial, oldOne);
}
}
LOG.assertTrue(element.getTextRange() != null);
- usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, isInNonStaticImport(element)));
+ final PsiFile containingFile = psiClass.getContainingFile();
+ final boolean sameFileWithSingleClass = containingFile instanceof PsiClassOwner &&
+ ((PsiClassOwner)containingFile).getClasses().length == 1 &&
+ element.getContainingFile() == containingFile;
+ usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, sameFileWithSingleClass || isInNonStaticImport(element)));
}
return true;
}
import com.intellij.openapi.extensions.Extensions;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
+import com.intellij.psi.util.CachedValueProvider;
+import com.intellij.psi.util.CachedValuesManager;
+import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.testIntegration.TestFramework;
import org.jetbrains.annotations.Nullable;
}
@Nullable
- public static TestFramework detectFramework(PsiClass psiClass) {
+ public static TestFramework detectFramework(final PsiClass psiClass) {
+ return CachedValuesManager.getCachedValue(psiClass, new CachedValueProvider<TestFramework>() {
+ @Nullable
+ @Override
+ public Result<TestFramework> compute() {
+ return Result.create(computeFramework(psiClass), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
+ }
+ });
+ }
+
+ @Nullable
+ private static TestFramework computeFramework(PsiClass psiClass) {
for (TestFramework framework : Extensions.getExtensions(TestFramework.EXTENSION_NAME)) {
if (framework.isTestClass(psiClass)) {
return framework;
return framework;
}
}
-
return null;
}
}
/*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-/*
- * @author max
- */
package com.intellij.psi.codeStyle;
import com.intellij.openapi.components.ServiceManager;
import java.util.Collection;
+/**
+ * @author max
+ */
public abstract class JavaCodeStyleManager {
public static JavaCodeStyleManager getInstance(Project project) {
return ServiceManager.getService(project, JavaCodeStyleManager.class);
}
public static final int DO_NOT_ADD_IMPORTS = 0x1000;
- public static final int UNCOMPLETE_CODE = 0x2000;
+ public static final int INCOMPLETE_CODE = 0x2000;
+
+ /** @deprecated use {@link #INCOMPLETE_CODE} (to be removed in IDEA 17) */
+ @SuppressWarnings({"unused", "SpellCheckingInspection"}) public static final int UNCOMPLETE_CODE = INCOMPLETE_CODE;
public abstract boolean addImport(@NotNull PsiJavaFile file, @NotNull PsiClass refClass);
- public abstract PsiElement shortenClassReferences(@NotNull PsiElement element, @MagicConstant(flags = {DO_NOT_ADD_IMPORTS, UNCOMPLETE_CODE}) int flags) throws IncorrectOperationException;
+ public abstract PsiElement shortenClassReferences(@NotNull PsiElement element,
+ @MagicConstant(flags = {DO_NOT_ADD_IMPORTS, INCOMPLETE_CODE}) int flags) throws IncorrectOperationException;
@NotNull public abstract String getPrefixByVariableKind(VariableKind variableKind);
@NotNull public abstract String getSuffixByVariableKind(VariableKind variableKind);
* non-qualified names and adds import statements as necessary.
*
* @param element the element to shorten references in.
- * @return the element in the PSI tree after the shorten references operation corresponding
- * to the original element.
- * @throws com.intellij.util.IncorrectOperationException if the file to shorten references in is read-only.
+ * @return the element in the PSI tree after the shorten references operation corresponding to the original element.
+ * @throws IncorrectOperationException if the file to shorten references in is read-only.
*/
public abstract PsiElement shortenClassReferences(@NotNull PsiElement element) throws IncorrectOperationException;
* non-qualified names and adds import statements as necessary.
*
* @param element the element to shorten references in.
- * @param startOffset the start offset in the <b>element</b> of the part where class references are
- * shortened.
- * @param endOffset the end offset in the <b>element</b> of the part where class references are
- * shortened.
+ * @param startOffset the start offset in the <b>element</b> of the part where class references are shortened.
+ * @param endOffset the end offset in the <b>element</b> of the part where class references are shortened.
* @throws IncorrectOperationException if the file to shorten references in is read-only.
*/
public abstract void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException;
public abstract PsiImportList prepareOptimizeImportsResult(@NotNull PsiJavaFile file);
/**
- * Returns the kind of the specified variable (local, parameter, field, static field or static
- * final field).
+ * Returns the kind of the specified variable (local, parameter, field, static field or static final field).
*
* @param variable the variable to get the kind for.
* @return the variable kind.
/**
* Suggests a unique name for the variable used at the specified location.
*
- * @param baseNameInfo the base name info for the variable.
- * @param place the location where the variable will be used.
- * @param lookForward if true, the existing variables are searched in both directions; if false - only backward
+ * @param baseNameInfo the base name info for the variable.
+ * @param place the location where the variable will be used.
+ * @param lookForward if true, the existing variables are searched in both directions; if false - only backward
* @return the generated unique name
*/
@NotNull
/**
* Suggests a unique name for the variable used at the specified location.
*
- *
* @param baseNameInfo the base name info for the variable.
* @param place the location where the variable will be used.
- * @param ignorePlaceName if true and place is PsiNamedElement, place.getName() would be still treated as unique name
- * @param lookForward if true, the existing variables are searched in both directions; if false - only backward @return the generated unique name,
+ * @param ignorePlaceName if true and place is PsiNamedElement, place.getName() would be still treated as unique name
+ * @param lookForward if true, the existing variables are searched in both directions; if false - only backward
* @return the generated unique name
*/
- @NotNull public abstract SuggestedNameInfo suggestUniqueVariableName(@NotNull SuggestedNameInfo baseNameInfo,
- PsiElement place,
- boolean ignorePlaceName,
- boolean lookForward);
+ @NotNull
+ public abstract SuggestedNameInfo suggestUniqueVariableName(@NotNull SuggestedNameInfo baseNameInfo,
+ PsiElement place,
+ boolean ignorePlaceName,
+ boolean lookForward);
/**
* Replaces all references to Java classes in the contents of the specified element,
* with full-qualified references.
*
* @param element the element to replace the references in.
- * @return the element in the PSI tree after the qualify operation corresponding to the
- * original element.
+ * @return the element in the PSI tree after the qualify operation corresponding to the original element.
*/
public abstract PsiElement qualifyClassReferences(@NotNull PsiElement element);
* Removes unused import statements from the specified Java file.
*
* @param file the file to remove the import statements from.
- * @throws IncorrectOperationException if the operation fails for some reason (for example,
- * the file is read-only).
+ * @throws IncorrectOperationException if the operation fails for some reason (for example, the file is read-only).
*/
public abstract void removeRedundantImports(@NotNull PsiJavaFile file) throws IncorrectOperationException;
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public PsiElement shortenClassReferences(@NotNull PsiElement element,
- @MagicConstant(flags = {DO_NOT_ADD_IMPORTS, UNCOMPLETE_CODE}) int flags)
+ @MagicConstant(flags = {DO_NOT_ADD_IMPORTS, INCOMPLETE_CODE}) int flags)
throws IncorrectOperationException {
return null;
}
return operand;
}
- private enum BreakPoint {P1, P2, P3, P4}
+ private enum BreakPoint {P1, P2, P4}
- // todo[r.sh] make 'this', 'super' and 'class' reference expressions
@Nullable
- private PsiBuilder.Marker parsePrimary(final PsiBuilder builder, @Nullable final BreakPoint breakPoint, final int breakOffset) {
+ private PsiBuilder.Marker parsePrimary(PsiBuilder builder, @Nullable BreakPoint breakPoint, int breakOffset) {
PsiBuilder.Marker startMarker = builder.mark();
PsiBuilder.Marker expr = parsePrimaryExpressionStart(builder);
dotPos.drop();
expr = parseNew(builder, expr);
}
+ else if (dotTokenType == JavaTokenType.SUPER_KEYWORD && builder.lookAhead(1) == JavaTokenType.LPARENTH) {
+ dotPos.drop();
+ PsiBuilder.Marker refExpr = expr.precede();
+ builder.mark().done(JavaElementType.REFERENCE_PARAMETER_LIST);
+ builder.advanceLexer();
+ refExpr.done(JavaElementType.REFERENCE_EXPRESSION);
+ expr = refExpr;
+ }
else if (THIS_OR_SUPER.contains(dotTokenType) && exprType(expr) == JavaElementType.REFERENCE_EXPRESSION) {
if (breakPoint == BreakPoint.P2 && builder.getCurrentOffset() == breakOffset) {
dotPos.rollbackTo();
return expr;
}
- final PsiBuilder.Marker copy = startMarker.precede();
- final int offset = builder.getCurrentOffset();
+ PsiBuilder.Marker copy = startMarker.precede();
+ int offset = builder.getCurrentOffset();
startMarker.rollbackTo();
- final PsiBuilder.Marker ref = myParser.getReferenceParser().parseJavaCodeReference(builder, false, true, false, false);
+ PsiBuilder.Marker ref = myParser.getReferenceParser().parseJavaCodeReference(builder, false, true, false, false);
if (ref == null || builder.getTokenType() != JavaTokenType.DOT || builder.getCurrentOffset() != dotOffset) {
copy.rollbackTo();
return parsePrimary(builder, BreakPoint.P2, offset);
expr = ref.precede();
expr.done(dotTokenType == JavaTokenType.THIS_KEYWORD ? JavaElementType.THIS_EXPRESSION : JavaElementType.SUPER_EXPRESSION);
}
- else if (dotTokenType == JavaTokenType.SUPER_KEYWORD) {
- dotPos.drop();
- final PsiBuilder.Marker refExpr = expr.precede();
- builder.mark().done(JavaElementType.REFERENCE_PARAMETER_LIST);
- builder.advanceLexer();
- refExpr.done(JavaElementType.REFERENCE_EXPRESSION);
- expr = refExpr;
- }
else {
dotPos.drop();
- final PsiBuilder.Marker refExpr = expr.precede();
+ PsiBuilder.Marker refExpr = expr.precede();
+
myParser.getReferenceParser().parseReferenceParameterList(builder, false, false);
if (!expectOrError(builder, ID_OR_SUPER, "expected.identifier")) {
}
else if (tokenType == JavaTokenType.LPARENTH) {
if (exprType(expr) != JavaElementType.REFERENCE_EXPRESSION) {
- if (exprType(expr) == JavaElementType.SUPER_EXPRESSION) {
- if (breakPoint == BreakPoint.P3) {
- startMarker.drop();
- return expr;
- }
-
- final PsiBuilder.Marker copy = startMarker.precede();
- startMarker.rollbackTo();
-
- final PsiBuilder.Marker qualifier = parsePrimaryExpressionStart(builder);
- if (qualifier != null) {
- final PsiBuilder.Marker refExpr = qualifier.precede();
- if (builder.getTokenType() == JavaTokenType.DOT) {
- builder.advanceLexer();
- if (builder.getTokenType() == JavaTokenType.SUPER_KEYWORD) {
- builder.advanceLexer();
- refExpr.done(JavaElementType.REFERENCE_EXPRESSION);
- expr = refExpr;
- startMarker = copy;
- continue;
- }
- }
- }
-
- copy.rollbackTo();
- return parsePrimary(builder, BreakPoint.P3, -1);
- }
- else {
- startMarker.drop();
- return expr;
- }
+ startMarker.drop();
+ return expr;
}
- final PsiBuilder.Marker callExpr = expr.precede();
+ PsiBuilder.Marker callExpr = expr.precede();
parseArgumentList(builder);
callExpr.done(JavaElementType.METHOD_CALL_EXPRESSION);
expr = callExpr;
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
return TargetType.UNKNOWN;
}
- // todo[r.sh] cache?
@Nullable
public static Set<TargetType> getAnnotationTargets(@NotNull PsiClass annotationType) {
if (!annotationType.isAnnotationType()) return null;
PsiUtilCore.ensureValid(expression);
PsiUtil.ensureValidType(type);
- PsiExpression toplevel = expression;
- while (toplevel.getParent() instanceof PsiArrayAccessExpression &&
- ((PsiArrayAccessExpression)toplevel.getParent()).getArrayExpression() == toplevel) {
- toplevel = (PsiExpression)toplevel.getParent();
+ PsiExpression topLevel = expression;
+ while (topLevel.getParent() instanceof PsiArrayAccessExpression &&
+ ((PsiArrayAccessExpression)topLevel.getParent()).getArrayExpression() == topLevel) {
+ topLevel = (PsiExpression)topLevel.getParent();
}
- if (toplevel instanceof PsiArrayAccessExpression && !PsiUtil.isAccessedForWriting(toplevel)) {
+ if (topLevel instanceof PsiArrayAccessExpression && !PsiUtil.isAccessedForWriting(topLevel)) {
return PsiUtil.captureToplevelWildcards(type, expression);
}
- final PsiType normalized = doNormalizeWildcardByPosition(type, expression, toplevel);
+ final PsiType normalized = doNormalizeWildcardByPosition(type, expression, topLevel);
LOG.assertTrue(normalized.isValid(), type);
- if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(toplevel)) {
+ if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(topLevel)) {
return PsiUtil.captureToplevelWildcards(normalized, expression);
}
return normalized;
}
- private static PsiType doNormalizeWildcardByPosition(final PsiType type, @NotNull PsiExpression expression, final PsiExpression toplevel) {
+ private static PsiType doNormalizeWildcardByPosition(PsiType type, @NotNull PsiExpression expression, PsiExpression topLevel) {
if (type instanceof PsiCapturedWildcardType) {
final PsiWildcardType wildcardType = ((PsiCapturedWildcardType)type).getWildcard();
if (expression instanceof PsiReferenceExpression && LambdaUtil.isLambdaReturnExpression(expression)) {
return type;
}
- if (PsiUtil.isAccessedForWriting(toplevel)) {
+ if (PsiUtil.isAccessedForWriting(topLevel)) {
return wildcardType.isSuper() ? wildcardType.getBound() : PsiCapturedWildcardType.create(wildcardType, expression);
}
else {
final PsiType upperBound = ((PsiCapturedWildcardType)type).getUpperBound();
- return upperBound instanceof PsiWildcardType ? doNormalizeWildcardByPosition(upperBound, expression, toplevel) : upperBound;
+ return upperBound instanceof PsiWildcardType ? doNormalizeWildcardByPosition(upperBound, expression, topLevel) : upperBound;
}
}
if (type instanceof PsiWildcardType) {
final PsiWildcardType wildcardType = (PsiWildcardType)type;
- if (PsiUtil.isAccessedForWriting(toplevel)) {
+ if (PsiUtil.isAccessedForWriting(topLevel)) {
return wildcardType.isSuper() ? wildcardType.getBound() : PsiCapturedWildcardType.create(wildcardType, expression);
}
else {
}
else if (type instanceof PsiArrayType) {
final PsiType componentType = ((PsiArrayType)type).getComponentType();
- final PsiType normalizedComponentType = doNormalizeWildcardByPosition(componentType, expression, toplevel);
+ final PsiType normalizedComponentType = doNormalizeWildcardByPosition(componentType, expression, topLevel);
if (normalizedComponentType != componentType) {
return normalizedComponentType.createArrayType();
}
@Nullable String attributeName,
@Nullable PsiAnnotationMemberValue value,
@NotNull PairFunction<Project, String, PsiAnnotation> annotationCreator) {
- final PsiAnnotationMemberValue existing = psiAnnotation.findDeclaredAttributeValue(attributeName);
+ PsiAnnotationMemberValue existing = psiAnnotation.findDeclaredAttributeValue(attributeName);
if (value == null) {
if (existing == null) {
return null;
}
existing.getParent().delete();
- } else {
+ }
+ else {
if (existing != null) {
((PsiNameValuePair)existing.getParent()).setValue(value);
- } else {
- final PsiNameValuePair[] attributes = psiAnnotation.getParameterList().getAttributes();
- if (attributes.length == 1 && attributes[0].getName() == null) {
- attributes[0].replace(createNameValuePair(attributes[0].getValue(), PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME + "=", annotationCreator));
+ }
+ else {
+ PsiNameValuePair[] attributes = psiAnnotation.getParameterList().getAttributes();
+ if (attributes.length == 1) {
+ PsiNameValuePair attribute = attributes[0];
+ if (attribute.getName() == null) {
+ PsiAnnotationMemberValue defValue = attribute.getValue();
+ assert defValue != null : attribute;
+ attribute.replace(createNameValuePair(defValue, PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME + "=", annotationCreator));
+ }
}
boolean allowNoName = attributes.length == 0 && ("value".equals(attributeName) || null == attributeName);
final String namePrefix;
if (allowNoName) {
namePrefix = "";
- } else {
+ }
+ else {
namePrefix = attributeName + "=";
}
psiAnnotation.getParameterList().addBefore(createNameValuePair(value, namePrefix, annotationCreator), null);
if (typeName.indexOf('<') != -1 || typeName.indexOf('[') != -1 || typeName.indexOf('.') == -1) {
try {
return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createTypeFromText(typeName, context);
- } catch(Exception ex) {} // invalid syntax will produce unresolved class type
+ }
+ catch(Exception ignored) { } // invalid syntax will produce unresolved class type
}
PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(typeName, context.getResolveScope());
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
if (!preserveQualification) {
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
- ref = (PsiJavaCodeReferenceElement)codeStyleManager.shortenClassReferences(ref, JavaCodeStyleManager.UNCOMPLETE_CODE);
+ ref = (PsiJavaCodeReferenceElement)codeStyleManager.shortenClassReferences(ref, JavaCodeStyleManager.INCOMPLETE_CODE);
}
return ref;
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
getTreeParent().replaceChildInternal(this, (TreeElement)ref.getNode());
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(manager.getProject());
if (!preserveQualification) {
- ref = (PsiExpression)codeStyleManager.shortenClassReferences(ref, JavaCodeStyleManager.UNCOMPLETE_CODE);
+ ref = (PsiExpression)codeStyleManager.shortenClassReferences(ref, JavaCodeStyleManager.INCOMPLETE_CODE);
}
return ref;
}
<Z> void foo(I3<Z> s) { }
void bar() {
- foo<error descr="Ambiguous method call: both 'AmbiguityRawGenerics.foo(I1)' and 'AmbiguityRawGenerics.foo(I2)' match">(()-> { throw new RuntimeException(); })</error>;
+ <error descr="Ambiguous method call: both 'AmbiguityRawGenerics.foo(I1)' and 'AmbiguityRawGenerics.foo(I2)' match">foo</error>(()-> { throw new RuntimeException(); });
}
}
\ No newline at end of file
public interface IDEA99969 {
default IntStream distinct(Stream s) {
- return s.map(i -> <error descr="Inconvertible types; cannot cast '<lambda parameter>' to 'int'">(int) i</error>);
+ return s.<error descr="Ambiguous method call: both 'Stream.map(Function)' and 'Stream.map(IntFunction)' match">map</error>(i -> <error descr="Inconvertible types; cannot cast '<lambda parameter>' to 'int'">(int) i</error>);
}
}
interface Stream<T> {