Java Code Examples for org.eclipse.xtext.nodemodel.ICompositeNode#getText()

The following examples show how to use org.eclipse.xtext.nodemodel.ICompositeNode#getText() . 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: IndentationHelper.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the last indentation found before given offset.
 *
 * @param root
 *          the root
 * @param fromOffset
 *          the offset is expected to be normalized with respect to root, i.e. fromOffset 0 <=> root.getOffset().
 * @return the indentation or NULL
 */
public static String getIndentation(final ICompositeNode root, final int fromOffset) {
  if (fromOffset <= 0) {
    return null;
  }
  String nodeText = root.getText();
  if (nodeText == null || fromOffset > nodeText.length()) {
    return null;
  }
  int lastNLIndex = nodeText.lastIndexOf('\n', fromOffset);
  StringBuffer result = new StringBuffer();
  Matcher m = PATTERN.matcher(nodeText.substring(lastNLIndex));
  if (m.find()) {
    result.append(m.group());
  }
  return result.toString();
}
 
Example 2
Source File: XtextReconcilerDebugger.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void assertResouceParsedCorrectly(XtextResource resource, final ReconcilerReplaceRegion region) {
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ICompositeNode rootNode = parseResult.getRootNode();
		final String resourceContent = rootNode.getText();
		IParseResult reparseResult = parser.parse(new StringReader(resourceContent));
		if(!emfStructureComparator.isSameStructure(parseResult.getRootASTElement(), reparseResult.getRootASTElement())) {
			new DisplayRunnable() {
				@Override
				protected void run() throws Exception {
					LOG.error("PartialParsing produced wrong model");
					LOG.error("Events: \n\t" + Joiner.on("\n\t").join(region.getDocumentEvents()));
					LOG.error("ReplaceRegion: \n\t'" + region + "'" );
					MessageDialog.openError(
							Display.getCurrent().getActiveShell(),
							"XtextReconcilerDebugger",
							"PartialParsing produced wrong model."
									+ "\n\nSee log for details.");
				}
				
			};
			
		}
	}
}
 
Example 3
Source File: DefaultNodeModelFormatter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IFormattedRegion format(ICompositeNode root, int offset, int length) {
	String indent = getIndentation(root, offset);
	TokenStringBuffer buf = new TokenStringBuffer();
	ITokenStream out = offset == 0 ? buf : new FilterFirstWhitespaceStream(buf);
	ITokenStream fmt;
	if (formatter instanceof IFormatterExtension) {
		EObject semanticElement = NodeModelUtils.findActualSemanticObjectFor(root);
		if (semanticElement != null)
			fmt = ((IFormatterExtension) formatter).createFormatterStream(semanticElement, indent, out, false);
		else {
			// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=380406
			ITextRegion rootRegion = root.getTextRegion();
			return new FormattedRegion(rootRegion.getOffset(), rootRegion.getLength(), root.getText());
		}
	} else
		fmt = formatter.createFormatterStream(indent, out, false);
	try {
		ITextRegion range = nodeModelStreamer.feedTokenStream(fmt, root, offset, length);
		return new FormattedRegion(range.getOffset(), range.getLength(), buf.toString());
	} catch (IOException e) {
		// this should never happen since TokenStringBuffer doesn't throw IOEs.
		throw new RuntimeException(e);
	}
}
 
Example 4
Source File: PartialParserTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testErrorMarkers() throws Exception {
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	// model contains an error due to missing ) at idx 23
	String model = "spielplatz 1 {kind (k 1}"; 
	XtextResource resource = getResourceFromStringAndExpect(model, 1);
	assertEquals(1, resource.getErrors().size());
	assertEquals(1, Iterables.size(resource.getParseResult().getSyntaxErrors()));
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, model.length() - 1);
	assertTrue(leaf.getSyntaxErrorMessage() != null);
	// resource.update(23, 0, ")");
	// assertTrue(resource.getParseResult().getParseErrors().isEmpty());
	IParseResult reparse = reparse(resource.getParseResult(), 23, 0, ")");
	rootNode = reparse.getRootNode();
	String expectedFixedModel = "spielplatz 1 {kind (k 1)}";
	String fixedModel = rootNode.getText();
	assertEquals("serialized model as expected", expectedFixedModel, fixedModel);
	resource = getResourceFromString(fixedModel);
	assertEquals("full reparse is fine", 0, resource.getErrors().size());
	assertFalse("partial reparse is fine", reparse.hasSyntaxErrors());
}
 
Example 5
Source File: XtextWebDocument.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
protected String refreshText() {
	String newText = "";
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ICompositeNode rootNode = parseResult.getRootNode();
		if (rootNode != null) {
			String text = rootNode.getText();
			if (text != null) {
				newText = text;
			} 
		}
	}
	return text = newText;
}
 
