Java Code Examples for org.eclipse.xtext.nodemodel.INode#getLength()

The following examples show how to use org.eclipse.xtext.nodemodel.INode#getLength() . 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: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToMain(JSONStringLiteral mainModuleJsonLiteral) {
	String mainPath = mainModuleJsonLiteral.getValue();
	if (!Strings.isNullOrEmpty(mainPath)) {
		URI packageJsonLoc = mainModuleJsonLiteral.eResource().getURI();
		IN4JSProject project = model.findProject(packageJsonLoc).orNull();
		INode node = NodeModelUtils.getNode(mainModuleJsonLiteral);

		if (project != null && node != null) {
			Region region = new Region(node.getOffset() + 1, node.getLength() - 2);
			SafeURI<?> mainResolvedPath = project.getLocation().resolve(mainPath);
			if (mainResolvedPath.exists()) {
				return Tuples.pair(mainResolvedPath, region);
			}
		}
	}

	return null;
}
 
Example 2
Source File: ValueSerializer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String serialize(INode node) {
	if (node instanceof ILeafNode)
		return ((ILeafNode) node).getText();
	else {
		StringBuilder builder = new StringBuilder(node.getLength());
		boolean hiddenSeen = false;
		for(ILeafNode leaf: node.getLeafNodes()) {
			if (!leaf.isHidden()) {
				if (hiddenSeen && builder.length() > 0)
					builder.append(' ');
				builder.append(leaf.getText());
				hiddenSeen = false;
			} else {
				hiddenSeen = true;
			}
		}
		return builder.toString();
	}
}
 
Example 3
Source File: DotHtmlLabelValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBasedError(String issueCode, String message,
		EObject object, EStructuralFeature feature, String[] issueData) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(object, feature);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	getMessageAcceptor().acceptError(message, object, offset, length,
			issueCode, issueData);
}
 
Example 4
Source File: DotStyleValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBaseError(String issueCode, String message,
		StyleItem styleItem, Context attributeContext) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(styleItem,
			StylePackage.Literals.STYLE_ITEM__NAME);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	// the issueData will be evaluated by the quickfixes
	String[] issueData = { issueCode, styleItem.getName(),
			attributeContext.toString() };
	getMessageAcceptor().acceptError(message, styleItem, offset, length,
			issueCode, issueData);
}
 
Example 5
Source File: DotStyleValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBasedWarning(String issueCode, String message,
		StyleItem styleItem) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(styleItem,
			StylePackage.Literals.STYLE_ITEM__NAME);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	// the issueData will be evaluated by the quickfixes
	List<String> issueData = new ArrayList<>();
	issueData.add(issueCode);
	issueData.add(styleItem.getName());
	issueData.addAll(styleItem.getArgs());

	getMessageAcceptor().acceptWarning(message, styleItem, offset, length,
			issueCode, issueData.toArray(new String[0]));
}
 
Example 6
Source File: DotAutoEditStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private HtmlContent findContentAtOffset(List<HtmlContent> contents,
		int offset) {
	HtmlContent result = null;

	for (HtmlContent content : contents) {
		HtmlTag tag = content.getTag();
		if (tag != null) {
			INode node = NodeModelUtils.getNode(content);
			if (node.getOffset() <= offset
					&& offset <= (node.getOffset() + node.getLength())) {
				if (result == null) {
					result = content;
				}
			}

			HtmlContent result2 = findContentAtOffset(tag.getChildren(),
					offset);
			if (result2 != null) {
				result = result2;
			}
		}
	}

	return result;
}
 
Example 7
Source File: EmitterNodeIterator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public EmitterNodeIterator(INode fromNode, INode toNode, boolean passAbsorber, boolean allowHidden) {
	if (fromNode != null) {
		this.iterator = new NodeIterator(fromNode);
		this.passAbsorber = passAbsorber;
		if (toNode != null) {
			if (toNode == fromNode)
				this.end = toNode.getOffset() + toNode.getLength();
			else if (toNode.getOffset() < fromNode.getOffset())
				this.end = toNode.getOffset() + toNode.getLength();
			else
				this.end = toNode.getOffset();
		} else
			this.end = Integer.MAX_VALUE;
		this.allowHidden = allowHidden;
		next();
	}
}
 
