Search in sources :

Example 56 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class GroovyBlockGenerator method generateSubBlocks.

public List<Block> generateSubBlocks() {
    //For binary expressions
    PsiElement blockPsi = myNode.getPsi();
    IElementType elementType = myNode.getElementType();
    if (blockPsi instanceof GrBinaryExpression && !(blockPsi.getParent() instanceof GrBinaryExpression)) {
        return generateForBinaryExpr();
    }
    //For multiline strings
    if ((elementType == GroovyTokenTypes.mSTRING_LITERAL || elementType == GroovyTokenTypes.mGSTRING_LITERAL) && myBlock.getTextRange().equals(myNode.getTextRange())) {
        String text = myNode.getText();
        if (text.length() > 6) {
            if (text.substring(0, 3).equals("'''") && text.substring(text.length() - 3).equals("'''") || text.substring(0, 3).equals("\"\"\"") & text.substring(text.length() - 3).equals("\"\"\"")) {
                return generateForMultiLineString();
            }
        }
    }
    //for gstrings
    if (elementType == GroovyElementTypes.GSTRING || elementType == GroovyElementTypes.REGEX || elementType == GroovyTokenTypes.mREGEX_LITERAL || elementType == GroovyTokenTypes.mDOLLAR_SLASH_REGEX_LITERAL) {
        final FormattingContext context = myNode.getPsi() instanceof GrString && ((GrString) myNode.getPsi()).isPlainString() ? myContext.createContext(true) : myContext;
        final ArrayList<Block> subBlocks = new ArrayList<>();
        ASTNode[] children = getGroovyChildren(myNode);
        for (ASTNode childNode : children) {
            if (childNode.getTextRange().getLength() > 0) {
                subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), Wrap.createWrap(WrapType.NONE, false), context));
            }
        }
        return subBlocks;
    }
    // chained properties, calls, indexing, etc
    if (NESTED.contains(elementType) && blockPsi.getParent() != null && !NESTED.contains(blockPsi.getParent().getNode().getElementType())) {
        final List<Block> subBlocks = new ArrayList<>();
        AlignmentProvider.Aligner dotsAligner = myContext.getSettings().ALIGN_MULTILINE_CHAINED_METHODS ? myAlignmentProvider.createAligner(false) : null;
        final Wrap wrap = myWrappingProcessor.getChainedMethodCallWrap();
        addNestedChildren(myNode.getPsi(), subBlocks, dotsAligner, true, wrap);
        return subBlocks;
    }
    if (blockPsi instanceof GrListOrMap && ((GrListOrMap) blockPsi).isMap() && myContext.getGroovySettings().ALIGN_NAMED_ARGS_IN_MAP) {
        AlignmentProvider.Aligner labels = myAlignmentProvider.createAligner(false);
        AlignmentProvider.Aligner exprs = myAlignmentProvider.createAligner(true);
        GrNamedArgument[] namedArgs = ((GrListOrMap) blockPsi).getNamedArguments();
        for (GrNamedArgument arg : namedArgs) {
            GrArgumentLabel label = arg.getLabel();
            if (label != null)
                labels.append(label);
            PsiElement colon = arg.getColon();
            if (colon == null)
                colon = arg.getExpression();
            if (colon != null)
                exprs.append(colon);
        }
    }
    // For Parameter lists
    if (isListLikeClause(blockPsi)) {
        final ArrayList<Block> subBlocks = new ArrayList<>();
        List<ASTNode> astNodes = visibleChildren(myNode);
        if (mustAlign(blockPsi, astNodes)) {
            final AlignmentProvider.Aligner aligner = myAlignmentProvider.createAligner(false);
            for (ASTNode node : astNodes) {
                if (!isKeyword(node))
                    aligner.append(node.getPsi());
            }
        }
        for (ASTNode childNode : astNodes) {
            subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
        }
        return subBlocks;
    }
    boolean classLevel = blockPsi instanceof GrTypeDefinitionBody;
    if (blockPsi instanceof GrClosableBlock && ((GrClosableBlock) blockPsi).getArrow() != null && ((GrClosableBlock) blockPsi).getParameters().length > 0 && !getClosureBodyVisibleChildren(myNode).isEmpty()) {
        GrClosableBlock closableBlock = (GrClosableBlock) blockPsi;
        ArrayList<Block> blocks = new ArrayList<>();
        PsiElement lbrace = closableBlock.getLBrace();
        if (lbrace != null) {
            ASTNode node = lbrace.getNode();
            blocks.add(new GroovyBlock(node, getIndent(node), Wrap.createWrap(WrapType.NONE, false), myContext));
        }
        /* {
        Indent indent = GroovyIndentProcessor.getChildIndent(myBlock, parameterListNode);
        GroovyBlock block = new GroovyBlock(parameterListNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider);
        blocks.add(block);
      }

      {
        PsiElement arrow = closableBlock.getArrow();
        ASTNode node = arrow.getNode();
        Indent indent = GroovyIndentProcessor.getChildIndent(myBlock, node);
        GroovyBlock block = new GroovyBlock(node, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider);
        blocks.add(block);
      }*/
        {
            Indent indent = Indent.getNormalIndent();
            ASTNode parameterListNode = closableBlock.getParameterList().getNode();
            ClosureBodyBlock bodyBlock = new ClosureBodyBlock(parameterListNode, indent, Wrap.createWrap(WrapType.NONE, false), myContext);
            blocks.add(bodyBlock);
        }
        PsiElement rbrace = closableBlock.getRBrace();
        if (rbrace != null) {
            ASTNode node = rbrace.getNode();
            blocks.add(new GroovyBlock(node, getIndent(node), Wrap.createWrap(WrapType.NONE, false), myContext));
        }
        return blocks;
    }
    if (blockPsi instanceof GrCodeBlock || blockPsi instanceof GroovyFile || classLevel) {
        return generateSubBlockForCodeBlocks(classLevel, visibleChildren(myNode), myContext.getGroovySettings().INDENT_LABEL_BLOCKS);
    }
    if (blockPsi instanceof GrMethod) {
        final ArrayList<Block> subBlocks = new ArrayList<>();
        for (ASTNode childNode : getGroovyChildren(myNode)) {
            if (childNode.getElementType() == GroovyTokenTypes.mLPAREN)
                continue;
            if (childNode.getElementType() == GroovyTokenTypes.mRPAREN)
                continue;
            if (childNode.getElementType() == GroovyElementTypes.PARAMETERS_LIST) {
                subBlocks.add(new ParameterListBlock(((GrMethod) blockPsi), Indent.getNoneIndent(), Wrap.createWrap(WrapType.NONE, false), myContext));
            } else if (canBeCorrectBlock(childNode)) {
                subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
            }
        }
        return subBlocks;
    } else if (blockPsi instanceof GrTraditionalForClause) {
        if (myContext.getSettings().ALIGN_MULTILINE_FOR) {
            final GrTraditionalForClause clause = (GrTraditionalForClause) blockPsi;
            final AlignmentProvider.Aligner parenthesesAligner = myAlignmentProvider.createAligner(false);
            parenthesesAligner.append(clause.getInitialization());
            parenthesesAligner.append(clause.getCondition());
            parenthesesAligner.append(clause.getUpdate());
        }
    } else if (blockPsi instanceof GrBinaryExpression) {
        if (myContext.getSettings().ALIGN_MULTILINE_BINARY_OPERATION) {
            final GrBinaryExpression binary = (GrBinaryExpression) blockPsi;
            final GrExpression left = binary.getLeftOperand();
            final GrExpression right = binary.getRightOperand();
            if (left != null && right != null) {
                myAlignmentProvider.addPair(left, right, false);
            }
        }
    } else if (blockPsi instanceof GrAssignmentExpression) {
        if (myContext.getSettings().ALIGN_MULTILINE_ASSIGNMENT) {
            final GrAssignmentExpression assignment = (GrAssignmentExpression) blockPsi;
            final GrExpression lValue = assignment.getLValue();
            final GrExpression rValue = assignment.getRValue();
            if (lValue != null && rValue != null) {
                myAlignmentProvider.addPair(lValue, rValue, false);
            }
        }
    } else if (blockPsi instanceof GrConditionalExpression) {
        if (myContext.getSettings().ALIGN_MULTILINE_TERNARY_OPERATION) {
            final GrConditionalExpression conditional = (GrConditionalExpression) blockPsi;
            final AlignmentProvider.Aligner exprAligner = myAlignmentProvider.createAligner(false);
            exprAligner.append(conditional.getCondition());
            if (!(conditional instanceof GrElvisExpression)) {
                exprAligner.append(conditional.getThenBranch());
            }
            exprAligner.append(conditional.getElseBranch());
            ASTNode question = conditional.getNode().findChildByType(GroovyTokenTypes.mQUESTION);
            ASTNode colon = conditional.getNode().findChildByType(GroovyTokenTypes.mCOLON);
            if (question != null && colon != null) {
                AlignmentProvider.Aligner questionColonAligner = myAlignmentProvider.createAligner(false);
                questionColonAligner.append(question.getPsi());
                questionColonAligner.append(colon.getPsi());
            }
        }
    }
    // For other cases
    final ArrayList<Block> subBlocks = new ArrayList<>();
    for (ASTNode childNode : visibleChildren(myNode)) {
        subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
    }
    return subBlocks;
}
Also used : FormattingContext(org.jetbrains.plugins.groovy.formatter.FormattingContext) GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) ArrayList(java.util.ArrayList) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) AlignmentProvider(org.jetbrains.plugins.groovy.formatter.AlignmentProvider) GrListOrMap(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap) ASTNode(com.intellij.lang.ASTNode) PsiElement(com.intellij.psi.PsiElement) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) GrCodeBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock) GrArgumentLabel(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) IElementType(com.intellij.psi.tree.IElementType) GrTypeDefinitionBody(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrCodeBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) GrTraditionalForClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause)

