Exemplo n.º 1
0
 private static String lookupCategoryName(AnnotationNode logAnnotation) {
   Expression member = logAnnotation.getMember("category");
   if (member != null && member.getText() != null) {
     return member.getText();
   }
   return DEFAULT_CATEGORY_NAME;
 }
 @Override
 public void makeSingleArgumentCall(
     final Expression receiver, final String message, final Expression arguments) {
   TypeChooser typeChooser = controller.getTypeChooser();
   ClassNode classNode = controller.getClassNode();
   ClassNode rType = typeChooser.resolveType(receiver, classNode);
   ClassNode aType = typeChooser.resolveType(arguments, classNode);
   if (trySubscript(receiver, message, arguments, rType, aType)) {
     return;
   }
   // new try with flow type instead of declaration type
   rType = receiver.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
   if (rType != null && trySubscript(receiver, message, arguments, rType, aType)) {
     return;
   }
   // todo: more cases
   throw new GroovyBugError(
       "At line "
           + receiver.getLineNumber()
           + " column "
           + receiver.getColumnNumber()
           + "\n"
           + "On receiver: "
           + receiver.getText()
           + " with message: "
           + message
           + " and arguments: "
           + arguments.getText()
           + "\n"
           + "This method should not have been called. Please try to create a simple example reproducing this error and file"
           + "a bug report at http://jira.codehaus.org/browse/GROOVY");
 }
