@Override
 public List<Error> visit(MethodDecl m) {
   if (!m.ifExtern()) {
     this.visit(m.getBlock());
   }
   return this.getErrors();
 }
 private void generateSetter(
     final TYPE_TYPE type,
     final FIELD_TYPE field,
     final AccessLevel level,
     final String propertyNameFieldName) {
   String fieldName = field.name();
   boolean isBoolean = field.isOfType("boolean");
   String setterName = TransformationsUtil.toSetterName(fieldName, isBoolean);
   if (type.hasMethod(setterName)) return;
   String oldValueName = OLD_VALUE_VARIABLE_NAME;
   List<lombok.ast.Annotation> nonNulls = field.annotations(TransformationsUtil.NON_NULL_PATTERN);
   MethodDecl methodDecl =
       MethodDecl(Type("void"), setterName)
           .withAccessLevel(level)
           .withArgument(Arg(field.type(), fieldName).withAnnotations(nonNulls));
   if (!nonNulls.isEmpty() && !field.isPrimitive()) {
     methodDecl.withStatement(
         If(Equal(Name(fieldName), Null()))
             .Then(Throw(New(Type(NullPointerException.class)).withArgument(String(fieldName)))));
   }
   methodDecl
       .withStatement(
           LocalDecl(field.type(), oldValueName)
               .makeFinal()
               .withInitialization(Field(fieldName))) //
       .withStatement(Assign(Field(fieldName), Name(fieldName))) //
       .withStatement(
           Call(Call(PROPERTY_CHANGE_SUPPORT_METHOD_NAME), FIRE_PROPERTY_CHANGE_METHOD_NAME) //
               .withArgument(Name(propertyNameFieldName))
               .withArgument(Name(oldValueName))
               .withArgument(Field(fieldName)));
   type.injectMethod(methodDecl);
 }
 /** @apilevel internal */
 private boolean castingConversionTo_compute(TypeDecl type) {
   if (type.isArrayDecl()) {
     return type.instanceOf(this);
   } else if (type.isClassDecl()) {
     return !type.isFinal() || type.instanceOf(this);
   } else if (type.isInterfaceDecl()) {
     for (Iterator i1 = methodsIterator(); i1.hasNext(); ) {
       MethodDecl m = (MethodDecl) i1.next();
       for (Iterator iter = type.methodsSignature(m.signature()).iterator(); iter.hasNext(); ) {
         MethodDecl n = (MethodDecl) iter.next();
         if (n.type() != m.type()) return false;
       }
     }
     return true;
   } else return super.castingConversionTo(type);
 }
 /** @apilevel internal */
 private SimpleSet ancestorMethods_compute(String signature) {
   SimpleSet set = SimpleSet.emptySet;
   for (Iterator outerIter = superinterfacesIterator(); outerIter.hasNext(); ) {
     TypeDecl typeDecl = (TypeDecl) outerIter.next();
     for (Iterator iter = typeDecl.methodsSignature(signature).iterator(); iter.hasNext(); ) {
       MethodDecl m = (MethodDecl) iter.next();
       set = set.add(m);
     }
   }
   if (!superinterfacesIterator().hasNext()) {
     for (Iterator iter = typeObject().methodsSignature(signature).iterator(); iter.hasNext(); ) {
       MethodDecl m = (MethodDecl) iter.next();
       if (m.isPublic()) set = set.add(m);
     }
   }
   return set;
 }
  private void generateSetter(
      final TYPE_TYPE type,
      final FIELD_TYPE field,
      final AccessLevel level,
      final boolean vetoable,
      final boolean throwVetoException,
      final String propertyNameFieldName) {
    String fieldName = field.filteredName();
    boolean isBoolean = field.isOfType("boolean");
    String setterName =
        toSetterName(field.getAnnotationValue(Accessors.class), field.name(), isBoolean);
    if (type.hasMethod(setterName, field.type())) return;
    String oldValueName = OLD_VALUE_VARIABLE_NAME;
    List<lombok.ast.Annotation> nonNulls = field.annotations(TransformationsUtil.NON_NULL_PATTERN);
    MethodDecl methodDecl =
        MethodDecl(Type("void"), setterName)
            .withAccessLevel(level)
            .withArgument(Arg(field.type(), fieldName).withAnnotations(nonNulls));
    if (!nonNulls.isEmpty() && !field.isPrimitive()) {
      methodDecl.withStatement(
          If(Equal(Name(fieldName), Null()))
              .Then(Throw(New(Type(NullPointerException.class)).withArgument(String(fieldName)))));
    }

    methodDecl.withStatement(
        LocalDecl(field.type(), oldValueName).makeFinal().withInitialization(Field(fieldName)));

    if (vetoable) {
      if (throwVetoException) {
        methodDecl.withThrownException(Type(PropertyVetoException.class));
        methodDecl.withStatement(
            Call(FIRE_VETOABLE_CHANGE_METHOD_NAME) //
                .withArgument(Name(propertyNameFieldName))
                .withArgument(Name(oldValueName))
                .withArgument(Name(fieldName)));
      } else {
        methodDecl.withStatement(
            Try(Block()
                    .withStatement(
                        Call(FIRE_VETOABLE_CHANGE_METHOD_NAME) //
                            .withArgument(Name(propertyNameFieldName))
                            .withArgument(Name(oldValueName))
                            .withArgument(Name(fieldName)))) //
                .Catch(
                    Arg(Type(PropertyVetoException.class), E_VALUE_VARIABLE_NAME),
                    Block().withStatement(Return())));
      }
    }

    methodDecl
        .withStatement(Assign(Field(fieldName), Name(fieldName))) //
        .withStatement(
            Call(FIRE_PROPERTY_CHANGE_METHOD_NAME) //
                .withArgument(Name(propertyNameFieldName))
                .withArgument(Name(oldValueName))
                .withArgument(Name(fieldName)));
    type.editor().injectMethod(methodDecl);
  }