Example 57 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class UpdateGroovyCopyrightsProvider method createInstance.

@Override
public UpdateCopyright createInstance(Project project, Module module, VirtualFile file, FileType base, CopyrightProfile options) {
    return new UpdateJavaFileCopyright(project, module, file, options) {

        @Override
        protected boolean accept() {
            return getFile() instanceof GroovyFile;
        }

        @Override
        protected PsiElement[] getImportsList() {
            return ((GroovyFile) getFile()).getImportStatements();
        }

        @Override
        protected PsiElement getPackageStatement() {
            return ((GroovyFile) getFile()).getPackageDefinition();
        }

        @Override
        protected void checkCommentsForTopClass(PsiClass topclass, int location, List<PsiComment> comments) {
            if (!(topclass instanceof GroovyScriptClass)) {
                super.checkCommentsForTopClass(topclass, location, comments);
                return;
            }
            final GroovyFile containingFile = (GroovyFile) topclass.getContainingFile();
            PsiElement last = containingFile.getFirstChild();
            while (last != null && !(last instanceof GrStatement)) {
                last = last.getNextSibling();
            }
            checkComments(last, location == JavaOptions.LOCATION_BEFORE_CLASS, comments);
        }
    };
}
Also used : GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass) UpdateJavaFileCopyright(com.maddyhome.idea.copyright.psi.UpdateJavaFileCopyright) PsiClass(com.intellij.psi.PsiClass) List(java.util.List) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) PsiElement(com.intellij.psi.PsiElement) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)

