Java Code Examples for org.eclipse.xtext.common.types.JvmDeclaredType#getPackageName()

The following examples show how to use org.eclipse.xtext.common.types.JvmDeclaredType#getPackageName() . 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: ConstantConditionsInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private boolean isFromXbaseLibrary(final XAbstractFeatureCall it, final EvaluationContext context) {
  boolean _xblockexpression = false;
  {
    final JvmIdentifiableElement feature = this.getFeature(it, context);
    boolean _switchResult = false;
    boolean _matched = false;
    if (feature instanceof JvmMember) {
      _matched=true;
      JvmDeclaredType _declaringType = null;
      if (((JvmMember)feature)!=null) {
        _declaringType=((JvmMember)feature).getDeclaringType();
      }
      String _packageName = null;
      if (_declaringType!=null) {
        _packageName=_declaringType.getPackageName();
      }
      String _string = XImportSectionNamespaceScopeProvider.XBASE_LIB.toString();
      _switchResult = Objects.equal(_packageName, _string);
    }
    if (!_matched) {
      _switchResult = false;
    }
    _xblockexpression = _switchResult;
  }
  return _xblockexpression;
}
 
Example 2
Source File: AbstractMultiModeOutlineTreeProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private String createQualifier(JvmMember jvmMember) {
	String qualifier = null;
	if (jvmMember instanceof JvmFeature) {
		JvmDeclaredType declaringType = jvmMember.getDeclaringType();
		qualifier = getPackageFreeNameForType(declaringType);
	} else if (jvmMember instanceof JvmDeclaredType) {
		if (jvmMember.eContainer() instanceof JvmDeclaredType) {
			qualifier = getPackageFreeNameForType((JvmDeclaredType) jvmMember.eContainer());
		} else {
			JvmDeclaredType jvmDeclaredType = (JvmDeclaredType) jvmMember;
			if (StringUtils.isEmpty(jvmDeclaredType.getPackageName())) {
				qualifier = "(default package)";
			} else {
				qualifier = jvmDeclaredType.getPackageName();
			}
		}
	}
	return qualifier;
}
 
Example 3
Source File: ImportOrganizer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected String getPackageLocalName(JvmDeclaredType type) {
	String packageName = type.getPackageName();
	if (isEmpty(packageName))
		return type.getQualifiedName('.');
	else
		return type.getQualifiedName('.').substring(packageName.length() + 1);
}
 
Example 4
Source File: ConflictResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Multimap<String, JvmDeclaredType> getLocallyDefinedTypes(XtextResource resource) {
	Multimap<String, JvmDeclaredType> result = LinkedHashMultimap.create();
	for(JvmDeclaredType type: config.getLocallyDefinedTypes(resource)) {
		String packageName = type.getPackageName();
		if(isEmpty(packageName)) 
			result.put(type.getQualifiedName('.'), type);
		else 
			result.put(type.getQualifiedName('.').substring(packageName.length() + 1), type);
	}
	return result;
}
 
Example 5
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public CharSequence generateType(final JvmDeclaredType type, final GeneratorConfig config) {
  final ImportManager importManager = this.createImportManager(type);
  final TreeAppendable bodyAppendable = this.createAppendable(type, importManager, config);
  bodyAppendable.openScope();
  this.assignThisAndSuper(bodyAppendable, type, config);
  this.generateBody(type, bodyAppendable, config);
  bodyAppendable.closeScope();
  final TreeAppendable importAppendable = this.createAppendable(type, importManager, config);
  this.generateFileHeader(type, importAppendable, config);
  String _packageName = type.getPackageName();
  boolean _tripleNotEquals = (_packageName != null);
  if (_tripleNotEquals) {
    importAppendable.append("package ").append(type.getPackageName()).append(";");
    importAppendable.newLine().newLine();
  }
  List<String> _imports = importManager.getImports();
  for (final String i : _imports) {
    importAppendable.append("import ").append(i).append(";").newLine();
  }
  boolean _isEmpty = importManager.getImports().isEmpty();
  boolean _not = (!_isEmpty);
  if (_not) {
    importAppendable.newLine();
  }
  importAppendable.append(bodyAppendable);
  return importAppendable;
}
 
