org.eclipse.xtext.grammaranalysis.impl.GrammarElementTitleSwitch Java Examples

The following examples show how to use org.eclipse.xtext.grammaranalysis.impl.GrammarElementTitleSwitch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AssertStructureAcceptor.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void assertElement(AbstractElement element) {
	AbstractRule expectedRule = null;
	if (stack.isEmpty()) {
		// FIXME: this doesn't work if the serialized EObject is not the model's root. 
		// expectedRule = EcoreUtil2.getContainerOfType(element, Grammar.class).getRules().get(0);
		return;
	} else
		expectedRule = stack.peek().getRule();
	AbstractRule actualRule = EcoreUtil2.getContainerOfType(element, AbstractRule.class);
	if (expectedRule != actualRule) {
		GrammarElementTitleSwitch formatter = new GrammarElementTitleSwitch().showQualified().showRule();
		String elementName = formatter.apply(element);
		String expName = expectedRule.getName();
		String actualName = actualRule.getName();
		String msg = "Element " + elementName + " should be in rule " + expName + " but it is in " + actualName;
		throw new IllegalStateException(msg);
	}
}
 
Example #2
Source File: SARLFormatter.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public ITextReplacer createCommentReplacer(IComment comment) {
	final EObject grammarElement = comment.getGrammarElement();
	if (grammarElement instanceof AbstractRule) {
		final String ruleName = ((AbstractRule) grammarElement).getName();
		CommentReplacer replacer = null;
		if (ruleName.startsWith("ML")) { //$NON-NLS-1$
			replacer = new SARLMultilineCommentReplacer(comment);
		} else if (ruleName.startsWith("SL")) { //$NON-NLS-1$
			replacer = new SARLSinglelineCommentReplacer(comment);
		}
		if (replacer != null) {
			this.injector.injectMembers(replacer);
			return replacer;
		}
	}
	final String elementName = new GrammarElementTitleSwitch().showQualified().showRule().doSwitch(grammarElement);
	throw new IllegalStateException(
			MessageFormat.format(Messages.SARLFormatter_0,
					ITextReplacer.class.getSimpleName(), elementName));
}
 
Example #3
Source File: SerializerPDA.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toString() {
	GrammarElementTitleSwitch fmt = new GrammarElementTitleSwitch().hideCardinality().showQualified()
			.showAssignments();
	switch (type) {
		case ELEMENT:
			return fmt.apply(grammarElement);
		case POP:
			return "<<" + fmt.apply(grammarElement);
		case PUSH:
			return ">>" + fmt.apply(grammarElement);
		case START:
			return "start";
		case STOP:
			return "stop";
	}
	return "";
}
 
Example #4
Source File: SyntacticSequencerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private List<String> getNodeSequence(EObject model) {
	List<String> result = Lists.newArrayList();
	GrammarElementTitleSwitch titleSwitch = new GrammarElementTitleSwitch().showAssignments();
	org.eclipse.xtext.serializer.sequencer.EmitterNodeIterator ni = 
			new org.eclipse.xtext.serializer.sequencer.EmitterNodeIterator(NodeModelUtils.findActualNodeFor(model));
	while (ni.hasNext()) {
		INode next = ni.next();
		EObject ele = next.getGrammarElement() instanceof CrossReference ? ((CrossReference) next
				.getGrammarElement()).getTerminal() : next.getGrammarElement();
		if (next instanceof ILeafNode || GrammarUtil.isDatatypeRuleCall(ele))
			result.add(titleSwitch.doSwitch(ele) + " -> " + next.getText().trim());
		else if (next instanceof ICompositeNode)
			result.add(titleSwitch.doSwitch(ele));
	}
	return result;
}
 
