Java Code Examples for org.eclipse.xtext.naming.QualifiedName#getFirstSegment()

The following examples show how to use org.eclipse.xtext.naming.QualifiedName#getFirstSegment() . 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: ImportsFactory.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Creates a new named import of 'name' from 'module' */
private ImportDeclaration createNamedImport(String name, IN4JSProject contextProject, TExportableElement te,
		Adapter nodelessMarker) {
	TModule tmodule = te.getContainingModule();
	IN4JSProject targetProject = core.findProject(te.eResource().getURI()).orNull();
	String moduleQN;
	if (targetProject != null && tmodule.getQualifiedName().toString().equals(targetProject.getMainModule())) {
		// If the project has a main module, use project import instead.
		moduleQN = targetProject.getProjectName().getRawName();
	} else {
		// Standard case
		moduleQN = te.getContainingModule().getQualifiedName();
	}
	QualifiedName qn = qualifiedNameConverter.toQualifiedName(moduleQN);
	N4JSProjectName firstSegment = new N4JSProjectName(qn.getFirstSegment());
	IN4JSProject project = ImportSpecifierUtil.getDependencyWithID(firstSegment, contextProject);

	return createImportDeclaration(qn, name, project, nodelessMarker, this::addNamedImport);
}
 
Example 2
Source File: ImportsFactory.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Creates a new default import with name 'name' from object description. */
private ImportDeclaration createNamespaceImport(String name, IN4JSProject contextProject,
		TExportableElement te,
		Adapter nodelessMarker) {
	String moduleQN = te.getContainingModule().getQualifiedName();
	QualifiedName qn = qualifiedNameConverter.toQualifiedName(moduleQN);
	N4JSProjectName firstSegment = new N4JSProjectName(qn.getFirstSegment());

	IN4JSProject project = ImportSpecifierUtil.getDependencyWithID(firstSegment, contextProject);
	if (project == null) {
		IN4JSProject projectByNamespace = ImportSpecifierUtil.getDependencyWithID(new N4JSProjectName(name),
				contextProject);
		IN4JSProject projectByEObject = core.findProject(te.eResource().getURI()).orNull();

		if (projectByNamespace != null && projectByEObject != null
				&& projectByNamespace.getLocation().equals(projectByEObject.getLocation()))
			project = projectByNamespace;
	}
	return createImportDeclaration(qn, name, project, nodelessMarker, this::addNamespaceImport);
}
 
Example 3
Source File: NestedTypeAwareImportNormalizer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private QualifiedName internalResolve(QualifiedName relativeName) {
	if (relativeName.getSegmentCount() != 1) {
		throw new IllegalArgumentException(relativeName.toString());
	}
	String lastImportSegment = getImportedNamespacePrefix().getLastSegment();
	int importDollarIndex = lastImportSegment.lastIndexOf('$');
	if (importDollarIndex != -1) {
		lastImportSegment = lastImportSegment.substring(importDollarIndex + 1);
	}
	String singleSegment = relativeName.getFirstSegment();
	if (lastImportSegment.equals(singleSegment)) {
		return getImportedNamespacePrefix();
	}
	if (singleSegment.startsWith(lastImportSegment) && singleSegment.charAt(lastImportSegment.length()) == '$') {
		if (importDollarIndex == -1)
			return getImportedNamespacePrefix().skipLast(1).append(relativeName);
		else {
			String resolvedLastSegment = getImportedNamespacePrefix().getLastSegment() + singleSegment.substring(lastImportSegment.length());
			return getImportedNamespacePrefix().skipLast(1).append(resolvedLastSegment);
		}
	}
	return null;
}
 
Example 4
Source File: CreateMemberQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected String getOperatorMethodName(XAbstractFeatureCall call) {
	StringBuilder sb = new StringBuilder();
	for(INode node: NodeModelUtils.findNodesForFeature(call, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE)) {
		for(ILeafNode leafNode: node.getLeafNodes()) {
			if(!leafNode.isHidden()) {
				sb.append(leafNode.getText());
			}
		}
	}
	
	String symbol = sb.toString();
	if(!symbol.isEmpty()) {
		QualifiedName methodName = operatorMapping.getMethodName(QualifiedName.create(symbol));
		if(methodName != null)
			return methodName.getFirstSegment();
	}
	
	return null;
}
 