Exemple #6
0
  public void atMethodDecl(MethodDecl method) throws CompileError {
    ASTList mods = method.getModifiers();
    setMaxLocals(1);
    while (mods != null) {
      Keyword k = (Keyword) mods.head();
      mods = mods.tail();
      if (k.get() == STATIC) {
        setMaxLocals(0);
        inStaticMethod = true;
      }
    }

    ASTList params = method.getParams();
    while (params != null) {
      atDeclarator((Declarator) params.head());
      params = params.tail();
    }

    Stmnt s = method.getBody();
    atMethodBody(s, method.isConstructor(), method.getReturn().getType() == VOID);
  }
 /** @apilevel internal */
 private HashMap methodsSignatureMap_compute() {
   HashMap map = new HashMap(localMethodsSignatureMap());
   for (Iterator outerIter = superinterfacesIterator(); outerIter.hasNext(); ) {
     TypeDecl typeDecl = (TypeDecl) outerIter.next();
     for (Iterator iter = typeDecl.methodsIterator(); iter.hasNext(); ) {
       MethodDecl m = (MethodDecl) iter.next();
       if (!m.isPrivate()
           && m.accessibleFrom(this)
           && !localMethodsSignatureMap().containsKey(m.signature()))
         putSimpleSetElement(map, m.signature(), m);
     }
   }
   for (Iterator iter = typeObject().methodsIterator(); iter.hasNext(); ) {
     MethodDecl m = (MethodDecl) iter.next();
     if (m.isPublic() && !map.containsKey(m.signature()))
       putSimpleSetElement(map, m.signature(), m);
   }
   return map;
 }
 /**
  * @ast method
  * @aspect TypeHierarchyCheck
  * @declaredat /home/uoji/JastAddJ/Java1.4Frontend/TypeHierarchyCheck.jrag:312
  */
 public void nameCheck() {
   super.nameCheck();
   if (isCircular()) error("circular inheritance dependency in " + typeName());
   else {
     for (int i = 0; i < getNumSuperInterfaceId(); i++) {
       TypeDecl typeDecl = getSuperInterfaceId(i).type();
       if (typeDecl.isCircular()) error("circular inheritance dependency in " + typeName());
     }
   }
   for (Iterator iter = methodsSignatureMap().values().iterator(); iter.hasNext(); ) {
     SimpleSet set = (SimpleSet) iter.next();
     if (set.size() > 1) {
       Iterator i2 = set.iterator();
       MethodDecl m = (MethodDecl) i2.next();
       while (i2.hasNext()) {
         MethodDecl n = (MethodDecl) i2.next();
         if (!n.mayOverrideReturn(m) && !m.mayOverrideReturn(n))
           error(
               "multiply inherited methods with the same signature must have the same return type");
       }
     }
   }
 }
  @Override
  public void visit(MethodDecl method) {
    System.out.print("public ");
    if (method.getReturnType() != null) method.getReturnType().accept(this);
    System.out.print(" ");
    if (method.getId() != null) method.getId().accept(this);
    System.out.print(" (");

    if (method.getParams() != null) {
      for (int i = 0; i < method.getParams().size(); i++) {
        if (method.getParams().elementAt(i) == null) continue;

        method.getParams().elementAt(i).accept(this);
        if (i < method.getParams().size() - 1) System.out.print(", ");
      }
    }

    System.out.println(") {");

    if (method.getVars() != null) {
      for (int i = 0; i < method.getVars().size(); i++) {
        if (method.getVars().elementAt(i) == null) continue;

        System.out.print("\t\t");
        method.getVars().elementAt(i).accept(this);
        System.out.println();
      }
    }

    if (method.getStms() != null) {
      for (int i = 0; i < method.getStms().size(); i++) {
        if (method.getStms().elementAt(i) == null) continue;

        System.out.print("\t\t");
        method.getStms().elementAt(i).accept(this);
        System.out.println();
      }
    }

    System.out.print("\t\treturn ");
    if (method.getReturnExp() != null) method.getReturnExp().accept(this);
    System.out.println(";");
    System.out.println("\t}");
  }
  /**
   * @ast method
   * @aspect GenerateClassfile
   * @declaredat /home/uoji/JastAddJ/Java1.4Backend/GenerateClassfile.jrag:142
   */
  public void generateClassfile() {
    super.generateClassfile();
    String fileName = destinationPath() + File.separator + constantPoolName() + ".class";
    if (options().verbose()) System.out.println("Writing class file to " + fileName);
    try {
      ConstantPool cp = constantPool();
      // force building of constant pool
      cp.addClass(constantPoolName());
      cp.addClass("java/lang/Object");
      for (int i = 0; i < getNumSuperInterfaceId(); i++) {
        cp.addClass(getSuperInterfaceId(i).type().constantPoolName());
      }
      for (Iterator iter = bcFields().iterator(); iter.hasNext(); ) {
        FieldDeclaration field = (FieldDeclaration) iter.next();
        cp.addUtf8(field.name());
        cp.addUtf8(field.type().typeDescriptor());
        field.attributes();
      }
      for (Iterator iter = bcMethods().iterator(); iter.hasNext(); ) {
        Object obj = iter.next();
        if (obj instanceof MethodDecl) {
          MethodDecl m = (MethodDecl) obj;
          cp.addUtf8(m.name());
          cp.addUtf8(m.descName());
          m.attributes();
        }
      }
      attributes();

      if (hasClinit()) {
        cp.addUtf8("<clinit>");
        cp.addUtf8("()V");
        clinit_attributes();
      }

      // actual classfile generation
      File dest = new File(fileName);
      File parentFile = dest.getParentFile();
      if (parentFile != null) parentFile.mkdirs();

      FileOutputStream f = new FileOutputStream(fileName);
      DataOutputStream out = new DataOutputStream(new BufferedOutputStream(f));
      out.writeInt(magicHeader());
      out.writeChar(minorVersion());
      out.writeChar(majorVersion());
      cp.emit(out);
      int flags = flags();
      if (isNestedType()) flags = mangledFlags(flags);
      if (isInterfaceDecl()) flags |= Modifiers.ACC_INTERFACE;
      out.writeChar(flags);
      out.writeChar(cp.addClass(constantPoolName()));
      out.writeChar(cp.addClass("java/lang/Object"));
      if (getNumSuperInterfaceId() == 1 && getSuperInterfaceId(0).type().isObject())
        out.writeChar(0);
      else out.writeChar(getNumSuperInterfaceId());
      for (int i = 0; i < getNumSuperInterfaceId(); i++) {
        TypeDecl typeDecl = getSuperInterfaceId(i).type();
        if (typeDecl.isInterfaceDecl()) out.writeChar(cp.addClass(typeDecl.constantPoolName()));
      }
      Collection fields = bcFields();
      out.writeChar(fields.size());
      for (Iterator iter = fields.iterator(); iter.hasNext(); ) {
        FieldDeclaration field = (FieldDeclaration) iter.next();
        out.writeChar(field.flags());
        out.writeChar(cp.addUtf8(field.name()));
        out.writeChar(cp.addUtf8(field.type().typeDescriptor()));
        out.writeChar(field.attributes().size());
        for (Iterator itera = field.attributes().iterator(); itera.hasNext(); )
          ((Attribute) itera.next()).emit(out);
      }
      Collection methods = bcMethods();
      out.writeChar(methods.size() + (hasClinit() ? 1 : 0));
      for (Iterator iter = methods.iterator(); iter.hasNext(); ) {
        BodyDecl b = (BodyDecl) iter.next();
        b.generateMethod(out, cp);
      }
      if (hasClinit()) {
        out.writeChar(Modifiers.ACC_STATIC);
        out.writeChar(cp.addUtf8("<clinit>"));
        out.writeChar(cp.addUtf8("()V"));
        out.writeChar(clinit_attributes().size());
        for (Iterator itera = clinit_attributes().iterator(); itera.hasNext(); )
          ((Attribute) itera.next()).emit(out);
      }
      out.writeChar(attributes().size());
      for (Iterator itera = attributes().iterator(); itera.hasNext(); )
        ((Attribute) itera.next()).emit(out);

      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 /** @apilevel internal */
 public void flushCollectionCache() {
   super.flushCollectionCache();
 }
 /** @apilevel low-level */
 public void flushCache() {
   super.flushCache();
   sourceMethodDecl_computed = false;
   sourceMethodDecl_value = null;
 }
Exemple #13
0
  public void delegateMethodsTo(
      TYPE_TYPE type,
      MethodDescriptor[] methodDescriptors,
      Expression<?> receiver,
      Map<String, String> methodMapper) {
    for (MethodDescriptor methodDesc : methodDescriptors) {
      List<TypeRef> argTypes = new ArrayList<>();
      List<Argument> methodArgs = new ArrayList<>();
      List<Expression<?>> callArgs = new ArrayList<>();
      int argCounter = 0;
      for (MethodDescriptor.Type argType : methodDesc.arguments) {
        String argName = "arg" + argCounter++;
        TypeRef argTypeRef = asTypeRef(argType);
        argTypes.add(argTypeRef);
        Argument arg = Arg(argTypeRef, argName);
        if (argType.annotations.length > 0) {
          List<Annotation> annotations = new ArrayList<>();
          for (int i = 0; i < argType.annotations.length; i++) {
            annotations.add(Annotation(asTypeRef(argType.annotations[i])));
          }
          arg.withAnnotations(annotations);
        }
        methodArgs.add(arg);
        callArgs.add(Name(argName));
      }

      if (type.hasMethodIncludingSupertypes(
          methodDesc.methodName, argTypes.toArray(new TypeRef[argTypes.size()]))) {
        continue;
      }

      String delegateMethodName = methodMapper.get(methodDesc.methodName);
      if (delegateMethodName == null) {
        delegateMethodName = methodDesc.methodName;
      }

      Call methodCall = Call(receiver, delegateMethodName).withArguments(callArgs);
      MethodDecl methodDecl =
          MethodDecl(asTypeRef(methodDesc.returnType), methodDesc.methodName)
              .makePublic()
              .withArguments(methodArgs);
      if (VOID.equals(methodDesc.returnType.type)) {
        methodDecl.withStatement(methodCall);
      } else {
        methodDecl.withStatement(Return(methodCall));
      }
      if (methodDesc.typeParameters.length > 0) {
        List<TypeParam> types = new ArrayList<>();
        for (int i = 0; i < methodDesc.typeParameters.length; i++) {
          types.add(asTypeParam(methodDesc.typeParameters[i]));
        }
        methodDecl.withTypeParameters(types);
      }
      if (methodDesc.exceptions.length > 0) {
        List<TypeRef> exceptions = new ArrayList<>();
        for (int i = 0; i < methodDesc.exceptions.length; i++) {
          exceptions.add(asTypeRef(methodDesc.exceptions[i]));
        }
        methodDecl.withThrownExceptions(exceptions);
      }
      if (methodDesc.annotations.length > 0) {
        List<Annotation> annotations = new ArrayList<>();
        for (int i = 0; i < methodDesc.annotations.length; i++) {
          annotations.add(Annotation(asTypeRef(methodDesc.annotations[i])));
        }
        methodDecl.withAnnotations(annotations);
      }

      type.editor().injectMethod(methodDecl);
    }
  }
  @Override
  protected ClassDecl contributeBody(
      ClassDecl decl, ImportManager importManager, TreeClassDescriptor[] arg) {
    importManager.addImports(
        listOf(
            importDecl(qualifiedName("org.jlato.internal.bu")).setOnDemand(true),
            importDecl(qualifiedName("org.jlato.internal.bu.coll")).setOnDemand(true),
            importDecl(qualifiedName("org.jlato.internal.bu.decl")).setOnDemand(true),
            importDecl(qualifiedName("org.jlato.internal.bu.expr")).setOnDemand(true),
            importDecl(qualifiedName("org.jlato.internal.bu.name")).setOnDemand(true),
            importDecl(qualifiedName("org.jlato.internal.bu.stmt")).setOnDemand(true),
            importDecl(qualifiedName("org.jlato.internal.bu.type")).setOnDemand(true),
            importDecl(qualifiedName("org.jlato.internal.parser.Token")),
            importDecl(qualifiedName("org.jlato.internal.parser.TokenType")),
            importDecl(qualifiedName("org.jlato.tree.Problem.Severity")),
            importDecl(qualifiedName("org.jlato.parser.ParseException")),
            importDecl(qualifiedName("org.jlato.tree.expr.AssignOp")),
            importDecl(qualifiedName("org.jlato.tree.expr.BinaryOp")),
            importDecl(qualifiedName("org.jlato.tree.expr.UnaryOp")),
            importDecl(qualifiedName("org.jlato.tree.decl.ModifierKeyword")),
            importDecl(qualifiedName("org.jlato.tree.type.Primitive"))));

    List<GProduction> allProductions = productions.getAll();

    int memoizedProductionCount = MEMOIZE_ALL_MATCHES ? allProductions.size() : 0;
    if (!MEMOIZE_ALL_MATCHES) {
      for (GProduction production : allProductions) {
        if (production.memoizeMatches) memoizedProductionCount++;
      }
    }

    NodeList<MemberDecl> members = Trees.emptyList();
    members =
        members.append(
            memberDecl(
                    "protected int memoizedProductionCount() { return "
                        + memoizedProductionCount
                        + "; }")
                .build());

    for (GProduction production : allProductions) {
      if (excluded(production)) continue;

      parseMethods = parseMethods.append(parseMethod(importManager, production));
    }

    for (MethodDecl parseMethod : parseMethods) {
      members = members.append(parseMethod);

      String id = parseMethod.name().id();
      int indexOfUnderscore = id.indexOf('_');
      String symbol =
          id.substring("parse".length(), indexOfUnderscore == -1 ? id.length() : indexOfUnderscore);

      List<MethodDecl> methods = perSymbolMatchMethods.get(symbol);
      if (methods != null) {
        Collections.sort(methods, (m1, m2) -> m1.name().id().compareTo(m2.name().id()));
        members = members.appendAll(listOf(methods));
      }
    }

    return decl.withMembers(members);
  }