CDT: How can I analyze the AST of a c/c++ file which are not linked to some project in an Eclipse workspace - eclipse-plugin

In my source code analysis Eclipse RCP project, I want to getAST to analyze the AST of some c/c++ files, which is neither a source file of a project within an eclipse workspace, nor a link resources of a project within an eclipse workspace. Basically, I do not have any workingspaces in my RCP application. Any suggestions would be appreciated!
cheers,

You need to programmatically create new project from folder of sources (make sure you have some basic .cproject file inside with correct source root):
IWorkspace workspace = ResourcesPlugin.getWorkspace();
project = workspace.getRoot().getProject("project");
if (!project.exists()) {
IProjectDescription description = workspace.newProjectDescription("project");
CCorePlugin.getDefault().createCDTProject(description, project, null);
} else {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
}
After you can use AST:
ITranslationUnit translationUnit = (ITranslationUnit) CoreModel.getDefault().create(file);
IASTTranslationUnit ast = translationUnit.getAST();

I found a simpler way if you happen to have that file in the editor, then you can use getEditorInput method on the editor part to get ITranslationUnit, i.e.:
// here is how you can get the active editor
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
IEditorPart editorPart = window.getActivePage().getActiveEditor();
// for an external file the editor input will be of type ITranslationUnitEditorInput
IEditorInput input = editorPart.getEditorInput();
if (input instanceof ITranslationUnitEditorInput) {
ITranslationUnit externalTU = ((ITranslationUnitEditorInput) input).getTranslationUnit();
}

Related

How to create a file in the resources folder in Kotlin, Gradle

In a completely fresh project, I want to create a single file myFile.json inside the src/main/resources/ folder at run time.
For reading a file, I need to do some config in the build.gradle.kts file, but I can't find anything on what to do for creating a file.
Assuming the directory src/main/resources/ exists:
val f = File("src/main/resources/myFile.json")
withContext(Dispatchers.IO) {
f.createNewFile() // This is the answer to the question
f.printWriter().use { out ->
out.println("{}")
}
}
#Endzeit has asked what have you tried so far. Please share the code.
Like #cyberbrain says - are you sure you want to write to resources folder?
Here is code that writes back to where the source resources folder is:
fun main(args: Array<String>) {
// Let's assume you want your project to be portable, so you don't
// want to use absolute file paths.
// Find out where your IDE will launch the project from. Normally this is
// the root folder of the whole project. Find out with this: the `canonicalPath` will help:
val workingFolder = File(".")
println("workingFolder=${workingFolder.canonicalPath}")
// Define the folder you want to write in to
// this will vary especially if you have a nested project structure
// IntelliJ under the Edit > Copy Path menu option will help you find the resources
// relative location
val parentFolder = File("src/main/resources")
println("parentFolder=${parentFolder.canonicalPath}")
require(parentFolder.exists())
val outFile = File(parentFolder, "test.txt")
outFile.printWriter(StandardCharsets.UTF_8).use {
it.println("Hello world")
}
println("Wrote to ${outFile.canonicalPath}")
}

Can the Image path for the AddImage method in MigraDoc be used for the Visual Studio project subfolders?

The following example shows a very simple construction for creating a PDF with MigraDoc. The most parts of it are taken from the examples provided in the MigraDoc - Wiki documentation.
I have commented all the most few steps for the job. The path for the "AddImage" points to the subfolder "Images" which is a subfolder of the folder "Resources" created in the root of the console application of a Visual Studio (VS) project.
The most recent MigraDoc library is added to the VS - project via "NuGet" just yesterday.
The application creates the PDF output file unfortunately without the provided image file, if it is used in another machine. Because the execution file has then no access to the subfolders created in VS project.
Is there any solution to this problem?
public class Program
{
static void Main(string[] args)
{
// Create a MigraDoc document
var document = new Document();
// Add a section the document
var section = document.AddSection();
// .....
/*
------------------------------- NOTE -------------------------------
The path "../../Resources/Images/MigraDoc.png" is valid only for the developer machine!
A copy of the content of the "Debug" or "Release" folder any where else does not show the image in the output PDF.
Because such a copy has no access to the subfolder "/Resources/Images" of the Visual Studio project on the developer machine.
*/
section.Headers.Primary.AddImage("../../Resources/Images/MigraDoc.png");
// Create a renderer for PDF that uses Unicode font encoding.
var pdfRenderer = new PdfDocumentRenderer(true);
// Set the MigraDoc document.
pdfRenderer.Document = document;
// Create the PDF document.
pdfRenderer.RenderDocument();
// Save the PDF document...
var filename = "Invoice.pdf";
// Create the output directory
Directory.CreateDirectory("PDF");
// Create the ouptput file path
var savePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\PDF\\" + filename;
// Delete the output file if it already exists
if (File.Exists(savePath))
File.Delete(savePath);
// Save the output file
pdfRenderer.Save(savePath);
// Start a the default PDF viewer from the operation system
Process.Start(savePath);
}
}
A path beginning with ..\..\ relies on the current directory. For a portable solution, include the images you need in your deployment.
Recommended usage: The MigraDoc Document class has an ImagePath property. If your installation folder has an Images folder, just locate your .EXE file and set the ImagePath property accordingly.