Example 5
Source File: NestedTypeLiteralScope.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected List<IEObjectDescription> getLocalElementsByName(QualifiedName name) {
	XAbstractFeatureCall featureCall = getFeatureCall();
	if (featureCall.isExplicitOperationCallOrBuilderSyntax())
		return Collections.emptyList();
	if (rawEnclosingType instanceof JvmDeclaredType && name.getSegmentCount() == 1) {
		String singleSegment = name.getFirstSegment();
		List<String> lookup = Collections.singletonList(singleSegment);
		if (singleSegment.indexOf('$') != -1) {
			lookup = Strings.split(singleSegment, '$');
		}
		JvmType result = findNestedType((JvmDeclaredType)rawEnclosingType, lookup.iterator());
		if (result != null) {
			IEObjectDescription description = EObjectDescription.create(name, result);
			return Collections.<IEObjectDescription>singletonList(new TypeLiteralDescription(description, enclosingType, isVisible(result)));
		}
	}
	return Collections.emptyList();
}
 
Example 6
Source File: ImportsFactory.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Creates a new default import with name 'name' from object description. */
private ImportDeclaration createDefaultImport(String name, IN4JSProject contextProject, TExportableElement te,
		Adapter nodelessMarker) {
	String moduleQN = te.getContainingModule().getQualifiedName();
	QualifiedName qn = qualifiedNameConverter.toQualifiedName(moduleQN);
	N4JSProjectName firstSegment = new N4JSProjectName(qn.getFirstSegment());
	IN4JSProject project = ImportSpecifierUtil.getDependencyWithID(firstSegment, contextProject);

	return createImportDeclaration(qn, name, project, nodelessMarker, this::addDefaultImport);
}
 
Example 7
Source File: AbstractKnownTypesScope.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected IEObjectDescription doGetSingleElement(QualifiedName name) {
	String firstSegment = name.getFirstSegment();
	int dollar = firstSegment.indexOf('$');
	if (dollar > 0) {
		firstSegment = firstSegment.substring(0, dollar);
	}
	return doGetSingleElement(name, firstSegment, dollar);
}
 
Example 8
Source File: TypeParameterScope.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected IEObjectDescription doGetSingleElement(QualifiedName name) {
	if (name.getSegmentCount() == 1) {
		String singleSegment = name.getFirstSegment();
		for(int i = 0; i < typeParameters.size(); i++) {
			List<JvmTypeParameter> chunk = typeParameters.get(i);
			for(int j = 0; j < chunk.size(); j++) {
				JvmTypeParameter candidate = chunk.get(j);
				if (singleSegment.equals(candidate.getSimpleName())) {
					return EObjectDescription.create(name, candidate);
				}	
			}
		}
	}
	return null;
}
 
Example 9
Source File: FunctionIDValueConverter.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toString(String value) throws ValueConverterException {
	QualifiedName operatorName = operatorMapping.getOperator(QualifiedName.create(value));
	if (operatorName != null) {
		return operatorName.getFirstSegment();
	}
	return getDelegate().toString(value);
}
 
Example 10
Source File: FunctionIDValueConverter.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toValue(String string, INode node) throws ValueConverterException {
	QualifiedName operatorMethodName = operatorMapping.getMethodName(QualifiedName.create(string));
	if (operatorMethodName != null) {
		return operatorMethodName.getFirstSegment();
	}
	return (String) getDelegate().toValue(string, node);
}
 
Example 11
Source File: NestedTypesScope.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Iterable<IEObjectDescription> getLocalElementsByName(QualifiedName name) {
	List<JvmDeclaredType> nestedTypeDeclarators = session.getNestedTypeDeclarators();
	if (nestedTypeDeclarators.isEmpty())
		return Collections.emptyList();
	Iterator<JvmDeclaredType> iterator = nestedTypeDeclarators.iterator();
	String simpleName = name.getFirstSegment();
	List<IEObjectDescription> result = null;
	if (name.getSegmentCount() == 1) {
		Set<JvmDeclaredType> nestedTypesSet = new LinkedHashSet<>();
		while(iterator.hasNext()) {
			JvmDeclaredType declarator = iterator.next();
			Iterable<JvmDeclaredType> nestedTypes = declarator.findAllNestedTypesByName(simpleName);
			CollectionExtensions.addAll(nestedTypesSet, nestedTypes);
		}
		if (!nestedTypesSet.isEmpty()) {
			result = addDescriptions(name, 0, nestedTypesSet, result);
		}
	}
	if (result == null && name.getSegmentCount() == 1 && simpleName.indexOf('$') > 0) {
		QualifiedName splitted = QualifiedName.create(Strings.split(simpleName, '$'));
		return getLocalElementsByName(splitted);
	}
	if (result != null)
		return result;
	return Collections.emptyList();
}
 