Exemplo n.º 3
0
 private static String lookupLogFieldName(AnnotationNode logAnnotation) {
   Expression member = logAnnotation.getMember("value");
   if (member != null && member.getText() != null) {
     return member.getText();
   } else {
     return "log";
   }
 }
  @Override
  protected void performInjectionInternal(
      String apiInstanceProperty, SourceUnit source, ClassNode classNode) {
    List<PropertyNode> tags = findTags(classNode);

    PropertyNode namespaceProperty = classNode.getProperty(NAMESPACE_PROPERTY);
    String namespace = GroovyPage.DEFAULT_NAMESPACE;
    if (namespaceProperty != null && namespaceProperty.isStatic()) {
      Expression initialExpression = namespaceProperty.getInitialExpression();
      if (initialExpression instanceof ConstantExpression) {
        namespace = initialExpression.getText();
      }
    }

    addGetTagLibNamespaceMethod(classNode, namespace);

    MethodCallExpression tagLibraryLookupMethodCall =
        new MethodCallExpression(
            new VariableExpression(apiInstanceProperty, ClassHelper.make(TagLibraryApi.class)),
            "getTagLibraryLookup",
            ZERO_ARGS);
    for (PropertyNode tag : tags) {
      String tagName = tag.getName();
      addAttributesAndBodyMethod(classNode, tagLibraryLookupMethodCall, tagName);
      addAttributesAndStringBodyMethod(classNode, tagName);
      addAttributesAndBodyMethod(classNode, tagLibraryLookupMethodCall, tagName, false);
      addAttributesAndBodyMethod(classNode, tagLibraryLookupMethodCall, tagName, true, false);
      addAttributesAndBodyMethod(classNode, tagLibraryLookupMethodCall, tagName, false, false);
    }
  }
  private void printField(PrintWriter out, FieldNode fieldNode, boolean isInterface) {
    if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
    printAnnotations(out, fieldNode);
    if (!isInterface) {
      printModifiers(out, fieldNode.getModifiers());
    }

    ClassNode type = fieldNode.getType();
    printType(out, type);

    out.print(" ");
    out.print(fieldNode.getName());
    if (isInterface || (fieldNode.getModifiers() & Opcodes.ACC_FINAL) != 0) {
      out.print(" = ");
      Expression valueExpr = fieldNode.getInitialValueExpression();
      if (valueExpr instanceof ConstantExpression) {
        valueExpr = Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) valueExpr);
      }
      if (valueExpr instanceof ConstantExpression
          && fieldNode.isStatic()
          && fieldNode.isFinal()
          && ClassHelper.isStaticConstantInitializerType(valueExpr.getType())
          && valueExpr.getType().equals(fieldNode.getType())) {
        // GROOVY-5150 : Initialize value with a dummy constant so that Java cross compiles
        // correctly
        if (ClassHelper.STRING_TYPE.equals(valueExpr.getType())) {
          out.print("\"" + escapeSpecialChars(valueExpr.getText()) + "\"");
        } else if (ClassHelper.char_TYPE.equals(valueExpr.getType())) {
          out.print("'" + valueExpr.getText() + "'");
        } else {
          ClassNode constantType = valueExpr.getType();
          out.print('(');
          printType(out, type);
          out.print(") ");
          out.print(valueExpr.getText());
          if (ClassHelper.Long_TYPE.equals(ClassHelper.getWrapper(constantType))) out.print('L');
        }
      } else if (ClassHelper.isPrimitiveType(type)) {
        String val = type == ClassHelper.boolean_TYPE ? "false" : "0";
        out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")");
      } else {
        out.print("null");
      }
    }
    out.println(";");
  }
 private Expression transformMapEntryExpression(
     MapEntryExpression me, ClassNode constructorCallType) {
   Expression key = me.getKeyExpression();
   Expression value = me.getValueExpression();
   ModuleNode module = currentClass.getModule();
   if (module != null && key instanceof ConstantExpression) {
     Map<String, ImportNode> importNodes = module.getStaticImports();
     if (importNodes.containsKey(key.getText())) {
       ImportNode importNode = importNodes.get(key.getText());
       if (importNode.getType().equals(constructorCallType)) {
         String newKey = importNode.getFieldName();
         return new MapEntryExpression(
             new ConstantExpression(newKey), value.transformExpression(this));
       }
     }
   }
   return me;
 }
 private List createPropertiesForHasManyExpression(Expression e, ClassNode classNode) {
   List properties = new ArrayList();
   if (e instanceof MapExpression) {
     MapExpression me = (MapExpression) e;
     List mapEntries = me.getMapEntryExpressions();
     for (Iterator j = mapEntries.iterator(); j.hasNext(); ) {
       MapEntryExpression mee = (MapEntryExpression) j.next();
       Expression keyExpression = mee.getKeyExpression();
       String key = keyExpression.getText();
       addAssociationForKey(key, properties, classNode);
     }
   }
   return properties;
 }
  protected void addError(String msg, ASTNode expr) {
    int line = expr.getLineNumber();
    int col = expr.getColumnNumber();
    // GRECLIPSE
    int start = expr.getStart();
    int end = expr.getEnd() - 1;
    if (expr instanceof ClassNode) {
      // assume we have a class declaration
      ClassNode cn = (ClassNode) expr;
      if (cn.getNameEnd() > 0) {
        start = cn.getNameStart();
        end = cn.getNameEnd();
      } else if (cn.getComponentType() != null) {
        // avoid extra whitespace after closing ]
        end--;
      }

    } else if (expr instanceof DeclarationExpression) {
      // assume that we just want to underline the variable declaration
      DeclarationExpression decl = (DeclarationExpression) expr;
      Expression lhs = decl.getLeftExpression();
      start = lhs.getStart();
      // avoid extra space before = if a variable
      end =
          lhs instanceof VariableExpression ? start + lhs.getText().length() - 1 : lhs.getEnd() - 1;
    }
    // end

    SourceUnit source = getSourceUnit();
    source
        .getErrorCollector()
        .addErrorAndContinue(
            // GRECLIPSE: start
            new SyntaxErrorMessage(
                new PreciseSyntaxException(msg + '\n', line, col, start, end), source)
            // end
            );
  }
  public void visit(ASTNode[] nodes, SourceUnit source) {
    sourceUnit = source;
    loader = null;
    initContextClassLoader = false;

    ModuleNode mn = (ModuleNode) nodes[0];

    allowShortGrab = true;
    allowShortGrabExcludes = true;
    allowShortGrabConfig = true;
    allowShortGrapes = true;
    allowShortGrabResolver = true;
    grabAliases = new HashSet<String>();
    grabExcludeAliases = new HashSet<String>();
    grabConfigAliases = new HashSet<String>();
    grapesAliases = new HashSet<String>();
    grabResolverAliases = new HashSet<String>();
    for (ImportNode im : mn.getImports()) {
      String alias = im.getAlias();
      String className = im.getClassName();
      if ((className.endsWith(GRAB_DOT_NAME) && ((alias == null) || (alias.length() == 0)))
          || (GRAB_CLASS_NAME.equals(alias))) {
        allowShortGrab = false;
      } else if (GRAB_CLASS_NAME.equals(className)) {
        grabAliases.add(im.getAlias());
      }
      if ((className.endsWith(GRAPES_DOT_NAME) && ((alias == null) || (alias.length() == 0)))
          || (GRAPES_CLASS_NAME.equals(alias))) {
        allowShortGrapes = false;
      } else if (GRAPES_CLASS_NAME.equals(className)) {
        grapesAliases.add(im.getAlias());
      }
      if ((className.endsWith(GRABRESOLVER_DOT_NAME) && ((alias == null) || (alias.length() == 0)))
          || (GRABRESOLVER_CLASS_NAME.equals(alias))) {
        allowShortGrabResolver = false;
      } else if (GRABRESOLVER_CLASS_NAME.equals(className)) {
        grabResolverAliases.add(im.getAlias());
      }
    }

    List<Map<String, Object>> grabMaps = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> grabExcludeMaps = new ArrayList<Map<String, Object>>();

    for (ClassNode classNode : sourceUnit.getAST().getClasses()) {
      grabAnnotations = new ArrayList<AnnotationNode>();
      grabExcludeAnnotations = new ArrayList<AnnotationNode>();
      grabConfigAnnotations = new ArrayList<AnnotationNode>();
      grapesAnnotations = new ArrayList<AnnotationNode>();
      grabResolverAnnotations = new ArrayList<AnnotationNode>();

      visitClass(classNode);

      ClassNode grapeClassNode = ClassHelper.make(Grape.class);

      List<Statement> grabResolverInitializers = new ArrayList<Statement>();

      if (!grapesAnnotations.isEmpty()) {
        for (AnnotationNode node : grapesAnnotations) {
          Expression init = node.getMember("initClass");
          Expression value = node.getMember("value");
          if (value instanceof ListExpression) {
            for (Object o : ((ListExpression) value).getExpressions()) {
              if (o instanceof ConstantExpression) {
                extractGrab(init, (ConstantExpression) o);
              }
            }
          } else if (value instanceof ConstantExpression) {
            extractGrab(init, (ConstantExpression) value);
          }
          // don't worry if it's not a ListExpression, or AnnotationConstant, etc.
          // the rest of GroovyC will flag it as a syntax error later, so we don't
          // need to raise the error ourselves
        }
      }

      if (!grabResolverAnnotations.isEmpty()) {
        grabResolverAnnotationLoop:
        for (AnnotationNode node : grabResolverAnnotations) {
          Map<String, Object> grabResolverMap = new HashMap<String, Object>();
          Expression value = node.getMember("value");
          ConstantExpression ce = null;
          if (value != null && value instanceof ConstantExpression) {
            ce = (ConstantExpression) value;
          }
          String sval = null;
          if (ce != null && ce.getValue() instanceof String) {
            sval = (String) ce.getValue();
          }
          if (sval != null && sval.length() > 0) {
            for (String s : GRABRESOLVER_REQUIRED) {
              Expression member = node.getMember(s);
              if (member != null) {
                addError(
                    "The attribute \""
                        + s
                        + "\" conflicts with attribute 'value' in @"
                        + node.getClassNode().getNameWithoutPackage()
                        + " annotations",
                    node);
                continue grabResolverAnnotationLoop;
              }
            }
            grabResolverMap.put("name", sval);
            grabResolverMap.put("root", sval);
          } else {
            for (String s : GRABRESOLVER_REQUIRED) {
              Expression member = node.getMember(s);
              if (member == null) {
                addError(
                    "The missing attribute \""
                        + s
                        + "\" is required in @"
                        + node.getClassNode().getNameWithoutPackage()
                        + " annotations",
                    node);
                continue grabResolverAnnotationLoop;
              } else if (member != null && !(member instanceof ConstantExpression)) {
                addError(
                    "Attribute \""
                        + s
                        + "\" has value "
                        + member.getText()
                        + " but should be an inline constant in @"
                        + node.getClassNode().getNameWithoutPackage()
                        + " annotations",
                    node);
                continue grabResolverAnnotationLoop;
              }
              grabResolverMap.put(s, ((ConstantExpression) member).getValue());
            }
          }
          Grape.addResolver(grabResolverMap);
          addGrabResolverAsStaticInitIfNeeded(
              grapeClassNode, node, grabResolverInitializers, grabResolverMap);
        }
      }

      if (!grabConfigAnnotations.isEmpty()) {
        for (AnnotationNode node : grabConfigAnnotations) {
          checkForClassLoader(node);
          checkForInitContextClassLoader(node);
          checkForAutoDownload(node);
          checkForDisableChecksums(node);
        }
        addInitContextClassLoaderIfNeeded(classNode);
      }

      if (!grabExcludeAnnotations.isEmpty()) {
        grabExcludeAnnotationLoop:
        for (AnnotationNode node : grabExcludeAnnotations) {
          Map<String, Object> grabExcludeMap = new HashMap<String, Object>();
          checkForConvenienceForm(node, true);
          for (String s : GRABEXCLUDE_REQUIRED) {
            Expression member = node.getMember(s);
            if (member == null) {
              addError(
                  "The missing attribute \""
                      + s
                      + "\" is required in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabExcludeAnnotationLoop;
            } else if (member != null && !(member instanceof ConstantExpression)) {
              addError(
                  "Attribute \""
                      + s
                      + "\" has value "
                      + member.getText()
                      + " but should be an inline constant in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabExcludeAnnotationLoop;
            }
            grabExcludeMap.put(s, ((ConstantExpression) member).getValue());
          }
          grabExcludeMaps.add(grabExcludeMap);
        }
      }

      if (!grabAnnotations.isEmpty()) {
        grabAnnotationLoop:
        for (AnnotationNode node : grabAnnotations) {
          Map<String, Object> grabMap = new HashMap<String, Object>();
          checkForConvenienceForm(node, false);
          for (String s : GRAB_ALL) {
            Expression member = node.getMember(s);
            if (member == null && !GRAB_OPTIONAL.contains(s)) {
              addError(
                  "The missing attribute \""
                      + s
                      + "\" is required in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabAnnotationLoop;
            } else if (member != null && !(member instanceof ConstantExpression)) {
              addError(
                  "Attribute \""
                      + s
                      + "\" has value "
                      + member.getText()
                      + " but should be an inline constant in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabAnnotationLoop;
            }
            if (node.getMember(s) != null) grabMap.put(s, ((ConstantExpression) member).getValue());
          }
          grabMaps.add(grabMap);
          callGrabAsStaticInitIfNeeded(classNode, grapeClassNode, node, grabExcludeMaps);
        }
      }

      if (!grabResolverInitializers.isEmpty()) {
        classNode.addStaticInitializerStatements(grabResolverInitializers, true);
      }
    }

    if (!grabMaps.isEmpty()) {
      Map<String, Object> basicArgs = new HashMap<String, Object>();
      basicArgs.put("classLoader", loader != null ? loader : sourceUnit.getClassLoader());
      if (!grabExcludeMaps.isEmpty()) basicArgs.put("excludes", grabExcludeMaps);
      if (autoDownload != null) basicArgs.put(AUTO_DOWNLOAD_SETTING, autoDownload);
      if (disableChecksums != null) basicArgs.put(DISABLE_CHECKSUMS_SETTING, disableChecksums);

      try {
        Grape.grab(basicArgs, grabMaps.toArray(new Map[grabMaps.size()]));
        // grab may have added more transformations through new URLs added to classpath, so do one
        // more scan
        if (compilationUnit != null) {
          ASTTransformationVisitor.addGlobalTransformsAfterGrab(
              compilationUnit.getASTTransformationsContext());
        }
      } catch (RuntimeException re) {
        // Decided against syntax exception since this is not a syntax error.
        // The down side is we lose line number information for the offending
        // @Grab annotation.
        source.addException(re);
      }
    }
  }
  public void visit(ASTNode[] nodes, SourceUnit source) {
    sourceUnit = source;
    loader = null;
    initContextClassLoader = false;

    ModuleNode mn = (ModuleNode) nodes[0];

    allowShortGrab = true;
    allowShortGrabExcludes = true;
    allowShortGrabConfig = true;
    allowShortGrapes = true;
    allowShortGrabResolver = true;
    grabAliases = new HashSet<String>();
    grabExcludeAliases = new HashSet<String>();
    grabConfigAliases = new HashSet<String>();
    grapesAliases = new HashSet<String>();
    grabResolverAliases = new HashSet<String>();
    for (ImportNode im : mn.getImports()) {
      String alias = im.getAlias();
      String className = im.getClassName();
      if ((className.endsWith(GRAB_DOT_NAME) && ((alias == null) || (alias.length() == 0)))
          || (GRAB_CLASS_NAME.equals(alias))) {
        allowShortGrab = false;
      } else if (GRAB_CLASS_NAME.equals(className)) {
        grabAliases.add(im.getAlias());
      }
      if ((className.endsWith(GRAPES_DOT_NAME) && ((alias == null) || (alias.length() == 0)))
          || (GRAPES_CLASS_NAME.equals(alias))) {
        allowShortGrapes = false;
      } else if (GRAPES_CLASS_NAME.equals(className)) {
        grapesAliases.add(im.getAlias());
      }
      if ((className.endsWith(GRABRESOLVER_DOT_NAME) && ((alias == null) || (alias.length() == 0)))
          || (GRABRESOLVER_CLASS_NAME.equals(alias))) {
        allowShortGrabResolver = false;
      } else if (GRABRESOLVER_CLASS_NAME.equals(className)) {
        grabResolverAliases.add(im.getAlias());
      }
    }

    List<Map<String, Object>> grabMaps = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> grabMapsInit = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> grabExcludeMaps = new ArrayList<Map<String, Object>>();

    for (ClassNode classNode : sourceUnit.getAST().getClasses()) {
      grabAnnotations = new ArrayList<AnnotationNode>();
      grabExcludeAnnotations = new ArrayList<AnnotationNode>();
      grabConfigAnnotations = new ArrayList<AnnotationNode>();
      grapesAnnotations = new ArrayList<AnnotationNode>();
      grabResolverAnnotations = new ArrayList<AnnotationNode>();

      visitClass(classNode);

      ClassNode grapeClassNode = ClassHelper.make(Grape.class);

      List<Statement> grabResolverInitializers = new ArrayList<Statement>();

      if (!grapesAnnotations.isEmpty()) {
        for (AnnotationNode node : grapesAnnotations) {
          Expression init = node.getMember("initClass");
          Expression value = node.getMember("value");
          if (value instanceof ListExpression) {
            for (Object o : ((ListExpression) value).getExpressions()) {
              if (o instanceof ConstantExpression) {
                extractGrab(init, (ConstantExpression) o);
              }
            }
          } else if (value instanceof ConstantExpression) {
            extractGrab(init, (ConstantExpression) value);
          }
          // don't worry if it's not a ListExpression, or AnnotationConstant, etc.
          // the rest of GroovyC will flag it as a syntax error later, so we don't
          // need to raise the error ourselves
        }
      }

      if (!grabResolverAnnotations.isEmpty()) {
        grabResolverAnnotationLoop:
        for (AnnotationNode node : grabResolverAnnotations) {
          Map<String, Object> grabResolverMap = new HashMap<String, Object>();
          String sval = getMemberStringValue(node, "value");
          if (sval != null && sval.length() > 0) {
            for (String s : GRABRESOLVER_REQUIRED) {
              String mval = getMemberStringValue(node, s);
              if (mval != null && mval.isEmpty()) mval = null;
              if (mval != null) {
                addError(
                    "The attribute \""
                        + s
                        + "\" conflicts with attribute 'value' in @"
                        + node.getClassNode().getNameWithoutPackage()
                        + " annotations",
                    node);
                continue grabResolverAnnotationLoop;
              }
            }
            grabResolverMap.put("name", sval);
            grabResolverMap.put("root", sval);
          } else {
            for (String s : GRABRESOLVER_REQUIRED) {
              String mval = getMemberStringValue(node, s);
              if (mval != null && mval.isEmpty()) mval = null;
              Expression member = node.getMember(s);
              if (member == null || mval == null) {
                addError(
                    "The missing attribute \""
                        + s
                        + "\" is required in @"
                        + node.getClassNode().getNameWithoutPackage()
                        + " annotations",
                    node);
                continue grabResolverAnnotationLoop;
              } else if (mval == null) {
                addError(
                    "Attribute \""
                        + s
                        + "\" has value "
                        + member.getText()
                        + " but should be an inline constant String in @"
                        + node.getClassNode().getNameWithoutPackage()
                        + " annotations",
                    node);
                continue grabResolverAnnotationLoop;
              }
              grabResolverMap.put(s, mval);
            }
          }

          // If no scheme is specified for the repository root,
          // then turn it into a URI relative to that of the source file.
          String root = (String) grabResolverMap.get("root");
          if (root != null && !root.contains(":")) {
            URI sourceURI = null;
            // Since we use the data: scheme for StringReaderSources (which are fairly common)
            // and those are not hierarchical we can't use them for making an absolute URI.
            if (!(getSourceUnit().getSource() instanceof StringReaderSource)) {
              // Otherwise let's trust the source to know where it is from.
              // And actually InputStreamReaderSource doesn't know what to do and so returns null.
              sourceURI = getSourceUnit().getSource().getURI();
            }
            // If source doesn't know how to get a reference to itself,
            // then let's use the current working directory, since the repo can be relative to that.
            if (sourceURI == null) {
              sourceURI = new File(".").toURI();
            }
            try {
              URI rootURI = sourceURI.resolve(new URI(root));
              grabResolverMap.put("root", rootURI.toString());
            } catch (URISyntaxException e) {
              // We'll be silent here.
              // If the URI scheme is unknown or not hierarchical, then we just can't help them and
              // shouldn't cause any trouble either.
              // addError("Attribute \"root\" has value '" + root + "' which can't be turned into a
              // valid URI relative to it's source '" + getSourceUnit().getName() + "' @" +
              // node.getClassNode().getNameWithoutPackage() + " annotations", node);
            }
          }

          Grape.addResolver(grabResolverMap);
          addGrabResolverAsStaticInitIfNeeded(
              grapeClassNode, node, grabResolverInitializers, grabResolverMap);
        }
      }

      if (!grabConfigAnnotations.isEmpty()) {
        for (AnnotationNode node : grabConfigAnnotations) {
          checkForClassLoader(node);
          checkForInitContextClassLoader(node);
          checkForAutoDownload(node);
          checkForDisableChecksums(node);
        }
        addInitContextClassLoaderIfNeeded(classNode);
      }

      if (!grabExcludeAnnotations.isEmpty()) {
        grabExcludeAnnotationLoop:
        for (AnnotationNode node : grabExcludeAnnotations) {
          Map<String, Object> grabExcludeMap = new HashMap<String, Object>();
          checkForConvenienceForm(node, true);
          for (String s : GRABEXCLUDE_REQUIRED) {
            Expression member = node.getMember(s);
            if (member == null) {
              addError(
                  "The missing attribute \""
                      + s
                      + "\" is required in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabExcludeAnnotationLoop;
            } else if (member != null && !(member instanceof ConstantExpression)) {
              addError(
                  "Attribute \""
                      + s
                      + "\" has value "
                      + member.getText()
                      + " but should be an inline constant in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabExcludeAnnotationLoop;
            }
            grabExcludeMap.put(s, ((ConstantExpression) member).getValue());
          }
          grabExcludeMaps.add(grabExcludeMap);
        }
      }

      if (!grabAnnotations.isEmpty()) {
        grabAnnotationLoop:
        for (AnnotationNode node : grabAnnotations) {
          Map<String, Object> grabMap = new HashMap<String, Object>();
          checkForConvenienceForm(node, false);
          for (String s : GRAB_ALL) {
            Expression member = node.getMember(s);
            String mval = getMemberStringValue(node, s);
            if (mval != null && mval.isEmpty()) member = null;
            if (member == null && !GRAB_OPTIONAL.contains(s)) {
              addError(
                  "The missing attribute \""
                      + s
                      + "\" is required in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabAnnotationLoop;
            } else if (member != null && !(member instanceof ConstantExpression)) {
              addError(
                  "Attribute \""
                      + s
                      + "\" has value "
                      + member.getText()
                      + " but should be an inline constant in @"
                      + node.getClassNode().getNameWithoutPackage()
                      + " annotations",
                  node);
              continue grabAnnotationLoop;
            }
            if (node.getMember(s) != null) {
              grabMap.put(s, ((ConstantExpression) member).getValue());
            }
          }
          grabMaps.add(grabMap);
          if ((node.getMember("initClass") == null)
              || (node.getMember("initClass") == ConstantExpression.TRUE)) {
            grabMapsInit.add(grabMap);
          }
        }
        callGrabAsStaticInitIfNeeded(classNode, grapeClassNode, grabMapsInit, grabExcludeMaps);
      }

      if (!grabResolverInitializers.isEmpty()) {
        classNode.addStaticInitializerStatements(grabResolverInitializers, true);
      }
    }

    if (!grabMaps.isEmpty()) {
      Map<String, Object> basicArgs = new HashMap<String, Object>();
      basicArgs.put("classLoader", loader != null ? loader : sourceUnit.getClassLoader());
      if (!grabExcludeMaps.isEmpty()) basicArgs.put("excludes", grabExcludeMaps);
      if (autoDownload != null) basicArgs.put(AUTO_DOWNLOAD_SETTING, autoDownload);
      if (disableChecksums != null) basicArgs.put(DISABLE_CHECKSUMS_SETTING, disableChecksums);

      try {
        Grape.grab(basicArgs, grabMaps.toArray(new Map[grabMaps.size()]));
        // grab may have added more transformations through new URLs added to classpath, so do one
        // more scan
        if (compilationUnit != null) {
          ASTTransformationVisitor.addGlobalTransformsAfterGrab(
              compilationUnit.getASTTransformationsContext());
        }
      } catch (RuntimeException re) {
        // Decided against syntax exception since this is not a syntax error.
        // The down side is we lose line number information for the offending
        // @Grab annotation.
        source.addException(re);
      }
    }
  }
Exemplo n.º 11
0
  protected Expression transformMethodCallExpression(MethodCallExpression mce) {
    Expression args = transform(mce.getArguments());
    Expression method = transform(mce.getMethod());
    Expression object = transform(mce.getObjectExpression());
    boolean isExplicitThisOrSuper = false;
    if (object instanceof VariableExpression) {
      VariableExpression ve = (VariableExpression) object;
      isExplicitThisOrSuper =
          !mce.isImplicitThis() && (ve.getName().equals("this") || ve.getName().equals("super"));
    }

    if (mce.isImplicitThis() || isExplicitThisOrSuper) {
      if (mce.isImplicitThis()) {
        Expression ret = findStaticMethodImportFromModule(method, args);
        if (ret != null) {
          // GRECLIPSE add
          if (!((StaticMethodCallExpression) ret).getMethod().equals(method.getText())) {
            // store the identifier to facilitate organizing static imports
            ret.setNodeMetaData("static.import.alias", method.getText());
          }
          // GRECLIPSE end
          setSourcePosition(ret, mce);
          return ret;
        }
        if (method instanceof ConstantExpression && !inLeftExpression) {
          // could be a closure field
          String methodName = (String) ((ConstantExpression) method).getValue();
          ret = findStaticFieldOrPropAccessorImportFromModule(methodName);
          if (ret != null) {
            ret = new MethodCallExpression(ret, "call", args);
            setSourcePosition(ret, mce);
            return ret;
          }
        }
      }

      if (method instanceof ConstantExpression) {
        ConstantExpression ce = (ConstantExpression) method;
        Object value = ce.getValue();
        if (value instanceof String) {
          String methodName = (String) value;
          boolean lookForPossibleStaticMethod = !methodName.equals("call");
          if (currentMethod != null && !currentMethod.isStatic()) {
            if (currentClass.hasPossibleMethod(methodName, args)) {
              lookForPossibleStaticMethod = false;
            }
          }
          if (inSpecialConstructorCall
              || (lookForPossibleStaticMethod
                  && currentClass.hasPossibleStaticMethod(methodName, args))) {
            StaticMethodCallExpression smce =
                new StaticMethodCallExpression(currentClass, methodName, args);
            setSourcePosition(smce, mce);
            return smce;
          }
        }
      }
    }

    MethodCallExpression result = new MethodCallExpression(object, method, args);
    result.setSafe(mce.isSafe());
    result.setImplicitThis(mce.isImplicitThis());
    result.setSpreadSafe(mce.isSpreadSafe());
    result.setMethodTarget(mce.getMethodTarget());
    // GROOVY-6757
    result.setGenericsTypes(mce.getGenericsTypes());
    setSourcePosition(result, mce);
    return result;
  }
Exemplo n.º 12
0
 public static boolean targetIsThis(MethodCallExpression call) {
   Expression target = call.getObjectExpression();
   return target instanceof VariableExpression && target.getText().equals("this");
 }