Exemple #1
0
 /** Returns a list of all names of source files in the tree. */
 private ListBuffer<String> addAllChildren(IResource root) {
   ListBuffer<String> result = new ListBuffer<String>();
   for (IJavaElement element : JavaElementUtils.listJavaElements(root)) {
     result.append(element.getLocation());
   }
   return result;
 }
 /** Returns a list of the expressions in the given list */
 public static List<JCExpression> toExpressionList(Iterable<ExpressionAndType> exprAndTypes) {
   ListBuffer<JCExpression> lb = ListBuffer.<JCExpression>lb();
   for (ExpressionAndType arg : exprAndTypes) {
     lb.append(arg.expression);
   }
   return lb.toList();
 }
Exemple #3
0
 /**
  * * Get a localized string representation for all the symbols in the input list.
  *
  * @param ts symbols to be displayed
  * @param locale the locale in which the string is to be rendered
  * @return localized string representation
  */
 public String visitSymbols(List<Symbol> ts, Locale locale) {
   ListBuffer<String> sbuf = ListBuffer.lb();
   for (Symbol t : ts) {
     sbuf.append(visit(t, locale));
   }
   return sbuf.toList().toString();
 }
  public JCTree.JCMethodDecl build() {
    if (built) {
      throw new IllegalStateException();
    }
    built = true;

    ListBuffer<JCVariableDecl> params = ListBuffer.lb();
    for (ParameterDefinitionBuilder pdb : this.params) {
      if (noAnnotations || ignoreAnnotations) {
        pdb.noAnnotations();
      }
      params.append(pdb.build());
    }

    return gen.make()
        .MethodDef(
            gen.make().Modifiers(modifiers, getAnnotations().toList()),
            makeName(name),
            resultTypeExpr,
            typeParams.toList(),
            params.toList(),
            List.<JCExpression>nil(),
            makeBody(body),
            null);
  }
Exemple #5
0
 /**
  * Get a localized string representation for all the types in the input list.
  *
  * @param ts types to be displayed
  * @param locale the locale in which the string is to be rendered
  * @return localized string representation
  */
 public String visitTypes(List<Type> ts, Locale locale) {
   ListBuffer<String> sbuf = ListBuffer.lb();
   for (Type t : ts) {
     sbuf.append(visit(t, locale));
   }
   return sbuf.toList().toString();
 }
Exemple #6
0
  public JCMethodDecl generateBuilderMethod(
      String builderMethodName,
      String builderClassName,
      JavacNode type,
      List<JCTypeParameter> typeParams) {
    JavacTreeMaker maker = type.getTreeMaker();

    ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
    for (JCTypeParameter typeParam : typeParams) {
      typeArgs.append(maker.Ident(typeParam.name));
    }

    JCExpression call =
        maker.NewClass(
            null,
            List.<JCExpression>nil(),
            namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams),
            List.<JCExpression>nil(),
            null);
    JCStatement statement = maker.Return(call);

    JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
    return maker.MethodDef(
        maker.Modifiers(Flags.STATIC | Flags.PUBLIC),
        type.toName(builderMethodName),
        namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams),
        copyTypeParams(maker, typeParams),
        List.<JCVariableDecl>nil(),
        List.<JCExpression>nil(),
        body,
        null);
  }
  /**
   * Given a list of field names and a node referring to a type, finds each name in the list that
   * does not match a field within the type.
   */
  public static List<Integer> createListOfNonExistentFields(
      List<String> list, JavacNode type, boolean excludeStandard, boolean excludeTransient) {
    boolean[] matched = new boolean[list.size()];

    for (JavacNode child : type.down()) {
      if (list.isEmpty()) break;
      if (child.getKind() != Kind.FIELD) continue;
      JCVariableDecl field = (JCVariableDecl) child.get();
      if (excludeStandard) {
        if ((field.mods.flags & Flags.STATIC) != 0) continue;
        if (field.name.toString().startsWith("$")) continue;
      }
      if (excludeTransient && (field.mods.flags & Flags.TRANSIENT) != 0) continue;

      int idx = list.indexOf(child.getName());
      if (idx > -1) matched[idx] = true;
    }

    ListBuffer<Integer> problematic = ListBuffer.lb();
    for (int i = 0; i < list.size(); i++) {
      if (!matched[i]) problematic.append(i);
    }

    return problematic.toList();
  }
 private static List<JCAnnotation> filterList(List<JCAnnotation> annotations, JCTree jcTree) {
   ListBuffer<JCAnnotation> newAnnotations = ListBuffer.lb();
   for (JCAnnotation ann : annotations) {
     if (jcTree != ann) newAnnotations.append(ann);
   }
   return newAnnotations.toList();
 }
 public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
   ListBuffer<File> files = new ListBuffer<File>();
   for (String name : names) {
     files.append(new File(name));
   }
   return getJavaFileObjectsFromFiles(files.toList());
 }
 static List<JCAnnotation> copyAnnotations(List<? extends JCExpression> in) {
   ListBuffer<JCAnnotation> out = ListBuffer.lb();
   for (JCExpression expr : in) {
     if (!(expr instanceof JCAnnotation)) continue;
     out.append((JCAnnotation) expr.clone());
   }
   return out.toList();
 }
 private static List<JCTree> addAllButOne(List<JCTree> defs, int idx) {
   ListBuffer<JCTree> out = ListBuffer.lb();
   int i = 0;
   for (JCTree def : defs) {
     if (i++ != idx) out.append(def);
   }
   return out.toList();
 }