Example 6
Source File: XtextReconcilerDebugger.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public void assertModelInSyncWithDocument(IDocument document, XtextResource resource, final ReconcilerReplaceRegion region) {
	if (document instanceof IDocumentExtension4 && resource != null) {
		long beforeGet = ((IDocumentExtension4) document).getModificationStamp();
		final String documentContent = document.get();
		long afterGet = ((IDocumentExtension4) document).getModificationStamp();
		if (beforeGet == afterGet && beforeGet == resource.getModificationStamp()) {
			IParseResult parseResult = resource.getParseResult();
			if (parseResult != null) {
				ICompositeNode rootNode = parseResult.getRootNode();
				final String resourceContent = rootNode.getText();
				if (!resourceContent.equals(documentContent)) {
					new DisplayRunnable() {
						@Override
						protected void run() throws Exception {
							LOG.error("XtextDocument and XtextResource have run out of sync:\n" 
											+ DiffUtil.diff(documentContent, resourceContent));
							LOG.error("Events: \n\t" + Joiner.on("\n\t").join(region.getDocumentEvents()));
							LOG.error("ReplaceRegion: \n\t'" + region + "'" );
							MessageDialog.openError(
									Display.getCurrent().getActiveShell(),
									"XtextReconcilerDebugger",
									"XtextDocument and XtextResource have run out of sync."
											+ "\n\nSee log for details.");
						}
						
					}.syncExec();
				} else {
					if (LOG.isDebugEnabled())
						LOG.debug("Model and document are in sync");
				}
			}
		}
	}
}
 
Example 7
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void moveUp(ICompositeNode node, ICompositeNode previousNode, IModificationContext context)
		throws BadLocationException {
	IXtextDocument document = context.getXtextDocument();
	String text = node.getText() + previousNode.getText();
	text = text.trim();
	remove(document, node);
	document.replace(previousNode.getOffset(), previousNode.getLength(), text);
}
 
Example 8
Source File: XtendHoverSerializer.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String caseXAbstractFeatureCall(XAbstractFeatureCall object) {
	ICompositeNode node = NodeModelUtils.findActualNodeFor(object);
	if (node != null)
		return node.getText();
	else
		return object.getFeature().getSimpleName();
}
 
Example 9
Source File: XtendHoverSerializer.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String caseXExpression(XExpression object) {
	if (object != null) {
		ICompositeNode node = NodeModelUtils.findActualNodeFor(object);
		if (node != null)
			return node.getText();
	}
	return "";
}
 
