com.sun.tools.javac.tree.JCTree.JCExpression Java Examples

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCExpression. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 7 votes vote down vote up
private Block convertLambdaBody(JCTree lambdaBody, TypeDescriptor returnTypeDescriptor) {
  Block body;
  if (lambdaBody.getKind() == Kind.BLOCK) {
    body = convertBlock((JCBlock) lambdaBody);
  } else {
    checkArgument(lambdaBody instanceof JCExpression);
    Expression lambdaMethodBody = convertExpression((JCExpression) lambdaBody);
    Statement statement =
        AstUtils.createReturnOrExpressionStatement(
            getSourcePosition(lambdaBody), lambdaMethodBody, returnTypeDescriptor);
    body =
        Block.newBuilder()
            .setSourcePosition(getSourcePosition(lambdaBody))
            .setStatements(statement)
            .build();
  }
  return body;
}
 
Example #2
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) {
	JavacTreeMaker maker = node.getTreeMaker();
	
	Context context = node.getContext();
	JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context);
	JCExpression varType = chainDots(node, exception.split("\\."));
	
	JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null);
	JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow");
	JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply(
			List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef,
			List.<JCExpression>of(maker.Ident(node.toName("$ex")))))));
	JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null);
	if (JavacHandlerUtil.inNetbeansEditor(node)) {
		//set span (start and end position) of the try statement and the main block
		//this allows NetBeans to dive into the statement correctly:
		JCCompilationUnit top = (JCCompilationUnit) node.top().get();
		int startPos = contents.head.pos;
		int endPos = Javac.getEndPosition(contents.last().pos(), top);
		tryBlock.pos = startPos;
		tryStatement.pos = startPos;
		Javac.storeEnd(tryBlock, endPos, top);
		Javac.storeEnd(tryStatement, endPos, top);
	}
	return setGeneratedBy(tryStatement, source, context);
}
 
Example #3
Source File: Corraller.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private JCBlock resolutionExceptionBlock() {
    if (resolutionExceptionBlock == null) {
        JCExpression expClass = null;
        // Split the exception class name at dots
        for (String id : SPIResolutionException.class.getName().split("\\.")) {
            Name nm = names.fromString(id);
            if (expClass == null) {
                expClass = make.Ident(nm);
            } else {
                expClass = make.Select(expClass, nm);
            }
        }
        JCNewClass exp = make.NewClass(null,
                null, expClass, List.of(make.Literal(keyIndex)), null);
        resolutionExceptionBlock = make.Block(0L, List.of(make.Throw(exp)));
    }
    return resolutionExceptionBlock;
}
 
Example #4
Source File: JavaCompiler.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Resolve an identifier.
 *
 * @param name The identifier to resolve
 */
public Symbol resolveIdent(String name) {
    if (name.equals(""))
        return syms.errSymbol;
    JavaFileObject prev = log.useSource(null);
    try {
        JCExpression tree = null;
        for (String s : name.split("\\.", -1)) {
            if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
                return syms.errSymbol;
            tree = (tree == null) ? make.Ident(names.fromString(s))
                    : make.Select(tree, names.fromString(s));
        }
        JCCompilationUnit toplevel =
                make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>nil());
        toplevel.packge = syms.unnamedPackage;
        return attr.attribIdent(tree, toplevel);
    } finally {
        log.useSource(prev);
    }
}
 