Example #5
Source File: ContextPDAProviderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String getParserRule(String body) throws Exception {
	Grammar grammar = (Grammar) getModel(HEADER + body);
	List<String> result = Lists.newArrayList();
	PdaListFormatter<ISerState, RuleCall> formatter = new PdaListFormatter<ISerState, RuleCall>();
	formatter.setStateFormatter(new ToStr());
	formatter.setStackitemFormatter(new GrammarElementTitleSwitch().showAssignments().hideCardinality());
	formatter.sortFollowers();
	IContextPDAProvider pdaProvider = get(IContextPDAProvider.class);
	SerializationContextMap<Pda<ISerState, RuleCall>> pdas = pdaProvider.getContextPDAs(grammar);
	for (Entry<Pda<ISerState, RuleCall>> ctx : pdas.sortedCopy().values()) {
		result.add(Joiner.on(", ").join(ctx.getContexts()) + ":");
		Pda<ISerState, RuleCall> pda = ctx.getValue();
		result.add("  " + formatter.format(pda).replace("\n", "\n  "));

		// StackTraceElement ele = Thread.currentThread().getStackTrace()[2];
		// String name = getClass().getSimpleName() + "_" + ele.getMethodName() + "_" + ctx.getSecond() + ".pdf";
		// new PdaToDot<ISerState, RuleCall>().draw(pda, "dot/" + name, "-T pdf");
	}
	return Joiner.on("\n").join(result);
}
 
Example #6
Source File: SyntacticSequencerDiagnosticProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ISerializationDiagnostic createInvalidFollowingAbsorberDiagnostic(ISerializationContext context, EObject semanticObject,
		ISynAbsorberState from, AbstractElement to) {
	GrammarElementTitleSwitch fmt = new GrammarElementTitleSwitch().showAssignments().showQualified();
	String fromName = from.toString(fmt);
	String toName = to == null ? "stop" : fmt.doSwitch(to);

	List<String> targets = Lists.newArrayList();
	for (ISynTransition trans : from.getOutTransitions())
		targets.add(trans.getTarget().toString(fmt));

	StringBuilder msg = new StringBuilder();
	msg.append("State '" + toName + "' may not follow '" + fromName + "'.\n");
	msg.append("Valid followers are: " + Joiner.on(", ").join(targets));

	return new SerializationDiagnostic(INVALID_FOLLOWING_ABSORBER, semanticObject, context,
			grammarAccess.getGrammar(), msg.toString());
}
 
Example #7
Source File: ContextTypePDAProviderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String getParserRule(String body) throws Exception {
	Grammar grammar = (Grammar) getModel(HEADER + body);
	// drawGrammar("pdf/" + getName(), grammar);
	List<String> result = Lists.newArrayList();
	PdaListFormatter<ISerState, RuleCall> formatter = new PdaListFormatter<ISerState, RuleCall>();
	formatter.setStateFormatter(new ToStr());
	formatter.setStackitemFormatter(new GrammarElementTitleSwitch().showAssignments().hideCardinality());
	formatter.sortFollowers();
	IContextTypePDAProvider typePDAProvider = get(IContextTypePDAProvider.class);
	SerializationContextMap<Pda<ISerState, RuleCall>> pdas = typePDAProvider.getContextTypePDAs(grammar);
	for (Entry<Pda<ISerState, RuleCall>> ctx : pdas.sortedCopy().values()) {
		result.add(Joiner.on(", ").join(ctx.getContexts()) + ":");
		result.add("  " + formatter.format(ctx.getValue()).replace("\n", "\n  "));
	}
	return Joiner.on("\n").join(result);
}
 
Example #8
Source File: HiddenTokenSequencerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private List<String> getNodeSequence(EObject model) {
	List<String> result = Lists.newArrayList();
	GrammarElementTitleSwitch titleSwitch = new GrammarElementTitleSwitch().showAssignments();
	//		System.out.println(NodeModelUtils.compactDump(NodeModelUtils.findActualNodeFor(model), true));
	org.eclipse.xtext.serializer.sequencer.EmitterNodeIterator ni = 
			new org.eclipse.xtext.serializer.sequencer.EmitterNodeIterator(NodeModelUtils.findActualNodeFor(model), null, true, true);
	while (ni.hasNext()) {
		INode next = ni.next();
		if (next instanceof ILeafNode)
			result.add(titleSwitch.doSwitch(next.getGrammarElement()) + " -> " + next.getText());
		if (next instanceof ICompositeNode)
			result.add(titleSwitch.doSwitch(next.getGrammarElement()));
	}
	return result;
}
 