Example 10
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public IParseResult reparse(IParser parser, IParseResult previousParseResult, ReplaceRegion changedRegion) {
	if (isBrokenPreviousState(previousParseResult, changedRegion.getOffset())) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	ICompositeNode oldRootNode = previousParseResult.getRootNode();
	Iterator<ILeafNode> leafNodes = oldRootNode.getLeafNodes().iterator();
	ILeafNode leftNode = getLeftNode(leafNodes, changedRegion.getOffset());
	if (leftNode == null) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	ILeafNode rightNode = getRightNode(leafNodes, changedRegion.getEndOffset());
	if (rightNode == null) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	while(leafNodes.hasNext()) {
		if (leafNodes.next().getSyntaxErrorMessage() != null) {
			return fullyReparse(parser, previousParseResult, changedRegion);
		}
	}
	String originalText = oldRootNode.getText().substring(leftNode.getTotalOffset());
	StringBuilder newTextBuilder = new StringBuilder(originalText);
	changedRegion.shiftBy(-leftNode.getTotalOffset()).applyTo(newTextBuilder);
	String newText = newTextBuilder.toString();
	if (originalText.equals(newText)) {
		// nothing to do
		return previousParseResult;
	}
	int originalLength = rightNode.getTotalEndOffset() - leftNode.getTotalOffset();
	int expectedLength = originalLength - changedRegion.getLength() + changedRegion.getText().length();
	if (!isSameTokenSequence(originalText.substring(0, originalLength), newText, expectedLength)) {
		// different token sequence, cannot perform a partial parse run
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	
	PartialParsingPointers parsingPointers = calculatePartialParsingPointers(oldRootNode, leftNode, rightNode);
	ICompositeNode replaceMe = getReplacedNode(parsingPointers);
	if (replaceMe == null || replaceMe == oldRootNode || replaceMe.getOffset() == 0 && replaceMe.getEndOffset() == oldRootNode.getLength()) {
		return fullyReparse(parser, previousParseResult, changedRegion);
	}
	String reparseRegion = insertChangeIntoReplaceRegion(replaceMe, changedRegion);
	
	EObject oldSemanticElement = getOldSemanticElement(replaceMe, parsingPointers);
	if (oldSemanticElement == null)
		return fullyReparse(parser, previousParseResult, changedRegion);
	if (oldSemanticElement == replaceMe.getParent().getSemanticElement()) {
		throw new IllegalStateException("oldParent == oldElement");
	}
	
	IParseResult newParseResult = doParseRegion(parser, parsingPointers, replaceMe, reparseRegion);
	if (newParseResult == null) {
		throw new IllegalStateException("Could not perform a partial parse operation");
	}
	
	replaceOldSemanticElement(oldSemanticElement, previousParseResult, newParseResult);
	nodeModelBuilder.replaceAndTransferLookAhead(replaceMe, newParseResult.getRootNode());
	((ParseResult) newParseResult).setRootNode(oldRootNode);
	StringBuilder builder = new StringBuilder(oldRootNode.getText());
	changedRegion.applyTo(builder);
	nodeModelBuilder.setCompleteContent(oldRootNode, builder.toString());
	return newParseResult;
}
 
Example 11
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
public String insertChangeIntoReplaceRegion(final ICompositeNode rootNode, final ReplaceRegion region) {
  final StringBuilder builder = new StringBuilder(rootNode.getText());
  region.shiftBy(0 - rootNode.getTotalOffset()).applyTo(builder);
  return builder.toString();
}
 
Example 12
Source File: SerializeTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private void checkSerialize(String model, int expectedErrors) throws Exception {
	ICompositeNode node = getRootNodeAndExpect(model, expectedErrors);
	String serialize = node.getText();
	assertEquals(model, serialize);
}
 
Example 13
Source File: AbstractPartialParserTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected String getReparseRegion(PartialParsingPointers parsingPointers) {
	ICompositeNode replaceRootNode = parsingPointers.getDefaultReplaceRootNode();
	return replaceRootNode.getText();
}
 
Example 14
Source File: PartialParsingHelper.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public String insertChangeIntoReplaceRegion(ICompositeNode rootNode, ReplaceRegion region) {
	final StringBuilder builder = new StringBuilder(rootNode.getText());
	region.shiftBy(0-rootNode.getTotalOffset()).applyTo(builder);
	return builder.toString();
}
 
Example 15
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected String insertChangeIntoReplaceRegion(ICompositeNode rootNode, ReplaceRegion region) {
	final StringBuilder builder = new StringBuilder(rootNode.getText());
	region.shiftBy(0-rootNode.getTotalOffset()).applyTo(builder);
	return builder.toString();
}
 
Example 16
Source File: BslValidator.java    From ru.capralow.dt.bslls.validator with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void validateModule(EObject object, CustomValidationMessageAcceptor messageAcceptor,
    CancelIndicator monitor)
{
    if (monitor.isCanceled())
        return;

    IV8Project v8Project = projectManager.getProject(object);
    if (v8Project == null)
        return;

    ProjectContext projectContext = projectsContext.get(v8Project.getProject());
    if (projectContext == null)
        return;

    long startTime = System.currentTimeMillis();
    BslValidatorPlugin.log(
        BslValidatorPlugin.createInfoStatus(BSL_LS_PREFIX.concat("Начало передачи текста модуля"))); //$NON-NLS-1$

    Module module = (Module)object;
    IFile moduleFile =
        ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(EcoreUtil.getURI(module).toPlatformString(true)));

    ICompositeNode node = NodeModelUtils.findActualNodeFor(module);
    String objectText = node.getText();

    Document doc = new Document(objectText);

    DocumentContext documentContext =
        projectContext.bslServerContext.addDocument(moduleFile.getLocationURI(), objectText);

    long computeStartTime = System.currentTimeMillis();
    List<Diagnostic> diagnostics = projectContext.diagnosticProvider.computeDiagnostics(documentContext);
    long computeDifference = System.currentTimeMillis() - computeStartTime;
    int findNodeAmount = diagnostics.size();
    for (Diagnostic diagnostic : diagnostics)
    {
        if (monitor.isCanceled())
            break;

        registerIssue(object, messageAcceptor, diagnostic, documentContext, doc, projectContext);

    }

    projectContext.diagnosticProvider.clearComputedDiagnostics(documentContext);
    documentContext.clearSecondaryData();

    long difference = System.currentTimeMillis() - startTime;

    if (difference > 10000)
        BslValidatorPlugin.log(BslValidatorPlugin.createInfoStatus(
            BSL_LS_PREFIX.concat("URI модуля длительной проверки: ").concat(moduleFile.getLocation().toString()))); //$NON-NLS-1$

    String differenceText = MessageFormat.format("(всего:{0}сек,анализ:{1}сек/{2}проб)", //$NON-NLS-1$
        Long.toString(difference / 1000), Long.toString(computeDifference / 1000), String.valueOf(findNodeAmount));

    BslValidatorPlugin.log(BslValidatorPlugin.createInfoStatus(
        BSL_LS_PREFIX.concat("Окончание передачи текста модуля ").concat(differenceText))); //$NON-NLS-1$
}
 
Example 17
Source File: Utils.java    From sarl with Apache License 2.0 3 votes vote down vote up
/** Replies the original code for the given Ecore object.
 *
 * <p>The replied code is the SARL code within the source file. It's format depends on
 * how the developer has input it.
 *
 * <p>This function does:<ul>
 * <li>replace any sequence of "new line" characters by a space character, and</li>
 * <li>trim the whitespaces.</li>
 * </ul>
 *
 * @param object the object to search the code for.
 * @return the SARL code for the given object, or {@code null} if no code was found.
 * @since 0.7
 */
public static String getSarlCodeFor(EObject object) {
	final ICompositeNode node = NodeModelUtils.getNode(object);
	if (node != null) {
		String text = node.getText();
		if (text != null) {
			text = text.trim();
			text = text.replaceAll("[\n\r\f]+", " "); //$NON-NLS-1$//$NON-NLS-2$
		}
		return Strings.emptyToNull(text);
	}
	return null;
}