Example #5
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 6 votes vote down vote up
public void visitReference0(JCTree tree) {
	try {
		printExpr(readTree(tree, "expr"));
		print("::");
		List<JCExpression> typeArgs = readExpressionList(tree, "typeargs");
		if (typeArgs != null) {
			print("<");
			printExprs(typeArgs);
			print(">");
		}
		;
		print(readObject(tree, "mode").toString().equals("INVOKE") ? readObject(tree, "name") : "new");
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example #6
Source File: JavacBinder.java    From manifold with Apache License 2.0 6 votes vote down vote up
@Override
protected Node<JCExpression, Tag> makeBinaryExpression( Node<JCExpression, Tag> left,
                                                        Node<JCExpression, Tag> right,
                                                        Symbol.MethodSymbol binderMethod )
{
  JCBinary binary = _make.Binary( right._operatorLeft == null
                                  ? Tag.MUL
                                  : right._operatorLeft, left._expr, right._expr );
  binary.pos = left._expr.pos;
  boolean rightToLeft =
    binderMethod instanceof OverloadOperatorSymbol && ((OverloadOperatorSymbol)binderMethod).isSwapped() ||
    binderMethod.name.toString().equals( "postfixBind" );
  IDynamicJdk.instance().setOperator( binary, new OverloadOperatorSymbol( binderMethod, rightToLeft ) );
  binary.type = rightToLeft
                ? memberType( right._expr.type, left._expr.type, binderMethod )
                : memberType( left._expr.type, right._expr.type, binderMethod );
  return new Node<>( binary, left._operatorLeft );
}
 
Example #7
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
private JCTree[] tempify( JCTree.JCBinary tree, TreeMaker make, JCExpression expr, Context ctx, Symbol owner, String varName )
{
  switch( expr.getTag() )
  {
    case LITERAL:
    case IDENT:
      return null;

    default:
      JCTree.JCVariableDecl tempVar = make.VarDef( make.Modifiers( FINAL | SYNTHETIC ),
        Names.instance( ctx ).fromString( varName + tempVarIndex ), make.Type( expr.type ), expr );
      tempVar.sym = new Symbol.VarSymbol( FINAL | SYNTHETIC, tempVar.name, expr.type, owner );
      tempVar.type = tempVar.sym.type;
      tempVar.pos = tree.pos;
      JCExpression ident = make.Ident( tempVar );
      ident.type = expr.type;
      ident.pos = tree.pos;
      return new JCTree[] {tempVar, ident};
  }
}
 
Example #8
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Unbox an object to a primitive value. */
JCExpression unbox(JCExpression tree, Type primitive) {
    Type unboxedType = types.unboxedType(tree.type);
    if (unboxedType.hasTag(NONE)) {
        unboxedType = primitive;
        if (!unboxedType.isPrimitive())
            throw new AssertionError(unboxedType);
        make_at(tree.pos());
        tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
    } else {
        // There must be a conversion from unboxedType to primitive.
        if (!types.isSubtype(unboxedType, primitive))
            throw new AssertionError(tree);
    }
    make_at(tree.pos());
    Symbol valueSym = lookupMethod(tree.pos(),
                                   unboxedType.tsym.name.append(names.Value), // x.intValue()
                                   tree.type,
                                   List.nil());
    return make.App(make.Select(tree, valueSym));
}
 
Example #9
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * determine the receiver of the method call - the receiver can
 * be a type qualifier, the synthetic receiver parameter or 'super'.
 */
private JCExpression expressionInvoke(VarSymbol rcvr) {
    JCExpression qualifier =
            (rcvr != null) ?
                makeReceiver(rcvr) :
                tree.getQualifierExpression();

    //create the qualifier expression
    JCFieldAccess select = make.Select(qualifier, tree.sym.name);
    select.sym = tree.sym;
    select.type = tree.sym.erasure(types);

    //create the method call expression
    JCExpression apply = make.Apply(List.nil(), select,
            convertArgs(tree.sym, args.toList(), tree.varargsElement)).
            setType(tree.sym.erasure(types).getReturnType());

    apply = transTypes.coerce(attrEnv, apply,
            types.erasure(localContext.tree.referentType.getReturnType()));

    setVarargsIfNeeded(apply, tree.varargsElement);
    return apply;
}
 
Example #10
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public static boolean isJailbreakReceiver( JCTree.JCFieldAccess fieldAccess )
{
  Symbol sym = null;
  JCExpression selected = fieldAccess.selected;
  if( selected instanceof JCTree.JCIdent )
  {
    sym = ((JCTree.JCIdent)selected).sym;
  }
  else if( selected instanceof JCTree.JCMethodInvocation )
  {
    if( ((JCTree.JCMethodInvocation)selected).meth instanceof JCTree.JCFieldAccess )
    {
      sym = ((JCTree.JCFieldAccess)((JCTree.JCMethodInvocation)selected).meth).sym;
    }
    else if( ((JCTree.JCMethodInvocation)selected).meth instanceof JCTree.JCIdent )
    {
      sym = ((JCTree.JCIdent)((JCTree.JCMethodInvocation)selected).meth).sym;
    }
  }

  return isJailbreakSymbol( sym );
}
 
Example #11
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCExpression createTypeReference(JavacNode type) {
	java.util.List<String> list = new ArrayList<String>();
	list.add(type.getName());
	JavacNode tNode = type.up();
	while (tNode != null && tNode.getKind() == Kind.TYPE) {
		list.add(tNode.getName());
		tNode = tNode.up();
	}
	Collections.reverse(list);
	
	JavacTreeMaker maker = type.getTreeMaker();
	JCExpression chain = maker.Ident(type.toName(list.get(0)));
	
	for (int i = 1; i < list.size(); i++) {
		chain = maker.Select(chain, type.toName(list.get(i)));
	}
	
	return chain;
}
 
Example #12
Source File: UMemberSelect.java    From Refaster with Apache License 2.0 5 votes vote down vote up
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
  JCExpression expression = getExpression().inline(inliner);
  if (expression.toString().equals(CONVERT_TO_IDENT)) {
    return inliner.maker().Ident(inliner.asName(identifier()));
  }
  return inliner.maker().Select(getExpression().inline(inliner), inliner.asName(identifier()));
}
 
Example #13
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void visitTypeApply(JCTypeApply tree) {
    if (tree.type.hasTag(CLASS)) {
        List<JCExpression> args = tree.arguments;
        List<Type> forms = tree.type.tsym.type.getTypeArguments();

        Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
        if (incompatibleArg != null) {
            for (JCTree arg : tree.arguments) {
                if (arg.type == incompatibleArg) {
                    log.error(arg, Errors.NotWithinBounds(incompatibleArg, forms.head));
                }
                forms = forms.tail;
             }
         }

        forms = tree.type.tsym.type.getTypeArguments();

        boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;

        // For matching pairs of actual argument types `a' and
        // formal type parameters with declared bound `b' ...
        while (args.nonEmpty() && forms.nonEmpty()) {
            validateTree(args.head,
                    !(isOuter && is_java_lang_Class),
                    false);
            args = args.tail;
            forms = forms.tail;
        }

        // Check that this type is either fully parameterized, or
        // not parameterized at all.
        if (tree.type.getEnclosingType().isRaw())
            log.error(tree.pos(), Errors.ImproperlyFormedTypeInnerRawParam);
        if (tree.clazz.hasTag(SELECT))
            visitSelectInternal((JCFieldAccess)tree.clazz);
    }
}
 
Example #14
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static JCExpression parseExpression(Context context, CharSequence expr, boolean onlyFullInput, SourcePositions[] pos, final List<Diagnostic<? extends JavaFileObject>> errors) {
    if (expr == null || (pos != null && pos.length != 1))
        throw new IllegalArgumentException();
    JavaCompiler compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(new DummyJFO());
    Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
        @Override
        public void report(JCDiagnostic diag) {
            errors.add(diag);
        }            
    };
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        ParserFactory factory = ParserFactory.instance(context);
        ScannerFactory scannerFactory = ScannerFactory.instance(context);
        Names names = Names.instance(context);
        Scanner scanner = scannerFactory.newScanner(buf, false);
        Parser parser = newParser(context, (NBParserFactory) factory, scanner, false, false, CancelService.instance(context), names);
        if (parser instanceof JavacParser) {
            if (pos != null)
                pos[0] = new ParserSourcePositions((JavacParser)parser);
            JCExpression result = parser.parseExpression();

            if (!onlyFullInput || scanner.token().kind == TokenKind.EOF) {
                return result;
            }
        }
        return null;
    } finally {
        compiler.log.useSource(prev);
        compiler.log.popDiagnosticHandler(discardHandler);
    }
}
 