Example 8
Source File: SolidityHyperlinkHelper.java    From solidity-ide with Eclipse Public License 1.0 6 votes vote down vote up
protected void createImportedNamespacesHyperlinksByOffset(XtextResource resource, int offset,
		IHyperlinkAcceptor acceptor) {
	INode node = NodeModelUtils.findLeafNodeAtOffset(resource.getParseResult().getRootNode(), offset);
	if (node != null) {			
		List<INode> importNodes = NodeModelUtils.findNodesForFeature(node.getSemanticElement(), SolidityPackage.Literals.IMPORT_DIRECTIVE__IMPORTED_NAMESPACE);
		if (importNodes != null && !importNodes.isEmpty()) {
			for (INode importNode : importNodes) {
				ImportDirective importElement = (ImportDirective) importNode.getSemanticElement();
				URI targetURI = getFileURIOfImport(importElement);
				XtextHyperlink result = getHyperlinkProvider().get();
				result.setURI(targetURI);
				Region region = new Region(importNode.getOffset(), importNode.getLength());
				result.setHyperlinkRegion(region);
				result.setHyperlinkText(targetURI.toString());
				acceptor.accept(result);
			}
		}
	}
}
 
Example 9
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToProjectProperty(NameValuePair nvpDependency) {
	String projectName = nvpDependency.getName();
	SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));
	if (pdu != null) {
		List<INode> node = NodeModelUtils.findNodesForFeature(nvpDependency,
				JSONPackage.Literals.NAME_VALUE_PAIR__NAME);

		if (!node.isEmpty()) {
			INode nameNode = node.get(0);
			Region region = new Region(nameNode.getOffset() + 1, nameNode.getLength() - 2);

			return Tuples.pair(pdu, region);
		}
	}

	return null;
}
 
Example 10
Source File: ImportRegionHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns with the length of the node including all hidden leaf nodes but the {@link LeafNodeWithSyntaxError} one,
 * that was created for the automatic semicolon insertion.
 */
private static int getLengthWithoutAutomaticSemicolon(final INode node) {
	if (node instanceof ILeafNode) {
		return node.getLength();
	}

	int length = 0;
	for (INode leafNode : ((ICompositeNode) node).getLeafNodes()) {
		if (!isIgnoredSyntaxErrorNode(leafNode, SEMICOLON_INSERTED)) {
			length += leafNode.getLength();
		}
	}

	return length;
}
 
Example 11
Source File: AbstractDiagnostic.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public int getLength() {
	INode node = getNode();
	if (node != null)
		return node.getLength();
	return 1;
}
 
Example 12
Source File: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void completeJavaTypes(ContentAssistContext context, EReference reference, boolean forced,
		IValueConverter<String> valueConverter, ITypesProposalProvider.Filter filter,
		ICompletionProposalAcceptor acceptor) {
	String prefix = context.getPrefix();
	if (prefix.length() > 0) {
		if (Character.isJavaIdentifierStart(context.getPrefix().charAt(0))) {
			if (!forced && getXbaseCrossReferenceProposalCreator().isShowSmartProposals()) {
				if (!prefix.contains(".") && !prefix.contains("::") && !Character.isUpperCase(prefix.charAt(0)))
					return;
			}
			typeProposalProvider.createTypeProposals(this, context, reference, filter, valueConverter, acceptor);
		}
	} else {
		if (forced || !getXbaseCrossReferenceProposalCreator().isShowSmartProposals()) {
			INode lastCompleteNode = context.getLastCompleteNode();
			if (lastCompleteNode instanceof ILeafNode && !((ILeafNode) lastCompleteNode).isHidden()) {
				if (lastCompleteNode.getLength() > 0 && lastCompleteNode.getTotalEndOffset() == context.getOffset()) {
					String text = lastCompleteNode.getText();
					char lastChar = text.charAt(text.length() - 1);
					if (Character.isJavaIdentifierPart(lastChar)) {
						return;
					}
				}
			}
			typeProposalProvider.createTypeProposals(this, context, reference, filter, valueConverter, acceptor);
		}
	}
}
 
