Search in sources :

Example 16 with ParameterParser

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

the class ScopeXpectMethod method scope.

@Override
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public // 
void scope(// 
@CommaSeparatedValuesExpectation ICommaSeparatedValuesExpectation expectation, // 
ICrossEReferenceAndEObject arg1) {
    EObject eobj = arg1.getEObject();
    IScope scope = scopeProvider.getScope(eobj, arg1.getCrossEReference());
    URI uri = eobj == null ? null : eobj.eResource() == null ? null : eobj.eResource().getURI();
    expectation.assertEquals(new ScopeAllElements(scope), new IsInScopeWithOptionalPositionPredicate(converter, uri, false, scope));
}
Also used : EObject(org.eclipse.emf.ecore.EObject) ICrossEReferenceAndEObject(org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject) IScope(org.eclipse.xtext.scoping.IScope) URI(org.eclipse.emf.common.util.URI) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 17 with ParameterParser

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

the class N4MFFormatterTest method formatted.

/**
 * @param expectation
 *            the expected formatted code
 * @param resource
 *            the Xtext resource to be formatted
 * @param offset
 *            the optional start offset from where formatting should be applied
 * @param to
 *            the optional to offset to which formatting should be applied
 */
@ParameterParser(syntax = "('from' arg2=OFFSET 'to' arg3=OFFSET)?")
@Xpect
public void formatted(@StringExpectation(whitespaceSensitive = true) IStringExpectation expectation, @ThisResource XtextResource resource, int offset, int to) {
    ICompositeNode rootNode = resource.getParseResult().getRootNode();
    FormatterRequest request = requestProvider.get().setTextRegionAccess(regionAccessBuilderProvider.get().forNodeModel(resource).create());
    int totalLength = rootNode.getTotalLength();
    if (offset >= 0 && to > offset) {
        request.setRegions(Collections.singleton(new TextRegion(offset, to - offset)));
    } else {
        request.setRegions(Collections.singleton(new TextRegion(offset, totalLength - offset)));
    }
    List<ITextReplacement> replacements = formatter.format(request);
    String formatted = request.getTextRegionAccess().getRewriter().renderToString(replacements);
    if (offset >= 0 && to > offset) {
        formatted = formatted.substring(offset, formatted.length() - (totalLength - to));
    } else {
        formatted = formatted.substring(offset);
    }
    if (isUnixEnding()) {
        formatted = formatted.replaceAll("\r\n", "\n");
    } else if (isWindowsEnding()) {
        if (!rootNode.getText().contains("\r\n")) {
            formatted = formatted.replaceAll("\r\n", "\n");
        } else {
            formatted = formatted.replaceAll("(!\r)\n", "\r\n");
        }
    }
    expectation.assertEquals(formatted);
}
Also used : TextRegion(org.eclipse.xtext.util.TextRegion) ITextReplacement(org.eclipse.xtext.formatting2.regionaccess.ITextReplacement) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) FormatterRequest(org.eclipse.xtext.formatting2.FormatterRequest) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 18 with ParameterParser

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

the class ProposalXpectMethod method proposalChange.

// @formatter:off
/**
 * Test the application of the given content assist entry. After applying the content assist there should be the
 * expected diff produced when comparing the document before and after applying the content assist.
 *
 * The diff has the following semantics:
 *
 * "  ": (whitespace) nothing changed
 * "+ ": line was added
 * "- ": line was deleted
 * "| ": line was modified, displayed as [oldText|newText]
 *
 * If the given expected content assist entry cannot be found, an error message is inserted at the offset resulting
 * in expectation mismatch and so also to a failing test.
 *
 * Also clf.
 * https://github.com/meysholdt/Xpect/tree/master/org.eclipse.xtext.example.domainmodel.xpect.tests/src/org
 * /eclipse/xtext/example/domainmodel/xpect/tests/modify for some more examples.
 *
 * /\* XPECT proposalChange 'methodA2' at 'methodA' ---
 *   (...)
 *  }
 * }
 * var A a = new A();
 * |a.[methodA|methodA2methodA]
 * --- *\/
 *
 * Please note, that the comparison always contains also some lines around the line that contains the diff.
 * Xpect currently doesn't allow to configure the number of those lines.
 *
 * @param expectation
 *            the expected diff comparing the document before and after applying the content assist
 * @param resource
 *            the resource under test
 * @param arg2
 *            the offset of where to invoke content assist (note: it must be named arg2 as Xpect injects the
 *            parameter values by position)
 * @param arg3
 *            the content assist entry to select
 * @throws Exception
 *             some exception
 */
