Search in sources :

Example 11 with ParameterParser

use of org.eclipse.xpect.parameter.ParameterParser in project n4js by eclipse.

the class FlowgraphsXpectMethod method allPaths.

/**
 * This xpect method can evaluate all paths from a given start code element. If no start code element is specified,
 * the first code element of the containing function.
 */
@ParameterParser(syntax = "('from' arg1=OFFSET)? ('direction' arg2=STRING)? ('pleaseNeverUseThisParameterSinceItExistsOnlyToGetAReferenceOffset' arg3=OFFSET)?")
@Xpect
public void allPaths(@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation, IEObjectCoveringRegion offset, String directionName, IEObjectCoveringRegion referenceOffset) {
    AllBranchPrintVisitor appw = performBranchAnalysis(offset, directionName, referenceOffset);
    List<String> pathStrings = appw.getPathStrings();
    expectation.assertEquals(pathStrings);
}
Also used : AllBranchPrintVisitor(org.eclipse.n4js.flowgraphs.analysers.AllBranchPrintVisitor) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 12 with ParameterParser

use of org.eclipse.xpect.parameter.ParameterParser in project n4js by eclipse.

the class LinkingXpectMethod method linkedPathname.

/**
 * Similar to {@link #linkedName(IStringExpectation, ICrossEReferenceAndEObject)} but concatenating the fully
 * qualified name again instead of using the qualified name provider, as the latter may not create a valid name for
 * non-globally available elements.
 * <p>
 * The qualified name created by retrieving all "name" properties of the target and its containers, using '/' as
 * separator.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void linkedPathname(@StringExpectation IStringExpectation expectation, ICrossEReferenceAndEObject arg1) {
    EObject targetObject = (EObject) arg1.getEObject().eGet(arg1.getCrossEReference());
    if (targetObject == null) {
        Assert.fail("Reference is null");
        // to avoid warnings in the following
        return;
    }
    if (targetObject.eIsProxy())
        Assert.fail("Reference is a Proxy: " + ((InternalEObject) targetObject).eProxyURI());
    Resource targetResource = targetObject.eResource();
    if (targetResource instanceof TypeResource)
        targetResource = arg1.getEObject().eResource();
    if (!(targetResource instanceof XtextResource))
        Assert.fail("Referenced EObject is not in an XtextResource.");
    Deque<String> segments = new ArrayDeque<>();
    do {
        EStructuralFeature nameFeature = targetObject.eClass().getEStructuralFeature("name");
        if (nameFeature != null) {
            Object obj = targetObject.eGet(nameFeature);
            if (obj instanceof String) {
                segments.push((String) obj);
            }
        } else {
            if (targetObject instanceof NamedElement) {
                segments.push(((NamedElement) targetObject).getName());
            }
        }
        targetObject = targetObject.eContainer();
    } while (targetObject != null);
    String pathname = Joiner.on('/').join(segments);
    expectation.assertEquals(pathname);
}
Also used : TypeResource(org.eclipse.xtext.common.types.access.TypeResource) EObject(org.eclipse.emf.ecore.EObject) InternalEObject(org.eclipse.emf.ecore.InternalEObject) ICrossEReferenceAndEObject(org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject) XtextResource(org.eclipse.xtext.resource.XtextResource) Resource(org.eclipse.emf.ecore.resource.Resource) TypeResource(org.eclipse.xtext.common.types.access.TypeResource) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) XtextResource(org.eclipse.xtext.resource.XtextResource) EObject(org.eclipse.emf.ecore.EObject) InternalEObject(org.eclipse.emf.ecore.InternalEObject) ICrossEReferenceAndEObject(org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject) NamedElement(org.eclipse.n4js.n4JS.NamedElement) ArrayDeque(java.util.ArrayDeque) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 13 with ParameterParser

use of org.eclipse.xpect.parameter.ParameterParser in project n4js by eclipse.

the class FindReferencesXpectMethod method findReferences.

/**
 * This Xpect methods compares all computed references at a given EObject to the expected references. The expected
 * references include the line number.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void findReferences(@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation, IEObjectCoveringRegion offset) {
    // When you write Xpect test methods, ALWAYS retrieve eObject via IEObjectCoveringRegion to get the right
    // eObject!
    // Do NOT use EObject arg1!
    EObject context = offset.getEObject();
    EObject argEObj = offsetHelper.resolveElementAt((XtextResource) context.eResource(), offset.getOffset());
    // If not a cross-reference element, use context instead
    if (argEObj == null)
        argEObj = context;
    EObject eObj = argEObj;
    if (argEObj instanceof ParameterizedTypeRef)
        eObj = ((ParameterizedTypeRef) argEObj).getDeclaredType();
    List<EObject> refs = findReferenceHelper.findReferences(eObj);
    ArrayList<String> result = Lists.newArrayList();
    for (EObject ref : refs) {
        if (ref instanceof PropertyNameOwner)
            ref = ((PropertyNameOwner) ref).getDeclaredName();
        ICompositeNode srcNode = NodeModelUtils.getNode(ref);
        int line = srcNode.getStartLine();
        String moduleName;
        if (ref.eResource() instanceof N4JSResource) {
            N4JSResource n4jsResource = (N4JSResource) ref.eResource();
            moduleName = n4jsResource.getModule().getQualifiedName();
        } else {
            moduleName = "(unknown resource)";
        }
        String text = NodeModelUtils.getTokenText(srcNode);
        if (ref instanceof GenericDeclaration)
            text = ((GenericDeclaration) ref).getDefinedType().getName();
        String resultText = moduleName + " - " + text + " - " + line;
        result.add(resultText);
    }
    expectation.assertEquals(result);
}
Also used : ParameterizedTypeRef(org.eclipse.n4js.ts.typeRefs.ParameterizedTypeRef) PropertyNameOwner(org.eclipse.n4js.n4JS.PropertyNameOwner) EObject(org.eclipse.emf.ecore.EObject) N4JSResource(org.eclipse.n4js.resource.N4JSResource) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) GenericDeclaration(org.eclipse.n4js.n4JS.GenericDeclaration) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 14 with ParameterParser

use of org.eclipse.xpect.parameter.ParameterParser in project n4js by eclipse.

the class OrganizeImportXpectMethod method organizeImports.

/**
 * Give the result as a multiline diff. If cancellation due to multiple possible resolution is expected, provide the
 * expected Exception with 'XPECT organizeImports ambiguous "Exception-Message" -->'.
 *
 * If the parameter is not provided, always the first computed solution in the list will be taken
 *
 * @param ambiguous
 *            - String Expectation in {@link BreakException}
 */
