Unnamed: 0
int64 0
1.65k
| func
stringlengths 33
161k
| target
bool 2
classes | project
stringlengths 82
187
|
---|---|---|---|
0 | public class AndroidBuildHookProvider implements ICeylonBuildHookProvider {
private static final class AndroidCeylonBuildHook extends CeylonBuildHook {
public static final String CEYLON_GENERATED_ARCHIVES_PREFIX = "ceylonGenerated-";
public static final String CEYLON_GENERATED_CLASSES_ARCHIVE = CEYLON_GENERATED_ARCHIVES_PREFIX + "CeylonClasses.jar";
public static final String ANDROID_LIBS_DIRECTORY = "libs";
public static final String[] ANDROID_PROVIDED_PACKAGES = new String[] {"android.app"};
public static final String[] UNNECESSARY_CEYLON_RUNTIME_LIBRARIES = new String[] {"org.jboss.modules",
"com.redhat.ceylon.module-resolver",
"com.redhat.ceylon.common"};
boolean areModulesChanged = false;
boolean hasAndroidNature = false;
boolean isReentrantBuild = false;
boolean isFullBuild = false;
WeakReference<IProgressMonitor> monitorRef = null;
WeakReference<IProject> projectRef = null;
private IProgressMonitor getMonitor() {
if (monitorRef != null) {
return monitorRef.get();
}
return null;
}
private IProject getProject() {
if (projectRef != null) {
return projectRef.get();
}
return null;
}
@Override
protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args,
IProject project, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException {
try {
hasAndroidNature = project.hasNature("com.android.ide.eclipse.adt.AndroidNature");
} catch (CoreException e) {
hasAndroidNature= false;
}
areModulesChanged = false;
monitorRef = new WeakReference<IProgressMonitor>(monitor);
projectRef = new WeakReference<IProject>(project);
isReentrantBuild = args.containsKey(CeylonBuilder.BUILDER_ID + ".reentrant");
if (hasAndroidNature) {
IJavaProject javaProject =JavaCore.create(project);
boolean CeylonCPCFound = false;
IMarker[] buildMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO);
for (IMarker m: buildMarkers) {
if (CeylonAndroidPlugin.PLUGIN_ID.equals(m.getAttribute(IMarker.SOURCE_ID))) {
m.delete();
}
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (CeylonClasspathUtil.isProjectModulesClasspathContainer(entry.getPath())) {
CeylonCPCFound = true;
} else {
IPath containerPath = entry.getPath();
int size = containerPath.segmentCount();
if (size > 0) {
if (containerPath.segment(0).equals("com.android.ide.eclipse.adt.LIBRARIES") ||
containerPath.segment(0).equals("com.android.ide.eclipse.adt.DEPENDENCIES")) {
if (! CeylonCPCFound) {
//if the ClassPathContainer is missing, add an error
IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER);
marker.setAttribute(IMarker.SOURCE_ID, CeylonAndroidPlugin.PLUGIN_ID);
marker.setAttribute(IMarker.MESSAGE, "Invalid Java Build Path for project " + project.getName() + " : " +
"The Ceylon libraries should be set before the Android libraries in the Java Build Path. " +
"Move down the 'Android Private Libraries' and 'Android Dependencies' after the Ceylon Libraries " +
"in the 'Order and Export' tab of the 'Java Build Path' properties page.");
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
marker.setAttribute(IMarker.LOCATION, "Java Build Path Order");
throw new CoreException(new Status(IStatus.CANCEL, CeylonAndroidPlugin.PLUGIN_ID, IResourceStatus.OK,
"Build cancelled because of invalid build path", null));
}
}
}
}
}
}
}
@Override
protected void deltasAnalyzed(List<IResourceDelta> currentDeltas,
BooleanHolder sourceModified,
BooleanHolder mustDoFullBuild,
BooleanHolder mustResolveClasspathContainer,
boolean mustContinueBuild) {
if (mustContinueBuild && hasAndroidNature) {
CeylonBuilder.waitForUpToDateJavaModel(10000, getProject(), getMonitor());
}
}
@Override
protected void setAndRefreshClasspathContainer() {
areModulesChanged = true;
}
@Override
protected void doFullBuild() {
isFullBuild = true;
}
@Override
protected void afterGeneratingBinaries() {
IProject project = getProject();
if (project == null) {
return;
}
if (! isReentrantBuild && hasAndroidNature) {
try {
File libsDirectory = project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toFile();
if (!libsDirectory.exists()) {
libsDirectory.mkdirs();
}
Files.walkFileTree(java.nio.file.FileSystems.getDefault().getPath(libsDirectory.getAbsolutePath()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException
{
if (areModulesChanged || isFullBuild ?
path.getFileName().toString().startsWith(CEYLON_GENERATED_ARCHIVES_PREFIX) :
path.getFileName().toString().equals(CEYLON_GENERATED_CLASSES_ARCHIVE)) {
try {
Files.delete(path);
} catch(IOException ioe) {
CeylonAndroidPlugin.logError("Could not delete a ceylon jar from the android libs directory", ioe);
}
}
return FileVisitResult.CONTINUE;
}
});
final List<IFile> filesToAddInArchive = new LinkedList<>();
final IFolder ceylonOutputFolder = CeylonBuilder.getCeylonClassesOutputFolder(project);
ceylonOutputFolder.refreshLocal(DEPTH_INFINITE, getMonitor());
ceylonOutputFolder.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (resource instanceof IFile) {
filesToAddInArchive.add((IFile)resource);
}
return true;
}
});
if (! filesToAddInArchive.isEmpty()) {
JarPackageData jarPkgData = new JarPackageData();
jarPkgData.setBuildIfNeeded(false);
jarPkgData.setOverwrite(true);
jarPkgData.setGenerateManifest(true);
jarPkgData.setExportClassFiles(true);
jarPkgData.setCompress(true);
jarPkgData.setJarLocation(project.findMember("libs").getLocation().append(CEYLON_GENERATED_CLASSES_ARCHIVE).makeAbsolute());
jarPkgData.setElements(filesToAddInArchive.toArray());
JarWriter3 jarWriter = null;
try {
jarWriter = new JarWriter3(jarPkgData, null);
for (IFile fileToAdd : filesToAddInArchive) {
jarWriter.write(fileToAdd, fileToAdd.getFullPath().makeRelativeTo(ceylonOutputFolder.getFullPath()));
}
} finally {
if (jarWriter != null) {
jarWriter.close();
}
}
}
if (isFullBuild || areModulesChanged) {
List<Path> jarsToCopyToLib = new LinkedList<>();
IJavaProject javaProject = JavaCore.create(project);
List<IClasspathContainer> cpContainers = CeylonClasspathUtil.getCeylonClasspathContainers(javaProject);
if (cpContainers != null) {
for (IClasspathContainer cpc : cpContainers) {
for (IClasspathEntry cpe : cpc.getClasspathEntries()) {
if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
Path path = FileSystems.getDefault().getPath(cpe.getPath().toOSString());
if (! Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) &&
Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
boolean isAndroidProvidedJar = false;
providerPackageFound:
for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
if (javaProject.isOnClasspath(root) &&
cpe.equals(root.getResolvedClasspathEntry())) {
for (String providedPackage : ANDROID_PROVIDED_PACKAGES) {
if (root.getPackageFragment(providedPackage).exists()) {
isAndroidProvidedJar = true;
break providerPackageFound;
}
}
}
}
if (! isAndroidProvidedJar) {
jarsToCopyToLib.add(path);
}
}
}
}
}
}
for (String runtimeJar : CeylonPlugin.getRuntimeRequiredJars()) {
boolean isNecessary = true;
for (String unnecessaryRuntime : UNNECESSARY_CEYLON_RUNTIME_LIBRARIES) {
if (runtimeJar.contains(unnecessaryRuntime + "-")) {
isNecessary = false;
break;
}
}
if (isNecessary) {
jarsToCopyToLib.add(FileSystems.getDefault().getPath(runtimeJar));
}
}
for (Path archive : jarsToCopyToLib) {
String newName = CEYLON_GENERATED_ARCHIVES_PREFIX + archive.getFileName();
if (newName.endsWith(ArtifactContext.CAR)) {
newName = newName.replaceFirst("\\.car$", "\\.jar");
}
Path destinationPath = FileSystems.getDefault().getPath(project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toOSString(), newName);
try {
Files.copy(archive, destinationPath);
} catch (IOException e) {
CeylonAndroidPlugin.logError("Could not copy a ceylon jar to the android libs directory", e);
}
}
}
project.findMember(ANDROID_LIBS_DIRECTORY).refreshLocal(DEPTH_INFINITE, getMonitor());
} catch (Exception e) {
CeylonAndroidPlugin.logError("Error during the generation of ceylon-derived archives for Android", e);
}
}
}
@Override
protected void endBuild() {
areModulesChanged = false;
hasAndroidNature = false;
isReentrantBuild = false;
isFullBuild = false;
monitorRef = null;
projectRef = null;
}
}
private static CeylonBuildHook buildHook = new AndroidCeylonBuildHook();
@Override
public CeylonBuildHook getHook() {
return buildHook;
}
} | false | plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.java |
1 | private static final class AndroidCeylonBuildHook extends CeylonBuildHook {
public static final String CEYLON_GENERATED_ARCHIVES_PREFIX = "ceylonGenerated-";
public static final String CEYLON_GENERATED_CLASSES_ARCHIVE = CEYLON_GENERATED_ARCHIVES_PREFIX + "CeylonClasses.jar";
public static final String ANDROID_LIBS_DIRECTORY = "libs";
public static final String[] ANDROID_PROVIDED_PACKAGES = new String[] {"android.app"};
public static final String[] UNNECESSARY_CEYLON_RUNTIME_LIBRARIES = new String[] {"org.jboss.modules",
"com.redhat.ceylon.module-resolver",
"com.redhat.ceylon.common"};
boolean areModulesChanged = false;
boolean hasAndroidNature = false;
boolean isReentrantBuild = false;
boolean isFullBuild = false;
WeakReference<IProgressMonitor> monitorRef = null;
WeakReference<IProject> projectRef = null;
private IProgressMonitor getMonitor() {
if (monitorRef != null) {
return monitorRef.get();
}
return null;
}
private IProject getProject() {
if (projectRef != null) {
return projectRef.get();
}
return null;
}
@Override
protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args,
IProject project, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException {
try {
hasAndroidNature = project.hasNature("com.android.ide.eclipse.adt.AndroidNature");
} catch (CoreException e) {
hasAndroidNature= false;
}
areModulesChanged = false;
monitorRef = new WeakReference<IProgressMonitor>(monitor);
projectRef = new WeakReference<IProject>(project);
isReentrantBuild = args.containsKey(CeylonBuilder.BUILDER_ID + ".reentrant");
if (hasAndroidNature) {
IJavaProject javaProject =JavaCore.create(project);
boolean CeylonCPCFound = false;
IMarker[] buildMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO);
for (IMarker m: buildMarkers) {
if (CeylonAndroidPlugin.PLUGIN_ID.equals(m.getAttribute(IMarker.SOURCE_ID))) {
m.delete();
}
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (CeylonClasspathUtil.isProjectModulesClasspathContainer(entry.getPath())) {
CeylonCPCFound = true;
} else {
IPath containerPath = entry.getPath();
int size = containerPath.segmentCount();
if (size > 0) {
if (containerPath.segment(0).equals("com.android.ide.eclipse.adt.LIBRARIES") ||
containerPath.segment(0).equals("com.android.ide.eclipse.adt.DEPENDENCIES")) {
if (! CeylonCPCFound) {
//if the ClassPathContainer is missing, add an error
IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER);
marker.setAttribute(IMarker.SOURCE_ID, CeylonAndroidPlugin.PLUGIN_ID);
marker.setAttribute(IMarker.MESSAGE, "Invalid Java Build Path for project " + project.getName() + " : " +
"The Ceylon libraries should be set before the Android libraries in the Java Build Path. " +
"Move down the 'Android Private Libraries' and 'Android Dependencies' after the Ceylon Libraries " +
"in the 'Order and Export' tab of the 'Java Build Path' properties page.");
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
marker.setAttribute(IMarker.LOCATION, "Java Build Path Order");
throw new CoreException(new Status(IStatus.CANCEL, CeylonAndroidPlugin.PLUGIN_ID, IResourceStatus.OK,
"Build cancelled because of invalid build path", null));
}
}
}
}
}
}
}
@Override
protected void deltasAnalyzed(List<IResourceDelta> currentDeltas,
BooleanHolder sourceModified,
BooleanHolder mustDoFullBuild,
BooleanHolder mustResolveClasspathContainer,
boolean mustContinueBuild) {
if (mustContinueBuild && hasAndroidNature) {
CeylonBuilder.waitForUpToDateJavaModel(10000, getProject(), getMonitor());
}
}
@Override
protected void setAndRefreshClasspathContainer() {
areModulesChanged = true;
}
@Override
protected void doFullBuild() {
isFullBuild = true;
}
@Override
protected void afterGeneratingBinaries() {
IProject project = getProject();
if (project == null) {
return;
}
if (! isReentrantBuild && hasAndroidNature) {
try {
File libsDirectory = project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toFile();
if (!libsDirectory.exists()) {
libsDirectory.mkdirs();
}
Files.walkFileTree(java.nio.file.FileSystems.getDefault().getPath(libsDirectory.getAbsolutePath()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException
{
if (areModulesChanged || isFullBuild ?
path.getFileName().toString().startsWith(CEYLON_GENERATED_ARCHIVES_PREFIX) :
path.getFileName().toString().equals(CEYLON_GENERATED_CLASSES_ARCHIVE)) {
try {
Files.delete(path);
} catch(IOException ioe) {
CeylonAndroidPlugin.logError("Could not delete a ceylon jar from the android libs directory", ioe);
}
}
return FileVisitResult.CONTINUE;
}
});
final List<IFile> filesToAddInArchive = new LinkedList<>();
final IFolder ceylonOutputFolder = CeylonBuilder.getCeylonClassesOutputFolder(project);
ceylonOutputFolder.refreshLocal(DEPTH_INFINITE, getMonitor());
ceylonOutputFolder.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (resource instanceof IFile) {
filesToAddInArchive.add((IFile)resource);
}
return true;
}
});
if (! filesToAddInArchive.isEmpty()) {
JarPackageData jarPkgData = new JarPackageData();
jarPkgData.setBuildIfNeeded(false);
jarPkgData.setOverwrite(true);
jarPkgData.setGenerateManifest(true);
jarPkgData.setExportClassFiles(true);
jarPkgData.setCompress(true);
jarPkgData.setJarLocation(project.findMember("libs").getLocation().append(CEYLON_GENERATED_CLASSES_ARCHIVE).makeAbsolute());
jarPkgData.setElements(filesToAddInArchive.toArray());
JarWriter3 jarWriter = null;
try {
jarWriter = new JarWriter3(jarPkgData, null);
for (IFile fileToAdd : filesToAddInArchive) {
jarWriter.write(fileToAdd, fileToAdd.getFullPath().makeRelativeTo(ceylonOutputFolder.getFullPath()));
}
} finally {
if (jarWriter != null) {
jarWriter.close();
}
}
}
if (isFullBuild || areModulesChanged) {
List<Path> jarsToCopyToLib = new LinkedList<>();
IJavaProject javaProject = JavaCore.create(project);
List<IClasspathContainer> cpContainers = CeylonClasspathUtil.getCeylonClasspathContainers(javaProject);
if (cpContainers != null) {
for (IClasspathContainer cpc : cpContainers) {
for (IClasspathEntry cpe : cpc.getClasspathEntries()) {
if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
Path path = FileSystems.getDefault().getPath(cpe.getPath().toOSString());
if (! Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) &&
Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
boolean isAndroidProvidedJar = false;
providerPackageFound:
for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
if (javaProject.isOnClasspath(root) &&
cpe.equals(root.getResolvedClasspathEntry())) {
for (String providedPackage : ANDROID_PROVIDED_PACKAGES) {
if (root.getPackageFragment(providedPackage).exists()) {
isAndroidProvidedJar = true;
break providerPackageFound;
}
}
}
}
if (! isAndroidProvidedJar) {
jarsToCopyToLib.add(path);
}
}
}
}
}
}
for (String runtimeJar : CeylonPlugin.getRuntimeRequiredJars()) {
boolean isNecessary = true;
for (String unnecessaryRuntime : UNNECESSARY_CEYLON_RUNTIME_LIBRARIES) {
if (runtimeJar.contains(unnecessaryRuntime + "-")) {
isNecessary = false;
break;
}
}
if (isNecessary) {
jarsToCopyToLib.add(FileSystems.getDefault().getPath(runtimeJar));
}
}
for (Path archive : jarsToCopyToLib) {
String newName = CEYLON_GENERATED_ARCHIVES_PREFIX + archive.getFileName();
if (newName.endsWith(ArtifactContext.CAR)) {
newName = newName.replaceFirst("\\.car$", "\\.jar");
}
Path destinationPath = FileSystems.getDefault().getPath(project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toOSString(), newName);
try {
Files.copy(archive, destinationPath);
} catch (IOException e) {
CeylonAndroidPlugin.logError("Could not copy a ceylon jar to the android libs directory", e);
}
}
}
project.findMember(ANDROID_LIBS_DIRECTORY).refreshLocal(DEPTH_INFINITE, getMonitor());
} catch (Exception e) {
CeylonAndroidPlugin.logError("Error during the generation of ceylon-derived archives for Android", e);
}
}
}
@Override
protected void endBuild() {
areModulesChanged = false;
hasAndroidNature = false;
isReentrantBuild = false;
isFullBuild = false;
monitorRef = null;
projectRef = null;
}
} | false | plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.java |
2 | Files.walkFileTree(java.nio.file.FileSystems.getDefault().getPath(libsDirectory.getAbsolutePath()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException
{
if (areModulesChanged || isFullBuild ?
path.getFileName().toString().startsWith(CEYLON_GENERATED_ARCHIVES_PREFIX) :
path.getFileName().toString().equals(CEYLON_GENERATED_CLASSES_ARCHIVE)) {
try {
Files.delete(path);
} catch(IOException ioe) {
CeylonAndroidPlugin.logError("Could not delete a ceylon jar from the android libs directory", ioe);
}
}
return FileVisitResult.CONTINUE;
}
}); | false | plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.java |
3 | ceylonOutputFolder.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (resource instanceof IFile) {
filesToAddInArchive.add((IFile)resource);
}
return true;
}
}); | false | plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.java |
4 | public class CeylonAndroidPlugin extends AbstractUIPlugin {
public static final String PLUGIN_ID = "com.redhat.ceylon.eclipse.android.plugin";
private static CeylonAndroidPlugin plugin;
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
public static CeylonAndroidPlugin getDefault() {
return plugin;
}
public static void logInfo(String msg) {
plugin.getLog().log(new Status(IStatus.INFO, PLUGIN_ID, msg));
}
public static void logInfo(String msg, IOException e) {
plugin.getLog().log(new Status(IStatus.INFO, PLUGIN_ID, msg, e));
}
public static void logError(String msg, Exception e) {
plugin.getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, msg, e));
}
} | false | plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_CeylonAndroidPlugin.java |
5 | public class BrowserInformationControl extends AbstractInformationControl
implements IInformationControlExtension2, IDelayedInputChangeProvider {
/**
* Tells whether the SWT Browser widget and hence this information
* control is available.
*
* @param parent the parent component used for checking or <code>null</code> if none
* @return <code>true</code> if this control is available
*/
public static boolean isAvailable(Composite parent) {
if (!fgAvailabilityChecked) {
try {
Browser browser= new Browser(parent, SWT.NONE);
browser.dispose();
fgIsAvailable= true;
Slider sliderV= new Slider(parent, SWT.VERTICAL);
Slider sliderH= new Slider(parent, SWT.HORIZONTAL);
int width= sliderV.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
int height= sliderH.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
fgScrollBarSize= new Point(width, height);
sliderV.dispose();
sliderH.dispose();
} catch (SWTError er) {
fgIsAvailable= false;
} finally {
fgAvailabilityChecked= true;
}
}
return fgIsAvailable;
}
/**
* Minimal size constraints.
* @since 3.2
*/
private static final int MIN_WIDTH= 80;
private static final int MIN_HEIGHT= 50;
/**
* Availability checking cache.
*/
private static boolean fgIsAvailable= false;
private static boolean fgAvailabilityChecked= false;
/**
* Cached scroll bar width and height
* @since 3.4
*/
private static Point fgScrollBarSize;
/** The control's browser widget */
private Browser fBrowser;
/** Tells whether the browser has content */
private boolean fBrowserHasContent;
/** Text layout used to approximate size of content when rendered in browser */
private TextLayout fTextLayout;
/** Bold text style */
private TextStyle fBoldStyle;
private BrowserInput fInput;
/**
* <code>true</code> iff the browser has completed loading of the last
* input set via {@link #setInformation(String)}.
* @since 3.4
*/
private boolean fCompleted= false;
/**
* The listener to be notified when a delayed location changing event happened.
* @since 3.4
*/
private IInputChangedListener fDelayedInputChangeListener;
/**
* The listeners to be notified when the input changed.
* @since 3.4
*/
private ListenerList/*<IInputChangedListener>*/fInputChangeListeners= new ListenerList(ListenerList.IDENTITY);
/**
* The symbolic name of the font used for size computations, or <code>null</code> to use dialog font.
* @since 3.4
*/
private final String fSymbolicFontName;
/**
* Creates a browser information control with the given shell as parent.
*
* @param parent the parent shell
* @param symbolicFontName the symbolic name of the font used for size computations
* @param resizable <code>true</code> if the control should be resizable
* @since 3.4
*/
public BrowserInformationControl(Shell parent, String symbolicFontName,
boolean resizable) {
super(parent, resizable);
fSymbolicFontName= symbolicFontName;
create();
}
/**
* Creates a browser information control with the given shell as parent.
*
* @param parent the parent shell
* @param symbolicFontName the symbolic name of the font used for size computations
* @param statusFieldText the text to be used in the optional status field
* or <code>null</code> if the status field should be hidden
* @since 3.4
*/
public BrowserInformationControl(Shell parent, String symbolicFontName,
String statusFieldText) {
super(parent, statusFieldText);
fSymbolicFontName= symbolicFontName;
create();
}
/**
* Creates a browser information control with the given shell as parent.
*
* @param parent the parent shell
* @param symbolicFontName the symbolic name of the font used for size computations
* @param toolBarManager the manager or <code>null</code> if toolbar is not desired
* @since 3.4
*/
public BrowserInformationControl(Shell parent, String symbolicFontName,
ToolBarManager toolBarManager) {
super(parent, toolBarManager);
fSymbolicFontName= symbolicFontName;
create();
}
@Override
protected void createContent(Composite parent) {
fBrowser= new Browser(parent, SWT.NONE);
fBrowser.setJavascriptEnabled(false);
Display display= getShell().getDisplay();
fBrowser.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
fBrowser.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
//fBrowser.setBackground(color);
fBrowser.addProgressListener(new ProgressAdapter() {
@Override
public void completed(ProgressEvent event) {
fCompleted= true;
}
});
fBrowser.addOpenWindowListener(new OpenWindowListener() {
@Override
public void open(WindowEvent event) {
event.required= true; // Cancel opening of new windows
}
});
// Replace browser's built-in context menu with none
fBrowser.setMenu(new Menu(getShell(), SWT.NONE));
createTextLayout();
}
/**
* {@inheritDoc}
* @deprecated use {@link #setInput(Object)}
*/
@Override
public void setInformation(final String content) {
setInput(new BrowserInput(null) {
@Override
public String getHtml() {
return content;
}
@Override
public String getInputName() {
return "";
}
});
}
/**
* {@inheritDoc} This control can handle {@link String} and
* {@link BrowserInput}.
*/
@Override
public void setInput(Object input) {
Assert.isLegal(input == null ||
input instanceof String ||
input instanceof BrowserInput);
if (input instanceof String) {
setInformation((String)input);
return;
}
fInput= (BrowserInput) input;
String content= null;
if (fInput != null)
content= fInput.getHtml();
fBrowserHasContent= content != null && content.length() > 0;
if (!fBrowserHasContent)
content= "<html><body ></html>"; //$NON-NLS-1$
boolean RTL= (getShell().getStyle() & SWT.RIGHT_TO_LEFT) != 0;
boolean resizable= isResizable();
// The default "overflow:auto" would not result in a predictable width for the client area
// and the re-wrapping would cause visual noise
String[] styles= null;
if (RTL && resizable)
styles= new String[] { "direction:rtl;", "overflow:scroll;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
else if (RTL && !resizable)
styles= new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
else if (!resizable)
//XXX: In IE, "word-wrap: break-word;" causes bogus wrapping even in non-broken words :-(see e.g. Javadoc of String).
// Re-check whether we really still need this now that the Javadoc Hover header already sets this style.
styles= new String[] { "overflow:hidden;"/*, "word-wrap: break-word;"*/}; //$NON-NLS-1$
else
styles= new String[] { "overflow:scroll;" }; //$NON-NLS-1$
StringBuilder buffer= new StringBuilder(content);
HTMLPrinter.insertStyles(buffer, styles);
content= buffer.toString();
/*
* XXX: Should add some JavaScript here that shows something like
* "(continued...)" or "..." at the end of the visible area when the page overflowed
* with "overflow:hidden;".
*/
fCompleted= false;
fBrowser.setText(content);
Object[] listeners= fInputChangeListeners.getListeners();
for (int i= 0; i < listeners.length; i++)
((IInputChangedListener)listeners[i]).inputChanged(fInput);
}
@Override
public void setVisible(boolean visible) {
Shell shell= getShell();
if (shell.isVisible() == visible)
return;
if (!visible) {
super.setVisible(false);
setInput(null);
return;
}
/*
* The Browser widget flickers when made visible while it is not completely loaded.
* The fix is to delay the call to setVisible until either loading is completed
* (see ProgressListener in constructor), or a timeout has been reached.
*/
final Display display= shell.getDisplay();
// Make sure the display wakes from sleep after timeout:
display.timerExec(100, new Runnable() {
@Override
public void run() {
fCompleted= true;
}
});
while (!fCompleted) {
// Drive the event loop to process the events required to load the browser widget's contents:
if (!display.readAndDispatch()) {
display.sleep();
}
}
shell= getShell();
if (shell == null || shell.isDisposed())
return;
/*
* Avoids flickering when replacing hovers, especially on Vista in ON_CLICK mode.
* Causes flickering on GTK. Carbon does not care.
*/
if ("win32".equals(SWT.getPlatform())) //$NON-NLS-1$
shell.moveAbove(null);
super.setVisible(true);
}
@Override
public void setSize(int width, int height) {
fBrowser.setRedraw(false); // avoid flickering
try {
super.setSize(width, height);
} finally {
fBrowser.setRedraw(true);
}
}
/**
* Creates and initializes the text layout used
* to compute the size hint.
*
* @since 3.2
*/
private void createTextLayout() {
fTextLayout= new TextLayout(fBrowser.getDisplay());
// Initialize fonts
String symbolicFontName= fSymbolicFontName == null ? JFaceResources.DIALOG_FONT : fSymbolicFontName;
Font font= JFaceResources.getFont(symbolicFontName);
fTextLayout.setFont(font);
fTextLayout.setWidth(-1);
font= JFaceResources.getFontRegistry().getBold(symbolicFontName);
fBoldStyle= new TextStyle(font, null, null);
// Compute and set tab width
fTextLayout.setText(" "); //$NON-NLS-1$
int tabWidth= fTextLayout.getBounds().width;
fTextLayout.setTabs(new int[] { tabWidth });
fTextLayout.setText(""); //$NON-NLS-1$
}
@Override
protected void handleDispose() {
if (fTextLayout != null) {
fTextLayout.dispose();
fTextLayout= null;
}
fBrowser= null;
super.handleDispose();
}
@Override
public Point computeSizeHint() {
Point sizeConstraints = getSizeConstraints();
Rectangle trim = computeTrim();
//FIXME: The HTML2TextReader does not render <p> like a browser.
// Instead of inserting an empty line, it just adds a single line break.
// Furthermore, the indentation of <dl><dd> elements is too small (e.g with a long @see line)
TextPresentation presentation= new TextPresentation();
HTML2TextReader reader= new HTML2TextReader(new StringReader(fInput.getHtml()), presentation);
String text;
try {
text= reader.getString();
} catch (IOException e) {
text= "";
}
finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
fTextLayout.setText(text);
fTextLayout.setWidth(sizeConstraints==null ? SWT.DEFAULT : sizeConstraints.x-trim.width);
@SuppressWarnings("unchecked")
Iterator<StyleRange> iter = presentation.getAllStyleRangeIterator();
while (iter.hasNext()) {
StyleRange sr = iter.next();
if (sr.fontStyle == SWT.BOLD)
fTextLayout.setStyle(fBoldStyle, sr.start, sr.start + sr.length);
}
Rectangle bounds = fTextLayout.getBounds(); // does not return minimum width, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=217446
int lineCount = fTextLayout.getLineCount();
int textWidth = 0;
for (int i=0; i<lineCount; i++) {
Rectangle rect = fTextLayout.getLineBounds(i);
int lineWidth = rect.x + rect.width;
if (i==0) {
lineWidth *= 1.25; //to accommodate it is not only bold but also monospace
lineWidth += 20;
}
textWidth = Math.max(textWidth, lineWidth);
}
bounds.width = textWidth;
fTextLayout.setText("");
int minWidth = textWidth;
int minHeight = trim.height + bounds.height;
// Add some air to accommodate for different browser renderings
minWidth += 30;
minHeight += 60;
// Apply max size constraints
if (sizeConstraints!=null) {
if (sizeConstraints.x!=SWT.DEFAULT)
minWidth = Math.min(sizeConstraints.x, minWidth + trim.width);
if (sizeConstraints.y!=SWT.DEFAULT)
minHeight = Math.min(sizeConstraints.y, minHeight);
}
// Ensure minimal size
int width = Math.max(MIN_WIDTH, minWidth);
int height = Math.max(MIN_HEIGHT, minHeight);
return new Point(width, height);
}
@Override
public Rectangle computeTrim() {
Rectangle trim= super.computeTrim();
if (isResizable() && fgScrollBarSize!=null) {
boolean RTL= (getShell().getStyle() & SWT.RIGHT_TO_LEFT) != 0;
if (RTL) {
trim.x-= fgScrollBarSize.x;
}
trim.width+= fgScrollBarSize.x;
trim.height+= fgScrollBarSize.y;
}
return trim;
}
/**
* Adds the listener to the collection of listeners who will be
* notified when the current location has changed or is about to change.
*
* @param listener the location listener
* @since 3.4
*/
public void addLocationListener(LocationListener listener) {
fBrowser.addLocationListener(listener);
}
@Override
public void setForegroundColor(Color foreground) {
super.setForegroundColor(foreground);
fBrowser.setForeground(foreground);
}
@Override
public void setBackgroundColor(Color background) {
super.setBackgroundColor(background);
fBrowser.setBackground(background);
}
@Override
public boolean hasContents() {
return fBrowserHasContent;
}
/**
* Adds a listener for input changes to this input change provider.
* Has no effect if an identical listener is already registered.
*
* @param inputChangeListener the listener to add
* @since 3.4
*/
public void addInputChangeListener(IInputChangedListener inputChangeListener) {
Assert.isNotNull(inputChangeListener);
fInputChangeListeners.add(inputChangeListener);
}
/**
* Removes the given input change listener from this input change provider.
* Has no effect if an identical listener is not registered.
*
* @param inputChangeListener the listener to remove
* @since 3.4
*/
public void removeInputChangeListener(IInputChangedListener inputChangeListener) {
fInputChangeListeners.remove(inputChangeListener);
}
@Override
public void setDelayedInputChangeListener(IInputChangedListener inputChangeListener) {
fDelayedInputChangeListener= inputChangeListener;
}
/**
* Tells whether a delayed input change listener is registered.
*
* @return <code>true</code> iff a delayed input change
* listener is currently registered
* @since 3.4
*/
public boolean hasDelayedInputChangeListener() {
return fDelayedInputChangeListener != null;
}
/**
* Notifies listeners of a delayed input change.
*
* @param newInput the new input, or <code>null</code> to request cancellation
* @since 3.4
*/
public void notifyDelayedInputChange(Object newInput) {
if (fDelayedInputChangeListener != null)
fDelayedInputChangeListener.inputChanged(newInput);
}
@Override
public String toString() {
String style= (getShell().getStyle() & SWT.RESIZE) == 0 ? "fixed" : "resizeable"; //$NON-NLS-1$ //$NON-NLS-2$
return super.toString() + " - style: " + style; //$NON-NLS-1$
}
/**
* @return the current browser input or <code>null</code>
*/
public BrowserInput getInput() {
return fInput;
}
@Override
public Point computeSizeConstraints(int widthInChars, int heightInChars) {
if (fSymbolicFontName == null)
return null;
GC gc= new GC(fBrowser);
Font font= fSymbolicFontName == null ? JFaceResources.getDialogFont() : JFaceResources.getFont(fSymbolicFontName);
gc.setFont(font);
int width= gc.getFontMetrics().getAverageCharWidth();
int height= gc.getFontMetrics().getHeight();
gc.dispose();
return new Point(widthInChars * width, heightInChars * height);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java |
6 | fBrowser.addProgressListener(new ProgressAdapter() {
@Override
public void completed(ProgressEvent event) {
fCompleted= true;
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java |
7 | fBrowser.addOpenWindowListener(new OpenWindowListener() {
@Override
public void open(WindowEvent event) {
event.required= true; // Cancel opening of new windows
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java |
8 | setInput(new BrowserInput(null) {
@Override
public String getHtml() {
return content;
}
@Override
public String getInputName() {
return "";
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java |
9 | display.timerExec(100, new Runnable() {
@Override
public void run() {
fCompleted= true;
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java |
10 | public abstract class BrowserInput {
private final BrowserInput fPrevious;
private BrowserInput fNext;
/**
* Create a new Browser input.
*
* @param previous the input previous to this or <code>null</code> if this is the first
*/
public BrowserInput(BrowserInput previous) {
fPrevious= previous;
if (previous != null)
previous.fNext= this;
}
/**
* The previous input or <code>null</code> if this
* is the first.
*
* @return the previous input or <code>null</code>
*/
public BrowserInput getPrevious() {
return fPrevious;
}
/**
* The next input or <code>null</code> if this
* is the last.
*
* @return the next input or <code>null</code>
*/
public BrowserInput getNext() {
return fNext;
}
/**
* @return the HTML contents
*/
public abstract String getHtml();
/**
* A human readable name for the input.
*
* @return the input name
*/
public abstract String getInputName();
/**
* Returns the HTML from {@link #getHtml()}.
* This is a fallback mode for platforms where the {@link BrowserInformationControl}
* is not available and this input is passed to a {@link DefaultInformationControl}.
*
* @return {@link #getHtml()}
*/
public String toString() {
return getHtml();
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInput.java |
11 | class BasicCompletionProposal extends CompletionProposal {
static void addImportProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, Scope scope) {
result.add(new BasicCompletionProposal(offset, prefix,
dec.getName(), escapeName(dec), dec, cpc));
}
static void addDocLinkProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, Scope scope) {
//for doc links, propose both aliases and unaliased qualified form
//we don't need to do this in code b/c there is no fully-qualified form
String name = dec.getName();
String aliasedName = dec.getName(cpc.getRootNode().getUnit());
if (!name.equals(aliasedName)) {
result.add(new BasicCompletionProposal(offset, prefix,
aliasedName, aliasedName, dec, cpc));
}
result.add(new BasicCompletionProposal(offset, prefix,
name, getTextForDocLink(cpc, dec), dec, cpc));
}
private final CeylonParseController cpc;
private final Declaration declaration;
private BasicCompletionProposal(int offset, String prefix,
String desc, String text, Declaration dec,
CeylonParseController cpc) {
super(offset, prefix, getImageForDeclaration(dec),
desc, text);
this.cpc = cpc;
this.declaration = dec;
}
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, declaration);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_BasicCompletionProposal.java |
12 | public class CeylonCompletionProcessor implements IContentAssistProcessor {
private static final char[] CONTEXT_INFO_ACTIVATION_CHARS = ",(;{".toCharArray();
private static final IContextInformation[] NO_CONTEXTS = new IContextInformation[0];
static ICompletionProposal[] NO_COMPLETIONS = new ICompletionProposal[0];
private ParameterContextValidator validator;
private CeylonEditor editor;
private boolean secondLevel;
private boolean returnedParamInfo;
private int lastOffsetAcrossSessions=-1;
private int lastOffset=-1;
public void sessionStarted() {
secondLevel = false;
lastOffset=-1;
}
public CeylonCompletionProcessor(CeylonEditor editor) {
this.editor=editor;
}
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
int offset) {
if (offset!=lastOffsetAcrossSessions) {
returnedParamInfo = false;
secondLevel = false;
}
try {
if (lastOffset>=0 && offset>0 && offset!=lastOffset &&
!isIdentifierCharacter(viewer, offset)) {
//user typed a whitespace char with an open
//completions window, so close the window
return NO_COMPLETIONS;
}
}
catch (BadLocationException ble) {
ble.printStackTrace();
return NO_COMPLETIONS;
}
if (offset==lastOffset) {
secondLevel = !secondLevel;
}
lastOffset = offset;
lastOffsetAcrossSessions = offset;
try {
ICompletionProposal[] contentProposals =
getContentProposals(editor.getParseController(),
offset, viewer, secondLevel, returnedParamInfo);
if (contentProposals!=null && contentProposals.length==1 &&
contentProposals[0] instanceof
InvocationCompletionProposal.ParameterInfo) {
returnedParamInfo = true;
}
return contentProposals;
}
catch (Exception e) {
e.printStackTrace();
return NO_COMPLETIONS;
}
}
private boolean isIdentifierCharacter(ITextViewer viewer, int offset)
throws BadLocationException {
char ch = viewer.getDocument().get(offset-1, 1).charAt(0);
return isLetter(ch) || isDigit(ch) || ch=='_' || ch=='.';
}
public IContextInformation[] computeContextInformation(final ITextViewer viewer,
final int offset) {
CeylonParseController cpc = editor.getParseController();
cpc.parse(viewer.getDocument(), new NullProgressMonitor(), null);
return computeParameterContextInformation(offset, cpc.getRootNode(), viewer)
.toArray(NO_CONTEXTS);
}
public char[] getCompletionProposalAutoActivationCharacters() {
return editor.getPrefStore().getString(AUTO_ACTIVATION_CHARS).toCharArray();
}
public char[] getContextInformationAutoActivationCharacters() {
return CONTEXT_INFO_ACTIVATION_CHARS;
}
public IContextInformationValidator getContextInformationValidator() {
if (validator==null) {
validator = new ParameterContextValidator(editor);
}
return validator;
}
public String getErrorMessage() {
return "No completions available";
}
public ICompletionProposal[] getContentProposals(CeylonParseController cpc,
int offset, ITextViewer viewer, boolean secondLevel,
boolean returnedParamInfo) {
if (cpc==null || viewer==null ||
cpc.getRootNode()==null ||
cpc.getTokens()==null) {
return null;
}
cpc.parse(viewer.getDocument(), new NullProgressMonitor(), null);
cpc.getHandler().updateAnnotations();
List<CommonToken> tokens = cpc.getTokens();
Tree.CompilationUnit rn = cpc.getRootNode();
//adjust the token to account for unclosed blocks
//we search for the first non-whitespace/non-comment
//token to the left of the caret
int tokenIndex = Nodes.getTokenIndexAtCharacter(tokens, offset);
if (tokenIndex<0) tokenIndex = -tokenIndex;
CommonToken adjustedToken = adjust(tokenIndex, offset, tokens);
int tt = adjustedToken.getType();
if (offset<=adjustedToken.getStopIndex() &&
offset>adjustedToken.getStartIndex()) {
if (isCommentOrCodeStringLiteral(adjustedToken)) {
return null;
}
}
if (isLineComment(adjustedToken) &&
offset>adjustedToken.getStartIndex() &&
adjustedToken.getLine()==getLine(offset,viewer)+1) {
return null;
}
//find the node at the token
Node node = getTokenNode(adjustedToken.getStartIndex(),
adjustedToken.getStopIndex()+1,
tt, rn, offset);
//it's useful to know the type of the preceding
//token, if any
int index = adjustedToken.getTokenIndex();
if (offset<=adjustedToken.getStopIndex()+1 &&
offset>adjustedToken.getStartIndex()) {
index--;
}
int tokenType = adjustedToken.getType();
int previousTokenType = index>=0 ?
adjust(index, offset, tokens).getType() :
-1;
//find the type that is expected in the current
//location so we can prioritize proposals of that
//type
//TODO: this breaks as soon as the user starts typing
// an expression, since RequiredTypeVisitor
// doesn't know how to search up the tree for
// the containing InvocationExpression
ProducedType requiredType =
getRequiredType(rn, node, adjustedToken);
String prefix = "";
String fullPrefix = "";
if (isIdentifierOrKeyword(adjustedToken)) {
String text = adjustedToken.getText();
//work from the end of the token to
//compute the offset, in order to
//account for quoted identifiers, where
//the \i or \I is not in the token text
int offsetInToken = offset-adjustedToken.getStopIndex()-1+text.length();
int realOffsetInToken = offset-adjustedToken.getStartIndex();
if (offsetInToken<=text.length()) {
prefix = text.substring(0, offsetInToken);
fullPrefix = getRealText(adjustedToken)
.substring(0, realOffsetInToken);
}
}
boolean isMemberOp = isMemberOperator(adjustedToken);
String qualified = null;
// special handling for doc links
boolean inDoc = isAnnotationStringLiteral(adjustedToken) &&
offset>adjustedToken.getStartIndex() &&
offset<=adjustedToken.getStopIndex();
if (inDoc) {
if (node instanceof Tree.DocLink) {
Tree.DocLink docLink = (Tree.DocLink) node;
int offsetInLink = offset-docLink.getStartIndex();
String text = docLink.getToken().getText();
int bar = text.indexOf('|')+1;
if (offsetInLink<bar) {
return null;
}
qualified = text.substring(bar, offsetInLink);
int dcolon = qualified.indexOf("::");
String pkg = null;
if (dcolon>=0) {
pkg = qualified.substring(0, dcolon+2);
qualified = qualified.substring(dcolon+2);
}
int dot = qualified.indexOf('.')+1;
isMemberOp = dot>0;
prefix = qualified.substring(dot);
if (dcolon>=0) {
qualified = pkg + qualified;
}
fullPrefix = prefix;
}
else {
return null;
}
}
Scope scope = getRealScope(node, rn);
//construct completions when outside ordinary code
ICompletionProposal[] completions =
constructCompletions(offset, fullPrefix, cpc, node,
adjustedToken, scope, returnedParamInfo,
isMemberOp, viewer.getDocument(), tokenType);
if (completions==null) {
//finally, construct and sort proposals
Map<String, DeclarationWithProximity> proposals =
getProposals(node, scope, prefix, isMemberOp, rn);
Map<String, DeclarationWithProximity> functionProposals =
getFunctionProposals(node, scope, prefix, isMemberOp);
Set<DeclarationWithProximity> sortedProposals =
sortProposals(prefix, requiredType, proposals);
Set<DeclarationWithProximity> sortedFunctionProposals =
sortProposals(prefix, requiredType, functionProposals);
completions =
constructCompletions(offset, inDoc ? qualified : fullPrefix,
sortedProposals, sortedFunctionProposals,
cpc, scope, node, adjustedToken, isMemberOp,
viewer.getDocument(), secondLevel, inDoc,
requiredType, previousTokenType, tokenType);
}
return completions;
}
private String getRealText(CommonToken token) {
String text = token.getText();
int type = token.getType();
int len = token.getStopIndex()-token.getStartIndex()+1;
if (text.length()<len) {
String quote;
if (type==LIDENTIFIER) {
quote = "\\i";
}
else if (type==UIDENTIFIER) {
quote = "\\I";
}
else {
quote = "";
}
return quote + text;
}
else {
return text;
}
}
private boolean isLineComment(CommonToken adjustedToken) {
return adjustedToken.getType()==LINE_COMMENT;
}
private boolean isCommentOrCodeStringLiteral(CommonToken adjustedToken) {
int tt = adjustedToken.getType();
return tt==MULTI_COMMENT ||
tt==LINE_COMMENT ||
tt==STRING_LITERAL ||
tt==STRING_END ||
tt==STRING_MID ||
tt==STRING_START ||
tt==VERBATIM_STRING ||
tt==CHAR_LITERAL ||
tt==FLOAT_LITERAL ||
tt==NATURAL_LITERAL;
}
private static boolean isAnnotationStringLiteral(CommonToken token) {
int type = token.getType();
return type == ASTRING_LITERAL ||
type == AVERBATIM_STRING;
}
private static CommonToken adjust(int tokenIndex, int offset,
List<CommonToken> tokens) {
CommonToken adjustedToken = tokens.get(tokenIndex);
while (--tokenIndex>=0 &&
(adjustedToken.getType()==WS //ignore whitespace
|| adjustedToken.getType()==EOF
|| adjustedToken.getStartIndex()==offset)) { //don't consider the token to the right of the caret
adjustedToken = tokens.get(tokenIndex);
if (adjustedToken.getType()!=WS &&
adjustedToken.getType()!=EOF &&
adjustedToken.getChannel()!=HIDDEN_CHANNEL) { //don't adjust to a ws token
break;
}
}
return adjustedToken;
}
private static Boolean isDirectlyInsideBlock(Node node,
CeylonParseController cpc, Scope scope,
CommonToken token) {
if (scope instanceof Interface ||
scope instanceof Package) {
return false;
}
else {
//TODO: check that it is not the opening/closing
// brace of a named argument list!
return !(node instanceof Tree.SequenceEnumeration) &&
occursAfterBraceOrSemicolon(token, cpc.getTokens());
}
}
private static Boolean occursAfterBraceOrSemicolon(CommonToken token,
List<CommonToken> tokens) {
if (token.getTokenIndex()==0) {
return false;
}
else {
int tokenType = token.getType();
if (tokenType==LBRACE ||
tokenType==RBRACE ||
tokenType==SEMICOLON) {
return true;
}
int previousTokenType = adjust(token.getTokenIndex()-1,
token.getStartIndex(), tokens).getType();
return previousTokenType==LBRACE ||
previousTokenType==RBRACE ||
previousTokenType==SEMICOLON;
}
}
private static Node getTokenNode(int adjustedStart, int adjustedEnd,
int tokenType, Tree.CompilationUnit rn, int offset) {
Node node = Nodes.findNode(rn, adjustedStart, adjustedEnd);
if (node instanceof Tree.StringLiteral &&
!((Tree.StringLiteral) node).getDocLinks().isEmpty()) {
node = Nodes.findNode(node, offset, offset);
}
if (tokenType==RBRACE &&
!(node instanceof Tree.IterableType) ||
tokenType==SEMICOLON) {
//We are to the right of a } or ;
//so the returned node is the previous
//statement/declaration. Look for the
//containing body.
class BodyVisitor extends Visitor {
Node node, currentBody, result;
BodyVisitor(Node node, Node root) {
this.node = node;
currentBody = root;
}
@Override
public void visitAny(Node that) {
if (that==node) {
result = currentBody;
}
else {
Node cb = currentBody;
if (that instanceof Tree.Body) {
currentBody = that;
}
if (that instanceof Tree.NamedArgumentList) {
currentBody = that;
}
super.visitAny(that);
currentBody = cb;
}
}
}
BodyVisitor mv = new BodyVisitor(node, rn);
mv.visit(rn);
node = mv.result;
}
if (node==null) node = rn; //we're in whitespace at the start of the file
return node;
}
private static boolean isIdentifierOrKeyword(Token token) {
int type = token.getType();
return type==LIDENTIFIER ||
type==UIDENTIFIER ||
type==AIDENTIFIER ||
type==PIDENTIFIER ||
Escaping.KEYWORDS.contains(token.getText());
}
private static ICompletionProposal[] constructCompletions(final int offset,
final String prefix, final CeylonParseController cpc, final Node node,
final CommonToken token, final Scope scope, boolean returnedParamInfo,
boolean memberOp, final IDocument document, int tokenType) {
final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();
if (!returnedParamInfo && atStartOfPositionalArgument(node, token)) {
addFakeShowParametersCompletion(node, cpc, result);
}
else if (node instanceof Tree.PackageLiteral) {
addPackageCompletions(cpc, offset, prefix, null, node, result, false);
}
else if (node instanceof Tree.ModuleLiteral) {
addModuleCompletions(cpc, offset, prefix, null, node, result, false);
}
else if (isDescriptorPackageNameMissing(node)) {
addCurrentPackageNameCompletion(cpc, offset, prefix, result);
}
else if (node instanceof Tree.Import && offset>token.getStopIndex()+1) {
addPackageCompletions(cpc, offset, prefix, null, node, result,
nextTokenType(cpc, token)!=LBRACE);
}
else if (node instanceof Tree.ImportModule && offset>token.getStopIndex()+1) {
addModuleCompletions(cpc, offset, prefix, null, node, result,
nextTokenType(cpc, token)!=STRING_LITERAL);
}
else if (node instanceof Tree.ImportPath) {
new ImportVisitor(prefix, token, offset, node, cpc, result)
.visit(cpc.getRootNode());
}
else if (isEmptyModuleDescriptor(cpc)) {
addModuleDescriptorCompletion(cpc, offset, prefix, result);
addKeywordProposals(cpc, offset, prefix, result, node, null, false, tokenType);
}
else if (isEmptyPackageDescriptor(cpc)) {
addPackageDescriptorCompletion(cpc, offset, prefix, result);
addKeywordProposals(cpc, offset, prefix, result, node, null, false, tokenType);
}
else if (node instanceof Tree.TypeArgumentList &&
token.getType()==LARGER_OP) {
if (offset==token.getStopIndex()+1) {
addTypeArgumentListProposal(offset, cpc, node, scope, document, result);
}
else if (isMemberNameProposable(offset, node, memberOp)) {
addMemberNameProposals(offset, cpc, node, result);
}
else {
return null;
}
}
else {
return null;
}
return result.toArray(new ICompletionProposal[result.size()]);
}
private static boolean atStartOfPositionalArgument(final Node node,
final CommonToken token) {
if (node instanceof Tree.PositionalArgumentList) {
int type = token.getType();
return type==LPAREN || type==COMMA;
}
else if (node instanceof Tree.NamedArgumentList) {
int type = token.getType();
return type==LBRACE || type==SEMICOLON;
}
else {
return false;
}
}
private static boolean isDescriptorPackageNameMissing(final Node node) {
Tree.ImportPath path;
if (node instanceof Tree.ModuleDescriptor) {
Tree.ModuleDescriptor md = (Tree.ModuleDescriptor) node;
path = md.getImportPath();
}
else if (node instanceof Tree.PackageDescriptor) {
Tree.PackageDescriptor pd = (Tree.PackageDescriptor) node;
path = pd.getImportPath();
}
else {
return false;
}
return path==null ||
path.getIdentifiers().isEmpty();
}
private static boolean isMemberNameProposable(int offset, Node node,
boolean memberOp) {
return !memberOp &&
node.getEndToken()!=null &&
((CommonToken)node.getEndToken()).getStopIndex()>=offset-2;
}
private static ICompletionProposal[] constructCompletions(final int offset,
final String prefix, Set<DeclarationWithProximity> sortedProposals,
Set<DeclarationWithProximity> sortedFunctionProposals,
CeylonParseController cpc, Scope scope, Node node, CommonToken token,
boolean memberOp, IDocument doc, boolean secondLevel, boolean inDoc,
ProducedType requiredType, int previousTokenType, int tokenType) {
final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();
OccurrenceLocation ol = getOccurrenceLocation(cpc.getRootNode(), node, offset);
if (node instanceof Tree.TypeConstraint) {
for (DeclarationWithProximity dwp: sortedProposals) {
Declaration dec = dwp.getDeclaration();
if (isTypeParameterOfCurrentDeclaration(node, dec)) {
addReferenceProposal(offset, prefix, cpc, result, dec,
scope, false, null, ol);
}
}
}
else if (prefix.isEmpty() && ol!=IS &&
isMemberNameProposable(offset, node, memberOp) &&
(node instanceof Tree.Type ||
node instanceof Tree.BaseTypeExpression ||
node instanceof Tree.QualifiedTypeExpression)) {
//member names we can refine
ProducedType t=null;
if (node instanceof Tree.Type) {
t = ((Tree.Type) node).getTypeModel();
}
else if (node instanceof Tree.BaseTypeExpression) {
ProducedReference target = ((Tree.BaseTypeExpression) node).getTarget();
if (target!=null) {
t = target.getType();
}
}
else if (node instanceof Tree.QualifiedTypeExpression) {
ProducedReference target = ((Tree.BaseTypeExpression) node).getTarget();
if (target!=null) {
t = target.getType();
}
}
if (t!=null) {
addRefinementProposals(offset, sortedProposals, cpc, scope, node, doc,
secondLevel, result, ol, t, false);
}
//otherwise guess something from the type
addMemberNameProposal(offset, prefix, node, result);
}
else if (node instanceof Tree.TypedDeclaration &&
!(node instanceof Tree.Variable &&
((Tree.Variable) node).getType() instanceof Tree.SyntheticVariable) &&
!(node instanceof Tree.InitializerParameter) &&
isMemberNameProposable(offset, node, memberOp)) {
//member names we can refine
Tree.Type dnt = ((Tree.TypedDeclaration) node).getType();
if (dnt!=null && dnt.getTypeModel()!=null) {
ProducedType t = dnt.getTypeModel();
addRefinementProposals(offset, sortedProposals, cpc, scope, node, doc,
secondLevel, result, ol, t, true);
}
//otherwise guess something from the type
addMemberNameProposal(offset, prefix, node, result);
}
else {
boolean isMember =
node instanceof Tree.QualifiedMemberOrTypeExpression ||
node instanceof Tree.QualifiedType ||
node instanceof Tree.MemberLiteral &&
((Tree.MemberLiteral) node).getType()!=null;
if (!secondLevel && !inDoc && !memberOp) {
addKeywordProposals(cpc, offset, prefix, result, node, ol, isMember, tokenType);
//addTemplateProposal(offset, prefix, result);
}
if (!secondLevel && !inDoc && !isMember) {
if (prefix.isEmpty() && !isTypeUnknown(requiredType) &&
node.getUnit().isCallableType(requiredType)) {
addAnonFunctionProposal(offset, requiredType, result);
}
}
boolean isPackageOrModuleDescriptor =
isModuleDescriptor(cpc) || isPackageDescriptor(cpc);
for (DeclarationWithProximity dwp: sortedProposals) {
Declaration dec = dwp.getDeclaration();
try {
if (!dec.isToplevel() &&
!dec.isClassOrInterfaceMember() &&
dec.getUnit().equals(node.getUnit())) {
Node decNode = Nodes.getReferencedNode(dec, cpc.getRootNode());
if (decNode!=null && offset<Nodes.getIdentifyingNode(decNode).getStartIndex()) {
continue;
}
}
if (isPackageOrModuleDescriptor && !inDoc &&
ol!=META && (ol==null || !ol.reference) &&
(!dec.isAnnotation() || !(dec instanceof Method))) {
continue;
}
if (!secondLevel &&
isParameterOfNamedArgInvocation(scope, dwp) &&
isDirectlyInsideNamedArgumentList(cpc, node, token)) {
addNamedArgumentProposal(offset, prefix, cpc, result, dec, scope);
addInlineFunctionProposal(offset, dec, scope, node, prefix, cpc, doc, result);
}
CommonToken nextToken = getNextToken(cpc, token);
boolean noParamsFollow = noParametersFollow(nextToken);
if (!secondLevel && !inDoc && noParamsFollow &&
isInvocationProposable(dwp, ol, previousTokenType) &&
(!isQualifiedType(node) || dec.isStaticallyImportable())) {
for (Declaration d: overloads(dec)) {
ProducedReference pr = isMember ?
getQualifiedProducedReference(node, d) :
getRefinedProducedReference(scope, d);
addInvocationProposals(offset, prefix, cpc, result,
d, pr, scope, ol, null, isMember);
}
}
if (isProposable(dwp, ol, scope, node.getUnit(),
requiredType, previousTokenType) &&
isProposable(node, ol, dec) &&
(definitelyRequiresType(ol) || noParamsFollow ||
dec instanceof Functional)) {
if (ol==DOCLINK) {
addDocLinkProposal(offset, prefix, cpc, result, dec, scope);
}
else if (ol==IMPORT) {
addImportProposal(offset, prefix, cpc, result, dec, scope);
}
else if (ol!=null && ol.reference) {
if (isReferenceProposable(ol, dec)) {
addProgramElementReferenceProposal(offset, prefix, cpc, result,
dec, scope, isMember);
}
}
else {
ProducedReference pr = isMember ?
getQualifiedProducedReference(node, dec) :
getRefinedProducedReference(scope, dec);
if (secondLevel) {
addSecondLevelProposal(offset, prefix, cpc, result, dec,
scope, false, pr, requiredType, ol);
}
else {
if (!(dec instanceof Method) ||
!isAbstraction(dec) ||
!noParamsFollow) {
addReferenceProposal(offset, prefix, cpc, result,
dec, scope, isMember, pr, ol);
}
}
}
}
if (!memberOp && !secondLevel &&
isProposable(dwp, ol, scope, node.getUnit(), requiredType,
previousTokenType) &&
ol!=IMPORT && ol!=CASE && ol!=CATCH &&
isDirectlyInsideBlock(node, cpc, scope, token)) {
addForProposal(offset, prefix, cpc, result, dwp, dec);
addIfExistsProposal(offset, prefix, cpc, result, dwp, dec);
addIfNonemptyProposal(offset, prefix, cpc, result, dwp, dec);
addTryProposal(offset, prefix, cpc, result, dwp, dec);
addSwitchProposal(offset, prefix, cpc, result, dwp, dec, node, doc);
}
if (!memberOp && !isMember && !secondLevel) {
for (Declaration d: overloads(dec)) {
if (isRefinementProposable(d, ol, scope)) {
addRefinementProposal(offset, d, (ClassOrInterface) scope,
node, scope, prefix, cpc, doc, result, true);
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
if (node instanceof Tree.QualifiedMemberExpression ||
memberOp && node instanceof Tree.QualifiedTypeExpression) {
for (DeclarationWithProximity dwp: sortedFunctionProposals) {
Tree.Primary primary =
((Tree.QualifiedMemberOrTypeExpression) node).getPrimary();
addFunctionProposal(offset, cpc, primary, result,
dwp.getDeclaration(), doc);
}
}
}
return result.toArray(new ICompletionProposal[result.size()]);
}
private static boolean isProposable(Node node, OccurrenceLocation ol,
Declaration dec) {
if (ol!=EXISTS && ol!=NONEMPTY && ol!=IS) {
return true;
}
else if (dec instanceof Value) {
Value val = (Value) dec;
if (val.isVariable() || val.isTransient() ||
val.isDefault() || val.isFormal() ||
isTypeUnknown(val.getType())) {
return false;
}
else {
switch (ol) {
case EXISTS:
return node.getUnit().isOptionalType(val.getType());
case NONEMPTY:
return node.getUnit().isPossiblyEmptyType(val.getType());
case IS:
return true;
default:
return false;
}
}
}
else {
return false;
}
}
private static void addAnonFunctionProposal(int offset,
ProducedType requiredType, List<ICompletionProposal> result) {
StringBuilder text = new StringBuilder();
text.append("(");
Unit unit = requiredType.getDeclaration().getUnit();
boolean first = true;
char c = 'a';
for (ProducedType paramType: unit.getCallableArgumentTypes(requiredType)) {
if (first) {
first = false;
}
else {
text.append(", ");
}
text.append(paramType.getProducedTypeName(unit))
.append(" ")
.append(c++);
}
text.append(")");
String funtext = text.toString() + " => nothing";
result.add(new CompletionProposal(offset, "", null, funtext, funtext) {
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.indexOf("nothing"), 7);
}
@Override
public Image getImage() {
return CeylonResources.MINOR_CHANGE;
}
});
if (unit.getCallableReturnType(requiredType).getDeclaration()
.equals(unit.getAnythingDeclaration())) {
String voidtext = "void " + text.toString() + " {}";
result.add(new CompletionProposal(offset, "", null, voidtext, voidtext) {
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.length()-1, 0);
}
@Override
public Image getImage() {
return CeylonResources.MINOR_CHANGE;
}
});
}
}
private static boolean isReferenceProposable(OccurrenceLocation ol,
Declaration dec) {
return (ol==VALUE_REF || !(dec instanceof Value)) &&
(ol==FUNCTION_REF || !(dec instanceof Method)) &&
(ol==ALIAS_REF || !(dec instanceof TypeAlias)) &&
(ol==TYPE_PARAMETER_REF || !(dec instanceof TypeParameter)) &&
//note: classes and interfaces are almost always proposable
// because they are legal qualifiers for other refs
(ol!=TYPE_PARAMETER_REF || dec instanceof TypeParameter);
}
private static void addRefinementProposals(int offset,
Set<DeclarationWithProximity> set, CeylonParseController cpc,
Scope scope, Node node, IDocument doc, boolean filter,
final List<ICompletionProposal> result, OccurrenceLocation ol,
ProducedType t, boolean preamble) {
for (DeclarationWithProximity dwp: set) {
Declaration dec = dwp.getDeclaration();
if (!filter && dec instanceof MethodOrValue) {
MethodOrValue m = (MethodOrValue) dec;
for (Declaration d: overloads(dec)) {
if (isRefinementProposable(d, ol, scope) &&
t.isSubtypeOf(m.getType())) {
try {
String pfx = doc.get(node.getStartIndex(),
offset-node.getStartIndex());
addRefinementProposal(offset, d, (ClassOrInterface) scope,
node, scope, pfx, cpc, doc, result, preamble);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
}
}
private static boolean isQualifiedType(Node node) {
return (node instanceof Tree.QualifiedType) ||
(node instanceof Tree.QualifiedMemberOrTypeExpression &&
((Tree.QualifiedMemberOrTypeExpression) node)
.getStaticMethodReference());
}
private static boolean noParametersFollow(CommonToken nextToken) {
return nextToken==null ||
//should we disable this, since a statement
//can in fact begin with an LPAREN??
nextToken.getType()!=LPAREN
//disabled now because a declaration can
//begin with an LBRACE (an Iterable type)
/*&& nextToken.getType()!=CeylonLexer.LBRACE*/;
}
private static boolean definitelyRequiresType(OccurrenceLocation ol) {
return ol==SATISFIES ||
ol==OF ||
ol==UPPER_BOUND ||
ol==TYPE_ALIAS;
}
private static CommonToken getNextToken(final CeylonParseController cpc,
CommonToken token) {
int i = token.getTokenIndex();
CommonToken nextToken=null;
List<CommonToken> tokens = cpc.getTokens();
do {
if (++i<tokens.size()) {
nextToken = tokens.get(i);
}
else {
break;
}
}
while (nextToken.getChannel()==HIDDEN_CHANNEL);
return nextToken;
}
private static boolean isDirectlyInsideNamedArgumentList(
CeylonParseController cpc, Node node, CommonToken token) {
return node instanceof Tree.NamedArgumentList ||
(!(node instanceof Tree.SequenceEnumeration) &&
occursAfterBraceOrSemicolon(token, cpc.getTokens()));
}
private static boolean isMemberOperator(Token token) {
int type = token.getType();
return type==MEMBER_OP ||
type==SPREAD_OP ||
type==SAFE_MEMBER_OP;
}
private static boolean isRefinementProposable(Declaration dec,
OccurrenceLocation ol, Scope scope) {
return ol==null &&
(dec.isDefault() || dec.isFormal()) &&
(dec instanceof MethodOrValue || dec instanceof Class) &&
scope instanceof ClassOrInterface &&
((ClassOrInterface) scope).isInheritedFromSupertype(dec);
}
private static boolean isInvocationProposable(DeclarationWithProximity dwp,
OccurrenceLocation ol, int previousTokenType) {
Declaration dec = dwp.getDeclaration();
return dec instanceof Functional &&
previousTokenType!=IS_OP && (previousTokenType!=CASE_TYPES||ol==OF) &&
(ol==null ||
ol==EXPRESSION && (!(dec instanceof Class) || !((Class) dec).isAbstract()) ||
ol==EXTENDS && dec instanceof Class && !((Class) dec).isFinal() &&
((Class) dec).getTypeParameters().isEmpty() ||
ol==CLASS_ALIAS && dec instanceof Class ||
ol==PARAMETER_LIST && dec instanceof Method &&
dec.isAnnotation()) &&
dwp.getNamedArgumentList()==null &&
(!dec.isAnnotation() || !(dec instanceof Method) ||
!((Method) dec).getParameterLists().isEmpty() &&
!((Method) dec).getParameterLists().get(0).getParameters().isEmpty());
}
private static boolean isProposable(DeclarationWithProximity dwp,
OccurrenceLocation ol, Scope scope, Unit unit,
ProducedType requiredType, int previousTokenType) {
Declaration dec = dwp.getDeclaration();
return (ol!=EXTENDS || dec instanceof Class && !((Class) dec).isFinal()) &&
(ol!=CLASS_ALIAS || dec instanceof Class) &&
(ol!=SATISFIES || dec instanceof Interface) &&
(ol!=OF || dec instanceof Class || isAnonymousClassValue(dec)) &&
((ol!=TYPE_ARGUMENT_LIST && ol!=UPPER_BOUND && ol!=TYPE_ALIAS && ol!=CATCH) ||
dec instanceof TypeDeclaration) &&
(ol!=CATCH || isExceptionType(unit, dec)) &&
(ol!=PARAMETER_LIST ||
dec instanceof TypeDeclaration ||
dec instanceof Method && dec.isAnnotation() || //i.e. an annotation
dec instanceof Value && dec.getContainer().equals(scope)) && //a parameter ref
(ol!=IMPORT || !dwp.isUnimported()) &&
(ol!=CASE || isCaseOfSwitch(requiredType, dec, previousTokenType)) &&
(previousTokenType!=IS_OP && (previousTokenType!=CASE_TYPES||ol==OF) ||
dec instanceof TypeDeclaration) &&
ol!=TYPE_PARAMETER_LIST &&
dwp.getNamedArgumentList()==null;
}
private static boolean isCaseOfSwitch(ProducedType requiredType,
Declaration dec, int previousTokenType) {
return previousTokenType==IS_OP &&
isTypeCaseOfSwitch(requiredType, dec) ||
previousTokenType!=IS_OP &&
isValueCaseOfSwitch(requiredType, dec);
}
private static boolean isValueCaseOfSwitch(ProducedType requiredType,
Declaration dec) {
TypeDeclaration rtd = requiredType==null ?
null: requiredType.getDeclaration();
if (rtd instanceof UnionType) {
for (ProducedType td: rtd.getCaseTypes()) {
if (isValueCaseOfSwitch(td, dec)) return true;
}
return false;
}
else {
return isAnonymousClassValue(dec) &&
(rtd==null || ((TypedDeclaration) dec).getTypeDeclaration().inherits(rtd));
}
}
private static boolean isTypeCaseOfSwitch(ProducedType requiredType,
Declaration dec) {
TypeDeclaration rtd = requiredType==null ?
null : requiredType.getDeclaration();
if (rtd instanceof UnionType) {
for (ProducedType td: rtd.getCaseTypes()) {
if (isTypeCaseOfSwitch(td, dec)) return true;
}
return false;
}
else {
return dec instanceof TypeDeclaration &&
(rtd==null || ((TypeDeclaration) dec).inherits(rtd));
}
}
private static boolean isExceptionType(Unit unit, Declaration dec) {
return dec instanceof TypeDeclaration &&
((TypeDeclaration) dec).inherits(unit.getExceptionDeclaration());
}
private static boolean isAnonymousClassValue(Declaration dec) {
return dec instanceof Value &&
((Value) dec).getTypeDeclaration()!=null &&
((Value) dec).getTypeDeclaration().isAnonymous();
}
private static boolean isTypeParameterOfCurrentDeclaration(Node node, Declaration d) {
//TODO: this is a total mess and totally error-prone - figure out something better!
return d instanceof TypeParameter && (((TypeParameter) d).getContainer()==node.getScope() ||
((Tree.TypeConstraint) node).getDeclarationModel()!=null &&
((TypeParameter) d).getContainer()==((Tree.TypeConstraint) node)
.getDeclarationModel().getContainer());
}
private static boolean isParameterOfNamedArgInvocation(Scope scope,
DeclarationWithProximity d) {
return scope==d.getNamedArgumentList();
}
private static ProducedReference getQualifiedProducedReference(Node node,
Declaration d) {
ProducedType pt;
if (node instanceof Tree.QualifiedMemberOrTypeExpression) {
pt = ((Tree.QualifiedMemberOrTypeExpression) node)
.getPrimary().getTypeModel();
}
else if (node instanceof Tree.QualifiedType) {
pt = ((Tree.QualifiedType) node).getOuterType().getTypeModel();
}
else {
return null;
}
if (pt!=null && d.isClassOrInterfaceMember()) {
pt = pt.getSupertype((TypeDeclaration) d.getContainer());
}
return d.getProducedReference(pt, Collections.<ProducedType>emptyList());
}
private static Set<DeclarationWithProximity> sortProposals(String prefix,
ProducedType type, Map<String, DeclarationWithProximity> proposals) {
Set<DeclarationWithProximity> set = new TreeSet<DeclarationWithProximity>(
new ProposalComparator(prefix, type));
set.addAll(proposals.values());
return set;
}
public static Map<String, DeclarationWithProximity> getProposals(Node node,
Scope scope, Tree.CompilationUnit cu) {
return getProposals(node, scope, "", false, cu);
}
private static Map<String, DeclarationWithProximity> getFunctionProposals(Node node,
Scope scope, String prefix, boolean memberOp) {
if (node instanceof Tree.QualifiedMemberOrTypeExpression) {
Tree.QualifiedMemberOrTypeExpression qmte =
(Tree.QualifiedMemberOrTypeExpression) node;
ProducedType type = getPrimaryType(qmte);
if (!qmte.getStaticMethodReference() && !isTypeUnknown(type)) {
return collectUnaryFunctions(type,
scope.getMatchingDeclarations(node.getUnit(), prefix, 0));
}
}
else if (memberOp && node instanceof Tree.Term) {
ProducedType type = null;
if (node instanceof Tree.Term) {
type = ((Tree.Term) node).getTypeModel();
}
if (type!=null) {
return collectUnaryFunctions(type,
scope.getMatchingDeclarations(node.getUnit(), prefix, 0));
}
else {
return emptyMap();
}
}
return emptyMap();
}
public static Map<String, DeclarationWithProximity> collectUnaryFunctions(
ProducedType type, Map<String, DeclarationWithProximity> candidates) {
Map<String,DeclarationWithProximity> matches =
new HashMap<String, DeclarationWithProximity>();
for (Map.Entry<String,DeclarationWithProximity> e:
candidates.entrySet()) {
Declaration declaration = e.getValue().getDeclaration();
if (declaration instanceof Method && !declaration.isAnnotation()) {
List<ParameterList> pls = ((Method) declaration).getParameterLists();
if (!pls.isEmpty()) {
ParameterList pl = pls.get(0);
List<Parameter> params = pl.getParameters();
if (!params.isEmpty()) {
boolean unary=true;
for (int i=1; i<params.size(); i++) {
if (!params.get(i).isDefaulted()) {
unary = false;
}
}
ProducedType t = params.get(0).getType();
if (unary && !isTypeUnknown(t) && type.isSubtypeOf(t)) {
matches.put(e.getKey(), e.getValue());
}
}
}
}
}
return matches;
}
private static Map<String, DeclarationWithProximity> getProposals(Node node,
Scope scope, String prefix, boolean memberOp, Tree.CompilationUnit cu) {
Unit unit = node.getUnit();
if (node instanceof MemberLiteral) { //this case is rather ugly!
Tree.StaticType mlt = ((Tree.MemberLiteral) node).getType();
if (mlt!=null) {
ProducedType type = mlt.getTypeModel();
if (type!=null) {
return type.resolveAliases().getDeclaration()
.getMatchingMemberDeclarations(unit, scope, prefix, 0);
}
else {
return emptyMap();
}
}
}
if (node instanceof Tree.QualifiedMemberOrTypeExpression) {
Tree.QualifiedMemberOrTypeExpression qmte =
(Tree.QualifiedMemberOrTypeExpression) node;
ProducedType type = getPrimaryType(qmte);
if (qmte.getStaticMethodReference()) {
type = unit.getCallableReturnType(type);
}
if (type!=null) {
return type.resolveAliases().getDeclaration()
.getMatchingMemberDeclarations(unit, scope, prefix, 0);
}
else if (qmte.getPrimary() instanceof Tree.MemberOrTypeExpression) {
//it might be a qualified type or even a static method reference
Declaration pmte = ((Tree.MemberOrTypeExpression) qmte.getPrimary())
.getDeclaration();
if (pmte instanceof TypeDeclaration) {
type = ((TypeDeclaration) pmte).getType();
if (type!=null) {
return type.resolveAliases().getDeclaration()
.getMatchingMemberDeclarations(unit, scope, prefix, 0);
}
}
}
return emptyMap();
}
else if (node instanceof Tree.QualifiedType) {
ProducedType type =
((Tree.QualifiedType) node).getOuterType().getTypeModel();
if (type!=null) {
return type.resolveAliases().getDeclaration()
.getMatchingMemberDeclarations(unit, scope, prefix, 0);
}
else {
return emptyMap();
}
}
else if (memberOp &&
(node instanceof Tree.Term ||
node instanceof Tree.DocLink)) {
ProducedType type = null;
if (node instanceof Tree.DocLink) {
Declaration d = ((Tree.DocLink)node).getBase();
if (d != null) {
type = getResultType(d);
if (type == null) {
type = d.getReference().getFullType();
}
}
}
// else if (node instanceof Tree.StringLiteral) {
// type = null;
// }
else if (node instanceof Tree.Term) {
type = ((Tree.Term)node).getTypeModel();
}
if (type!=null) {
return type.resolveAliases().getDeclaration()
.getMatchingMemberDeclarations(unit, scope, prefix, 0);
}
else {
return emptyMap();
}
}
else {
if (scope instanceof ImportList) {
return ((ImportList) scope).getMatchingDeclarations(unit, prefix, 0);
}
else {
return scope==null ? //a null scope occurs when we have not finished parsing the file
getUnparsedProposals(cu, prefix) :
scope.getMatchingDeclarations(unit, prefix, 0);
}
}
}
private static ProducedType getPrimaryType(Tree.QualifiedMemberOrTypeExpression qme) {
ProducedType type = qme.getPrimary().getTypeModel();
if (type==null) {
return null;
}
else if (qme.getMemberOperator() instanceof Tree.SafeMemberOp) {
return qme.getUnit().getDefiniteType(type);
}
else if (qme.getMemberOperator() instanceof Tree.SpreadOp) {
return qme.getUnit().getIteratedType(type);
}
else {
return type;
}
}
private static Map<String, DeclarationWithProximity> getUnparsedProposals(Node node,
String prefix) {
if (node == null) {
return newEmptyProposals();
}
Unit unit = node.getUnit();
if (unit == null) {
return newEmptyProposals();
}
Package pkg = unit.getPackage();
if (pkg == null) {
return newEmptyProposals();
}
return pkg.getModule().getAvailableDeclarations(prefix);
}
private static TreeMap<String, DeclarationWithProximity> newEmptyProposals() {
return new TreeMap<String,DeclarationWithProximity>();
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CeylonCompletionProcessor.java |
13 | result.add(new CompletionProposal(offset, "", null, funtext, funtext) {
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.indexOf("nothing"), 7);
}
@Override
public Image getImage() {
return CeylonResources.MINOR_CHANGE;
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CeylonCompletionProcessor.java |
14 | class BodyVisitor extends Visitor {
Node node, currentBody, result;
BodyVisitor(Node node, Node root) {
this.node = node;
currentBody = root;
}
@Override
public void visitAny(Node that) {
if (that==node) {
result = currentBody;
}
else {
Node cb = currentBody;
if (that instanceof Tree.Body) {
currentBody = that;
}
if (that instanceof Tree.NamedArgumentList) {
currentBody = that;
}
super.visitAny(that);
currentBody = cb;
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CeylonCompletionProcessor.java |
15 | result.add(new CompletionProposal(offset, "", null, voidtext, voidtext) {
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.length()-1, 0);
}
@Override
public Image getImage() {
return CeylonResources.MINOR_CHANGE;
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CeylonCompletionProcessor.java |
16 | public class CodeCompletions {
private static boolean forceExplicitTypeArgs(Declaration d,
OccurrenceLocation ol) {
if (ol==EXTENDS) {
return true;
}
else {
//TODO: this is a pretty limited implementation
// for now, but eventually we could do
// something much more sophisticated to
// guess if explicit type args will be
// necessary (variance, etc)
if (d instanceof Functional) {
List<ParameterList> pls = ((Functional) d).getParameterLists();
return pls.isEmpty() ||
pls.get(0).getParameters().isEmpty();
}
else {
return false;
}
}
}
static String getTextForDocLink(CeylonParseController cpc,
Declaration decl) {
Package pkg = decl.getUnit().getPackage();
String qname = decl.getQualifiedNameString();
// handle language package or same module and package
Unit unit = cpc.getRootNode().getUnit();
if (pkg!=null &&
(Module.LANGUAGE_MODULE_NAME.equals(pkg.getNameAsString())
|| (unit!=null && pkg.equals(unit.getPackage())))) {
if (decl.isToplevel()) {
return decl.getNameAsString();
}
else { // not top level in language module
int loc = qname.indexOf("::");
if (loc>=0) {
return qname.substring(loc + 2);
}
else {
return qname;
}
}
}
else {
return qname;
}
}
public static String getTextFor(Declaration dec, Unit unit) {
StringBuilder result = new StringBuilder();
result.append(escapeName(dec, unit));
appendTypeParameters(dec, result);
return result.toString();
}
public static String getPositionalInvocationTextFor(
Declaration dec, OccurrenceLocation ol,
ProducedReference pr, Unit unit, boolean includeDefaulted,
String typeArgs) {
StringBuilder result = new StringBuilder(escapeName(dec, unit));
if (typeArgs!=null) {
result.append(typeArgs);
}
else if (forceExplicitTypeArgs(dec, ol)) {
appendTypeParameters(dec, result);
}
appendPositionalArgs(dec, pr, unit, result, includeDefaulted, false);
appendSemiToVoidInvocation(result, dec);
return result.toString();
}
public static String getNamedInvocationTextFor(Declaration dec,
ProducedReference pr, Unit unit, boolean includeDefaulted,
String typeArgs) {
StringBuilder result = new StringBuilder(escapeName(dec, unit));
if (typeArgs!=null) {
result.append(typeArgs);
}
else if (forceExplicitTypeArgs(dec, null)) {
appendTypeParameters(dec, result);
}
appendNamedArgs(dec, pr, unit, result, includeDefaulted, false);
appendSemiToVoidInvocation(result, dec);
return result.toString();
}
private static void appendSemiToVoidInvocation(StringBuilder result,
Declaration dd) {
if ((dd instanceof Method) && ((Method) dd).isDeclaredVoid() &&
((Method) dd).getParameterLists().size()==1) {
result.append(';');
}
}
public static String getDescriptionFor(Declaration dec, Unit unit) {
StringBuilder result = new StringBuilder(dec.getName(unit));
appendTypeParameters(dec, result);
return result.toString();
}
public static String getPositionalInvocationDescriptionFor(
Declaration dec, OccurrenceLocation ol,
ProducedReference pr, Unit unit, boolean includeDefaulted,
String typeArgs) {
StringBuilder result = new StringBuilder(dec.getName(unit));
if (typeArgs!=null) {
result.append(typeArgs);
}
else if (forceExplicitTypeArgs(dec, ol)) {
appendTypeParameters(dec, result);
}
appendPositionalArgs(dec, pr, unit, result,
includeDefaulted, true);
return result.toString();
}
public static String getNamedInvocationDescriptionFor(
Declaration dec, ProducedReference pr,
Unit unit, boolean includeDefaulted, String typeArgs) {
StringBuilder result = new StringBuilder(dec.getName(unit));
if (typeArgs!=null) {
result.append(typeArgs);
}
else if (forceExplicitTypeArgs(dec, null)) {
appendTypeParameters(dec, result);
}
appendNamedArgs(dec, pr, unit, result,
includeDefaulted, true);
return result.toString();
}
public static String getRefinementTextFor(Declaration d,
ProducedReference pr, Unit unit, boolean isInterface,
ClassOrInterface ci, String indent, boolean containsNewline) {
return getRefinementTextFor(d, pr, unit, isInterface, ci,
indent, containsNewline, true);
}
public static String getRefinementTextFor(Declaration d,
ProducedReference pr, Unit unit, boolean isInterface,
ClassOrInterface ci, String indent, boolean containsNewline,
boolean preamble) {
StringBuilder result = new StringBuilder();
if (preamble) {
result.append("shared actual ");
if (isVariable(d) && !isInterface) {
result.append("variable ");
}
}
appendDeclarationHeaderText(d, pr, unit, result);
appendTypeParameters(d, result);
appendParametersText(d, pr, unit, result);
if (d instanceof Class) {
result.append(extraIndent(extraIndent(indent, containsNewline),
containsNewline))
.append(" extends super.").append(escapeName(d));
appendPositionalArgs(d, pr, unit, result, true, false);
}
appendConstraints(d, pr, unit, indent, containsNewline, result);
appendImplText(d, pr, isInterface, unit, indent, result, ci);
return result.toString();
}
private static void appendConstraints(Declaration d, ProducedReference pr,
Unit unit, String indent, boolean containsNewline,
StringBuilder result) {
if (d instanceof Functional) {
for (TypeParameter tp: ((Functional) d).getTypeParameters()) {
List<ProducedType> sts = tp.getSatisfiedTypes();
if (!sts.isEmpty()) {
result.append(extraIndent(extraIndent(indent, containsNewline),
containsNewline))
.append("given ").append(tp.getName())
.append(" satisfies ");
boolean first = true;
for (ProducedType st: sts) {
if (first) {
first = false;
}
else {
result.append("&");
}
result.append(st.substitute(pr.getTypeArguments())
.getProducedTypeName(unit));
}
}
}
}
}
static String getInlineFunctionTextFor(Parameter p,
ProducedReference pr, Unit unit, String indent) {
StringBuilder result = new StringBuilder();
appendNamedArgumentHeader(p, pr, result, false);
appendTypeParameters(p.getModel(), result);
appendParametersText(p.getModel(), pr, unit, result);
if (p.isDeclaredVoid()) {
result.append(" {}");
}
else {
result.append(" => nothing;");
}
return result.toString();
}
public static boolean isVariable(Declaration d) {
return d instanceof TypedDeclaration &&
((TypedDeclaration) d).isVariable();
}
static String getRefinementDescriptionFor(Declaration d,
ProducedReference pr, Unit unit) {
StringBuilder result = new StringBuilder("shared actual ");
if (isVariable(d)) {
result.append("variable ");
}
appendDeclarationHeaderDescription(d, pr, unit, result);
appendTypeParameters(d, result);
appendParametersDescription(d, pr, unit, result);
/*result.append(" - refine declaration in ")
.append(((Declaration) d.getContainer()).getName());*/
return result.toString();
}
static String getInlineFunctionDescriptionFor(Parameter p,
ProducedReference pr, Unit unit) {
StringBuilder result = new StringBuilder();
appendNamedArgumentHeader(p, pr, result, true);
appendTypeParameters(p.getModel(), result);
appendParametersDescription(p.getModel(), pr, unit, result);
return result.toString();
}
public static String getLabelDescriptionFor(Declaration d) {
StringBuilder result = new StringBuilder();
if (d!=null) {
appendDeclarationAnnotations(d, result);
appendDeclarationHeaderDescription(d, d.getUnit(), result);
appendTypeParameters(d, result, true);
appendParametersDescription(d, result, null);
}
return result.toString();
}
private static void appendDeclarationAnnotations(Declaration d,
StringBuilder result) {
if (d.isActual()) result.append("actual ");
if (d.isFormal()) result.append("formal ");
if (d.isDefault()) result.append("default ");
if (isVariable(d)) result.append("variable ");
}
public static String getDocDescriptionFor(Declaration d,
ProducedReference pr, Unit unit) {
StringBuilder result = new StringBuilder();
appendDeclarationHeaderDescription(d, pr, unit, result);
appendTypeParameters(d, pr, result, true, unit);
appendParametersDescription(d, pr, unit, result);
return result.toString();
}
public static StyledString getQualifiedDescriptionFor(Declaration d) {
StyledString result = new StyledString();
if (d!=null) {
appendDeclarationDescription(d, result);
if (d.isClassOrInterfaceMember()) {
Declaration ci = (Declaration) d.getContainer();
result.append(ci.getName(), Highlights.TYPE_ID_STYLER).append('.');
appendMemberName(d, result);
}
else {
appendDeclarationName(d, result);
}
appendTypeParameters(d, result, true);
appendParametersDescription(d, result);
if (d instanceof TypedDeclaration) {
if (EditorsUI.getPreferenceStore().getBoolean(DISPLAY_RETURN_TYPES)) {
TypedDeclaration td = (TypedDeclaration) d;
if (!td.isParameter() &&
!td.isDynamicallyTyped() &&
!(td instanceof Method && ((Method) td).isDeclaredVoid())) {
ProducedType t = td.getType();
if (t!=null) {
result.append(" ∊ ");
appendTypeName(result, t, Highlights.ARROW_STYLER);
}
}
}
}
/*result.append(" - refines declaration in ")
.append(((Declaration) d.getContainer()).getName());*/
}
return result;
}
public static StyledString getStyledDescriptionFor(Declaration d) {
StyledString result = new StyledString();
if (d!=null) {
appendDeclarationAnnotations(d, result);
appendDeclarationDescription(d, result);
appendDeclarationName(d, result);
appendTypeParameters(d, result, true);
appendParametersDescription(d, result);
if (d instanceof TypedDeclaration) {
if (EditorsUI.getPreferenceStore().getBoolean(DISPLAY_RETURN_TYPES)) {
TypedDeclaration td = (TypedDeclaration) d;
if (!td.isParameter() &&
!td.isDynamicallyTyped() &&
!(td instanceof Method && ((Method) td).isDeclaredVoid())) {
ProducedType t = td.getType();
if (t!=null) {
result.append(" ∊ ");
appendTypeName(result, t, Highlights.ARROW_STYLER);
}
}
}
}
/*result.append(" - refines declaration in ")
.append(((Declaration) d.getContainer()).getName());*/
}
return result;
}
private static void appendDeclarationAnnotations(Declaration d,
StyledString result) {
if (d.isActual()) result.append("actual ", Highlights.ANN_STYLER);
if (d.isFormal()) result.append("formal ", Highlights.ANN_STYLER);
if (d.isDefault()) result.append("default ", Highlights.ANN_STYLER);
if (isVariable(d)) result.append("variable ", Highlights.ANN_STYLER);
}
public static void appendPositionalArgs(Declaration dec,
Unit unit, StringBuilder result, boolean includeDefaulted,
boolean descriptionOnly) {
appendPositionalArgs(dec, dec.getReference(),
unit, result, includeDefaulted,
descriptionOnly);
}
private static void appendPositionalArgs(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result, boolean includeDefaulted,
boolean descriptionOnly) {
if (d instanceof Functional) {
List<Parameter> params = getParameters((Functional) d,
includeDefaulted, false);
if (params.isEmpty()) {
result.append("()");
}
else {
boolean paramTypes = descriptionOnly &&
EditorsUI.getPreferenceStore().getBoolean(DISPLAY_PARAMETER_TYPES);
result.append("(");
for (Parameter p: params) {
ProducedTypedReference typedParameter =
pr.getTypedParameter(p);
if (p.getModel() instanceof Functional) {
if (p.isDeclaredVoid()) {
result.append("void ");
}
appendParameters(p.getModel(),
typedParameter,
unit, result,
descriptionOnly);
if (p.isDeclaredVoid()) {
result.append(" {}");
}
else {
result.append(" => ")
.append("nothing");
}
}
else {
ProducedType pt = typedParameter.getType();
if (descriptionOnly && paramTypes && !isTypeUnknown(pt)) {
if (p.isSequenced()) {
pt = unit.getSequentialElementType(pt);
}
result.append(pt.getProducedTypeName(unit));
if (p.isSequenced()) {
result.append(p.isAtLeastOne()?'+':'*');
}
result.append(" ");
}
else if (p.isSequenced()) {
result.append("*");
}
result.append(descriptionOnly || p.getModel()==null ?
p.getName() : escapeName(p.getModel()));
}
result.append(", ");
}
result.setLength(result.length()-2);
result.append(")");
}
}
}
static void appendSuperArgsText(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result, boolean includeDefaulted) {
if (d instanceof Functional) {
List<Parameter> params = getParameters((Functional) d,
includeDefaulted, false);
if (params.isEmpty()) {
result.append("()");
}
else {
result.append("(");
for (Parameter p: params) {
if (p.isSequenced()) {
result.append("*");
}
result.append(escapeName(p.getModel()))
.append(", ");
}
result.setLength(result.length()-2);
result.append(")");
}
}
}
private static List<Parameter> getParameters(Functional fd,
boolean includeDefaults, boolean namedInvocation) {
List<ParameterList> plists = fd.getParameterLists();
if (plists==null || plists.isEmpty()) {
return Collections.<Parameter>emptyList();
}
else {
return CompletionUtil.getParameters(plists.get(0),
includeDefaults, namedInvocation);
}
}
private static void appendNamedArgs(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result, boolean includeDefaulted,
boolean descriptionOnly) {
if (d instanceof Functional) {
List<Parameter> params = getParameters((Functional) d,
includeDefaulted, true);
if (params.isEmpty()) {
result.append(" {}");
}
else {
boolean paramTypes = descriptionOnly &&
EditorsUI.getPreferenceStore().getBoolean(DISPLAY_PARAMETER_TYPES);
result.append(" { ");
for (Parameter p: params) {
String name = descriptionOnly ?
p.getName() :
escapeName(p.getModel());
if (p.getModel() instanceof Functional) {
if (p.isDeclaredVoid()) {
result.append("void ");
}
else {
if (paramTypes && !isTypeUnknown(p.getType())) {
result.append(p.getType().getProducedTypeName(unit)).append(" ");
}
else {
result.append("function ");
}
}
result.append(name);
appendParameters(p.getModel(),
pr.getTypedParameter(p),
unit, result,
descriptionOnly);
if (descriptionOnly) {
result.append("; ");
}
else if (p.isDeclaredVoid()) {
result.append(" {} ");
}
else {
result.append(" => ")
//.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType()))
.append("nothing; ");
}
}
else {
if (p==params.get(params.size()-1) &&
!isTypeUnknown(p.getType()) &&
unit.isIterableParameterType(p.getType())) {
// result.append(" ");
}
else {
if (descriptionOnly && paramTypes && !isTypeUnknown(p.getType())) {
result.append(p.getType().getProducedTypeName(unit)).append(" ");
}
result.append(name)
.append(" = ")
//.append(CeylonQuickFixAssistant.defaultValue(p.getUnit(), p.getType()))
.append("nothing")
.append("; ");
}
}
}
result.append("}");
}
}
}
private static void appendTypeParameters(Declaration d,
StringBuilder result) {
appendTypeParameters(d, result, false);
}
private static void appendTypeParameters(Declaration d,
StringBuilder result, boolean variances) {
if (d instanceof Generic) {
List<TypeParameter> types =
((Generic) d).getTypeParameters();
if (!types.isEmpty()) {
result.append("<");
for (TypeParameter tp: types) {
if (variances) {
if (tp.isCovariant()) {
result.append("out ");
}
if (tp.isContravariant()) {
result.append("in ");
}
}
result.append(tp.getName()).append(", ");
}
result.setLength(result.length()-2);
result.append(">");
}
}
}
private static void appendTypeParameters(Declaration d,
ProducedReference pr, StringBuilder result,
boolean variances, Unit unit) {
if (d instanceof Generic) {
List<TypeParameter> types =
((Generic) d).getTypeParameters();
if (!types.isEmpty()) {
result.append("<");
boolean first = true;
for (TypeParameter tp: types) {
if (first) {
first = false;
}
else {
result.append(", ");
}
ProducedType arg = pr==null ?
null : pr.getTypeArguments().get(tp);
if (arg == null) {
if (variances) {
if (tp.isCovariant()) {
result.append("out ");
}
if (tp.isContravariant()) {
result.append("in ");
}
}
result.append(tp.getName());
}
else {
if (pr instanceof ProducedType) {
if (variances) {
SiteVariance variance =
((ProducedType) pr).getVarianceOverrides().get(tp);
if (variance==SiteVariance.IN) {
result.append("in ");
}
if (variance==SiteVariance.OUT) {
result.append("out ");
}
}
}
result.append(arg.getProducedTypeName(unit));
}
}
result.append(">");
}
}
}
private static void appendTypeParameters(Declaration d,
StyledString result, boolean variances) {
if (d instanceof Generic) {
List<TypeParameter> types =
((Generic) d).getTypeParameters();
if (!types.isEmpty()) {
result.append("<");
int len = types.size(), i = 0;
for (TypeParameter tp: types) {
if (variances) {
if (tp.isCovariant()) {
result.append("out ", Highlights.KW_STYLER);
}
if (tp.isContravariant()) {
result.append("in ", Highlights.KW_STYLER);
}
}
result.append(tp.getName(), Highlights.TYPE_STYLER);
if (++i<len) result.append(", ");
}
result.append(">");
}
}
}
private static void appendDeclarationHeaderDescription(Declaration d,
Unit unit, StringBuilder result) {
appendDeclarationHeader(d, null, unit, result, true);
}
private static void appendDeclarationHeaderDescription(Declaration d,
ProducedReference pr, Unit unit, StringBuilder result) {
appendDeclarationHeader(d, pr, unit, result, true);
}
private static void appendDeclarationHeaderText(Declaration d,
ProducedReference pr, Unit unit, StringBuilder result) {
appendDeclarationHeader(d, pr, unit, result, false);
}
private static void appendDeclarationHeader(Declaration d,
ProducedReference pr, Unit unit,
StringBuilder result,
boolean descriptionOnly) {
if (d instanceof Class) {
if (d.isAnonymous()) {
result.append("object");
}
else {
result.append("class");
}
}
else if (d instanceof Interface) {
result.append("interface");
}
else if (d instanceof TypeAlias) {
result.append("alias");
}
else if (d instanceof TypedDeclaration) {
TypedDeclaration td = (TypedDeclaration) d;
boolean isSequenced = d.isParameter() &&
((MethodOrValue) d).getInitializerParameter()
.isSequenced();
ProducedType type;
if (pr == null) {
type = td.getType();
}
else {
type = pr.getType();
}
if (isSequenced && type!=null) {
type = unit.getIteratedType(type);
}
if (type==null) {
type = new UnknownType(unit).getType();
}
String typeName = type.getProducedTypeName(unit);
if (td.isDynamicallyTyped()) {
result.append("dynamic");
}
else if (td instanceof Value &&
type.getDeclaration().isAnonymous()) {
result.append("object");
}
else if (d instanceof Method) {
if (((Functional) d).isDeclaredVoid()) {
result.append("void");
}
else {
result.append(typeName);
}
}
else {
result.append(typeName);
}
if (isSequenced) {
if (((MethodOrValue) d).getInitializerParameter()
.isAtLeastOne()) {
result.append("+");
}
else {
result.append("*");
}
}
}
result.append(" ")
.append(descriptionOnly ?
d.getName() : escapeName(d));
}
private static void appendNamedArgumentHeader(Parameter p,
ProducedReference pr, StringBuilder result,
boolean descriptionOnly) {
if (p.getModel() instanceof Functional) {
Functional fp = (Functional) p.getModel();
result.append(fp.isDeclaredVoid() ? "void" : "function");
}
else {
result.append("value");
}
result.append(" ")
.append(descriptionOnly ?
p.getName() : escapeName(p.getModel()));
}
private static void appendDeclarationDescription(Declaration d,
StyledString result) {
if (d instanceof Class) {
if (d.isAnonymous()) {
result.append("object", Highlights.KW_STYLER);
}
else {
result.append("class", Highlights.KW_STYLER);
}
}
else if (d instanceof Interface) {
result.append("interface", Highlights.KW_STYLER);
}
else if (d instanceof TypeAlias) {
result.append("alias", Highlights.KW_STYLER);
}
else if (d.isParameter()) {
TypedDeclaration td = (TypedDeclaration) d;
ProducedType type = td.getType();
if (td.isDynamicallyTyped()) {
result.append("dynamic", Highlights.KW_STYLER);
}
else if (type!=null) {
boolean isSequenced = //d.isParameter() &&
((MethodOrValue) d).getInitializerParameter()
.isSequenced();
if (isSequenced) {
type = d.getUnit().getIteratedType(type);
}
/*if (td instanceof Value &&
td.getTypeDeclaration().isAnonymous()) {
result.append("object", KW_STYLER);
}
else*/ if (d instanceof Method) {
if (((Functional)d).isDeclaredVoid()) {
result.append("void", Highlights.KW_STYLER);
}
else {
appendTypeName(result, type);
}
}
else {
appendTypeName(result, type);
}
if (isSequenced) {
result.append("*");
}
}
}
else if (d instanceof Value) {
Value v = (Value) d;
if (v.isDynamicallyTyped()) {
result.append("dynamic", Highlights.KW_STYLER);
}
else if (v.getTypeDeclaration()!=null &&
v.getTypeDeclaration().isAnonymous()) {
result.append("object", Highlights.KW_STYLER);
}
else {
result.append("value", Highlights.KW_STYLER);
}
}
else if (d instanceof Method) {
Method m = (Method) d;
if (m.isDynamicallyTyped()) {
result.append("dynamic", Highlights.KW_STYLER);
}
else if (m.isDeclaredVoid()) {
result.append("void", Highlights.KW_STYLER);
}
else {
result.append("function", Highlights.KW_STYLER);
}
}
else if (d instanceof Setter) {
result.append("assign", Highlights.KW_STYLER);
}
result.append(" ");
}
private static void appendMemberName(Declaration d, StyledString result) {
String name = d.getName();
if (name != null) {
if (d instanceof TypeDeclaration) {
result.append(name, Highlights.TYPE_STYLER);
}
else {
result.append(name, Highlights.MEMBER_STYLER);
}
}
}
private static void appendDeclarationName(Declaration d, StyledString result) {
String name = d.getName();
if (name != null) {
if (d instanceof TypeDeclaration) {
result.append(name, Highlights.TYPE_STYLER);
}
else {
result.append(name, Highlights.ID_STYLER);
}
}
}
/*private static void appendPackage(Declaration d, StringBuilder result) {
if (d.isToplevel()) {
result.append(" - ").append(getPackageLabel(d));
}
if (d.isClassOrInterfaceMember()) {
result.append(" - ");
ClassOrInterface td = (ClassOrInterface) d.getContainer();
result.append( td.getName() );
appendPackage(td, result);
}
}*/
private static void appendImplText(Declaration d, ProducedReference pr,
boolean isInterface, Unit unit, String indent, StringBuilder result,
ClassOrInterface ci) {
if (d instanceof Method) {
if (ci!=null && !ci.isAnonymous()) {
if (d.getName().equals("equals")) {
List<ParameterList> pl = ((Method) d).getParameterLists();
if (!pl.isEmpty()) {
List<Parameter> ps = pl.get(0).getParameters();
if (!ps.isEmpty()) {
appendEqualsImpl(unit, indent, result, ci, ps);
return;
}
}
}
}
if (!d.isFormal()) {
result.append(" => super.").append(d.getName());
appendSuperArgsText(d, pr, unit, result, true);
result.append(";");
}
else {
if (((Functional) d).isDeclaredVoid()) {
result.append(" {}");
}
else {
result.append(" => nothing;");
}
}
}
else if (d instanceof Value) {
if (ci!=null && !ci.isAnonymous()) {
if (d.getName().equals("hash")) {
appendHashImpl(unit, indent, result, ci);
return;
}
}
if (isInterface/*||d.isParameter()*/) {
//interfaces can't have references,
//so generate a setter for variables
if (d.isFormal()) {
result.append(" => nothing;");
}
else {
result.append(" => super.")
.append(d.getName()).append(";");
}
if (isVariable(d)) {
result.append(indent)
.append("assign ").append(d.getName())
.append(" {}");
}
}
else {
//we can have a references, so use = instead
//of => for variables
String arrow = isVariable(d) ? " = " : " => ";
if (d.isFormal()) {
result.append(arrow).append("nothing;");
}
else {
result.append(arrow)
.append("super.").append(d.getName())
.append(";");
}
}
}
else {
//TODO: in the case of a class, formal member refinements!
result.append(" {}");
}
}
private static void appendHashImpl(Unit unit, String indent,
StringBuilder result, ClassOrInterface ci) {
result.append(" {")
.append(indent).append(getDefaultIndent())
.append("variable value hash = 1;")
.append(indent).append(getDefaultIndent());
String ind = indent+getDefaultIndent();
appendMembersToHash(unit, ind, result, ci);
result.append("return hash;")
.append(indent)
.append("}");
}
private static void appendEqualsImpl(Unit unit, String indent,
StringBuilder result, ClassOrInterface ci, List<Parameter> ps) {
Parameter p = ps.get(0);
result.append(" {")
.append(indent).append(getDefaultIndent())
.append("if (is ").append(ci.getName()).append(" ").append(p.getName()).append(") {")
.append(indent).append(getDefaultIndent()).append(getDefaultIndent())
.append("return ");
String ind = indent+getDefaultIndent()+getDefaultIndent()+getDefaultIndent();
appendMembersToEquals(unit, ind, result, ci, p);
result.append(indent).append(getDefaultIndent())
.append("}")
.append(indent).append(getDefaultIndent())
.append("else {")
.append(indent).append(getDefaultIndent()).append(getDefaultIndent())
.append("return false;")
.append(indent).append(getDefaultIndent())
.append("}")
.append(indent)
.append("}");
}
private static boolean isObjectField(Declaration m) {
return m.getName()!=null &&
m.getName().equals("hash") ||
m.getName().equals("string");
}
private static void appendMembersToEquals(Unit unit, String indent,
StringBuilder result, ClassOrInterface ci, Parameter p) {
boolean found = false;
for (Declaration m: ci.getMembers()) {
if (m instanceof Value &&
!isObjectField(m)) {
Value value = (Value) m;
if (!value.isTransient()) {
if (!unit.getNullValueDeclaration().getType()
.isSubtypeOf(value.getType())) {
result.append(value.getName())
.append("==")
.append(p.getName())
.append(".")
.append(value.getName())
.append(" && ")
.append(indent);
found = true;
}
}
}
}
if (found) {
result.setLength(result.length()-4-indent.length());
result.append(";");
}
else {
result.append("true;");
}
}
private static void appendMembersToHash(Unit unit, String indent,
StringBuilder result, ClassOrInterface ci) {
for (Declaration m: ci.getMembers()) {
if (m instanceof Value &&
!isObjectField(m)) {
Value value = (Value) m;
if (!value.isTransient()) {
if (!unit.getNullValueDeclaration().getType()
.isSubtypeOf(value.getType())) {
result.append("hash = 31*hash + ")
.append(value.getName())
.append(".hash;")
.append(indent);
}
}
}
}
}
private static String extraIndent(String indent, boolean containsNewline) {
return containsNewline ? indent + getDefaultIndent() : indent;
}
public static void appendParametersDescription(Declaration d, StringBuilder result,
CeylonParseController cpc) {
appendParameters(d, null, d.getUnit(), result, cpc, true);
}
public static void appendParametersText(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result) {
appendParameters(d, pr, unit, result, null, false);
}
private static void appendParametersDescription(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result) {
appendParameters(d, pr, unit, result, null, true);
}
private static void appendParameters(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result, boolean descriptionOnly) {
appendParameters(d, pr, unit, result, null, descriptionOnly);
}
private static void appendParameters(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result, CeylonParseController cpc,
boolean descriptionOnly) {
if (d instanceof Functional) {
List<ParameterList> plists = ((Functional) d).getParameterLists();
if (plists!=null) {
for (ParameterList params: plists) {
if (params.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
for (Parameter p: params.getParameters()) {
appendParameter(result, pr, p, unit,
descriptionOnly);
if (cpc!=null) {
result.append(getDefaultValueDescription(p, cpc));
}
result.append(", ");
}
result.setLength(result.length()-2);
result.append(")");
}
}
}
}
}
public static void appendParameterText(StringBuilder result,
ProducedReference pr, Parameter p, Unit unit) {
appendParameter(result, pr, p, unit, false);
}
private static void appendParameter(StringBuilder result,
ProducedReference pr, Parameter p, Unit unit,
boolean descriptionOnly) {
if (p.getModel() == null) {
result.append(p.getName());
}
else {
ProducedTypedReference ppr = pr==null ?
null : pr.getTypedParameter(p);
appendDeclarationHeader(p.getModel(), ppr, unit, result,
descriptionOnly);
appendParameters(p.getModel(), ppr, unit, result,
descriptionOnly);
}
}
public static void appendParameterContextInfo(StringBuilder result,
ProducedReference pr, Parameter p, Unit unit,
boolean namedInvocation, boolean isListedValues) {
if (p.getModel() == null) {
result.append(p.getName());
}
else {
ProducedTypedReference ppr = pr==null ?
null : pr.getTypedParameter(p);
String typeName;
ProducedType type = ppr.getType();
if (isListedValues && namedInvocation) {
ProducedType et = unit.getIteratedType(type);
typeName = et.getProducedTypeName(unit);
if (unit.isEntryType(et)) {
typeName = '<' + typeName + '>';
}
typeName += unit.isNonemptyIterableType(type) ? '+' : '*';
}
else if (p.isSequenced() && !namedInvocation) {
ProducedType et = unit.getSequentialElementType(type);
typeName = et.getProducedTypeName(unit);
if (unit.isEntryType(et)) {
typeName = '<' + typeName + '>';
}
typeName += p.isAtLeastOne() ? '+' : '*';
}
else {
typeName = type.getProducedTypeName(unit);
}
result.append(typeName).append(" ").append(p.getName());
appendParametersDescription(p.getModel(), ppr, unit, result);
}
if (namedInvocation && !isListedValues) {
result.append(p.getModel() instanceof Method ?
" => ... " : " = ... " );
}
}
private static void appendParametersDescription(Declaration d, StyledString result) {
if (d instanceof Functional) {
List<ParameterList> plists = ((Functional) d).getParameterLists();
if (plists!=null) {
for (ParameterList params: plists) {
if (params.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
int len = params.getParameters().size(), i=0;
for (Parameter p: params.getParameters()) {
if (p.getModel()==null) {
result.append(p.getName());
}
else {
appendDeclarationDescription(p.getModel(), result);
appendDeclarationName(p.getModel(), result);
appendParametersDescription(p.getModel(), result);
/*result.append(p.getType().getProducedTypeName(), TYPE_STYLER)
.append(" ").append(p.getName(), ID_STYLER);
if (p instanceof FunctionalParameter) {
result.append("(");
FunctionalParameter fp = (FunctionalParameter) p;
List<Parameter> fpl = fp.getParameterLists().get(0).getParameters();
int len2 = fpl.size(), j=0;
for (Parameter pp: fpl) {
result.append(pp.getType().getProducedTypeName(), TYPE_STYLER)
.append(" ").append(pp.getName(), ID_STYLER);
if (++j<len2) result.append(", ");
}
result.append(")");
}*/
}
if (++i<len) result.append(", ");
}
result.append(")");
}
}
}
}
}
} | true | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CodeCompletions.java |
17 | public class CompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2, ICompletionProposalExtension4,
ICompletionProposalExtension6 {
protected final String text;
private final Image image;
protected final String prefix;
private final String description;
protected int offset;
private int length;
private boolean toggleOverwrite;
public CompletionProposal(int offset, String prefix, Image image,
String desc, String text) {
this.text = text;
this.image = image;
this.offset = offset;
this.prefix = prefix;
this.length = prefix.length();
this.description = desc;
Assert.isNotNull(description);
}
@Override
public Image getImage() {
return image;
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.length() - prefix.length(), 0);
}
public void apply(IDocument document) {
try {
document.replace(start(), length(document),
withoutDupeSemi(document));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
protected ReplaceEdit createEdit(IDocument document) {
return new ReplaceEdit(start(), length(document),
withoutDupeSemi(document));
}
public int length(IDocument document) {
String overwrite = EditorsUI.getPreferenceStore().getString(COMPLETION);
if ("overwrite".equals(overwrite)!=toggleOverwrite) {
int length = prefix.length();
try {
for (int i=offset;
i<document.getLength() &&
Character.isJavaIdentifierPart(document.getChar(i));
i++) {
length++;
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
return length;
}
else {
return this.length;
}
}
public int start() {
return offset-prefix.length();
}
public String withoutDupeSemi(IDocument document) {
try {
if (text.endsWith(";") &&
document.getChar(offset)==';') {
return text.substring(0,text.length()-1);
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
return text;
}
public String getDisplayString() {
return description;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public boolean isAutoInsertable() {
return true;
}
protected boolean qualifiedNameIsPath() {
return false;
}
@Override
public StyledString getStyledDisplayString() {
StyledString result = new StyledString();
Highlights.styleProposal(result, getDisplayString(),
qualifiedNameIsPath());
return result;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask,
int offset) {
toggleOverwrite = (stateMask&SWT.CTRL)!=0;
length = prefix.length() + offset - this.offset;
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
if (offset<this.offset) {
return false;
}
try {
//TODO: really this strategy is only applicable
// for completion of declaration names, so
// move this implementation to subclasses
int start = this.offset-prefix.length();
String typedText = document.get(start, offset-start);
return isNameMatching(typedText, text);
// String typedText = document.get(this.offset, offset-this.offset);
// return text.substring(prefix.length())
// .startsWith(typedText);
}
catch (BadLocationException e) {
return false;
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionProposal.java |
18 | public class CompletionUtil {
public static List<Declaration> overloads(Declaration dec) {
if (dec instanceof Functional && ((Functional) dec).isAbstraction()) {
return ((Functional) dec).getOverloads();
}
else {
return Collections.singletonList(dec);
}
}
static List<Parameter> getParameters(ParameterList pl,
boolean includeDefaults, boolean namedInvocation) {
List<Parameter> ps = pl.getParameters();
if (includeDefaults) {
return ps;
}
else {
List<Parameter> list = new ArrayList<Parameter>();
for (Parameter p: ps) {
if (!p.isDefaulted() ||
(namedInvocation &&
p==ps.get(ps.size()-1) &&
p.getModel() instanceof Value &&
p.getType()!=null &&
p.getDeclaration().getUnit()
.isIterableParameterType(p.getType()))) {
list.add(p);
}
}
return list;
}
}
static String fullPath(int offset, String prefix,
Tree.ImportPath path) {
StringBuilder fullPath = new StringBuilder();
if (path!=null) {
fullPath.append(Util.formatPath(path.getIdentifiers()));
fullPath.append('.');
fullPath.setLength(offset-path.getStartIndex()-prefix.length());
}
return fullPath.toString();
}
static boolean isPackageDescriptor(CeylonParseController cpc) {
return cpc.getRootNode() != null &&
cpc.getRootNode().getUnit() != null &&
cpc.getRootNode().getUnit().getFilename().equals("package.ceylon");
}
static boolean isModuleDescriptor(CeylonParseController cpc) {
return cpc.getRootNode() != null &&
cpc.getRootNode().getUnit() != null &&
cpc.getRootNode().getUnit().getFilename().equals("module.ceylon");
}
static boolean isEmptyModuleDescriptor(CeylonParseController cpc) {
return isModuleDescriptor(cpc) &&
cpc.getRootNode() != null &&
cpc.getRootNode().getModuleDescriptors().isEmpty();
}
static boolean isEmptyPackageDescriptor(CeylonParseController cpc) {
return cpc.getRootNode() != null &&
cpc.getRootNode().getUnit() != null &&
cpc.getRootNode().getUnit().getFilename().equals("package.ceylon") &&
cpc.getRootNode().getPackageDescriptors().isEmpty();
}
public static OccurrenceLocation getOccurrenceLocation(Tree.CompilationUnit cu,
Node node, int offset) {
FindOccurrenceLocationVisitor visitor =
new FindOccurrenceLocationVisitor(offset, node);
cu.visit(visitor);
return visitor.getOccurrenceLocation();
}
static int nextTokenType(final CeylonParseController cpc,
final CommonToken token) {
for (int i=token.getTokenIndex()+1; i<cpc.getTokens().size(); i++) {
CommonToken tok = cpc.getTokens().get(i);
if (tok.getChannel()!=CommonToken.HIDDEN_CHANNEL) {
return tok.getType();
}
}
return -1;
}
/**
* BaseMemberExpressions in Annotations have funny lying
* scopes, but we can extract the real scope out of the
* identifier! (Yick)
*/
static Scope getRealScope(final Node node, CompilationUnit cu) {
class FindScopeVisitor extends Visitor {
Scope scope;
public void visit(Tree.Declaration that) {
super.visit(that);
AnnotationList al = that.getAnnotationList();
if (al!=null) {
for (Tree.Annotation a: al.getAnnotations()) {
Integer i = a.getPrimary().getStartIndex();
Integer j = node.getStartIndex();
if (i.intValue()==j.intValue()) {
scope = that.getDeclarationModel().getScope();
}
}
}
}
public void visit(Tree.DocLink that) {
super.visit(that);
scope = ((Tree.DocLink)node).getPkg();
}
};
FindScopeVisitor fsv = new FindScopeVisitor();
fsv.visit(cu);
return fsv.scope==null ? node.getScope() : fsv.scope;
}
static int getLine(final int offset, ITextViewer viewer) {
int line=-1;
try {
line = viewer.getDocument().getLineOfOffset(offset);
}
catch (BadLocationException e) {
e.printStackTrace();
}
return line;
}
public static boolean isInBounds(List<ProducedType> upperBounds, ProducedType t) {
boolean ok = true;
for (ProducedType ub: upperBounds) {
if (!t.isSubtypeOf(ub) &&
!(ub.containsTypeParameters() &&
t.getDeclaration().inherits(ub.getDeclaration()))) {
ok = false;
break;
}
}
return ok;
}
public static List<DeclarationWithProximity> getSortedProposedValues(Scope scope, Unit unit) {
List<DeclarationWithProximity> results = new ArrayList<DeclarationWithProximity>(
scope.getMatchingDeclarations(unit, "", 0).values());
Collections.sort(results, new Comparator<DeclarationWithProximity>() {
public int compare(DeclarationWithProximity x, DeclarationWithProximity y) {
if (x.getProximity()<y.getProximity()) return -1;
if (x.getProximity()>y.getProximity()) return 1;
int c = x.getDeclaration().getName().compareTo(y.getDeclaration().getName());
if (c!=0) return c;
return x.getDeclaration().getQualifiedNameString()
.compareTo(y.getDeclaration().getQualifiedNameString());
}
});
return results;
}
public static boolean isIgnoredLanguageModuleClass(Class clazz) {
String name = clazz.getName();
return name.equals("String") ||
name.equals("Integer") ||
name.equals("Float") ||
name.equals("Character") ||
clazz.isAnnotation();
}
public static boolean isIgnoredLanguageModuleValue(Value value) {
String name = value.getName();
return name.equals("process") ||
name.equals("runtime") ||
name.equals("system") ||
name.equals("operatingSystem") ||
name.equals("language") ||
name.equals("emptyIterator") ||
name.equals("infinity") ||
name.endsWith("IntegerValue") ||
name.equals("finished");
}
public static boolean isIgnoredLanguageModuleMethod(Method method) {
String name = method.getName();
return name.equals("className") ||
name.equals("flatten") ||
name.equals("unflatten")||
name.equals("curry") ||
name.equals("uncurry") ||
name.equals("compose") ||
method.isAnnotation();
}
static boolean isIgnoredLanguageModuleType(TypeDeclaration td) {
String name = td.getName();
return !name.equals("Object") &&
!name.equals("Anything") &&
!name.equals("String") &&
!name.equals("Integer") &&
!name.equals("Character") &&
!name.equals("Float") &&
!name.equals("Boolean");
}
public static String getInitialValueDescription(final Declaration dec, CeylonParseController cpc) {
Node refnode = Nodes.getReferencedNode(dec, cpc);
Tree.SpecifierOrInitializerExpression sie = null;
String arrow = null;
if (refnode instanceof Tree.AttributeDeclaration) {
sie = ((Tree.AttributeDeclaration) refnode).getSpecifierOrInitializerExpression();
arrow = " = ";
}
else if (refnode instanceof Tree.MethodDeclaration) {
sie = ((Tree.MethodDeclaration) refnode).getSpecifierExpression();
arrow = " => ";
}
if (sie==null) {
class FindInitializerVisitor extends Visitor {
Tree.SpecifierOrInitializerExpression result;
@Override
public void visit(Tree.InitializerParameter that) {
super.visit(that);
Declaration d = that.getParameterModel().getModel();
if (d!=null && d.equals(dec)) {
result = that.getSpecifierExpression();
}
}
}
FindInitializerVisitor fiv = new FindInitializerVisitor();
fiv.visit(cpc.getRootNode());
sie = fiv.result;
}
if (sie!=null) {
if (sie.getExpression()!=null) {
Tree.Term term = sie.getExpression().getTerm();
if (term.getUnit().equals(cpc.getRootNode().getUnit())) {
return arrow + Nodes.toString(term, cpc.getTokens());
}
else if (term instanceof Tree.Literal) {
return arrow + term.getToken().getText();
}
else if (term instanceof Tree.BaseMemberOrTypeExpression) {
Tree.BaseMemberOrTypeExpression bme =
(Tree.BaseMemberOrTypeExpression) term;
if (bme.getIdentifier()!=null && bme.getTypeArguments()==null) {
return arrow + bme.getIdentifier().getText();
}
}
//don't have the token stream :-/
//TODO: figure out where to get it from!
return arrow + "...";
}
}
return "";
}
public static String getDefaultValueDescription(Parameter p,
CeylonParseController cpc) {
if (p.isDefaulted()) {
if (p.getModel() instanceof Functional) {
return " => ...";
}
else {
return getInitialValueDescription(p.getModel(), cpc);
}
}
else {
return "";
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionUtil.java |
19 | Collections.sort(results, new Comparator<DeclarationWithProximity>() {
public int compare(DeclarationWithProximity x, DeclarationWithProximity y) {
if (x.getProximity()<y.getProximity()) return -1;
if (x.getProximity()>y.getProximity()) return 1;
int c = x.getDeclaration().getName().compareTo(y.getDeclaration().getName());
if (c!=0) return c;
return x.getDeclaration().getQualifiedNameString()
.compareTo(y.getDeclaration().getQualifiedNameString());
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionUtil.java |
20 | class FindInitializerVisitor extends Visitor {
Tree.SpecifierOrInitializerExpression result;
@Override
public void visit(Tree.InitializerParameter that) {
super.visit(that);
Declaration d = that.getParameterModel().getModel();
if (d!=null && d.equals(dec)) {
result = that.getSpecifierExpression();
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionUtil.java |
21 | class FindScopeVisitor extends Visitor {
Scope scope;
public void visit(Tree.Declaration that) {
super.visit(that);
AnnotationList al = that.getAnnotationList();
if (al!=null) {
for (Tree.Annotation a: al.getAnnotations()) {
Integer i = a.getPrimary().getStartIndex();
Integer j = node.getStartIndex();
if (i.intValue()==j.intValue()) {
scope = that.getDeclarationModel().getScope();
}
}
}
}
public void visit(Tree.DocLink that) {
super.visit(that);
scope = ((Tree.DocLink)node).getPkg();
}
}; | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionUtil.java |
22 | class ControlStructureCompletionProposal extends CompletionProposal {
static void addForProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
DeclarationWithProximity dwp, Declaration d) {
if (d instanceof Value) {
TypedDeclaration td = (TypedDeclaration) d;
if (td.getType()!=null &&
d.getUnit().isIterableType(td.getType())) {
String elemName;
String name = d.getName();
if (name.length()==1) {
elemName = "element";
}
else if (name.endsWith("s")) {
elemName = name.substring(0, name.length()-1);
}
else {
elemName = name.substring(0, 1);
}
Unit unit = cpc.getRootNode().getUnit();
result.add(new ControlStructureCompletionProposal(offset, prefix,
"for (" + elemName + " in " + getDescriptionFor(d, unit) + ")",
"for (" + elemName + " in " + getTextFor(d, unit) + ") {}",
d, cpc));
}
}
}
static void addIfExistsProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
DeclarationWithProximity dwp, Declaration d) {
if (!dwp.isUnimported()) {
if (d instanceof Value) {
TypedDeclaration v = (TypedDeclaration) d;
if (v.getType()!=null &&
d.getUnit().isOptionalType(v.getType()) &&
!v.isVariable()) {
Unit unit = cpc.getRootNode().getUnit();
result.add(new ControlStructureCompletionProposal(offset, prefix,
"if (exists " + getDescriptionFor(d, unit) + ")",
"if (exists " + getTextFor(d, unit) + ") {}",
d, cpc));
}
}
}
}
static void addIfNonemptyProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
DeclarationWithProximity dwp, Declaration d) {
if (!dwp.isUnimported()) {
if (d instanceof Value) {
TypedDeclaration v = (TypedDeclaration) d;
if (v.getType()!=null &&
d.getUnit().isPossiblyEmptyType(v.getType()) &&
!v.isVariable()) {
Unit unit = cpc.getRootNode().getUnit();
result.add(new ControlStructureCompletionProposal(offset, prefix,
"if (nonempty " + getDescriptionFor(d, unit) + ")",
"if (nonempty " + getTextFor(d, unit) + ") {}",
d, cpc));
}
}
}
}
static void addTryProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
DeclarationWithProximity dwp, Declaration d) {
if (!dwp.isUnimported()) {
if (d instanceof Value) {
TypedDeclaration v = (TypedDeclaration) d;
if (v.getType()!=null &&
v.getType().getDeclaration()
.inherits(d.getUnit().getObtainableDeclaration()) &&
!v.isVariable()) {
Unit unit = cpc.getRootNode().getUnit();
result.add(new ControlStructureCompletionProposal(offset, prefix,
"try (" + getDescriptionFor(d, unit) + ")",
"try (" + getTextFor(d, unit) + ") {}",
d, cpc));
}
}
}
}
static void addSwitchProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
DeclarationWithProximity dwp, Declaration d, Node node,
IDocument doc) {
if (!dwp.isUnimported()) {
if (d instanceof Value) {
TypedDeclaration v = (TypedDeclaration) d;
if (v.getType()!=null &&
v.getType().getCaseTypes()!=null &&
!v.isVariable()) {
StringBuilder body = new StringBuilder();
String indent = getIndent(node, doc);
for (ProducedType pt: v.getType().getCaseTypes()) {
body.append(indent).append("case (");
if (!pt.getDeclaration().isAnonymous()) {
body.append("is ");
}
body.append(pt.getProducedTypeName(node.getUnit()))
.append(") {}")
.append(getDefaultLineDelimiter(doc));
}
body.append(indent);
Unit unit = cpc.getRootNode().getUnit();
result.add(new ControlStructureCompletionProposal(offset, prefix,
"switch (" + getDescriptionFor(d, unit) + ")",
"switch (" + getTextFor(d, unit) + ")" +
getDefaultLineDelimiter(doc) + body,
d, cpc));
}
}
}
}
private final CeylonParseController cpc;
private final Declaration declaration;
private ControlStructureCompletionProposal(int offset, String prefix,
String desc, String text, Declaration dec,
CeylonParseController cpc) {
super(offset, prefix, CeylonLabelProvider.MINOR_CHANGE,
desc, text);
this.cpc = cpc;
this.declaration = dec;
}
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, declaration);
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.indexOf('}') - prefix.length(), 0);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ControlStructureCompletionProposal.java |
23 | public class ControlStructureCompletions {
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ControlStructureCompletions.java |
24 | class FindOccurrenceLocationVisitor extends Visitor
implements NaturalVisitor {
private Node node;
private int offset;
private OccurrenceLocation occurrence;
private boolean inTypeConstraint = false;
FindOccurrenceLocationVisitor(int offset, Node node) {
this.offset = offset;
this.node = node;
}
OccurrenceLocation getOccurrenceLocation() {
return occurrence;
}
@Override
public void visitAny(Node that) {
if (inBounds(that)) {
super.visitAny(that);
}
//otherwise, as a performance optimization
//don't go any further down this branch
}
@Override
public void visit(Tree.Condition that) {
if (inBounds(that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.ExistsCondition that) {
super.visit(that);
if (that.getVariable()==null ?
inBounds(that) :
inBounds(that.getVariable().getIdentifier())) {
occurrence = EXISTS;
}
}
@Override
public void visit(Tree.NonemptyCondition that) {
super.visit(that);
if (that.getVariable()==null ?
inBounds(that) :
inBounds(that.getVariable().getIdentifier())) {
occurrence = NONEMPTY;
}
}
@Override
public void visit(Tree.IsCondition that) {
super.visit(that);
boolean inBounds;
if (that.getVariable()!=null) {
inBounds = inBounds(that.getVariable().getIdentifier());
}
else if (that.getType()!=null) {
inBounds = inBounds(that) && offset>that.getType().getStopIndex()+1;
}
else {
inBounds = false;
}
if (inBounds) {
occurrence = IS;
}
}
public void visit(Tree.TypeConstraint that) {
inTypeConstraint=true;
super.visit(that);
inTypeConstraint=false;
}
public void visit(Tree.ImportMemberOrTypeList that) {
if (inBounds(that)) {
occurrence = IMPORT;
}
super.visit(that);
}
public void visit(Tree.ExtendedType that) {
if (inBounds(that)) {
occurrence = EXTENDS;
}
super.visit(that);
}
public void visit(Tree.SatisfiedTypes that) {
if (inBounds(that)) {
occurrence = inTypeConstraint?
UPPER_BOUND : SATISFIES;
}
super.visit(that);
}
public void visit(Tree.CaseTypes that) {
if (inBounds(that)) {
occurrence = OF;
}
super.visit(that);
}
public void visit(Tree.CatchClause that) {
if (inBounds(that) &&
!inBounds(that.getBlock())) {
occurrence = CATCH;
}
else {
super.visit(that);
}
}
public void visit(Tree.CaseClause that) {
if (inBounds(that) &&
!inBounds(that.getBlock())) {
occurrence = CASE;
}
super.visit(that);
}
@Override
public void visit(Tree.BinaryOperatorExpression that) {
Term right = that.getRightTerm();
if (right==null) {
right = that;
}
Term left = that.getLeftTerm();
if (left==null) {
left = that;
}
if (inBounds(left, right)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.UnaryOperatorExpression that) {
Term term = that.getTerm();
if (term==null) {
term = that;
}
if (inBounds(that, term) || inBounds(term, that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.ParameterList that) {
if (inBounds(that)) {
occurrence = PARAMETER_LIST;
}
super.visit(that);
}
@Override
public void visit(Tree.TypeParameterList that) {
if (inBounds(that)) {
occurrence = TYPE_PARAMETER_LIST;
}
super.visit(that);
}
@Override
public void visit(Tree.TypeSpecifier that) {
if (inBounds(that)) {
occurrence = TYPE_ALIAS;
}
super.visit(that);
}
@Override
public void visit(Tree.ClassSpecifier that) {
if (inBounds(that)) {
occurrence = CLASS_ALIAS;
}
super.visit(that);
}
@Override
public void visit(Tree.SpecifierOrInitializerExpression that) {
if (inBounds(that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.ArgumentList that) {
if (inBounds(that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.TypeArgumentList that) {
if (inBounds(that)) {
occurrence = TYPE_ARGUMENT_LIST;
}
super.visit(that);
}
@Override
public void visit(QualifiedMemberOrTypeExpression that) {
if (inBounds(that.getMemberOperator(), that.getIdentifier())) {
occurrence = EXPRESSION;
}
else {
super.visit(that);
}
}
@Override
public void visit(Tree.Declaration that) {
if (inBounds(that)) {
if (occurrence!=PARAMETER_LIST) {
occurrence=null;
}
}
super.visit(that);
}
public void visit(Tree.MetaLiteral that) {
super.visit(that);
if (inBounds(that)) {
if (occurrence!=TYPE_ARGUMENT_LIST) {
switch (that.getNodeType()) {
case "ModuleLiteral":
occurrence=MODULE_REF;
break;
case "PackageLiteral":
occurrence=PACKAGE_REF;
break;
case "ValueLiteral":
occurrence=VALUE_REF;
break;
case "FunctionLiteral":
occurrence=FUNCTION_REF;
break;
case "InterfaceLiteral":
occurrence=INTERFACE_REF;
break;
case "ClassLiteral":
occurrence=CLASS_REF;
break;
case "TypeParameterLiteral":
occurrence=TYPE_PARAMETER_REF;
break;
case "AliasLiteral":
occurrence=ALIAS_REF;
break;
default:
occurrence = META;
}
}
}
}
public void visit(Tree.StringLiteral that) {
if (inBounds(that)) {
occurrence = DOCLINK;
}
}
public void visit(Tree.DocLink that) {
if (this.node instanceof Tree.DocLink) {
occurrence = DOCLINK;
}
}
private boolean inBounds(Node that) {
return inBounds(that, that);
}
private boolean inBounds(Node left, Node right) {
if (left==null) return false;
if (right==null) right=left;
Integer startIndex = left.getStartIndex();
Integer stopIndex = right.getStopIndex();
return startIndex!=null && stopIndex!=null &&
startIndex <= node.getStartIndex() &&
stopIndex >= node.getStopIndex();
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_FindOccurrenceLocationVisitor.java |
25 | final class FunctionCompletionProposal extends
CompletionProposal {
private final CeylonParseController cpc;
private final Declaration dec;
private FunctionCompletionProposal(int offset, String prefix,
String desc, String text, Declaration dec,
CeylonParseController cpc) {
super(offset, prefix,
getDecoratedImage(dec.isShared() ?
CEYLON_FUN : CEYLON_LOCAL_FUN,
getDecorationAttributes(dec), false),
desc, text);
this.cpc = cpc;
this.dec = dec;
}
private DocumentChange createChange(IDocument document)
throws BadLocationException {
DocumentChange change =
new DocumentChange("Complete Invocation", document);
change.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
Tree.CompilationUnit cu = cpc.getRootNode();
importDeclaration(decs, dec, cu);
int il=applyImports(change, decs, cu, document);
change.addEdit(createEdit(document));
offset+=il;
return change;
}
@Override
public boolean isAutoInsertable() {
return false;
}
@Override
public void apply(IDocument document) {
try {
createChange(document).perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}
}
protected static void addFunctionProposal(int offset,
final CeylonParseController cpc,
Tree.Primary primary,
List<ICompletionProposal> result,
final Declaration dec,
IDocument doc) {
Tree.Term arg = primary;
while (arg instanceof Tree.Expression) {
arg = ((Tree.Expression) arg).getTerm();
}
final int start = arg.getStartIndex();
final int stop = arg.getStopIndex();
int origin = primary.getStartIndex();
String argText;
String prefix;
try {
//the argument
argText = doc.get(start, stop-start+1);
//the text to replace
prefix = doc.get(origin, offset-origin);
}
catch (BadLocationException e) {
return;
}
String text = dec.getName(arg.getUnit())
+ "(" + argText + ")";
if (((Functional)dec).isDeclaredVoid()) {
text += ";";
}
Unit unit = cpc.getRootNode().getUnit();
result.add(new FunctionCompletionProposal(offset, prefix,
getDescriptionFor(dec, unit) + "(...)", text, dec, cpc));
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_FunctionCompletionProposal.java |
26 | final class ImportVisitor extends Visitor {
private final String prefix;
private final CommonToken token;
private final int offset;
private final Node node;
private final CeylonParseController cpc;
private final List<ICompletionProposal> result;
ImportVisitor(String prefix, CommonToken token, int offset,
Node node, CeylonParseController cpc,
List<ICompletionProposal> result) {
this.prefix = prefix;
this.token = token;
this.offset = offset;
this.node = node;
this.cpc = cpc;
this.result = result;
}
@Override
public void visit(Tree.ModuleDescriptor that) {
super.visit(that);
if (that.getImportPath()==node) {
addCurrentPackageNameCompletion(cpc, offset,
fullPath(offset, prefix, that.getImportPath()) + prefix,
result);
}
}
public void visit(Tree.PackageDescriptor that) {
super.visit(that);
if (that.getImportPath()==node) {
addCurrentPackageNameCompletion(cpc, offset,
fullPath(offset, prefix, that.getImportPath()) + prefix,
result);
}
}
@Override
public void visit(Tree.Import that) {
super.visit(that);
if (that.getImportPath()==node) {
addPackageCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result,
nextTokenType(cpc, token)!=CeylonLexer.LBRACE);
}
}
@Override
public void visit(Tree.PackageLiteral that) {
super.visit(that);
if (that.getImportPath()==node) {
addPackageCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result, false);
}
}
@Override
public void visit(Tree.ImportModule that) {
super.visit(that);
if (that.getImportPath()==node) {
addModuleCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result,
nextTokenType(cpc, token)!=CeylonLexer.STRING_LITERAL);
}
}
@Override
public void visit(Tree.ModuleLiteral that) {
super.visit(that);
if (that.getImportPath()==node) {
addModuleCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result, false);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ImportVisitor.java |
27 | class InvocationCompletionProposal extends CompletionProposal {
static void addProgramElementReferenceProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, Scope scope, boolean isMember) {
Unit unit = cpc.getRootNode().getUnit();
result.add(new InvocationCompletionProposal(offset, prefix,
dec.getName(unit), escapeName(dec, unit),
dec, dec.getReference(), scope, cpc,
true, false, false, isMember, null));
}
static void addReferenceProposal(int offset, String prefix,
final CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, Scope scope, boolean isMember,
ProducedReference pr, OccurrenceLocation ol) {
Unit unit = cpc.getRootNode().getUnit();
//proposal with type args
if (dec instanceof Generic) {
result.add(new InvocationCompletionProposal(offset, prefix,
getDescriptionFor(dec, unit), getTextFor(dec, unit),
dec, pr, scope, cpc, true, false, false, isMember, null));
if (((Generic) dec).getTypeParameters().isEmpty()) {
//don't add another proposal below!
return;
}
}
//proposal without type args
boolean isAbstract =
dec instanceof Class && ((Class) dec).isAbstract() ||
dec instanceof Interface;
if ((!isAbstract &&
ol!=EXTENDS && ol!=SATISFIES &&
ol!=CLASS_ALIAS && ol!=TYPE_ALIAS)) {
result.add(new InvocationCompletionProposal(offset, prefix,
dec.getName(unit), escapeName(dec, unit),
dec, pr, scope, cpc, true, false, false, isMember, null));
}
}
static void addSecondLevelProposal(int offset, String prefix,
final CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, Scope scope, boolean isMember, ProducedReference pr,
ProducedType requiredType, OccurrenceLocation ol) {
if (!(dec instanceof Functional) &&
!(dec instanceof TypeDeclaration)) {
//add qualified member proposals
Unit unit = cpc.getRootNode().getUnit();
ProducedType type = pr.getType();
if (isTypeUnknown(type)) return;
Collection<DeclarationWithProximity> members =
type.getDeclaration().getMatchingMemberDeclarations(unit, scope, "", 0).values();
for (DeclarationWithProximity ndwp: members) {
final Declaration m = ndwp.getDeclaration();
if (m instanceof TypedDeclaration) { //TODO: member Class would also be useful!
final ProducedTypedReference ptr =
type.getTypedMember((TypedDeclaration) m,
Collections.<ProducedType>emptyList());
ProducedType mt = ptr.getType();
if (mt!=null &&
(requiredType==null || mt.isSubtypeOf(requiredType))) {
result.add(new InvocationCompletionProposal(offset, prefix,
dec.getName() + "." + getPositionalInvocationDescriptionFor(m, ol, ptr, unit, false, null),
dec.getName() + "." + getPositionalInvocationTextFor(m, ol, ptr, unit, false, null),
m, ptr, scope, cpc, true, true, false, true, dec));
}
}
}
}
}
static void addInvocationProposals(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, ProducedReference pr, Scope scope,
OccurrenceLocation ol, String typeArgs, boolean isMember) {
if (dec instanceof Functional) {
Unit unit = cpc.getRootNode().getUnit();
boolean isAbstractClass =
dec instanceof Class && ((Class) dec).isAbstract();
Functional fd = (Functional) dec;
List<ParameterList> pls = fd.getParameterLists();
if (!pls.isEmpty()) {
ParameterList parameterList = pls.get(0);
List<Parameter> ps = parameterList.getParameters();
String inexactMatches = EditorsUI.getPreferenceStore().getString(INEXACT_MATCHES);
boolean exact = (typeArgs==null ? prefix : prefix.substring(0,prefix.length()-typeArgs.length()))
.equalsIgnoreCase(dec.getName(unit));
boolean positional = exact ||
"both".equals(inexactMatches) ||
"positional".equals(inexactMatches);
boolean named = exact ||
"both".equals(inexactMatches);
if (positional &&
(!isAbstractClass || ol==EXTENDS || ol==CLASS_ALIAS)) {
if (ps.size()!=getParameters(parameterList, false, false).size()) {
result.add(new InvocationCompletionProposal(offset, prefix,
getPositionalInvocationDescriptionFor(dec, ol, pr, unit, false, typeArgs),
getPositionalInvocationTextFor(dec, ol, pr, unit, false, typeArgs), dec,
pr, scope, cpc, false, true, false, isMember, null));
}
result.add(new InvocationCompletionProposal(offset, prefix,
getPositionalInvocationDescriptionFor(dec, ol, pr, unit, true, typeArgs),
getPositionalInvocationTextFor(dec, ol, pr, unit, true, typeArgs), dec,
pr, scope, cpc, true, true, false, isMember, null));
}
if (named &&
(!isAbstractClass && ol!=EXTENDS && ol!=CLASS_ALIAS &&
!fd.isOverloaded())) {
//if there is at least one parameter,
//suggest a named argument invocation
if (ps.size()!=getParameters(parameterList, false, true).size()) {
result.add(new InvocationCompletionProposal(offset, prefix,
getNamedInvocationDescriptionFor(dec, pr, unit, false, typeArgs),
getNamedInvocationTextFor(dec, pr, unit, false, typeArgs), dec,
pr, scope, cpc, false, false, true, isMember, null));
}
if (!ps.isEmpty()) {
result.add(new InvocationCompletionProposal(offset, prefix,
getNamedInvocationDescriptionFor(dec, pr, unit, true, typeArgs),
getNamedInvocationTextFor(dec, pr, unit, true, typeArgs), dec,
pr, scope, cpc, true, false, true, isMember, null));
}
}
}
}
}
final class NestedCompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2 {
private final String op;
private final int loc;
private final int index;
private final boolean basic;
private final Declaration dec;
NestedCompletionProposal(Declaration dec, int loc,
int index, boolean basic, String op) {
this.op = op;
this.loc = loc;
this.index = index;
this.basic = basic;
this.dec = dec;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
//the following awfulness is necessary because the
//insertion point may have changed (and even its
//text may have changed, since the proposal was
//instantiated).
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
if (offset>0 && document.getChar(offset)==' ') {
offset++;
}
int nextOffset = findCharCount(index+1, document,
loc+startOfArgs, endOfLine,
",;", "", true);
int middleOffset = findCharCount(1, document,
offset, nextOffset,
"=", "", true)+1;
if (middleOffset>0 &&
document.getChar(middleOffset)=='>') {
middleOffset++;
}
while (middleOffset>0 &&
document.getChar(middleOffset)==' ') {
middleOffset++;
}
if (middleOffset>offset &&
middleOffset<nextOffset) {
offset = middleOffset;
}
String str = getText(false);
if (nextOffset==-1) {
nextOffset = offset;
}
if (document.getChar(nextOffset)=='}') {
str += " ";
}
document.replace(offset, nextOffset-offset, str);
}
catch (BadLocationException e) {
e.printStackTrace();
}
//adding imports drops us out of linked mode :(
/*try {
DocumentChange tc = new DocumentChange("imports", document);
tc.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
CompilationUnit cu = cpc.getRootNode();
importDeclaration(decs, d, cu);
if (d instanceof Functional) {
List<ParameterList> pls = ((Functional) d).getParameterLists();
if (!pls.isEmpty()) {
for (Parameter p: pls.get(0).getParameters()) {
MethodOrValue pm = p.getModel();
if (pm instanceof Method) {
for (ParameterList ppl: ((Method) pm).getParameterLists()) {
for (Parameter pp: ppl.getParameters()) {
importSignatureTypes(pp.getModel(), cu, decs);
}
}
}
}
}
}
applyImports(tc, decs, cu, document);
tc.perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}*/
}
private String getText(boolean description) {
StringBuilder sb = new StringBuilder()
.append(op).append(dec.getName(getUnit()));
if (dec instanceof Functional && !basic) {
appendPositionalArgs(dec, getUnit(), sb,
false, description);
}
return sb.toString();
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getDisplayString() {
return getText(true);
}
@Override
public Image getImage() {
return getImageForDeclaration(dec);
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int currentOffset,
DocumentEvent event) {
if (event==null) {
return true;
}
else {
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
String content = document.get(offset, currentOffset - offset);
int eq = content.indexOf("=");
if (eq>0) {
content = content.substring(eq+1);
}
String filter = content.trim().toLowerCase();
String decName = dec.getName(getUnit());
if ((op+decName).toLowerCase().startsWith(filter) ||
decName.toLowerCase().startsWith(filter)) {
return true;
}
}
catch (BadLocationException e) {
// ignore concurrently modified document
}
return false;
}
}
}
final class NestedLiteralCompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2 {
private final int loc;
private final int index;
private final String value;
NestedLiteralCompletionProposal(String value, int loc,
int index) {
this.value = value;
this.loc = loc;
this.index = index;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
//the following awfulness is necessary because the
//insertion point may have changed (and even its
//text may have changed, since the proposal was
//instantiated).
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
if (offset>0 && document.getChar(offset)==' ') {
offset++;
}
int nextOffset = findCharCount(index+1, document,
loc+startOfArgs, endOfLine,
",;", "", true);
int middleOffset = findCharCount(1, document,
offset, nextOffset,
"=", "", true)+1;
if (middleOffset>0 &&
document.getChar(middleOffset)=='>') {
middleOffset++;
}
while (middleOffset>0 &&
document.getChar(middleOffset)==' ') {
middleOffset++;
}
if (middleOffset>offset &&
middleOffset<nextOffset) {
offset = middleOffset;
}
String str = value;
if (nextOffset==-1) {
nextOffset = offset;
}
if (document.getChar(nextOffset)=='}') {
str += " ";
}
document.replace(offset, nextOffset-offset, str);
}
catch (BadLocationException e) {
e.printStackTrace();
}
//adding imports drops us out of linked mode :(
/*try {
DocumentChange tc = new DocumentChange("imports", document);
tc.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
CompilationUnit cu = cpc.getRootNode();
importDeclaration(decs, d, cu);
if (d instanceof Functional) {
List<ParameterList> pls = ((Functional) d).getParameterLists();
if (!pls.isEmpty()) {
for (Parameter p: pls.get(0).getParameters()) {
MethodOrValue pm = p.getModel();
if (pm instanceof Method) {
for (ParameterList ppl: ((Method) pm).getParameterLists()) {
for (Parameter pp: ppl.getParameters()) {
importSignatureTypes(pp.getModel(), cu, decs);
}
}
}
}
}
}
applyImports(tc, decs, cu, document);
tc.perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}*/
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getDisplayString() {
return value;
}
@Override
public Image getImage() {
return getDecoratedImage(CEYLON_LITERAL, 0, false);
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int currentOffset,
DocumentEvent event) {
if (event==null) {
return true;
}
else {
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
String content = document.get(offset, currentOffset - offset);
int eq = content.indexOf("=");
if (eq>0) {
content = content.substring(eq+1);
}
String filter = content.trim().toLowerCase();
if (value.toLowerCase().startsWith(filter)) {
return true;
}
}
catch (BadLocationException e) {
// ignore concurrently modified document
}
return false;
}
}
}
private final CeylonParseController cpc;
private final Declaration declaration;
private final ProducedReference producedReference;
private final Scope scope;
private final boolean includeDefaulted;
private final boolean namedInvocation;
private final boolean positionalInvocation;
private final boolean qualified;
private Declaration qualifyingValue;
private InvocationCompletionProposal(int offset, String prefix,
String desc, String text, Declaration dec,
ProducedReference producedReference, Scope scope,
CeylonParseController cpc, boolean includeDefaulted,
boolean positionalInvocation, boolean namedInvocation,
boolean qualified, Declaration qualifyingValue) {
super(offset, prefix, getImageForDeclaration(dec),
desc, text);
this.cpc = cpc;
this.declaration = dec;
this.producedReference = producedReference;
this.scope = scope;
this.includeDefaulted = includeDefaulted;
this.namedInvocation = namedInvocation;
this.positionalInvocation = positionalInvocation;
this.qualified = qualified;
this.qualifyingValue = qualifyingValue;
}
private Unit getUnit() {
return cpc.getRootNode().getUnit();
}
private DocumentChange createChange(IDocument document)
throws BadLocationException {
DocumentChange change =
new DocumentChange("Complete Invocation", document);
change.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
Tree.CompilationUnit cu = cpc.getRootNode();
if (qualifyingValue!=null) {
importDeclaration(decs, qualifyingValue, cu);
}
if (!qualified) {
importDeclaration(decs, declaration, cu);
}
if (positionalInvocation||namedInvocation) {
importCallableParameterParamTypes(declaration, decs, cu);
}
int il=applyImports(change, decs, cu, document);
change.addEdit(createEdit(document));
offset+=il;
return change;
}
@Override
public void apply(IDocument document) {
try {
createChange(document).perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}
if (EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
activeLinkedMode(document);
}
}
private void activeLinkedMode(IDocument document) {
if (declaration instanceof Generic) {
Generic generic = (Generic) declaration;
ParameterList paramList = null;
if (declaration instanceof Functional &&
(positionalInvocation||namedInvocation)) {
List<ParameterList> pls =
((Functional) declaration).getParameterLists();
if (!pls.isEmpty() &&
!pls.get(0).getParameters().isEmpty()) {
paramList = pls.get(0);
}
}
if (paramList!=null) {
List<Parameter> params = getParameters(paramList,
includeDefaulted, namedInvocation);
if (!params.isEmpty()) {
enterLinkedMode(document, params, null);
return; //NOTE: early exit!
}
}
List<TypeParameter> typeParams = generic.getTypeParameters();
if (!typeParams.isEmpty()) {
enterLinkedMode(document, null, typeParams);
}
}
}
@Override
public Point getSelection(IDocument document) {
int first = getFirstPosition();
if (first<=0) {
//no arg list
return super.getSelection(document);
}
int next = getNextPosition(document, first);
if (next<=0) {
//an empty arg list
return super.getSelection(document);
}
int middle = getCompletionPosition(first, next);
int start = offset-prefix.length()+first+middle;
int len = next-middle;
try {
if (document.get(start, len).trim().equals("{}")) {
start++;
len=0;
}
} catch (BadLocationException e) {}
return new Point(start, len);
}
protected int getCompletionPosition(int first, int next) {
return text.substring(first, first+next-1).lastIndexOf(' ')+1;
}
protected int getFirstPosition() {
int index;
if (namedInvocation) {
index = text.indexOf('{');
}
else if (positionalInvocation) {
index = text.indexOf('(');
}
else {
index = text.indexOf('<');
}
return index+1;
}
public int getNextPosition(IDocument document,
int lastOffset) {
int loc = offset-prefix.length();
int comma = -1;
try {
int start = loc+lastOffset;
int end = loc+text.length()-1;
if (text.endsWith(";")) {
end--;
}
comma = findCharCount(1, document, start, end,
",;", "", true) - start;
}
catch (BadLocationException e) {
e.printStackTrace();
}
if (comma<0) {
int index;
if (namedInvocation) {
index = text.lastIndexOf('}');
}
else if (positionalInvocation) {
index = text.lastIndexOf(')');
}
else {
index = text.lastIndexOf('>');
}
return index - lastOffset;
}
return comma;
}
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, declaration,
producedReference);
}
public void enterLinkedMode(IDocument document,
List<Parameter> params,
List<TypeParameter> typeParams) {
boolean proposeTypeArguments = params==null;
int paramCount = proposeTypeArguments ?
typeParams.size() : params.size();
if (paramCount==0) return;
try {
final int loc = offset-prefix.length();
int first = getFirstPosition();
if (first<=0) return; //no arg list
int next = getNextPosition(document, first);
if (next<=0) return; //empty arg list
LinkedModeModel linkedModeModel = new LinkedModeModel();
int seq=0, param=0;
while (next>0 && param<paramCount) {
boolean voidParam = !proposeTypeArguments &&
params.get(param).isDeclaredVoid();
if (proposeTypeArguments || positionalInvocation ||
//don't create linked positions for
//void callable parameters in named
//argument lists
!voidParam) {
List<ICompletionProposal> props =
new ArrayList<ICompletionProposal>();
if (proposeTypeArguments) {
addTypeArgumentProposals(typeParams.get(seq),
loc, first, props, seq);
}
else if (!voidParam) {
addValueArgumentProposals(params.get(param),
loc, first, props, seq,
param==params.size()-1);
}
int middle = getCompletionPosition(first, next);
int start = loc+first+middle;
int len = next-middle;
if (voidParam) {
start++;
len=0;
}
ProposalPosition linkedPosition =
new ProposalPosition(document, start, len, seq,
props.toArray(NO_COMPLETIONS));
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
first = first+next+1;
next = getNextPosition(document, first);
seq++;
}
param++;
}
if (seq>0) {
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
seq, loc+text.length());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void addValueArgumentProposals(Parameter p, final int loc,
int first, List<ICompletionProposal> props, int index,
boolean last) {
if (p.getModel().isDynamicallyTyped()) {
return;
}
ProducedType type = producedReference.getTypedParameter(p)
.getType();
if (type==null) return;
Unit unit = getUnit();
List<DeclarationWithProximity> proposals =
getSortedProposedValues(scope, unit);
for (DeclarationWithProximity dwp: proposals) {
if (dwp.getProximity()<=1) {
addValueArgumentProposal(p, loc, props, index, last,
type, unit, dwp);
}
}
addLiteralProposals(loc, props, index, type, unit);
for (DeclarationWithProximity dwp: proposals) {
if (dwp.getProximity()>1) {
addValueArgumentProposal(p, loc, props, index, last,
type, unit, dwp);
}
}
}
private void addValueArgumentProposal(Parameter p, final int loc,
List<ICompletionProposal> props, int index, boolean last,
ProducedType type, Unit unit, DeclarationWithProximity dwp) {
if (dwp.isUnimported()) {
return;
}
TypeDeclaration td = type.getDeclaration();
Declaration d = dwp.getDeclaration();
if (d instanceof Value) {
Value value = (Value) d;
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleValue(value)) {
return;
}
}
ProducedType vt = value.getType();
if (vt!=null && !vt.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), vt) ||
vt.isSubtypeOf(type))) {
boolean isIterArg = namedInvocation && last &&
unit.isIterableParameterType(type);
boolean isVarArg = p.isSequenced() && positionalInvocation;
props.add(new NestedCompletionProposal(d,
loc, index, false, isIterArg || isVarArg ? "*" : ""));
}
}
if (d instanceof Method) {
if (!d.isAnnotation()) {
Method method = (Method) d;
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleMethod(method)) {
return;
}
}
ProducedType mt = method.getType();
if (mt!=null && !mt.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), mt) ||
mt.isSubtypeOf(type))) {
boolean isIterArg = namedInvocation && last &&
unit.isIterableParameterType(type);
boolean isVarArg = p.isSequenced() && positionalInvocation;
props.add(new NestedCompletionProposal(d,
loc, index, false, isIterArg || isVarArg ? "*" : ""));
}
}
}
if (d instanceof Class) {
Class clazz = (Class) d;
if (!clazz.isAbstract() && !d.isAnnotation()) {
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleClass(clazz)) {
return;
}
}
ProducedType ct = clazz.getType();
if (ct!=null && !ct.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), ct) ||
ct.getDeclaration().equals(type.getDeclaration()) ||
ct.isSubtypeOf(type))) {
boolean isIterArg = namedInvocation && last &&
unit.isIterableParameterType(type);
boolean isVarArg = p.isSequenced() && positionalInvocation;
props.add(new NestedCompletionProposal(d, loc, index, false,
isIterArg || isVarArg ? "*" : ""));
}
}
}
}
private void addLiteralProposals(final int loc,
List<ICompletionProposal> props, int index, ProducedType type,
Unit unit) {
TypeDeclaration dtd = unit.getDefiniteType(type).getDeclaration();
if (dtd instanceof Class) {
if (dtd.equals(unit.getIntegerDeclaration())) {
props.add(new NestedLiteralCompletionProposal("0", loc, index));
props.add(new NestedLiteralCompletionProposal("1", loc, index));
}
if (dtd.equals(unit.getFloatDeclaration())) {
props.add(new NestedLiteralCompletionProposal("0.0", loc, index));
props.add(new NestedLiteralCompletionProposal("1.0", loc, index));
}
if (dtd.equals(unit.getStringDeclaration())) {
props.add(new NestedLiteralCompletionProposal("\"\"", loc, index));
}
if (dtd.equals(unit.getCharacterDeclaration())) {
props.add(new NestedLiteralCompletionProposal("' '", loc, index));
props.add(new NestedLiteralCompletionProposal("'\\n'", loc, index));
props.add(new NestedLiteralCompletionProposal("'\\t'", loc, index));
}
}
else if (dtd instanceof Interface) {
if (dtd.equals(unit.getIterableDeclaration())) {
props.add(new NestedLiteralCompletionProposal("{}", loc, index));
}
if (dtd.equals(unit.getSequentialDeclaration()) ||
dtd.equals(unit.getEmptyDeclaration())) {
props.add(new NestedLiteralCompletionProposal("[]", loc, index));
}
}
}
private void addTypeArgumentProposals(TypeParameter tp,
final int loc, int first, List<ICompletionProposal> props,
final int index) {
for (DeclarationWithProximity dwp:
getSortedProposedValues(scope, getUnit())) {
Declaration d = dwp.getDeclaration();
if (d instanceof TypeDeclaration && !dwp.isUnimported()) {
TypeDeclaration td = (TypeDeclaration) d;
ProducedType t = td.getType();
if (td.getTypeParameters().isEmpty() &&
!td.isAnnotation() &&
!(td instanceof NothingType) &&
!td.inherits(td.getUnit().getExceptionDeclaration())) {
if (td.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleType(td)) {
continue;
}
}
if (isInBounds(tp.getSatisfiedTypes(), t)) {
props.add(new NestedCompletionProposal(d, loc, index,
true, ""));
}
}
}
}
}
@Override
public IContextInformation getContextInformation() {
if (namedInvocation||positionalInvocation) { //TODO: context info for type arg lists!
if (declaration instanceof Functional) {
List<ParameterList> pls = ((Functional) declaration).getParameterLists();
if (!pls.isEmpty()) {
int argListOffset = isParameterInfo() ?
this.offset :
offset-prefix.length() +
text.indexOf(namedInvocation?'{':'(');
return new ParameterContextInformation(declaration,
producedReference, getUnit(),
pls.get(0), argListOffset, includeDefaulted,
namedInvocation /*!isParameterInfo()*/);
}
}
}
return null;
}
boolean isParameterInfo() {
return false;
}
static final class ParameterInfo
extends InvocationCompletionProposal {
private ParameterInfo(int offset, Declaration dec,
ProducedReference producedReference,
Scope scope, CeylonParseController cpc,
boolean namedInvocation) {
super(offset, "", "show parameters", "", dec,
producedReference, scope, cpc, true,
true, namedInvocation, false, null);
}
@Override
boolean isParameterInfo() {
return true;
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public void apply(IDocument document) {}
}
static List<IContextInformation> computeParameterContextInformation(final int offset,
final Tree.CompilationUnit rootNode, final ITextViewer viewer) {
final List<IContextInformation> infos =
new ArrayList<IContextInformation>();
rootNode.visit(new Visitor() {
@Override
public void visit(Tree.InvocationExpression that) {
Tree.ArgumentList al = that.getPositionalArgumentList();
if (al==null) {
al = that.getNamedArgumentList();
}
if (al!=null) {
//TODO: should reuse logic for adjusting tokens
// from CeylonContentProposer!!
Integer start = al.getStartIndex();
Integer stop = al.getStopIndex();
if (start!=null && stop!=null && offset>start) {
String string = "";
if (offset>stop) {
try {
string = viewer.getDocument()
.get(stop+1, offset-stop-1);
}
catch (BadLocationException e) {}
}
if (string.trim().isEmpty()) {
Tree.MemberOrTypeExpression mte =
(Tree.MemberOrTypeExpression) that.getPrimary();
Declaration declaration = mte.getDeclaration();
if (declaration instanceof Functional) {
List<ParameterList> pls =
((Functional) declaration).getParameterLists();
if (!pls.isEmpty()) {
//Note: This line suppresses the little menu
// that gives me a choice of context infos.
// Delete it to get a choice of all surrounding
// argument lists.
infos.clear();
infos.add(new ParameterContextInformation(declaration,
mte.getTarget(), rootNode.getUnit(),
pls.get(0), al.getStartIndex(),
true, al instanceof Tree.NamedArgumentList /*false*/));
}
}
}
}
}
super.visit(that);
}
});
return infos;
}
static void addFakeShowParametersCompletion(final Node node,
final CeylonParseController cpc,
final List<ICompletionProposal> result) {
new Visitor() {
@Override
public void visit(Tree.InvocationExpression that) {
Tree.ArgumentList al = that.getPositionalArgumentList();
if (al==null) {
al = that.getNamedArgumentList();
}
if (al!=null) {
Integer startIndex = al.getStartIndex();
Integer startIndex2 = node.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
Tree.Primary primary = that.getPrimary();
if (primary instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte =
(Tree.MemberOrTypeExpression) primary;
if (mte.getDeclaration()!=null && mte.getTarget()!=null) {
result.add(new ParameterInfo(al.getStartIndex(),
mte.getDeclaration(), mte.getTarget(),
node.getScope(), cpc,
al instanceof Tree.NamedArgumentList));
}
}
}
}
super.visit(that);
}
}.visit(cpc.getRootNode());
}
static final class ParameterContextInformation
implements IContextInformation {
private final Declaration declaration;
private final ProducedReference producedReference;
private final ParameterList parameterList;
private final int argumentListOffset;
private final Unit unit;
private final boolean includeDefaulted;
// private final boolean inLinkedMode;
private final boolean namedInvocation;
private ParameterContextInformation(Declaration declaration,
ProducedReference producedReference, Unit unit,
ParameterList parameterList, int argumentListOffset,
boolean includeDefaulted, boolean namedInvocation) {
// boolean inLinkedMode
this.declaration = declaration;
this.producedReference = producedReference;
this.unit = unit;
this.parameterList = parameterList;
this.argumentListOffset = argumentListOffset;
this.includeDefaulted = includeDefaulted;
// this.inLinkedMode = inLinkedMode;
this.namedInvocation = namedInvocation;
}
@Override
public String getContextDisplayString() {
return "Parameters of '" + declaration.getName() + "'";
}
@Override
public Image getImage() {
return getImageForDeclaration(declaration);
}
@Override
public String getInformationDisplayString() {
List<Parameter> ps = getParameters(parameterList,
includeDefaulted, namedInvocation);
if (ps.isEmpty()) {
return "no parameters";
}
StringBuilder result = new StringBuilder();
for (Parameter p: ps) {
boolean isListedValues = namedInvocation &&
p==ps.get(ps.size()-1) &&
p.getModel() instanceof Value &&
p.getType()!=null &&
unit.isIterableParameterType(p.getType());
if (includeDefaulted || !p.isDefaulted() ||
isListedValues) {
if (producedReference==null) {
result.append(p.getName());
}
else {
ProducedTypedReference pr =
producedReference.getTypedParameter(p);
appendParameterContextInfo(result, pr, p, unit,
namedInvocation, isListedValues);
}
if (!isListedValues) {
result.append(namedInvocation ? "; " : ", ");
}
}
}
if (!namedInvocation && result.length()>0) {
result.setLength(result.length()-2);
}
return result.toString();
}
@Override
public boolean equals(Object that) {
if (that instanceof ParameterContextInformation) {
return ((ParameterContextInformation) that).declaration
.equals(declaration);
}
else {
return false;
}
}
int getArgumentListOffset() {
return argumentListOffset;
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java |
28 | rootNode.visit(new Visitor() {
@Override
public void visit(Tree.InvocationExpression that) {
Tree.ArgumentList al = that.getPositionalArgumentList();
if (al==null) {
al = that.getNamedArgumentList();
}
if (al!=null) {
//TODO: should reuse logic for adjusting tokens
// from CeylonContentProposer!!
Integer start = al.getStartIndex();
Integer stop = al.getStopIndex();
if (start!=null && stop!=null && offset>start) {
String string = "";
if (offset>stop) {
try {
string = viewer.getDocument()
.get(stop+1, offset-stop-1);
}
catch (BadLocationException e) {}
}
if (string.trim().isEmpty()) {
Tree.MemberOrTypeExpression mte =
(Tree.MemberOrTypeExpression) that.getPrimary();
Declaration declaration = mte.getDeclaration();
if (declaration instanceof Functional) {
List<ParameterList> pls =
((Functional) declaration).getParameterLists();
if (!pls.isEmpty()) {
//Note: This line suppresses the little menu
// that gives me a choice of context infos.
// Delete it to get a choice of all surrounding
// argument lists.
infos.clear();
infos.add(new ParameterContextInformation(declaration,
mte.getTarget(), rootNode.getUnit(),
pls.get(0), al.getStartIndex(),
true, al instanceof Tree.NamedArgumentList /*false*/));
}
}
}
}
}
super.visit(that);
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java |
29 | new Visitor() {
@Override
public void visit(Tree.InvocationExpression that) {
Tree.ArgumentList al = that.getPositionalArgumentList();
if (al==null) {
al = that.getNamedArgumentList();
}
if (al!=null) {
Integer startIndex = al.getStartIndex();
Integer startIndex2 = node.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
Tree.Primary primary = that.getPrimary();
if (primary instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte =
(Tree.MemberOrTypeExpression) primary;
if (mte.getDeclaration()!=null && mte.getTarget()!=null) {
result.add(new ParameterInfo(al.getStartIndex(),
mte.getDeclaration(), mte.getTarget(),
node.getScope(), cpc,
al instanceof Tree.NamedArgumentList));
}
}
}
}
super.visit(that);
}
}.visit(cpc.getRootNode()); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java |
30 | final class NestedCompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2 {
private final String op;
private final int loc;
private final int index;
private final boolean basic;
private final Declaration dec;
NestedCompletionProposal(Declaration dec, int loc,
int index, boolean basic, String op) {
this.op = op;
this.loc = loc;
this.index = index;
this.basic = basic;
this.dec = dec;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
//the following awfulness is necessary because the
//insertion point may have changed (and even its
//text may have changed, since the proposal was
//instantiated).
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
if (offset>0 && document.getChar(offset)==' ') {
offset++;
}
int nextOffset = findCharCount(index+1, document,
loc+startOfArgs, endOfLine,
",;", "", true);
int middleOffset = findCharCount(1, document,
offset, nextOffset,
"=", "", true)+1;
if (middleOffset>0 &&
document.getChar(middleOffset)=='>') {
middleOffset++;
}
while (middleOffset>0 &&
document.getChar(middleOffset)==' ') {
middleOffset++;
}
if (middleOffset>offset &&
middleOffset<nextOffset) {
offset = middleOffset;
}
String str = getText(false);
if (nextOffset==-1) {
nextOffset = offset;
}
if (document.getChar(nextOffset)=='}') {
str += " ";
}
document.replace(offset, nextOffset-offset, str);
}
catch (BadLocationException e) {
e.printStackTrace();
}
//adding imports drops us out of linked mode :(
/*try {
DocumentChange tc = new DocumentChange("imports", document);
tc.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
CompilationUnit cu = cpc.getRootNode();
importDeclaration(decs, d, cu);
if (d instanceof Functional) {
List<ParameterList> pls = ((Functional) d).getParameterLists();
if (!pls.isEmpty()) {
for (Parameter p: pls.get(0).getParameters()) {
MethodOrValue pm = p.getModel();
if (pm instanceof Method) {
for (ParameterList ppl: ((Method) pm).getParameterLists()) {
for (Parameter pp: ppl.getParameters()) {
importSignatureTypes(pp.getModel(), cu, decs);
}
}
}
}
}
}
applyImports(tc, decs, cu, document);
tc.perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}*/
}
private String getText(boolean description) {
StringBuilder sb = new StringBuilder()
.append(op).append(dec.getName(getUnit()));
if (dec instanceof Functional && !basic) {
appendPositionalArgs(dec, getUnit(), sb,
false, description);
}
return sb.toString();
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getDisplayString() {
return getText(true);
}
@Override
public Image getImage() {
return getImageForDeclaration(dec);
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int currentOffset,
DocumentEvent event) {
if (event==null) {
return true;
}
else {
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
String content = document.get(offset, currentOffset - offset);
int eq = content.indexOf("=");
if (eq>0) {
content = content.substring(eq+1);
}
String filter = content.trim().toLowerCase();
String decName = dec.getName(getUnit());
if ((op+decName).toLowerCase().startsWith(filter) ||
decName.toLowerCase().startsWith(filter)) {
return true;
}
}
catch (BadLocationException e) {
// ignore concurrently modified document
}
return false;
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java |
31 | final class NestedLiteralCompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2 {
private final int loc;
private final int index;
private final String value;
NestedLiteralCompletionProposal(String value, int loc,
int index) {
this.value = value;
this.loc = loc;
this.index = index;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
//the following awfulness is necessary because the
//insertion point may have changed (and even its
//text may have changed, since the proposal was
//instantiated).
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
if (offset>0 && document.getChar(offset)==' ') {
offset++;
}
int nextOffset = findCharCount(index+1, document,
loc+startOfArgs, endOfLine,
",;", "", true);
int middleOffset = findCharCount(1, document,
offset, nextOffset,
"=", "", true)+1;
if (middleOffset>0 &&
document.getChar(middleOffset)=='>') {
middleOffset++;
}
while (middleOffset>0 &&
document.getChar(middleOffset)==' ') {
middleOffset++;
}
if (middleOffset>offset &&
middleOffset<nextOffset) {
offset = middleOffset;
}
String str = value;
if (nextOffset==-1) {
nextOffset = offset;
}
if (document.getChar(nextOffset)=='}') {
str += " ";
}
document.replace(offset, nextOffset-offset, str);
}
catch (BadLocationException e) {
e.printStackTrace();
}
//adding imports drops us out of linked mode :(
/*try {
DocumentChange tc = new DocumentChange("imports", document);
tc.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
CompilationUnit cu = cpc.getRootNode();
importDeclaration(decs, d, cu);
if (d instanceof Functional) {
List<ParameterList> pls = ((Functional) d).getParameterLists();
if (!pls.isEmpty()) {
for (Parameter p: pls.get(0).getParameters()) {
MethodOrValue pm = p.getModel();
if (pm instanceof Method) {
for (ParameterList ppl: ((Method) pm).getParameterLists()) {
for (Parameter pp: ppl.getParameters()) {
importSignatureTypes(pp.getModel(), cu, decs);
}
}
}
}
}
}
applyImports(tc, decs, cu, document);
tc.perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}*/
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getDisplayString() {
return value;
}
@Override
public Image getImage() {
return getDecoratedImage(CEYLON_LITERAL, 0, false);
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int currentOffset,
DocumentEvent event) {
if (event==null) {
return true;
}
else {
try {
IRegion li = document.getLineInformationOfOffset(loc);
int endOfLine = li.getOffset() + li.getLength();
int startOfArgs = getFirstPosition();
int offset = findCharCount(index, document,
loc+startOfArgs, endOfLine,
",;", "", true)+1;
String content = document.get(offset, currentOffset - offset);
int eq = content.indexOf("=");
if (eq>0) {
content = content.substring(eq+1);
}
String filter = content.trim().toLowerCase();
if (value.toLowerCase().startsWith(filter)) {
return true;
}
}
catch (BadLocationException e) {
// ignore concurrently modified document
}
return false;
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java |
32 | static final class ParameterContextInformation
implements IContextInformation {
private final Declaration declaration;
private final ProducedReference producedReference;
private final ParameterList parameterList;
private final int argumentListOffset;
private final Unit unit;
private final boolean includeDefaulted;
// private final boolean inLinkedMode;
private final boolean namedInvocation;
private ParameterContextInformation(Declaration declaration,
ProducedReference producedReference, Unit unit,
ParameterList parameterList, int argumentListOffset,
boolean includeDefaulted, boolean namedInvocation) {
// boolean inLinkedMode
this.declaration = declaration;
this.producedReference = producedReference;
this.unit = unit;
this.parameterList = parameterList;
this.argumentListOffset = argumentListOffset;
this.includeDefaulted = includeDefaulted;
// this.inLinkedMode = inLinkedMode;
this.namedInvocation = namedInvocation;
}
@Override
public String getContextDisplayString() {
return "Parameters of '" + declaration.getName() + "'";
}
@Override
public Image getImage() {
return getImageForDeclaration(declaration);
}
@Override
public String getInformationDisplayString() {
List<Parameter> ps = getParameters(parameterList,
includeDefaulted, namedInvocation);
if (ps.isEmpty()) {
return "no parameters";
}
StringBuilder result = new StringBuilder();
for (Parameter p: ps) {
boolean isListedValues = namedInvocation &&
p==ps.get(ps.size()-1) &&
p.getModel() instanceof Value &&
p.getType()!=null &&
unit.isIterableParameterType(p.getType());
if (includeDefaulted || !p.isDefaulted() ||
isListedValues) {
if (producedReference==null) {
result.append(p.getName());
}
else {
ProducedTypedReference pr =
producedReference.getTypedParameter(p);
appendParameterContextInfo(result, pr, p, unit,
namedInvocation, isListedValues);
}
if (!isListedValues) {
result.append(namedInvocation ? "; " : ", ");
}
}
}
if (!namedInvocation && result.length()>0) {
result.setLength(result.length()-2);
}
return result.toString();
}
@Override
public boolean equals(Object that) {
if (that instanceof ParameterContextInformation) {
return ((ParameterContextInformation) that).declaration
.equals(declaration);
}
else {
return false;
}
}
int getArgumentListOffset() {
return argumentListOffset;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java |
33 | static final class ParameterInfo
extends InvocationCompletionProposal {
private ParameterInfo(int offset, Declaration dec,
ProducedReference producedReference,
Scope scope, CeylonParseController cpc,
boolean namedInvocation) {
super(offset, "", "show parameters", "", dec,
producedReference, scope, cpc, true,
true, namedInvocation, false, null);
}
@Override
boolean isParameterInfo() {
return true;
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public void apply(IDocument document) {}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_InvocationCompletionProposal.java |
34 | public class KeywordCompletionProposal extends CompletionProposal {
public static final Set<String> expressionKeywords =
new LinkedHashSet<String>(Arrays.asList(
"object", "value", "void", "function",
"this", "outer", "super",
"of", "in", "else", "for", "if", "is",
"exists", "nonempty", "then", "let"));
public static final Set<String> postfixKeywords =
new LinkedHashSet<String>(Arrays.asList(
"of", "in", "else", "exists", "nonempty", "then"));
public static final Set<String> conditionKeywords =
new LinkedHashSet<String>(Arrays.asList("assert", "let",
"while", "for", "if", "switch", "case", "catch"));
static void addKeywordProposals(CeylonParseController cpc, int offset,
String prefix, List<ICompletionProposal> result, Node node,
OccurrenceLocation ol, boolean postfix, int previousTokenType) {
if (isModuleDescriptor(cpc) &&
ol!=META && (ol==null||!ol.reference)) {
//outside of backtick quotes, the only keyword allowed
//in a module descriptor is "import"
if ("import".startsWith(prefix)) {
addKeywordProposal(offset, prefix, result, "import");
}
}
else if (!prefix.isEmpty() && ol!=CATCH && ol!=CASE) {
//TODO: this filters out satisfies/extends in an object named arg
Set<String> keywords;
if (ol==EXPRESSION) {
keywords = postfix ? postfixKeywords : expressionKeywords;
}
else {
keywords = Escaping.KEYWORDS;
}
for (String keyword: keywords) {
if (keyword.startsWith(prefix)) {
addKeywordProposal(offset, prefix, result, keyword);
}
}
}
else if (ol==CASE && previousTokenType==CeylonLexer.LPAREN) {
addKeywordProposal(offset, prefix, result, "is");
}
else if (!prefix.isEmpty() && ol==CASE) {
if ("case".startsWith(prefix)) {
addKeywordProposal(offset, prefix, result, "case");
}
}
else if (ol==null && node instanceof Tree.ConditionList &&
previousTokenType==CeylonLexer.LPAREN) {
addKeywordProposal(offset, prefix, result, "exists");
addKeywordProposal(offset, prefix, result, "nonempty");
}
}
KeywordCompletionProposal(int offset, String prefix, String keyword) {
super(offset, prefix, null, keyword,
conditionKeywords.contains(keyword) ? keyword+" ()" : keyword);
}
@Override
public Point getSelection(IDocument document) {
int close = text.indexOf(')');
if (close>0) {
return new Point(offset + close - prefix.length(), 0);
}
else {
return super.getSelection(document);
}
}
@Override
public int length(IDocument document) {
return prefix.length();
}
@Override
public Image getImage() {
return getDecoratedImage(CEYLON_LITERAL, 0, false);
}
@Override
public StyledString getStyledDisplayString() {
return new StyledString(getDisplayString(), Highlights.KW_STYLER);
}
static void addKeywordProposal(int offset, String prefix,
List<ICompletionProposal> result, String keyword) {
result.add(new KeywordCompletionProposal(offset, prefix, keyword));
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_KeywordCompletionProposal.java |
35 | public class LinkedModeCompletionProposal
implements ICompletionProposal, ICompletionProposalExtension2 {
private static final class NullProposal
implements ICompletionProposal, ICompletionProposalExtension2 {
private List<ICompletionProposal> proposals;
private NullProposal(List<ICompletionProposal> proposals) {
this.proposals = proposals;
}
@Override
public void apply(IDocument document) {}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public String getDisplayString() {
return "";
}
@Override
public Image getImage() {
return null;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask,
int offset) {}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int offset,
DocumentEvent event) {
for (ICompletionProposal p: proposals) {
if (p instanceof ICompletionProposalExtension2) {
ICompletionProposalExtension2 ext =
(ICompletionProposalExtension2) p;
if (ext.validate(document, offset, event)) {
return true;
}
}
else {
return true;
}
}
return false;
}
}
private final String text;
private final Image image;
private final int offset;
private int position;
private LinkedModeCompletionProposal(int offset, String text,
int position) {
this(offset, text, position, null);
}
private LinkedModeCompletionProposal(int offset, String text,
int position, Image image) {
this.text=text;
this.position = position;
this.image = image;
this.offset = offset;
}
@Override
public Image getImage() {
return image;
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset + text.length(), 0);
}
public void apply(IDocument document) {
try {
IRegion region = getCurrentRegion(document);
document.replace(region.getOffset(),
region.getLength(), text);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
protected IRegion getCurrentRegion(IDocument document)
throws BadLocationException {
int start = offset;
int length = 0;
int count = 0;
for (int i=offset;
i<document.getLength();
i++) {
char ch = document.getChar(i);
if (Character.isWhitespace(ch) || ch=='(') {
if (count++==position) {
break;
}
else {
start = i+1;
length = -1;
}
}
length++;
}
return new Region(start, length);
}
public String getDisplayString() {
return text;
}
public String getAdditionalProposalInfo() {
return null;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int offset,
DocumentEvent event) {
try {
IRegion region = getCurrentRegion(document);
String prefix = document.get(region.getOffset(),
offset-region.getOffset());
return text.startsWith(prefix);
}
catch (BadLocationException e) {
return false;
}
}
public static ICompletionProposal[] getNameProposals(int offset,
int seq, String[] names) {
return getNameProposals(offset, seq, names, null);
}
public static ICompletionProposal[] getNameProposals(int offset,
int seq, String[] names, String defaultName) {
List<ICompletionProposal> nameProposals =
new ArrayList<ICompletionProposal>();
Set<String> proposedNames = new HashSet<String>();
if (defaultName!=null) {
LinkedModeCompletionProposal nameProposal =
new LinkedModeCompletionProposal(offset, defaultName, seq);
nameProposals.add(nameProposal);
proposedNames.add(defaultName);
}
for (String name: names) {
if (proposedNames.add(name)) {
if (defaultName==null || !defaultName.equals(name)) {
LinkedModeCompletionProposal nameProposal =
new LinkedModeCompletionProposal(offset, name, seq);
nameProposals.add(nameProposal);
}
}
}
ICompletionProposal[] proposals =
new ICompletionProposal[nameProposals.size() + 1];
int i=0;
proposals[i++] = new NullProposal(nameProposals);
for (ICompletionProposal tp: nameProposals) {
proposals[i++] = tp;
}
return proposals;
}
public static ICompletionProposal[] getSupertypeProposals(int offset,
Unit unit, ProducedType type, boolean includeValue, String kind) {
if (type==null) {
return new ICompletionProposal[0];
}
TypeDeclaration td = type.getDeclaration();
List<TypeDeclaration> supertypes = isTypeUnknown(type) ?
Collections.<TypeDeclaration>emptyList() :
td.getSupertypeDeclarations();
int size = supertypes.size();
if (includeValue) size++;
if (td instanceof UnionType ||
td instanceof IntersectionType) {
size++;
}
ICompletionProposal[] typeProposals =
new ICompletionProposal[size];
int i=0;
if (includeValue) {
typeProposals[i++] =
new LinkedModeCompletionProposal(offset, kind, 0,
getDecoratedImage(CEYLON_LITERAL, 0, false));
}
if (td instanceof UnionType ||
td instanceof IntersectionType) {
String typeName =
type.getProducedTypeName(unit);
typeProposals[i++] =
new LinkedModeCompletionProposal(offset, typeName, 0,
getImageForDeclaration(td));
}
for (int j=supertypes.size()-1; j>=0; j--) {
ProducedType supertype =
type.getSupertype(supertypes.get(j));
String typeName =
supertype.getProducedTypeName(unit);
typeProposals[i++] =
new LinkedModeCompletionProposal(offset, typeName, 0,
getImageForDeclaration(supertype.getDeclaration()));
}
return typeProposals;
}
public static ICompletionProposal[] getCaseTypeProposals(int offset, Unit unit, ProducedType type) {
if (type==null) {
return new ICompletionProposal[0];
}
List<ProducedType> caseTypes = type.getCaseTypes();
if (caseTypes==null) {
return new ICompletionProposal[0];
}
ICompletionProposal[] typeProposals =
new ICompletionProposal[caseTypes.size()];
for (int i=0; i<caseTypes.size(); i++) {
ProducedType ct = caseTypes.get(i);
String typeName =
ct.getProducedTypeName(unit);
typeProposals[i] =
new LinkedModeCompletionProposal(offset, typeName, 0,
getImageForDeclaration(ct.getDeclaration()));
}
return typeProposals;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_LinkedModeCompletionProposal.java |
36 | private static final class NullProposal
implements ICompletionProposal, ICompletionProposalExtension2 {
private List<ICompletionProposal> proposals;
private NullProposal(List<ICompletionProposal> proposals) {
this.proposals = proposals;
}
@Override
public void apply(IDocument document) {}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public String getDisplayString() {
return "";
}
@Override
public Image getImage() {
return null;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask,
int offset) {}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int offset,
DocumentEvent event) {
for (ICompletionProposal p: proposals) {
if (p instanceof ICompletionProposalExtension2) {
ICompletionProposalExtension2 ext =
(ICompletionProposalExtension2) p;
if (ext.validate(document, offset, event)) {
return true;
}
}
else {
return true;
}
}
return false;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_LinkedModeCompletionProposal.java |
37 | public class MemberNameCompletions {
static void addMemberNameProposals(final int offset,
final CeylonParseController cpc, final Node node,
final List<ICompletionProposal> result) {
final Integer startIndex2 = node.getStartIndex();
new Visitor() {
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
Tree.TypeArguments tal = that.getTypeArguments();
Integer startIndex = tal==null ? null : tal.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
addMemberNameProposal(offset, "", that, result);
}
super.visit(that);
}
public void visit(Tree.SimpleType that) {
Tree.TypeArgumentList tal = that.getTypeArgumentList();
Integer startIndex = tal==null ? null : tal.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
addMemberNameProposal(offset, "", that, result);
}
super.visit(that);
}
}.visit(cpc.getRootNode());
}
static void addMemberNameProposal(int offset, String prefix,
Node node, List<ICompletionProposal> result) {
Set<String> proposals = new LinkedHashSet<String>();
if (node instanceof Tree.TypeDeclaration) {
//TODO: dictionary completions?
return;
}
else if (node instanceof Tree.TypedDeclaration) {
Tree.TypedDeclaration td = (Tree.TypedDeclaration) node;
Tree.Type type = td.getType();
Tree.Identifier id = td.getIdentifier();
if (id==null || offset>=id.getStartIndex() && offset<=id.getStopIndex()+1) {
node = type;
}
else {
node = null;
}
}
if (node instanceof Tree.SimpleType) {
Tree.SimpleType simpleType = (Tree.SimpleType) node;
addProposals(proposals, simpleType.getIdentifier(),
simpleType.getTypeModel());
}
else if (node instanceof Tree.BaseTypeExpression) {
Tree.BaseTypeExpression typeExpression = (Tree.BaseTypeExpression) node;
addProposals(proposals, typeExpression.getIdentifier(),
getLiteralType(node, typeExpression));
}
else if (node instanceof Tree.QualifiedTypeExpression) {
Tree.QualifiedTypeExpression typeExpression = (Tree.QualifiedTypeExpression) node;
addProposals(proposals, typeExpression.getIdentifier(),
getLiteralType(node, typeExpression));
}
else if (node instanceof Tree.OptionalType) {
Tree.StaticType et = ((Tree.OptionalType) node).getDefiniteType();
if (et instanceof Tree.SimpleType) {
addProposals(proposals, ((Tree.SimpleType) et).getIdentifier(),
((Tree.OptionalType) node).getTypeModel());
}
}
else if (node instanceof Tree.SequenceType) {
Tree.StaticType et = ((Tree.SequenceType) node).getElementType();
if (et instanceof Tree.SimpleType) {
addPluralProposals(proposals, ((Tree.SimpleType) et).getIdentifier(),
((Tree.SequenceType) node).getTypeModel());
}
proposals.add("sequence");
}
else if (node instanceof Tree.IterableType) {
Tree.Type et = ((Tree.IterableType) node).getElementType();
if (et instanceof Tree.SequencedType) {
et = ((Tree.SequencedType) et).getType();
}
if (et instanceof Tree.SimpleType) {
addPluralProposals(proposals, ((Tree.SimpleType) et).getIdentifier(),
((Tree.IterableType) node).getTypeModel());
}
proposals.add("iterable");
}
else if (node instanceof Tree.TupleType) {
List<Type> ets = ((Tree.TupleType) node).getElementTypes();
if (ets.size()==1) {
Tree.Type et = ets.get(0);
if (et instanceof Tree.SequencedType) {
et = ((Tree.SequencedType) et).getType();
}
if (et instanceof Tree.SimpleType) {
addPluralProposals(proposals, ((Tree.SimpleType) et).getIdentifier(),
((Tree.TupleType) node).getTypeModel());
}
proposals.add("sequence");
}
}
/*if (suggestedName!=null) {
suggestedName = lower(suggestedName);
String unquoted = prefix.startsWith("\\i")||prefix.startsWith("\\I") ?
prefix.substring(2) : prefix;
if (!suggestedName.startsWith(unquoted)) {
suggestedName = prefix + upper(suggestedName);
}
result.add(new CompletionProposal(offset, prefix, LOCAL_NAME,
suggestedName, escape(suggestedName)));
}*/
/*if (proposals.isEmpty()) {
proposals.add("it");
}*/
for (String name: proposals) {
String unquotedPrefix = prefix.startsWith("\\i") ?
prefix.substring(2) : prefix;
if (name.startsWith(unquotedPrefix)) {
String unquotedName = name.startsWith("\\i") ?
name.substring(2) : name;
result.add(new CompletionProposal(offset, prefix,
LOCAL_NAME, unquotedName, name));
}
}
}
private static ProducedType getLiteralType(Node node,
Tree.StaticMemberOrTypeExpression typeExpression) {
Unit unit = node.getUnit();
ProducedType pt = typeExpression.getTypeModel();
return unit.isCallableType(pt) ?
unit.getCallableReturnType(pt) : pt;
}
private static void addProposals(Set<String> proposals,
Tree.Identifier identifier, ProducedType type) {
Nodes.addNameProposals(proposals, false, identifier.getText());
if (!isTypeUnknown(type) &&
identifier.getUnit().isIterableType(type)) {
addPluralProposals(proposals, identifier, type);
}
}
private static void addPluralProposals(Set<String> proposals,
Tree.Identifier identifier, ProducedType type) {
Nodes.addNameProposals(proposals, true,
identifier.getUnit().getIteratedType(type)
.getDeclaration().getName());
}
/*private static String lower(String suggestedName) {
return Character.toLowerCase(suggestedName.charAt(0)) +
suggestedName.substring(1);
}
private static String upper(String suggestedName) {
return Character.toUpperCase(suggestedName.charAt(0)) +
suggestedName.substring(1);
}*/
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_MemberNameCompletions.java |
38 | new Visitor() {
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
Tree.TypeArguments tal = that.getTypeArguments();
Integer startIndex = tal==null ? null : tal.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
addMemberNameProposal(offset, "", that, result);
}
super.visit(that);
}
public void visit(Tree.SimpleType that) {
Tree.TypeArgumentList tal = that.getTypeArgumentList();
Integer startIndex = tal==null ? null : tal.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
addMemberNameProposal(offset, "", that, result);
}
super.visit(that);
}
}.visit(cpc.getRootNode()); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_MemberNameCompletions.java |
39 | public class ModuleCompletions {
static final class ModuleDescriptorProposal extends CompletionProposal {
ModuleDescriptorProposal(int offset, String prefix, String moduleName) {
super(offset, prefix, MODULE,
"module " + moduleName,
"module " + moduleName + " \"1.0.0\" {}");
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset - prefix.length() + text.indexOf('\"')+1, 5);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
static final class ModuleProposal extends CompletionProposal {
private final int len;
private final String versioned;
private final ModuleDetails module;
private final boolean withBody;
private final ModuleVersionDetails version;
private final String name;
private Node node;
ModuleProposal(int offset, String prefix, int len,
String versioned, ModuleDetails module,
boolean withBody, ModuleVersionDetails version,
String name, Node node) {
super(offset, prefix, MODULE, versioned,
versioned.substring(len));
this.len = len;
this.versioned = versioned;
this.module = module;
this.withBody = withBody;
this.version = version;
this.name = name;
this.node = node;
}
@Override
public String getDisplayString() {
String str = super.getDisplayString();
/*if (withBody &&
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
str = str.replaceAll("\".*\"", "\"<...>\"");
}*/
return str;
}
@Override
public Point getSelection(IDocument document) {
final int off = offset+versioned.length()-prefix.length()-len;
if (withBody) {
final int verlen = version.getVersion().length();
return new Point(off-verlen-2, verlen);
}
else {
return new Point(off, 0);
}
}
@Override
public void apply(IDocument document) {
super.apply(document);
if (withBody && //module.getVersions().size()>1 && //TODO: put this back in when sure it works
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
final LinkedModeModel linkedModeModel = new LinkedModeModel();
final Point selection = getSelection(document);
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
for (final ModuleVersionDetails d: module.getVersions()) {
proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return CeylonResources.VERSION;
}
@Override
public String getDisplayString() {
return d.getVersion();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return "Repository: " + d.getOrigin();
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getVersion());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
});
}
ProposalPosition linkedPosition =
new ProposalPosition(document, selection.x, selection.y, 0,
proposals.toArray(NO_COMPLETIONS));
try {
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
1, selection.x+selection.y+2);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
@Override
public String getAdditionalProposalInfo() {
Scope scope = node.getScope();
Unit unit = node.getUnit();
return JDKUtils.isJDKModule(name) ?
getDocumentationForModule(name, JDKUtils.jdk.version,
"This module forms part of the Java SDK.",
scope, unit) :
getDocumentationFor(module, version.getVersion(),
scope, unit);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
static final class JDKModuleProposal extends CompletionProposal {
private final String name;
JDKModuleProposal(int offset, String prefix, int len,
String versioned, String name) {
super(offset, prefix, MODULE, versioned,
versioned.substring(len));
this.name = name;
}
@Override
public String getAdditionalProposalInfo() {
return getDocumentationForModule(name, JDKUtils.jdk.version,
"This module forms part of the Java SDK.",
null, null);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
private static final SortedSet<String> JDK_MODULE_VERSION_SET = new TreeSet<String>();
{
JDK_MODULE_VERSION_SET.add(JDKUtils.jdk.version);
}
static void addModuleCompletions(CeylonParseController cpc,
int offset, String prefix, Tree.ImportPath path, Node node,
List<ICompletionProposal> result, boolean withBody) {
String fullPath = fullPath(offset, prefix, path);
addModuleCompletions(offset, prefix, node, result, fullPath.length(),
fullPath+prefix, cpc, withBody);
}
private static void addModuleCompletions(int offset, String prefix, Node node,
List<ICompletionProposal> result, final int len, String pfp,
final CeylonParseController cpc, final boolean withBody) {
if (pfp.startsWith("java.")) {
for (String name:
new TreeSet<String>(JDKUtils.getJDKModuleNames())) {
if (name.startsWith(pfp) &&
!moduleAlreadyImported(cpc, name)) {
result.add(new JDKModuleProposal(offset, prefix, len,
getModuleString(withBody, name, JDKUtils.jdk.version),
name));
}
}
}
else {
final TypeChecker tc = cpc.getTypeChecker();
if (tc!=null) {
IProject project = cpc.getProject();
for (ModuleDetails module:
getModuleSearchResults(pfp, tc,project).getResults()) {
final String name = module.getName();
if (!name.equals(Module.DEFAULT_MODULE_NAME) &&
!moduleAlreadyImported(cpc, name)) {
if (EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
result.add(new ModuleProposal(offset, prefix, len,
getModuleString(withBody, name,
module.getLastVersion().getVersion()),
module, withBody, module.getLastVersion(),
name, node));
}
else {
for (final ModuleVersionDetails version:
module.getVersions().descendingSet()) {
result.add(new ModuleProposal(offset, prefix, len,
getModuleString(withBody, name, version.getVersion()),
module, withBody, version, name, node));
}
}
}
}
}
}
}
private static boolean moduleAlreadyImported(CeylonParseController cpc, final String mod) {
if (mod.equals(Module.LANGUAGE_MODULE_NAME)) {
return true;
}
List<Tree.ModuleDescriptor> md = cpc.getRootNode().getModuleDescriptors();
if (!md.isEmpty()) {
Tree.ImportModuleList iml = md.get(0).getImportModuleList();
if (iml!=null) {
for (Tree.ImportModule im: iml.getImportModules()) {
if (im.getImportPath()!=null) {
if (formatPath(im.getImportPath().getIdentifiers()).equals(mod)) {
return true;
}
}
}
}
}
//Disabled, because once the module is imported, it hangs around!
// for (ModuleImport mi: node.getUnit().getPackage().getModule().getImports()) {
// if (mi.getModule().getNameAsString().equals(mod)) {
// return true;
// }
// }
return false;
}
private static String getModuleString(boolean withBody,
String name, String version) {
if (!name.matches("^[a-z_]\\w*(\\.[a-z_]\\w*)*$")) {
name = '"' + name + '"';
}
return withBody ? name + " \"" + version + "\";" : name;
}
static void addModuleDescriptorCompletion(CeylonParseController cpc,
int offset, String prefix, List<ICompletionProposal> result) {
if (!"module".startsWith(prefix)) return;
IFile file = cpc.getProject().getFile(cpc.getPath());
String moduleName = getPackageName(file);
if (moduleName!=null) {
result.add(new ModuleDescriptorProposal(offset, prefix, moduleName));
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ModuleCompletions.java |
40 | static final class JDKModuleProposal extends CompletionProposal {
private final String name;
JDKModuleProposal(int offset, String prefix, int len,
String versioned, String name) {
super(offset, prefix, MODULE, versioned,
versioned.substring(len));
this.name = name;
}
@Override
public String getAdditionalProposalInfo() {
return getDocumentationForModule(name, JDKUtils.jdk.version,
"This module forms part of the Java SDK.",
null, null);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ModuleCompletions.java |
41 | static final class ModuleDescriptorProposal extends CompletionProposal {
ModuleDescriptorProposal(int offset, String prefix, String moduleName) {
super(offset, prefix, MODULE,
"module " + moduleName,
"module " + moduleName + " \"1.0.0\" {}");
}
@Override
public Point getSelection(IDocument document) {
return new Point(offset - prefix.length() + text.indexOf('\"')+1, 5);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ModuleCompletions.java |
42 | static final class ModuleProposal extends CompletionProposal {
private final int len;
private final String versioned;
private final ModuleDetails module;
private final boolean withBody;
private final ModuleVersionDetails version;
private final String name;
private Node node;
ModuleProposal(int offset, String prefix, int len,
String versioned, ModuleDetails module,
boolean withBody, ModuleVersionDetails version,
String name, Node node) {
super(offset, prefix, MODULE, versioned,
versioned.substring(len));
this.len = len;
this.versioned = versioned;
this.module = module;
this.withBody = withBody;
this.version = version;
this.name = name;
this.node = node;
}
@Override
public String getDisplayString() {
String str = super.getDisplayString();
/*if (withBody &&
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
str = str.replaceAll("\".*\"", "\"<...>\"");
}*/
return str;
}
@Override
public Point getSelection(IDocument document) {
final int off = offset+versioned.length()-prefix.length()-len;
if (withBody) {
final int verlen = version.getVersion().length();
return new Point(off-verlen-2, verlen);
}
else {
return new Point(off, 0);
}
}
@Override
public void apply(IDocument document) {
super.apply(document);
if (withBody && //module.getVersions().size()>1 && //TODO: put this back in when sure it works
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
final LinkedModeModel linkedModeModel = new LinkedModeModel();
final Point selection = getSelection(document);
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
for (final ModuleVersionDetails d: module.getVersions()) {
proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return CeylonResources.VERSION;
}
@Override
public String getDisplayString() {
return d.getVersion();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return "Repository: " + d.getOrigin();
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getVersion());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
});
}
ProposalPosition linkedPosition =
new ProposalPosition(document, selection.x, selection.y, 0,
proposals.toArray(NO_COMPLETIONS));
try {
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
1, selection.x+selection.y+2);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
@Override
public String getAdditionalProposalInfo() {
Scope scope = node.getScope();
Unit unit = node.getUnit();
return JDKUtils.isJDKModule(name) ?
getDocumentationForModule(name, JDKUtils.jdk.version,
"This module forms part of the Java SDK.",
scope, unit) :
getDocumentationFor(module, version.getVersion(),
scope, unit);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ModuleCompletions.java |
43 | proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return CeylonResources.VERSION;
}
@Override
public String getDisplayString() {
return d.getVersion();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return "Repository: " + d.getOrigin();
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getVersion());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ModuleCompletions.java |
44 | public enum OccurrenceLocation {
EXISTS(false),
NONEMPTY(false),
IS(false),
EXTENDS(false),
SATISFIES(false),
CLASS_ALIAS(false),
OF(false),
UPPER_BOUND(false),
TYPE_ALIAS(false),
CASE(false),
CATCH(false),
IMPORT(false),
EXPRESSION(false),
PARAMETER_LIST(false),
TYPE_PARAMETER_LIST(false),
TYPE_ARGUMENT_LIST(false),
META(false),
PACKAGE_REF(true),
MODULE_REF(true),
INTERFACE_REF(true),
CLASS_REF(true),
ALIAS_REF(true),
TYPE_PARAMETER_REF(true),
VALUE_REF(true),
FUNCTION_REF(true),
DOCLINK(false);
public final boolean reference;
OccurrenceLocation(boolean reference) {
this.reference = reference;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_OccurrenceLocation.java |
45 | public class PackageCompletions {
static final class PackageDescriptorProposal extends CompletionProposal {
PackageDescriptorProposal(int offset, String prefix, String packageName) {
super(offset, prefix, PACKAGE,
"package " + packageName,
"package " + packageName + ";");
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
static final class PackageProposal extends CompletionProposal {
private final boolean withBody;
private final int len;
private final Package p;
private final String completed;
private final CeylonParseController cpc;
PackageProposal(int offset, String prefix, boolean withBody,
int len, Package p, String completed,
CeylonParseController cpc) {
super(offset, prefix, PACKAGE, completed,
completed.substring(len));
this.withBody = withBody;
this.len = len;
this.p = p;
this.completed = completed;
this.cpc = cpc;
}
@Override
public Point getSelection(IDocument document) {
if (withBody) {
return new Point(offset+completed.length()-prefix.length()-len-5, 3);
}
else {
return new Point(offset+completed.length()-prefix.length()-len, 0);
}
}
@Override
public void apply(IDocument document) {
super.apply(document);
if (withBody &&
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
final LinkedModeModel linkedModeModel = new LinkedModeModel();
final Point selection = getSelection(document);
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
for (final Declaration d: p.getMembers()) {
if (Util.isResolvable(d) && d.isShared() &&
!isOverloadedVersion(d)) {
proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return getImageForDeclaration(d);
}
@Override
public String getDisplayString() {
return d.getName();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getName());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
});
}
}
if (!proposals.isEmpty()) {
ProposalPosition linkedPosition =
new ProposalPosition(document, selection.x, selection.y, 0,
proposals.toArray(NO_COMPLETIONS));
try {
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
-1, 0);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
}
@Override
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, p);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
}
static void addPackageCompletions(CeylonParseController cpc,
int offset, String prefix, Tree.ImportPath path, Node node,
List<ICompletionProposal> result, boolean withBody) {
String fullPath = fullPath(offset, prefix, path);
addPackageCompletions(offset, prefix, node, result, fullPath.length(),
fullPath+prefix, cpc, withBody);
}
private static void addPackageCompletions(final int offset, final String prefix,
Node node, List<ICompletionProposal> result, final int len, String pfp,
final CeylonParseController cpc, final boolean withBody) {
//TODO: someday it would be nice to propose from all packages
// and auto-add the module dependency!
/*TypeChecker tc = CeylonBuilder.getProjectTypeChecker(cpc.getProject().getRawProject());
if (tc!=null) {
for (Module m: tc.getContext().getModules().getListOfModules()) {*/
//Set<Package> packages = new HashSet<Package>();
Unit unit = node.getUnit();
if (unit!=null) { //a null unit can occur if we have not finished parsing the file
Module module = unit.getPackage().getModule();
for (final Package p: module.getAllPackages()) {
//if (!packages.contains(p)) {
//packages.add(p);
//if ( p.getModule().equals(module) || p.isShared() ) {
final String pkg = escapePackageName(p);
if (!pkg.isEmpty() && pkg.startsWith(pfp)) {
boolean already = false;
if (!pfp.equals(pkg)) {
//don't add already imported packages, unless
//it is an exact match to the typed path
for (ImportList il: node.getUnit().getImportLists()) {
if (il.getImportedScope()==p) {
already = true;
break;
}
}
}
if (!already) {
result.add(new PackageProposal(offset, prefix, withBody,
len, p, pkg + (withBody ? " { ... }" : ""), cpc));
}
}
//}
}
}
}
static void addPackageDescriptorCompletion(CeylonParseController cpc,
int offset, String prefix, List<ICompletionProposal> result) {
if (!"package".startsWith(prefix)) return;
IFile file = cpc.getProject().getFile(cpc.getPath());
String packageName = getPackageName(file);
if (packageName!=null) {
result.add(new PackageDescriptorProposal(offset, prefix, packageName));
}
}
static void addCurrentPackageNameCompletion(CeylonParseController cpc,
int offset, String prefix, List<ICompletionProposal> result) {
IFile file = cpc.getProject().getFile(cpc.getPath());
String moduleName = getPackageName(file);
if (moduleName!=null) {
result.add(new CompletionProposal(offset, prefix,
isModuleDescriptor(cpc) ? MODULE : PACKAGE,
moduleName, moduleName));
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_PackageCompletions.java |
46 | static final class PackageDescriptorProposal extends CompletionProposal {
PackageDescriptorProposal(int offset, String prefix, String packageName) {
super(offset, prefix, PACKAGE,
"package " + packageName,
"package " + packageName + ";");
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_PackageCompletions.java |
47 | static final class PackageProposal extends CompletionProposal {
private final boolean withBody;
private final int len;
private final Package p;
private final String completed;
private final CeylonParseController cpc;
PackageProposal(int offset, String prefix, boolean withBody,
int len, Package p, String completed,
CeylonParseController cpc) {
super(offset, prefix, PACKAGE, completed,
completed.substring(len));
this.withBody = withBody;
this.len = len;
this.p = p;
this.completed = completed;
this.cpc = cpc;
}
@Override
public Point getSelection(IDocument document) {
if (withBody) {
return new Point(offset+completed.length()-prefix.length()-len-5, 3);
}
else {
return new Point(offset+completed.length()-prefix.length()-len, 0);
}
}
@Override
public void apply(IDocument document) {
super.apply(document);
if (withBody &&
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
final LinkedModeModel linkedModeModel = new LinkedModeModel();
final Point selection = getSelection(document);
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
for (final Declaration d: p.getMembers()) {
if (Util.isResolvable(d) && d.isShared() &&
!isOverloadedVersion(d)) {
proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return getImageForDeclaration(d);
}
@Override
public String getDisplayString() {
return d.getName();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getName());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
});
}
}
if (!proposals.isEmpty()) {
ProposalPosition linkedPosition =
new ProposalPosition(document, selection.x, selection.y, 0,
proposals.toArray(NO_COMPLETIONS));
try {
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
-1, 0);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
}
@Override
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, p);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_PackageCompletions.java |
48 | proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return getImageForDeclaration(d);
}
@Override
public String getDisplayString() {
return d.getName();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getName());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_PackageCompletions.java |
49 | class ParameterContextValidator
implements IContextInformationValidator, IContextInformationPresenter {
private int position;
private IContextInformation information;
private int currentParameter;
private CeylonEditor editor;
ParameterContextValidator(CeylonEditor editor) {
this.editor = editor;
}
@Override
public boolean updatePresentation(int brokenPosition,
TextPresentation presentation) {
String s = information.getInformationDisplayString();
presentation.clear();
if (this.position==-1) {
presentation.addStyleRange(new StyleRange(0, s.length(),
null, null, SWT.BOLD));
addItalics(presentation, s);
return true;
}
int currentParameter = -1;
CeylonSourceViewer viewer = editor.getCeylonSourceViewer();
int position = viewer.getSelectedRange().x;
IDocument doc = viewer.getDocument();
try {
boolean namedInvocation = doc.getChar(this.position)=='{';
if (!namedInvocation) Assert.isTrue(doc.getChar(this.position)=='(');
// int paren = doc.get(this.position, position-this.position)
// .indexOf(namedInvocation?'{':'(');
// if (paren<0) { //TODO: is this really useful?
// this.position = doc.get(0, position).lastIndexOf('(');
// }
currentParameter = getCharCount(doc,
this.position+1, position,
namedInvocation?";":",", "", true);
}
catch (BadLocationException x) {
return false;
}
if (currentParameter != -1) {
if (this.currentParameter == currentParameter) {
return false;
}
}
presentation.clear();
this.currentParameter = currentParameter;
int[] commas = computeCommaPositions(s);
if (commas.length - 2 < currentParameter) {
presentation.addStyleRange(new StyleRange(0, s.length(),
null, null, SWT.NORMAL));
addItalics(presentation, s);
return true;
}
int start = commas[currentParameter] + 1;
int end = commas[currentParameter + 1];
if (start > 0) {
presentation.addStyleRange(new StyleRange(0, start,
null, null, SWT.NORMAL));
}
if (end > start) {
presentation.addStyleRange(new StyleRange(start, end - start,
null, null, SWT.BOLD));
}
if (end < s.length()) {
presentation.addStyleRange(new StyleRange(end, s.length() - end,
null, null, SWT.NORMAL));
}
addItalics(presentation, s);
return true;
}
private void addItalics(TextPresentation presentation, String s) {
Matcher m2 = p2.matcher(s);
while (m2.find()) {
presentation.mergeStyleRange(new StyleRange(m2.start(), m2.end()-m2.start(),
null, null, SWT.ITALIC));
}
// Matcher m1 = p1.matcher(s);
// while (m1.find()) {
// presentation.mergeStyleRange(new StyleRange(m1.start(), m1.end()-m1.start()+1,
// typeColor, null));
// }
}
// final Pattern p1 = Pattern.compile("\\b\\p{javaUpperCase}\\w*\\b");
final Pattern p2 = Pattern.compile("\\b\\p{javaLowerCase}\\w*\\b");
// final Color typeColor = color(getCurrentTheme().getColorRegistry(), TYPES);
@Override
public void install(IContextInformation info, ITextViewer viewer,
int documentPosition) {
if (info instanceof InvocationCompletionProposal.ParameterContextInformation) {
ParameterContextInformation pci =
(InvocationCompletionProposal.ParameterContextInformation) info;
this.position = pci.getArgumentListOffset();
}
else {
this.position = -1;
}
Assert.isTrue(viewer==editor.getCeylonSourceViewer());
this.information = info;
this.currentParameter= -1;
}
@Override
public boolean isContextInformationValid(int brokenPosition) {
if (editor.isInLinkedMode()) {
Object linkedModeOwner = editor.getLinkedModeOwner();
if (linkedModeOwner instanceof InvocationCompletionProposal ||
linkedModeOwner instanceof RefinementCompletionProposal) {
return true;
}
}
try {
CeylonSourceViewer viewer = editor.getCeylonSourceViewer();
int position = viewer.getSelectedRange().x;
if (position < this.position) {
return false;
}
IDocument document = viewer.getDocument();
IRegion line =
document.getLineInformationOfOffset(this.position);
if (position < line.getOffset() ||
position >= document.getLength()) {
return false;
}
// System.out.println(document.get(this.position, position-this.position));
int semiCount = getCharCount(document, this.position, position, ";", "", true);
int fenceCount = getCharCount(document, this.position, position, "{(", "})", false);
return semiCount==0 && fenceCount>0;
}
catch (BadLocationException x) {
return false;
}
}
/*@Override
public boolean isContextInformationValid(int offset) {
IContextInformation[] infos= computeContextInformation(viewer, offset);
if (infos != null && infos.length > 0) {
for (int i= 0; i < infos.length; i++)
if (information.equals(infos[i]))
return true;
}
return false;
}*/
private static final int NONE = 0;
private static final int BRACKET = 1;
private static final int BRACE = 2;
private static final int PAREN = 3;
private static final int ANGLE = 4;
private static int getCharCount(IDocument document,
final int start, final int end,
String increments, String decrements,
boolean considerNesting)
throws BadLocationException {
Assert.isTrue((increments.length() != 0 || decrements.length() != 0)
&& !increments.equals(decrements));
int nestingMode = NONE;
int nestingLevel = 0;
int charCount = 0;
int offset = start;
char prev = ' ';
while (offset < end) {
char curr = document.getChar(offset++);
switch (curr) {
case '/':
if (offset < end) {
char next = document.getChar(offset);
if (next == '*') {
// a comment starts, advance to the comment end
offset= getCommentEnd(document, offset + 1, end);
}
else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
int nextLine= document.getLineOfOffset(offset) + 1;
if (nextLine == document.getNumberOfLines()) {
offset= end;
}
else {
offset= document.getLineOffset(nextLine);
}
}
}
break;
case '*':
if (offset < end) {
char next= document.getChar(offset);
if (next == '/') {
// we have been in a comment: forget what we read before
charCount= 0;
++ offset;
}
}
break;
case '"':
case '\'':
offset= getStringEnd(document, offset, end, curr);
break;
case '[':
if (considerNesting) {
if (nestingMode == BRACKET || nestingMode == NONE) {
nestingMode= BRACKET;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ']':
if (considerNesting) {
if (nestingMode == BRACKET) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '(':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=PAREN;
nestingLevel= 1;
}
if (nestingMode == PAREN || nestingMode == NONE) {
nestingMode= PAREN;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ')':
if (considerNesting) {
if (nestingMode == PAREN) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '{':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=BRACE;
nestingLevel= 1;
}
if (nestingMode == BRACE || nestingMode == NONE) {
nestingMode= BRACE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '}':
if (considerNesting) {
if (nestingMode == BRACE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '<':
if (considerNesting) {
if (nestingMode == ANGLE || nestingMode == NONE
/*&& checkGenericsHeuristic(document, offset - 1, start - 1)*/) {
nestingMode= ANGLE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '>':
if (considerNesting
&& prev != '=') { //check that it's not a fat arrow
if (nestingMode == ANGLE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
default:
if (nestingLevel==0) {
if (increments.indexOf(curr) >= 0) {
++ charCount;
}
if (decrements.indexOf(curr) >= 0) {
-- charCount;
}
}
}
}
return charCount;
}
static int findCharCount(int count, IDocument document,
final int start, final int end,
String increments, String decrements,
boolean considerNesting)
throws BadLocationException {
Assert.isTrue((increments.length() != 0 || decrements.length() != 0)
&& !increments.equals(decrements));
final int NONE= 0;
final int BRACKET= 1;
final int BRACE= 2;
final int PAREN= 3;
final int ANGLE= 4;
int nestingMode= NONE;
int nestingLevel= 0;
int charCount= 0;
int offset= start;
boolean lastWasEquals = false;
while (offset < end) {
if (nestingLevel == 0) {
if (count==charCount) {
return offset-1;
}
}
char curr= document.getChar(offset++);
switch (curr) {
case '/':
if (offset < end) {
char next= document.getChar(offset);
if (next == '*') {
// a comment starts, advance to the comment end
offset= getCommentEnd(document, offset + 1, end);
}
else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
int nextLine= document.getLineOfOffset(offset) + 1;
if (nextLine == document.getNumberOfLines()) {
offset= end;
}
else {
offset= document.getLineOffset(nextLine);
}
}
}
break;
case '*':
if (offset < end) {
char next= document.getChar(offset);
if (next == '/') {
// we have been in a comment: forget what we read before
charCount= 0;
++ offset;
}
}
break;
case '"':
case '\'':
offset= getStringEnd(document, offset, end, curr);
break;
case '[':
if (considerNesting) {
if (nestingMode == BRACKET || nestingMode == NONE) {
nestingMode= BRACKET;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ']':
if (considerNesting) {
if (nestingMode == BRACKET)
if (--nestingLevel == 0) {
nestingMode= NONE;
}
break;
}
//$FALL-THROUGH$
case '(':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=PAREN;
nestingLevel= 1;
}
if (nestingMode == PAREN || nestingMode == NONE) {
nestingMode= PAREN;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case ')':
if (considerNesting) {
if (nestingMode == 0) {
return offset-1;
}
if (nestingMode == PAREN) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '{':
if (considerNesting) {
if (nestingMode == ANGLE) {
// generics heuristic failed
nestingMode=BRACE;
nestingLevel= 1;
}
if (nestingMode == BRACE || nestingMode == NONE) {
nestingMode= BRACE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '}':
if (considerNesting) {
if (nestingMode == 0) {
return offset-1;
}
if (nestingMode == BRACE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
//$FALL-THROUGH$
case '<':
if (considerNesting) {
if (nestingMode == ANGLE || nestingMode == NONE /*&& checkGenericsHeuristic(document, offset - 1, start - 1)*/) {
nestingMode= ANGLE;
nestingLevel++;
}
break;
}
//$FALL-THROUGH$
case '>':
if (!lastWasEquals) {
if (nestingMode == 0) {
return offset-1;
}
if (considerNesting) {
if (nestingMode == ANGLE) {
if (--nestingLevel == 0) {
nestingMode= NONE;
}
}
break;
}
}
//$FALL-THROUGH$
default:
if (nestingLevel == 0) {
if (increments.indexOf(curr) >= 0) {
++ charCount;
}
if (decrements.indexOf(curr) >= 0) {
-- charCount;
}
}
}
lastWasEquals = curr=='=';
}
return -1;
}
private static int[] computeCommaPositions(String code) {
final int length= code.length();
int pos = 0;
int angleLevel = 0;
List<Integer> positions= new ArrayList<Integer>();
positions.add(new Integer(-1));
char prev = ' ';
while (pos < length && pos != -1) {
char ch = code.charAt(pos);
switch (ch) {
case ',':
case ';':
if (angleLevel == 0) {
positions.add(new Integer(pos));
}
break;
case '<':
case '(':
case '{':
case '[':
angleLevel++;
break;
case '>':
if (prev=='=') break;
case ')':
case '}':
case ']':
angleLevel--;
break;
// case '[':
// pos= code.indexOf(']', pos);
// break;
default:
break;
}
if (pos != -1) {
pos++;
}
}
positions.add(new Integer(length));
int[] fields= new int[positions.size()];
for (int i= 0; i < fields.length; i++) {
fields[i]= positions.get(i).intValue();
}
return fields;
}
private static int getCommentEnd(IDocument d, int pos, int end)
throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '*') {
if (pos < end && d.getChar(pos) == '/') {
return pos + 1;
}
}
}
return end;
}
private static int getStringEnd(IDocument d, int pos, int end, char ch)
throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '\\') {
// ignore escaped characters
pos++;
}
else if (curr == ch) {
return pos;
}
}
return end;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ParameterContextValidator.java |
50 | final class ProposalComparator
implements Comparator<DeclarationWithProximity> {
private final String prefix;
private final ProducedType type;
ProposalComparator(String prefix, ProducedType type) {
this.prefix = prefix;
this.type = type;
}
public int compare(DeclarationWithProximity x, DeclarationWithProximity y) {
try {
boolean xbt = x.getDeclaration() instanceof NothingType;
boolean ybt = y.getDeclaration() instanceof NothingType;
if (xbt&&ybt) {
return 0;
}
if (xbt&&!ybt) {
return 1;
}
if (ybt&&!xbt) {
return -1;
}
ProducedType xtype = getResultType(x.getDeclaration());
ProducedType ytype = getResultType(y.getDeclaration());
boolean xbottom = xtype!=null && xtype.isNothing();
boolean ybottom = ytype!=null && ytype.isNothing();
if (xbottom && !ybottom) {
return 1;
}
if (ybottom && !xbottom) {
return -1;
}
String xName = x.getName();
String yName = y.getName();
boolean yUpperCase = isUpperCase(yName.charAt(0));
boolean xUpperCase = isUpperCase(xName.charAt(0));
if (!prefix.isEmpty()) {
boolean upperCasePrefix = isUpperCase(prefix.charAt(0));
if (!xUpperCase && yUpperCase) {
return upperCasePrefix ? 1 : -1;
}
else if (xUpperCase && !yUpperCase) {
return upperCasePrefix ? -1 : 1;
}
}
if (type!=null) {
boolean xassigns = xtype!=null && xtype.isSubtypeOf(type);
boolean yassigns = ytype!=null && ytype.isSubtypeOf(type);
if (xassigns && !yassigns) {
return -1;
}
if (yassigns && !xassigns) {
return 1;
}
if (xassigns && yassigns) {
boolean xtd = x.getDeclaration() instanceof TypedDeclaration;
boolean ytd = y.getDeclaration() instanceof TypedDeclaration;
if (xtd && !ytd) {
return -1;
}
if (ytd && !xtd) {
return 1;
}
}
}
if (x.getProximity()!=y.getProximity()) {
return new Integer(x.getProximity()).compareTo(y.getProximity());
}
//if (!prefix.isEmpty() && isLowerCase(prefix.charAt(0))) {
if (!xUpperCase && yUpperCase) {
return -1;
}
else if (xUpperCase && !yUpperCase) {
return 1;
}
int nc = xName.compareTo(yName);
if (nc==0) {
String xqn = x.getDeclaration().getQualifiedNameString();
String yqn = y.getDeclaration().getQualifiedNameString();
return xqn.compareTo(yqn);
}
else {
return nc;
}
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ProposalComparator.java |
51 | public final class RefinementCompletionProposal extends CompletionProposal {
final class ReturnValueContextInfo implements IContextInformation {
@Override
public String getInformationDisplayString() {
if (declaration instanceof TypedDeclaration) {
return getType().getProducedTypeName(getUnit());
}
else {
return null;
}
}
@Override
public Image getImage() {
return getImageForDeclaration(declaration);
}
@Override
public String getContextDisplayString() {
return "Return value of '" + declaration.getName() + "'";
}
}
public static Image DEFAULT_REFINEMENT = CeylonPlugin.getInstance()
.getImageRegistry().get(CEYLON_DEFAULT_REFINEMENT);
public static Image FORMAL_REFINEMENT = CeylonPlugin.getInstance()
.getImageRegistry().get(CEYLON_FORMAL_REFINEMENT);
static void addRefinementProposal(int offset, final Declaration dec,
ClassOrInterface ci, Node node, Scope scope, String prefix,
CeylonParseController cpc, IDocument doc,
List<ICompletionProposal> result, boolean preamble) {
boolean isInterface = scope instanceof Interface;
ProducedReference pr = getRefinedProducedReference(scope, dec);
Unit unit = node.getUnit();
result.add(new RefinementCompletionProposal(offset, prefix, pr,
getRefinementDescriptionFor(dec, pr, unit),
getRefinementTextFor(dec, pr, unit, isInterface, ci,
getDefaultLineDelimiter(doc) + getIndent(node, doc),
true, preamble),
cpc, dec, scope, false, true));
}
static void addNamedArgumentProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, Scope scope) {
//TODO: type argument substitution using the ProducedReference of the primary node
Unit unit = cpc.getRootNode().getUnit();
result.add(new RefinementCompletionProposal(offset, prefix,
dec.getReference(), //TODO: this needs to do type arg substitution
getDescriptionFor(dec, unit),
getTextFor(dec, unit) + " = nothing;",
cpc, dec, scope, true, false));
}
static void addInlineFunctionProposal(int offset, Declaration dec,
Scope scope, Node node, String prefix, CeylonParseController cpc,
IDocument doc, List<ICompletionProposal> result) {
//TODO: type argument substitution using the ProducedReference of the primary node
if (dec.isParameter()) {
Parameter p = ((MethodOrValue) dec).getInitializerParameter();
Unit unit = node.getUnit();
result.add(new RefinementCompletionProposal(offset, prefix,
dec.getReference(), //TODO: this needs to do type arg substitution
getInlineFunctionDescriptionFor(p, null, unit),
getInlineFunctionTextFor(p, null, unit,
getDefaultLineDelimiter(doc) + getIndent(node, doc)),
cpc, dec, scope, false, false));
}
}
public static ProducedReference getRefinedProducedReference(Scope scope,
Declaration d) {
return refinedProducedReference(scope.getDeclaringType(d), d);
}
public static ProducedReference getRefinedProducedReference(ProducedType superType,
Declaration d) {
if (superType.getDeclaration() instanceof IntersectionType) {
for (ProducedType pt: superType.getDeclaration().getSatisfiedTypes()) {
ProducedReference result = getRefinedProducedReference(pt, d);
if (result!=null) return result;
}
return null; //never happens?
}
else {
ProducedType declaringType =
superType.getDeclaration().getDeclaringType(d);
if (declaringType==null) return null;
ProducedType outerType =
superType.getSupertype(declaringType.getDeclaration());
return refinedProducedReference(outerType, d);
}
}
private static ProducedReference refinedProducedReference(ProducedType outerType,
Declaration d) {
List<ProducedType> params = new ArrayList<ProducedType>();
if (d instanceof Generic) {
for (TypeParameter tp: ((Generic) d).getTypeParameters()) {
params.add(tp.getType());
}
}
return d.getProducedReference(outerType, params);
}
private final CeylonParseController cpc;
private final Declaration declaration;
private final ProducedReference pr;
private final boolean fullType;
private final Scope scope;
private boolean explicitReturnType;
private RefinementCompletionProposal(int offset, String prefix,
ProducedReference pr, String desc, String text,
CeylonParseController cpc, Declaration dec, Scope scope,
boolean fullType, boolean explicitReturnType) {
super(offset, prefix, getRefinementIcon(dec), desc, text);
this.cpc = cpc;
this.declaration = dec;
this.pr = pr;
this.fullType = fullType;
this.scope = scope;
this.explicitReturnType = explicitReturnType;
}
private Unit getUnit() {
return cpc.getRootNode().getUnit();
}
@Override
public StyledString getStyledDisplayString() {
StyledString result = new StyledString();
String string = getDisplayString();
if (string.startsWith("shared actual")) {
result.append(string.substring(0,13), Highlights.ANN_STYLER);
string=string.substring(13);
}
Highlights.styleProposal(result, string, false);
return result;
}
private ProducedType getType() {
return fullType ?
pr.getFullType() :
pr.getType();
}
@Override
public Point getSelection(IDocument document) {
int loc = text.indexOf("nothing;");
int length;
int start;
if (loc<0) {
start = offset + text.length()-prefix.length();
if (text.endsWith("{}")) start--;
length = 0;
}
else {
start = offset + loc-prefix.length();
length = 7;
}
return new Point(start, length);
}
@Override
public void apply(IDocument document) {
try {
createChange(document).perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}
if (EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
enterLinkedMode(document);
}
}
private DocumentChange createChange(IDocument document)
throws BadLocationException {
DocumentChange change =
new DocumentChange("Complete Refinement", document);
change.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
Tree.CompilationUnit cu = cpc.getRootNode();
if (explicitReturnType) {
importSignatureTypes(declaration, cu, decs);
}
else {
importParameterTypes(declaration, cu, decs);
}
int il=applyImports(change, decs, cu, document);
change.addEdit(createEdit(document));
offset+=il;
return change;
}
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, declaration);
}
public void enterLinkedMode(IDocument document) {
try {
final int loc = offset-prefix.length();
int pos = text.indexOf("nothing");
if (pos>0) {
final LinkedModeModel linkedModeModel =
new LinkedModeModel();
List<ICompletionProposal> props =
new ArrayList<ICompletionProposal>();
addProposals(loc+pos, props, prefix);
ProposalPosition linkedPosition =
new ProposalPosition(document,
loc+pos, 7, 0,
props.toArray(NO_COMPLETIONS));
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
1, loc+text.length());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public IContextInformation getContextInformation() {
return new ReturnValueContextInfo();
}
@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
if (offset<this.offset) {
return false;
}
try {
int start = this.offset-prefix.length();
String typedText = document.get(start, offset-start);
return isNameMatching(typedText, declaration.getName());
}
catch (BadLocationException e) {
return false;
}
}
private void addProposals(final int loc,
List<ICompletionProposal> props, String prefix) {
ProducedType type = getType();
if (type==null) return;
TypeDeclaration td = type.getDeclaration();
for (DeclarationWithProximity dwp:
getSortedProposedValues(scope, getUnit())) {
if (dwp.isUnimported()) {
//don't propose unimported stuff b/c adding
//imports drops us out of linked mode and
//because it results in a pause
continue;
}
Declaration d = dwp.getDeclaration();
final String name = d.getName();
String[] split = prefix.split("\\s+");
if (split.length>0 &&
name.equals(split[split.length-1])) {
continue;
}
if (d instanceof Value && !d.equals(declaration)) {
Value value = (Value) d;
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleValue(value)) {
continue;
}
}
ProducedType vt = value.getType();
if (vt!=null && !vt.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), vt) ||
vt.isSubtypeOf(type))) {
props.add(new NestedCompletionProposal(d, loc));
}
}
if (d instanceof Method && !d.equals(declaration)) {
if (!d.isAnnotation()) {
Method method = (Method) d;
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleMethod(method)) {
continue;
}
}
ProducedType mt = method.getType();
if (mt!=null && !mt.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), mt) ||
mt.isSubtypeOf(type))) {
props.add(new NestedCompletionProposal(d, loc));
}
}
}
if (d instanceof Class) {
Class clazz = (Class) d;
if (!clazz.isAbstract() && !d.isAnnotation()) {
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleClass(clazz)) {
continue;
}
}
ProducedType ct = clazz.getType();
if (ct!=null && !ct.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), ct) ||
ct.getDeclaration().equals(type.getDeclaration()) ||
ct.isSubtypeOf(type))) {
props.add(new NestedCompletionProposal(d, loc));
}
}
}
}
}
final class NestedCompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2 {
private final Declaration dec;
private final int offset;
public NestedCompletionProposal(Declaration dec, int offset) {
super();
this.dec = dec;
this.offset = offset;
}
@Override
public void apply(IDocument document) {
try {
int len = 0;
while (isJavaIdentifierPart(document.getChar(offset+len))) {
len++;
}
document.replace(offset, len, getText(false));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public String getDisplayString() {
return getText(true);
}
@Override
public Image getImage() {
return getImageForDeclaration(dec);
}
@Override
public IContextInformation getContextInformation() {
return null;
}
private String getText(boolean description) {
StringBuilder sb = new StringBuilder()
.append(dec.getName());
if (dec instanceof Functional) {
appendPositionalArgs(dec, getUnit(),
sb, false, description);
}
return sb.toString();
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int currentOffset,
DocumentEvent event) {
if (event==null) {
return true;
}
else {
try {
String content = document.get(offset,
currentOffset-offset);
String filter = content.trim().toLowerCase();
if ((dec.getName().toLowerCase())
.startsWith(filter)) {
return true;
}
}
catch (BadLocationException e) {
// ignore concurrently modified document
}
return false;
}
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_RefinementCompletionProposal.java |
52 | final class NestedCompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2 {
private final Declaration dec;
private final int offset;
public NestedCompletionProposal(Declaration dec, int offset) {
super();
this.dec = dec;
this.offset = offset;
}
@Override
public void apply(IDocument document) {
try {
int len = 0;
while (isJavaIdentifierPart(document.getChar(offset+len))) {
len++;
}
document.replace(offset, len, getText(false));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public String getDisplayString() {
return getText(true);
}
@Override
public Image getImage() {
return getImageForDeclaration(dec);
}
@Override
public IContextInformation getContextInformation() {
return null;
}
private String getText(boolean description) {
StringBuilder sb = new StringBuilder()
.append(dec.getName());
if (dec instanceof Functional) {
appendPositionalArgs(dec, getUnit(),
sb, false, description);
}
return sb.toString();
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int currentOffset,
DocumentEvent event) {
if (event==null) {
return true;
}
else {
try {
String content = document.get(offset,
currentOffset-offset);
String filter = content.trim().toLowerCase();
if ((dec.getName().toLowerCase())
.startsWith(filter)) {
return true;
}
}
catch (BadLocationException e) {
// ignore concurrently modified document
}
return false;
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_RefinementCompletionProposal.java |
53 | final class ReturnValueContextInfo implements IContextInformation {
@Override
public String getInformationDisplayString() {
if (declaration instanceof TypedDeclaration) {
return getType().getProducedTypeName(getUnit());
}
else {
return null;
}
}
@Override
public Image getImage() {
return getImageForDeclaration(declaration);
}
@Override
public String getContextDisplayString() {
return "Return value of '" + declaration.getName() + "'";
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_RefinementCompletionProposal.java |
54 | public class TypeArgumentListCompletions {
public static void addTypeArgumentListProposal(final int offset,
final CeylonParseController cpc, final Node node,
final Scope scope, final IDocument document,
final List<ICompletionProposal> result) {
final Integer startIndex2 = node.getStartIndex();
final Integer stopIndex2 = node.getStopIndex();
final String typeArgText;
try {
typeArgText = document.get(startIndex2, stopIndex2-startIndex2+1);
}
catch (BadLocationException e) {
e.printStackTrace();
return;
}
new Visitor() {
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
Tree.TypeArguments tal = that.getTypeArguments();
Integer startIndex = tal==null ?
null : that.getTypeArguments().getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
ProducedReference pr = that.getTarget();
Declaration d = that.getDeclaration();
if (d instanceof Functional && pr!=null) {
try {
String pref = document.get(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1);
addInvocationProposals(offset, pref, cpc, result, d,
pr, scope, null, typeArgText, false);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
super.visit(that);
}
public void visit(Tree.SimpleType that) {
Tree.TypeArgumentList tal = that.getTypeArgumentList();
Integer startIndex = tal==null ? null : tal.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
Declaration d = that.getDeclarationModel();
if (d instanceof Functional) {
try {
String pref = document.get(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1);
addInvocationProposals(offset, pref, cpc, result, d,
that.getTypeModel(), scope, null, typeArgText,
false);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
super.visit(that);
}
}.visit(cpc.getRootNode());
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_TypeArgumentListCompletions.java |
55 | new Visitor() {
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
Tree.TypeArguments tal = that.getTypeArguments();
Integer startIndex = tal==null ?
null : that.getTypeArguments().getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
ProducedReference pr = that.getTarget();
Declaration d = that.getDeclaration();
if (d instanceof Functional && pr!=null) {
try {
String pref = document.get(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1);
addInvocationProposals(offset, pref, cpc, result, d,
pr, scope, null, typeArgText, false);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
super.visit(that);
}
public void visit(Tree.SimpleType that) {
Tree.TypeArgumentList tal = that.getTypeArgumentList();
Integer startIndex = tal==null ? null : tal.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
Declaration d = that.getDeclarationModel();
if (d instanceof Functional) {
try {
String pref = document.get(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1);
addInvocationProposals(offset, pref, cpc, result, d,
that.getTypeModel(), scope, null, typeArgText,
false);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
super.visit(that);
}
}.visit(cpc.getRootNode()); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_TypeArgumentListCompletions.java |
56 | public class AddAnnotionProposal extends CorrectionProposal {
private static final List<String> ANNOTATIONS_ORDER =
asList("doc", "throws", "see", "tagged", "shared", "abstract",
"actual", "formal", "default", "variable");
private static final List<String> ANNOTATIONS_ON_SEPARATE_LINE =
asList("doc", "throws", "see", "tagged");
private final Declaration dec;
private final String annotation;
AddAnnotionProposal(Declaration dec, String annotation,
String desc, int offset, TextFileChange change,
Region selection) {
super(desc, change, selection);
this.dec = dec;
this.annotation = annotation;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddAnnotionProposal) {
AddAnnotionProposal that = (AddAnnotionProposal) obj;
return that.dec.equals(dec) &&
that.annotation.equals(annotation);
}
else {
return super.equals(obj);
}
}
@Override
public int hashCode() {
return dec.hashCode();
}
private static void addAddAnnotationProposal(Node node, String annotation,
String desc, Declaration dec, Collection<ICompletionProposal> proposals,
IProject project) {
if (dec!=null && dec.getName()!=null &&
!(node instanceof Tree.MissingDeclaration)) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv =
new FindDeclarationNodeVisitor(dec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode =
(Tree.Declaration) fdv.getDeclarationNode();
if (decNode!=null) {
addAddAnnotationProposal(annotation, desc, dec,
proposals, unit, node, decNode);
}
break;
}
}
}
}
private static void addAddAnnotationProposal(String annotation, String desc,
Declaration dec, Collection<ICompletionProposal> proposals,
PhasedUnit unit, Node node, Tree.Declaration decNode) {
IFile file = getFile(unit);
TextFileChange change = new TextFileChange(desc, file);
change.setEdit(new MultiTextEdit());
TextEdit edit = createReplaceAnnotationEdit(annotation, node, change);
if (edit==null) {
edit = createInsertAnnotationEdit(annotation, decNode,
EditorUtil.getDocument(change));
}
change.addEdit(edit);
if (decNode instanceof Tree.TypedDeclaration &&
!(decNode instanceof Tree.ObjectDefinition)) {
Tree.Type type = ((Tree.TypedDeclaration) decNode).getType();
if (type.getToken()!=null &&
(type instanceof Tree.FunctionModifier ||
type instanceof Tree.ValueModifier)) {
ProducedType it = type.getTypeModel();
if (it!=null && !(it.getDeclaration() instanceof UnknownType)) {
String explicitType = it.getProducedTypeName();
change.addEdit(new ReplaceEdit(type.getStartIndex(),
type.getText().length(), explicitType));
}
}
}
Region selection;
if (node!=null && node.getUnit().equals(decNode.getUnit())) {
selection = new Region(edit.getOffset(), annotation.length());
}
else {
selection = null;
}
Scope container = dec.getContainer();
String containerDesc = container instanceof TypeDeclaration ?
" in '" + ((TypeDeclaration) container).getName() + "'" : "";
String description =
"Make '" + dec.getName() + "' " + annotation + containerDesc;
AddAnnotionProposal p = new AddAnnotionProposal(dec, annotation,
description, edit.getOffset(), change, selection);
if (!proposals.contains(p)) {
proposals.add(p);
}
}
private static ReplaceEdit createReplaceAnnotationEdit(String annotation,
Node node, TextFileChange change) {
String toRemove;
if ("formal".equals(annotation)) {
toRemove = "default";
}
else if ("abstract".equals(annotation)) {
toRemove = "final";
}
else {
return null;
}
Tree.AnnotationList annotationList = getAnnotationList(node);
if (annotationList != null) {
for (Tree.Annotation ann:
annotationList.getAnnotations()) {
if (toRemove.equals(getAnnotationIdentifier(ann))) {
return new ReplaceEdit(ann.getStartIndex(),
ann.getStopIndex()+1-ann.getStartIndex(),
annotation);
}
}
}
return null;
}
public static InsertEdit createInsertAnnotationEdit(String newAnnotation,
Node node, IDocument doc) {
String newAnnotationName = getAnnotationWithoutParam(newAnnotation);
Tree.Annotation prevAnnotation = null;
Tree.Annotation nextAnnotation = null;
Tree.AnnotationList annotationList = getAnnotationList(node);
if (annotationList != null) {
for (Tree.Annotation annotation:
annotationList.getAnnotations()) {
if (isAnnotationAfter(newAnnotationName,
getAnnotationIdentifier(annotation))) {
prevAnnotation = annotation;
} else if (nextAnnotation == null) {
nextAnnotation = annotation;
break;
}
}
}
int nextNodeStartIndex;
if (nextAnnotation != null) {
nextNodeStartIndex = nextAnnotation.getStartIndex();
}
else {
if (node instanceof Tree.AnyAttribute ||
node instanceof Tree.AnyMethod ) {
nextNodeStartIndex =
((Tree.TypedDeclaration) node).getType().getStartIndex();
}
else if (node instanceof Tree.ObjectDefinition ) {
nextNodeStartIndex =
((CommonToken) node.getMainToken()).getStartIndex();
}
else if (node instanceof Tree.ClassOrInterface) {
nextNodeStartIndex =
((CommonToken) node.getMainToken()).getStartIndex();
}
else {
nextNodeStartIndex = node.getStartIndex();
}
}
int newAnnotationOffset;
StringBuilder newAnnotationText = new StringBuilder();
if (isAnnotationOnSeparateLine(newAnnotationName) &&
!(node instanceof Tree.Parameter)) {
if (prevAnnotation != null &&
isAnnotationOnSeparateLine(getAnnotationIdentifier(prevAnnotation))) {
newAnnotationOffset = prevAnnotation.getStopIndex() + 1;
newAnnotationText.append(System.lineSeparator());
newAnnotationText.append(getIndent(node, doc));
newAnnotationText.append(newAnnotation);
} else {
newAnnotationOffset = nextNodeStartIndex;
newAnnotationText.append(newAnnotation);
newAnnotationText.append(System.lineSeparator());
newAnnotationText.append(getIndent(node, doc));
}
} else {
newAnnotationOffset = nextNodeStartIndex;
newAnnotationText.append(newAnnotation);
newAnnotationText.append(" ");
}
return new InsertEdit(newAnnotationOffset,
newAnnotationText.toString());
}
public static Tree.AnnotationList getAnnotationList(Node node) {
Tree.AnnotationList annotationList = null;
if (node instanceof Tree.Declaration) {
annotationList =
((Tree.Declaration) node).getAnnotationList();
}
else if (node instanceof Tree.ModuleDescriptor) {
annotationList =
((Tree.ModuleDescriptor) node).getAnnotationList();
}
else if (node instanceof Tree.PackageDescriptor) {
annotationList =
((Tree.PackageDescriptor) node).getAnnotationList();
}
else if (node instanceof Tree.Assertion) {
annotationList =
((Tree.Assertion) node).getAnnotationList();
}
return annotationList;
}
public static String getAnnotationIdentifier(Tree.Annotation annotation) {
String annotationName = null;
if (annotation != null) {
if (annotation.getPrimary() instanceof Tree.BaseMemberExpression) {
Tree.BaseMemberExpression bme =
(Tree.BaseMemberExpression) annotation.getPrimary();
annotationName = bme.getIdentifier().getText();
}
}
return annotationName;
}
private static String getAnnotationWithoutParam(String annotation) {
int index = annotation.indexOf("(");
if (index != -1) {
return annotation.substring(0, index).trim();
}
index = annotation.indexOf("\"");
if (index != -1) {
return annotation.substring(0, index).trim();
}
index = annotation.indexOf(" ");
if (index != -1) {
return annotation.substring(0, index).trim();
}
return annotation.trim();
}
private static boolean isAnnotationAfter(String annotation1, String annotation2) {
int index1 = ANNOTATIONS_ORDER.indexOf(annotation1);
int index2 = ANNOTATIONS_ORDER.indexOf(annotation2);
return index1 >= index2;
}
private static boolean isAnnotationOnSeparateLine(String annotation) {
return ANNOTATIONS_ON_SEPARATE_LINE.contains(annotation);
}
static void addMakeActualDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
boolean shared = dec.isShared();
addAddAnnotationProposal(node,
shared ? "actual" : "shared actual",
shared ? "Make Actual" : "Make Shared Actual",
dec, proposals, project);
}
static void addMakeDefaultProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration d;
if (node instanceof Tree.Declaration) {
Tree.Declaration decNode = (Tree.Declaration) node;
d = decNode.getDeclarationModel();
}
else if (node instanceof Tree.BaseMemberExpression) {
d = ((Tree.BaseMemberExpression) node).getDeclaration();
}
else {
return;
}
if (d.isClassOrInterfaceMember()) {
List<Declaration> rds =
((ClassOrInterface) d.getContainer())
.getInheritedMembers(d.getName());
Declaration rd=null;
if (rds.isEmpty()) {
rd=d; //TODO: is this really correct? What case does it handle?
}
else {
for (Declaration r: rds) {
if (!r.isDefault()) {
//just take the first one :-/
//TODO: this is very wrong! Instead, make them all default!
rd = r;
break;
}
}
}
if (rd!=null) {
addAddAnnotationProposal(node,
"default", "Make Default",
rd, proposals, project);
}
}
}
static void addMakeDefaultDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node,
dec.isShared() ? "default" : "shared default",
dec.isShared() ? "Make Default" : "Make Shared Default",
dec, proposals, project);
}
static void addMakeFormalDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node,
dec.isShared() ? "formal" : "shared formal",
dec.isShared() ? "Make Formal" : "Make Shared Formal",
dec, proposals, project);
}
static void addMakeAbstractDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
if (dec instanceof Class) {
addAddAnnotationProposal(node,
"abstract", "Make Abstract",
dec, proposals, project);
}
}
static void addMakeContainerAbstractProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
Scope container =
((Tree.Declaration) node).getDeclarationModel().getContainer();
if (container instanceof Declaration) {
dec = (Declaration) container;
}
else {
return;
}
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node,
"abstract", "Make Abstract",
dec, proposals, project);
}
static void addMakeVariableProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Term term;
if (node instanceof Tree.AssignmentOp) {
term = ((Tree.AssignOp) node).getLeftTerm();
}
else if (node instanceof Tree.UnaryOperatorExpression) {
term = ((Tree.PrefixOperatorExpression) node).getTerm();
}
else if (node instanceof Tree.MemberOrTypeExpression) {
term = (Tree.MemberOrTypeExpression) node;
}
else if (node instanceof Tree.SpecifierStatement) {
term = ((Tree.SpecifierStatement) node).getBaseMemberExpression();
}
else {
return;
}
if (term instanceof Tree.MemberOrTypeExpression) {
Declaration dec =
((Tree.MemberOrTypeExpression) term).getDeclaration();
if (dec instanceof Value) {
if (((Value) dec).getOriginalDeclaration()==null) {
addAddAnnotationProposal(node,
"variable", "Make Variable",
dec, proposals, project);
}
}
}
}
static void addMakeVariableDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Tree.Declaration node) {
final Declaration dec = node.getDeclarationModel();
if (dec instanceof Value && node instanceof Tree.AttributeDeclaration) {
final Value v = (Value) dec;
if (!v.isVariable() && !v.isTransient()) {
addAddAnnotationProposal(node,
"variable", "Make Variable",
dec, proposals, project);
}
}
}
static void addMakeVariableDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Tree.CompilationUnit cu, Node node) {
final Tree.SpecifierOrInitializerExpression sie =
(Tree.SpecifierOrInitializerExpression) node;
class GetInitializedVisitor extends Visitor {
Value dec;
@Override
public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
if (that.getSpecifierOrInitializerExpression()==sie) {
dec = that.getDeclarationModel();
}
}
}
GetInitializedVisitor v = new GetInitializedVisitor();
v.visit(cu);
addAddAnnotationProposal(node,
"variable", "Make Variable",
v.dec, proposals, project);
}
static void addMakeSharedProposalForSupertypes(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
if (node instanceof Tree.ClassOrInterface) {
Tree.ClassOrInterface c = (Tree.ClassOrInterface) node;
ProducedType extendedType =
c.getDeclarationModel().getExtendedType();
if (extendedType!=null) {
addMakeSharedProposal(proposals, project,
extendedType.getDeclaration());
for (ProducedType typeArgument:
extendedType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
List<ProducedType> satisfiedTypes =
c.getDeclarationModel().getSatisfiedTypes();
if (satisfiedTypes!=null) {
for (ProducedType satisfiedType: satisfiedTypes) {
addMakeSharedProposal(proposals, project,
satisfiedType.getDeclaration());
for (ProducedType typeArgument:
satisfiedType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
}
}
static void addMakeRefinedSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
if (node instanceof Tree.Declaration) {
Declaration refined = ((Tree.Declaration) node).getDeclarationModel()
.getRefinedDeclaration();
if (refined.isDefault() || refined.isFormal()) {
addMakeSharedProposal(proposals, project, refined);
}
else {
addAddAnnotationProposal(node,
"shared default", "Make Shared Default",
refined, proposals, project);
}
}
}
static void addMakeSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec = null;
List<ProducedType> typeArgumentList = null;
if (node instanceof Tree.StaticMemberOrTypeExpression) {
Tree.StaticMemberOrTypeExpression qmte =
(Tree.StaticMemberOrTypeExpression) node;
dec = qmte.getDeclaration();
}
//TODO: handle much more kinds of types!
else if (node instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) node;
dec = st.getDeclarationModel();
}
else if (node instanceof Tree.OptionalType) {
Tree.OptionalType ot = (Tree.OptionalType) node;
if (ot.getDefiniteType() instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) ot.getDefiniteType();
dec = st.getDeclarationModel();
}
}
else if (node instanceof Tree.IterableType) {
Tree.IterableType it = (Tree.IterableType) node;
if (it.getElementType() instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) it.getElementType();
dec = st.getDeclarationModel();
}
}
else if (node instanceof Tree.SequenceType) {
Tree.SequenceType qt = (Tree.SequenceType) node;
if (qt.getElementType() instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) qt.getElementType();
dec = st.getDeclarationModel();
}
}
else if (node instanceof Tree.ImportMemberOrType) {
Tree.ImportMemberOrType imt = (Tree.ImportMemberOrType) node;
dec = imt.getDeclarationModel();
}
else if (node instanceof Tree.TypedDeclaration) {
Tree.TypedDeclaration td = ((Tree.TypedDeclaration) node);
if (td.getDeclarationModel() != null) {
ProducedType pt = td.getDeclarationModel().getType();
dec = pt.getDeclaration();
typeArgumentList = pt.getTypeArgumentList();
}
}
else if (node instanceof Tree.Parameter) {
Tree.Parameter parameter = ((Tree.Parameter) node);
if (parameter.getParameterModel()!=null &&
parameter.getParameterModel().getType()!=null) {
ProducedType pt = parameter.getParameterModel().getType();
dec = pt.getDeclaration();
typeArgumentList = pt.getTypeArgumentList();
}
}
addMakeSharedProposal(proposals, project, dec);
if (typeArgumentList != null) {
for (ProducedType typeArgument : typeArgumentList) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
static void addMakeSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Declaration dec) {
if (dec!=null) {
if (dec instanceof UnionType) {
List<ProducedType> caseTypes =
((UnionType) dec).getCaseTypes();
for (ProducedType caseType: caseTypes) {
addMakeSharedProposal(proposals, project,
caseType.getDeclaration());
for (ProducedType typeArgument:
caseType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
else if (dec instanceof IntersectionType) {
List<ProducedType> satisfiedTypes =
((IntersectionType) dec).getSatisfiedTypes();
for (ProducedType satisfiedType: satisfiedTypes) {
addMakeSharedProposal(proposals, project,
satisfiedType.getDeclaration());
for (ProducedType typeArgument:
satisfiedType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
else if (dec instanceof TypedDeclaration ||
dec instanceof ClassOrInterface ||
dec instanceof TypeAlias) {
if (!dec.isShared()) {
addAddAnnotationProposal(null,
"shared", "Make Shared",
dec, proposals, project);
}
}
}
}
static void addMakeSharedDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
if (node instanceof Tree.Declaration) {
Declaration d = ((Tree.Declaration) node).getDeclarationModel();
addAddAnnotationProposal(node,
"shared", "Make Shared",
d, proposals, project);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddAnnotionProposal.java |
57 | class GetInitializedVisitor extends Visitor {
Value dec;
@Override
public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
if (that.getSpecifierOrInitializerExpression()==sie) {
dec = that.getDeclarationModel();
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddAnnotionProposal.java |
58 | class AddInitializerProposal extends InitializerProposal {
private AddInitializerProposal(TypedDeclaration dec, int offset, int length,
TextChange change) {
super("Add initializer to '" + dec.getName() + "'",
change, dec, dec.getType(), new Region(offset, length),
MINOR_CHANGE, -1, null);
}
private static void addInitializerProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals, IFile file,
Tree.TypedDeclaration decNode, Tree.SpecifierOrInitializerExpression sie) {
MethodOrValue dec = (MethodOrValue) decNode.getDeclarationModel();
if (dec==null) return;
if (dec.getInitializerParameter()==null && !dec.isFormal()) {
TextChange change = new TextFileChange("Add Initializer", file);
int offset = decNode.getStopIndex();
String defaultValue = defaultValue(cu.getUnit(), dec.getType());
String def;
int selectionOffset;
if (decNode instanceof Tree.MethodDeclaration) {
def = " => " + defaultValue;
selectionOffset = offset + 4;
}
else {
def = " = " + defaultValue;
selectionOffset = offset + 3;
}
change.setEdit(new InsertEdit(offset, def));
proposals.add(new AddInitializerProposal(dec,
selectionOffset, defaultValue.length(),
change));
}
}
static void addInitializerProposals(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, Node node) {
if (node instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) node;
Tree.SpecifierOrInitializerExpression sie =
attDecNode.getSpecifierOrInitializerExpression();
if (!(sie instanceof Tree.LazySpecifierExpression)) {
addInitializerProposal(cu, proposals, file, attDecNode, sie);
}
}
if (node instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration methDecNode = (Tree.MethodDeclaration) node;
Tree.SpecifierExpression sie = methDecNode.getSpecifierExpression();
addInitializerProposal(cu, proposals, file, methDecNode, sie);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddInitializerProposal.java |
59 | class AddModuleImportProposal implements ICompletionProposal,
ICompletionProposalExtension6 {
private final IProject project;
private final Unit unit;
private final String name;
private final String version;
AddModuleImportProposal(IProject project, Unit unit, ModuleDetails details) {
this.project = project;
this.unit = unit;
this.name = details.getName();
this.version = details.getLastVersion().getVersion();
}
AddModuleImportProposal(IProject project, Unit unit, String name, String version) {
this.project = project;
this.unit = unit;
this.name = name;
this.version = version;
}
@Override
public void apply(IDocument document) {
ModuleImportUtil.addModuleImport(project,
unit.getPackage().getModule(),
name, version);
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public String getDisplayString() {
return "Add 'import " + name + "' to module descriptor";
}
@Override
public Image getImage() {
return IMPORT;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), true);
}
static void addModuleImportProposals(Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, Node node) {
Unit unit = node.getUnit();
if (unit.getPackage().getModule().isDefault()) {
return;
}
if (node instanceof Tree.Import) {
node = ((Tree.Import) node).getImportPath();
}
List<Tree.Identifier> ids = ((Tree.ImportPath) node).getIdentifiers();
String pkg = formatPath(ids);
if (JDKUtils.isJDKAnyPackage(pkg)) {
for (String mod: new TreeSet<String>(JDKUtils.getJDKModuleNames())) {
if (JDKUtils.isJDKPackage(mod, pkg)) {
proposals.add(new AddModuleImportProposal(project, unit, mod,
JDKUtils.jdk.version));
return;
}
}
}
ModuleQuery query = getModuleQuery("", project);
query.setMemberName(formatPath(ids));
query.setMemberSearchPackageOnly(true);
query.setMemberSearchExact(true);
query.setCount(1l);
query.setBinaryMajor(Versions.JVM_BINARY_MAJOR_VERSION);
ModuleSearchResult msr = tc.getContext().getRepositoryManager()
.searchModules(query);
for (ModuleDetails md: msr.getResults()) {
proposals.add(new AddModuleImportProposal(project, unit, md));
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddModuleImportProposal.java |
60 | class AddParameterProposal extends InitializerProposal {
private AddParameterProposal(Declaration d, Declaration dec,
ProducedType type, int offset, int len, TextChange change,
int exitPos, CeylonEditor editor) {
super("Add '" + d.getName() + "' to parameter list of '" + dec.getName() + "'",
change, dec, type, new Region(offset, len), ADD_CORR, exitPos, editor);
}
private static void addParameterProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals, IFile file,
Tree.TypedDeclaration decNode,
Tree.SpecifierOrInitializerExpression sie, Node node,
CeylonEditor editor) {
MethodOrValue dec = (MethodOrValue) decNode.getDeclarationModel();
if (dec==null) return;
if (dec.getInitializerParameter()==null && !dec.isFormal()) {
TextChange change = new TextFileChange("Add Parameter", file);
change.setEdit(new MultiTextEdit());
IDocument doc = EditorUtil.getDocument(change);
//TODO: copy/pasted from SplitDeclarationProposal
String params = null;
if (decNode instanceof Tree.MethodDeclaration) {
List<ParameterList> pls =
((Tree.MethodDeclaration) decNode).getParameterLists();
if (pls.isEmpty()) {
return;
}
else {
Integer start = pls.get(0).getStartIndex();
Integer end = pls.get(pls.size()-1).getStopIndex();
try {
params = doc.get(start, end-start+1);
}
catch (BadLocationException e) {
e.printStackTrace();
return;
}
}
}
Tree.Declaration container = findDeclarationWithBody(cu, decNode);
Tree.ParameterList pl;
if (container instanceof Tree.ClassDefinition) {
pl = ((Tree.ClassDefinition) container).getParameterList();
if (pl==null) {
return;
}
}
else if (container instanceof Tree.MethodDefinition) {
List<Tree.ParameterList> pls =
((Tree.MethodDefinition) container).getParameterLists();
if (pls.isEmpty()) {
return;
}
pl = pls.get(0);
}
else {
return;
}
String def;
int len;
if (sie==null) {
String defaultValue =
defaultValue(cu.getUnit(), dec.getType());
len = defaultValue.length();
if (decNode instanceof Tree.MethodDeclaration) {
def = " => " + defaultValue;
}
else {
def = " = " + defaultValue;
}
}
else {
len = 0;
int start;
try {
def = doc.get(sie.getStartIndex(),
sie.getStopIndex()-sie.getStartIndex()+1);
start = sie.getStartIndex();
if (start>0 && doc.get(start-1,1).equals(" ")) {
start--;
def = " " + def;
}
}
catch (BadLocationException e) {
e.printStackTrace();
return;
}
change.addEdit(new DeleteEdit(start, sie.getStopIndex()-start+1));
}
if (params!=null) {
def = " = " + params + def;
}
String param = (pl.getParameters().isEmpty() ? "" : ", ") +
dec.getName() + def;
Integer offset = pl.getStopIndex();
change.addEdit(new InsertEdit(offset, param));
Tree.Type type = decNode.getType();
int shift=0;
ProducedType paramType;
if (type instanceof Tree.LocalModifier) {
Integer typeOffset = type.getStartIndex();
paramType = type.getTypeModel();
String explicitType;
if (paramType==null) {
explicitType = "Object";
paramType = type.getUnit().getObjectDeclaration().getType();
}
else {
explicitType = paramType.getProducedTypeName();
HashSet<Declaration> decs = new HashSet<Declaration>();
importType(decs, paramType, cu);
shift = applyImports(change, decs, cu, doc);
}
change.addEdit(new ReplaceEdit(typeOffset, type.getText().length(),
explicitType));
}
else {
paramType = type.getTypeModel();
}
int exitPos = node.getStopIndex()+1;
proposals.add(new AddParameterProposal(dec, container.getDeclarationModel(),
paramType, offset+param.length()+shift-len, len, change, exitPos, editor));
}
}
static void addParameterProposals(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, Node node, CeylonEditor editor) {
if (node instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) node;
Tree.SpecifierOrInitializerExpression sie =
attDecNode.getSpecifierOrInitializerExpression();
if (!(sie instanceof Tree.LazySpecifierExpression)) {
addParameterProposal(cu, proposals, file, attDecNode, sie, node, editor);
}
}
if (node instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration methDecNode = (Tree.MethodDeclaration) node;
Tree.SpecifierExpression sie = methDecNode.getSpecifierExpression();
addParameterProposal(cu, proposals, file, methDecNode, sie, node, editor);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddParameterProposal.java |
61 | class AddParenthesesProposal extends CorrectionProposal {
AddParenthesesProposal(Declaration dec, int offset,
TextFileChange change) {
super("Add empty parameter list to '" + dec.getName() + "'" +
(dec.getContainer() instanceof TypeDeclaration?
" in '" + ((TypeDeclaration) dec.getContainer()).getName() + "'" : ""),
change, new Region(offset, 0));
}
static void addAddParenthesesProposal(ProblemLocation problem, IFile file,
Collection<ICompletionProposal> proposals, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
Node n = getBeforeParenthesisNode(decNode);
if (n!=null) {
int offset = n.getStopIndex();
TextFileChange change = new TextFileChange("Add Empty Parameter List", file);
change.setEdit(new InsertEdit(offset+1, "()"));
proposals.add(new AddParenthesesProposal(decNode.getDeclarationModel(),
offset+2, change));
}
}
private static Node getBeforeParenthesisNode(Tree.Declaration decNode) {
Node n = decNode.getIdentifier();
if (decNode instanceof Tree.TypeDeclaration) {
Tree.TypeParameterList tpl = ((Tree.TypeDeclaration) decNode).getTypeParameterList();
if (tpl!=null) {
n = tpl;
}
}
if (decNode instanceof Tree.AnyMethod) {
Tree.TypeParameterList tpl = ((Tree.AnyMethod) decNode).getTypeParameterList();
if (tpl!=null) {
n = tpl;
}
}
return n;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddParenthesesProposal.java |
62 | public class AddSatisfiesProposal extends CorrectionProposal {
public static void addSatisfiesProposals(Tree.CompilationUnit cu,
Node node, Collection<ICompletionProposal> proposals,
IProject project) {
node = determineNode(node);
if (node == null) {
return;
}
TypeDeclaration typeDec = determineTypeDeclaration(node);
if (typeDec == null) {
return;
}
boolean isTypeParam = typeDec instanceof TypeParameter;
List<ProducedType> missingSatisfiedTypes =
determineMissingSatisfiedTypes(cu, node, typeDec);
if (!isTypeParam) {
for (Iterator<ProducedType> it =
missingSatisfiedTypes.iterator();
it.hasNext();) {
ProducedType pt = it.next();
if (!(pt.getDeclaration() instanceof Interface)) {
it.remove();
}
//TODO: add extends clause for if the type is a Class
}
}
if (missingSatisfiedTypes.isEmpty()) {
return;
}
String changeText =
asIntersectionTypeString(missingSatisfiedTypes);
for (PhasedUnit unit: getUnits(project)) {
if (!isTypeParam ||
typeDec.getUnit().equals(unit.getUnit())) {
Node declaration =
determineContainer(unit.getCompilationUnit(), typeDec);
if (declaration==null) {
continue;
}
createProposals(proposals, typeDec, isTypeParam,
changeText, unit, declaration);
break;
}
}
}
private static void createProposals(Collection<ICompletionProposal> proposals,
TypeDeclaration typeDec, boolean isTypeParam, String changeText,
PhasedUnit unit, Node declaration) {
if (isTypeParam) {
if (declaration instanceof Tree.ClassDefinition) {
Tree.ClassDefinition classDefinition =
(Tree.ClassDefinition) declaration;
addConstraintSatisfiesProposals(typeDec, changeText,
unit, proposals,
classDefinition.getTypeConstraintList(),
classDefinition.getClassBody().getStartIndex());
}
else if (declaration instanceof Tree.InterfaceDefinition) {
Tree.InterfaceDefinition interfaceDefinition =
(Tree.InterfaceDefinition) declaration;
addConstraintSatisfiesProposals(typeDec, changeText,
unit, proposals,
interfaceDefinition.getTypeConstraintList(),
interfaceDefinition.getInterfaceBody().getStartIndex());
}
else if (declaration instanceof Tree.MethodDefinition) {
Tree.MethodDefinition methodDefinition =
(Tree.MethodDefinition)declaration;
addConstraintSatisfiesProposals(typeDec, changeText,
unit, proposals,
methodDefinition.getTypeConstraintList(),
methodDefinition.getBlock().getStartIndex());
}
else if (declaration instanceof Tree.ClassDeclaration) {
Tree.ClassDeclaration classDefinition =
(Tree.ClassDeclaration) declaration;
addConstraintSatisfiesProposals(typeDec, changeText,
unit, proposals,
classDefinition.getTypeConstraintList(),
classDefinition.getClassSpecifier().getStartIndex());
}
else if (declaration instanceof Tree.InterfaceDefinition) {
Tree.InterfaceDeclaration interfaceDefinition =
(Tree.InterfaceDeclaration) declaration;
addConstraintSatisfiesProposals(typeDec, changeText,
unit, proposals,
interfaceDefinition.getTypeConstraintList(),
interfaceDefinition.getTypeSpecifier().getStartIndex());
}
else if (declaration instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration methodDefinition =
(Tree.MethodDeclaration)declaration;
addConstraintSatisfiesProposals(typeDec, changeText,
unit, proposals,
methodDefinition.getTypeConstraintList(),
methodDefinition.getSpecifierExpression().getStartIndex());
}
}
else {
if (declaration instanceof Tree.ClassDefinition) {
Tree.ClassDefinition classDefinition =
(Tree.ClassDefinition) declaration;
addSatisfiesProposals(typeDec, changeText, unit, proposals,
classDefinition.getSatisfiedTypes(),
classDefinition.getTypeConstraintList()==null ?
classDefinition.getClassBody().getStartIndex() :
classDefinition.getTypeConstraintList().getStartIndex());
}
else if (declaration instanceof Tree.ObjectDefinition) {
Tree.ObjectDefinition objectDefinition =
(Tree.ObjectDefinition) declaration;
addSatisfiesProposals(typeDec, changeText, unit, proposals,
objectDefinition.getSatisfiedTypes(),
objectDefinition.getClassBody().getStartIndex());
}
else if (declaration instanceof Tree.InterfaceDefinition) {
Tree.InterfaceDefinition interfaceDefinition =
(Tree.InterfaceDefinition) declaration;
addSatisfiesProposals(typeDec, changeText, unit, proposals,
interfaceDefinition.getSatisfiedTypes(),
interfaceDefinition.getTypeConstraintList()==null ?
interfaceDefinition.getInterfaceBody().getStartIndex() :
interfaceDefinition.getTypeConstraintList().getStartIndex());
}
}
}
private static void addConstraintSatisfiesProposals(TypeDeclaration typeParam,
String missingSatisfiedType, PhasedUnit unit,
Collection<ICompletionProposal> proposals,
TypeConstraintList typeConstraints,
Integer typeContainerBodyStartIndex) {
String changeText = null;
Integer changeIndex = null;
if (typeConstraints != null) {
for (TypeConstraint typeConstraint:
typeConstraints.getTypeConstraints()) {
if (typeConstraint.getDeclarationModel().equals(typeParam)) {
changeText = " & " + missingSatisfiedType;
changeIndex = typeConstraint.getStopIndex() + 1;
break;
}
}
}
if (changeText == null) {
changeText = "given "+ typeParam.getName() +
" satisfies " + missingSatisfiedType + " ";
changeIndex = typeContainerBodyStartIndex;
}
if (changeText != null) {
IFile file = CeylonBuilder.getFile(unit);
TextFileChange change =
new TextFileChange("Add generic type constraint", file);
change.setEdit(new InsertEdit(changeIndex, changeText));
String desc = "Add generic type constraint '" + typeParam.getName() +
" satisfies " + missingSatisfiedType + "'";
AddSatisfiesProposal p =
new AddSatisfiesProposal(typeParam, desc,
missingSatisfiedType, change);
if ( !proposals.contains(p)) {
proposals.add(p);
}
}
}
private static void addSatisfiesProposals(TypeDeclaration typeParam,
String missingSatisfiedType, PhasedUnit unit,
Collection<ICompletionProposal> proposals,
Tree.SatisfiedTypes typeConstraints,
Integer typeContainerBodyStartIndex) {
String changeText = null;
Integer changeIndex = null;
if (typeConstraints != null) {
changeText = " & " + missingSatisfiedType;
changeIndex = typeConstraints.getStopIndex() + 1;
}
else if (changeText == null) {
changeText = "satisfies " + missingSatisfiedType + " ";
changeIndex = typeContainerBodyStartIndex;
}
if (changeText != null) {
IFile file = CeylonBuilder.getFile(unit);
TextFileChange change =
new TextFileChange("Add satisfies type", file);
change.setEdit(new InsertEdit(changeIndex, changeText));
String desc = "Add inherited interface '" + typeParam.getName() +
" satisfies " + missingSatisfiedType + "'";
AddSatisfiesProposal p =
new AddSatisfiesProposal(typeParam, desc,
missingSatisfiedType, change);
if (!proposals.contains(p)) {
proposals.add(p);
}
}
}
private static Node determineNode(Node node) {
if (node instanceof Tree.SpecifierExpression) {
node = ((Tree.SpecifierExpression) node).getExpression();
}
if (node instanceof Tree.Expression) {
node = ((Tree.Expression) node).getTerm();
}
return node;
}
private static TypeDeclaration determineTypeDeclaration(Node node) {
TypeDeclaration typeDec = null;
if (node instanceof Tree.ClassOrInterface ||
node instanceof Tree.TypeParameterDeclaration) {
Declaration declaration =
((Tree.Declaration) node).getDeclarationModel();
if (declaration instanceof ClassOrInterface) {
typeDec = (TypeDeclaration) declaration;
}
}
else if (node instanceof Tree.ObjectDefinition) {
Value val =
((Tree.ObjectDefinition) node).getDeclarationModel();
return val.getType().getDeclaration();
}
else if (node instanceof Tree.BaseType) {
TypeDeclaration baseTypeDecl =
((Tree.BaseType) node).getDeclarationModel();
if (baseTypeDecl instanceof TypeDeclaration) {
typeDec = baseTypeDecl;
}
}
else if (node instanceof Tree.Term) {
// ProducedType type = node.getUnit()
// .denotableType(((Tree.Term)node).getTypeModel());
ProducedType type = ((Tree.Term) node).getTypeModel();
if (type != null) {
typeDec = type.getDeclaration();
}
}
return typeDec;
}
private static Node determineContainer(CompilationUnit cu, final TypeDeclaration typeDec) {
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec) {
@Override
public void visit(Tree.ObjectDefinition that) {
if (that.getDeclarationModel().getType().getDeclaration().equals(typeDec)) {
declarationNode = that;
}
super.visit(that);
}
};
fdv.visit(cu);
Tree.Declaration dec =
(Tree.Declaration) fdv.getDeclarationNode();
if (dec != null) {
FindContainerVisitor fcv =
new FindContainerVisitor(dec);
fcv.visit(cu);
return fcv.getStatementOrArgument();
}
return null;
}
private static List<ProducedType> determineMissingSatisfiedTypes(CompilationUnit cu,
Node node, TypeDeclaration typeDec) {
List<ProducedType> missingSatisfiedTypes =
new ArrayList<ProducedType>();
if (node instanceof Tree.Term) {
FindInvocationVisitor fav = new FindInvocationVisitor(node);
fav.visit(cu);
if (fav.parameter != null) {
ProducedType type = fav.parameter.getType();
if (type!=null && type.getDeclaration()!=null) {
if (type.getDeclaration() instanceof ClassOrInterface) {
missingSatisfiedTypes.add(type);
}
else if (type.getDeclaration() instanceof IntersectionType) {
for (ProducedType it: type.getDeclaration().getSatisfiedTypes()) {
if (!typeDec.inherits(it.getDeclaration())) {
missingSatisfiedTypes.add(it);
}
}
}
}
}
}
else {
List<TypeParameter> stTypeParams =
determineSatisfiedTypesTypeParams(cu, node, typeDec);
if (!stTypeParams.isEmpty()) {
ProducedType typeParamType = typeDec.getType();
Map<TypeParameter, ProducedType> substitutions =
new HashMap<TypeParameter, ProducedType>();
for (TypeParameter stTypeParam : stTypeParams) {
substitutions.put(stTypeParam, typeParamType);
}
for (TypeParameter stTypeParam : stTypeParams) {
for (ProducedType stTypeParamSatisfiedType:
stTypeParam.getSatisfiedTypes()) {
stTypeParamSatisfiedType =
stTypeParamSatisfiedType.substitute(substitutions);
boolean isMissing = true;
for (ProducedType typeParamSatisfiedType:
typeDec.getSatisfiedTypes()) {
if (stTypeParamSatisfiedType.isSupertypeOf(typeParamSatisfiedType)) {
isMissing = false;
break;
}
}
if (isMissing) {
for(ProducedType missingSatisfiedType:
missingSatisfiedTypes) {
if( missingSatisfiedType.isExactly(stTypeParamSatisfiedType) ) {
isMissing = false;
break;
}
}
}
if (isMissing) {
missingSatisfiedTypes.add(stTypeParamSatisfiedType);
}
}
}
}
}
return missingSatisfiedTypes;
}
private static List<TypeParameter> determineSatisfiedTypesTypeParams(
Tree.CompilationUnit cu, Node typeParamNode,
final TypeDeclaration typeDec) {
final List<TypeParameter> stTypeParams = new ArrayList<TypeParameter>();
FindContainerVisitor fcv = new FindContainerVisitor(typeParamNode);
fcv.visit(cu);
Tree.StatementOrArgument soa = fcv.getStatementOrArgument();
soa.visit(new Visitor() {
@Override
public void visit(Tree.SimpleType that) {
super.visit(that);
determineSatisfiedTypesTypeParams(typeDec, that, stTypeParams);
}
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
super.visit(that);
determineSatisfiedTypesTypeParams(typeDec, that, stTypeParams);
}
});
// if (soa instanceof Tree.ClassOrInterface) {
// Tree.ClassOrInterface coi = (Tree.ClassOrInterface) soa;
// if (coi.getSatisfiedTypes() != null) {
// for (Tree.StaticType st: coi.getSatisfiedTypes().getTypes()) {
// // FIXME: gavin this needs checking
// if (st instanceof Tree.SimpleType) {
// }
// }
// }
// }
// else if (soa instanceof Tree.AttributeDeclaration) {
// Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) soa;
// Tree.Type at = ad.getType();
// if (at instanceof Tree.SimpleType) {
// determineSatisfiedTypesTypeParams(typeDec,
// (Tree.SimpleType) at, stTypeParams);
// }
// }
return stTypeParams;
}
private static void determineSatisfiedTypesTypeParams(TypeDeclaration typeParam,
Tree.SimpleType st, List<TypeParameter> stTypeParams) {
Tree.TypeArgumentList args = st.getTypeArgumentList();
if (args != null) {
List<Tree.Type> stTypeArguments =
args.getTypes();
for (int i=0; i<stTypeArguments.size(); i++) {
ProducedType stTypeArgument =
stTypeArguments.get(i).getTypeModel();
if (stTypeArgument!=null &&
typeParam.equals(stTypeArgument.getDeclaration())) {
TypeDeclaration stDecl = st.getDeclarationModel();
if (stDecl!=null) {
if (stDecl.getTypeParameters()!=null &&
stDecl.getTypeParameters().size()>i) {
stTypeParams.add(stDecl.getTypeParameters().get(i));
}
}
}
}
}
}
private static void determineSatisfiedTypesTypeParams(TypeDeclaration typeParam,
Tree.StaticMemberOrTypeExpression st, List<TypeParameter> stTypeParams) {
Tree.TypeArguments args = st.getTypeArguments();
if (args instanceof Tree.TypeArgumentList) {
List<Tree.Type> stTypeArguments = ((Tree.TypeArgumentList) args).getTypes();
for (int i=0; i<stTypeArguments.size(); i++) {
ProducedType stTypeArgument =
stTypeArguments.get(i).getTypeModel();
if (stTypeArgument!=null &&
typeParam.equals(stTypeArgument.getDeclaration())) {
Declaration stDecl = st.getDeclaration();
if (stDecl instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration)stDecl;
if (td.getTypeParameters()!=null &&
td.getTypeParameters().size()>i) {
stTypeParams.add(td.getTypeParameters().get(i));
}
}
}
}
}
}
private final TypeDeclaration typeParam;
private final String missingSatisfiedTypeText;
private AddSatisfiesProposal(TypeDeclaration typeParam,
String description, String missingSatisfiedTypeText,
TextFileChange change) {
super(description, change,
new Region(change.getEdit().getOffset(), 0));
this.typeParam = typeParam;
this.missingSatisfiedTypeText = missingSatisfiedTypeText;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddSatisfiesProposal) {
AddSatisfiesProposal that = (AddSatisfiesProposal) obj;
return that.typeParam.equals(typeParam) &&
that.missingSatisfiedTypeText
.equals(missingSatisfiedTypeText);
}
return false;
}
@Override
public int hashCode() {
return typeParam.hashCode() +
missingSatisfiedTypeText.hashCode();
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddSatisfiesProposal.java |
63 | FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec) {
@Override
public void visit(Tree.ObjectDefinition that) {
if (that.getDeclarationModel().getType().getDeclaration().equals(typeDec)) {
declarationNode = that;
}
super.visit(that);
}
}; | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddSatisfiesProposal.java |
64 | soa.visit(new Visitor() {
@Override
public void visit(Tree.SimpleType that) {
super.visit(that);
determineSatisfiedTypesTypeParams(typeDec, that, stTypeParams);
}
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
super.visit(that);
determineSatisfiedTypesTypeParams(typeDec, that, stTypeParams);
}
}); | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddSatisfiesProposal.java |
65 | public class AddSpreadToVariadicParameterProposal extends CorrectionProposal {
public static void addEllipsisToSequenceParameterProposal(CompilationUnit cu,
Node node, Collection<ICompletionProposal> proposals, IFile file) {
if( !(node instanceof Tree.Term) ) {
return;
}
Tree.Term term = (Tree.Term) node;
ProducedType type = term.getTypeModel();
Interface id = type.getDeclaration().getUnit().getIterableDeclaration();
if( type.getSupertype(id) == null ) {
return;
}
FindInvocationVisitor fiv = new FindInvocationVisitor(term);
fiv.visit(cu);
if (fiv.parameter == null ||
!(fiv.parameter.isParameter()) ||
!((MethodOrValue) fiv.parameter).getInitializerParameter().isSequenced()) {
return;
}
TextFileChange change =
new TextFileChange("Spread iterable argument of variadic parameter", file);
change.setEdit(new InsertEdit(term.getStartIndex(), "*"));
AddSpreadToVariadicParameterProposal p =
new AddSpreadToVariadicParameterProposal(fiv.parameter,
term.getStopIndex() + 4, change);
if ( !proposals.contains(p)) {
proposals.add(p);
}
}
private final TypedDeclaration parameter;
private AddSpreadToVariadicParameterProposal(TypedDeclaration parameter,
int offset, TextFileChange change) {
super("Spread iterable argument of variadic parameter", change,
new Region(offset, 0));
this.parameter = parameter;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddSpreadToVariadicParameterProposal) {
AddSpreadToVariadicParameterProposal that =
(AddSpreadToVariadicParameterProposal) obj;
return that.parameter.equals(parameter);
}
return false;
}
@Override
public int hashCode() {
return parameter.hashCode();
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddSpreadToVariadicParameterProposal.java |
66 | public class AddThrowsAnnotationProposal extends CorrectionProposal {
public static void addThrowsAnnotationProposal(Collection<ICompletionProposal> proposals,
Tree.Statement statement, Tree.CompilationUnit cu, IFile file, IDocument doc) {
ProducedType exceptionType = determineExceptionType(statement);
if (exceptionType == null) {
return;
}
Tree.Declaration throwContainer = determineThrowContainer(statement, cu);
if( !(throwContainer instanceof Tree.MethodDefinition) &&
!(throwContainer instanceof Tree.AttributeGetterDefinition) &&
!(throwContainer instanceof Tree.AttributeSetterDefinition) &&
!(throwContainer instanceof Tree.ClassOrInterface) ) {
return;
}
if (isAlreadyPresent(throwContainer, exceptionType)) {
return;
}
String throwsAnnotation = "throws (`class " + exceptionType.getProducedTypeName() + "`, \"\")";
InsertEdit throwsAnnotationInsertEdit = createInsertAnnotationEdit(throwsAnnotation, throwContainer, doc);
TextFileChange throwsAnnotationChange = new TextFileChange("Add Throws Annotation", file);
throwsAnnotationChange.setEdit(throwsAnnotationInsertEdit);
int cursorOffset = throwsAnnotationInsertEdit.getOffset() + throwsAnnotationInsertEdit.getText().indexOf(")") - 1;
AddThrowsAnnotationProposal proposal =
new AddThrowsAnnotationProposal(throwsAnnotationChange, exceptionType, cursorOffset,
throwContainer.getIdentifier() != null ? throwContainer.getIdentifier().getText() : "");
if (!proposals.contains(proposal)) {
proposals.add(proposal);
}
}
private static ProducedType determineExceptionType(Tree.Statement statement) {
ProducedType exceptionType = null;
if (statement instanceof Tree.Throw) {
ProducedType ceylonLangExceptionType = statement.getUnit().getExceptionDeclaration().getType();
Tree.Expression throwExpression = ((Tree.Throw) statement).getExpression();
if (throwExpression == null) {
exceptionType = ceylonLangExceptionType;
} else {
ProducedType throwExpressionType = throwExpression.getTypeModel();
if ( throwExpressionType != null &&
throwExpressionType.isSubtypeOf(ceylonLangExceptionType) ) {
exceptionType = throwExpressionType;
}
}
}
return exceptionType;
}
private static Tree.Declaration determineThrowContainer(Tree.Statement statement,
Tree.CompilationUnit cu) {
FindContainerVisitor fcv = new FindContainerVisitor(statement);
fcv.visit(cu);
return fcv.getDeclaration();
}
private static boolean isAlreadyPresent(Tree.Declaration throwContainer, ProducedType exceptionType) {
Tree.AnnotationList annotationList = throwContainer.getAnnotationList();
if (annotationList != null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
String annotationIdentifier = getAnnotationIdentifier(annotation);
if ("throws".equals(annotationIdentifier)) {
Tree.PositionalArgumentList positionalArgumentList = annotation.getPositionalArgumentList();
if (positionalArgumentList != null &&
positionalArgumentList.getPositionalArguments() != null &&
positionalArgumentList.getPositionalArguments().size() > 0) {
Tree.PositionalArgument throwsArg = positionalArgumentList.getPositionalArguments().get(0);
if (throwsArg instanceof Tree.ListedArgument) {
Tree.Expression throwsArgExp = ((Tree.ListedArgument) throwsArg).getExpression();
if (throwsArgExp != null) {
Tree.Term term = throwsArgExp.getTerm();
if (term instanceof Tree.MemberOrTypeExpression) {
Declaration declaration = ((Tree.MemberOrTypeExpression) term).getDeclaration();
if (declaration instanceof TypeDeclaration) {
ProducedType type = ((TypeDeclaration) declaration).getType();
if (exceptionType.isExactly(type)) {
return true;
}
}
}
}
}
}
}
}
}
return false;
}
private AddThrowsAnnotationProposal(Change change, ProducedType exceptionType, int offset, String declName) {
super("Add throws annotation to '" + declName + "'", change, new Region(offset, 0));
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddThrowsAnnotationProposal.java |
67 | class AssertExistsDeclarationProposal extends CorrectionProposal {
private AssertExistsDeclarationProposal(Declaration dec,
String existsOrNonempty, int offset, TextChange change) {
super("Change to 'assert (" + existsOrNonempty + " " + dec.getName() + ")'",
change, new Region(offset, 0));
}
private static void addSplitDeclarationProposal(IDocument doc,
Tree.AttributeDeclaration decNode, Tree.CompilationUnit cu,
IFile file, Collection<ICompletionProposal> proposals) {
Value dec = decNode.getDeclarationModel();
Tree.SpecifierOrInitializerExpression sie =
decNode.getSpecifierOrInitializerExpression();
if (dec==null || dec.isParameter() || dec.isToplevel() ||
sie==null || sie.getExpression()==null) {
return;
}
ProducedType siet = sie.getExpression().getTypeModel();
String existsOrNonempty;
String desc;
if (isTypeUnknown(siet)) {
return;
}
else if (cu.getUnit().isOptionalType(siet)) {
existsOrNonempty = "exists";
desc = "Assert Exists";
}
else if (cu.getUnit().isPossiblyEmptyType(siet)) {
existsOrNonempty = "nonempty";
desc = "Assert Nonempty";
}
else {
return;
}
Tree.Identifier id = decNode.getIdentifier();
if (id==null || id.getToken()==null) {
return;
}
// int idStartOffset = id.getStartIndex();
int idEndOffset = id.getStopIndex()+1;
int semiOffset = decNode.getStopIndex();
TextChange change = new TextFileChange(desc, file);
change.setEdit(new MultiTextEdit());
Type type = decNode.getType();
Integer typeOffset = type.getStartIndex();
Integer typeLen = type.getStopIndex()-typeOffset+1;
change.addEdit(new ReplaceEdit(typeOffset, typeLen,
"assert (" + existsOrNonempty));
change.addEdit(new InsertEdit(semiOffset, ")"));
proposals.add(new AssertExistsDeclarationProposal(dec,
existsOrNonempty,
idEndOffset + 8 + existsOrNonempty.length() - typeLen,
change));
}
static void addAssertExistsDeclarationProposals(
Collection<ICompletionProposal> proposals, IDocument doc,
IFile file, Tree.CompilationUnit cu, Tree.Declaration decNode) {
if (decNode==null) return;
Declaration dec = decNode.getDeclarationModel();
if (dec!=null) {
if (decNode instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration attDecNode =
(Tree.AttributeDeclaration) decNode;
Tree.SpecifierOrInitializerExpression sie =
attDecNode.getSpecifierOrInitializerExpression();
if (sie!=null || dec.isParameter()) {
addSplitDeclarationProposal(doc,
attDecNode, cu, file, proposals);
}
}
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssertExistsDeclarationProposal.java |
68 | class AssignToForProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to For", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "for (" + initialName + " in "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ") {}"));
exitPos = stopIndex+4;
}
else {
change.addEdit(new ReplaceEdit(stopIndex, 1, ") {}"));
exitPos = stopIndex+3;
}
return change;
}
public AssignToForProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
// ProposalPosition typePosition =
// new ProposalPosition(document, offset, 5, 1,
// getSupertypeProposals(offset, unit,
// type, true, "value"));
ProposalPosition namePosition =
new ProposalPosition(document, offset+5, initialName.length(), 0,
getNameProposals(offset+5, 0, nameProposals));
// LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
String[] computeNameProposals(Node expression) {
return Nodes.nameProposals(expression, true);
}
@Override
public String getDisplayString() {
return "Assign expression to 'for' loop";
}
@Override
boolean isEnabled(ProducedType resultType) {
return resultType!=null &&
rootNode.getUnit().isIterableType(resultType);
}
static void addAssignToForProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToForProposal prop =
new AssignToForProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToForProposal.java |
69 | class AssignToIfExistsProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to If Exists", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "if (exists " + initialName + " = "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ") {}"));
exitPos = stopIndex+9;
}
else {
change.addEdit(new ReplaceEdit(stopIndex, 1, ") {}"));
exitPos = stopIndex+8;
}
return change;
}
public AssignToIfExistsProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
// ProposalPosition typePosition =
// new ProposalPosition(document, offset, 5, 1,
// getSupertypeProposals(offset, unit,
// type, true, "value"));
ProposalPosition namePosition =
new ProposalPosition(document, offset+11, initialName.length(), 0,
getNameProposals(offset+11, 0, nameProposals));
// LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
String[] computeNameProposals(Node expression) {
return super.computeNameProposals(expression);
}
@Override
public String getDisplayString() {
return "Assign expression to 'if (exists)' condition";
}
@Override
boolean isEnabled(ProducedType resultType) {
return resultType!=null &&
rootNode.getUnit().isOptionalType(resultType);
}
static void addAssignToIfExistsProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToIfExistsProposal prop =
new AssignToIfExistsProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToIfExistsProposal.java |
70 | class AssignToIfIsProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to If Is", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "if (is Nothing " + initialName + " = "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ") {}"));
exitPos = stopIndex+13;
}
else {
change.addEdit(new ReplaceEdit(stopIndex, 1, ") {}"));
exitPos = stopIndex+12;
}
return change;
}
public AssignToIfIsProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
ProposalPosition typePosition =
new ProposalPosition(document, offset+7, 7, 1,
getCaseTypeProposals(offset+7, unit, type));
ProposalPosition namePosition =
new ProposalPosition(document, offset+15, initialName.length(), 0,
getNameProposals(offset+15, 1, nameProposals));
LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
String[] computeNameProposals(Node expression) {
return super.computeNameProposals(expression);
}
@Override
public String getDisplayString() {
return "Assign expression to 'if (is)' condition";
}
@Override
boolean isEnabled(ProducedType resultType) {
return true;
}
static void addAssignToIfIsProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToIfIsProposal prop =
new AssignToIfIsProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToIfIsProposal.java |
71 | class AssignToIfNonemptyProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to If Nonempty", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "if (nonempty " + initialName + " = "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ") {}"));
exitPos = stopIndex+11;
}
else {
change.addEdit(new ReplaceEdit(stopIndex, 1, ") {}"));
exitPos = stopIndex+10;
}
return change;
}
public AssignToIfNonemptyProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
// ProposalPosition typePosition =
// new ProposalPosition(document, offset, 5, 1,
// getSupertypeProposals(offset, unit,
// type, true, "value"));
ProposalPosition namePosition =
new ProposalPosition(document, offset+13, initialName.length(), 0,
getNameProposals(offset+13, 0, nameProposals));
// LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
String[] computeNameProposals(Node expression) {
return super.computeNameProposals(expression);
}
@Override
public String getDisplayString() {
return "Assign expression to 'if (nonempty)' condition";
}
@Override
boolean isEnabled(ProducedType resultType) {
return resultType!=null &&
rootNode.getUnit().isPossiblyEmptyType(resultType);
}
static void addAssignToIfNonemptyProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToIfNonemptyProposal prop =
new AssignToIfNonemptyProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToIfNonemptyProposal.java |
72 | class AssignToLocalProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to Local", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "value " + initialName + " = "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ";"));
exitPos = stopIndex+2;
}
else {
exitPos = stopIndex+1;
}
return change;
}
public AssignToLocalProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
ProposalPosition typePosition =
new ProposalPosition(document, offset, 5, 1,
getSupertypeProposals(offset, unit,
type, true, "value"));
ProposalPosition namePosition =
new ProposalPosition(document, offset+6, initialName.length(), 0,
getNameProposals(offset, 1, nameProposals));
LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
public String getDisplayString() {
return "Assign expression to new local";
}
static void addAssignToLocalProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToLocalProposal prop =
new AssignToLocalProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToLocalProposal.java |
73 | class AssignToTryProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to Try", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "try (" + initialName + " = "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ") {}"));
exitPos = stopIndex+3;
}
else {
change.addEdit(new ReplaceEdit(stopIndex, 1, ") {}"));
exitPos = stopIndex+2;
}
return change;
}
public AssignToTryProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
// ProposalPosition typePosition =
// new ProposalPosition(document, offset, 5, 1,
// getSupertypeProposals(offset, unit,
// type, true, "value"));
ProposalPosition namePosition =
new ProposalPosition(document, offset+5, initialName.length(), 0,
getNameProposals(offset+5, 0, nameProposals));
// LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
String[] computeNameProposals(Node expression) {
return super.computeNameProposals(expression);
}
@Override
public String getDisplayString() {
return "Assign expression to 'try'";
}
@Override
boolean isEnabled(ProducedType resultType) {
return resultType!=null &&
rootNode.getUnit().isUsableType(resultType);
}
static void addAssignToTryProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToTryProposal prop =
new AssignToTryProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToTryProposal.java |
74 | public class CeylonCorrectionProcessor extends QuickAssistAssistant
implements IQuickAssistProcessor {
private CeylonEditor editor; //may only be used for quick assists!!!
private Tree.CompilationUnit model;
private IFile file; //may only be used for markers!
public CeylonCorrectionProcessor(CeylonEditor editor) {
this.editor = editor;
setQuickAssistProcessor(this);
}
public CeylonCorrectionProcessor(IMarker marker) {
IFileEditorInput input = MarkerUtils.getInput(marker);
if (input!=null) {
file = input.getFile();
IProject project = file.getProject();
IJavaProject javaProject = JavaCore.create(project);
TypeChecker tc = getProjectTypeChecker(project);
if (tc!=null) {
try {
for (IPackageFragmentRoot pfr: javaProject.getPackageFragmentRoots()) {
if (pfr.getPath().isPrefixOf(file.getFullPath())) {
IPath relPath = file.getFullPath().makeRelativeTo(pfr.getPath());
model = tc.getPhasedUnitFromRelativePath(relPath.toString())
.getCompilationUnit();
}
}
}
catch (JavaModelException e) {
e.printStackTrace();
}
}
}
setQuickAssistProcessor(this);
}
private IFile getFile() {
if (editor!=null &&
editor.getEditorInput() instanceof FileEditorInput) {
FileEditorInput input = (FileEditorInput) editor.getEditorInput();
if (input!=null) {
return input.getFile();
}
}
return file;
}
private Tree.CompilationUnit getRootNode() {
if (editor!=null) {
return editor.getParseController().getRootNode();
}
else if (model!=null) {
return (Tree.CompilationUnit) model;
}
else {
return null;
}
}
@Override
public String getErrorMessage() {
return null;
}
private void collectProposals(IQuickAssistInvocationContext context,
IAnnotationModel model, Collection<Annotation> annotations,
boolean addQuickFixes, boolean addQuickAssists,
Collection<ICompletionProposal> proposals) {
ArrayList<ProblemLocation> problems = new ArrayList<ProblemLocation>();
// collect problem locations and corrections from marker annotations
for (Annotation curr: annotations) {
if (curr instanceof CeylonAnnotation) {
ProblemLocation problemLocation =
getProblemLocation((CeylonAnnotation) curr, model);
if (problemLocation != null) {
problems.add(problemLocation);
}
}
}
if (problems.isEmpty() && addQuickFixes) {
for (Annotation curr: annotations) {
if (curr instanceof SimpleMarkerAnnotation) {
collectMarkerProposals((SimpleMarkerAnnotation) curr, proposals);
}
}
}
ProblemLocation[] problemLocations =
problems.toArray(new ProblemLocation[problems.size()]);
Arrays.sort(problemLocations);
if (addQuickFixes) {
collectCorrections(context, problemLocations, proposals);
}
if (addQuickAssists) {
collectAssists(context, problemLocations, proposals);
}
}
private static ProblemLocation getProblemLocation(CeylonAnnotation annotation,
IAnnotationModel model) {
int problemId = annotation.getId();
if (problemId != -1) {
Position pos = model.getPosition((Annotation) annotation);
if (pos != null) {
return new ProblemLocation(pos.getOffset(), pos.getLength(),
annotation); // java problems all handled by the quick assist processors
}
}
return null;
}
private void collectAssists(IQuickAssistInvocationContext context,
ProblemLocation[] locations, Collection<ICompletionProposal> proposals) {
if (proposals.isEmpty()) {
addProposals(context, editor, proposals);
}
}
private static void collectMarkerProposals(SimpleMarkerAnnotation annotation,
Collection<ICompletionProposal> proposals) {
IMarker marker = annotation.getMarker();
IMarkerResolution[] res = IDE.getMarkerHelpRegistry().getResolutions(marker);
if (res.length > 0) {
for (int i = 0; i < res.length; i++) {
proposals.add(new CeylonMarkerResolutionProposal(res[i], marker));
}
}
}
@Override
public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext context) {
ArrayList<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
ISourceViewer viewer = context.getSourceViewer();
List<Annotation> annotations =
getAnnotationsForLine(viewer, getLine(context, viewer));
collectProposals(context, viewer.getAnnotationModel(),
annotations, true, true, proposals);
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
private int getLine(IQuickAssistInvocationContext context, ISourceViewer viewer) {
try {
return viewer.getDocument().getLineOfOffset(context.getOffset());
}
catch (BadLocationException e) {
e.printStackTrace();
return 0;
}
}
public void collectCorrections(IQuickAssistInvocationContext context,
ProblemLocation location, Collection<ICompletionProposal> proposals) {
Tree.CompilationUnit rootNode = getRootNode();
if (rootNode!=null) {
addProposals(context, location, getFile(),
rootNode, proposals);
}
}
private void collectCorrections(IQuickAssistInvocationContext context,
ProblemLocation[] locations, Collection<ICompletionProposal> proposals) {
ISourceViewer viewer = context.getSourceViewer();
Tree.CompilationUnit rootNode = getRootNode();
for (int i=locations.length-1; i>=0; i--) {
ProblemLocation loc = locations[i];
if (loc.getOffset()<=viewer.getSelectedRange().x) {
for (int j=i; j>=0; j--) {
ProblemLocation location = locations[j];
if (location.getOffset()!=loc.getOffset()) {
break;
}
addProposals(context, location, getFile(),
rootNode, proposals);
}
if (!proposals.isEmpty()) {
viewer.setSelectedRange(loc.getOffset(),
loc.getLength());
return;
}
}
}
for (int i=0; i<locations.length; i++) {
ProblemLocation loc = locations[i];
for (int j=i; j<locations.length; j++) {
ProblemLocation location = locations[j];
if (location.getOffset()!=loc.getOffset()) break;
addProposals(context, location, getFile(),
rootNode, proposals);
}
if (!proposals.isEmpty()) {
viewer.setSelectedRange(loc.getOffset(),
loc.getLength());
return;
}
}
}
public static boolean canFix(IMarker marker) {
try {
if (marker.getType().equals(PROBLEM_MARKER_ID)) {
return marker.getAttribute(MarkerCreator.ERROR_CODE_KEY,0)>0;
}
else {
return false;
}
}
catch (CoreException e) {
return false;
}
}
@Override
public boolean canFix(Annotation annotation) {
if (annotation instanceof CeylonAnnotation) {
return ((CeylonAnnotation) annotation).getId()>0;
}
else if (annotation instanceof MarkerAnnotation) {
return canFix(((MarkerAnnotation) annotation).getMarker());
}
else {
return false;
}
}
@Override
public boolean canAssist(IQuickAssistInvocationContext context) {
//oops, all this is totally useless, because
//this method never gets called :-/
/*Tree.CompilationUnit cu = (CompilationUnit) context.getModel()
.getAST(new NullMessageHandler(), new NullProgressMonitor());
return CeylonSourcePositionLocator.findNode(cu, context.getOffset(),
context.getOffset()+context.getLength()) instanceof Tree.Term;*/
return true;
}
private void addProposals(IQuickAssistInvocationContext context,
ProblemLocation problem, IFile file,
Tree.CompilationUnit rootNode,
Collection<ICompletionProposal> proposals) {
if (file==null) return;
IProject project = file.getProject();
TypeChecker tc = getProjectTypeChecker(project);
int offset = problem.getOffset();
Node node = Nodes.findNode(rootNode, offset,
offset + problem.getLength());
switch ( problem.getProblemId() ) {
case 100:
addDeclareLocalProposal(rootNode, node, proposals, file, editor);
//fall through:
case 102:
if (tc!=null) {
addImportProposals(rootNode, node, proposals, file);
}
addCreateEnumProposal(rootNode, node, problem, proposals,
project, tc, file);
addCreationProposals(rootNode, node, problem, proposals,
project, tc, file);
if (tc!=null) {
addChangeReferenceProposals(rootNode, node, problem, proposals, file);
}
break;
case 101:
addCreateParameterProposals(rootNode, node, problem, proposals,
project, tc, file);
if (tc!=null) {
addChangeReferenceProposals(rootNode, node, problem, proposals, file);
}
break;
case 200:
addSpecifyTypeProposal(rootNode, node, proposals, null);
break;
case 300:
addRefineFormalMembersProposal(proposals, node, rootNode, false);
addMakeAbstractDecProposal(proposals, project, node);
break;
case 350:
addRefineFormalMembersProposal(proposals, node, rootNode, true);
addMakeAbstractDecProposal(proposals, project, node);
break;
case 310:
addMakeAbstractDecProposal(proposals, project, node);
break;
case 320:
addRemoveAnnotationProposal(node, "formal", proposals, project);
break;
case 400:
addMakeSharedProposal(proposals, project, node);
break;
case 500:
case 510:
addMakeDefaultProposal(proposals, project, node);
break;
case 600:
addMakeActualDecProposal(proposals, project, node);
break;
case 701:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "actual", project, node);
break;
case 702:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 703:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "default", project, node);
break;
case 710:
case 711:
addMakeSharedProposal(proposals, project, node);
break;
case 712:
addExportModuleImportProposal(proposals, project, node);
break;
case 713:
addMakeSharedProposalForSupertypes(proposals, project, node);
break;
case 714:
addExportModuleImportProposalForSupertypes(proposals, project, node, rootNode);
break;
case 800:
case 804:
addMakeVariableProposal(proposals, project, node);
break;
case 803:
addMakeVariableProposal(proposals, project, node);
break;
case 801:
addMakeVariableDecProposal(proposals, project, rootNode, node);
break;
case 802:
break;
case 905:
addMakeContainerAbstractProposal(proposals, project, node);
break;
case 1100:
addMakeContainerAbstractProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 1101:
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
//TODO: replace body with ;
break;
case 1000:
addAddParenthesesProposal(problem, file, proposals, node);
addChangeDeclarationProposal(problem, file, proposals, node);
break;
case 1050:
addFixAliasProposal(proposals, file, problem);
break;
case 1200:
case 1201:
addRemoveAnnotationDecProposal(proposals, "shared", project, node);
break;
case 1300:
case 1301:
addMakeRefinedSharedProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "actual", project, node);
break;
case 1302:
case 1312:
case 1307:
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 1303:
case 1313:
addRemoveAnnotationDecProposal(proposals, "default", project, node);
break;
case 1400:
case 1401:
addMakeFormalDecProposal(proposals, project, node);
break;
case 1450:
addMakeFormalDecProposal(proposals, project, node);
addParameterProposals(proposals, file, rootNode, node, null);
addInitializerProposals(proposals, file, rootNode, node);
break;
case 1500:
addRemoveAnnotationDecProposal(proposals, "variable", project, node);
break;
case 1600:
addRemoveAnnotationDecProposal(proposals, "abstract", project, node);
break;
case 2000:
addCreateParameterProposals(rootNode, node, problem, proposals,
project, tc, file);
break;
case 2100:
addChangeTypeProposals(rootNode, node, problem, proposals, project);
addSatisfiesProposals(rootNode, node, proposals, project);
break;
case 2102:
addChangeTypeArgProposals(rootNode, node, problem, proposals, project);
addSatisfiesProposals(rootNode, node, proposals, project);
break;
case 2101:
addEllipsisToSequenceParameterProposal(rootNode, node, proposals, file);
break;
case 3000:
addAssignToLocalProposal(rootNode, proposals, node, offset);
addAssignToForProposal(rootNode, proposals, node, offset);
addAssignToIfExistsProposal(rootNode, proposals, node, offset);
addAssignToIfNonemptyProposal(rootNode, proposals, node, offset);
addAssignToTryProposal(rootNode, proposals, node, offset);
addAssignToIfIsProposal(rootNode, proposals, node, offset);
addPrintProposal(rootNode, proposals, node, offset);
break;
case 3100:
addShadowReferenceProposal(file, rootNode, proposals, node);
break;
case 3101:
case 3102:
addShadowSwitchReferenceProposal(file, rootNode, proposals, node);
break;
case 5001:
case 5002:
addChangeIdentifierCaseProposal(node, proposals, file);
break;
case 6000:
addFixMultilineStringIndentation(proposals, file, rootNode, node);
break;
case 7000:
addModuleImportProposals(proposals, project, tc, node);
break;
case 8000:
addRenameDescriptorProposal(rootNode, context, problem, proposals, file);
//TODO: figure out some other way to get a Shell!
if (context.getSourceViewer()!=null) {
addMoveDirProposal(file, rootNode, project, proposals,
context.getSourceViewer().getTextWidget().getShell());
}
break;
case 9000:
addChangeRefiningTypeProposal(file, rootNode, proposals, node);
break;
case 9100:
case 9200:
addChangeRefiningParametersProposal(file, rootNode, proposals, node);
break;
}
}
private void addProposals(IQuickAssistInvocationContext context,
CeylonEditor editor, Collection<ICompletionProposal> proposals) {
if (editor==null) return;
IDocument doc = context.getSourceViewer().getDocument();
IProject project = EditorUtil.getProject(editor.getEditorInput());
IFile file = EditorUtil.getFile(editor.getEditorInput());
Tree.CompilationUnit rootNode = editor.getParseController().getRootNode();
if (rootNode!=null) {
Node node = Nodes.findNode(rootNode, context.getOffset(),
context.getOffset() + context.getLength());
int currentOffset = editor.getSelection().getOffset();
RenameProposal.add(proposals, editor);
InlineDeclarationProposal.add(proposals, editor);
ChangeParametersProposal.add(proposals, editor);
ExtractValueProposal.add(proposals, editor, node);
ExtractFunctionProposal.add(proposals, editor, node);
ExtractParameterProposal.add(proposals, editor, node);
CollectParametersProposal.add(proposals, editor);
MoveOutProposal.add(proposals, editor, node);
MakeReceiverProposal.add(proposals, editor, node);
InvertBooleanProposal.add(proposals, editor);
addAssignToLocalProposal(rootNode, proposals, node, currentOffset);
addAssignToForProposal(rootNode, proposals, node, currentOffset);
addAssignToIfExistsProposal(rootNode, proposals, node, currentOffset);
addAssignToIfNonemptyProposal(rootNode, proposals, node, currentOffset);
addAssignToTryProposal(rootNode, proposals, node, currentOffset);
addAssignToIfIsProposal(rootNode, proposals, node, currentOffset);
addPrintProposal(rootNode, proposals, node, currentOffset);
addConvertToNamedArgumentsProposal(proposals, file, rootNode,
editor, currentOffset);
addConvertToPositionalArgumentsProposal(proposals, file, rootNode,
editor, currentOffset);
Tree.Statement statement = findStatement(rootNode, node);
Tree.Declaration declaration = findDeclaration(rootNode, node);
Tree.NamedArgument argument = findArgument(rootNode, node);
Tree.ImportMemberOrType imp = findImport(rootNode, node);
addVerboseRefinementProposal(proposals, file, statement, rootNode);
addAnnotationProposals(proposals, project, declaration,
doc, currentOffset);
addTypingProposals(proposals, file, rootNode, node, declaration, editor);
addAnonymousFunctionProposals(editor, proposals, doc, file, rootNode,
currentOffset);
addDeclarationProposals(editor, proposals, doc, file, rootNode,
declaration, currentOffset);
addConvertToClassProposal(proposals, declaration, editor);
addAssertExistsDeclarationProposals(proposals, doc, file, rootNode, declaration);
addSplitDeclarationProposals(proposals, doc, file, rootNode, declaration);
addJoinDeclarationProposal(proposals, rootNode, statement, file);
addParameterProposals(proposals, file, rootNode, declaration, editor);
addArgumentProposals(proposals, doc, file, argument);
addUseAliasProposal(imp, proposals, editor);
addRenameAliasProposal(imp, proposals, editor);
addRemoveAliasProposal(imp, proposals, file, editor);
addRenameVersionProposals(node, proposals, rootNode, editor);
addConvertToIfElseProposal(doc, proposals, file, statement);
addConvertToThenElseProposal(rootNode, doc, proposals, file, statement);
addReverseIfElseProposal(doc, proposals, file, statement, rootNode);
addConvertGetterToMethodProposal(proposals, editor, file, statement);
addConvertMethodToGetterProposal(proposals, editor, file, statement);
addThrowsAnnotationProposal(proposals, statement, rootNode, file, doc);
MoveToNewUnitProposal.add(proposals, editor);
MoveToUnitProposal.add(proposals, editor);
addRefineFormalMembersProposal(proposals, node, rootNode, false);
addConvertToVerbatimProposal(proposals, file, rootNode, node, doc);
addConvertFromVerbatimProposal(proposals, file, rootNode, node, doc);
addConvertToConcatenationProposal(proposals, file, rootNode, node, doc);
addConvertToInterpolationProposal(proposals, file, rootNode, node, doc);
addExpandTypeProposal(editor, statement, file, doc, proposals);
}
}
private void addAnnotationProposals(Collection<ICompletionProposal> proposals,
IProject project, Tree.Declaration decNode, IDocument doc, int offset) {
if (decNode!=null) {
try {
Node in = Nodes.getIdentifyingNode(decNode);
if (in==null ||
doc.getLineOfOffset(in.getStartIndex())!=
doc.getLineOfOffset(offset)) {
return;
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
Declaration d = decNode.getDeclarationModel();
if (d!=null) {
if (decNode instanceof Tree.AttributeDeclaration) {
addMakeVariableDecProposal(proposals, project, decNode);
}
if ((d.isClassOrInterfaceMember()||d.isToplevel()) &&
!d.isShared()) {
addMakeSharedDecProposal(proposals, project, decNode);
}
if (d.isClassOrInterfaceMember() &&
!d.isDefault() && !d.isFormal()) {
if (decNode instanceof Tree.AnyClass) {
addMakeDefaultDecProposal(proposals, project, decNode);
}
else if (decNode instanceof Tree.AnyAttribute) {
addMakeDefaultDecProposal(proposals, project, decNode);
}
else if (decNode instanceof Tree.AnyMethod) {
addMakeDefaultDecProposal(proposals, project, decNode);
}
if (decNode instanceof Tree.ClassDefinition) {
addMakeFormalDecProposal(proposals, project, decNode);
}
else if (decNode instanceof Tree.AttributeDeclaration) {
if (((Tree.AttributeDeclaration) decNode).getSpecifierOrInitializerExpression()==null) {
addMakeFormalDecProposal(proposals, project, decNode);
}
}
else if (decNode instanceof Tree.MethodDeclaration) {
if (((Tree.MethodDeclaration) decNode).getSpecifierExpression()==null) {
addMakeFormalDecProposal(proposals, project, decNode);
}
}
}
}
}
}
private static void addAnonymousFunctionProposals(CeylonEditor editor,
Collection<ICompletionProposal> proposals, IDocument doc,
IFile file, Tree.CompilationUnit cu,
final int currentOffset) {
class FindAnonFunctionVisitor extends Visitor {
Tree.FunctionArgument result;
public void visit(Tree.FunctionArgument that) {
if (currentOffset>=that.getStartIndex() &&
currentOffset<=that.getStopIndex()+1) {
result = that;
}
super.visit(that);
}
}
FindAnonFunctionVisitor v = new FindAnonFunctionVisitor();
v.visit(cu);
Tree.FunctionArgument fun = v.result;
if (fun!=null) {
if (fun.getExpression()!=null) {
addConvertToBlockProposal(doc, proposals, file, fun);
}
if (fun.getBlock()!=null) {
addConvertToSpecifierProposal(doc, proposals, file,
fun.getBlock(), true);
}
}
}
private static void addDeclarationProposals(CeylonEditor editor,
Collection<ICompletionProposal> proposals, IDocument doc,
IFile file, Tree.CompilationUnit cu,
Tree.Declaration decNode, int currentOffset) {
if (decNode==null) return;
if (decNode.getAnnotationList()!=null) {
Integer stopIndex = decNode.getAnnotationList().getStopIndex();
if (stopIndex!=null && currentOffset<=stopIndex+1) {
return;
}
}
if (decNode instanceof Tree.TypedDeclaration) {
Tree.TypedDeclaration tdn = (Tree.TypedDeclaration) decNode;
if (tdn.getType()!=null) {
Integer stopIndex = tdn.getType().getStopIndex();
if (stopIndex!=null && currentOffset<=stopIndex+1) {
return;
}
}
}
if (decNode instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) decNode;
Tree.SpecifierOrInitializerExpression se =
attDecNode.getSpecifierOrInitializerExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file, decNode);
}
else {
addConvertToGetterProposal(doc, proposals, file, attDecNode);
}
}
if (decNode instanceof Tree.MethodDeclaration) {
Tree.SpecifierOrInitializerExpression se =
((Tree.MethodDeclaration) decNode).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file, decNode);
}
}
if (decNode instanceof Tree.AttributeSetterDefinition) {
Tree.SpecifierOrInitializerExpression se =
((Tree.AttributeSetterDefinition) decNode).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file, decNode);
}
Tree.Block b = ((Tree.AttributeSetterDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.AttributeGetterDefinition) {
Tree.Block b = ((Tree.AttributeGetterDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.MethodDefinition) {
Tree.Block b = ((Tree.MethodDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
}
private void addArgumentProposals(Collection<ICompletionProposal> proposals,
IDocument doc, IFile file, Tree.StatementOrArgument node) {
if (node instanceof Tree.MethodArgument) {
Tree.MethodArgument ma = (Tree.MethodArgument) node;
Tree.SpecifierOrInitializerExpression se =
ma.getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file, node);
}
Tree.Block b = ma.getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (node instanceof Tree.AttributeArgument) {
Tree.AttributeArgument aa = (Tree.AttributeArgument) node;
Tree.SpecifierOrInitializerExpression se =
aa.getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file, node);
}
Tree.Block b = aa.getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (node instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) node;
addFillInArgumentNameProposal(proposals, doc, file, sa);
}
}
private void addCreationProposals(Tree.CompilationUnit cu, final Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
if (node instanceof Tree.MemberOrTypeExpression) {
addCreateProposals(cu, node, proposals, project, file);
}
else if (node instanceof Tree.SimpleType) {
class FindExtendedTypeExpressionVisitor extends Visitor {
Tree.InvocationExpression invocationExpression;
@Override
public void visit(Tree.ExtendedType that) {
super.visit(that);
if (that.getType()==node) {
invocationExpression = that.getInvocationExpression();
}
}
}
FindExtendedTypeExpressionVisitor v = new FindExtendedTypeExpressionVisitor();
v.visit(cu);
if (v.invocationExpression!=null) {
addCreateProposals(cu, v.invocationExpression.getPrimary(),
proposals, project, file);
}
}
//TODO: should we add this stuff back in??
/*else if (node instanceof Tree.BaseType) {
Tree.BaseType bt = (Tree.BaseType) node;
String brokenName = bt.getIdentifier().getText();
String idef = "interface " + brokenName + " {}";
String idesc = "interface '" + brokenName + "'";
String cdef = "class " + brokenName + "() {}";
String cdesc = "class '" + brokenName + "()'";
//addCreateLocalProposals(proposals, project, idef, idesc, INTERFACE, cu, bt);
addCreateLocalProposals(proposals, project, cdef, cdesc, CLASS, cu, bt, null, null);
addCreateToplevelProposals(proposals, project, idef, idesc, INTERFACE, cu, bt, null, null);
addCreateToplevelProposals(proposals, project, cdef, cdesc, CLASS, cu, bt, null, null);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals, idef, idesc,
INTERFACE, file, brokenName, null, null);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals, cdef, cdesc,
CLASS, file, brokenName, null, null);
}*/
if (node instanceof Tree.BaseType) {
Tree.BaseType bt = (Tree.BaseType) node;
String brokenName = bt.getIdentifier().getText();
addCreateTypeParameterProposal(proposals, project, cu, bt, brokenName);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CeylonCorrectionProcessor.java |
75 | class FindAnonFunctionVisitor extends Visitor {
Tree.FunctionArgument result;
public void visit(Tree.FunctionArgument that) {
if (currentOffset>=that.getStartIndex() &&
currentOffset<=that.getStopIndex()+1) {
result = that;
}
super.visit(that);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CeylonCorrectionProcessor.java |
76 | class FindExtendedTypeExpressionVisitor extends Visitor {
Tree.InvocationExpression invocationExpression;
@Override
public void visit(Tree.ExtendedType that) {
super.visit(that);
if (that.getType()==node) {
invocationExpression = that.getInvocationExpression();
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CeylonCorrectionProcessor.java |
77 | public class CeylonMarkerResolutionProposal implements ICompletionProposal {
private IMarkerResolution fResolution;
private IMarker fMarker;
public CeylonMarkerResolutionProposal(IMarkerResolution resolution, IMarker marker) {
fResolution = resolution;
fMarker = marker;
}
public void apply(IDocument document) {
fResolution.run(fMarker);
}
public String getAdditionalProposalInfo() {
if (fResolution instanceof IMarkerResolution2) {
return ((IMarkerResolution2) fResolution).getDescription();
}
if (fResolution instanceof ICompletionProposal) {
return ((ICompletionProposal) fResolution)
.getAdditionalProposalInfo();
}
try {
return "Problem description: " + fMarker.getAttribute(IMarker.MESSAGE);
} catch (CoreException e) {
// JavaPlugin.log(e);
}
return null;
}
public IContextInformation getContextInformation() {
return null;
}
public String getDisplayString() {
return fResolution.getLabel();
}
public Image getImage() {
if (fResolution instanceof IMarkerResolution2) {
return ((IMarkerResolution2) fResolution).getImage();
}
if (fResolution instanceof ICompletionProposal) {
return ((ICompletionProposal) fResolution).getImage();
}
return MINOR_CHANGE;
}
public Point getSelection(IDocument document) {
if (fResolution instanceof ICompletionProposal) {
return ((ICompletionProposal) fResolution).getSelection(document);
}
return null;
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CeylonMarkerResolutionProposal.java |
78 | class ChangeDeclarationProposal extends CorrectionProposal {
ChangeDeclarationProposal(String kw, int offset,
TextFileChange change) {
super("Change declaration to '" + kw + "'", change,
new Region(offset, kw.length()));
}
static void addChangeDeclarationProposal(ProblemLocation problem, IFile file,
Collection<ICompletionProposal> proposals, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
CommonToken token = (CommonToken) decNode.getMainToken();
String keyword;
if (decNode instanceof Tree.AnyClass){
keyword = "interface";
}
else if (decNode instanceof Tree.AnyMethod) {
if (token.getText().equals("void")) return;
keyword = "value";
}
else {
return;
}
TextFileChange change = new TextFileChange("Change Declaration", file);
change.setEdit(new ReplaceEdit(token.getStartIndex(),
token.getText().length(), keyword));
proposals.add(new ChangeDeclarationProposal(keyword,
token.getStartIndex(), change));
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeDeclarationProposal.java |
79 | public class ChangeInitialCaseOfIdentifierInDeclaration
extends CorrectionProposal {
public static void addChangeIdentifierCaseProposal(Node node,
Collection<ICompletionProposal> proposals, IFile file) {
Tree.Identifier identifier = null;
if (node instanceof Tree.TypeDeclaration) {
identifier = ((Tree.TypeDeclaration) node).getIdentifier();
}
else if (node instanceof Tree.TypeParameterDeclaration) {
identifier = ((Tree.TypeParameterDeclaration) node).getIdentifier();
}
else if (node instanceof Tree.TypedDeclaration) {
identifier = ((Tree.TypedDeclaration) node).getIdentifier();
}
else if (node instanceof Tree.ImportPath) {
List<Identifier> importIdentifiers = ((Tree.ImportPath) node).getIdentifiers();
for (Identifier importIdentifier : importIdentifiers) {
if (importIdentifier.getText() != null &&
!importIdentifier.getText().isEmpty() &&
Character.isUpperCase(importIdentifier.getText().charAt(0))) {
identifier = importIdentifier;
break;
}
}
}
if (identifier != null && !identifier.getText().isEmpty()) {
addProposal(identifier, proposals, file);
}
}
private static void addProposal(Identifier identifier,
Collection<ICompletionProposal> proposals, IFile file) {
String newIdentifier;
String newFirstLetter;
String oldIdentifier = identifier.getText();
if (Character.isUpperCase(oldIdentifier.charAt(0))) {
newFirstLetter = String.valueOf(Character.toLowerCase(oldIdentifier.charAt(0)));
newIdentifier = newFirstLetter + oldIdentifier.substring(1);
} else {
newFirstLetter = String.valueOf(Character.toUpperCase(oldIdentifier.charAt(0)));
newIdentifier = newFirstLetter + oldIdentifier.substring(1);
}
TextFileChange change = new TextFileChange("Change initial case of identifier", file);
change.setEdit(new ReplaceEdit(identifier.getStartIndex(), 1, newFirstLetter));
ChangeInitialCaseOfIdentifierInDeclaration proposal =
new ChangeInitialCaseOfIdentifierInDeclaration(newIdentifier, change);
if (!proposals.contains(proposal)) {
proposals.add(proposal);
}
}
public ChangeInitialCaseOfIdentifierInDeclaration(String newIdentifier, Change change) {
super("Change initial case of identifier to '" + newIdentifier + "'", change, null);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeInitialCaseOfIdentifierInDeclaration.java |
80 | class ChangeParametersProposal implements ICompletionProposal,
ICompletionProposalExtension6 {
private final Declaration dec;
private final CeylonEditor editor;
ChangeParametersProposal(Declaration dec, CeylonEditor editor) {
this.dec = dec;
this.editor = editor;
}
@Override
public Point getSelection(IDocument doc) {
return null;
}
@Override
public Image getImage() {
return REORDER;
}
@Override
public String getDisplayString() {
return "Change parameters of '" + dec.getName() + "'";
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument doc) {
new ChangeParametersRefactoringAction(editor).run();
}
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), false);
}
public static void add(Collection<ICompletionProposal> proposals,
CeylonEditor editor) {
ChangeParametersRefactoring cpr = new ChangeParametersRefactoring(editor);
if (cpr.isEnabled()) {
proposals.add(new ChangeParametersProposal(cpr.getDeclaration(),
editor));
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeParametersProposal.java |
81 | class ChangeReferenceProposal extends CorrectionProposal
implements ICompletionProposalExtension {
private ChangeReferenceProposal(ProblemLocation problem,
String name, String pkg, TextFileChange change) {
super("Change reference to '" + name + "'" + pkg, change,
new Region(problem.getOffset(), name.length()),
MINOR_CHANGE);
}
static void addChangeReferenceProposal(ProblemLocation problem,
Collection<ICompletionProposal> proposals, IFile file,
String brokenName, DeclarationWithProximity dwp, int dist,
Tree.CompilationUnit cu) {
TextFileChange change =
new TextFileChange("Change Reference", file);
change.setEdit(new MultiTextEdit());
IDocument doc = EditorUtil.getDocument(change);
Declaration dec = dwp.getDeclaration();
String pkg = "";
if (dec.isToplevel() &&
!isImported(dec, cu) &&
isInPackage(cu, dec)) {
String pn = dec.getContainer().getQualifiedNameString();
pkg = " in '" + pn + "'";
if (!pn.isEmpty() &&
!pn.equals(Module.LANGUAGE_MODULE_NAME)) {
OccurrenceLocation ol =
getOccurrenceLocation(cu,
Nodes.findNode(cu, problem.getOffset()),
problem.getOffset());
if (ol!=IMPORT) {
List<InsertEdit> ies =
importEdits(cu, singleton(dec),
null, null, doc);
for (InsertEdit ie: ies) {
change.addEdit(ie);
}
}
}
}
change.addEdit(new ReplaceEdit(problem.getOffset(),
brokenName.length(), dwp.getName())); //Note: don't use problem.getLength() because it's wrong from the problem list
proposals.add(new ChangeReferenceProposal(problem,
dwp.getName(), pkg, change));
}
protected static boolean isInPackage(Tree.CompilationUnit cu,
Declaration dec) {
return !dec.getUnit().getPackage()
.equals(cu.getUnit().getPackage());
}
@Override
public void apply(IDocument document, char trigger, int offset) {
apply(document);
}
@Override
public boolean isValidFor(IDocument document, int offset) {
return true;
}
@Override
public char[] getTriggerCharacters() {
return "r".toCharArray();
}
@Override
public int getContextInformationPosition() {
return -1;
}
static void addChangeReferenceProposals(Tree.CompilationUnit cu,
Node node, ProblemLocation problem,
Collection<ICompletionProposal> proposals, IFile file) {
String brokenName = Nodes.getIdentifyingNode(node).getText();
if (brokenName.isEmpty()) return;
for (DeclarationWithProximity dwp:
getProposals(node, node.getScope(), cu).values()) {
if (isUpperCase(dwp.getName().charAt(0))==isUpperCase(brokenName.charAt(0))) {
int dist = getLevenshteinDistance(brokenName, dwp.getName()); //+dwp.getProximity()/3;
//TODO: would it be better to just sort by dist, and
// then select the 3 closest possibilities?
if (dist<=brokenName.length()/3+1) {
addChangeReferenceProposal(problem, proposals, file,
brokenName, dwp, dist, cu);
}
}
}
}
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), true);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeReferenceProposal.java |
82 | public class ChangeRefiningTypeProposal {
static void addChangeRefiningTypeProposal(IFile file,
Tree.CompilationUnit cu, Collection<ICompletionProposal> proposals,
Node node) {
Tree.Declaration decNode = findDeclaration(cu, node);
if (decNode instanceof Tree.TypedDeclaration) {
TypedDeclaration dec =
((Tree.TypedDeclaration) decNode).getDeclarationModel();
Declaration rd = dec.getRefinedDeclaration();
if (rd instanceof TypedDeclaration) {
TypeDeclaration decContainer =
(TypeDeclaration) dec.getContainer();
TypeDeclaration rdContainer =
(TypeDeclaration) rd.getContainer();
ProducedType supertype =
decContainer.getType().getSupertype(rdContainer);
ProducedReference pr =
rd.getProducedReference(supertype,
Collections.<ProducedType>emptyList());
ProducedType t = pr.getType();
String type = t.getProducedTypeName(decNode.getUnit());
TextFileChange change =
new TextFileChange("Change Type", file);
int offset = node.getStartIndex();
int length = node.getStopIndex()-offset+1;
change.setEdit(new ReplaceEdit(offset, length, type));
proposals.add(new CorrectionProposal("Change type to '" + type + "'",
change, new Region(offset, length)));
}
}
}
static void addChangeRefiningParametersProposal(IFile file,
CompilationUnit cu, Collection<ICompletionProposal> proposals,
Node node) {
Tree.Declaration decNode =
(Tree.Declaration) Nodes.findStatement(cu, node);
Tree.ParameterList list;
if (decNode instanceof Tree.AnyMethod) {
list = ((Tree.AnyMethod) decNode).getParameterLists().get(0);
}
else if (decNode instanceof Tree.AnyClass) {
list = ((Tree.AnyClass) decNode).getParameterList();
}
else {
return;
}
Declaration dec = decNode.getDeclarationModel();
Declaration rd = dec.getRefinedDeclaration();
if (rd instanceof Functional && dec instanceof Functional) {
List<ParameterList> rdPls =
((Functional) rd).getParameterLists();
List<ParameterList> decPls =
((Functional) dec).getParameterLists();
if (rdPls.isEmpty() || decPls.isEmpty()) {
return;
}
List<Parameter> rdpl =
rdPls.get(0).getParameters();
List<Parameter> dpl =
decPls.get(0).getParameters();
TypeDeclaration decContainer =
(TypeDeclaration) dec.getContainer();
TypeDeclaration rdContainer =
(TypeDeclaration) rd.getContainer();
ProducedType supertype =
decContainer.getType().getSupertype(rdContainer);
ProducedReference pr =
rd.getProducedReference(supertype,
Collections.<ProducedType>emptyList());
List<Tree.Parameter> params = list.getParameters();
TextFileChange change =
new TextFileChange("Fix Refining Parameter List", file);
change.setEdit(new MultiTextEdit());
Unit unit = decNode.getUnit();
for (int i=0; i<params.size(); i++) {
Tree.Parameter p = params.get(i);
if (rdpl.size()<=i) {
Integer start = i==0 ?
list.getStartIndex()+1 :
params.get(i-1).getStopIndex()+1;
Integer stop = params.get(params.size()-1).getStopIndex()+1;
change.addEdit(new DeleteEdit(start, stop-start));
break;
}
else {
Parameter rdp = rdpl.get(i);
ProducedType pt =
pr.getTypedParameter(rdp).getFullType();
ProducedType dt =
dpl.get(i).getModel()
.getTypedReference().getFullType();
if (!dt.isExactly(pt)) {
change.addEdit(new ReplaceEdit(p.getStartIndex(),
p.getStopIndex()-p.getStartIndex()+1,
//TODO: better handling for callable parameters
pt.getProducedTypeName(unit) + " " + rdp.getName()));
}
}
}
if (rdpl.size()>params.size()) {
StringBuilder buf = new StringBuilder();
for (int i=params.size(); i<rdpl.size(); i++) {
Parameter p = rdpl.get(i);
if (i>0) {
buf.append(", ");
}
appendParameterText(buf, pr, p, unit);
}
Integer offset = params.isEmpty() ?
list.getStartIndex()+1 :
params.get(params.size()-1).getStopIndex()+1;
change.addEdit(new InsertEdit(offset, buf.toString()));
}
if (change.getEdit().hasChildren()) {
proposals.add(new CorrectionProposal("Fix refining parameter list",
change, new Region(list.getStartIndex()+1, 0)));
}
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeRefiningTypeProposal.java |
83 | class ChangeTypeProposal extends CorrectionProposal {
ChangeTypeProposal(ProblemLocation problem,
String name, String type, int offset,
TextFileChange change) {
super("Change type of "+ name + " to '" + type + "'",
change, new Region(offset, type.length()));
}
static void addChangeTypeProposal(Node node, ProblemLocation problem,
Collection<ICompletionProposal> proposals, Declaration dec,
ProducedType newType, IFile file, Tree.CompilationUnit cu) {
if (node.getStartIndex() == null || node.getStopIndex() == null) {
return;
}
if (newType.isNothing()) {
return;
}
TextFileChange change = new TextFileChange("Change Type", file);
change.setEdit(new MultiTextEdit());
IDocument doc = EditorUtil.getDocument(change);
String typeName = newType.getProducedTypeName(cu.getUnit());
int offset = node.getStartIndex();
int length = node.getStopIndex()-offset+1;
HashSet<Declaration> decs = new HashSet<Declaration>();
importType(decs, newType, cu);
int il=applyImports(change, decs, cu, doc);
change.addEdit(new ReplaceEdit(offset, length, typeName));
String name;
if (dec.isParameter()) {
name = "parameter '" + dec.getName() + "' of '" +
((Declaration) dec.getContainer()).getName() + "'";
}
else if (dec.isClassOrInterfaceMember()) {
name = "member '" + dec.getName() + "' of '" +
((ClassOrInterface) dec.getContainer()).getName() + "'";
}
else {
name = "'" + dec.getName() + "'";
}
proposals.add(new ChangeTypeProposal(problem, name,
typeName, offset+il, change));
}
static void addChangeTypeArgProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project) {
if (node instanceof Tree.SimpleType) {
TypeDeclaration decl = ((Tree.SimpleType) node).getDeclarationModel();
if (decl instanceof TypeParameter) {
Tree.Statement statement = findStatement(cu, node);
if (statement instanceof Tree.TypedDeclaration) {
Tree.TypedDeclaration ad = (Tree.TypedDeclaration) statement;
if (ad.getType() instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) ad.getType();
TypeParameter stTypeParam = null;
if (st.getTypeArgumentList() != null) {
List<Tree.Type> stTypeArguments =
st.getTypeArgumentList().getTypes();
for (int i=0; i<stTypeArguments.size(); i++) {
Tree.SimpleType stTypeArgument =
(Tree.SimpleType) stTypeArguments.get(i);
if (decl.getName().equals(
stTypeArgument.getDeclarationModel().getName())) {
TypeDeclaration stDecl = st.getDeclarationModel();
if (stDecl != null) {
if (stDecl.getTypeParameters()!=null &&
stDecl.getTypeParameters().size()>i) {
stTypeParam = stDecl.getTypeParameters().get(i);
break;
}
}
}
}
}
if (stTypeParam != null &&
!stTypeParam.getSatisfiedTypes().isEmpty()) {
IntersectionType it = new IntersectionType(cu.getUnit());
it.setSatisfiedTypes(stTypeParam.getSatisfiedTypes());
addChangeTypeProposals(proposals, problem, project, node,
it.canonicalize().getType(), decl, true);
}
}
}
}
}
}
static void addChangeTypeProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project) {
if (node instanceof Tree.SpecifierExpression) {
Tree.Expression e = ((Tree.SpecifierExpression) node).getExpression();
if (e!=null) {
node = e.getTerm();
}
}
if (node instanceof Tree.Expression) {
node = ((Tree.Expression) node).getTerm();
}
if (node instanceof Tree.Term) {
ProducedType t = ((Tree.Term) node).getTypeModel();
if (t==null) return;
ProducedType type = node.getUnit().denotableType(t);
FindInvocationVisitor fav = new FindInvocationVisitor(node);
fav.visit(cu);
TypedDeclaration td = fav.parameter;
if (td!=null) {
if (node instanceof Tree.InvocationExpression) {
node = ((Tree.InvocationExpression) node).getPrimary();
}
if (node instanceof Tree.BaseMemberExpression) {
TypedDeclaration d = (TypedDeclaration)
((Tree.BaseMemberExpression) node).getDeclaration();
addChangeTypeProposals(proposals, problem, project, node,
td.getType(), d, true);
}
if (node instanceof Tree.QualifiedMemberExpression){
TypedDeclaration d = (TypedDeclaration)
((Tree.QualifiedMemberExpression) node).getDeclaration();
addChangeTypeProposals(proposals, problem, project, node,
td.getType(), d, true);
}
addChangeTypeProposals(proposals, problem, project,
node, type, td, false);
}
}
}
private static void addChangeTypeProposals(Collection<ICompletionProposal> proposals,
ProblemLocation problem, IProject project, Node node, ProducedType type,
Declaration dec, boolean intersect) {
if (dec!=null) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
ProducedType t = null;
Node typeNode = null;
if (dec instanceof TypeParameter) {
t = ((TypeParameter) dec).getType();
typeNode = node;
}
if (dec instanceof TypedDeclaration) {
TypedDeclaration typedDec = (TypedDeclaration) dec;
FindDeclarationNodeVisitor fdv =
new FindDeclarationNodeVisitor(typedDec);
getRootNode(unit).visit(fdv);
Tree.TypedDeclaration decNode =
(Tree.TypedDeclaration) fdv.getDeclarationNode();
if (decNode!=null) {
typeNode = decNode.getType();
if (typeNode!=null) {
t= ((Tree.Type) typeNode).getTypeModel();
}
}
}
//TODO: fix this condition to properly distinguish
// between a method reference and an invocation
if (dec instanceof Method &&
node.getUnit().isCallableType(type)) {
type = node.getUnit().getCallableReturnType(type);
}
if (typeNode != null && !isTypeUnknown(type)) {
addChangeTypeProposal(typeNode, problem, proposals, dec,
type, getFile(unit), unit.getCompilationUnit());
if (t != null) {
ProducedType newType = intersect ?
intersectionType(t, type, unit.getUnit()) :
unionType(t, type, unit.getUnit());
if (!newType.isExactly(t)) {
addChangeTypeProposal(typeNode, problem,
proposals, dec, newType, getFile(unit),
unit.getCompilationUnit());
}
}
}
}
}
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeTypeProposal.java |
84 | class CollectParametersProposal implements ICompletionProposal,
ICompletionProposalExtension6 {
private final CeylonEditor editor;
CollectParametersProposal(CeylonEditor editor) {
this.editor = editor;
}
@Override
public Point getSelection(IDocument doc) {
return null;
}
@Override
public Image getImage() {
return COMPOSITE_CHANGE;
}
@Override
public String getDisplayString() {
return "Collect selected parameters into new class";
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument doc) {
new CollectParametersRefactoringAction(editor).run();
}
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), false);
}
public static void add(Collection<ICompletionProposal> proposals,
CeylonEditor editor) {
CollectParametersRefactoring cpr = new CollectParametersRefactoring(editor);
if (cpr.isEnabled()) {
proposals.add(new CollectParametersProposal(editor));
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CollectParametersProposal.java |
85 | public class ConvertGetterToMethodProposal extends CorrectionProposal {
public static void addConvertGetterToMethodProposal(Collection<ICompletionProposal> proposals,
CeylonEditor editor, IFile file, Node node) {
Value getter = null;
Tree.Type type = null;
if (node instanceof Tree.AttributeGetterDefinition) {
getter = ((Tree.AttributeGetterDefinition) node).getDeclarationModel();
type = ((Tree.AttributeGetterDefinition) node).getType();
}
else if (node instanceof Tree.AttributeDeclaration &&
((Tree.AttributeDeclaration) node).getSpecifierOrInitializerExpression()
instanceof Tree.LazySpecifierExpression) {
getter = ((Tree.AttributeDeclaration) node).getDeclarationModel();
type = ((Tree.AttributeDeclaration) node).getType();
}
if (getter != null) {
addConvertGetterToMethodProposal(proposals, editor, file, getter, type);
}
}
private static void addConvertGetterToMethodProposal(Collection<ICompletionProposal> proposals,
CeylonEditor editor, IFile file, Value getter, Tree.Type type) {
try {
RenameRefactoring refactoring = new RenameRefactoring(editor) {
@Override
public String getName() {
return "Convert Getter to Method";
};
};
refactoring.setNewName(getter.getName() + "()");
if (refactoring.getDeclaration() == null
|| !refactoring.getDeclaration().equals(getter)
|| !refactoring.isEnabled()
|| !refactoring.checkAllConditions(new NullProgressMonitor()).isOK()) {
return;
}
CompositeChange change = refactoring.createChange(new NullProgressMonitor());
if (change.getChildren().length == 0) {
return;
}
if (type instanceof Tree.ValueModifier) {
TextFileChange tfc = new TextFileChange("Convert Getter to Method", file);
tfc.setEdit(new ReplaceEdit(type.getStartIndex(),
type.getStopIndex() - type.getStartIndex() + 1,
"function"));
change.add(tfc);
}
ConvertGetterToMethodProposal proposal =
new ConvertGetterToMethodProposal(change, getter);
if (!proposals.contains(proposal)) {
proposals.add(proposal);
}
} catch (OperationCanceledException e) {
// noop
} catch (CoreException e) {
throw new RuntimeException(e);
}
}
private ConvertGetterToMethodProposal(Change change, Value getter) {
super("Convert getter '" + getter.getName() + "' to method",
change, null, CHANGE);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertGetterToMethodProposal.java |
86 | RenameRefactoring refactoring = new RenameRefactoring(editor) {
@Override
public String getName() {
return "Convert Getter to Method";
};
}; | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertGetterToMethodProposal.java |
87 | class ConvertIfElseToThenElse extends CorrectionProposal {
ConvertIfElseToThenElse(int offset, TextChange change) {
super("Convert to then-else", change, new Region(offset, 0));
}
static void addConvertToThenElseProposal(CompilationUnit cu, IDocument doc,
Collection<ICompletionProposal> proposals, IFile file,
Statement statement) {
TextChange change = createTextChange(cu, doc, statement, file);
if (change != null) {
proposals.add(new ConvertIfElseToThenElse(change.getEdit().getOffset(), change));
}
}
static TextChange createTextChange(CompilationUnit cu,
IDocument doc, Statement statement, IFile file) {
if (! (statement instanceof Tree.IfStatement)) {
return null;
}
IfStatement ifStmt = (IfStatement) statement;
if (ifStmt.getElseClause() == null) {
return null;
}
Block ifBlock = ifStmt.getIfClause().getBlock();
if (ifBlock.getStatements().size() != 1) {
return null;
}
Block elseBlock = ifStmt.getElseClause().getBlock();
if (elseBlock.getStatements().size() != 1) {
return null;
}
Node ifBlockNode = ifBlock.getStatements().get(0);
Node elseBlockNode = elseBlock.getStatements().get(0);
List<Condition> conditions = ifStmt.getIfClause()
.getConditionList().getConditions();
if (conditions.size()!=1) {
return null;
}
Condition condition = conditions.get(0);
Integer replaceFrom = statement.getStartIndex();
String test = removeEnclosingParentesis(getTerm(doc, condition));
String thenStr = null;
String elseStr = null;
String attributeIdentifier = null;
String operator = null;
String action;
if (ifBlockNode instanceof Tree.Return) {
Tree.Return ifReturn = (Tree.Return) ifBlockNode;
if (! (elseBlockNode instanceof Tree.Return)) {
return null;
}
Tree.Return elseReturn = (Tree.Return) elseBlockNode;
action = "return ";
thenStr = getOperands(doc, ifReturn.getExpression());
elseStr = getOperands(doc, elseReturn.getExpression());
} else if (ifBlockNode instanceof Tree.SpecifierStatement) {
SpecifierStatement ifSpecifierStmt = (Tree.SpecifierStatement) ifBlockNode;
attributeIdentifier = getTerm(doc, ifSpecifierStmt.getBaseMemberExpression());
operator = " = ";
action = attributeIdentifier + operator;
if (!(elseBlockNode instanceof Tree.SpecifierStatement)) {
return null;
}
String elseId = getTerm(doc, ((Tree.SpecifierStatement)elseBlockNode).getBaseMemberExpression());
if (!attributeIdentifier.equals(elseId)) {
return null;
}
thenStr = getOperands(doc, ifSpecifierStmt.getSpecifierExpression().getExpression().getTerm());
elseStr = getOperands(doc, ((Tree.SpecifierStatement) elseBlockNode).getSpecifierExpression().getExpression().getTerm());
} else if (ifBlockNode instanceof Tree.ExpressionStatement) {
if (!(elseBlockNode instanceof Tree.ExpressionStatement)) {
return null;
}
Term ifOperator = ((Tree.ExpressionStatement) ifBlockNode).getExpression().getTerm();
if (!(ifOperator instanceof AssignOp)) {
return null;
}
Term elseOperator = ((Tree.ExpressionStatement) elseBlockNode).getExpression().getTerm();
if (!(elseOperator instanceof AssignOp)) {
return null;
}
AssignOp ifAssign = (AssignOp) ifOperator;
AssignOp elseAssign = (AssignOp) elseOperator;
attributeIdentifier = getTerm(doc, ifAssign.getLeftTerm());
String elseId = getTerm(doc, elseAssign.getLeftTerm());
if (!attributeIdentifier.equals(elseId)) {
return null;
}
operator = " = ";
action = attributeIdentifier + operator;
thenStr = getOperands(doc, ifAssign.getRightTerm());
elseStr = getOperands(doc, elseAssign.getRightTerm());
} else {
return null;
}
if (attributeIdentifier != null) {
Statement prevStatement = findPreviousStatement(cu, doc, statement);
if (prevStatement != null) {
if (prevStatement instanceof AttributeDeclaration) {
AttributeDeclaration attrDecl = (AttributeDeclaration) prevStatement;
if (attributeIdentifier.equals(getTerm(doc, attrDecl.getIdentifier()))) {
action = removeSemiColon(getTerm(doc, attrDecl)) + operator;
replaceFrom = attrDecl.getStartIndex();
}
}
}
}
if (condition instanceof Tree.ExistsCondition) {
Tree.ExistsCondition existsCond = (Tree.ExistsCondition) condition;
Variable variable = existsCond.getVariable();
if (thenStr.equals(getTerm(doc, variable.getIdentifier()))) {
Expression existsExpr = variable.getSpecifierExpression().getExpression();
test = getTerm(doc, existsExpr);
thenStr = null;
} else {
return null; //Disabling because type narrowing does not work with then.
}
} else if (! (condition instanceof Tree.BooleanCondition)) {
return null; //Disabling because type narrowing does not work with then.
} else if (((BooleanCondition)condition).getExpression().getTerm() instanceof IsOp){
return null; //Disabling because type narrowing does not work with then.
}
StringBuilder replace = new StringBuilder();
replace.append(action).append(test);
if (thenStr != null) {
replace.append(" then ").append(thenStr);
}
if (!elseStr.equals("null")) {
replace.append(" else ").append(elseStr);
}
replace.append(";");
TextChange change = new TextFileChange("Convert to then-else", file);
// TextChange change = new DocumentChange("Convert to then-else", doc);
change.setEdit(new ReplaceEdit(replaceFrom,
statement.getStopIndex() - replaceFrom + 1,
replace.toString()));
return change;
}
private static String getOperands(IDocument doc, Term operand) {
String term = getTerm(doc, operand);
if (hasLowerPrecedenceThenElse(operand)) {
return "(" + term + ")";
}
return term;
}
private static boolean hasLowerPrecedenceThenElse(Term operand) {
Term node;
if (operand instanceof Tree.Expression) {
Tree.Expression exp = (Tree.Expression) operand;
node = exp.getTerm();
} else {
node = operand;
}
return node instanceof Tree.DefaultOp ||
node instanceof ThenOp ||
node instanceof AssignOp;
}
private static String removeSemiColon(String term) {
if (term.endsWith(";")) {
return term.substring(0, term.length() - 1);
}
return term;
}
private static Statement findPreviousStatement(CompilationUnit cu, IDocument doc,
Statement statement) {
try {
int previousLineNo = doc.getLineOfOffset(statement.getStartIndex());
while (previousLineNo > 1) {
previousLineNo--;
IRegion lineInfo = doc.getLineInformation(previousLineNo);
String prevLine = doc.get(lineInfo.getOffset(), lineInfo.getLength());
Matcher m = Pattern.compile("(\\s*)\\w+").matcher(prevLine);
if (m.find()) {
int whitespaceLen = m.group(1).length();
Node node = Nodes.findNode(cu, lineInfo.getOffset() + whitespaceLen,
lineInfo.getOffset() + whitespaceLen + 1);
return Nodes.findStatement(cu, node);
}
}
} catch (BadLocationException e) {
e.printStackTrace();
}
return null;
}
private static String removeEnclosingParentesis(String s) {
if (s.charAt(0) == '(' && s.charAt(s.length() - 1) == ')') {
return s.substring(1, s.length() - 1);
}
return s;
}
private static String getTerm(IDocument doc, Node node) {
try {
return doc.get(node.getStartIndex(),
node.getStopIndex() - node.getStartIndex() + 1);
} catch (BadLocationException e) {
throw new RuntimeException(e);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertIfElseToThenElse.java |
88 | public class ConvertMethodToGetterProposal extends CorrectionProposal {
public static void addConvertMethodToGetterProposal(Collection<ICompletionProposal> proposals,
CeylonEditor editor, IFile file, Node node) {
Method method = null;
Tree.Type type = null;
if (node instanceof Tree.MethodDefinition) {
method = ((Tree.MethodDefinition) node).getDeclarationModel();
type = ((Tree.MethodDefinition) node).getType();
}
else if (node instanceof Tree.MethodDeclaration &&
((Tree.MethodDeclaration) node).getSpecifierExpression()
instanceof Tree.LazySpecifierExpression) {
method = ((Tree.MethodDeclaration) node).getDeclarationModel();
type = ((Tree.MethodDeclaration) node).getType();
}
if (method != null
&& !method.isDeclaredVoid()
&& method.getParameterLists().size() == 1
&& method.getParameterLists().get(0).getParameters().size() == 0 ) {
addConvertMethodToGetterProposal(proposals, editor, file, method, type);
}
}
private static void addConvertMethodToGetterProposal(Collection<ICompletionProposal> proposals,
CeylonEditor editor, IFile file, Method method, Tree.Type type) {
try {
RenameRefactoring refactoring = new RenameRefactoring(editor) {
@Override
public String getName() {
return "Convert method to getter";
};
@Override
protected void renameNode(TextChange tfc, Node node, Tree.CompilationUnit root) {
Integer startIndex = null;
Integer stopIndex = null;
if (node instanceof Tree.AnyMethod) {
ParameterList parameterList = ((Tree.AnyMethod) node).getParameterLists().get(0);
startIndex = parameterList.getStartIndex();
stopIndex = parameterList.getStopIndex();
} else {
FindInvocationVisitor fiv = new FindInvocationVisitor(node);
fiv.visit(root);
if (fiv.result != null && fiv.result.getPrimary() == node) {
startIndex = fiv.result.getPositionalArgumentList().getStartIndex();
stopIndex = fiv.result.getPositionalArgumentList().getStopIndex();
}
}
if (startIndex != null && stopIndex != null) {
tfc.addEdit(new DeleteEdit(startIndex, stopIndex - startIndex + 1));
}
}
};
if (refactoring.getDeclaration() == null
|| !refactoring.getDeclaration().equals(method)
|| !refactoring.isEnabled()
|| !refactoring.checkAllConditions(new NullProgressMonitor()).isOK()) {
return;
}
CompositeChange change = refactoring.createChange(new NullProgressMonitor());
if (change.getChildren().length == 0) {
return;
}
if (type instanceof Tree.FunctionModifier) {
TextFileChange tfc = new TextFileChange("Convert method to getter", file);
tfc.setEdit(new ReplaceEdit(type.getStartIndex(),
type.getStopIndex() - type.getStartIndex() + 1,
"value"));
change.add(tfc);
}
ConvertMethodToGetterProposal proposal =
new ConvertMethodToGetterProposal(change, method);
if (!proposals.contains(proposal)) {
proposals.add(proposal);
}
} catch (OperationCanceledException e) {
// noop
} catch (CoreException e) {
throw new RuntimeException(e);
}
}
private ConvertMethodToGetterProposal(Change change, Method method) {
super("Convert method '" + method.getName() + "()' to getter",
change, null, CHANGE);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertMethodToGetterProposal.java |
89 | RenameRefactoring refactoring = new RenameRefactoring(editor) {
@Override
public String getName() {
return "Convert method to getter";
};
@Override
protected void renameNode(TextChange tfc, Node node, Tree.CompilationUnit root) {
Integer startIndex = null;
Integer stopIndex = null;
if (node instanceof Tree.AnyMethod) {
ParameterList parameterList = ((Tree.AnyMethod) node).getParameterLists().get(0);
startIndex = parameterList.getStartIndex();
stopIndex = parameterList.getStopIndex();
} else {
FindInvocationVisitor fiv = new FindInvocationVisitor(node);
fiv.visit(root);
if (fiv.result != null && fiv.result.getPrimary() == node) {
startIndex = fiv.result.getPositionalArgumentList().getStartIndex();
stopIndex = fiv.result.getPositionalArgumentList().getStopIndex();
}
}
if (startIndex != null && stopIndex != null) {
tfc.addEdit(new DeleteEdit(startIndex, stopIndex - startIndex + 1));
}
}
}; | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertMethodToGetterProposal.java |
90 | class ConvertStringProposal extends CorrectionProposal {
private ConvertStringProposal(String name, Change change) {
super(name, change, null);
}
static void addConvertToVerbatimProposal(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, Node node, IDocument doc) {
if (node instanceof Tree.StringLiteral) {
Tree.StringLiteral literal = (Tree.StringLiteral) node;
Token token = node.getToken();
if (token.getType()==CeylonLexer.ASTRING_LITERAL ||
token.getType()==CeylonLexer.STRING_LITERAL) {
String text = "\"\"\"" + literal.getText() + "\"\"\"";
int offset = node.getStartIndex();
int length = node.getStopIndex() - node.getStartIndex() + 1;
String reindented = getConvertedText(text, token.getCharPositionInLine()+3, doc);
TextFileChange change = new TextFileChange("Convert to Verbatim String", file);
change.setEdit(new ReplaceEdit(offset, length, reindented));
proposals.add(new ConvertStringProposal("Convert to verbatim string", change));
}
}
}
static void addConvertFromVerbatimProposal(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, Node node, IDocument doc) {
if (node instanceof Tree.StringLiteral) {
Tree.StringLiteral literal = (Tree.StringLiteral) node;
Token token = node.getToken();
if (token.getType()==CeylonLexer.AVERBATIM_STRING ||
token.getType()==CeylonLexer.VERBATIM_STRING) {
String text = "\"" +
literal.getText()
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("`", "\\`") +
"\"";
int offset = node.getStartIndex();
int length = node.getStopIndex() - node.getStartIndex() + 1;
String reindented = getConvertedText(text, token.getCharPositionInLine()+1, doc);
TextFileChange change = new TextFileChange("Convert to Ordinary String", file);
change.setEdit(new ReplaceEdit(offset, length, reindented));
proposals.add(new ConvertStringProposal("Convert to ordinary string", change));
}
}
}
private static String getConvertedText(String text, int indentation,
IDocument doc) {
StringBuilder result = new StringBuilder();
for (String line: text.split("\n|\r\n?")) {
if (result.length() == 0) {
//the first line of the string
result.append(line);
}
else {
for (int i = 0; i<indentation; i++) {
result.append(" ");
}
result.append(line);
}
result.append(Indents.getDefaultLineDelimiter(doc));
}
result.setLength(result.length()-1);
return result.toString();
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertStringProposal.java |
91 | class ConvertThenElseToIfElse extends CorrectionProposal {
ConvertThenElseToIfElse(int offset, TextChange change) {
super("Convert to if-else", change, new Region(offset, 0));
}
static void addConvertToIfElseProposal(IDocument doc,
Collection<ICompletionProposal> proposals, IFile file,
Statement statement) {
try {
String action;
String declaration = null;
Node operation;
if (statement instanceof Tree.Return) {
Tree.Return returnOp = (Return) statement;
action = "return ";
if (returnOp.getExpression() == null || returnOp.getExpression().getTerm() == null) {
return;
}
operation = returnOp.getExpression().getTerm();
} else if (statement instanceof Tree.ExpressionStatement) {
Tree.ExpressionStatement expressionStmt = (Tree.ExpressionStatement) statement;
if (expressionStmt.getExpression() == null) {
return;
}
Tree.Expression expression = expressionStmt.getExpression();
if (expression.getTerm()==null) {
return;
}
if (! (expression.getTerm() instanceof Tree.AssignOp)) {
return;
}
Tree.AssignOp assignOp = (Tree.AssignOp) expression.getTerm();
action = getTerm(doc, assignOp.getLeftTerm()) + " = ";
operation = assignOp.getRightTerm();
} else if (statement instanceof Tree.SpecifierStatement) {
Tree.SpecifierStatement specifierStmt = (Tree.SpecifierStatement) statement;
action = getTerm(doc, specifierStmt.getBaseMemberExpression()) + " = ";
operation = specifierStmt.getSpecifierExpression().getExpression();
} else if (statement instanceof CustomTree.AttributeDeclaration) {
CustomTree.AttributeDeclaration attrDecl = (CustomTree.AttributeDeclaration) statement;
if (attrDecl.getIdentifier()==null) {
return;
}
String identifier = getTerm(doc, attrDecl.getIdentifier());
String annotations = "";
if (!attrDecl.getAnnotationList().getAnnotations().isEmpty()) {
annotations = getTerm(doc, attrDecl.getAnnotationList()) + " ";
}
String type;
if (attrDecl.getType() instanceof ValueModifier) {
ValueModifier valueModifier = (ValueModifier) attrDecl.getType();
ProducedType typeModel = valueModifier.getTypeModel();
if (typeModel==null) return;
type = typeModel.getProducedTypeName();
} else {
type = getTerm(doc, attrDecl.getType());
}
declaration = annotations + type + " " + identifier + ";";
SpecifierOrInitializerExpression sie = attrDecl.getSpecifierOrInitializerExpression();
if (sie==null || sie.getExpression()==null) return;
action = identifier + " = ";
operation = sie.getExpression().getTerm();
} else {
return;
}
String test;
String elseTerm;
String thenTerm;
while (operation instanceof Expression) {
//If Operation is enclosed in parenthesis we need to get down through them: return (test then x else y);
operation = ((Expression) operation).getTerm();
}
if (operation instanceof Tree.DefaultOp) {
Tree.DefaultOp defaultOp = (Tree.DefaultOp) operation;
if (defaultOp.getLeftTerm() instanceof Tree.ThenOp) {
Tree.ThenOp thenOp = (ThenOp) defaultOp.getLeftTerm();
thenTerm = getTerm(doc, thenOp.getRightTerm());
test = getTerm(doc, thenOp.getLeftTerm());
} else {
Term leftTerm = defaultOp.getLeftTerm();
String leftTermStr = getTerm(doc, leftTerm);
if (leftTerm instanceof BaseMemberExpression) {
thenTerm = leftTermStr;
test = "exists " + leftTermStr;
} else {
String id = Nodes.nameProposals(leftTerm)[0];
test = "exists " + id + " = " + leftTermStr;
thenTerm = id;
}
}
elseTerm = getTerm(doc, defaultOp.getRightTerm());
} else if (operation instanceof Tree.ThenOp) {
Tree.ThenOp thenOp = (ThenOp) operation;
thenTerm = getTerm(doc, thenOp.getRightTerm());
test = getTerm(doc, thenOp.getLeftTerm());
elseTerm = "null";
} else {
return;
}
String baseIndent = getIndent(statement, doc);
String indent = getDefaultIndent();
test = removeEnclosingParentesis(test);
StringBuilder replace = new StringBuilder();
String delim = Indents.getDefaultLineDelimiter(doc);
if (declaration != null) {
replace.append(declaration)
.append(delim)
.append(baseIndent);
}
replace.append("if (").append(test).append(") {")
.append(delim)
.append(baseIndent).append(indent).append(action).append(thenTerm).append(";")
.append(delim)
.append(baseIndent).append("}")
.append(delim)
.append(baseIndent).append("else {")
.append(delim)
.append(baseIndent).append(indent).append(action).append(elseTerm).append(";")
.append(delim)
.append(baseIndent).append("}");
TextChange change = new TextFileChange("Convert to if-else", file);
change.setEdit(new ReplaceEdit(statement.getStartIndex(),
statement.getStopIndex() - statement.getStartIndex() + 1,
replace.toString()));
proposals.add(new ConvertThenElseToIfElse(statement.getStartIndex(), change));
} catch (BadLocationException e) {
e.printStackTrace();
}
}
private static String removeEnclosingParentesis(String s) {
if (s.charAt(0) == '(' && s.charAt(s.length() - 1) == ')') {
return s.substring(1, s.length() - 1);
}
return s;
}
private static String getTerm(IDocument doc, Node node) throws BadLocationException {
return doc.get(node.getStartIndex(), node.getStopIndex() - node.getStartIndex() + 1);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertThenElseToIfElse.java |
92 | class ConvertToBlockProposal extends CorrectionProposal {
ConvertToBlockProposal(String desc, int offset, TextChange change) {
super(desc, change, new Region(offset, 0));
}
static void addConvertToBlockProposal(IDocument doc,
Collection<ICompletionProposal> proposals, IFile file,
Node decNode) {
TextChange change = new TextFileChange("Convert to Block", file);
change.setEdit(new MultiTextEdit());
int offset;
int len;
String semi;
boolean isVoid;
String addedKeyword = null;
String desc = "Convert => to block";
if (decNode instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration md = (Tree.MethodDeclaration) decNode;
Method dm = md.getDeclarationModel();
if (dm==null || dm.isParameter()) return;
isVoid = dm.isDeclaredVoid();
List<Tree.ParameterList> pls = md.getParameterLists();
if (pls.isEmpty()) return;
offset = pls.get(pls.size()-1).getStopIndex()+1;
len = md.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) decNode;
Value dm = ad.getDeclarationModel();
if (dm==null || dm.isParameter()) return;
isVoid = false;
offset = ad.getIdentifier().getStopIndex()+1;
len = ad.getSpecifierOrInitializerExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.AttributeSetterDefinition) {
Tree.AttributeSetterDefinition asd = (Tree.AttributeSetterDefinition) decNode;
isVoid = true;
offset = asd.getIdentifier().getStopIndex()+1;
len = asd.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.MethodArgument) {
Tree.MethodArgument ma = (Tree.MethodArgument) decNode;
Method dm = ma.getDeclarationModel();
if (dm==null) return;
isVoid = dm.isDeclaredVoid();
if (ma.getType().getToken()==null) {
addedKeyword = "function ";
}
List<Tree.ParameterList> pls = ma.getParameterLists();
if (pls.isEmpty()) return;
offset = pls.get(pls.size()-1).getStopIndex()+1;
len = ma.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.AttributeArgument) {
Tree.AttributeArgument aa = (Tree.AttributeArgument) decNode;
isVoid = false;
if (aa.getType().getToken()==null) {
addedKeyword = "value ";
}
offset = aa.getIdentifier().getStopIndex()+1;
len = aa.getSpecifierExpression().getExpression().getStartIndex() - offset;
semi = "";
}
else if (decNode instanceof Tree.FunctionArgument) {
Tree.FunctionArgument fun = (Tree.FunctionArgument) decNode;
Method dm = fun.getDeclarationModel();
if (dm==null) return;
isVoid = dm.isDeclaredVoid();
List<Tree.ParameterList> pls = fun.getParameterLists();
if (pls.isEmpty()) return;
offset = pls.get(pls.size()-1).getStopIndex()+1;
len = fun.getExpression().getStartIndex() - offset;
semi = ";";
desc = "Convert anonymous function => to block";
}
else {
return;
}
if (addedKeyword!=null) {
change.addEdit(new InsertEdit(decNode.getStartIndex(), addedKeyword));
}
change.addEdit(new ReplaceEdit(offset, len, " {" + (isVoid?"":" return") + " "));
change.addEdit(new InsertEdit(decNode.getStopIndex()+1, semi + " }"));
proposals.add(new ConvertToBlockProposal(desc, offset + 3, change));
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToBlockProposal.java |
93 | class ConvertToClassProposal extends AbstractLinkedMode implements ICompletionProposal {
private final Tree.ObjectDefinition node;
public ConvertToClassProposal(Tree.ObjectDefinition node,
CeylonEditor editor) {
super(editor);
this.node = node;
}
@Override
public Point getSelection(IDocument doc) {
return null;
}
@Override
public Image getImage() {
return node.getDeclarationModel().isShared() ?
CeylonLabelProvider.CLASS :
CeylonLabelProvider.LOCAL_CLASS;
}
@Override
public String getDisplayString() {
return "Convert " + node.getDeclarationModel().getName() + " to class";
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument doc) {
Value declaration = node.getDeclarationModel();
String name = declaration.getName();
String initialName = Character.toUpperCase(name.charAt(0))+name.substring(1);
TextChange change = new DocumentChange("Convert to Class", doc);
change.setEdit(new MultiTextEdit());
Tree.ObjectDefinition od = (Tree.ObjectDefinition) node;
int dstart = ((CommonToken) od.getMainToken()).getStartIndex();
change.addEdit(new ReplaceEdit(dstart, 6, "class"));
int start = od.getIdentifier().getStartIndex();
int length = od.getIdentifier().getStopIndex()-start+1;
change.addEdit(new ReplaceEdit(start, length, initialName + "()"));
int offset = od.getStopIndex()+1;
//TODO: handle actual object declarations
String mods = declaration.isShared() ? "shared " : "";
String ws = getDefaultLineDelimiter(doc) + getIndent(od, doc);
String impl = " = " + initialName + "();";
String dec = ws + mods + initialName + " " + name;
change.addEdit(new InsertEdit(offset, dec + impl));
try {
change.perform(new NullProgressMonitor());
LinkedPositionGroup group = new LinkedPositionGroup();
group.addPosition(new LinkedPosition(doc, start-1, length, 0));
group.addPosition(new LinkedPosition(doc, offset+ws.length()+mods.length()+1, length, 1));
group.addPosition(new LinkedPosition(doc, offset+dec.length()+4, length, 2));
linkedModeModel.addGroup(group);
enterLinkedMode(doc, -1, start-1);
openPopup();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void addConvertToClassProposal(Collection<ICompletionProposal> proposals,
Tree.Declaration declaration, CeylonEditor editor) {
if (declaration instanceof Tree.ObjectDefinition) {
ConvertToClassProposal prop =
new ConvertToClassProposal((ObjectDefinition) declaration, editor);
proposals.add(prop);
}
}
@Override
protected String getHintTemplate() {
return "Enter name for new class {0}";
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToClassProposal.java |
94 | class ConvertToConcatenationProposal extends CorrectionProposal {
private ConvertToConcatenationProposal(String name, Change change) {
super(name, change, null);
}
static void addConvertToConcatenationProposal(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, final Node node, IDocument doc) {
class TemplateVisitor extends Visitor {
Tree.StringTemplate result;
@Override
public void visit(Tree.StringTemplate that) {
if (that.getStartIndex()<=node.getStartIndex() &&
that.getStopIndex()>=node.getStopIndex()) {
result = that;
}
super.visit(that);
}
}
TemplateVisitor tv = new TemplateVisitor();
tv.visit(cu);
Tree.StringTemplate template = tv.result;
if (template!=null) {
TextFileChange change = new TextFileChange("Convert to Concatenation", file);
change.setEdit(new MultiTextEdit());
List<Tree.StringLiteral> literals = template.getStringLiterals();
List<Tree.Expression> expressions = template.getExpressions();
for (int i=0; i<literals.size(); i++) {
Tree.StringLiteral s = literals.get(i);
int stt = s.getToken().getType();
if (stt==STRING_END||stt==STRING_MID) {
change.addEdit(new ReplaceEdit(s.getStartIndex(), 2, " + \""));
}
if (stt==STRING_START||stt==STRING_MID) {
change.addEdit(new ReplaceEdit(s.getStopIndex()-1, 2, "\" + "));
}
if (i<expressions.size()) {
Tree.Expression e = expressions.get(i);
if (!e.getTypeModel().isSubtypeOf(node.getUnit().getStringDeclaration().getType())) {
change.addEdit(new InsertEdit(e.getStopIndex()+1, ".string"));
}
}
}
proposals.add(new ConvertToConcatenationProposal("Convert to string concatenation", change));
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToConcatenationProposal.java |
95 | class TemplateVisitor extends Visitor {
Tree.StringTemplate result;
@Override
public void visit(Tree.StringTemplate that) {
if (that.getStartIndex()<=node.getStartIndex() &&
that.getStopIndex()>=node.getStopIndex()) {
result = that;
}
super.visit(that);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToConcatenationProposal.java |
96 | class ConvertToGetterProposal extends CorrectionProposal {
ConvertToGetterProposal(Declaration dec, int offset,
TextChange change) {
super("Convert '" + dec.getName() + "' to getter",
change, new Region(offset, 0));
}
static void addConvertToGetterProposal(IDocument doc,
Collection<ICompletionProposal> proposals, IFile file,
Tree.AttributeDeclaration decNode) {
Value dec = decNode.getDeclarationModel();
final SpecifierOrInitializerExpression sie =
decNode.getSpecifierOrInitializerExpression();
if (dec!=null && sie!=null) {
if (dec.isParameter()) return;
if (!dec.isVariable()) { //TODO: temp restriction, autocreate setter!
TextChange change = new TextFileChange("Convert to Getter", file);
change.setEdit(new MultiTextEdit());
Integer offset = sie.getStartIndex();
String space;
try {
space = doc.getChar(offset-1)==' ' ? "" : " ";
}
catch (BadLocationException e) {
e.printStackTrace();
return;
}
change.addEdit(new ReplaceEdit(offset, 1, "=>"));
// change.addEdit(new ReplaceEdit(offset, 1, space + "{ return" + spaceAfter));
// change.addEdit(new InsertEdit(decNode.getStopIndex()+1, " }"));
proposals.add(new ConvertToGetterProposal(dec,
offset + space.length() + 2 , change));
}
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToGetterProposal.java |
97 | class ConvertToInterpolationProposal extends CorrectionProposal {
private ConvertToInterpolationProposal(String name, Change change) {
super(name, change, null);
}
static void addConvertToInterpolationProposal(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, final Node node, IDocument doc) {
class ConcatenationVisitor extends Visitor {
Tree.SumOp result;
@Override
public void visit(Tree.SumOp that) {
if (that.getStartIndex()<=node.getStartIndex() &&
that.getStopIndex()>=node.getStopIndex()) {
Tree.Term lt = that.getLeftTerm();
Tree.Term rt = that.getRightTerm();
if ((lt instanceof Tree.StringLiteral ||
lt instanceof Tree.StringTemplate) &&
rt instanceof Tree.SumOp &&
(((Tree.SumOp) rt).getRightTerm()
instanceof Tree.StringLiteral ||
((Tree.SumOp) rt).getRightTerm()
instanceof Tree.StringTemplate)) {
result = that;
}
if ((rt instanceof Tree.StringLiteral ||
rt instanceof Tree.StringTemplate) &&
lt instanceof Tree.SumOp &&
(((Tree.SumOp) lt).getLeftTerm()
instanceof Tree.StringLiteral ||
((Tree.SumOp) lt).getLeftTerm()
instanceof Tree.StringTemplate)) {
result = that;
}
}
super.visit(that);
}
}
ConcatenationVisitor tv = new ConcatenationVisitor();
tv.visit(cu);
Tree.SumOp op = tv.result;
if (op!=null) {
TextFileChange change = new TextFileChange("Convert to Interpolation", file);
change.setEdit(new MultiTextEdit());
Tree.Term rt = op.getRightTerm();
Tree.Term lt = op.getLeftTerm();
if (rt instanceof Tree.StringLiteral ||
rt instanceof Tree.StringTemplate) {
change.addEdit(new ReplaceEdit(lt.getStopIndex()+1,
rt.getStartIndex()-lt.getStopIndex(),
"``"));
}
else {
Tree.SumOp rop = (Tree.SumOp) rt;
change.addEdit(new ReplaceEdit(rop.getLeftTerm().getStopIndex()+1,
rop.getRightTerm().getStartIndex()-rop.getLeftTerm().getStopIndex(),
"``"));
if (rop.getLeftTerm() instanceof Tree.QualifiedMemberExpression) {
Tree.QualifiedMemberExpression rlt =
(Tree.QualifiedMemberExpression) rop.getLeftTerm();
if (rlt.getDeclaration().getName().equals("string")) {
int from = rlt.getMemberOperator().getStartIndex();
int to = rlt.getIdentifier().getStartIndex();
change.addEdit(new DeleteEdit(from, to-from));
}
}
}
if (lt instanceof Tree.StringLiteral ||
lt instanceof Tree.StringTemplate) {
change.addEdit(new ReplaceEdit(lt.getStopIndex(),
rt.getStartIndex()-lt.getStopIndex(),
"``"));
}
else {
Tree.SumOp lop = (Tree.SumOp) lt;
change.addEdit(new ReplaceEdit(lop.getLeftTerm().getStopIndex(),
lop.getRightTerm().getStartIndex()-lop.getLeftTerm().getStopIndex(),
"``"));
if (lop.getRightTerm() instanceof Tree.QualifiedMemberExpression) {
Tree.QualifiedMemberExpression lrt =
(Tree.QualifiedMemberExpression) lop.getRightTerm();
if (lrt.getDeclaration().getName().equals("string")) {
int from = lrt.getMemberOperator().getStartIndex();
int to = lrt.getIdentifier().getStopIndex()+1;
change.addEdit(new DeleteEdit(from, to-from));
}
}
}
proposals.add(new ConvertToInterpolationProposal("Convert to string interpolation", change));
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToInterpolationProposal.java |
98 | class ConcatenationVisitor extends Visitor {
Tree.SumOp result;
@Override
public void visit(Tree.SumOp that) {
if (that.getStartIndex()<=node.getStartIndex() &&
that.getStopIndex()>=node.getStopIndex()) {
Tree.Term lt = that.getLeftTerm();
Tree.Term rt = that.getRightTerm();
if ((lt instanceof Tree.StringLiteral ||
lt instanceof Tree.StringTemplate) &&
rt instanceof Tree.SumOp &&
(((Tree.SumOp) rt).getRightTerm()
instanceof Tree.StringLiteral ||
((Tree.SumOp) rt).getRightTerm()
instanceof Tree.StringTemplate)) {
result = that;
}
if ((rt instanceof Tree.StringLiteral ||
rt instanceof Tree.StringTemplate) &&
lt instanceof Tree.SumOp &&
(((Tree.SumOp) lt).getLeftTerm()
instanceof Tree.StringLiteral ||
((Tree.SumOp) lt).getLeftTerm()
instanceof Tree.StringTemplate)) {
result = that;
}
}
super.visit(that);
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToInterpolationProposal.java |
99 | class ConvertToNamedArgumentsProposal extends CorrectionProposal {
public ConvertToNamedArgumentsProposal(int offset, Change change) {
super("Convert to named arguments", change, new Region(offset, 0));
}
public static void addConvertToNamedArgumentsProposal(
Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu,
CeylonEditor editor, int currentOffset) {
Tree.PositionalArgumentList pal =
findPositionalArgumentList(currentOffset, cu);
if (canConvert(pal)) {
final TextChange tc =
new TextFileChange("Convert to Named Arguments", file);
Integer start = pal.getStartIndex();
int length = pal.getStopIndex()-start+1;
StringBuilder result = new StringBuilder();
try {
if (!isWhitespace(getDocument(tc).getChar(start-1))) {
result.append(" ");
}
}
catch (BadLocationException e1) {
e1.printStackTrace();
}
result.append("{ ");
boolean sequencedArgs = false;
List<CommonToken> tokens =
editor.getParseController().getTokens();
final List<Tree.PositionalArgument> args =
pal.getPositionalArguments();
int i=0;
for (Tree.PositionalArgument arg: args) {
Parameter param = arg.getParameter();
if (param==null) {
return;
}
if (param.isSequenced()) {
if (sequencedArgs) {
result.append(", ");
}
else {
//TODO: if we _only_ have a single spread
// argument we don't need to wrap it
// in a sequence, we only need to
// get rid of the * operator
result.append(param.getName())
.append(" = [");
sequencedArgs=true;
}
result.append(Nodes.toString(arg, tokens));
}
else {
if (sequencedArgs) {
return;
}
if (arg instanceof Tree.ListedArgument) {
final Expression e =
((Tree.ListedArgument) arg).getExpression();
if (e!=null) {
Tree.Term term = e.getTerm();
if (term instanceof Tree.FunctionArgument) {
Tree.FunctionArgument fa =
(Tree.FunctionArgument) term;
if (fa.getType() instanceof Tree.VoidModifier) {
result.append("void ");
}
else {
result.append("function ");
}
result.append(param.getName());
Unit unit = cu.getUnit();
Nodes.appendParameters(result, fa, unit, tokens);
if (fa.getBlock()!=null) {
result.append(" ")
.append(Nodes.toString(fa.getBlock(), tokens))
.append(" ");
}
else {
result.append(" => ");
}
if (fa.getExpression()!=null) {
result.append(Nodes.toString(fa.getExpression(), tokens))
.append("; ");
}
continue;
}
if (++i==args.size() &&
term instanceof Tree.SequenceEnumeration) {
Tree.SequenceEnumeration se =
(Tree.SequenceEnumeration) term;
Tree.SequencedArgument sa = se.getSequencedArgument();
if (sa!=null) {
result.append(Nodes.toString(sa, tokens))
.append(" ");
}
continue;
}
}
}
result.append(param.getName())
.append(" = ")
.append(Nodes.toString(arg, tokens))
.append("; ");
}
}
if (sequencedArgs) {
result.append("]; ");
}
result.append("}");
tc.setEdit(new ReplaceEdit(start, length, result.toString()));
int offset = start+result.toString().length();
proposals.add(new ConvertToNamedArgumentsProposal(offset, tc));
}
}
public static boolean canConvert(Tree.PositionalArgumentList pal) {
if (pal==null) {
return false;
}
else {
//if it is an indirect invocations, or an
//invocation of an overloaded Java method
//or constructor, we can't call it using
//named arguments!
for (Tree.PositionalArgument arg: pal.getPositionalArguments()) {
Parameter param = arg.getParameter();
if (param==null) return false;
}
return true;
}
}
private static Tree.PositionalArgumentList findPositionalArgumentList(
int currentOffset, Tree.CompilationUnit cu) {
FindPositionalArgumentsVisitor fpav =
new FindPositionalArgumentsVisitor(currentOffset);
fpav.visit(cu);
return fpav.getArgumentList();
}
private static class FindPositionalArgumentsVisitor
extends Visitor
implements NaturalVisitor {
Tree.PositionalArgumentList argumentList;
int offset;
private Tree.PositionalArgumentList getArgumentList() {
return argumentList;
}
private FindPositionalArgumentsVisitor(int offset) {
this.offset = offset;
}
@Override
public void visit(Tree.ExtendedType that) {
//don't add proposals for extends clause
}
@Override
public void visit(Tree.PositionalArgumentList that) {
Integer start = that.getStartIndex();
Integer stop = that.getStopIndex();
if (start!=null && offset>=start &&
stop!=null && offset<=stop+1) {
argumentList = that;
}
super.visit(that);
}
}
} | false | plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToNamedArgumentsProposal.java |