Example 13
Source File: XbaseHyperLinkHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isNameNode(EObject element, EStructuralFeature feature, ILeafNode node) {
	List<INode> nameNode = NodeModelUtils.findNodesForFeature(element, feature);
	for (INode iNode : nameNode) {
		if (iNode.getOffset() <= node.getOffset() && iNode.getLength()>= node.getLength()) {
			return true;
		}
	}
	return false;
}
 
Example 14
Source File: ExpressionUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return the smallest single expression containing the selection.  
 */
public XExpression findSelectedExpression(XtextResource resource, ITextSelection selection) {
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ICompositeNode rootNode = parseResult.getRootNode();
		INode node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset());
		if (node == null) {
			return null;
		}
		if (isHidden(node)) {
			if (selection.getLength() > node.getLength()) {
				node = NodeModelUtils.findLeafNodeAtOffset(rootNode, node.getEndOffset());
			} else {
				node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset() - 1);
			}
		} else if (node.getOffset() == selection.getOffset() && !isBeginOfExpression(node)) { 
			node = NodeModelUtils.findLeafNodeAtOffset(rootNode, selection.getOffset() - 1);
		}
		if(node != null) {
			EObject currentSemanticElement = NodeModelUtils.findActualSemanticObjectFor(node);
			while (!(contains(currentSemanticElement, node, selection) && currentSemanticElement instanceof XExpression)) {
				node = nextNodeForFindSelectedExpression(currentSemanticElement, node, selection);
				if(node == null)
					return null;
				currentSemanticElement = NodeModelUtils.findActualSemanticObjectFor(node);
			}
			return (XExpression) currentSemanticElement;
		}
	}
	return null;
}
 
Example 15
Source File: DotHtmlLabelRenameStrategy.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void createDeclarationUpdates(String newName,
		ResourceSet resourceSet,
		IRefactoringUpdateAcceptor updateAcceptor) {
	super.createDeclarationUpdates(newName, resourceSet, updateAcceptor);

	// perform renaming of the dependent element
	URI resourceURI = getTargetElementOriginalURI().trimFragment();

	if (targetElement instanceof HtmlTag) {
		HtmlTag htmlTag = (HtmlTag) targetElement;
		if (!htmlTag.isSelfClosing()) {
			List<INode> nodes = NodeModelUtils.findNodesForFeature(htmlTag,
					HtmllabelPackage.Literals.HTML_TAG__CLOSE_NAME);
			if (nodes.size() == 1) {
				INode node = nodes.get(0);
				TextEdit referenceEdit = new ReplaceEdit(node.getOffset(),
						node.getLength(), newName);
				updateAcceptor.accept(resourceURI, referenceEdit);
			} else {
				System.err.println(
						"Exact 1 node is expected for the name of the html closing tag, but got " //$NON-NLS-1$
								+ nodes.size());
			}

		}
	}
}
 
Example 16
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToDependencySection(NameValuePair projectNameInValue) {
	JSONStringLiteral jsonValue = (JSONStringLiteral) projectNameInValue.getValue();
	String projectName = jsonValue.getValue();
	SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));

	if (pdu != null) {
		INode valueNode = NodeModelUtils.getNode(jsonValue);
		Region region = new Region(valueNode.getOffset() + 1, valueNode.getLength() - 2);

		return Tuples.pair(pdu, region);
	}
	return null;
}
 