// @formatter:on
@ParameterParser(syntax = "(arg3=STRING 'at' arg2=STRING)?")
@Xpect
public void proposalChange(@StringDiffExpectation IStringDiffExpectation expectation, @ThisResource XtextResource resource, /* @ThisOffset int */
RegionWithCursor arg2, String arg3) throws Exception {
    // val int offset = arg2;
    RegionWithCursor offset = arg2;
    String text = arg3;
    // println("proposal change with offset="+arg2+" selection="+arg3)
    N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
    ICompletionProposal proposal = exactlyMatchingProposal(offset, fixture, text);
    String before = resource.getParseResult().getRootNode().getText();
    if (proposal != null) {
        IXtextDocument document = fixture.getDocument(XtextResourceCleanUtil.cleanXtextResource(resource), before);
        String after = applyProposal(proposal, document);
        before = XpectCommentRemovalUtil.removeAllXpectComments(before);
        after = XpectCommentRemovalUtil.removeAllXpectComments(after);
        expectation.assertDiffEquals(before, after);
    }
}
Also used : RegionWithCursor(org.eclipse.n4js.xpect.ui.methods.contentassist.RegionWithCursor) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 19 with ParameterParser

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

the class ContentAssistXpectMethod method contentAssistList.

/*-
	 contentAssistList              at ’a.<|>methodA’       display    ’methodA2’           --> ’methodA2(): any - A’
	 contentAssistList              at 'a.<|>methodA'       proposals                       --> <$objectProposals>, methodA2
	 contentAssistList              at 'a.<|>methodA'       proposals                       --> <$objectProposals>, methodA2
	 contentAssistList              at 'a.<|>methodA'       proposals                       --> methodA, methodA2
	 contentAssistList              at 'a.<|>methodA'       proposals             contains  --> methodA2
	 contentAssistList              at 'a.<|>methodA'       proposals             exactly   --> methodA, methodA2
	 contentAssistList              at 'a.<|>methodA'       proposals             not       --> methodB
	 contentAssistList              at 'a.<|>methodA'       proposals             ordered   --> methodA, methodA2
	 contentAssistList              at 'a.<|>methodA'       proposals             unordered --> methodA2, methodA
	 contentAssistList              at 'a.<|>methodA'       display   'methodA2'            --> 'methodA2(): any - A'
	 contentAssistList kind 'smart' at 'a.<|>methodA'       display   'methodA2'            --> 'methodA2(): any - A'
	
	                    kind        offset                  checkType  selected    mode
	                    arg4        arg2                    arg3       arg5        arg6
	 */
/**
 * Compares the expected list of expected display strings with the actual computed one by the proposal provider.
 *
 * @param expect
 *            injected from right hand side - a list expected display strings
 * @param resource
 *            injected - the resource under test
 * @param offset
 *            arg2 - the offset of where to invoke content assist given as string matching next line with cursor
 *            position
 * @param checkType
 *            arg3 - one of {proposals | display }
 * @param kind
 *            arg4 - contentAssist - cycling: current kind like 'n4js'(default) or 'recommenders'
 * @param selected
 *            arg5 - chosen selection form the proposal list
 * @param mode
 *            arg6 - depending on checkTye: apply->{insert(default)|override}, proposals->{contains,
 *            exactly(default), not}
 * @param orderMod
 *            arg7 - for proposal-modes contains/exactly there are two mode available{ordered, unordered(default)}
 * @throws Exception
 *             some exception
 */