Exemple #12
0
 /** Visitor method: enter classes of a list of trees, returning a list of types. */
 <T extends JCTree> List<Type> classEnter(List<T> trees, Env<AttrContext> env) {
   ListBuffer<Type> ts = new ListBuffer<Type>();
   for (List<T> l = trees; l.nonEmpty(); l = l.tail) {
     Type t = classEnter(l.head, env);
     if (t != null) ts.append(t);
   }
   return ts.toList();
 }
Exemple #13
0
 public <T extends JCTree> List<T> build(
     final java.util.List<? extends lombok.ast.Node<?>> nodes, final Class<T> extectedType) {
   if (nodes == null) return null;
   ListBuffer<T> list = ListBuffer.lb();
   for (lombok.ast.Node<?> node : nodes) {
     list.append(build(node, extectedType));
   }
   return list.toList();
 }
 public void flush() {
   if (enterCount != 0) return;
   enterCount++;
   try {
     while (q.nonEmpty()) q.next().enterAnnotation();
   } finally {
     enterCount--;
   }
 }
Exemple #15
0
 @Override
 public JCTree visitAnnotation(final lombok.ast.Annotation node, final Void p) {
   final ListBuffer<JCExpression> args = ListBuffer.lb();
   for (Entry<String, lombok.ast.Expression<?>> entry : node.getValues().entrySet()) {
     args.append(build(Assign(Name(entry.getKey()), entry.getValue()), JCExpression.class));
   }
   final JCAnnotation annotation =
       setGeneratedBy(M(node).Annotation(build(node.getType()), args.toList()), source);
   return annotation;
 }
Exemple #16
0
  private <T extends Attribute.Compound> List<T> getAttributesForCompletion(
      final Annotate.AnnotateRepeatedContext<T> ctx) {

    Map<Symbol.TypeSymbol, ListBuffer<T>> annotated = ctx.annotated;
    boolean atLeastOneRepeated = false;
    List<T> buf = List.<T>nil();
    for (ListBuffer<T> lb : annotated.values()) {
      if (lb.size() == 1) {
        buf = buf.prepend(lb.first());
      } else { // repeated
        // This will break when other subtypes of Attributs.Compound
        // are introduced, because PlaceHolder is a subtype of TypeCompound.
        T res;
        @SuppressWarnings("unchecked")
        T ph = (T) new Placeholder<T>(ctx, lb.toList(), sym);
        res = ph;
        buf = buf.prepend(res);
        atLeastOneRepeated = true;
      }
    }

    if (atLeastOneRepeated) {
      // The Symbol s is now annotated with a combination of
      // finished non-repeating annotations and placeholders for
      // repeating annotations.
      //
      // We need to do this in two passes because when creating
      // a container for a repeating annotation we must
      // guarantee that the @Repeatable on the
      // contained annotation is fully annotated
      //
      // The way we force this order is to do all repeating
      // annotations in a pass after all non-repeating are
      // finished. This will work because @Repeatable
      // is non-repeating and therefore will be annotated in the
      // fist pass.

      // Queue a pass that will replace Attribute.Placeholders
      // with Attribute.Compound (made from synthesized containers).
      ctx.annotateRepeated(
          new Annotate.Annotator() {
            @Override
            public String toString() {
              return "repeated annotation pass of: " + sym + " in: " + sym.owner;
            }

            @Override
            public void enterAnnotation() {
              complete(ctx);
            }
          });
    }
    // Add non-repeating attributes
    return buf.reverse();
  }
 /**
  * Return exceptions this method or constructor throws.
  *
  * @return an array of ClassDoc[] representing the exceptions thrown by this method.
  */
 public ClassDoc[] thrownExceptions() {
   ListBuffer<ClassDocImpl> l = new ListBuffer<ClassDocImpl>();
   for (Type ex : sym.type.getThrownTypes()) {
     ex = env.types.erasure(ex);
     // ### Will these casts succeed in the face of static semantic
     // ### errors in the documented code?
     ClassDocImpl cdi = env.getClassDoc((ClassSymbol) ex.tsym);
     if (cdi != null) l.append(cdi);
   }
   return l.toArray(new ClassDocImpl[l.length()]);
 }
