Search in sources :

Example 31 with GrLiteral

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral in project android by JetBrains.

the class GradleFilePsiMerger method pullDependenciesIntoMap.

/**
   * Looks for statements adding dependencies to different configurations (which look like 'configurationName "dependencyCoordinate"')
   * and tries to parse them into Gradle coordinates. If successful, adds the new coordinate to the map and removes the corresponding
   * PsiElement from the tree.
   *
   * @return true if new items were added to the map
   */
private static boolean pullDependenciesIntoMap(@NotNull PsiElement root, @NotNull Map<String, Multimap<String, GradleCoordinate>> allConfigurations, @Nullable List<String> unparsedDependencies) {
    boolean wasMapUpdated = false;
    for (PsiElement existingElem : root.getChildren()) {
        if (existingElem instanceof GrCall) {
            PsiElement reference = existingElem.getFirstChild();
            if (reference instanceof GrReferenceExpression) {
                final String configurationName = reference.getText();
                boolean parsed = false;
                GrCall call = (GrCall) existingElem;
                GrArgumentList arguments = call.getArgumentList();
                // Don't try merging dependencies if one of them has a closure block attached.
                if (arguments != null && call.getClosureArguments().length == 0) {
                    GrExpression[] expressionArguments = arguments.getExpressionArguments();
                    if (expressionArguments.length == 1 && expressionArguments[0] instanceof GrLiteral) {
                        Object value = ((GrLiteral) expressionArguments[0]).getValue();
                        if (value instanceof String) {
                            String coordinateText = (String) value;
                            GradleCoordinate coordinate = GradleCoordinate.parseCoordinateString(coordinateText);
                            if (coordinate != null) {
                                parsed = true;
                                Multimap<String, GradleCoordinate> map = allConfigurations.get(configurationName);
                                if (map == null) {
                                    map = LinkedListMultimap.create();
                                    allConfigurations.put(configurationName, map);
                                }
                                if (!map.get(coordinate.getId()).contains(coordinate)) {
                                    map.put(coordinate.getId(), coordinate);
                                    existingElem.delete();
                                    wasMapUpdated = true;
                                }
                            }
                        }
                    }
                    if (!parsed && unparsedDependencies != null) {
                        unparsedDependencies.add(existingElem.getText());
                    }
                }
            }
        }
    }
    return wasMapUpdated;
}
Also used : GradleCoordinate(com.android.ide.common.repository.GradleCoordinate) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) GrCall(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral) PsiElement(com.intellij.psi.PsiElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 32 with GrLiteral

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral in project android by JetBrains.

the class GradleSettingsFile method addModule.

/**
   * Adds a reference to the module to the settings file, if there is not already one. The module path must be colon separated, with a
   * leading colon, e.g. ":project:subproject". Must be run inside a write action.
   *
   * If the file does not match the default module location, this method will override the location.
   */
public void addModule(@NotNull String modulePath, @NotNull File location) {
    checkInitialized();
    commitDocumentChanges();
    for (GrMethodCall includeStatement : getMethodCalls(myGroovyFile, INCLUDE_METHOD)) {
        for (GrLiteral lit : getLiteralArguments(includeStatement)) {
            if (modulePath.equals(lit.getValue())) {
                return;
            }
        }
    }
    GrMethodCall includeStatement = getMethodCall(myGroovyFile, INCLUDE_METHOD);
    if (includeStatement != null) {
        GrArgumentList argList = includeStatement.getArgumentList();
        GrLiteral literal = GroovyPsiElementFactory.getInstance(myProject).createLiteralFromValue(modulePath);
        argList.addAfter(literal, argList.getLastChild());
    } else {
        GrStatement statement = GroovyPsiElementFactory.getInstance(myProject).createStatementFromText(INCLUDE_METHOD + " '" + modulePath + "'");
        myGroovyFile.add(statement);
    }
    // We get location relative to this file parent
    VirtualFile parent = getFile().getParent();
    File defaultLocation = GradleUtil.getModuleDefaultPath(parent, modulePath);
    if (!FileUtil.filesEqual(defaultLocation, location)) {
        final String path;
        File parentFile = VfsUtilCore.virtualToIoFile(parent);
        if (FileUtil.isAncestor(parentFile, location, true)) {
            path = PathUtil.toSystemIndependentName(FileUtil.getRelativePath(parentFile, location));
        } else {
            path = PathUtil.toSystemIndependentName(location.getAbsolutePath());
        }
        String locationAssignment = String.format(CUSTOM_LOCATION_FORMAT, modulePath, path);
        GrStatement locationStatement = GroovyPsiElementFactory.getInstance(myProject).createStatementFromText(locationAssignment);
        myGroovyFile.add(locationStatement);
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)

Example 33 with GrLiteral

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral in project android by JetBrains.

the class GradleSettingsFile method removeModule.

/**
   * Removes the reference to the module from the settings file, if present. The module path must be colon separated, with a
   * leading colon, e.g. ":project:subproject". Must be run inside a write action.
   */
public void removeModule(@NotNull String modulePath) {
    checkInitialized();
    commitDocumentChanges();
    boolean removedAnyIncludes = false;
    for (GrMethodCall includeStatement : getMethodCalls(myGroovyFile, INCLUDE_METHOD)) {
        for (GrLiteral lit : getLiteralArguments(includeStatement)) {
            if (modulePath.equals(lit.getValue())) {
                lit.delete();
                removedAnyIncludes = true;
                if (getArguments(includeStatement).length == 0) {
                    includeStatement.delete();
                // If this happens we will fall through both for loops before we get into iteration trouble. We want to keep iterating in
                // case the module is added more than once (via hand-editing of the file).
                }
            }
        }
    }
    if (removedAnyIncludes) {
        for (Pair<String, GrAssignmentExpression> pair : getAllProjectLocationStatements()) {
            if (modulePath.equals(pair.first)) {
                pair.second.delete();
            }
        }
    }
}
Also used : GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral)

Example 34 with GrLiteral

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral in project android by JetBrains.

the class LintIdeGradleDetector method visitBuildScript.

@Override
public void visitBuildScript(@NonNull final Context context, Map<String, Object> sharedData) {
    ApplicationManager.getApplication().runReadAction(new Runnable() {

        @Override
        public void run() {
            final PsiFile psiFile = LintIdeUtils.getPsiFile(context);
            if (!(psiFile instanceof GroovyFile)) {
                return;
            }
            GroovyFile groovyFile = (GroovyFile) psiFile;
            groovyFile.accept(new GroovyRecursiveElementVisitor() {

                @Override
                public void visitClosure(GrClosableBlock closure) {
                    String parentName = getClosureName(closure);
                    String parentParentName = null;
                    if (parentName != null) {
                        GrClosableBlock block = PsiTreeUtil.getParentOfType(closure, GrClosableBlock.class, true);
                        if (block != null) {
                            parentParentName = getClosureName(block);
                        }
                    }
                    if (parentName != null && isInterestingBlock(parentName, parentParentName)) {
                        for (PsiElement element : closure.getChildren()) {
                            if (element instanceof GrApplicationStatement) {
                                GrApplicationStatement call = (GrApplicationStatement) element;
                                GrExpression propertyExpression = call.getInvokedExpression();
                                GrCommandArgumentList argumentList = call.getArgumentList();
                                if (propertyExpression instanceof GrReferenceExpression) {
                                    GrReferenceExpression propertyRef = (GrReferenceExpression) propertyExpression;
                                    String property = propertyRef.getReferenceName();
                                    //noinspection ConstantConditions
                                    if (property != null && isInterestingProperty(property, parentName, parentParentName) && argumentList != null) {
                                        String value = argumentList.getText();
                                        checkDslPropertyAssignment(context, property, value, parentName, parentParentName, argumentList, call);
                                    }
                                }
                            } else if (element instanceof GrAssignmentExpression) {
                                GrAssignmentExpression assignment = (GrAssignmentExpression) element;
                                GrExpression lValue = assignment.getLValue();
                                if (lValue instanceof GrReferenceExpression) {
                                    GrReferenceExpression propertyRef = (GrReferenceExpression) lValue;
                                    String property = propertyRef.getReferenceName();
                                    if (property != null && isInterestingProperty(property, parentName, parentParentName)) {
                                        GrExpression rValue = assignment.getRValue();
                                        if (rValue != null) {
                                            String value = rValue.getText();
                                            checkDslPropertyAssignment(context, property, value, parentName, parentParentName, rValue, assignment);
                                            // handle it here.
                                            if (property.equals(ATTR_MIN_SDK_VERSION) || property.equals(ATTR_TARGET_SDK_VERSION)) {
                                                int lValueEnd = lValue.getTextRange().getEndOffset();
                                                int rValueStart = rValue.getTextRange().getStartOffset();
                                                assert lValueEnd <= rValueStart;
                                                DefaultPosition startPosition = new DefaultPosition(-1, -1, lValueEnd);
                                                DefaultPosition endPosition = new DefaultPosition(-1, -1, rValueStart);
                                                Location location = Location.create(context.file, startPosition, endPosition);
                                                String message = String.format("Do not use assignment with the %1$s property (remove the '=')", property);
                                                context.report(GradleDetector.IDE_SUPPORT, location, message, null);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    super.visitClosure(closure);
                }

                @Override
                public void visitApplicationStatement(GrApplicationStatement applicationStatement) {
                    GrClosableBlock block = PsiTreeUtil.getParentOfType(applicationStatement, GrClosableBlock.class, true);
                    String parentName = block != null ? getClosureName(block) : null;
                    String statementName = applicationStatement.getInvokedExpression().getText();
                    if (isInterestingStatement(statementName, parentName)) {
                        GrCommandArgumentList argumentList = applicationStatement.getArgumentList();
                        Map<String, String> namedArguments = Maps.newHashMap();
                        List<String> unnamedArguments = Lists.newArrayList();
                        for (GroovyPsiElement groovyPsiElement : argumentList.getAllArguments()) {
                            if (groovyPsiElement instanceof GrNamedArgument) {
                                GrNamedArgument namedArgument = (GrNamedArgument) groovyPsiElement;
                                GrExpression expression = namedArgument.getExpression();
                                if (expression == null || !(expression instanceof GrLiteral)) {
                                    continue;
                                }
                                Object value = ((GrLiteral) expression).getValue();
                                if (value == null) {
                                    continue;
                                }
                                namedArguments.put(namedArgument.getLabelName(), value.toString());
                            } else if (groovyPsiElement instanceof GrExpression) {
                                unnamedArguments.add(groovyPsiElement.getText());
                            }
                        }
                        checkMethodCall(context, statementName, parentName, namedArguments, unnamedArguments, applicationStatement);
                    }
                    super.visitApplicationStatement(applicationStatement);
                }
            });
        }
    });
}
Also used : GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) PsiFile(com.intellij.psi.PsiFile) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) PsiElement(com.intellij.psi.PsiElement) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Example 35 with GrLiteral

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral in project android by JetBrains.

the class GradleDslLiteral method getValue.

@Override
@Nullable
public Object getValue() {
    if (myUnsavedValue != null) {
        return myUnsavedValue;
    }
    if (myExpression == null) {
        return null;
    }
    Object value = ((GrLiteral) myExpression).getValue();
    if (value != null) {
        return value;
    }
    if (myExpression instanceof GrString) {
        // String literal with variables. ex: compileSdkVersion = "$ANDROID-${VERSION}"
        String literalText = myExpression.getText();
        if (isQuotedString(literalText)) {
            literalText = unquoteString(literalText);
        }
        List<GradleResolvedVariable> resolvedVariables = Lists.newArrayList();
        GrStringInjection[] injections = ((GrString) myExpression).getInjections();
        for (GrStringInjection injection : injections) {
            String variableName = null;
            GrClosableBlock closableBlock = injection.getClosableBlock();
            if (closableBlock != null) {
                String blockText = closableBlock.getText();
                variableName = blockText.substring(1, blockText.length() - 1);
            } else {
                GrExpression expression = injection.getExpression();
                if (expression != null) {
                    variableName = expression.getText();
                }
            }
            if (!isEmpty(variableName)) {
                GradleDslExpression resolvedExpression = resolveReference(variableName, GradleDslExpression.class);
                if (resolvedExpression != null) {
                    Object resolvedValue = resolvedExpression.getValue();
                    if (resolvedValue != null) {
                        resolvedVariables.add(new GradleResolvedVariable(variableName, resolvedValue, resolvedExpression));
                        literalText = literalText.replace(injection.getText(), resolvedValue.toString());
                    }
                }
            }
        }
        setResolvedVariables(resolvedVariables);
        return literalText;
    }
    return null;
}
Also used : GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString) GradleResolvedVariable(com.android.tools.idea.gradle.dsl.parser.GradleResolvedVariable) GrStringInjection(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

GrLiteral (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral)45 Nullable (org.jetbrains.annotations.Nullable)14 PsiElement (com.intellij.psi.PsiElement)13 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)10 NonNls (org.jetbrains.annotations.NonNls)9 PsiType (com.intellij.psi.PsiType)6 GrArgumentList (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList)6 GrString (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString)6 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)5 TextRange (com.intellij.openapi.util.TextRange)4 BigInteger (java.math.BigInteger)4 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)4 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)4 GrStringInjection (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection)4 Document (com.intellij.openapi.editor.Document)3 Project (com.intellij.openapi.project.Project)3 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 GrNamedArgument (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument)3 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)3 GrMethodCallExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression)3