@ParameterParser(syntax = "('ambiguous' arg0=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void organizeImports(// arg0
String ambiguous, @StringDiffExpectation(whitespaceSensitive = false, allowSingleSegmentDiff = false, allowSingleLineDiff = false) IStringDiffExpectation expectation, @ThisResource XtextResource resource) throws Exception {
    logger.info("organize imports ...");
    boolean bAmbiguityCheck = ambiguous != null && ambiguous.trim().length() > 0;
    Interaction iaMode = bAmbiguityCheck ? Interaction.breakBuild : Interaction.takeFirst;
    try {
        if (expectation == null) /* || expectation.isEmpty() */
        {
            // Cannot access the region which could be asked for it's length.
            throw new AssertionFailedError("The test is missing a diff: // XPECT organizeImports --> [old string replaced|new string expected] ");
        }
        // capture text for comparison:
        String beforeApplication = resource.getParseResult().getRootNode().getText();
        N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
        IXtextDocument xtextDoc = fixture.getDocument(resource, beforeApplication);
        // in case of cross-file hyperlinks, we have to make sure the target resources are fully resolved
        final ResourceSet resSet = resource.getResourceSet();
        for (Resource currRes : new ArrayList<>(resSet.getResources())) {
            N4JSResource.postProcess(currRes);
        }
        // Calling organize imports
        Display.getDefault().syncExec(() -> imortsOrganizer.unsafeOrganizeDocument(xtextDoc, iaMode));
        if (bAmbiguityCheck) {
            // should fail if here
            assertEquals("Expected ambiguous resolution to break the organize import command.", ambiguous, "");
        }
        // checking that no errors are left.
        String textAfterApplication = xtextDoc.get();
        // compare with expectation, it's a multiline-diff expectation.
        String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
        String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);
        expectation.assertDiffEquals(before, after);
    } catch (Exception exc) {
        if (exc instanceof RuntimeException && exc.getCause() instanceof BreakException) {
            String breakMessage = exc.getCause().getMessage();
            assertEquals(ambiguous, breakMessage);
        } else {
            throw exc;
        }
    }
}
Also used : Interaction(org.eclipse.n4js.ui.organize.imports.Interaction) ThisResource(org.eclipse.xpect.xtext.lib.setup.ThisResource) XtextResource(org.eclipse.xtext.resource.XtextResource) N4JSResource(org.eclipse.n4js.resource.N4JSResource) Resource(org.eclipse.emf.ecore.resource.Resource) ArrayList(java.util.ArrayList) BreakException(org.eclipse.n4js.ui.organize.imports.BreakException) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) AssertionFailedError(junit.framework.AssertionFailedError) BreakException(org.eclipse.n4js.ui.organize.imports.BreakException) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 15 with ParameterParser