Exemple #18
0
 /**
  * Split a path into its elements. If emptyPathDefault is not null, all empty elements in the
  * path, including empty elements at either end of the path, will be replaced with the value of
  * emptyPathDefault.
  *
  * @param path The path to be split
  * @param emptyPathDefault The value to substitute for empty path elements, or null, to ignore
  *     empty path elements
  * @return The elements of the path
  */
 private static Iterable<File> getPathEntries(String path, File emptyPathDefault) {
   ListBuffer<File> entries = new ListBuffer<File>();
   int start = 0;
   while (start <= path.length()) {
     int sep = path.indexOf(File.pathSeparatorChar, start);
     if (sep == -1) sep = path.length();
     if (start < sep) entries.add(new File(path.substring(start, sep)));
     else if (emptyPathDefault != null) entries.add(emptyPathDefault);
     start = sep + 1;
   }
   return entries;
 }
  private static JCExpression cloneType0(TreeMaker maker, JCTree in) {
    if (in == null) return null;

    if (in instanceof JCPrimitiveTypeTree) return (JCExpression) in;

    if (in instanceof JCIdent) {
      return maker.Ident(((JCIdent) in).name);
    }

    if (in instanceof JCFieldAccess) {
      JCFieldAccess fa = (JCFieldAccess) in;
      return maker.Select(cloneType0(maker, fa.selected), fa.name);
    }

    if (in instanceof JCArrayTypeTree) {
      JCArrayTypeTree att = (JCArrayTypeTree) in;
      return maker.TypeArray(cloneType0(maker, att.elemtype));
    }

    if (in instanceof JCTypeApply) {
      JCTypeApply ta = (JCTypeApply) in;
      ListBuffer<JCExpression> lb = ListBuffer.lb();
      for (JCExpression typeArg : ta.arguments) {
        lb.append(cloneType0(maker, typeArg));
      }
      return maker.TypeApply(cloneType0(maker, ta.clazz), lb.toList());
    }

    if (in instanceof JCWildcard) {
      JCWildcard w = (JCWildcard) in;
      JCExpression newInner = cloneType0(maker, w.inner);
      TypeBoundKind newKind;
      switch (w.getKind()) {
        case SUPER_WILDCARD:
          newKind = maker.TypeBoundKind(BoundKind.SUPER);
          break;
        case EXTENDS_WILDCARD:
          newKind = maker.TypeBoundKind(BoundKind.EXTENDS);
          break;
        default:
        case UNBOUNDED_WILDCARD:
          newKind = maker.TypeBoundKind(BoundKind.UNBOUND);
          break;
      }
      return maker.Wildcard(newKind, newInner);
    }

    // This is somewhat unsafe, but it's better than outright throwing an exception here. Returning
    // null will just cause an exception down the pipeline.
    return (JCExpression) in;
  }