Example #15
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Construct an expression using the builder, with the given rval
 *  expression as an argument to the builder.  However, the rval
 *  expression must be computed only once, even if used multiple
 *  times in the result of the builder.  We do that by
 *  constructing a "let" expression that saves the rvalue into a
 *  temporary variable and then uses the temporary variable in
 *  place of the expression built by the builder.  The complete
 *  resulting expression is of the form
 *  <pre>
 *    (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
 *     in (<b>BUILDER</b>(<b>TEMP</b>)))
 *  </pre>
 *  where <code><b>TEMP</b></code> is a newly declared variable
 *  in the let expression.
 */
JCExpression abstractRval(JCExpression rval, Type type, TreeBuilder builder) {
    rval = TreeInfo.skipParens(rval);
    switch (rval.getTag()) {
    case LITERAL:
        return builder.build(rval);
    case IDENT:
        JCIdent id = (JCIdent) rval;
        if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
            return builder.build(rval);
    }
    Name name = TreeInfo.name(rval);
    if (name == names._super || name == names._this)
        return builder.build(rval);
    VarSymbol var =
        new VarSymbol(FINAL|SYNTHETIC,
                      names.fromString(
                                      target.syntheticNameChar()
                                      + "" + rval.hashCode()),
                                  type,
                                  currentMethodSym);
    rval = convert(rval,type);
    JCVariableDecl def = make.VarDef(var, rval); // XXX cast
    JCExpression built = builder.build(make.Ident(var));
    JCExpression res = make.LetExpr(def, built);
    res.type = built.type;
    return res;
}
 