How can I retrieve the contents a multi page editor plugin when selecting "Run as" in Eclipse Plugin Development?

An eclipse plugin is needed to allow users to input a script and run that script through the IDE. For this I've implemented an eclipse plugin, using the multi-page editor template. I added the extension org.eclipse.debug.ui.launchShortcuts and provided a reference to my implementation of the interface org.eclipse.debug.ui.ILaunchShortcut. This interface requires to provide an implementation of these methods:
public void launch(final ISelection selection, final String mode);
public void launch(final IEditorPart editor, final String mode);
When the user - e.g. me - right clicks the file from the project explorer, selects "run as" and selects the launcher I provided, then the implementation of this launch method is hit. The first method - i.e. the ISelection version - is hit when selecting the file from the project explorer. The second method - i.e. the IEditorPart version - is hit when right clicking the editor zone and selecting the launcher through the "run as" option from the context menu.
I now need to find out how I can retrieve the contents of that editor page. In the first method I believe I could retrieve the filename with the below code:
IFile file = (IFile) ((IStructuredSelection) selection).getFirstElement();
String path = file.getFullPath().makeAbsolute().toString();
However, the that path is relevant with respect to the root of the project. I don't know how to retrieve the path of the root of the project.
The implementation of the second method is more problematic given I don't know how to find the path based on the IEditorPart.
I hope you can help. Many thanks
If you are asking how to get the file that the editor is current editing you can use something like:
IPath filepath = null;
IEditorInput input = editor.getEditorInput();
IFile file = input.getAdapter(IFile.class);
if (file != null) {
filepath = file.getFullPath();
}
if (filepath == null) {
ILocationProvider locationProvider = input.getAdapter(ILocationProvider.class);
if (locationProvider != null) {
filepath = locationProvider.getPath(input);
}
}
which tries to get the IFile frpm the editor directly and if that fails tries for a location provider.

Is there a eventlistener in eclipse core for "OnFileOpen"?

I am trying to write a plugin which parses the source code of any opened (java) file.
All I have found so far is IResourceChangeListener, but what I need is a Listener for some kind of "onRecourceOpenedEvent".
Does something like that exist?
The nearest you can get to this is to use an IPartListener to list to part events:
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().addPartListener(listener);
In the listener the partOpened tells you about a new part opening:
public void partOpened(IWorkbenchPart part) {
// Is this an editor
if (part instanceof IEditorPart) {
IEditorPart editor = (IEditorPart)part;
// Get file being edited
IFile file = (IFile)editor.getAdapter(IFile.class);
// TODO file is the current file - may be null
}
}

Get project in Eclipse plugin without having an open editor

In a Eclipse plugin it's easy to get the current project(IProject) if there's an editor opened, you just need to use this snippet:
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
IFileEditorInput input = (IFileEditorInput)editor.getEditorInput();
IFile file = input.getFile();
IProject project = file.getProject();
But, is there a way to get the project if I don't have any kind of file opened in the editor?, i.e: imagine that you have a plugin that adds an option when you right click a project, and if you click this option a dialog window is launched, how can I print the project name in this dialog?
For menu items and the like which use a 'command' with a 'handler' you can use code in the handler which is something like:
public class CommandHandler extends AbstractHandler
{
#Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
ISelection sel = HandlerUtil.getCurrentSelection(event);
if (sel instanceof IStructuredSelection)
{
Object selected = ((IStructuredSelection)sel).getFirstElement();
IResource resource = (IResource)Platform.getAdapterManager().getAdapter(selected, IResource.class);
if (resource != null)
{
IProject project = resource.getProject();
...
}
}
return null;
}
}
What do you mean by "The current project"? Getting a specific project will always require some way of uniquely identifying that specific project.
If by current project you mean that the project is open, then that's not a good criterion for uniqueness (in the general case), since multiple projects can be open at the same time.
A guarantee of uniquely defining a project is by getting a reference to a resource contained by that project. For example, this can be done through the editor input, as you state, or trough a selection, as greg pointed out.
If you have the project's name, then you can use IWorkspaceRoot#getProject(String), but I assume that's not the case. Still, for completeness:
ResourcesPlugin.getWorkspace().getRoot().getProject("MyProject");
You could also get a list of all projects, and iterate over that list to check for a property that you know the project has (or the projects have). See the example below. Of course, this again doesn't guarantee uniqueness in the general case, since there can be multiple projects that satisfy the criteria. That's why I used Lists in the example.
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
List<IProject> openProjects = new ArrayList<>();
List<IProject> myNatureProjects = new ArrayList<>();
for(IProject project : projects)
{
if(project.isOpen())
openProjects.add(project);
if(project.hasNature("MyNatureId")
myNatureProjects.add(project);
}