Example 12
Source File: N4JSImportedNamespaceAwareLocalScopeProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected IScope getResourceScope(Resource res, EReference reference) {
	if (res == null) {
		return IScope.NULLSCOPE;
	}
	EObject context = res.getContents().get(0);

	// ||-- changed super-impl here:
	// IDE-662 filtering ArgumentsType & EnumBaseType from globalScobe, since it is a VirtualBaseType.
	Predicate<IEObjectDescription> filter = p -> {
		QualifiedName name = p.getName();
		if (name.getSegmentCount() == 1) {
			String singleSegment = name.getFirstSegment();
			return !("ArgumentsType".equals(singleSegment) || "EnumBaseType".equals(singleSegment));
		}
		return true;
	};
	IScope globalScope = getGlobalScope(res, reference, filter);
	// -- done change --||

	List<ImportNormalizer> normalizers = getImplicitImports(isIgnoreCase(reference));

	// IDE-1735 adding support for static-polyfills:
	TModule module = (TModule) res.getContents().get(1);
	if (module.isStaticPolyfillModule()) { // limit to situations of resources, that contain at least
		// one @StaticPolyfill
		normalizers.add(createImportedNamespaceResolver(
				module.getQualifiedName() + N4JSQualifiedNameConverter.DELIMITER + "*", false));
	}

	if (!normalizers.isEmpty()) {
		globalScope = createImportScope(globalScope, normalizers, null, reference.getEReferenceType(),
				isIgnoreCase(reference));
	}
	IScope resScope = getResourceScope(globalScope, context, reference);
	return resScope;
}
 
