Search code examples
importxtextcross-reference

Xtext: Cross-reference to other files works, but I can't access the EObject


This is my grammar:

A: field=[B]
B: C | D

The cross-reference works very well both when C/D sits in the same file and also when C/D sits in another file (using import).

The problem is with my function that gets Model (EObject, AST's root) as an input and extracts the C/D EObject.

When C/D sits in the same file, I can do something like this to get the C/D EObjects:

A a = ...
if (a.getField() instanceof C)
{
C c = (C)a.getField();
//do something with c
}
else if (a.getField() instanceof D)
{
D d = (D)a.getField();
//do something with d
}

However, when C/D sits in another file, the cross-reference works but the above doesn't work: a.getField() isn't null but it's also not an instance of C and not an instance of D.

Giving a model (that imports many other models), how can I access C/D that sits in other model?

UPDATE

This is my code to obtain the resource:

XtextResourceSetProvider rsp = (XtextResourceSetProvider)IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(uri).get(IResourceSetProvider.class);      

XtextResourceSet rs = (XtextResourceSet) rsp.get(project);

Resource r = rs.getResource(uri, true);

Solution

  • looks overcomplicated what you are doing

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    
    IFile file = root.getFile(new Path(inputFilePath));
    URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
    IProject project = file.getProject();
    
    XtextResourceSetProvider rsp = (XtextResourceSetProvider) IResourceServiceProvider.Registry.INSTANCE
        .getResourceServiceProvider(uri)
        .get(IResourceSetProvider.class);
    XtextResourceSet rs = (XtextResourceSet) rsp.get(project);
    
    Resource r = rs.getResource(uri, true);
    Model m = (Model) r.getContents().get(0);