public static boolean processImplicitImports( @NotNull PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place, @NotNull GroovyFile file) { JavaPsiFacade facade = JavaPsiFacade.getInstance(file.getProject()); final DelegatingScopeProcessor packageSkipper = new DelegatingScopeProcessor(processor) { @Override public boolean execute(@NotNull PsiElement element, ResolveState state) { if (element instanceof PsiPackage) return true; return super.execute(element, state); } }; for (final String implicitlyImported : getImplicitlyImportedPackages(file)) { PsiPackage aPackage = facade.findPackage(implicitlyImported); if (aPackage == null) continue; if (!aPackage.processDeclarations(packageSkipper, state, lastParent, place)) { return false; } } GroovyPsiManager groovyPsiManager = GroovyPsiManager.getInstance(file.getProject()); for (String implicitlyImportedClass : GroovyFileBase.IMPLICITLY_IMPORTED_CLASSES) { PsiClass clazz = groovyPsiManager.findClassWithCache(implicitlyImportedClass, file.getResolveScope()); if (clazz != null && !ResolveUtil.processElement(processor, clazz, state)) return false; } return true; }
private Collection<PsiClass> getAllScriptClasses(String shortName, GlobalSearchScope scope) { final ArrayList<PsiClass> result = CollectionFactory.arrayList(); for (GroovyFile file : StubIndex.getInstance() .get( GrScriptClassNameIndex.KEY, shortName, myProject, new GrSourceFilterScope(scope))) { ContainerUtil.addIfNotNull(file.getScriptClass(), result); } return result; }
public boolean hasWriteAccess() { if (myHasWriteAccess != null) return myHasWriteAccess.booleanValue(); myFile.accept( new GroovyRecursiveElementVisitor() { @Override public void visitAssignmentExpression(GrAssignmentExpression expression) { if (isRefToMe(expression.getLValue())) { myHasWriteAccess = true; } super.visitAssignmentExpression(expression); } @Override public void visitTypeDefinition(GrTypeDefinition typeDefinition) { // don't go inside type definitions } @Override public void visitElement(GroovyPsiElement element) { if (myHasWriteAccess == null) { super.visitElement(element); } } }); if (myHasWriteAccess == null) myHasWriteAccess = false; return myHasWriteAccess.booleanValue(); }
@Override protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { if (!(element instanceof GrReferenceElement)) return; final GrReferenceElement ref = (GrReferenceElement) element; final PsiElement resolved = ref.resolve(); if (!(resolved instanceof PsiClass)) return; final String qname = ((PsiClass) resolved).getQualifiedName(); final GrImportStatement importStatement = GroovyPsiElementFactory.getInstance(project) .createImportStatementFromText(qname, true, true, null); final PsiFile containingFile = element.getContainingFile(); if (!(containingFile instanceof GroovyFile)) return; ((GroovyFile) containingFile).addImport(importStatement); for (PsiReference reference : ReferencesSearch.search(resolved, new LocalSearchScope(containingFile))) { final PsiElement refElement = reference.getElement(); if (refElement == null) continue; final PsiElement parent = refElement.getParent(); if (parent instanceof GrQualifiedReference<?>) { org.jetbrains.plugins.groovy.codeStyle.GrReferenceAdjuster.shortenReference( (GrQualifiedReference<?>) parent); } } }
@Nullable private static GrVariableDeclaration findDeclaration(GroovyFile file) { final Ref<GrVariableDeclaration> ref = Ref.create(); file.accept( new GroovyRecursiveElementVisitor() { @Override public void visitVariableDeclaration(@NotNull GrVariableDeclaration variableDeclaration) { super.visitVariableDeclaration(variableDeclaration); if (variableDeclaration .getModifierList() .findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_BASE_SCRIPT) != null) { ref.set(variableDeclaration); } } @Override public void visitElement(@NotNull GroovyPsiElement element) { if (ref.isNull()) { super.visitElement(element); } } }); return ref.get(); }
@Override public void doCollectInformation(@NotNull ProgressIndicator progress) { final List<HighlightInfo> result = new ArrayList<HighlightInfo>(); myFile.accept( new PsiRecursiveElementVisitor() { @Override public void visitElement(PsiElement element) { IElementType tokenType = element.getNode().getElementType(); if (TokenSets.KEYWORDS.contains(tokenType)) { if (highlightKeyword(element, tokenType)) { result.add( HighlightInfo.createHighlightInfo( HighlightInfoType.INFORMATION, element, null, DefaultHighlighter.KEYWORD)); } } else if (!(element instanceof GroovyPsiElement)) { final TextAttributesKey attribute = getDeclarationAttribute(element); if (attribute != null) { result.add( HighlightInfo.createHighlightInfo( HighlightInfoType.INFORMATION, element, null, attribute)); } } else { super.visitElement(element); } } }); toHighlight = result; }
private static String stripImports(String text, GroovyFile toEval) { GrImportStatement[] imports = toEval.getImportStatements(); for (int i = imports.length - 1; i >= 0; i--) { TextRange range = imports[i].getTextRange(); text = text.substring(0, range.getStartOffset()) + text.substring(range.getEndOffset(), text.length()); } return StringUtil.escapeStringCharacters(text); }
public List<PsiClass> getScriptClassesByFQName( final String name, final GlobalSearchScope scope, final boolean srcOnly) { GlobalSearchScope actualScope = srcOnly ? new GrSourceFilterScope(scope) : scope; final Collection<GroovyFile> files = StubIndex.getInstance() .get(GrFullScriptNameIndex.KEY, name.hashCode(), myProject, actualScope); if (files.isEmpty()) { return Collections.emptyList(); } final ArrayList<PsiClass> result = new ArrayList<PsiClass>(); for (GroovyFile file : files) { if (file.isScript()) { final PsiClass scriptClass = file.getScriptClass(); if (scriptClass != null && name.equals(scriptClass.getQualifiedName())) { result.add(scriptClass); } } } return result; }
protected RunnerAndConfigurationSettings createConfigurationByElement( final Location location, final ConfigurationContext context) { final PsiElement element = location.getPsiElement(); final PsiFile file = element.getContainingFile(); if (!(file instanceof GroovyFile)) { return null; } GroovyFile groovyFile = (GroovyFile) file; if (groovyFile.isScript()) { mySourceElement = element; final PsiClass scriptClass = getScriptClass(location.getPsiElement()); if (scriptClass == null) return null; final RunnerAndConfigurationSettings settings = createConfiguration(scriptClass); if (settings != null) { final GroovyScriptRunConfiguration configuration = (GroovyScriptRunConfiguration) settings.getConfiguration(); GroovyScriptTypeDetector.getScriptType(groovyFile) .tuneConfiguration(groovyFile, configuration, location); return settings; } } if (!file.getText().contains("@Grab")) return null; ApplicationConfigurationProducer producer = new ApplicationConfigurationProducer(); RunnerAndConfigurationSettings settings = producer.createConfigurationByElement(location, context); if (settings != null) { PsiElement src = producer.getSourceElement(); mySourceElement = src; return createConfiguration( src instanceof PsiMethod ? ((PsiMethod) src).getContainingClass() : (PsiClass) src); } return null; }
private static String generateClassInfo(PsiClass aClass) { StringBuilder buffer = new StringBuilder(); GroovyFile file = (GroovyFile) aClass.getContainingFile(); String packageName = file.getPackageName(); if (!packageName.isEmpty()) { buffer.append(packageName).append("\n"); } final String classString = aClass.isInterface() ? "interface" : aClass instanceof PsiTypeParameter ? "type parameter" : aClass.isEnum() ? "enum" : "class"; buffer.append(classString).append(" ").append(aClass.getName()); JavaDocumentationProvider.generateTypeParameters(aClass, buffer); JavaDocumentationProvider.writeExtends(aClass, buffer, aClass.getExtendsListTypes()); JavaDocumentationProvider.writeImplements(aClass, buffer, aClass.getImplementsListTypes()); return buffer.toString(); }
@Override public void tuneConfiguration( @NotNull GroovyFile file, @NotNull GroovyScriptRunConfiguration configuration, Location location) { List<String> tasks = getTasksTarget(location); if (tasks != null) { String s = StringUtil.join(tasks, " "); configuration.setScriptParameters(s); configuration.setName("gradle:" + s); } RunManagerEx.disableTasks( file.getProject(), configuration, CompileStepBeforeRun.ID, CompileStepBeforeRunNoErrorCheck.ID); }
public GrReferenceExpression bindToElementViaStaticImport(@NotNull PsiMember member) { if (getQualifier() != null) { throw new IncorrectOperationException("Reference has qualifier"); } if (StringUtil.isEmpty(getReferenceName())) { throw new IncorrectOperationException("Reference has empty name"); } PsiClass containingClass = member.getContainingClass(); if (containingClass == null) { throw new IncorrectOperationException("Member has no containing class"); } final PsiFile file = getContainingFile(); if (file instanceof GroovyFile) { GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject()); String text = "import static " + containingClass.getQualifiedName() + "." + member.getName(); final GrImportStatement statement = factory.createImportStatementFromText(text); ((GroovyFile) file).addImport(statement); } return this; }
@Override public GlobalSearchScope patchResolveScope( @NotNull GroovyFile file, @NotNull GlobalSearchScope baseScope) { final Module module = ModuleUtilCore.findModuleForPsiElement(file); final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); if (module != null) { if (libraryManager.getGradleHome(module) != null) { return baseScope; } } final Collection<VirtualFile> files = libraryManager.getClassRoots(file.getProject()); if (files == null || files.isEmpty()) { return baseScope; } GlobalSearchScope result = baseScope; for (final VirtualFile root : files) { result = result.uniteWith(new NonClasspathDirectoryScope(root)); } return result; }
private void getBindings() { final PsiClass containingClass = PsiTreeUtil.getParentOfType(myRefExpr, PsiClass.class); if (containingClass != null) return; final PsiFile file = FileContextUtil.getContextFile(myRefExpr); if (file instanceof GroovyFile) { ((GroovyFile) file) .accept( new GroovyRecursiveElementVisitor() { @Override public void visitAssignmentExpression(GrAssignmentExpression expression) { super.visitAssignmentExpression(expression); final GrExpression value = expression.getLValue(); if (value instanceof GrReferenceExpression && !((GrReferenceExpression) value).isQualified()) { final PsiElement resolved = ((GrReferenceExpression) value).resolve(); if (resolved instanceof GrBindingVariable) { myProcessor.execute(resolved, ResolveState.initial()); } else if (resolved == null) { myProcessor.execute( new GrBindingVariable( (GroovyFile) file, ((GrReferenceExpression) value).getReferenceName(), true), ResolveState.initial()); } } } @Override public void visitTypeDefinition(GrTypeDefinition typeDefinition) { // don't go into classes } }); } }
public GrBindingVariable(final GroovyFile file, String name, Boolean isWriteAccess) { super(file.getManager(), name, CommonClassNames.JAVA_LANG_OBJECT, file); myFile = file; myHasWriteAccess = isWriteAccess; }
protected GrKeywordAndDeclarationHighlighter(GroovyFile file, Document document) { super(file.getProject(), document); myFile = file; }
@Override public void doApplyInformationToEditor() { if (toHighlight == null) return; UpdateHighlightersUtil.setHighlightersToEditor( myProject, myDocument, 0, myFile.getTextLength(), toHighlight, getColorsScheme(), getId()); }
@SuppressWarnings({"HardCodedStringLiteral"}) private static String generateClassInfo(PsiClass aClass) { StringBuilder buffer = new StringBuilder(); GroovyFile file = (GroovyFile) aClass.getContainingFile(); String packageName = file.getPackageName(); if (packageName.length() > 0) { buffer.append(packageName).append("\n"); } final String classString = aClass.isInterface() ? "interface" : aClass instanceof PsiTypeParameter ? "type parameter" : aClass.isEnum() ? "enum" : "class"; buffer.append(classString).append(" ").append(aClass.getName()); if (aClass.hasTypeParameters()) { PsiTypeParameter[] typeParameters = aClass.getTypeParameters(); buffer.append("<"); for (int i = 0; i < typeParameters.length; i++) { if (i > 0) buffer.append(", "); PsiTypeParameter tp = typeParameters[i]; buffer.append(tp.getName()); PsiClassType[] refs = tp.getExtendsListTypes(); if (refs.length > 0) { buffer.append(" extends "); for (int j = 0; j < refs.length; j++) { if (j > 0) buffer.append(" & "); appendTypeString(buffer, refs[j], aClass); } } } buffer.append(">"); } PsiClassType[] refs = aClass.getExtendsListTypes(); if (refs.length > 0 || !aClass.isInterface() && !CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) { buffer.append(" extends "); if (refs.length == 0) { buffer.append("Object"); } else { for (int i = 0; i < refs.length; i++) { if (i > 0) buffer.append(", "); appendTypeString(buffer, refs[i], aClass); } } } refs = aClass.getImplementsListTypes(); if (refs.length > 0) { buffer.append("\nimplements "); for (int i = 0; i < refs.length; i++) { if (i > 0) buffer.append(", "); appendTypeString(buffer, refs[i], aClass); } } return buffer.toString(); }
public void doCollectInformation(ProgressIndicator progress) { if (!(myFile instanceof GroovyFile)) return; GroovyFile groovyFile = (GroovyFile) myFile; GroovyImportsTracker importsTracker = GroovyImportsTracker.getInstance(groovyFile.getProject()); myUnusedImports = importsTracker.getUnusedImportStatements(groovyFile); }
public JavaCodeFragment createCodeFragment( TextWithImports textWithImports, PsiElement context, Project project) { String text = textWithImports.getText(); String imports = textWithImports.getImports(); final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); final GroovyFile toEval = factory.createGroovyFile(text, false, context); final Set<String> namesList = new HashSet<String>(); final GrClosableBlock closure = PsiTreeUtil.getParentOfType(context, GrClosableBlock.class); final Set<String> valList = new HashSet<String>(); toEval.accept( new GroovyRecursiveElementVisitor() { public void visitReferenceExpression(GrReferenceExpression referenceExpression) { super.visitReferenceExpression(referenceExpression); PsiElement resolved = referenceExpression.resolve(); if (resolved instanceof PsiMethod && "getDelegate".equals(((PsiMethod) resolved).getName()) && closure != null) { replaceWithReference(referenceExpression, "owner"); return; } if (resolved instanceof GrField && !referenceExpression.isQualified()) { replaceWithReference( referenceExpression, (closure == null ? "delegate" : "owner") + "." + referenceExpression.getReferenceName()); return; } if (resolved instanceof GrVariableBase && !(resolved instanceof GrField) && !PsiTreeUtil.isAncestor(toEval, resolved, false)) { final String name = ((GrVariableBase) resolved).getName(); if (resolved instanceof ClosureSyntheticParameter && PsiTreeUtil.isAncestor( toEval, ((ClosureSyntheticParameter) resolved).getClosure(), false)) { return; } namesList.add(name); if (closure != null && PsiTreeUtil.findCommonParent(resolved, closure) != closure && !(resolved instanceof ClosureSyntheticParameter)) { // Evaluating inside closure for outer variable definitions // All non-local variables are accessed by references valList.add("this." + name); } else { valList.add(name); } } } @Override public void visitThisExpression(final GrThisReferenceExpression thisExpression) { super.visitThisExpression(thisExpression); replaceWithReference(thisExpression, closure == null ? "delegate" : "owner"); } @Override public void visitSuperExpression(final GrSuperReferenceExpression superExpression) { super.visitSuperExpression(superExpression); replaceWithReference(superExpression, closure == null ? "delegate" : "owner"); } private void replaceWithReference(GrExpression expr, final String exprText) { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(expr.getProject()); visitReferenceExpression( (GrReferenceExpression) expr.replaceWithExpression(factory.createExpressionFromText(exprText), false)); } public void visitCodeReferenceElement(GrCodeReferenceElement refElement) { if (refElement.getQualifier() != null) { super.visitCodeReferenceElement(refElement); } else { PsiElement resolved = refElement.resolve(); if (resolved instanceof PsiClass) { String qName = ((PsiClass) resolved).getQualifiedName(); if (qName != null) { int dotIndex = qName.lastIndexOf("."); if (dotIndex < 0) return; String packageName = qName.substring(0, dotIndex); refElement.setQualifier(factory.createReferenceElementFromText(packageName)); } } } } }); text = toEval.getText(); String[] names = namesList.toArray(new String[namesList.size()]); String[] vals = valList.toArray(new String[valList.size()]); PsiClass contextClass = PsiUtil.getContextClass(context); boolean isStatic = isStaticContext(context); StringBuffer javaText = new StringBuffer(); javaText.append("groovy.lang.MetaClass mc;\n"); javaText.append("java.lang.Class clazz;\n"); if (!isStatic) { javaText.append("clazz = ((java.lang.Object)this).getClass();\n"); javaText.append("mc = ((groovy.lang.GroovyObject)this).getMetaClass();\n"); } else { javaText .append("clazz = java.lang.Class.forName(\"") .append(contextClass.getQualifiedName()) .append("\");\n"); javaText.append( "mc = groovy.lang.GroovySystem.getMetaClassRegistry().getMetaClass(clazz);\n"); } javaText.append(createProperty(stripImports(text, toEval), imports, names)); javaText.append( "groovy.lang.ExpandoMetaClass emc = new groovy.lang.ExpandoMetaClass(clazz);\n"); if (!isStatic) { javaText.append("emc.setProperty(\"").append(EVAL_NAME).append("\", closure);\n"); javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(emc);\n"); } else { javaText .append("((groovy.lang.GroovyObject)emc.getProperty(\"static\")).setProperty(\"") .append(EVAL_NAME) .append("\", closure);\n"); javaText.append( "groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, emc);\n"); } javaText.append("emc.initialize();\n"); javaText.append(unwrapVals(vals)); if (!isStatic) { javaText .append("java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeMethod(this, \"") .append(EVAL_NAME) .append("\", ") .append("resVals") .append(");\n"); javaText.append( "((groovy.lang.GroovyObject)this).setMetaClass(mc);"); // try/finally is not supported } else { javaText .append( "java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeStaticMethod(clazz, \"") .append(EVAL_NAME) .append("\", ") .append("resVals") .append(");\n"); javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, mc);\n"); } javaText.append("res"); PsiElementFactory elementFactory = JavaPsiFacade.getInstance(toEval.getProject()).getElementFactory(); JavaCodeFragment result = elementFactory.createCodeBlockCodeFragment(javaText.toString(), null, true); if (contextClass != null) { result.setThisType(elementFactory.createType(contextClass)); } return result; }