use of org.eclipse.xpect.parameter.ParameterParser in project n4js by eclipse.

the class ScopeXpectMethod method binding.

/**
 * Checks that a given element is bound to something identified by (simple) qualified name. The check is designed as
 * simple as possible. That is, simply the next following expression is tested, and within that we expect a property
 * access or a direct identifiable element. The compared name is the simple qualified name, that is container (type)
 * followed by elements name, without URIs of modules etc.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public // 
void binding(// 
@CommaSeparatedValuesExpectation ICommaSeparatedValuesExpectation expectation, // 
ICrossEReferenceAndEObject arg1) {
    EObject eobj = arg1.getEObject();
    ParameterizedPropertyAccessExpression ppae = EcoreUtil2.getContainerOfType(eobj, ParameterizedPropertyAccessExpression.class);
    IdentifiableElement element;
    if (ppae != null) {
        element = ppae.getProperty();
    } else if (eobj instanceof IdentifiableElement) {
        element = (IdentifiableElement) eobj;
    } else {
        throw new IllegalArgumentException("Cannot check binding for " + (eobj == null ? "null" : eobj.eClass().getName()));
    }
    String container = "";
    if (element instanceof TMember) {
        container = ((TMember) element).getContainingType().getName() + ".";
    }
    final String qn = container + element.getName();
    // URI uri = eobj == null ? null : eobj.eResource() == null ? null : eobj.eResource().getURI();
    expectation.assertEquals(Collections.singleton(qn));
}
Also used : ParameterizedPropertyAccessExpression(org.eclipse.n4js.n4JS.ParameterizedPropertyAccessExpression) EObject(org.eclipse.emf.ecore.EObject) ICrossEReferenceAndEObject(org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject) IdentifiableElement(org.eclipse.n4js.ts.types.IdentifiableElement) TMember(org.eclipse.n4js.ts.types.TMember) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Aggregations

ParameterParser (org.eclipse.xpect.parameter.ParameterParser)30 Xpect (org.eclipse.xpect.runner.Xpect)30 EObject (org.eclipse.emf.ecore.EObject)11 ControlFlowElement (org.eclipse.n4js.n4JS.ControlFlowElement)9 LinkedList (java.util.LinkedList)6 IXtextDocument (org.eclipse.xtext.ui.editor.model.IXtextDocument)6 ConsumedIssues (org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues)5 ICrossEReferenceAndEObject (org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject)5 XtextResource (org.eclipse.xtext.resource.XtextResource)5 URI (org.eclipse.emf.common.util.URI)4 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)4 List (java.util.List)3 Resource (org.eclipse.emf.ecore.resource.Resource)3 N4JSResource (org.eclipse.n4js.resource.N4JSResource)3 ThisResource (org.eclipse.xpect.xtext.lib.setup.ThisResource)3 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)3 Lists (com.google.common.collect.Lists)2 Inject (com.google.inject.Inject)2 ArrayList (java.util.ArrayList)2 Optional (java.util.Optional)2