Example 58 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class GroovyCodeFragmentFactory method createCodeFragment.

@Override
public JavaCodeFragment createCodeFragment(TextWithImports textWithImports, PsiElement context, Project project) {
    final Pair<Map<String, String>, GroovyFile> pair = externalParameters(textWithImports.getText(), context);
    GroovyFile toEval = pair.second;
    final Map<String, String> parameters = pair.first;
    List<String> names = new ArrayList<>(parameters.keySet());
    List<String> values = ContainerUtil.map(names, name -> parameters.get(name));
    String text = toEval.getText();
    final String groovyText = StringUtil.join(names, ", ") + "->" + stripImports(text, toEval);
    PsiClass contextClass = PsiUtil.getContextClass(context);
    boolean isStatic = isStaticContext(context);
    StringBuilder javaText = new StringBuilder();
    javaText.append("java.lang.Class |clazz;\n");
    if (!isStatic) {
        javaText.append("java.lang.Object |thiz0;\n");
        PsiFile containingFile = context.getContainingFile();
        if (containingFile.getContext() != null) {
            containingFile = containingFile.getContext().getContainingFile();
        }
        String fileName = containingFile.getOriginalFile().getName();
        String s = StringUtil.escapeStringCharacters(Pattern.quote(fileName));
        // We believe what class is reloaded if stacktrace matches one of two patterns:
        // 1.) [com.package.Foo$$ENLbVXwm.methodName(FileName.groovy:12), com.package.Foo$$DNLbVXwm.methodName(Unknown Source), *
        // 2.) [com.package.Foo$$ENLbVXwm.methodName(FileName.groovy:12), * com.springsource.loaded. *
        // Pattern below test this.
        //javaText.append("System.out.println(java.util.Arrays.toString(new Exception().getStackTrace()));\n");
        //javaText.append("System.out.println(\"\\\\[([^,()]+\\\\$\\\\$)[A-Za-z0-9]{8}(\\\\.[^,()]+)\\\\(" + s + ":\\\\d+\\\\), (\\\\1[A-Za-z0-9]{8}\\\\2\\\\(Unknown Source\\\\), |.+(?:com|org)\\\\.springsource\\\\.loaded\\\\.).+\")\n");
        javaText.append("Class.forName(\"java.lang.StackTraceElement\");\n");
        javaText.append("StackTraceElement[] |trace = new Exception().getStackTrace();\n");
        javaText.append("if (java.util.Arrays.toString(|trace).matches(\"\\\\[([^,()]+\\\\$\\\\$)[A-Za-z0-9]{8}(\\\\.[^,()]+)\\\\(").append(s).append(":\\\\d+\\\\), (\\\\1[A-Za-z0-9]{8}\\\\2\\\\(Unknown Source\\\\), $OR$.+(?:com$OR$org)\\\\.springsource\\\\.loaded\\\\.).+\")) {\n");
        javaText.append("  |thiz0 = thiz;\n");
        javaText.append(" } else {\n");
        if (contextClass instanceof GrTraitTypeDefinition) {
            javaText.append("  |thiz0 = $self;\n");
        } else {
            javaText.append("  |thiz0 = this;\n");
        }
        javaText.append(" }\n");
    }
    if (!isStatic) {
        javaText.append("|clazz = |thiz0.getClass();\n");
    } else {
        assert contextClass != null;
        javaText.append("|clazz = java.lang.Class.forName(\"").append(ClassUtil.getJVMClassName(contextClass)).append("\");\n");
    }
    javaText.append("final java.lang.ClassLoader |parentLoader = |clazz.getClassLoader();\n" + "   final groovy.lang.GroovyClassLoader |loader = new groovy.lang.GroovyClassLoader(|parentLoader);\n" + "   final java.lang.Class |c = |loader.parseClass(");
    javaText.append("\"" + IMPORTS + "class DUMMY").append(" { ").append("public groovy.lang.Closure ").append(EVAL_NAME).append(" = {").append(TEXT).append("}}\"");
    javaText.append(", \"DUMMY.groovy\");\n" + "   int |i;\n" + "   java.lang.reflect.Field[] |fields = |c.getFields();\n" + "   for (int |j = 0; |j < |fields.length; |j++) if (|fields[|j].getName().equals(\"_JETGROOVY_EVAL_\")) {|i = |j; break;}\n" + "   final java.lang.reflect.Field |field = |fields[|i];\n" + "   final java.lang.Object |closure = |field.get(|c.newInstance());\n");
    javaText.append("groovy.lang.ExpandoMetaClass |emc = new groovy.lang.ExpandoMetaClass(|clazz);\n");
    if (!isStatic) {
        javaText.append("|closure.setDelegate(|thiz0);\n");
        javaText.append("|emc.setProperty(\"").append(EVAL_NAME).append("\", |closure);\n");
    } else {
        javaText.append("|emc.getProperty(\"static\").setProperty(\"").append(EVAL_NAME).append("\", |closure);\n");
    }
    javaText.append("|emc.initialize();\n");
    javaText.append(unwrapVals(values));
    if (!isStatic) {
        javaText.append("java.lang.Object |res = ((groovy.lang.MetaClassImpl)|emc).invokeMethod(|thiz0, \"").append(EVAL_NAME).append("\", |resVals);\n");
    } else {
        javaText.append("java.lang.Object |res = ((groovy.lang.MetaClassImpl)|emc).invokeStaticMethod(|clazz, \"").append(EVAL_NAME).append("\", |resVals);\n");
    }
    javaText.append("|res");
    final PsiElementFactory factory = JavaPsiFacade.getInstance(toEval.getProject()).getElementFactory();
    final String hiddenJavaVars = StringUtil.replace(javaText.toString(), "|", "_$_" + new Random().nextInt(42)).replaceAll("\\$OR\\$", "|");
    final String finalText = StringUtil.replace(StringUtil.replace(hiddenJavaVars, TEXT, groovyText), IMPORTS, textWithImports.getImports());
    final JavaCodeFragment result = JavaCodeFragmentFactory.getInstance(project).createCodeBlockCodeFragment(finalText, null, true);
    if (contextClass != null) {
        result.setThisType(factory.createType(contextClass));
    }
    return result;
}
Also used : GrTraitTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTraitTypeDefinition) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) THashMap(gnu.trove.THashMap) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Example 59 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class GroovyPositionManager method getClassNameForJvm.