Exemple #20
0
  // where
  private DeclaredType getDeclaredType0(Type outer, ClassSymbol sym, TypeMirror... typeArgs) {
    if (typeArgs.length != sym.type.getTypeArguments().length())
      throw new IllegalArgumentException("Incorrect number of type arguments");

    ListBuffer<Type> targs = new ListBuffer<Type>();
    for (TypeMirror t : typeArgs) {
      if (!(t instanceof ReferenceType || t instanceof WildcardType))
        throw new IllegalArgumentException(t.toString());
      targs.append((Type) t);
    }
    // TODO: Would like a way to check that type args match formals.

    return (DeclaredType) new Type.ClassType(outer, targs.toList(), sym);
  }
 /**
  * Searches the given field node for annotations and returns each one that matches the provided
  * regular expression pattern.
  *
  * <p>Only the simple name is checked - the package and any containing class are ignored.
  */
 public static List<JCAnnotation> findAnnotations(JavacNode fieldNode, Pattern namePattern) {
   ListBuffer<JCAnnotation> result = ListBuffer.lb();
   for (JavacNode child : fieldNode.down()) {
     if (child.getKind() == Kind.ANNOTATION) {
       JCAnnotation annotation = (JCAnnotation) child.get();
       String name = annotation.annotationType.toString();
       int idx = name.lastIndexOf(".");
       String suspect = idx == -1 ? name : name.substring(idx + 1);
       if (namePattern.matcher(suspect).matches()) {
         result.append(annotation);
       }
     }
   }
   return result.toList();
 }
Exemple #22
0
  private List<ModuleSymbol> scanModulePath(ModuleSymbol toFind) {
    ListBuffer<ModuleSymbol> results = new ListBuffer<>();
    Map<Name, Location> namesInSet = new HashMap<>();
    while (moduleLocationIterator.hasNext()) {
      Set<Location> locns = (moduleLocationIterator.next());
      namesInSet.clear();
      for (Location l : locns) {
        try {
          Name n = names.fromString(fileManager.inferModuleName(l));
          if (namesInSet.put(n, l) == null) {
            ModuleSymbol msym = syms.enterModule(n);
            if (msym.sourceLocation != null || msym.classLocation != null) {
              // module has already been found, so ignore this instance
              continue;
            }
            if (moduleLocationIterator.outer == StandardLocation.MODULE_SOURCE_PATH) {
              msym.sourceLocation = l;
              if (fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) {
                msym.classLocation =
                    fileManager.getLocationForModule(
                        StandardLocation.CLASS_OUTPUT, msym.name.toString());
              }
            } else {
              msym.classLocation = l;
            }
            if (moduleLocationIterator.outer == StandardLocation.SYSTEM_MODULES
                || moduleLocationIterator.outer == StandardLocation.UPGRADE_MODULE_PATH) {
              msym.flags_field |= Flags.SYSTEM_MODULE;
            }
            if (toFind == msym || toFind == null) {
              // Note: cannot return msym directly, because we must finish
              // processing this set first
              results.add(msym);
            }
          } else {
            log.error(
                Errors.DuplicateModuleOnPath(getDescription(moduleLocationIterator.outer), n));
          }
        } catch (IOException e) {
          // skip location for now?  log error?
        }
      }
      if (toFind != null && results.nonEmpty()) return results.toList();
    }

    return results.toList();
  }
 /**
  * Generates the class and returns the generated tree.
  *
  * @return the generated class tree, to be added to the appropriate {@link
  *     JCTree.JCCompilationUnit}.
  */
 public List<JCTree> build() {
   ListBuffer<JCTree> defs = ListBuffer.lb();
   appendDefinitionsTo(defs);
   if (javaClassName != null) {
     ClassDefinitionBuilder classBuilder =
         ClassDefinitionBuilder.klass(owner, javaClassName, null)
             .modifiers(Flags.FINAL | (modifiers & (Flags.PUBLIC | Flags.PRIVATE)))
             .constructorModifiers(Flags.PRIVATE)
             .annotations(owner.makeAtAttribute())
             .annotations(annotations.toList())
             .defs(defs.toList());
     if (valueConstructor && hasField) generateValueConstructor(classBuilder.addConstructor());
     return classBuilder.build();
   } else {
     return defs.toList();
   }
 }