Example 17
Source File: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToRequiredRTLibs(JSONStringLiteral mainModuleJsonLiteral) {
	String projectName = mainModuleJsonLiteral.getValue();
	if (!Strings.isNullOrEmpty(projectName)) {
		SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));
		INode node = NodeModelUtils.getNode(mainModuleJsonLiteral);

		if (pdu != null && node != null) {
			Region region = new Region(node.getOffset() + 1, node.getLength() - 2);

			return Tuples.pair(pdu, region);
		}
	}

	return null;
}
 
Example 18
Source File: DotArrowTypeValidator.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
private void reportRangeBasedWarning(String issueCode, String message,
		EObject object, EStructuralFeature feature) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(object, feature);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	String code = null;
	// the issueData will be evaluated by the quickfixes
	List<String> issueData = new ArrayList<>();
	issueData.add(issueCode);
	switch (issueCode) {
	case DEPRECATED_ARROW_SHAPE:
		DeprecatedArrowShape arrowShape = (DeprecatedArrowShape) object;
		issueData.add(arrowShape.getShape().toString());
		break;
	case INVALID_ARROW_SHAPE_MODIFIER:
		if (ArrowtypePackage.Literals.ARROW_SHAPE__OPEN == feature) {
			issueData.add("o");
		}
		if (ArrowtypePackage.Literals.ARROW_SHAPE__SIDE == feature) {
			issueData.add(((ArrowShape) object).getSide());
		}
		issueData.add(Integer.toString(offset));
	default:
		break;
	}

	getMessageAcceptor().acceptWarning(message, object, offset, length,
			code, issueData.toArray(new String[0]));
}
 
Example 19
Source File: PackageImportHyperlinkHelper.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected IHyperlink createHyperlink(INode node, final PackageImport pkgImport) {
	XtextHyperlink result = getHyperlinkProvider().get();
	result.setURI(pkgImport.getFileURI());
	Region region = new Region(node.getOffset(), node.getLength());
	result.setHyperlinkRegion(region);
	result.setHyperlinkText(pkgImport.getUri().toString());
	return result;
}
 
Example 20
Source File: PackageJsonChangeProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns change instance to set the ProjectType to the given value.
 *
 * @param pckJsonResource
 *            The package.json resource
 * @param projectType
 *            The project type to set
 * @param projectDescription
 *            The project description object of the package.json
 */
public static IAtomicChange setProjectType(Resource pckJsonResource, ProjectType projectType,
		ProjectDescription projectDescription) {

	URI uri = pckJsonResource.getURI();
	String newProjectTypeInQuotations = "\"" + projectType.getName().toLowerCase() + "\"";

	List<JSONStringLiteral> pairs = PackageJsonUtils.findNameValuePairs(pckJsonResource,
			PackageJsonProperties.PROJECT_TYPE, JSONStringLiteral.class);

	INode prjTypeNode = null;
	if (!pairs.isEmpty()) {
		JSONStringLiteral jsonStringLiteral = pairs.get(0);
		prjTypeNode = NodeModelUtils.findActualNodeFor(jsonStringLiteral);
	}

	if (prjTypeNode == null) {
		// Append a new entry
		List<JSONObject> n4jss = PackageJsonUtils.findNameValuePairs(pckJsonResource, PackageJsonProperties.N4JS,
				JSONObject.class);

		if (!n4jss.isEmpty()) {
			prjTypeNode = NodeModelUtils.findActualNodeFor(n4jss.get(0));
			int location = (prjTypeNode == null) ? 0 : prjTypeNode.getEndOffset();

			String name = PackageJsonProperties.PROJECT_TYPE.name;
			String nameValuePair = "\n" + name + ": " + newProjectTypeInQuotations + ((location == 0) ? "\n" : "");
			return new Replacement(uri, location, 0, nameValuePair);
		}
	} else {
		// Replace existing entry
		return new Replacement(uri, prjTypeNode.getOffset(), prjTypeNode.getLength(), newProjectTypeInQuotations);
	}

	return new Replacement(uri, 0, 0, "");
}