org.eclipse.xtext.parser.ParseResult Java Examples

The following examples show how to use org.eclipse.xtext.parser.ParseResult. 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: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void replaceOldSemanticElement(EObject oldElement, IParseResult previousParseResult,
		IParseResult newParseResult) {
	EObject oldSemanticParentElement = oldElement.eContainer();
	if (oldSemanticParentElement != null) {
		EStructuralFeature feature = oldElement.eContainingFeature();
		if (feature.isMany()) {
			List featureValueList = (List) oldSemanticParentElement.eGet(feature);
			int index = featureValueList.indexOf(oldElement);
			unloadSemanticObject(oldElement);
			featureValueList.set(index, newParseResult.getRootASTElement());
		} else {
			unloadSemanticObject(oldElement);
			oldSemanticParentElement.eSet(feature, newParseResult.getRootASTElement());
		}
		((ParseResult) newParseResult).setRootASTElement(previousParseResult.getRootASTElement());
	} else {
		unloadSemanticObject(oldElement);
	}
}
 
Example #2
Source File: ResourceStorageLoadable.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void readNodeModel(StorageAwareResource resource, InputStream inputStream) throws IOException {
	SerializableNodeModel serializableNodeModel = new SerializableNodeModel(resource);
	// if this is a synthetic resource (i.e. tests or so, don't load the node model)
	if (!resource.getResourceSet().getURIConverter().exists(resource.getURI(),
			resource.getResourceSet().getLoadOptions())) {
		LOG.info("Skipping loading node model for synthetic resource " + resource.getURI());
		return;
	}
	String completeContent = CharStreams.toString(
			new InputStreamReader(resource.getResourceSet().getURIConverter().createInputStream(resource.getURI()),
					resource.getEncoding()));
	DeserializationConversionContext deserializationContext = new DeserializationConversionContext(resource,
			completeContent);
	serializableNodeModel.readObjectData(new DataInputStream(inputStream), deserializationContext);
	resource.setParseResult(new ParseResult(head(resource.getContents()), serializableNodeModel.root,
			deserializationContext.hasErrors()));
}
 
Example #3
Source File: AbstractContextualAntlrParser.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected IParseResult doParse(final String ruleName, final CharStream in, final NodeModelBuilder nodeModelBuilder, final int initialLookAhead) {
  final IParseResult parseResult = super.doParse(ruleName, in, nodeModelBuilder, initialLookAhead);
  if (delegate == null || parseResult.hasSyntaxErrors()) {
    return parseResult;
  }
  // If delegation was potentially used, we need to check for syntax errors in replaced nodes
  boolean hasError = false;
  Iterator<AbstractNode> nodeIterator = ((CompositeNode) parseResult.getRootNode()).basicIterator();
  while (nodeIterator.hasNext()) {
    AbstractNode node = nodeIterator.next();
    if (node.getSyntaxErrorMessage() != null) {
      hasError = true;
      break;
    }
  }
  if (hasError) {
    return new ParseResult(parseResult.getRootASTElement(), parseResult.getRootNode(), true);
  }
  return parseResult;
}
 
Example #4
Source File: ProxyCompositeNode.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Installs a proxy node model in the given resource which when accessed will {@link ResourceLoadMode#ONLY_NODE_MODEL demand-load} the real node model.
 *
 * @param resource
 *          resource, must not be {@code null}
 */
static void installProxyNodeModel(final Resource resource) {
  if (resource.getContents().isEmpty()) {
    return;
  }

  ArrayList<EObject> idToEObjectMap = Lists.newArrayList();
  EObject root = resource.getContents().get(0);

  ProxyCompositeNode rootNode = installProxyNodeModel(root, idToEObjectMap);
  idToEObjectMap.trimToSize();
  rootNode.idToEObjectMap = idToEObjectMap;

  if (resource instanceof XtextResource) {
    ((XtextResource) resource).setParseResult(new ParseResult(root, rootNode, false));
  }
}
 
Example #5
Source File: AbstractContextualAntlrParser.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IParseResult doParse(final Reader reader) {
  IParseResult parseResult = super.doParse(reader);
  if (parseResult.getRootASTElement() == null) {
    // Most of ASMD languages are not good with empty models, so create an empty root element
    AbstractRule rule = GrammarUtil.findRuleForName(grammarAccess.getGrammar(), getDefaultRuleName());
    EObject newRoot = getElementFactory().create(rule.getType().getClassifier());
    return new ParseResult(newRoot, parseResult.getRootNode(), true);
  }
  return parseResult;
}
 
Example #6
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 #7
Source File: DirectLinkingResourceStorageLoadable.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Read the node model from the given input stream.
 *
 * @param resource
 *          target resource, must not be {@code null}
 * @param inputStream
 *          input stream, must not be {@code null}
 * @param content
 *          corresponding source content as required by node model, must not be {@code null}
 * @throws IOException
 *           if an I/O exception occurred
 */
protected void readNodeModel(final StorageAwareResource resource, final InputStream inputStream, final String content) throws IOException {
  DeserializationConversionContext deserializationContext = new ProxyAwareDeserializationConversionContext(resource, content);
  DataInputStream dataIn = new DataInputStream(inputStream);
  SerializableNodeModel serializableNodeModel = new SerializableNodeModel(resource);
  serializableNodeModel.readObjectData(dataIn, deserializationContext);
  resource.setParseResult(new ParseResult(resource.getContents().get(0), serializableNodeModel.root, deserializationContext.hasErrors()));
}
 
Example #8
Source File: LazyLinkingResource2.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Sets the parse result for this resource.
 *
 * @param parseResult
 *          the parse result containing the EMF and Node model, must not be {@code null}
 * @param refreshSyntaxErrors
 *          whether diagnostics should be created for syntax errors
 */
@Override
public void setParseResult(final ParseResult parseResult, final boolean refreshSyntaxErrors) {
  setParseResult(parseResult);
  if (refreshSyntaxErrors) {
    addSyntaxErrors();
  }
}
 
Example #9
Source File: CustomN4JSParser.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * @param node
 *            the root node of the model to parse
 * @param startOffset
 *            the start offset to consider
 * @param endOffset
 *            the exclusive end offset
 * @param strict
 *            if true the parser will not use error recovery on the very last token of the input.
 * @return a collection of follow elements.
 */
public Collection<FollowElement> getFollowElements(INode node, int startOffset, int endOffset, boolean strict) {
	return getFollowElements(new ParseResult(null, (ICompositeNode) node, false), endOffset, strict);
}
 
Example #10
Source File: ILazyLinkingResource2.java    From dsl-devkit with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Sets the parse result for this resource.
 *
 * @param parseResult
 *          the parse result containing the EMF and Node model, must not be {@code null}
 * @param refreshSyntaxErrors
 *          whether diagnostics should be created for syntax errors
 */
void setParseResult(final ParseResult parseResult, final boolean refreshSyntaxErrors);