Exemple #24
0
 /**
  * Process Win32-style command files for the specified command line arguments and return the
  * resulting arguments. A command file argument is of the form '@file' where 'file' is the name of
  * the file whose contents are to be parsed for additional arguments. The contents of the command
  * file are parsed using StreamTokenizer and the original '@file' argument replaced with the
  * resulting tokens. Recursive command files are not supported. The '@' character itself can be
  * quoted with the sequence '@@'.
  */
 public static String[] parse(String[] args) throws IOException {
   ListBuffer<String> newArgs = new ListBuffer<String>();
   for (int i = 0; i < args.length; i++) {
     String arg = args[i];
     if (arg.length() > 1 && arg.charAt(0) == '@') {
       arg = arg.substring(1);
       if (arg.charAt(0) == '@') {
         newArgs.append(arg);
       } else {
         loadCmdFile(arg, newArgs);
       }
     } else {
       newArgs.append(arg);
     }
   }
   return newArgs.toList().toArray(new String[newArgs.length()]);
 }
Exemple #25
0
  public static class Comments {
    public com.sun.tools.javac.util.ListBuffer<Comment> comments =
        com.sun.tools.javac.util.ListBuffer.lb();

    void add(Comment comment) {
      comments.append(comment);
    }
  }
Exemple #26
0
 @Override
 public JCTree visitNewArray(final lombok.ast.NewArray node, final Void p) {
   final ListBuffer<JCExpression> dims = ListBuffer.lb();
   dims.appendList(build(node.getDimensionExpressions(), JCExpression.class));
   final JCExpression elemtype = build(node.getType());
   final List<JCExpression> initializerExpressions =
       build(node.getInitializerExpressions(), JCExpression.class);
   JCNewArray newClass =
       setGeneratedBy(
           M(node)
               .NewArray(
                   elemtype,
                   dims.toList(),
                   initializerExpressions.isEmpty() ? null : initializerExpressions),
           source);
   return newClass;
 }
  public static void deleteImportFromCompilationUnit(JavacNode node, String name) {
    if (inNetbeansEditor(node)) return;
    if (!node.shouldDeleteLombokAnnotations()) return;
    ListBuffer<JCTree> newDefs = ListBuffer.lb();

    JCCompilationUnit unit = (JCCompilationUnit) node.top().get();

    for (JCTree def : unit.defs) {
      boolean delete = false;
      if (def instanceof JCImport) {
        JCImport imp0rt = (JCImport) def;
        delete = (!imp0rt.staticImport && imp0rt.qualid.toString().equals(name));
      }
      if (!delete) newDefs.append(def);
    }
    unit.defs = newDefs.toList();
  }
 public MethodDefinitionBuilder block(JCBlock block) {
   if (block != null) {
     body.clear();
     return body(block.getStatements());
   } else {
     return noBody();
   }
 }
  /**
   * Appends to <tt>defs</tt> the definitions that would go into the class generated by {@link
   * #build()}
   *
   * @param defs a {@link ListBuffer} to which the definitions will be appended.
   */
  public void appendDefinitionsTo(ListBuffer<JCTree> defs) {
    if (hasField) {
      defs.append(generateField());
      if (variableInit != null) defs.append(generateFieldInit());
    }

    if (readable) {
      getterBuilder.modifiers(getGetSetModifiers());
      getterBuilder.noAnnotations(noAnnotations);
      defs.append(getterBuilder.build());
    }

    if (writable) {
      setterBuilder.modifiers(getGetSetModifiers());
      setterBuilder.noAnnotations(noAnnotations);
      defs.append(setterBuilder.build());
    }
  }
 public static JCExpression cloneSelfType(JavacNode field) {
   JavacNode typeNode = field;
   TreeMaker maker = field.getTreeMaker();
   while (typeNode != null && typeNode.getKind() != Kind.TYPE) typeNode = typeNode.up();
   if (typeNode != null && typeNode.get() instanceof JCClassDecl) {
     JCClassDecl type = (JCClassDecl) typeNode.get();
     ListBuffer<JCExpression> typeArgs = ListBuffer.lb();
     if (!type.typarams.isEmpty()) {
       for (JCTypeParameter tp : type.typarams) {
         typeArgs.append(maker.Ident(tp.name));
       }
       return maker.TypeApply(maker.Ident(type.name), typeArgs.toList());
     } else {
       return maker.Ident(type.name);
     }
   } else {
     return null;
   }
 }