Example #9
Source File: AbstractFormatter2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public ITextReplacer createCommentReplacer(IComment comment) {
	EObject grammarElement = comment.getGrammarElement();
	if (grammarElement instanceof AbstractRule) {
		String ruleName = ((AbstractRule) grammarElement).getName();
		if (ruleName.startsWith("ML"))
			return new MultilineCommentReplacer(comment, '*');
		if (ruleName.startsWith("SL")) {
			if (comment.getLineRegions().get(0).getIndentation().getLength() > 0)
				return new SinglelineDocCommentReplacer(comment, "//");
			else
				return new SinglelineCodeCommentReplacer(comment, "//");
		}
	}
	String elementName = new GrammarElementTitleSwitch().showQualified().showRule().doSwitch(grammarElement);
	throw new IllegalStateException("No " + ITextReplacer.class.getSimpleName() + " configured for " + elementName);
}
 
Example #10
Source File: AssertStructureAcceptor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertPop(RuleCall call) {
	RuleCall expected = stack.pop();
	if (call != expected) {
		GrammarElementTitleSwitch formatter = new GrammarElementTitleSwitch().showQualified().showRule();
		String expectedName = formatter.apply(expected);
		String actualName = formatter.apply(call);
		throw new IllegalStateException("Expected rule call " + expectedName + " but got " + actualName);
	}
}
 
Example #11
Source File: GrammarPDAProviderTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private String toListString(final Pda<ISerState, RuleCall> pda) {
  final GrammarElementTitleSwitch ts = new GrammarElementTitleSwitch().showAssignments().hideCardinality().showQualified();
  final PdaListFormatter<ISerState, RuleCall> formatter = new PdaListFormatter<ISerState, RuleCall>();
  final Function<ISerState, String> _function = (ISerState it) -> {
    String _switchResult = null;
    ISerState.SerStateType _type = it.getType();
    if (_type != null) {
      switch (_type) {
        case START:
          _switchResult = "start";
          break;
        case STOP:
          _switchResult = "stop";
          break;
        default:
          _switchResult = ts.apply(it.getGrammarElement());
          break;
      }
    } else {
      _switchResult = ts.apply(it.getGrammarElement());
    }
    return _switchResult;
  };
  formatter.setStateFormatter(_function);
  formatter.setStackitemFormatter(new GrammarElementTitleSwitch().showAssignments().hideCardinality());
  formatter.sortFollowers();
  String _format = formatter.format(pda);
  return (_format + "\n");
}
 
Example #12
Source File: AssignmentFinderTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private String findAssignments(EObject obj, Object value, AbstractElement... assignments) {
	AbstractElement element = (AbstractElement) NodeModelUtils.getNode(obj).getGrammarElement();
	ISerializationContext ctx = SerializationContext.forChild(null, element, obj);
	Multimap<AbstractElement, ISerializationContext> ass = ArrayListMultimap.create();
	for (AbstractElement e : assignments)
		ass.put(e, ctx);
	List<AbstractElement> found = Lists.newArrayList(finder.findAssignmentsByValue(obj, ass, value, null));
	Collections.sort(found, GrammarElementDeclarationOrder.get(GrammarUtil.getGrammar(assignments[0])));
	return Joiner.on(", ").join(Iterables.transform(found, new GrammarElementTitleSwitch().showAssignments()));
}
 
Example #13
Source File: FirstSetComputationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertFirstSet(String expectation, AbstractRule rule) {
	RuleCall ruleCall = XtextFactory.eINSTANCE.createRuleCall();
	ruleCall.setRule(rule);
	List<AbstractElement> firstSet = AntlrGrammarGenUtil.getFirstSet(ruleCall);
	StringBuilder actual = new StringBuilder();
	GrammarElementTitleSwitch stringifier = new GrammarElementTitleSwitch();
	for(int i = 0; i < firstSet.size(); i++) {
		if (i != 0)
			actual.append(", ");
		actual.append(stringifier.apply(firstSet.get(i)));
	}
	assertEquals(expectation, actual.toString());
}
 