@Nullable
private static String getClassNameForJvm(@NotNull final PsiClass typeDefinition) {
    String suffix = typeDefinition instanceof GrTypeDefinition && ((GrTypeDefinition) typeDefinition).isTrait() ? "$Trait$Helper" : "";
    final PsiClass psiClass = typeDefinition.getContainingClass();
    if (psiClass != null) {
        String parent = getClassNameForJvm(psiClass);
        return parent == null ? null : parent + "$" + typeDefinition.getName() + suffix;
    }
    PsiFile file = typeDefinition.getContainingFile();
    if (file instanceof GroovyFile && ((GroovyFile) file).isScript()) {
        for (ScriptPositionManagerHelper helper : ScriptPositionManagerHelper.EP_NAME.getExtensions()) {
            String s = helper.isAppropriateScriptFile((GroovyFile) file) ? helper.customizeClassName(typeDefinition) : null;
            if (s != null) {
                return s;
            }
        }
    }
    String qname = typeDefinition.getQualifiedName();
    return qname == null ? null : qname + suffix;
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) PsiClass(com.intellij.psi.PsiClass) ScriptPositionManagerHelper(org.jetbrains.plugins.groovy.extensions.debugger.ScriptPositionManagerHelper) PsiFile(com.intellij.psi.PsiFile) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) Nullable(org.jetbrains.annotations.Nullable)