Example 13
Source File: ImportSpecifierUtil.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convenience method over {@link ImportSpecifierUtil#computeImportType(QualifiedName, boolean, IN4JSProject)}
 */
public static ModuleSpecifierForm computeImportType(QualifiedName name, IN4JSProject project) {
	final N4JSProjectName firstSegment = new N4JSProjectName(name.getFirstSegment());
	final IN4JSProject targetProject = getDependencyWithID(firstSegment, project);
	final boolean firstSegmentIsProjectName = targetProject != null;
	return ImportSpecifierUtil.computeImportType(name, firstSegmentIsProjectName, targetProject);
}
 
Example 14
Source File: ProjectImportEnablingScope.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convenience method over {@link ImportSpecifierUtil#computeImportType(QualifiedName, boolean, IN4JSProject)}
 */
private ModuleSpecifierForm computeImportType(QualifiedName name, IN4JSProject project) {
	final String firstSegment = name.getFirstSegment();
	final IN4JSProject targetProject = findProject(new N4JSProjectName(firstSegment), project);
	final boolean firstSegmentIsProjectName = targetProject != null;
	return ImportSpecifierUtil.computeImportType(name, firstSegmentIsProjectName, targetProject);
}
 
Example 15
Source File: XtendProposalProvider.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void completeMember_Name(final EObject model, Assignment assignment, final ContentAssistContext context,
		final ICompletionProposalAcceptor acceptor) {
	if (announceProcessing(Lists.newArrayList("completeMember_Name", model, assignment.getFeature()))) {
		EObject previousModel = context.getPreviousModel();
		if (previousModel instanceof XExpression) {
			if (!(previousModel instanceof XBlockExpression)) {
				return;
			}
		}
		if (model instanceof XtendField) {
			//TODO go up type hierarchy and collect all local fields
			final List<XtendField> siblings = EcoreUtil2.getSiblingsOfType(model, XtendField.class);
			Set<String> alreadyTaken = Sets.newHashSet();
			for(XtendField sibling: siblings) {
				alreadyTaken.add(sibling.getName());
			}
			alreadyTaken.addAll(getAllKeywords());
			completions.getVariableProposals(model, XtendPackage.Literals.XTEND_FIELD__TYPE,
					VariableType.INSTANCE_FIELD, alreadyTaken, new JdtVariableCompletions.CompletionDataAcceptor() {
						@Override
						public void accept(String replaceText, StyledString label, Image img) {
							acceptor.accept(createCompletionProposal(replaceText, label, img, context));
						}
					});
		} else if (model instanceof XtendFunction) {
			for(QualifiedName operator: operatorMapping.getOperators()) {
				StyledString displayString = new StyledString(operator.getFirstSegment());
				displayString.append(" " + operatorMapping.getMethodName(operator), StyledString.DECORATIONS_STYLER);
				acceptor.accept(createCompletionProposal(
						operator.getFirstSegment(),
						displayString,
						getImage(model),
						context));
			}
			super.completeMember_Name(model, assignment, context, acceptor);
		} else {
			super.completeMember_Name(model, assignment, context, acceptor);
		}
	}
}
 
Example 16
Source File: AbstractMemberScope.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected IEObjectDescription getSingleLocalElementByName(QualifiedName name) {
	if (name.getSegmentCount() != 1) {
		return null;
	}
	final String nameAsString = name.getFirstSegment();

	// both read/write required
	if (ExpressionExtensions.isBothReadFromAndWrittenTo(context)) {
		TMember reader = findMember(nameAsString, false, staticAccess);
		TMember writer = findMember(nameAsString, true, staticAccess);
		if (null == reader && null == writer) {
			// will be caught as error "Could not resolve reference"
			return null;
		}
		if (null == reader) {
			return new UnsatisfiedRWAccessDescription(EObjectDescription.create(writer.getName(), writer), true);
		}
		if (null == writer) {
			return new UnsatisfiedRWAccessDescription(EObjectDescription.create(reader.getName(), reader), false);
		}
		// pick arbitrarily the setter
		return createSingleElementDescription(writer);
	}

	// either read or write requirement that moreover is satisfied
	final boolean accessForWriteOperation = ExpressionExtensions.isLeftHandSide(context);
	TMember existingMember = findMember(nameAsString, accessForWriteOperation, staticAccess);
	if (existingMember != null) {
		return createSingleElementDescription(existingMember);
	}

	// wrong read/write
	existingMember = findMember(nameAsString, !accessForWriteOperation, staticAccess);
	if (existingMember != null) {

		// allowed special case: writing in the ctor to a final field that lacks init value
		final boolean isAssOfFinalInCtor = N4JSASTUtils
				.isSemiLegalAssignmentToFinalFieldInCtor(context.eContainer(), existingMember);
		final boolean isLegalAssOfFinalInCtor = isAssOfFinalInCtor && !((TField) existingMember).isHasExpression();
		if (isLegalAssOfFinalInCtor) {
			return createSingleElementDescription(existingMember);
		}

		// allowed special case: accessing a setter for read operation in context of structural field init typing
		if (structFieldInitMode && !accessForWriteOperation && existingMember instanceof TSetter) {
			return createSingleElementDescription(existingMember);
		}

		// allowed special case: wrong read/write in a mode other than N4JS
		if (jsVariantHelper.allowWrongReadWrite(context)) { // cf. sec. 13.1
			return createSingleElementDescription(existingMember);
		}

		return new WrongWriteAccessDescription(
				EObjectDescription.create(existingMember.getName(), existingMember),
				accessForWriteOperation, isAssOfFinalInCtor);
	}

	// wrong static / non-static
	existingMember = findMember(nameAsString, accessForWriteOperation, !staticAccess);
	if (existingMember == null) {
		// if both read/write access and static access are wrong, we want to
		// complain (only) about "wrong static access" -> so include this case here
		existingMember = findMember(nameAsString, !accessForWriteOperation, !staticAccess);
	}
	if (existingMember != null && !isDynamicType) {
		return new WrongStaticAccessDescription(
				EObjectDescription.create(existingMember.getName(), existingMember),
				staticAccess);
	}

	return null;
}
 
Example 17
Source File: GamlNameConverter.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String toString(final QualifiedName qualifiedName) {
	return qualifiedName == null ? "" : qualifiedName.getFirstSegment();
}