private Pair<CommaSeparatedValuesExpectationImpl, CharSequence> expandVariables( CommaSeparatedValuesExpectationImpl csvE, XpEnvironmentData data) { // val CommaSeparatedValuesExpectationImpl csvE = (expectation as CommaSeparatedValuesExpectationImpl); IExpectationRegion region = csvE.getRegion(); CharSequence doc = region.getDocument(); CharSequence expectedText = null; if (region.getLength() < 0) { expectedText = ""; } else { expectedText = doc.subSequence(region.getOffset(), region.getOffset() + region.getLength()); } CommaSeparatedValuesExpectationCfg cfg = new CommaSeparatedValuesExpectationCfg(csvE.getAnnotation()); cfg.setData(data); VarSubstCommaSeparatedValuesExpectationImpl csvRet = new VarSubstCommaSeparatedValuesExpectationImpl(csvE, cfg); VarSubstExpectationCollection vseColl = new VarSubstExpectationCollection(data); vseColl.init(expectedText.toString()); String expandedExpectedText = IteratorExtensions.join(vseColl.iterator(), ","); return new Pair<>(csvRet, expandedExpectedText); }
/** * Convenience method to perform subtype checks. Depending on the given variance, this will check * <code>left <: right</code> OR <code>left >: right</code> OR both. */ private boolean isSubtypeOf(TypeRef left, TypeRef right, Variance variance) { // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // recursion guard final Pair<String, Pair<TypeRef, TypeRef>> key = Pair.of(RuleEnvironmentExtensions.GUARD_REDUCER_IS_SUBTYPE_OF, Pair.of(left, right)); if (G.get(key) != null) { return true; } final RuleEnvironment G2 = RuleEnvironmentExtensions.wrap(G); G2.add(key, Boolean.TRUE); // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ switch (variance) { case CO: return ts.subtypeSucceeded(G2, left, right); case CONTRA: return ts.subtypeSucceeded(G2, right, left); case INV: return ts.equaltypeSucceeded(G2, left, right); } throw new IllegalStateException("unreachable"); // actually unreachable, each case above returns }
private void initFParAggregate(ComposedFParInfo fpAggr) { for (Pair<TFormalParameter, RuleEnvironment> fpPair : fpAggr.fpSiblings) { TFormalParameter tFpar = fpPair.getKey(); RuleEnvironment G = fpPair.getValue(); // handle: name final String nextName = tFpar.getName(); if (nextName != null && !fpAggr.names.contains(nextName)) { fpAggr.names.add(nextName); } // handle: typeRef lists TypeRef typeRefSubst = ts.substTypeVariablesInTypeRef(G, tFpar.getTypeRef()); if (typeRefSubst != null && !(typeRefSubst instanceof UnknownTypeRef)) { TypeRef typeRefCopy = TypeUtils.copyIfContained(typeRefSubst); fpAggr.typeRefs.add(typeRefCopy); if (tFpar.isVariadic()) { fpAggr.typeRefsVariadic.add(typeRefCopy); } } // handle: optional fpAggr.allOptional &= tFpar.isOptional(); fpAggr.allNonOptional &= !tFpar.isOptional(); } }
private void handleFParameters(TMember member, RuleEnvironment G) { EList<TFormalParameter> fpars = null; if (member instanceof TMethod) { TMethod method = (TMethod) member; fpars = method.getFpars(); } if (member instanceof TSetter) { TSetter setter = (TSetter) member; fpars = new BasicEList<>(); fpars.add(setter.getFpar()); } if (fpars != null) { for (int i = 0; i < fpars.size(); i++) { TFormalParameter fpar = fpars.get(i); if (fParameters.size() <= i) { fParameters.add(new ComposedFParInfo()); } ComposedFParInfo fpAggr = fParameters.get(i); Pair<TFormalParameter, RuleEnvironment> fpPair = new Pair<>(fpar, G); fpAggr.fpSiblings.add(fpPair); } } }
private void handleValidationProblems() { for (Pair<TMember, RuleEnvironment> pair : siblings) { if (pair == null) continue; TMember member = pair.getKey(); if (member instanceof TMethod) { TMethod tMethod = (TMethod) member; for (int i = 0; i < tMethod.getFpars().size(); i++) { TFormalParameter currFP = tMethod.getFpars().get(i); if (currFP.isVariadic() && tMethod.getFpars().size() > i + 1) { ComposedFParInfo currFPA = fParameters.get(i); currFPA.hasValidationProblem = true; return; } } } } }
/** * In {@link #hasErrors() case of error}, returns human-readable error messages. Otherwise, an empty list will be * returned. */ public List<String> getErrorMessages() { final List<String> msgs = new ArrayList<>(); for (IN4JSProject p : projectsWithUndefImplIds) { msgs.add("project '" + p.getProjectId() + "' does not define an ImplementationId in its manifest"); } for (Map.Entry<Pair<String, String>, Set<IN4JSProject>> currConflict : conflicts.entrySet()) { final String apiId = currConflict.getKey().getKey(); final String implId = currConflict.getKey().getValue(); final Set<IN4JSProject> culprits = currConflict.getValue(); final String culpritsStr = " - " + culprits.stream().map(c -> c.getProjectId()).collect(Collectors.joining("\n - ")); msgs.add("several projects define an implementation for API project '" + apiId + "' with implementation ID '" + implId + "':\n" + culpritsStr); } return msgs; }
/** * creates a fresh resource set with the given resources * * @param resources - pairs of file names and their contents * @return a ResourceSet, containing the given resources. * @throws IOException if the resource loading fails */ public ResourceSet resourceSet(Pair<String,? extends CharSequence> ...resources ) throws IOException { XtextResourceSet result = resourceSetProvider.get(); result.setClasspathURIContext(classpathUriContext); FileProjectConfig projectConfig = new FileProjectConfig(new File(workspaceRoot,PROJECT_NAME), PROJECT_NAME); projectConfig.addSourceFolder("src"); ProjectConfigAdapter.install(result, projectConfig); for (Pair<String, ? extends CharSequence> entry : resources) { URI uri = copyToWorkspace(getSourceFolderPath()+"/"+entry.getKey(), entry.getValue()); Resource resource = result.createResource(uri); if (resource == null) throw new IllegalStateException("Couldn't create resource for URI "+uri+". Resource.Factory not registered?"); resource.load(newHashMap()); } return result; }
public Iterable<ITypeDescriptor> getDescriptors(final ClassLoader classLoader, final Collection<String> packagePrefixes) { try { synchronized (this) { if ((this.classLoaderDescriptors == null)) { this.classLoaderDescriptors = this.createClassLoaderCache(); } } Pair<ClassLoader, Collection<String>> _mappedTo = Pair.<ClassLoader, Collection<String>>of(classLoader, packagePrefixes); final Callable<Iterable<ITypeDescriptor>> _function = () -> { return this.loadDescriptors(classLoader, packagePrefixes); }; return this.classLoaderDescriptors.get(_mappedTo, _function); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
public Iterable<ITypeDescriptor> getDescriptors(final URI uri, final Collection<String> packagePrefixes) { try { synchronized (this) { if ((this.uriDescriptors == null)) { this.uriDescriptors = this.createUriCache(); } } Pair<URI, Collection<String>> _mappedTo = Pair.<URI, Collection<String>>of(uri, packagePrefixes); final Callable<Iterable<ITypeDescriptor>> _function = () -> { return this.loadDescriptors(uri, packagePrefixes); }; return this.uriDescriptors.get(_mappedTo, _function); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
@Test public void testUnderscoreInNumericLiteral() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("{"); _builder.newLine(); _builder.append("\t"); _builder.append("val x = 123_456_789"); _builder.newLine(); _builder.append("}"); _builder.newLine(); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("final int x = 123_456_789;"); _builder_1.newLine(); Pair<JavaVersion, JavaVersion> _mappedTo = Pair.<JavaVersion, JavaVersion>of(JavaVersion.JAVA7, JavaVersion.JAVA8); this.compilesTo(_builder, _builder_1, _mappedTo); }
@Test public void testToMap() { List<Pair<Integer, String>> pairs = new ArrayList<Pair<Integer, String>>(); pairs.add(new Pair<Integer, String>(1, "A")); pairs.add(new Pair<Integer, String>(1, "a")); pairs.add(new Pair<Integer, String>(2, "B")); pairs.add(new Pair<Integer, String>(2, "b")); Function1<Pair<Integer, String>, Integer> computeKeys = new Function1<Pair<Integer, String>, Integer>() { @Override public Integer apply(Pair<Integer, String> p) { return p.getKey(); } }; Map<Integer, Pair<Integer, String>> map = IteratorExtensions.toMap(pairs.iterator(), computeKeys); Assert.assertEquals("Expected grouped map size", 2, map.size()); Assert.assertTrue("Contains 1 as key", map.keySet().contains(1)); Assert.assertEquals("Contains entry 1->a for key 1", map.get(1), new Pair<Integer, String>(1, "a")); Assert.assertTrue("Contains 2 as key", map.keySet().contains(2)); Assert.assertEquals("Contains entry 2->b for key 2", map.get(2), new Pair<Integer, String>(2, "b")); }
@Test public void testGroupBy() { List<Pair<Integer, String>> pairs = new ArrayList<Pair<Integer, String>>(); pairs.add(new Pair<Integer, String>(1, "A")); pairs.add(new Pair<Integer, String>(1, "a")); pairs.add(new Pair<Integer, String>(2, "B")); pairs.add(new Pair<Integer, String>(2, "b")); Function1<Pair<Integer, String>, Integer> computeKeys = new Function1<Pair<Integer, String>, Integer>() { @Override public Integer apply(Pair<Integer, String> p) { return p.getKey(); } }; Map<Integer, List<Pair<Integer, String>>> map = IteratorExtensions.groupBy(pairs.iterator(), computeKeys); Assert.assertEquals("Expected grouped map size", 2, map.size()); Assert.assertTrue("Contains 1 as key", map.keySet().contains(1)); Assert.assertEquals("Contains 2 entries for key 1", 2, map.get(1).size()); Assert.assertEquals("Contains entry 1->A for key 1", new Pair<Integer, String>(1, "A"), map.get(1).get(0)); Assert.assertEquals("Contains entry 1->a for key 1", new Pair<Integer, String>(1, "a"), map.get(1).get(1)); Assert.assertTrue("Contains 2 as key", map.keySet().contains(2)); Assert.assertEquals("Contains 2 entries for key 2", 2, map.get(2).size()); Assert.assertEquals("Contains entry 2->B for key 2", new Pair<Integer, String>(2, "B"), map.get(2).get(0)); Assert.assertEquals("Contains entry 2->b for key 2", new Pair<Integer, String>(2, "b"), map.get(2).get(1)); }
@Before public void setUp() throws Exception { aclStatsService = new AclLiveStatisticsRpcServiceImpl(config, dataBroker, odlDirectStatsService); singleTransactionDataBroker = new SingleTransactionDataBroker(dataBroker); LOG.info("Acl mode: {}", config.getSecurityGroupMode()); newElan(ELAN, ELAN_TAG); newElanInterface(ELAN, PORT_1, true); Pair<DataTreeIdentifier<Interface>, Interface> port1 = new IdentifiedInterfaceWithAclBuilder() .interfaceName(PORT_1) .portSecurity(true).build(); dataBrokerUtil.put(port1); testInterfaceManager.addInterface(port1.getValue()); putNewStateInterface(dataBroker, "port1", PORT_MAC_1); asyncEventsWaiter.awaitEventsConsumption(); }
/** * Gets the offset and the error message for a given {@link Diagnostic}. * * @param diagnostic * instance of {@link Diagnostic} * @return * offset and error message */ private Pair<Integer, String> processDiagnostic(final Diagnostic diagnostic) { StringBuilder errorMessage = new StringBuilder(); if (diagnostic instanceof AbstractValidationDiagnostic) { AbstractValidationDiagnostic avd = (AbstractValidationDiagnostic) diagnostic; errorMessage.append("Unexpected issue found. Code '"); errorMessage.append(avd.getIssueCode()).append("'\n"); errorMessage.append(avd.getMessage()); if (avd instanceof FeatureBasedDiagnostic && ((FeatureBasedDiagnostic) avd).getFeature() != null) { List<INode> nodes = NodeModelUtils.findNodesForFeature(avd.getSourceEObject(), ((FeatureBasedDiagnostic) avd).getFeature()); if (nodes != null && !nodes.isEmpty()) { return new Pair<Integer, String>(findFirstNonHiddenLeafNode(nodes.get(0)).getTotalOffset(), errorMessage.toString()); } } else if (avd instanceof RangeBasedDiagnostic) { return new Pair<Integer, String>(((RangeBasedDiagnostic) avd).getOffset(), errorMessage.toString()); } else { return new Pair<Integer, String>(NodeModelUtils.getNode(avd.getSourceEObject()).getTotalOffset(), errorMessage.toString()); } } return null; }
@Test public void testFormattingClosedFile() { final Procedure1<FormattingConfiguration> _function = (FormattingConfiguration it) -> { StringConcatenation _builder = new StringConcatenation(); _builder.append("type Foo{int bar} type Bar{Foo foo}"); Pair<String, String> _mappedTo = Pair.<String, String>of("foo.testlang", _builder.toString()); it.setFilesInScope(Collections.<String, CharSequence>unmodifiableMap(CollectionLiterals.<String, CharSequence>newHashMap(_mappedTo))); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("type Foo{"); _builder_1.newLine(); _builder_1.append("\t"); _builder_1.append("int bar"); _builder_1.newLine(); _builder_1.append("}"); _builder_1.newLine(); _builder_1.append("type Bar{"); _builder_1.newLine(); _builder_1.append("\t"); _builder_1.append("Foo foo"); _builder_1.newLine(); _builder_1.append("}"); _builder_1.newLine(); it.setExpectedText(_builder_1.toString()); }; this.testFormatting(_function); }
@Test public void testSimple() { final InMemoryURIHandler fs = new InMemoryURIHandler(); StringConcatenation _builder = new StringConcatenation(); _builder.append("#2 foo"); Pair<String, String> _mappedTo = Pair.<String, String>of("inmemory:/file1.pstl", _builder.toString()); this._changeSerializerTestHelper.operator_add(fs, _mappedTo); final ResourceSet rs = this._changeSerializerTestHelper.createResourceSet(fs); final MandatoryValue model = this._changeSerializerTestHelper.<MandatoryValue>contents(rs, "inmemory:/file1.pstl", MandatoryValue.class); final IChangeSerializer serializer = this._changeSerializerTestHelper.newChangeSerializer(); final IChangeSerializer.IModification<Resource> _function = (Resource it) -> { model.setName("bar"); }; serializer.<Resource>addModification(model.eResource(), _function); Collection<IEmfResourceChange> _endRecordChangesToTextDocuments = this._changeSerializerTestHelper.endRecordChangesToTextDocuments(serializer); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("----------------- inmemory:/file1.pstl (syntax: <offset|text>) -----------------"); _builder_1.newLine(); _builder_1.append("#2 <3:3|bar>"); _builder_1.newLine(); _builder_1.append("--------------------------------------------------------------------------------"); _builder_1.newLine(); _builder_1.append("3 3 \"foo\" -> \"bar\""); _builder_1.newLine(); this._changeSerializerTestHelper.operator_tripleEquals(_endRecordChangesToTextDocuments, _builder_1); }
@Test public void testDeleteChild() { final InMemoryURIHandler fs = new InMemoryURIHandler(); StringConcatenation _builder = new StringConcatenation(); _builder.append("#1 root { child1 { foo1; } }"); Pair<String, String> _mappedTo = Pair.<String, String>of("inmemory:/file1.pstl", _builder.toString()); this._changeSerializerTestHelper.operator_add(fs, _mappedTo); final ResourceSet rs = this._changeSerializerTestHelper.createResourceSet(fs); final Node model = this._changeSerializerTestHelper.<Node>contents(rs, "inmemory:/file1.pstl", Node.class); final IChangeSerializer serializer = this._changeSerializerTestHelper.newChangeSerializer(); final IChangeSerializer.IModification<Resource> _function = (Resource it) -> { EcoreUtil.remove(model.getChildren().get(0).getChildren().get(0)); }; serializer.<Resource>addModification(model.eResource(), _function); Collection<IEmfResourceChange> _endRecordChangesToTextDocuments = this._changeSerializerTestHelper.endRecordChangesToTextDocuments(serializer); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("----------------- inmemory:/file1.pstl (syntax: <offset|text>) -----------------"); _builder_1.newLine(); _builder_1.append("#1 root { child1 {<18:7| >} }"); _builder_1.newLine(); _builder_1.append("--------------------------------------------------------------------------------"); _builder_1.newLine(); _builder_1.append("18 7 \" foo1; \" -> \" \""); _builder_1.newLine(); this._changeSerializerTestHelper.operator_tripleEquals(_endRecordChangesToTextDocuments, _builder_1); }
@Test public void testResourceURIChange() { final InMemoryURIHandler fs = new InMemoryURIHandler(); StringConcatenation _builder = new StringConcatenation(); _builder.append("#1 root { }"); Pair<String, String> _mappedTo = Pair.<String, String>of("inmemory:/f.pstl", _builder.toString()); this._changeSerializerTestHelper.operator_add(fs, _mappedTo); final ResourceSet rs = this._changeSerializerTestHelper.createResourceSet(fs); final Node model = this._changeSerializerTestHelper.<Node>contents(rs, "inmemory:/f.pstl", Node.class); final IChangeSerializer serializer = this._changeSerializerTestHelper.newChangeSerializer(); final IChangeSerializer.IModification<Resource> _function = (Resource it) -> { Resource _eResource = model.eResource(); _eResource.setURI(URI.createURI("inmemory:/x.pstl")); }; serializer.<Resource>addModification(model.eResource(), _function); Collection<IEmfResourceChange> _endRecordChangesToTextDocuments = this._changeSerializerTestHelper.endRecordChangesToTextDocuments(serializer); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("----- renamed inmemory:/f.pstl to inmemory:/x.pstl (syntax: <offset|text>) -----"); _builder_1.newLine(); _builder_1.append("(no changes)"); _builder_1.newLine(); _builder_1.append("--------------------------------------------------------------------------------"); _builder_1.newLine(); this._changeSerializerTestHelper.operator_tripleEquals(_endRecordChangesToTextDocuments, _builder_1); }
protected Map<String, List<Diagnostic>> getDiagnostics() { try { final Function1<CancelIndicator, HashMap<String, List<Diagnostic>>> _function = (CancelIndicator it) -> { final HashMap<String, List<Diagnostic>> result = CollectionLiterals.<String, List<Diagnostic>>newHashMap(); final Function1<Pair<String, Object>, Object> _function_1 = (Pair<String, Object> it_1) -> { return it_1.getValue(); }; Iterable<PublishDiagnosticsParams> _filter = Iterables.<PublishDiagnosticsParams>filter(ListExtensions.<Pair<String, Object>, Object>map(this.notifications, _function_1), PublishDiagnosticsParams.class); for (final PublishDiagnosticsParams diagnostic : _filter) { result.put(diagnostic.getUri(), diagnostic.getDiagnostics()); } return result; }; return this.languageServer.getRequestManager().<HashMap<String, List<Diagnostic>>>runRead(_function).get(); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
@Before public void before() { try { final Path tmpPath = Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value()); StringConcatenation _builder = new StringConcatenation(); _builder.append("tempFolder_"); UUID _randomUUID = UUID.randomUUID(); _builder.append(_randomUUID); final Path output = Files.createTempDirectory(tmpPath, _builder.toString()); final Path resource = Files.createFile(output.resolve(URIBasedFileSystemAccessTest.EXISTING_RESOURCE_NAME)); resource.toFile().deleteOnExit(); output.toFile().deleteOnExit(); final OutputConfiguration config = IterableExtensions.<OutputConfiguration>head(this.configProvider.getOutputConfigurations()); config.setOutputDirectory(output.toString()); Pair<String, OutputConfiguration> _mappedTo = Pair.<String, OutputConfiguration>of(IFileSystemAccess.DEFAULT_OUTPUT, config); this.fsa.setOutputConfigurations(Collections.<String, OutputConfiguration>unmodifiableMap(CollectionLiterals.<String, OutputConfiguration>newHashMap(_mappedTo))); this.fsa.setConverter(this.uriConverter); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
@Test public void testGetElementsByName_04() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate test \'http://test\'"); _builder.newLine(); _builder.append("Rule: name=ID;"); _builder.newLine(); _builder.append("terminal ID: super;"); _builder.newLine(); final String grammarAsString = _builder.toString(); EObject _model = this.getModel(grammarAsString); final Grammar grammar = ((Grammar) _model); AbstractRule _last = IterableExtensions.<AbstractRule>last(grammar.getRules()); final SuperCallScope scope = new SuperCallScope(_last); Iterable<IEObjectDescription> _elements = scope.getElements(QualifiedName.create("super")); AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "org.eclipse.xtext.common.Terminals.ID"); Pair<String, AbstractRule> _mappedTo = Pair.<String, AbstractRule>of("super", _findRuleForName); this.assertElements(_elements, _mappedTo); }
@Test public void testGetElementsByName_05() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate test \'http://test\'"); _builder.newLine(); _builder.append("Rule: name=ID;"); _builder.newLine(); _builder.append("terminal ID: super;"); _builder.newLine(); final String grammarAsString = _builder.toString(); EObject _model = this.getModel(grammarAsString); final Grammar grammar = ((Grammar) _model); final SuperCallScope scope = new SuperCallScope(grammar); Iterable<IEObjectDescription> _elements = scope.getElements(QualifiedName.create("super", "ID")); AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "org.eclipse.xtext.common.Terminals.ID"); Pair<String, AbstractRule> _mappedTo = Pair.<String, AbstractRule>of("super.ID", _findRuleForName); this.assertElements(_elements, _mappedTo); }
@Test public void testGetElementsByName_06() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate test \'http://test\'"); _builder.newLine(); _builder.append("Rule: name=ID;"); _builder.newLine(); _builder.append("terminal ID: super;"); _builder.newLine(); final String grammarAsString = _builder.toString(); EObject _model = this.getModel(grammarAsString); final Grammar grammar = ((Grammar) _model); final SuperCallScope scope = new SuperCallScope(grammar); Iterable<IEObjectDescription> _elements = scope.getElements(QualifiedName.create("Lang", "ID")); AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "test.Lang.ID"); Pair<String, AbstractRule> _mappedTo = Pair.<String, AbstractRule>of("Lang.ID", _findRuleForName); this.assertElements(_elements, _mappedTo); }
@Test public void testGetElementsByName_07() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate test \'http://test\'"); _builder.newLine(); _builder.append("Rule: name=ID;"); _builder.newLine(); _builder.append("terminal ID: super;"); _builder.newLine(); final String grammarAsString = _builder.toString(); EObject _model = this.getModel(grammarAsString); final Grammar grammar = ((Grammar) _model); final SuperCallScope scope = new SuperCallScope(grammar); Iterable<IEObjectDescription> _elements = scope.getElements(QualifiedName.create("test", "Lang", "ID")); AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "test.Lang.ID"); Pair<String, AbstractRule> _mappedTo = Pair.<String, AbstractRule>of("test.Lang.ID", _findRuleForName); this.assertElements(_elements, _mappedTo); }
@Test public void testGetElementsByEObject_01() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate test \'http://test\'"); _builder.newLine(); _builder.append("Rule: name=ID;"); _builder.newLine(); _builder.append("terminal ID: super;"); _builder.newLine(); final String grammarAsString = _builder.toString(); EObject _model = this.getModel(grammarAsString); final Grammar grammar = ((Grammar) _model); final SuperCallScope scope = new SuperCallScope(grammar); final AbstractRule id = GrammarUtil.findRuleForName(grammar, "test.Lang.ID"); Iterable<IEObjectDescription> _elements = scope.getElements(id); AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "test.Lang.ID"); Pair<String, AbstractRule> _mappedTo = Pair.<String, AbstractRule>of("Lang.ID", _findRuleForName); AbstractRule _findRuleForName_1 = GrammarUtil.findRuleForName(grammar, "test.Lang.ID"); Pair<String, AbstractRule> _mappedTo_1 = Pair.<String, AbstractRule>of("test.Lang.ID", _findRuleForName_1); this.assertElements(_elements, _mappedTo, _mappedTo_1); }
@Test public void testGetElementsByEObject_02() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate test \'http://test\'"); _builder.newLine(); _builder.append("Rule: name=ID;"); _builder.newLine(); _builder.append("terminal ID: super;"); _builder.newLine(); final String grammarAsString = _builder.toString(); EObject _model = this.getModel(grammarAsString); final Grammar grammar = ((Grammar) _model); AbstractRule _head = IterableExtensions.<AbstractRule>head(grammar.getRules()); final SuperCallScope scope = new SuperCallScope(_head); final AbstractRule id = GrammarUtil.findRuleForName(grammar, "org.eclipse.xtext.common.Terminals.ID"); Iterable<IEObjectDescription> _elements = scope.getElements(id); AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "org.eclipse.xtext.common.Terminals.ID"); Pair<String, AbstractRule> _mappedTo = Pair.<String, AbstractRule>of("super.ID", _findRuleForName); AbstractRule _findRuleForName_1 = GrammarUtil.findRuleForName(grammar, "org.eclipse.xtext.common.Terminals.ID"); Pair<String, AbstractRule> _mappedTo_1 = Pair.<String, AbstractRule>of("Lang.ID", _findRuleForName_1); AbstractRule _findRuleForName_2 = GrammarUtil.findRuleForName(grammar, "org.eclipse.xtext.common.Terminals.ID"); Pair<String, AbstractRule> _mappedTo_2 = Pair.<String, AbstractRule>of("test.Lang.ID", _findRuleForName_2); this.assertElements(_elements, _mappedTo, _mappedTo_1, _mappedTo_2); }
/** * This xpect method can evaluate all branches that are merged at the given node name. */ @ParameterParser(syntax = "('pleaseNeverUseThisParameterSinceItExistsOnlyToGetAReferenceOffset' arg1=OFFSET)?") @Xpect public void allMergeBranches(@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation, IEObjectCoveringRegion referenceOffset) { N4JSFlowAnalyzerDataRecorder.setEnabled(true); GraphVisitor gv = new DummyForwardBackwardVisitor(); ControlFlowElement referenceCFE = getCFE(referenceOffset); getFlowAnalyzer(referenceCFE).accept(gv); N4JSFlowAnalyzerDataRecorder.setEnabled(false); performBranchAnalysis(referenceOffset, null, referenceOffset); List<String> edgeStrings = new LinkedList<>(); int groupIdx = 0; List<Pair<Node, List<ControlFlowEdge>>> mergedEdges = N4JSFlowAnalyzerDataRecorder.getMergedEdges(); for (Pair<Node, List<ControlFlowEdge>> pair : mergedEdges) { Node startNode = pair.getKey(); List<ControlFlowEdge> edges = pair.getValue(); for (ControlFlowEdge edge : edges) { String c = edge.start == startNode ? "B" : "F"; edgeStrings.add(c + groupIdx + ": " + edge.toString()); } groupIdx++; } Collections.sort(edgeStrings); expectation.assertEquals(edgeStrings); }
/** * Adds a sibling member on which a new composed member is based upon. (Also refer to the life cycle mentioned * above.) */ public void addMember(TMember member, RuleEnvironment G) { Objects.nonNull(siblings); Pair<TMember, RuleEnvironment> pair = null; if (member != null) { pair = new Pair<>(member, G); } siblings.add(pair); // adds null to indicate missing members }
ComposedMemberInfo(boolean writeAccess, Resource resource, N4JSTypeSystem ts, List<Pair<TMember, RuleEnvironment>> siblings) { this.isWriteAccess = writeAccess; this.resource = resource; this.ts = ts; this.siblings = new LinkedList<>(); this.siblings.addAll(siblings); }
synchronized private void initMemberAggregate() { if (isInitialized) return; this.isSiblingMissing = siblings.contains(null); MemberType lastMType = null; for (Pair<TMember, RuleEnvironment> pair : siblings) { if (pair == null) continue; this.isEmpty = false; TMember member = pair.getKey(); RuleEnvironment G = pair.getValue(); lastMType = handleMemberTypes(lastMType, member); handleReadOnlyField(member); handleAccessibility(member); handleTypeRefLists(member, G); handleFParameters(member, G); } // init: fParameters List<TypeRef> currVariadicAccumulated = new LinkedList<>(); for (ComposedFParInfo fpAggr : fParameters) { initFParAggregate(fpAggr); // handle: typeRefsVariadicAccumulated currVariadicAccumulated.addAll(fpAggr.typeRefsVariadic); fpAggr.typeRefsVariadicAccumulated.addAll(currVariadicAccumulated); } handleIsVariadicButLastFParIsDifferent(); handleValidationProblems(); this.isInitialized = true; }
private void putConflict(String apiId, String implId, IN4JSProject... culprit) { final Pair<String, String> apiId_implId = new Pair<>(apiId, implId); Set<IN4JSProject> culprits = conflicts.get(apiId_implId); if (culprits == null) { culprits = new LinkedHashSet<>(); conflicts.put(apiId_implId, culprits); } culprits.addAll(Arrays.asList(culprit)); }
/** * Parses, validates and compiles the given sources. Calls the given acceptor for each * resource which is generated from the source. * * @param sources some inputs written in the language under test. * @param acceptor gets called once for each file generated in {@link IGenerator} * @throws IOException if the resource loading fails * * @since 2.8 */ @SuppressWarnings("unchecked") public void compile(Iterable<? extends CharSequence> sources, IAcceptor<Result> acceptor) throws IOException { int index = 0; List<Pair<String, ? extends CharSequence>> pairs = newArrayList(); for (CharSequence source : sources) { String fileName = "MyFile" + (++index) + "." + extensionProvider.getPrimaryFileExtension(); pairs.add(new Pair<String, CharSequence>(fileName, source)); } compile(resourceSet(((Pair<String, ? extends CharSequence>[])Conversions.unwrapArray(pairs, Pair.class))), acceptor); }
/** * same as {@link #resourceSet(Pair...)} but without actually loading the created resources. */ public ResourceSet unLoadedResourceSet(Pair<String,? extends CharSequence> ...resources ) throws IOException { XtextResourceSet result = resourceSetProvider.get(); for (Pair<String, ? extends CharSequence> entry : resources) { URI uri = copyToWorkspace(getSourceFolderPath()+"/"+entry.getKey(), entry.getValue()); Resource resource = result.createResource(uri); if (resource == null) throw new IllegalStateException("Couldn't create resource for URI "+uri+". Resource.Factory not registered?"); } return result; }
@Test public void testTelemetry() { StringConcatenation _builder = new StringConcatenation(); _builder.append("{"); _builder.newLine(); _builder.append("\t"); _builder.append("\"jsonrpc\": \"2.0\","); _builder.newLine(); _builder.append("\t"); _builder.append("\"method\": \"telemetry/event\","); _builder.newLine(); _builder.append("\t"); _builder.append("\"params\": {"); _builder.newLine(); _builder.append("\t\t"); _builder.append("\"foo\": 12.3,"); _builder.newLine(); _builder.append("\t\t"); _builder.append("\"bar\": \"qwertz\""); _builder.newLine(); _builder.append("\t"); _builder.append("}"); _builder.newLine(); _builder.append("}"); _builder.newLine(); NotificationMessage _notificationMessage = new NotificationMessage(); final Procedure1<NotificationMessage> _function = (NotificationMessage it) -> { it.setJsonrpc("2.0"); it.setMethod(MessageMethods.TELEMETRY_EVENT); Pair<String, Double> _mappedTo = Pair.<String, Double>of("foo", Double.valueOf(12.3)); Pair<String, String> _mappedTo_1 = Pair.<String, String>of("bar", "qwertz"); it.setParams(CollectionLiterals.<String, Object>newLinkedHashMap(_mappedTo, _mappedTo_1)); }; NotificationMessage _doubleArrow = ObjectExtensions.<NotificationMessage>operator_doubleArrow(_notificationMessage, _function); this.assertParse(_builder, _doubleArrow); }
@Test public void testClassShadowing() { StringConcatenation _builder = new StringConcatenation(); _builder.append("package org.eclipse.xtext.java.tests;"); _builder.newLine(); _builder.append("public class MySuperClass2 {"); _builder.newLine(); _builder.append(" "); _builder.append("public void doSomething() {"); _builder.newLine(); _builder.append(" "); _builder.newLine(); _builder.append(" "); _builder.append("}"); _builder.newLine(); _builder.append("}"); _builder.newLine(); Pair<String, String> _mappedTo = Pair.<String, String>of("org/eclipse/xtext/java/tests/MySuperClass2.java", _builder.toString()); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("package org.eclipse.xtext.java.tests;"); _builder_1.newLine(); _builder_1.append("public class MySubClass2 extends MySuperClass2 {"); _builder_1.newLine(); _builder_1.append("}"); _builder_1.newLine(); Pair<String, String> _mappedTo_1 = Pair.<String, String>of("org/eclipse/xtext/java/tests/MySubClass2.java", _builder_1.toString()); final XtextResourceSet rs = this.resourceSet(_mappedTo, _mappedTo_1); final Function1<Resource, Boolean> _function = (Resource it) -> { return Boolean.valueOf(it.getURI().toString().endsWith("MySuperClass2.java")); }; final Resource superResource = IterableExtensions.<Resource>findFirst(rs.getResources(), _function); EObject _head = IterableExtensions.<EObject>head(superResource.getContents()); final JvmGenericType clazz = ((JvmGenericType) _head); Assert.assertNotNull(IterableExtensions.<JvmOperation>head(clazz.getDeclaredOperations())); }
protected void resultsIn(final CharSequence javaCode, final Procedure1<? super IResourceDescription> assertion) { String _string = javaCode.toString(); Pair<String, String> _mappedTo = Pair.<String, String>of("SomeJava.java", _string); final XtextResourceSet resourceSet = this.resourceSet(_mappedTo); this.compilerPhases.setIndexing(resourceSet, true); final Resource resource = IterableExtensions.<Resource>head(resourceSet.getResources()); final IResourceDescription description = this.resourceDesriptionManager.getResourceDescription(resource); assertion.apply(description); }
@Override @SuppressWarnings("unchecked") public <T extends JvmDeclaredType> void accept(T type, Procedure1<? super T> lateInitialization) { if (type != null && type.eContainer() == null) resource.getContents().add(type); if (lateInitialization != null && type != null) { later.add(new Pair<JvmDeclaredType, Procedure1<? super JvmDeclaredType>>(type, (Procedure1<? super JvmDeclaredType>) lateInitialization)); } }
protected void compilesTo(final CharSequence xbaseCode, final CharSequence result, Pair<JavaVersion, JavaVersion> minAndMaxVersion) throws Exception { int min = minAndMaxVersion.getKey().ordinal(); int max = minAndMaxVersion.getValue().ordinal(); if (min > max) throw new IllegalArgumentException(); for (int i = min; i <= max; i++) { JavaVersion version = JavaVersion.values()[i]; assertCompilesTo(result, xbaseCode, version); } }
@Test public void test_toQualifiedName() { Pair<List<String>, String> _mappedTo = Pair.<List<String>, String>of(Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList("foo")), "foo"); Pair<List<String>, String> _mappedTo_1 = Pair.<List<String>, String>of(Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList("foo", "bar")), "foo.bar"); Pair<List<String>, String> _mappedTo_2 = Pair.<List<String>, String>of(Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList("..")), ".."); Pair<List<String>, String> _mappedTo_3 = Pair.<List<String>, String>of(Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList("..<")), "..<"); Pair<List<String>, String> _mappedTo_4 = Pair.<List<String>, String>of(Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList(">..")), ">.."); final Map<List<String>, String> testdata = Collections.<List<String>, String>unmodifiableMap(CollectionLiterals.<List<String>, String>newHashMap(_mappedTo, _mappedTo_1, _mappedTo_2, _mappedTo_3, _mappedTo_4)); final Consumer<Map.Entry<List<String>, String>> _function = (Map.Entry<List<String>, String> it) -> { Assert.assertEquals(QualifiedName.create(it.getKey()), this.converter.toQualifiedName(it.getValue())); }; testdata.entrySet().forEach(_function); }
@Override public CompletableFuture<?> request(String method, Object parameter) { Assert.assertTrue(expectedRequests.containsKey(method)); Pair<Object, Object> result = expectedRequests.remove(method); Assert.assertEquals(result.getKey().toString(), parameter.toString()); return CompletableFuture.completedFuture(result.getValue()); }