@Xpect
@ParameterParser(syntax = "( ('kind' arg4=STRING)? 'at' (arg2=STRING (arg3=ID  (arg5=STRING)?  (arg6=ID (arg7=ID)? )? )? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void contentAssistList(// arg0
@CommaSeparatedValuesExpectation(quoted = true) ICommaSeparatedValuesExpectation expect, // arg1
@ThisResource XtextResource resource, // arg2 //@ThisOffset is obsolete
RegionWithCursor offset, // arg3
String checkType, // arg4
String kind, // arg5
String selected, // arg6
String mode, // arg7
String orderMod, ISetupInitializer<XpEnvironmentData> uiTestRunInit) throws Exception {
    XpEnvironmentData xpEnvData = new XpEnvironmentData();
    uiTestRunInit.initialize(xpEnvData);
    xpEnvData.setResourceUnderTest(resource);
    // Expansion of Variables. This changes the original expectation:
    CommaSeparatedValuesExpectationImpl csvE = (CommaSeparatedValuesExpectationImpl) expect;
    Pair<CommaSeparatedValuesExpectationImpl, CharSequence> exptectationAndText = expandVariables(csvE, xpEnvData);
    CommaSeparatedValuesExpectationImpl expectation = exptectationAndText.getKey();
    CharSequence expectedText = exptectationAndText.getValue();
    // System.out.println("---|" + expectedText + "|---");
    List<String> proposals = getProposalDisplayStrings(resource, offset, kind);
    if (("display").equals(checkType)) {
        // TODO check original code, seems like errors wehn porting
        // expectation exactly one string:
        // pick the proposal, test that only one is Picked && verify with expectation.
        List<String> candidates = proposals.stream().filter(p -> p.contains(selected)).collect(Collectors.toList());
        if (candidates.size() > 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("more then one proposal matches the selection '").append(selected).append("' matches:[");
            candidates.forEach(m -> sb.append(m).append(","));
            sb.append("]");
            throw new RuntimeException(sb.toString());
        }
        if (candidates.size() == 0) {
            StringBuilder sb = new StringBuilder();
            sb.append("nothing matches the selection '").append(selected).append("' available are [");
            candidates.forEach(m -> sb.append(m).append(","));
            sb.append("]");
            throw new RuntimeException(sb.toString());
        }
        // exactly one:
        expectation.assertEquals(candidates);
        return;
    } else if ("proposals".equals(checkType)) {
        // order-mode, default is 'unordered'
        boolean ordered = ("ordered" == orderMod || "ordered" == mode);
        if (mode == null) {
            if (ordered) {
                assertExactlyOrdered(proposals, separateOnCommaAndQuote(expectedText), expectation);
            } else {
                assertExactly(proposals, separateOnCommaAndQuote(expectedText), expectation);
            }
            return;
        }
        switch(mode) {
            case "":
            // just in case mode is default, then orderMod gets assigned to mode
            case "ordered":
            // just in case mode is default, then orderMod gets assigned to mode
            case "unordered":
            case // default case.
            "exactly":
                if (ordered) {
                    assertExactlyOrdered(proposals, separateOnCommaAndQuote(expectedText), expectation);
                } else {
                    assertExactly(proposals, separateOnCommaAndQuote(expectedText), expectation);
                }
                return;
            case "contains":
                {
                    if (ordered) {
                        assertContainingMatchAllOrdered(proposals, separateOnCommaAndQuote(expectedText), expectation);
                    } else {
                        assertContainingMatchAll(proposals, separateOnCommaAndQuote(expectedText), expectation);
                    }
                    return;
                }
            case "not":
                // ordered / unordered doesn't apply here
                assertNoMatch(proposals, separateOnCommaAndQuote(expectedText), expectation);
                return;
            default:
                throw new RuntimeException("unrecognized mode for proposal-test : '" + mode + "'");
        }
    } else {
        throw new UnsupportedOperationException("unrecognized checktype: '" + checkType + "'");
    }
}
Also used : VarDef(org.eclipse.n4js.xpect.config.VarDef) Arrays(java.util.Arrays) IExpectationRegion(org.eclipse.xpect.expectation.IExpectationRegion) ISetupInitializer(org.eclipse.xpect.setup.ISetupInitializer) ThisResource(org.eclipse.xpect.xtext.lib.setup.ThisResource) Inject(com.google.inject.Inject) ICommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.ICommaSeparatedValuesExpectation) HashMap(java.util.HashMap) QuickFixTestHelper.extractSingleChangedLine(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper.extractSingleChangedLine) AtomicReference(java.util.concurrent.atomic.AtomicReference) Point(org.eclipse.swt.graphics.Point) XtextResourceCleanUtil(org.eclipse.n4js.xpect.ui.common.XtextResourceCleanUtil) Logger(org.apache.log4j.Logger) QuickFixTestHelper.separateOnCommaAndQuote(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper.separateOnCommaAndQuote) ValidationTestModuleSetup(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup) Lists(com.google.common.collect.Lists) Config(org.eclipse.n4js.xpect.config.Config) Map(java.util.Map) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) TemplateProposal(org.eclipse.jface.text.templates.TemplateProposal) ComparisonFailure(junit.framework.ComparisonFailure) XpectImport(org.eclipse.xpect.XpectImport) ParameterParser(org.eclipse.xpect.parameter.ParameterParser) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) CommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.CommaSeparatedValuesExpectation) XtextResource(org.eclipse.xtext.resource.XtextResource) N4JSOffsetAdapter(org.eclipse.n4js.xpect.common.N4JSOffsetAdapter) QuickFixTestHelper.asString2(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper.asString2) Severity(org.eclipse.xtext.diagnostics.Severity) AbstractExpectation(org.eclipse.xpect.expectation.impl.AbstractExpectation) ExpectationCollection(org.eclipse.xpect.expectation.impl.ExpectationCollection) AssertionFailedError(junit.framework.AssertionFailedError) Display(org.eclipse.swt.widgets.Display) Collectors(java.util.stream.Collectors) ChangeInfo(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper.ChangeInfo) IteratorExtensions(org.eclipse.xtext.xbase.lib.IteratorExtensions) List(java.util.List) XpEnvironmentData(org.eclipse.n4js.xpect.config.XpEnvironmentData) Predicate(com.google.common.base.Predicate) CommaSeparatedValuesExpectationImpl(org.eclipse.xpect.expectation.impl.CommaSeparatedValuesExpectationImpl) Entry(java.util.Map.Entry) Optional(java.util.Optional) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Pair(org.eclipse.xtext.xbase.lib.Pair) Comparator(java.util.Comparator) IStringExpectation(org.eclipse.xpect.expectation.IStringExpectation) Xpect(org.eclipse.xpect.runner.Xpect) XpEnvironmentData(org.eclipse.n4js.xpect.config.XpEnvironmentData) CommaSeparatedValuesExpectationImpl(org.eclipse.xpect.expectation.impl.CommaSeparatedValuesExpectationImpl) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 20 with ParameterParser

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

