Unnamed: 0
int64
0
305k
body
stringlengths
7
52.9k
name
stringlengths
1
185
32,600
boolean (PsiModifierListOwner owner, PsiAnnotation[] annotations) { final String id = AnnotationUtilEx.calcAnnotationValue(annotations, "value"); final String prefix = AnnotationUtilEx.calcAnnotationValue(annotations, "prefix"); final String suffix = AnnotationUtilEx.calcAnnotationValue(annotations, "suffix"); final BaseInjection injection = new BaseInjection(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID); if (prefix != null) injection.setPrefix(prefix); if (suffix != null) injection.setSuffix(suffix); if (id != null) injection.setInjectedLanguageId(id); processInjectionWithContext(injection, false); return false; }
processAnnotationInjectionInner
32,601
boolean (BaseInjection injection, PsiModifierListOwner owner, PsiMethod method, int paramIndex) { processInjectionWithContext(injection, true); if (injection.isTerminal()) { return false; } return true; }
processXmlInjections
32,602
boolean (PsiVariable owner) { Ref<PsiElement> causeRef = Ref.create(); PsiElement anchor = owner.getFirstChild() instanceof PsiComment? (owner.getModifierList() != null? owner.getModifierList() : owner.getTypeElement()) : owner; if (anchor == null) return true; BaseInjection injection = mySupport.findCommentInjection(anchor, causeRef); return injection == null || processCommentInjectionInner(owner, causeRef.get(), injection); }
processCommentInjections
32,603
void (BaseInjection injection, boolean settingsAvailable) { Language language = InjectorUtils.getLanguage(injection); if (language == null) return; String languageID = language.getID(); List<InjectionInfo> list = new ArrayList<>(); boolean unparsable = false; StringBuilder prefix = new StringBuilder(); //String suffix = ""; for (int i = 0; i < myOperands.length; i++) { PsiElement operand = myOperands[i]; final ElementManipulator<PsiElement> manipulator = ElementManipulators.getManipulator(operand); if (manipulator == null) { unparsable = true; prefix.append(getStringPresentation(operand)); if (i == myOperands.length - 1) { InjectionInfo last = ContainerUtil.getLastItem(list); if (last != null) { InjectedLanguage injected = last.language(); list.set(list.size() - 1, new InjectionInfo(last.host(), InjectedLanguage.create(injected.getID(), injected.getPrefix(), prefix.toString(), false), last.range())); } } } else if (operand instanceof PsiLanguageInjectionHost host) { InjectedLanguage injectedLanguage = InjectedLanguage.create(languageID, prefix.toString(), "", false); TextRange range = manipulator.getRangeInElement(host); list.add(new InjectionInfo(host, injectedLanguage, range)); prefix.setLength(0); } } if (!list.isEmpty()) { processInjection(language, list, settingsAvailable, unparsable); } }
processInjectionWithContext
32,604
void (Language language, List<InjectionInfo> list, boolean settingsAvailable, boolean unparsable) { }
processInjection
32,605
Collection<String> (@NotNull Project project) { // note: external annotations not supported return InjectionCache.getInstance(project).getAnnoIndex(); }
getAnnotatedElementsValue
32,606
Collection<String> (@NotNull Project project) { return InjectionCache.getInstance(project).getXmlIndex(); }
getXmlAnnotatedElementsValue
32,607
void (@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { assert context instanceof GrLiteral; final GrLiteral literal = (GrLiteral)context; if (!literal.isValidHost()) return; processInPlace(registrar, literal); }
getLanguagesToInject
32,608
void (MultiHostRegistrar registrar, GrLiteral literal) { BaseInjection injection = findLanguageParams(literal); if (injection != null) { LanguageInjectionSupport support = InjectorUtils.findInjectionSupport(GroovyLanguageInjectionSupport.GROOVY_SUPPORT_ID); InjectorUtils.registerInjectionSimple(literal, injection, support, registrar); } }
processInPlace
32,609
BaseInjection (PsiElement place) { PsiElement parent = place.getParent(); if (parent instanceof GrAssignmentExpression && ((GrAssignmentExpression)parent).getRValue() == place) { final GrExpression lvalue = ((GrAssignmentExpression)parent).getLValue(); if (lvalue instanceof GrReferenceExpression) { final PsiElement resolved = ((GrReferenceExpression)lvalue).resolve(); if (resolved instanceof PsiModifierListOwner) { return getLanguageParams((PsiModifierListOwner)resolved); } } } else if (parent instanceof GrVariable) { return getLanguageParams((PsiModifierListOwner)parent); } else if (parent instanceof GrArgumentList) { final PsiElement pparent = parent.getParent(); if (pparent instanceof GrCall call) { final GroovyResolveResult result = call.advancedResolve(); if (result.getElement() != null) { final Map<GrExpression, Pair<PsiParameter, PsiType>> map = GrClosureSignatureUtil .mapArgumentsToParameters(result, place, false, false, call.getNamedArguments(), call.getExpressionArguments(), call.getClosureArguments()); if (map != null) { final Pair<PsiParameter, PsiType> pair = map.get(place); return getLanguageParams(pair.first); } } } } return null; }
findLanguageParams
32,610
BaseInjection (PsiModifierListOwner annotationOwner) { return CachedValuesManager.getCachedValue(annotationOwner, () -> CachedValueProvider.Result.create(calcLanguageParams(annotationOwner), PsiModificationTracker.MODIFICATION_COUNT)); }
getLanguageParams
32,611
BaseInjection (PsiModifierListOwner annotationOwner) { final Pair<String, ? extends Set<String>> pair = Configuration.getInstance().getAdvancedConfiguration().getLanguageAnnotationPair(); final PsiAnnotation[] annotations = getAnnotationFrom(annotationOwner, pair, true, true); if (annotations.length > 0) { String prefix = StringUtil.notNullize(AnnotationUtilEx.calcAnnotationValue(annotations, "prefix")); String suffix = StringUtil.notNullize(AnnotationUtilEx.calcAnnotationValue(annotations, "suffix")); String id = StringUtil.notNullize(AnnotationUtilEx.calcAnnotationValue(annotations, "value")); if (!StringUtil.isEmpty(id)) { BaseInjection injection = new BaseInjection(GroovyLanguageInjectionSupport.GROOVY_SUPPORT_ID); injection.setPrefix(prefix); injection.setSuffix(suffix); injection.setInjectedLanguageId(id); return injection; } } if (annotationOwner instanceof PsiParameter && annotationOwner.getParent() instanceof PsiParameterList && annotationOwner.getParent().getParent() instanceof PsiMethod) { List<BaseInjection> injections = Configuration.getInstance().getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID); for (BaseInjection injection : injections) { if (injection.acceptsPsiElement(annotationOwner)) { return injection; } } } return null; }
calcLanguageParams
32,612
boolean (PsiModifierListOwner owner) { return owner instanceof GrMethod && ((GrMethod)owner).getReturnTypeElementGroovy() == null || owner instanceof GrVariable && ((GrVariable)owner).getTypeElementGroovy() == null || PsiUtilEx.isLanguageAnnotationTarget(owner); }
isLanguageAnnotationTargetGroovy
32,613
String () { return GROOVY_SUPPORT_ID; }
getId
32,614
BaseInjection (@NotNull PsiElement host, @Nullable Ref<? super PsiElement> commentRef) { PsiFile containingFile = host.getContainingFile(); boolean compiled = containingFile != null && containingFile.getOriginalFile() instanceof PsiCompiledFile; return compiled ? null : super.findCommentInjection(host, commentRef); }
findCommentInjection
32,615
boolean (PsiLanguageInjectionHost host) { return host instanceof GroovyPsiElement; }
isApplicableTo
32,616
boolean (PsiLanguageInjectionHost host) { return true; }
useDefaultInjector
32,617
String () { return "reference.settings.language.injection.groovy"; }
getHelpId
32,618
boolean (Language language, @Nullable PsiLanguageInjectionHost psiElement) { if (language == null) return false; if (!isStringLiteral(psiElement)) return false; return doInject(language.getID(), psiElement, psiElement); }
addInjectionInPlace
32,619
boolean (@Nullable final PsiLanguageInjectionHost psiElement) { if (!isStringLiteral(psiElement)) return false; GrLiteralContainer host = (GrLiteralContainer)psiElement; final HashMap<BaseInjection, Pair<PsiMethod, Integer>> injectionsMap = new HashMap<>(); final ArrayList<PsiElement> annotations = new ArrayList<>(); final Project project = host.getProject(); final Configuration configuration = Configuration.getProjectInstance(project); collectInjections(host, configuration, this, injectionsMap, annotations); if (injectionsMap.isEmpty() && annotations.isEmpty()) return false; final ArrayList<BaseInjection> originalInjections = new ArrayList<>(injectionsMap.keySet()); final List<BaseInjection> newInjections = ContainerUtil.mapNotNull(originalInjections, (NullableFunction<BaseInjection, BaseInjection>)injection -> { final Pair<PsiMethod, Integer> pair = injectionsMap.get(injection); final String placeText = JavaLanguageInjectionSupport.getPatternStringForJavaPlace(pair.first, pair.second); final BaseInjection newInjection = injection.copy(); newInjection.setPlaceEnabled(placeText, false); return InjectorUtils.canBeRemoved(newInjection) ? null : newInjection; }); configuration.replaceInjectionsWithUndo(project, psiElement.getContainingFile(), newInjections, originalInjections, annotations); return true; }
removeInjectionInPlace
32,620
void (@NotNull GrLiteralContainer host, @NotNull Configuration configuration, @NotNull LanguageInjectionSupport support, @NotNull final HashMap<BaseInjection, Pair<PsiMethod, Integer>> injectionsMap, @NotNull final ArrayList<PsiElement> annotations) { new GrConcatenationAwareInjector.InjectionProcessor(configuration, support, host) { @Override protected boolean processCommentInjectionInner(PsiVariable owner, PsiElement comment, BaseInjection injection) { ContainerUtil.addAll(annotations, comment); return true; } @Override protected boolean processAnnotationInjectionInner(PsiModifierListOwner owner, PsiAnnotation[] annos) { ContainerUtil.addAll(annotations, annos); return true; } @Override protected boolean processXmlInjections(BaseInjection injection, PsiModifierListOwner owner, PsiMethod method, int paramIndex) { injectionsMap.put(injection, Pair.create(method, paramIndex)); return true; } }.processInjections(); }
collectInjections
32,621
boolean (PsiVariable owner, PsiElement comment, BaseInjection injection) { ContainerUtil.addAll(annotations, comment); return true; }
processCommentInjectionInner
32,622
boolean (PsiModifierListOwner owner, PsiAnnotation[] annos) { ContainerUtil.addAll(annotations, annos); return true; }
processAnnotationInjectionInner
32,623
boolean (BaseInjection injection, PsiModifierListOwner owner, PsiMethod method, int paramIndex) { injectionsMap.put(injection, Pair.create(method, paramIndex)); return true; }
processXmlInjections
32,624
boolean (@NotNull String languageId, @NotNull PsiElement psiElement, @NotNull PsiLanguageInjectionHost host) { final PsiElement target = getTopLevelInjectionTarget(psiElement); final PsiElement parent = target.getParent(); final Project project = psiElement.getProject(); if (parent instanceof GrReturnStatement) { final GrControlFlowOwner owner = ControlFlowUtils.findControlFlowOwner(parent); if (owner instanceof GrOpenBlock && owner.getParent() instanceof GrMethod) { return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)owner.getParent(), -1, host, languageId); } } else if (parent instanceof GrMethod) { return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (GrMethod)parent, -1, host, languageId); } else if (parent instanceof GrAnnotationNameValuePair) { final PsiReference ref = parent.getReference(); if (ref != null) { final PsiElement resolved = ref.resolve(); if (resolved instanceof PsiMethod) { return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)resolved, -1, host, languageId); } } } else if (parent instanceof GrArgumentList && parent.getParent() instanceof GrMethodCall) { final PsiMethod method = ((GrMethodCall)parent.getParent()).resolveMethod(); if (method != null) { final int index = GrInjectionUtil.findParameterIndex(target, ((GrMethodCall)parent.getParent())); if (index >= 0) { return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, method, index, host, languageId); } } } else if (parent instanceof GrAssignmentExpression) { final GrExpression expr = ((GrAssignmentExpression)parent).getLValue(); if (expr instanceof GrReferenceExpression) { final PsiElement element = ((GrReferenceExpression)expr).resolve(); if (element != null) { return doInject(languageId, element, host); } } } else { if (parent instanceof PsiVariable) { Processor<PsiLanguageInjectionHost> fixer = getAnnotationFixer(project, languageId); if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)parent, host, languageId, fixer)) return true; } else if (target instanceof PsiVariable && !(target instanceof LightElement)) { Processor<PsiLanguageInjectionHost> fixer = getAnnotationFixer(project, languageId); if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)target, host, languageId, fixer)) return true; } } return false; }
doInject
32,625
Processor<PsiLanguageInjectionHost> (@NotNull final Project project, @NotNull final String languageId) { return host -> { if (host == null) return false; final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration(); boolean allowed = configuration.isSourceModificationAllowed(); configuration.setSourceModificationAllowed(true); try { return doInject(languageId, host, host); } finally { configuration.setSourceModificationAllowed(allowed); } }; }
getAnnotationFixer
32,626
boolean (@Nullable PsiLanguageInjectionHost element) { if (element instanceof GrStringContent) { return true; } else if (element instanceof GrLiteral) { final IElementType type = GrLiteralImpl.getLiteralType((GrLiteral)element); return TokenSets.STRING_LITERALS.contains(type); } return false; }
isStringLiteral
32,627
PsiElement (@NotNull final PsiElement host) { PsiElement target = host; PsiElement parent = target.getParent(); for (; parent != null; target = parent, parent = target.getParent()) { if (parent instanceof GrBinaryExpression) continue; if (parent instanceof GrString) continue; if (parent instanceof GrParenthesizedExpression) continue; if (parent instanceof GrConditionalExpression && ((GrConditionalExpression)parent).getCondition() != target) continue; if (parent instanceof GrAnnotationArrayInitializer) continue; if (parent instanceof GrListOrMap) { parent = parent.getParent(); continue; } break; } return target; }
getTopLevelInjectionTarget
32,628
void (@NotNull PsiType qualifierType, @NotNull final PsiScopeProcessor scopeProcessor, @NotNull final PsiElement place, @NotNull final ResolveState state) { final PsiFile containingFile = place.getContainingFile(); if (containingFile == null) { PsiUtilCore.ensureValid(place); ResolveUtilKt.getLog().error("Containing file is null for " + place.getClass()); return; } final PsiFile file = containingFile.getOriginalFile(); final BaseInjection injection = file.getUserData(BaseInjection.INJECTION_KEY); Processor<PsiElement> processor = element -> element.processDeclarations(scopeProcessor, state, null, place); if (injection == null) { processDevContext(file, processor); } else { processPatternContext(injection, file, processor); } }
processDynamicElements
32,629
boolean (@NotNull BaseInjection injection, @NotNull PsiFile file, @NotNull Processor<? super PsiElement> processor) { return processor.process(getRootByClasses(file, InjectorUtils.getPatternClasses(injection.getSupportId()))); }
processPatternContext
32,630
PsiFile (@NotNull PsiFile file, Class @NotNull [] classes) { final Project project = file.getProject(); SoftFactoryMap<Class[], PsiFile> map = project.getUserData(PATTERN_INJECTION_CONTEXT); if (map == null) { map = new SoftFactoryMap<>() { @Override protected PsiFile create(Class @NotNull [] key) { String text = PatternCompilerFactory.getFactory().getPatternCompiler(key).dumpContextDeclarations(); return PsiFileFactory.getInstance(project).createFileFromText("context.groovy", GroovyFileType.GROOVY_FILE_TYPE, text); } }; project.putUserData(PATTERN_INJECTION_CONTEXT, map); } return map.get(classes); }
getRootByClasses
32,631
PsiFile (Class @NotNull [] key) { String text = PatternCompilerFactory.getFactory().getPatternCompiler(key).dumpContextDeclarations(); return PsiFileFactory.getInstance(project).createFileFromText("context.groovy", GroovyFileType.GROOVY_FILE_TYPE, text); }
create
32,632
boolean (final PsiFile file, Processor<? super PsiElement> processor) { final XmlTag tag = getTagByInjectedFile(file); final XmlTag parentTag = tag == null ? null : tag.getParentTag(); final String parentTagName = parentTag == null ? null : parentTag.getName(); final String name = tag == null ? null : tag.getName(); if ("place".equals(name) && "injection".equals(parentTagName)) { return processRootsByClassNames(file, parentTag.getAttributeValue("injector-id"), processor); } else if ("pattern".equals(name) && parentTag != null) { return processRootsByClassNames(file, tag.getAttributeValue("type"), processor); } return true; }
processDevContext
32,633
XmlTag (final PsiFile file) { final SmartPsiElementPointer pointer = file.getUserData(FileContextUtil.INJECTED_IN_ELEMENT); final PsiElement element = pointer == null? null : pointer.getElement(); return element instanceof XmlText ? ((XmlText)element).getParentTag() : null; }
getTagByInjectedFile
32,634
boolean (@NotNull PsiFile file, @Nullable String type, @NotNull Processor<? super PsiElement> processor) { Project project = file.getProject(); Set<String> classNames = collectDevPatternClassNames(project); if (!classNames.isEmpty()) { JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); for (String className : classNames) { PsiClass patternClass = psiFacade.findClass(className, GlobalSearchScope.allScope(project)); if (patternClass != null && !processor.process(patternClass)) return false; } } Class[] classes = StringUtil.isEmpty(type) ? ArrayUtil.EMPTY_CLASS_ARRAY : PatternCompilerFactory.getFactory().getPatternClasses(type); return classes.length == 0 || processor.process(getRootByClasses(file, classes)); }
processRootsByClassNames
32,635
Set<String> (@NotNull final Project project) { CachedValue<Set<String>> cachedValue = project.getUserData(PATTERN_CLASSES); if (cachedValue == null) { cachedValue = CachedValuesManager.getManager(project).createCachedValue( () -> CachedValueProvider.Result.create(calcDevPatternClassNames(project), PsiModificationTracker.MODIFICATION_COUNT), false); project.putUserData(PATTERN_CLASSES, cachedValue); } return cachedValue.getValue(); }
collectDevPatternClassNames
32,636
Set<String> (@NotNull final Project project) { final List<String> roots = ContainerUtil.createLockFreeCopyOnWriteList(); JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); PsiClass beanClass = psiFacade.findClass(PatternClassBean.class.getName(), GlobalSearchScope.allScope(project)); if (beanClass != null) { GlobalSearchScope scope = GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(project), StdFileTypes.XML); final TextOccurenceProcessor occurenceProcessor = (element, offsetInElement) -> { XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class); String className = tag == null ? null : tag.getAttributeValue("className"); if (StringUtil.isNotEmpty(className) && tag.getLocalName().endsWith("patternClass")) { roots.add(className); } return true; }; final StringSearcher searcher = new StringSearcher("patternClass", true, true); CacheManager.getInstance(beanClass.getProject()).processFilesWithWord(psiFile -> { LowLevelSearchUtil.processElementsContainingWordInElement(occurenceProcessor, psiFile, searcher, true, new EmptyProgressIndicator()); return true; }, searcher.getPattern(), UsageSearchContext.IN_FOREIGN_LANGUAGES, scope, searcher.isCaseSensitive()); } return new HashSet<>(roots); }
calcDevPatternClassNames
32,637
List<PatternContext> () { return PATTERN_CONTEXTS; }
getPatternContexts
32,638
boolean (@NotNull Language language) { return language == GroovyLanguage.INSTANCE; }
isMyLanguage
32,639
TokenSet () { return VARIABLE_DELIMITERS; }
getVariableDelimiters
32,640
PsiCodeFragment (@NotNull Project project, @NotNull String text, String contextId) { return new GroovyCodeFragment(project, text); }
createCodeFragment
32,641
String (@NotNull String pattern, @Nullable Language language, String contextId) { return CLASS_CONTEXT.getId().equals(contextId) ? "class AAAAA { " + PATTERN_PLACEHOLDER + " }" : PATTERN_PLACEHOLDER; }
getContext
32,642
boolean (@Nullable PsiElement element) { return element instanceof PsiIdentifier; }
isIdentifier
32,643
boolean (@NotNull PsiElement context) { return context.getLanguage().isKindOf(GroovyLanguage.INSTANCE); }
isMyContext
32,644
EquivalenceDescriptor (@NotNull PsiElement e) { final EquivalenceDescriptorBuilder builder = new EquivalenceDescriptorBuilder(); if (e instanceof GrVariableDeclaration) { return builder.elements(((GrVariableDeclaration)e).getVariables()); } else if (e instanceof GrParameter p) { return builder .element(p.getNameIdentifierGroovy()) .optionally(p.getTypeElementGroovy()) .optionallyInPattern(p.getInitializerGroovy()); } else if (e instanceof GrVariable v) { return builder .element(v.getNameIdentifierGroovy()) .optionally(v.getTypeElementGroovy()) .optionallyInPattern(v.getInitializerGroovy()); } else if (e instanceof GrMethod m) { return builder .element(m.getNameIdentifierGroovy()) .elements(m.getParameters()) .optionally(m.getReturnTypeElementGroovy()) .optionallyInPattern(m.getBlock()); } else if (e instanceof GrTypeDefinitionBody b) { return builder .inAnyOrder(b.getFields()) .inAnyOrder(b.getMethods()) .inAnyOrder(b.getInitializers()) .inAnyOrder(b.getInnerClasses()); } else if (e instanceof GrTypeDefinition d) { return builder.element(d.getNameIdentifierGroovy()) .optionallyInPattern(d.getExtendsClause()) .optionallyInPattern(d.getImplementsClause()) .optionallyInPattern(d.getBody()); } else if (e instanceof GrForInClause f) { return builder .element(f.getDeclaredVariable()) .element(f.getIteratedExpression()); } else if (e instanceof GrReferenceList) { return builder.inAnyOrder(((GrReferenceList)e).getReferenceElementsGroovy()); } else if (e instanceof GrCodeBlock) { return builder.codeBlock(((GrStatementOwner)e).getStatements()); } // todo: support 'object method()' <-> 'object.method()' return null; }
buildDescriptor
32,645
TokenSet () { return IGNORED_TOKENS; }
getIgnoredTokens
32,646
void (@NotNull PsiType qualifierType, @NotNull PsiScopeProcessor processor, @NotNull PsiElement place, @NotNull ResolveState state) { GlobalSearchScope scope = place.getResolveScope(); if (scope instanceof StructuralSearchScriptScope) { PsiPackage openApiPackage = JavaPsiFacade.getInstance(place.getProject()).findPackage("com.intellij.psi"); if (openApiPackage != null) { traversePackage(openApiPackage, c -> { processor.execute(c, state); c.processDeclarations(processor, state, null, place); }); } } }
processDynamicElements
32,647
void (PsiPackage psiPackage, Consumer<? super PsiClass> classConsumer) { for (PsiPackage aPackage : psiPackage.getSubPackages()) { traversePackage(aPackage, classConsumer); } for (PsiClass psiClass : psiPackage.getClasses()) { classConsumer.consume(psiClass); } }
traversePackage
32,648
void () { String s = """ def int x = 0; def y = 0; int z = 10; def int x1"""; doTest(s, "def $x$ = $value$;", 3, 1); doTest(s, "def $x$", 4, 3); doTest(s, "int $x$", 3, 3); doTest(s, "def $x$ = $value$", 3, 1); doTest(s, "def $x$ = 0", 2, 1); doTest(s, "int $x$ = 0", 1, 1); doTest(s, "int $x$ = $value$", 2, 2); }
test1
32,649
void () { String s = """ def void f(int x) {} def f(int x) { System.out.println("hello"); } def f(def x) {} void g(x) {} public def void f(def int y) { System.out.println("hello"); } def int f() {}"""; doTest(s, "def $f$($param$)", 5, 2); doTest(s, "def $f$($param$) {}", 3, 1); doTest(s, "void $f$($param$) {}", 2, 2); doTest(s, "void $f$(def x)", 2, 0); doTest(s, "def $f$(def x)", 4, 1); doTest(s, "void $f$(def $x$)", 3, 0); doTest(s, "void $f$(int $x$)", 2, 2); doTest(s, "def $f$(int $x$)", 3, 1); doTest(s, "def g($param$)", 1, 0); doTest(s, "def '_T1('_T2*)", 6, 2); // a problem with default eq is that ; is not part of statement doTest(s, "def '_T1('_T2*) {'_T3+}", 2, 0); doTest(s, "def '_T1('_T2*) {'_T3*}", 6, 1); }
test2
32,650
void () { String s = """ public class C implements I1, I2 { void f() { def a = 1; def int b = 2; } }"""; doTest(s, "class $name$", 1, 1); doTest(s, "class $name$ implements I1, I2", 1, 1); doTest(s, "class $name$ implements $interface$", 1, 0); doTest(s, "class '_T1 implements '_T2*", 1, 1); doTest(s, "class '_T1 implements '_T2+", 1, 1); doTest(s, "class $name$ implements I2, I1", 1, 0); doTest(s, "class C implements I1, I2 {}", 1, 0); doTest(s, "def a = 1;\n def b = 2;", 1, 0); doTest(s, "def a = 1\n def b = 2", 1, 0); }
test3
32,651
void () { String s = """ for (a in list) { println("hello1"); println("hello2"); }"""; doTest(s, """ for ($a$ in $b$) { $st1$; $st2$ }""", 1, 0); doTest(s, """ for ($a$ in $b$) { $st1$; $st2$; }""", 1, 1); doTest(s, """ for ($a$ in $b$) { $st1$ $st2$ }""", 1, 0); doTest(s, """ for ($a$ in $b$) { $st$ }""", 0, 0); doTest(s, """ for ($a$ in $b$) { '_T* }""", 1, 0); doTest(s, """ for ($a$ in $b$) { '_T+ }""", 1, 0); }
test4
32,652
void () { String s = """ class A { def f = { println('Hello1') println('Hello2') } def f1 = { println('Hello') } }"""; doTest(s, """ def $name$ = { '_T+ }""", 0, 0); final PatternContext old = options.getPatternContext(); try { options.setPatternContext(GroovyStructuralSearchProfile.CLASS_CONTEXT); doTest(s, """ def $name$ = { '_T+ }""", 2, 2); } finally { options.setPatternContext(old); } }
test5
32,653
void (String source, String pattern, int expectedOccurrences, int expectedWithDefaultEquivalence) { findAndCheck(source, pattern, expectedOccurrences); try { EquivalenceDescriptorProvider.ourUseDefaultEquivalence = true; findAndCheck(source, pattern, expectedWithDefaultEquivalence); } finally { EquivalenceDescriptorProvider.ourUseDefaultEquivalence = false; } }
doTest
32,654
void (String source, String pattern, int expectedOccurrences) { assertEquals(expectedOccurrences, findMatchesCount(source, pattern, GroovyFileType.GROOVY_FILE_TYPE)); }
findAndCheck
32,655
String () { return "Groovy"; }
getName
32,656
String () { return GROOVY_DESCRIPTION; }
getDescription
32,657
String () { return DEFAULT_EXTENSION; }
getDefaultExtension
32,658
Icon () { return JetgroovyIcons.Groovy.Groovy_16x16; }
getIcon
32,659
boolean () { return true; }
isJVMDebuggingSupported
32,660
boolean (FileType ft) { return ft instanceof GroovyEnabledFileType || ft instanceof LanguageFileType && ((LanguageFileType)ft).getLanguage() == GroovyLanguage.INSTANCE; }
isGroovyEnabledFileType
32,661
Icon (@NotNull VirtualFile virtualFile, @Iconable.IconFlags int flags, @Nullable Project project) { if (project == null || !FileTypeRegistry.getInstance().isFileOfType(virtualFile, GroovyFileType.GROOVY_FILE_TYPE)) return null; final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (!(psiFile instanceof GroovyFile file)) return null; final Icon icon; if (file.isScript()) { icon = GroovyScriptTypeDetector.getIcon(file); } else if (GrFileIndexUtil.isGroovySourceFile(file)) { final GrTypeDefinition[] typeDefinitions = file.getTypeDefinitions(); icon = typeDefinitions.length > 0 ? typeDefinitions[0].getIcon(flags) : JetgroovyIcons.Groovy.GroovyFile; } else { icon = JetgroovyIcons.Groovy.Groovy_outsideSources; } return IconManager.getInstance().createLayeredIcon(psiFile, icon, ElementBase.transformFlags(psiFile, flags)); }
getIcon
32,662
boolean (VirtualFile virtualFile) { return FileTypeRegistry.getInstance().isFileOfType(virtualFile, GroovyFileType.GROOVY_FILE_TYPE); }
value
32,663
PsiType (GrMethodCall methodCall, PsiMethod method) { GrExpression[] allArguments = PsiUtil.getAllArguments(methodCall); GrClosableBlock closure = null; for (GrExpression argument : allArguments) { if (argument instanceof GrClosableBlock) { closure = (GrClosableBlock)argument; break; } } if (closure == null) return null; final GrClosableBlock finalClosure = closure; return RecursionManager.doPreventingRecursion(methodCall, true, () -> { PsiType returnType = finalClosure.getReturnType(); if (PsiTypes.voidType().equals(returnType)) return null; return returnType; }); }
fun
32,664
PsiType (GrMethodCall methodCall, PsiMethod method) { GrArgumentList argumentList = methodCall.getArgumentList(); GrExpression[] arguments = argumentList.getExpressionArguments(); if (arguments.length == 0) return null; return arguments[0].getType(); }
fun
32,665
void (PsiElement element) { encodeContextInfo(element, element); }
encodeContextInfo
32,666
void (PsiElement element, PsiElement scope) { if (!(element instanceof GroovyPsiElement)) return; if (PsiUtil.isThisReference(element)) { GrReferenceExpression thisExpr = (GrReferenceExpression)element; final PsiClass containingClass = PsiTreeUtil.getParentOfType(thisExpr, PsiClass.class); element.putCopyableUserData(KEY_ENCODED, KEY_ENCODED); thisExpr.putCopyableUserData(QUALIFIER_CLASS_KEY, containingClass); } else if (element instanceof GrReferenceExpression refExpr) { final GrExpression qualifier = refExpr.getQualifierExpression(); if (qualifier == null) { PsiElement refElement = refExpr.resolve(); element.putCopyableUserData(KEY_ENCODED, KEY_ENCODED); if (refElement != null && !PsiTreeUtil.isContextAncestor(scope, refElement, false)) { if (refElement instanceof GrAccessorMethod) refElement = ((GrAccessorMethod)refElement).getProperty(); if (refElement instanceof PsiClass) { refExpr.putCopyableUserData(REF_TO_CLASS, (PsiClass)refElement); } else if (refElement instanceof PsiMember) { refExpr.putCopyableUserData(REF_TO_MEMBER, (PsiMember)refElement); } } } } else if (element instanceof GrCodeReferenceElement) { final PsiElement resolvedElement = ((GrCodeReferenceElement)element).resolve(); element.putCopyableUserData(KEY_ENCODED, KEY_ENCODED); if (resolvedElement instanceof PsiClass && !PsiTreeUtil.isContextAncestor(scope, resolvedElement, false)) { element.putCopyableUserData(REF_TO_CLASS, (PsiClass)resolvedElement); } } for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { encodeContextInfo(child, scope); } }
encodeContextInfo
32,667
void (PsiElement element, @Nullable PsiClass thisClass, @Nullable GrExpression thisAccessExpr) { if (!(element instanceof GroovyPsiElement)) return; for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { decodeContextInfo(child, thisClass, thisAccessExpr); } if (element.getCopyableUserData(KEY_ENCODED) != null) { element.putCopyableUserData(KEY_ENCODED, null); final PsiManager manager = element.getManager(); if (PsiUtil.isThisReference(element)) { final PsiClass thisQualClass = element.getCopyableUserData(QUALIFIER_CLASS_KEY); element.putCopyableUserData(QUALIFIER_CLASS_KEY, null); if (thisAccessExpr != null && !manager.areElementsEquivalent(thisClass, thisQualClass)) { element.replace(thisAccessExpr); return; } } else if (element instanceof GrReferenceExpression refExpr) { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject()); final PsiElement resolvedElement = refExpr.resolve(); final PsiMember memberRef = refExpr.getCopyableUserData(REF_TO_MEMBER); refExpr.putCopyableUserData(REF_TO_MEMBER, null); if (memberRef != null && memberRef.isValid()) { final PsiClass memberClass = memberRef.getContainingClass(); if (memberClass != null) { if (memberRef.hasModifierProperty(PsiModifier.STATIC)) { if (!manager.areElementsEquivalent(memberRef, resolvedElement)) { final PsiElement qualifier = refExpr.getQualifier(); if (!(qualifier instanceof GrReferenceExpression)) { refExpr.setQualifier(factory.createReferenceExpressionFromText(memberClass.getQualifiedName())); JavaCodeStyleManager.getInstance(manager.getProject()).shortenClassReferences(refExpr.getQualifier()); return; } } } else if (thisAccessExpr instanceof GrReferenceExpression) { final PsiElement qualifier = refExpr.getQualifier(); if (!(qualifier instanceof GrReferenceExpression)) { refExpr.setQualifier(thisAccessExpr); return; } } } } } PsiClass refClass = element.getCopyableUserData(REF_TO_CLASS); element.putCopyableUserData(REF_TO_CLASS, null); if (refClass != null && refClass.isValid()) { final PsiReference ref = element.getReference(); if (ref != null) { ref.bindToElement(refClass); } } } }
decodeContextInfo
32,668
void (PsiElement scope) { scope.putCopyableUserData(QUALIFIER_CLASS_KEY, null); scope.putCopyableUserData(REF_TO_CLASS, null); scope.putCopyableUserData(REF_TO_MEMBER, null); for (PsiElement child = scope.getFirstChild(); child != null; child = child.getNextSibling()) { clearContextInfo(child); } }
clearContextInfo
32,669
GrMethod (GrTypeDefinition aClass, PsiMethod method, PsiSubstitutor substitutor) { final Project project = aClass.getProject(); final boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); String templName = isAbstract ? JavaTemplateUtil.TEMPLATE_IMPLEMENTED_METHOD_BODY : JavaTemplateUtil.TEMPLATE_OVERRIDDEN_METHOD_BODY; final FileTemplate template = FileTemplateManager.getInstance(method.getProject()).getCodeTemplate(templName); final GrMethod result = (GrMethod)GenerateMembersUtil.substituteGenericMethod(method, substitutor, aClass); setupModifierList(result); setupOverridingMethodBody(project, method, result, template, substitutor); setupReturnType(result, method); setupAnnotations(aClass, method, result); GroovyChangeContextUtil.encodeContextInfo(result); return result; }
generateMethodPrototype
32,670
GrMethod (GrTypeDefinition aClass, GrTraitMethod method, PsiSubstitutor substitutor) { final Project project = aClass.getProject(); final GrMethod result = (GrMethod)GenerateMembersUtil.substituteGenericMethod(method, substitutor, aClass); setupModifierList(result); setupTraitMethodBody(project, result, method); setupReturnType(result, method); setupAnnotations(aClass, method, result); GroovyChangeContextUtil.encodeContextInfo(result); return result; }
generateTraitMethodPrototype
32,671
void (GrMethod result, PsiMethod method) { if (method instanceof GrMethod && ((GrMethod)method).getReturnTypeElementGroovy() == null) { result.setReturnType(null); GrModifierList modifierList = result.getModifierList(); if (!modifierList.hasExplicitVisibilityModifiers()) { modifierList.setModifierProperty(GrModifier.DEF, true); } } }
setupReturnType
32,672
void (@NotNull GrTypeDefinition aClass, @NotNull PsiMethod method, @NotNull GrMethod result) { if (OverrideImplementUtil.isInsertOverride(method, aClass)) { result.getModifierList().addAnnotation(CommonClassNames.JAVA_LANG_OVERRIDE); } final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(method.getProject()); final PsiParameter[] originalParams = method.getParameterList().getParameters(); GrParameter[] parameters = result.getParameters(); for (int i = 0; i < parameters.length; i++) { GrParameter parameter = parameters[i]; PsiParameter original = originalParams[i]; for (PsiAnnotation annotation : original.getModifierList().getAnnotations()) { final GrModifierList modifierList = parameter.getModifierList(); String qname = annotation.getQualifiedName(); if (qname != null && !modifierList.hasAnnotation(qname)) { if (annotation instanceof GrAnnotation) { modifierList.add(annotation); } else { modifierList.add(factory.createAnnotationFromText(annotation.getText())); } } } } }
setupAnnotations
32,673
void (GrMethod result) { PsiModifierList modifierList = result.getModifierList(); modifierList.setModifierProperty(PsiModifier.ABSTRACT, false); modifierList.setModifierProperty(PsiModifier.NATIVE, false); }
setupModifierList
32,674
PsiType (@NotNull PsiMethod superMethod) { if (superMethod instanceof GrMethod) { final GrTypeElement element = ((GrMethod)superMethod).getReturnTypeElementGroovy(); return element != null ? element.getType() : null; } return superMethod.getReturnType(); }
getSuperReturnType
32,675
void (Project project, PsiMethod method, GrMethod resultMethod, FileTemplate template, PsiSubstitutor substitutor) { final PsiType returnType = substitutor.substitute(getSuperReturnType(method)); String returnTypeText = ""; if (returnType != null) { returnTypeText = returnType.getPresentableText(); } Properties properties = FileTemplateManager.getInstance(project).getDefaultProperties(); properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, returnTypeText); properties.setProperty(FileTemplate.ATTRIBUTE_DEFAULT_RETURN_VALUE, PsiTypesUtil.getDefaultValueOfType(returnType)); properties.setProperty(FileTemplate.ATTRIBUTE_CALL_SUPER, callSuper(method, resultMethod)); JavaTemplateUtil.setClassAndMethodNameProperties(properties, method.getContainingClass(), resultMethod); try { String bodyText = StringUtil.replace(template.getText(properties), ";", ""); GroovyFile file = GroovyPsiElementFactory.getInstance(project).createGroovyFile("\n " + bodyText + "\n", false, null); GrOpenBlock block = resultMethod.getBlock(); block.getNode().addChildren(file.getFirstChild().getNode(), null, block.getRBrace().getNode()); } catch (IOException e) { LOG.error(e); } }
setupOverridingMethodBody
32,676
void (Project project, GrMethod resultMethod, GrTraitMethod traitMethod) { PsiClass traitClass = traitMethod.getPrototype().getContainingClass(); @NlsSafe StringBuilder builder = new StringBuilder(); builder.append("\nreturn "); builder.append(traitClass.getQualifiedName()); builder.append(".super."); builder.append(traitMethod.getName()); builder.append("("); GrParameter[] parameters = resultMethod.getParameters(); for (GrParameter parameter : parameters) { builder.append(parameter.getName()).append(","); } if (parameters.length > 0) { builder.replace(builder.length() - 1, builder.length(), ")\n"); } else { builder.append(")\n"); } GroovyFile file = GroovyPsiElementFactory.getInstance(project).createGroovyFile(builder, false, null); GrOpenBlock block = resultMethod.getBlock(); block.getNode().addChildren(file.getFirstChild().getNode(), null, block.getRBrace().getNode()); }
setupTraitMethodBody
32,677
void (@NotNull Project project, @NotNull Editor editor, @NotNull GrTypeDefinition aClass) { FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.CODEASSISTS_OVERRIDE_IMPLEMENT); chooseAndOverrideOrImplementMethods(project, editor, aClass, false); }
chooseAndOverrideMethods
32,678
void (@NotNull Project project, @NotNull Editor editor, @NotNull GrTypeDefinition aClass) { FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.CODEASSISTS_OVERRIDE_IMPLEMENT); chooseAndOverrideOrImplementMethods(project, editor, aClass, true); }
chooseAndImplementMethods
32,679
void (@NotNull Project project, @NotNull final Editor editor, @NotNull final GrTypeDefinition aClass, boolean toImplement) { LOG.assertTrue(aClass.isValid()); ApplicationManager.getApplication().assertReadAccessAllowed(); Collection<CandidateInfo> candidates = GroovyOverrideImplementExploreUtil.getMethodsToOverrideImplement(aClass, toImplement); Collection<CandidateInfo> secondary = toImplement || aClass.isInterface() ? new ArrayList<>() : GroovyOverrideImplementExploreUtil .getMethodsToOverrideImplement(aClass, true); if (toImplement) { for (Iterator<CandidateInfo> iterator = candidates.iterator(); iterator.hasNext(); ) { CandidateInfo candidate = iterator.next(); PsiElement element = candidate.getElement(); if (element instanceof GrMethod method) { if (GrTraitUtil.isTrait(method.getContainingClass()) && !GrTraitUtil.isMethodAbstract(method)) { iterator.remove(); secondary.add(candidate); } } } } OverrideImplementUtil.showJavaOverrideImplementChooser(editor, aClass, toImplement, candidates, secondary, chooser->{ if (chooser == null) return; final List<PsiMethodMember> selectedElements = chooser.getSelectedElements(); if (selectedElements == null || selectedElements.isEmpty()) return; LOG.assertTrue(aClass.isValid()); WriteCommandAction.writeCommandAction(project, aClass.getContainingFile()).run( () -> OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(editor, aClass, selectedElements, chooser.isCopyJavadoc(), chooser.isInsertOverrideAnnotation())); }); }
chooseAndOverrideOrImplementMethods
32,680
String (PsiMethod superMethod, PsiMethod overriding) { @NonNls StringBuilder buffer = new StringBuilder(); if (!superMethod.isConstructor() && !PsiTypes.voidType().equals(superMethod.getReturnType())) { buffer.append("return "); } buffer.append("super"); PsiParameter[] parms = overriding.getParameterList().getParameters(); if (!superMethod.isConstructor()) { buffer.append("."); buffer.append(superMethod.getName()); } buffer.append("("); for (int i = 0; i < parms.length; i++) { String name = parms[i].getName(); if (i > 0) buffer.append(","); buffer.append(name); } buffer.append(")"); return buffer.toString(); }
callSuper
32,681
PsiElement () { return null; }
resolve
32,682
File[] (String dirPath, final String patternString) { final Pattern pattern = Pattern.compile(patternString); return LibrariesUtil.getFilesInDirectoryByPattern(dirPath, pattern); }
getFilesInDirectoryByPattern
32,683
GrTypeDefinition (@NotNull Project project, @NotNull VirtualFile file) { return getPublicClass(file, PsiManager.getInstance(project)); }
getPublicClass
32,684
GrTypeDefinition (@Nullable VirtualFile virtualFile, @NotNull PsiManager manager) { if (virtualFile == null) return null; PsiElement psiFile = manager.findFile(virtualFile); if (psiFile instanceof PsiCompiledFile) { psiFile = psiFile.getNavigationElement(); } if (psiFile instanceof GroovyFile) { return getClassDefinition((GroovyFile)psiFile); } return null; }
getPublicClass
32,685
GrTypeDefinition (@NotNull GroovyFile groovyFile) { String fileName = groovyFile.getName(); int idx = fileName.lastIndexOf('.'); if (idx < 0) return null; return getClassDefinition(groovyFile, fileName.substring(0, idx)); }
getClassDefinition
32,686
GrTypeDefinition (@NotNull GroovyFile groovyFile, @NotNull String classSimpleName) { for (GrTypeDefinition definition : (groovyFile).getTypeDefinitions()) { if (classSimpleName.equals(definition.getName())) { return definition; } } return null; }
getClassDefinition
32,687
T () { while (true) { T value = myValueRef.get(); if (value != null) return value; // value already computed and cached final NotNullComputable<T> computable = myComputable; if (computable == null) continue; // computable is null only after some thread succeeds CAS RecursionGuard.StackStamp stamp = RecursionManager.markStack(); value = computable.compute(); if (stamp.mayCacheNow()) { if (myValueRef.compareAndSet(null, value)) { // try to cache value myComputable = null; // if ok, allow gc to clean computable return value; } // if CAS failed then other thread already set this value => loop & get value from reference } else { return value; // recursion detected } } }
compute
32,688
boolean () { return myValueRef.get() != null; }
isComputed
32,689
long () { SdkHomeBean sdkHome = mySdkHome; return sdkHome == null ? 0 : sdkHome.getModificationCount(); }
getStateModificationCount
32,690
SdkHomeBean () { return mySdkHome; }
getState
32,691
void (@NotNull SdkHomeBean state) { SdkHomeBean oldState = mySdkHome; mySdkHome = state; // do not increment on a first load if (oldState != null && !StringUtil.equals(oldState.getSdkHome(), state.getSdkHome())) { myManager.dropPsiCaches(); } }
loadState
32,692
VirtualFile (@Nullable SdkHomeBean state) { if (state == null) { return null; } final String sdk_home = state.getSdkHome(); if (StringUtil.isEmpty(sdk_home)) { return null; } return StandardFileSystems.local().findFileByPath(sdk_home); }
calcHome
32,693
VirtualFile () { return calcHome(mySdkHome); }
getSdkHome
32,694
List<VirtualFile> () { return calcRoots(getSdkHome()); }
getClassRoots
32,695
List<VirtualFile> (@Nullable VirtualFile home) { if (home == null) return Collections.emptyList(); VirtualFile lib = home.findChild("lib"); if (lib == null) return Collections.emptyList(); List<VirtualFile> result = new ArrayList<>(); for (VirtualFile file : lib.getChildren()) { if ("jar".equals(file.getExtension())) { ContainerUtil.addIfNotNull(result, JarFileSystem.getInstance().getRootByLocal(file)); } } return result; }
calcRoots
32,696
boolean (@NotNull PsiFile file) { return file instanceof GroovyFileBase && isGroovySourceFile((GroovyFileBase)file); }
isGroovySourceFile
32,697
boolean (@NotNull GroovyFileBase file) { return isInSourceFiles(file.getVirtualFile(), file.getProject()); }
isGroovySourceFile
32,698
boolean (@Nullable VirtualFile file, @NotNull Project project) { if (file != null && !(file instanceof LightVirtualFile)) { final FileIndexFacade index = FileIndexFacade.getInstance(project); if (index.isInSource(file) || index.isInLibraryClasses(file)) { return true; } } return false; }
isInSourceFiles
32,699
Collection<MethodSignature> (@NotNull GrTypeDefinition aClass) { if (aClass.isAnnotationType()) return Collections.emptySet(); return getMapToOverrideImplement(aClass, false, true).keySet(); }
getMethodSignaturesToOverride