Example #16
Source File: ArgumentAttr.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the results of method attribution.
 */
void setResult(JCExpression tree, Type type) {
    result = type;
    if (env.info.isSpeculative) {
        //if we are in a speculative branch we can save the type in the tree itself
        //as there's no risk of polluting the original tree.
        tree.type = result;
    }
}
 
Example #17
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Make an attributed class instance creation expression.
 *  @param ctype    The class type.
 *  @param args     The constructor arguments.
 *  @param cons     The constructor symbol
 */
JCNewClass makeNewClass(Type ctype, List<JCExpression> args, Symbol cons) {
    JCNewClass tree = make.NewClass(null,
        null, make.QualIdent(ctype.tsym), args, null);
    tree.constructor = cons;
    tree.type = ctype;
    return tree;
}
 
Example #18
Source File: HandleBuilder.java    From EasyMPermission with MIT License 5 votes vote down vote up
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);
}
 
Example #19
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Check that each type is a reference type, i.e. a class, interface or array type
 *  or a type variable.
 *  @param trees         Original trees, used for error reporting.
 *  @param types         The types to be checked.
 */
List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
    List<JCExpression> tl = trees;
    for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
        l.head = checkRefType(tl.head.pos(), l.head);
        tl = tl.tail;
    }
    return types;
}
 
Example #20
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convert method/constructor arguments by inserting appropriate cast
 * as required by type-erasure - this is needed when bridging a lambda/method
 * reference, as the bridged signature might require downcast to be compatible
 * with the generated signature.
 */
private List<JCExpression> convertArgs(Symbol meth, List<JCExpression> args, Type varargsElement) {
   Assert.check(meth.kind == MTH);
   List<Type> formals = types.erasure(meth.type).getParameterTypes();
   if (varargsElement != null) {
       Assert.check((meth.flags() & VARARGS) != 0);
   }
   return transTypes.translateArgs(args, formals, varargsElement, attrEnv);
}
 