Example 60 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class GStringBackspaceHandlerDelegate method beforeCharDeleted.

@Override
public void beforeCharDeleted(char c, PsiFile file, Editor editor) {
    if (c != '{')
        return;
    if (!(file instanceof GroovyFile))
        return;
    final int offset = editor.getCaretModel().getOffset();
    final EditorHighlighter highlighter = ((EditorEx) editor).getHighlighter();
    if (offset < 1)
        return;
    HighlighterIterator iterator = highlighter.createIterator(offset);
    if (iterator.getTokenType() != GroovyTokenTypes.mRCURLY)
        return;
    iterator.retreat();
    if (iterator.getStart() < 1 || iterator.getTokenType() != GroovyTokenTypes.mLCURLY)
        return;
    editor.getDocument().deleteString(offset, offset + 1);
}
Also used : EditorEx(com.intellij.openapi.editor.ex.EditorEx) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator) EditorHighlighter(com.intellij.openapi.editor.highlighter.EditorHighlighter)

Aggregations

GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)91 PsiFile (com.intellij.psi.PsiFile)26 PsiElement (com.intellij.psi.PsiElement)21 NotNull (org.jetbrains.annotations.NotNull)17 GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)17 VirtualFile (com.intellij.openapi.vfs.VirtualFile)13 Project (com.intellij.openapi.project.Project)10 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)10 PsiClass (com.intellij.psi.PsiClass)9 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)9 Nullable (org.jetbrains.annotations.Nullable)8 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)8 GroovyScriptClass (org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass)8 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)7 Module (com.intellij.openapi.module.Module)6 IncorrectOperationException (com.intellij.util.IncorrectOperationException)6 GrReferenceElement (org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)6 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)6 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)6 ASTNode (com.intellij.lang.ASTNode)5