Example #14
Source File: ContentAssistContextTestHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public String firstSetGrammarElementsToString(final ContentAssistContextFactory factory) {
  final int offset = this.document.indexOf(this.cursor);
  Preconditions.checkArgument((offset >= 0), "you forgot to provide a cursor");
  final String doc = this.document.replace(this.cursor, "");
  final XtextResource res = this.parse(doc);
  factory.setPool(Executors.newCachedThreadPool());
  TextRegion _textRegion = new TextRegion(0, 0);
  final ContentAssistContext[] ctxs = factory.create(doc, _textRegion, offset, res);
  final GrammarElementTitleSwitch f = new GrammarElementTitleSwitch().showAssignments().showQualified().showRule();
  StringConcatenation _builder = new StringConcatenation();
  {
    Iterable<Pair<Integer, ContentAssistContext>> _indexed = IterableExtensions.<ContentAssistContext>indexed(((Iterable<? extends ContentAssistContext>)Conversions.doWrapArray(ctxs)));
    for(final Pair<Integer, ContentAssistContext> ctx : _indexed) {
      _builder.append("context");
      Integer _key = ctx.getKey();
      _builder.append(_key);
      _builder.append(" {");
      _builder.newLineIfNotEmpty();
      {
        ImmutableList<AbstractElement> _firstSetGrammarElements = ctx.getValue().getFirstSetGrammarElements();
        for(final AbstractElement ele : _firstSetGrammarElements) {
          _builder.append("\t");
          String _name = ele.eClass().getName();
          _builder.append(_name, "\t");
          _builder.append(": ");
          String _apply = f.apply(ele);
          _builder.append(_apply, "\t");
          _builder.newLineIfNotEmpty();
        }
      }
      _builder.append("}");
      _builder.newLine();
    }
  }
  return _builder.toString();
}
 
Example #15
Source File: SyntacticSequencerDiagnosticProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ISerializationDiagnostic createUnexpectedStackStateDiagnostic(EObject semanticObject, RuleCallStack stack,
		RuleCall popped, ISynState toConsume) {
	String poppedStr = popped == null ? "null" : new GrammarElementTitleSwitch().showAssignments().doSwitch(popped);
	StringBuilder buf = new StringBuilder();
	buf.append("Unexpected stack state.\n");
	buf.append("Found on top of the stack: " + poppedStr + "\n");
	buf.append("Expected: " + toConsume + "\n");
	buf.append("Rest of the stack: " + stack + "\n");
	return new SerializationDiagnostic(UNEXPECTED_STACK_TRACE, semanticObject, (ISerializationContext) null,
			grammarAccess.getGrammar(), buf.toString());
}
 
Example #16
Source File: GrammarAlias.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toString() {
	GrammarElementTitleSwitch t2s = new GrammarElementTitleSwitch().showAssignments().hideCardinality();
	Function<Production<AbstractElementAlias, AbstractElement>, String> formatter2 = new ProductionFormatter<AbstractElementAlias, AbstractElement>()
			.setTokenToString(t2s);
	return formatter2.apply(new GrammarAliasAdapter(this));
}
 
Example #17
Source File: GrammarConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toString() {
	GrammarElementTitleSwitch t2s = new GrammarElementTitleSwitch().hideCardinality().showActionsAsRuleCalls().showAssignments();
	ProductionFormatter<IConstraintElement, AbstractElement> formatter = new ProductionFormatter<IConstraintElement, AbstractElement>();
	formatter.setTokenToString(t2s);
	return formatter.format(new ConstraintElementProduction(getContainingConstraint()), this, true);
}
 
Example #18
Source File: AbstractSemanticRegionsFinder.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public String toString() {
	String string = new GrammarElementTitleSwitch().showRule().showQualified().doSwitch(grammarElement);
	return "Predicate[" + string + "]";
}
 
Example #19
Source File: SyntacticSequencerPDAProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public String toString() {
	return toString(new GrammarElementTitleSwitch().showAssignments().showQualified());
}
 
Example #20
Source File: SemanticSequencerNfaProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public String toString() {
	if (assignedGrammarElement == null)
		return "(null)";
	return new GrammarElementTitleSwitch().showQualified().showAssignments().apply(assignedGrammarElement);
}
 
Example #21
Source File: RuleCallStack.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public String elementToStr(RuleCall value) {
	if (value == null)
		return "(null)";
	return new GrammarElementTitleSwitch().showAssignments().doSwitch(value);
}