Example #21
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void checkModuleName (JCModuleDecl tree) {
    Name moduleName = tree.sym.name;
    Assert.checkNonNull(moduleName);
    if (lint.isEnabled(LintCategory.MODULE)) {
        JCExpression qualId = tree.qualId;
        while (qualId != null) {
            Name componentName;
            DiagnosticPosition pos;
            switch (qualId.getTag()) {
                case SELECT:
                    JCFieldAccess selectNode = ((JCFieldAccess) qualId);
                    componentName = selectNode.name;
                    pos = selectNode.pos();
                    qualId = selectNode.selected;
                    break;
                case IDENT:
                    componentName = ((JCIdent) qualId).name;
                    pos = qualId.pos();
                    qualId = null;
                    break;
                default:
                    throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
            }
            if (componentName != null) {
                String moduleNameComponentString = componentName.toString();
                int nameLength = moduleNameComponentString.length();
                if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
                    log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName));
                }
            }
        }
    }
}
 
Example #22
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Create an attributed tree of the form left.name(). */
private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
    Assert.checkNonNull(left.type);
    Symbol funcsym = lookupMethod(make_pos, name, left.type,
                                  TreeInfo.types(args));
    return make.App(make.Select(left, funcsym), args);
}
 
Example #23
Source File: Insertions.java    From annotation-tools with MIT License 5 votes vote down vote up
static TypeTree fromJCTree(JCTree jt) {
  if (jt != null) {
    Kind kind = jt.getKind();
    switch (kind) {
    case ANNOTATED_TYPE:
      return fromJCTree(
          ((JCTree.JCAnnotatedType) jt).getUnderlyingType());
    case IDENTIFIER:
      return new IdentifierTT(
          ((JCTree.JCIdent) jt).sym.getSimpleName().toString());
    case ARRAY_TYPE:
      return new ArrayTT(
          fromJCTree(((JCTree.JCArrayTypeTree) jt).getType()));
    case MEMBER_SELECT:
      return new MemberSelectTT(
          fromJCTree(((JCTree.JCFieldAccess) jt).getExpression()),
          ((JCTree.JCFieldAccess) jt).getIdentifier());
    case EXTENDS_WILDCARD:
    case SUPER_WILDCARD:
      return new WildcardTT(kind,
          fromJCTree(((JCTree.JCWildcard) jt).getBound()));
    case UNBOUNDED_WILDCARD:
      return new WildcardTT();
    case PARAMETERIZED_TYPE:
      com.sun.tools.javac.util.List<JCExpression> typeArgs =
        ((JCTree.JCTypeApply) jt).getTypeArguments();
      List<Tree> args = new ArrayList<>(typeArgs.size());
      for (JCTree.JCExpression typeArg : typeArgs) {
        args.add(fromJCTree(typeArg));
      }
      return new ParameterizedTypeTT(
          fromJCTree(((JCTree.JCTypeApply) jt).getType()),
          args);
    default:
      break;
    }
  }
  return null;
}
 
Example #24
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> jceBlank = List.nil();
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	long baseFlags = JavacHandlerUtil.addFinalIfNeeded(0, builderType.getContext());
	Name entryName = builderType.toName("$lombokEntry");
	
	JCExpression forEachType = chainDots(builderType, "java", "util", "Map", "Entry");
	forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs(), source);
	JCExpression keyArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getKey")), List.<JCExpression>nil());
	JCExpression valueArg = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(entryName), builderType.toName("getValue")), List.<JCExpression>nil());
	JCExpression addKey = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$key", "add"), List.of(keyArg));
	JCExpression addValue = maker.Apply(List.<JCExpression>nil(), chainDots(builderType, "this", data.getPluralName() + "$value", "add"), List.of(valueArg));
	JCBlock forEachBody = maker.Block(0, List.<JCStatement>of(maker.Exec(addKey), maker.Exec(addValue)));
	JCExpression entrySetInvocation = maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("entrySet")), jceBlank);
	JCStatement forEach = maker.ForeachLoop(maker.VarDef(maker.Modifiers(baseFlags), entryName, forEachType, null), entrySetInvocation, forEachBody);
	statements.append(forEach);
	
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getPluralName();
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("putAll", name.toString()));
	JCExpression paramType = chainDots(builderType, "java", "util", "Map");
	paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), jceBlank, body, null);
	injectMethod(builderType, method);
}
 