Example 6
Source File: JvmModelGenerator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void addJavaDocImports(final EObject it, final ITreeAppendable appendable, final List<INode> documentationNodes) {
  for (final INode node : documentationNodes) {
    List<ReplaceRegion> _computeTypeRefRegions = this.javaDocTypeReferenceProvider.computeTypeRefRegions(node);
    for (final ReplaceRegion region : _computeTypeRefRegions) {
      {
        final String text = region.getText();
        if (((text != null) && (text.length() > 0))) {
          final QualifiedName fqn = this.qualifiedNameConverter.toQualifiedName(text);
          final EObject context = NodeModelUtils.findActualSemanticObjectFor(node);
          if (((fqn.getSegmentCount() == 1) && (context != null))) {
            final IScope scope = this.scopeProvider.getScope(context, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
            final IEObjectDescription candidate = scope.getSingleElement(fqn);
            if ((candidate != null)) {
              EObject _xifexpression = null;
              boolean _eIsProxy = candidate.getEObjectOrProxy().eIsProxy();
              if (_eIsProxy) {
                _xifexpression = EcoreUtil.resolve(candidate.getEObjectOrProxy(), context);
              } else {
                _xifexpression = candidate.getEObjectOrProxy();
              }
              final JvmType jvmType = ((JvmType) _xifexpression);
              if (((jvmType instanceof JvmDeclaredType) && (!jvmType.eIsProxy()))) {
                final JvmDeclaredType referencedType = ((JvmDeclaredType) jvmType);
                final JvmDeclaredType contextDeclarator = EcoreUtil2.<JvmDeclaredType>getContainerOfType(it, JvmDeclaredType.class);
                String _packageName = referencedType.getPackageName();
                String _packageName_1 = contextDeclarator.getPackageName();
                boolean _notEquals = (!Objects.equal(_packageName, _packageName_1));
                if (_notEquals) {
                  final ImportManager importManager = this.getImportManager(appendable);
                  importManager.addImportFor(jvmType);
                }
              }
            }
          }
        }
      }
    }
  }
}
 
Example 7
Source File: JvmDeclaredTypeImplCustom.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String getPackageName() {
	JvmDeclaredType declaringType = internalGetDeclaringType();
	if (declaringType != null)
		return declaringType.getPackageName();
	return packageName;
}
 
Example 8
Source File: XtendOutlineJvmTreeProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IXtendOutlineContext buildXtendNode(EObject modelElement, IXtendOutlineContext context) {
	IXtendOutlineContext resultedContext = super.buildXtendNode(modelElement, context);
	
	if (!context.isShowInherited()) {
		EclipseXtendOutlineContext eclipseXtendOutlineContext = (EclipseXtendOutlineContext) context;
		IOutlineNode parentNode = eclipseXtendOutlineContext.getParentNode();
		if (parentNode instanceof DocumentRootNode) {
			if (modelElement instanceof JvmDeclaredType) {
				JvmDeclaredType jvmDeclaredType = (JvmDeclaredType) modelElement;
				String packageName = jvmDeclaredType.getPackageName();
				if (packageName != null) {
					EObject rootElement = modelElement.eResource().getContents().get(0);
					if (rootElement instanceof XtendFile) {
						XtendFile xtendFile = (XtendFile) rootElement;
						String primaryPackage = xtendFile.getPackage();
						if (!packageName.equals(primaryPackage)) {
							EObjectNode typeNode = (EObjectNode) ((EclipseXtendOutlineContext) resultedContext).getParentNode();
							if (typeNode.getText() instanceof StyledString) {
								typeNode.setText(((StyledString) typeNode.getText()).append(new StyledString(" - "
										+ packageName, StyledString.QUALIFIER_STYLER)));
							}
						}
					}
				}
			}
		}
	}
	return resultedContext;
}
 
Example 9
Source File: TypeScopeWithWildcardImports.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void doGetElements(JvmType type, List<IEObjectDescription> result) {
	if (!(type instanceof JvmDeclaredType)) {
		return;
	}
	JvmDeclaredType declaredType = (JvmDeclaredType) type;
	String packageName = declaredType.getPackageName();
	if (!Strings.isEmpty(packageName)) {
		QualifiedName qualifiedPackageName = QualifiedName.create(Strings.split(packageName, '.'));
		QualifiedName withDot = null;
		String withDollar = null; 
		for(int i = 0; i < imports.length; i++) {
			ImportNormalizer[] chunk = imports[i];
			for(int j = 0; j < chunk.length; j++) {
				ImportNormalizer normalizer = chunk[j];
				QualifiedName namespacePrefix = normalizer.getImportedNamespacePrefix();
				if (namespacePrefix.equals(qualifiedPackageName)) {
					if (withDot == null) {
						withDot = QualifiedName.create(Strings.split(type.getQualifiedName('.'), '.'));
						withDollar = type.eContainer() instanceof JvmType ? type.getQualifiedName('$').substring(packageName.length() + 1) : null;
					}
					result.add(EObjectDescription.create(withDot.skipFirst(qualifiedPackageName.getSegmentCount()), type));
					if (withDollar != null) {
						result.add(EObjectDescription.create(withDollar, type));	
					}
				}
			}
		}
	}
	if (parent != null) {
		parent.doGetElements(type, result);
	} else {
		Iterables.addAll(result, typeScope.getElements(type));
	}
}
 
Example 10
Source File: SARLJvmModelInferrer.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies if the given type is accessible according to the Java specifications.
 * Indeed, since Java11, several types, e.g. {@code HotSpotIntrinsicCandidate} annotation,
 * are inaccessible because they are in private modules.
 *
 * @param context the generation context.
 * @param type the type to test.
 * @return {@code true} if the type is accessible.
 */
@SuppressWarnings("static-method")
protected boolean isAccessibleTypeAccordingToJavaSpecifications(GenerationContext context, JvmDeclaredType type) {
	if (context.isAtLeastJava11()) {
		// TODO find and use an API-oriented way to have access to the module access definitions.
		final String packageName = type.getPackageName();
		if (!Strings.isNullOrEmpty(packageName)) {
			return !packageName.contains(".internal"); //$NON-NLS-1$
		}
	}
	return true;
}
 
Example 11
Source File: FeatureScopeSessionWithContext.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean isVisible(JvmMember member, /* @Nullable */ LightweightTypeReference receiverType, /* @Nullable */ JvmIdentifiableElement receiverFeature) {
	boolean result = isVisible(member);
	if (result && JvmVisibility.PROTECTED == member.getVisibility()) {
		if (receiverFeature != null) {
			// We bypass this check for qualified.this and qualified.super in the scope provider
			// they are considered to be always visible
			/*
			 * class A {
			 *   class B {
			 *     {
			 *       A.super.toString
			 *     }
			 *   }
			 * }
			 */
			if (isThisSuperOrTypeLiteral(receiverFeature)) {
				if (receiverType == null || !receiverType.isType(Class.class)) {
					return true;
				}
			}
		}
		JvmType contextType = visibilityHelper.getRawContextType();
		if (contextType instanceof JvmDeclaredType) {
			String packageName = visibilityHelper.getPackageName();
			JvmDeclaredType declaringType = member.getDeclaringType();
			String memberPackageName = declaringType.getPackageName();
			if (Strings.equal(packageName, memberPackageName)) {
				return true;
			}
		}
		if (receiverType != null) {
			if (receiverType.isSubtypeOf(contextType)) {
				return true;
			}
			EObject container = contextType.eContainer();
			while (container instanceof JvmType) {
				if (receiverType.isSubtypeOf((JvmType)container)) {
					return true;
				}
				container = container.eContainer();
			}
		}
		return false;
	}
	return result;
}
 
Example 12
Source File: RewritableImportSection.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
public boolean needsImport(JvmDeclaredType type) {
	if (type.getDeclaringType() != null)
		return true;
	String packageName = type.getPackageName();
	return packageName != null && !(implicitlyImportedPackages.contains(packageName));
}
 
Example 13
Source File: ProjectAwareUniqueClassNameValidator.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public boolean doCheckUniqueInProject(QualifiedName name, JvmDeclaredType type) throws JavaModelException {
	IJavaProject javaProject = javaProjectProvider.getJavaProject(type.eResource().getResourceSet());
	getContext().put(ProjectAwareUniqueClassNameValidator.OUTPUT_CONFIGS,
			outputConfigurationProvider.getOutputConfigurations(type.eResource()));

	String packageName = type.getPackageName();
	String typeName = type.getSimpleName();
	IndexManager indexManager = JavaModelManager.getIndexManager();
	List<IPackageFragmentRoot> sourceFolders = new ArrayList<>();
	for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
		if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
			sourceFolders.add(root);
		}
	}

	if (sourceFolders.isEmpty() || indexManager.awaitingJobsCount() > 0) {
		// still indexing - don't enter a busy wait loop but ask the source folders directly
		SourceTraversal sourceTraversal = doCheckUniqueInProjectSource(packageName != null ? packageName : "", typeName, type,
				sourceFolders);
		if (sourceTraversal == SourceTraversal.DUPLICATE) {
			return false;
		} else if (sourceTraversal == SourceTraversal.UNIQUE) {
			return true;
		}
	}

	Set<String> workingCopyPaths = new HashSet<>();
	ICompilationUnit[] copies = getWorkingCopies(type);
	if (copies != null) {
		for (ICompilationUnit workingCopy : copies) {
			IPath path = workingCopy.getPath();
			if (javaProject.getPath().isPrefixOf(path) && !isDerived(workingCopy.getResource())) {
				if (workingCopy.getPackageDeclaration(packageName).exists()) {
					IType result = workingCopy.getType(typeName);
					if (result.exists()) {
						addIssue(type, workingCopy.getElementName());
						return false;
					}
				}
				workingCopyPaths.add(workingCopy.getPath().toString());
			}
		}
	}

	// The code below is adapted from BasicSearchEnginge.searchAllSecondaryTypes
	// The Index is ready, query it for a secondary type 
	char[] pkg = packageName == null ? CharOperation.NO_CHAR : packageName.toCharArray();
	TypeDeclarationPattern pattern = new TypeDeclarationPattern(pkg, //
			CharOperation.NO_CHAR_CHAR, // top level type - no enclosing type names
			typeName.toCharArray(), //
			IIndexConstants.TYPE_SUFFIX, //
			SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

	IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {

		@Override
		public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant,
				AccessRuleSet access) {
			if (workingCopyPaths.contains(documentPath)) {
				return true; // filter out working copies
			}
			IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(documentPath));
			if (!isDerived(file)) {
				addIssue(type, file.getName());
				return false;
			}
			return true;
		}
	};

	try {
		SearchParticipant searchParticipant = BasicSearchEngine.getDefaultSearchParticipant(); // Java search only
		IJavaSearchScope javaSearchScope = BasicSearchEngine.createJavaSearchScope(sourceFolders.toArray(new IJavaElement[0]));
		PatternSearchJob patternSearchJob = new PatternSearchJob(pattern, searchParticipant, javaSearchScope, searchRequestor);
		indexManager.performConcurrentJob(patternSearchJob, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
		return true;
	} catch (Throwable OperationCanceledException) {
		return false;
	}
}