the class ContentAssistXpectMethod method contentAssist.

/*-
	 contentAssist              at ’a.<|>methodA’        ’methodA2’           --> a.methodA2() <|>methodA
	 contentAssist              at ’a.<|><[>methodA<]>’  ’methodA2’ override  --> a.methodA2()<|>
	 contentAssist              at ’a.methodA’           ’methodA2’           --> a.methodA2() <|>methodA
	 contentAssist              at ’var A<|> a’          ’A - import’         ---
	 contentAssist              at 'a.<|>methodA'       'methodA2'            --> a.methodA2()<|>methodA
	 contentAssist              at 'a.<|>methodA'       'methodA2'   insert   --> a.methodA2()<|>methodA
	 contentAssist              at 'a.<|>methodA'       'methodA2'   override --> a.methodA2()<|>
	 contentAssist kind 'smart' at '<a|>methodA'        'methodA2'            ---
	              kind             offset               selected    mode
	              arg3             arg2                 arg4        arg5
	 */
/**
 * Application of a content assist. The right hand side describes the expected modifications.
 *
 * Up to now only single-line changes are supported.
 *
 * @param expectation
 *            injected Applicaiton
 * @param resource
 *            injected xtext resource
 * @param offset
 *            parsed arg2 - Cursorposition and Selection
 * @param kind
 *            parsed arg3 - named kind of assistence-provider 'recommenders',...
 * @param selected
 *            parsed arg4 - string of things to select in proposal list.
 * @param mode
 *            parsed arg5 - mode modifier
 * @throws Exception
 *             in junit-error case
 */