Example #25
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Make an attributed class instance creation expression.
 *  @param ctype    The class type.
 *  @param args     The constructor arguments.
 */
JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
    JCNewClass tree = make.NewClass(null,
        null, make.QualIdent(ctype.tsym), args, null);
    tree.constructor = rs.resolveConstructor(
        make_pos, attrEnv, ctype, TreeInfo.types(args), List.nil());
    tree.type = ctype;
    return tree;
}
 
Example #26
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
/** For javac, both JCExpression and JCStatement are considered as valid children types. */
@Override
protected Collection<Class<? extends JCTree>> getStatementTypes() {
	Collection<Class<? extends JCTree>> collection = new ArrayList<Class<? extends JCTree>>(3);
	collection.add(JCStatement.class);
	collection.add(JCExpression.class);
	collection.add(JCCatch.class);
	return collection;
}
 
Example #27
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
/**
 * Generates a new statement that checks if the given variable is null, and if so, throws a specified exception with the
 * variable name as message.
 * 
 * @param exName The name of the exception to throw; normally {@code java.lang.NullPointerException}.
 */
public static JCStatement generateNullCheck(JavacTreeMaker maker, JavacNode variable, JavacNode source) {
	NullCheckExceptionType exceptionType = source.getAst().readConfiguration(ConfigurationKeys.NON_NULL_EXCEPTION_TYPE);
	if (exceptionType == null) exceptionType = NullCheckExceptionType.NULL_POINTER_EXCEPTION;
	
	JCVariableDecl varDecl = (JCVariableDecl) variable.get();
	if (isPrimitive(varDecl.vartype)) return null;
	Name fieldName = varDecl.name;
	JCExpression exType = genTypeRef(variable, exceptionType.getExceptionType());
	JCExpression exception = maker.NewClass(null, List.<JCExpression>nil(), exType, List.<JCExpression>of(maker.Literal(exceptionType.toExceptionMessage(fieldName.toString()))), null);
	JCStatement throwStatement = maker.Throw(exception);
	JCBlock throwBlock = maker.Block(0, List.of(throwStatement));
	return maker.If(maker.Binary(CTC_EQUAL, maker.Ident(fieldName), maker.Literal(CTC_BOT, null)), throwBlock, null);
}
 
Example #28
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	
	JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression thisDotField2 = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
	
	JCExpression create = maker.Apply(jceBlank, chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), getBuilderMethodName(data)), jceBlank);
	JCStatement thenPart = maker.Exec(maker.Assign(thisDotField2, create));
	
	return maker.If(cond, thenPart, null);
}
 
Example #29
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static JCExpression chainDots(JavacNode node, LombokImmutableList<String> elems) {
	assert elems != null;
	
	JavacTreeMaker maker = node.getTreeMaker();
	JCExpression e = null;
	for (String elem : elems) {
		if (e == null) e = maker.Ident(node.toName(elem));
		else e = maker.Select(e, node.toName(elem));
	}
	return e;
}
 
Example #30
Source File: Modules.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void checkDuplicateOpensToModule(JCExpression name, ModuleSymbol msym,
        OpensDirective d) {
    if (d.modules != null) {
        for (ModuleSymbol other : d.modules) {
            if (msym == other) {
                reportOpensConflictToModule(name, msym);
            }
        }
    }
}