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

Dataset Card for "ceylon_ide_eclipse_1_1_0"

More Information needed

Downloads last month
1
Edit dataset card