@Xpect
@ParameterParser(syntax = "( ('kind' arg3=STRING)? 'at' (arg2=STRING  ('apply' arg4=STRING)?  (arg5=ID)? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void contentAssist(// arg0
IStringExpectation expectation, // arg1
@ThisResource XtextResource resource, // arg2 //@ThisOffset is obsolete
RegionWithCursor offset, // arg3
String kind, // arg4
String selected, // arg5
String mode) throws Exception {
    N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
    ICompletionProposal proposal = exactlyMatchingProposal(offset, fixture, selected);
    String before = resource.getParseResult().getRootNode().getText();
    // apply:
    // so working with the fixture cannot get any selection information since these are mocked away.
    IXtextDocument document = fixture.getDocument(XtextResourceCleanUtil.cleanXtextResource(resource), before);
    Optional<String> optionalMode = Optional.ofNullable(mode);
    if (optionalMode.isPresent() && optionalMode.get().trim() == "override") {
    // TODO mode override: needs to have a real selectionprovider in the fixture.
    // currently there is a mockup which doesn't support selection
    // see org.eclipse.xtext.ui.testing.ContentAssistProcessorTestBuilder.getSourceViewer(String,
    // IXtextDocument)
    // val sv = fixture.getSourceViewer(null, document)
    // sv.selectionProvider.selection = new TextSelection(..)
    }
    String after = applyProposal(proposal, document);
    // Expecting change only in single line:
    ChangeInfo changedLines = extractSingleChangedLine(before, after);
    if (changedLines.isMoreThanOne()) {
        throw new AssertionError("more then one line changed: " + changedLines.asString());
    } else if (changedLines.isEmpty()) {
        throw new AssertionError("Nothing changed.");
    }
    String exp = changedLines.first().getAfter();
    Point selection = proposal.getSelection(document);
    if (selection != null) {
        IExpectationRegion region = ((AbstractExpectation) expectation).getRegion();
        if (CursorMarkerHelper.exists(region.getRegionText(), CursorMarkerHelper.markerCursor)) {
            int newPos = selection.x - changedLines.first().getAfterOffset();
            exp = new StringBuilder(exp).insert(newPos, CursorMarkerHelper.markerCursor).toString();
        }
    }
    // Single changed line:
    expectation.assertEquals(exp);
// TODO up to now this only removes the locations for the cursor but doesn't check the location.
// TODO multilines must be supported.
// // before = replaceXPECT(before);
// // after = replaceXPECT(after);
// expectation.assertEquals(after)
// expectation.assertDiffEquals("a", "b - not implemented yet")
}
Also used : ChangeInfo(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper.ChangeInfo) AbstractExpectation(org.eclipse.xpect.expectation.impl.AbstractExpectation) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) Point(org.eclipse.swt.graphics.Point) IExpectationRegion(org.eclipse.xpect.expectation.IExpectationRegion) Point(org.eclipse.swt.graphics.Point) 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)

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