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

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCVariableDecl. 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: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
RewritingContext(
        JCTree originalTree,
        JCTree oldTree,
        JCTree replacement,
        StatementAnalyzer<JCTree, JCTree> analyzer,
        Env<AttrContext> env) {
    this.originalTree = originalTree;
    this.oldTree = oldTree;
    this.replacement = replacement;
    this.analyzer = analyzer;
    this.env = attr.copyEnv(env);
    /*  this is a temporary workaround that should be removed once we have a truly independent
     *  clone operation
     */
    if (originalTree.hasTag(VARDEF)) {
        // avoid redefinition clashes
        this.env.info.scope.remove(((JCVariableDecl)originalTree).sym);
    }
}
 
Example #2
Source File: JavacAST.java    From EasyMPermission with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected JavacNode buildTree(JCTree node, Kind kind) {
	switch (kind) {
	case COMPILATION_UNIT:
		return buildCompilationUnit((JCCompilationUnit) node);
	case TYPE:
		return buildType((JCClassDecl) node);
	case FIELD:
		return buildField((JCVariableDecl) node);
	case INITIALIZER:
		return buildInitializer((JCBlock) node);
	case METHOD:
		return buildMethod((JCMethodDecl) node);
	case ARGUMENT:
		return buildLocalVar((JCVariableDecl) node, kind);
	case LOCAL:
		return buildLocalVar((JCVariableDecl) node, kind);
	case STATEMENT:
		return buildStatementOrExpression(node);
	case ANNOTATION:
		return buildAnnotation((JCAnnotation) node, false);
	default:
		throw new AssertionError("Did not expect: " + kind);
	}
}
 
Example #3
Source File: JavacMultilineProcessor.java    From mdict-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
	Set<? extends Element> fields = roundEnv.getElementsAnnotatedWith(Multiline.class);
	for (Element field : fields) {
		String docComment = elementUtils.getDocComment(field);
		if (null != docComment) {
			Multiline annotation = field.getAnnotation(Multiline.class);
			if(annotation.trim()){
				docComment=comments.matcher(docComment).replaceAll(" ");
				docComment=docComment.replaceAll("\\s+"," ");
				docComment=docComment.replaceAll(" ?([={}<>;,+\\-]) ?","$1");
			}

			JCVariableDecl fieldNode = (JCVariableDecl) elementUtils.getTree(field);
			fieldNode.init = maker.Literal(docComment);
		}
	}
	return true;
}
 
Example #4
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
/**
 * Checks if there is a field with the provided name.
 * 
 * @param fieldName the field name to check for.
 * @param node Any node that represents the Type (JCClassDecl) to look in, or any child node thereof.
 */
public static MemberExistsResult fieldExists(String fieldName, JavacNode node) {
	node = upToTypeNode(node);
	
	if (node != null && node.get() instanceof JCClassDecl) {
		for (JCTree def : ((JCClassDecl)node.get()).defs) {
			if (def instanceof JCVariableDecl) {
				if (((JCVariableDecl)def).name.contentEquals(fieldName)) {
					return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK;
				}
			}
		}
	}
	
	return MemberExistsResult.NOT_EXISTS;
}
 
Example #5
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Complain that pending exceptions are not caught.
 */
void errorUncaught() {
    for (FlowPendingExit exit = pendingExits.next();
         exit != null;
         exit = pendingExits.next()) {
        if (classDef != null &&
            classDef.pos == exit.tree.pos) {
            log.error(exit.tree.pos(),
                      Errors.UnreportedExceptionDefaultConstructor(exit.thrown));
        } else if (exit.tree.hasTag(VARDEF) &&
                ((JCVariableDecl)exit.tree).sym.isResourceVariable()) {
            log.error(exit.tree.pos(),
                      Errors.UnreportedExceptionImplicitClose(exit.thrown,
                                                              ((JCVariableDecl)exit.tree).sym.name));
        } else {
            log.error(exit.tree.pos(),
                      Errors.UnreportedExceptionNeedToCatchOrThrow(exit.thrown));
        }
    }
}
 
Example #6
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 #7
Source File: MemberEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void checkReceiver(JCVariableDecl tree, Env<AttrContext> localEnv) {
    attr.attribExpr(tree.nameexpr, localEnv);
    MethodSymbol m = localEnv.enclMethod.sym;
    if (m.isConstructor()) {
        Type outertype = m.owner.owner.type;
        if (outertype.hasTag(TypeTag.METHOD)) {
            // we have a local inner class
            outertype = m.owner.owner.owner.type;
        }
        if (outertype.hasTag(TypeTag.CLASS)) {
            checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
            checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
        } else {
            log.error(tree, Errors.ReceiverParameterNotApplicableConstructorToplevelClass);
        }
    } else {
        checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
        checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
    }
}
 
Example #8
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner,
        long additionalFlags) {
    long flags = FINAL | SYNTHETIC | additionalFlags;
    List<JCVariableDecl> defs = List.nil();
    Set<Name> proxyNames = new HashSet<>();
    for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
        VarSymbol v = l.head;
        int index = 0;
        Name proxyName;
        do {
            proxyName = proxyName(v.name, index++);
        } while (!proxyNames.add(proxyName));
        VarSymbol proxy = new VarSymbol(
            flags, proxyName, v.erasure(types), owner);
        proxies.put(v, proxy);
        JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
        vd.vartype = access(vd.vartype);
        defs = defs.prepend(vd);
    }
    return defs;
}
 
Example #9
Source File: HandleFieldDefaults.java    From EasyMPermission with MIT License 6 votes vote down vote up
public void setFieldDefaultsForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level, boolean makeFinal) {
	JCVariableDecl field = (JCVariableDecl) fieldNode.get();
	if (level != null && level != AccessLevel.NONE) {
		if ((field.mods.flags & (Flags.PUBLIC | Flags.PRIVATE | Flags.PROTECTED)) == 0) {
			if (!hasAnnotationAndDeleteIfNeccessary(PackagePrivate.class, fieldNode)) {
				field.mods.flags |= toJavacModifier(level);
			}
		}
	}
	
	if (makeFinal && (field.mods.flags & Flags.FINAL) == 0) {
		if (!hasAnnotationAndDeleteIfNeccessary(NonFinal.class, fieldNode)) {
			field.mods.flags |= Flags.FINAL;
		}
	}
	
	fieldNode.rebuild();
}
 
Example #10
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 #11
Source File: TypeAnnotations.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void visitLambda(JCLambda tree) {
    JCLambda prevLambda = currentLambda;
    try {
        currentLambda = tree;

        int i = 0;
        for (JCVariableDecl param : tree.params) {
            if (!param.mods.annotations.isEmpty()) {
                // Nothing to do for separateAnnotationsKinds if
                // there are no annotations of either kind.
                TypeAnnotationPosition pos = new TypeAnnotationPosition();
                pos.type = TargetType.METHOD_FORMAL_PARAMETER;
                pos.parameter_index = i;
                pos.pos = param.vartype.pos;
                pos.onLambda = tree;
                separateAnnotationsKinds(param.vartype, param.sym.type, param.sym, pos);
            }
            ++i;
        }

        push(tree);
        scan(tree.body);
        scan(tree.params);
        pop();
    } finally {
        currentLambda = prevLambda;
    }
}
 
Example #12
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private JCStatement makeTwrCloseStatement(Symbol primaryException, JCExpression resource) {
    // primaryException.addSuppressed(catchException);
    VarSymbol catchException =
        new VarSymbol(SYNTHETIC, make.paramName(2),
                      syms.throwableType,
                      currentMethodSym);
    JCStatement addSuppressionStatement =
        make.Exec(makeCall(make.Ident(primaryException),
                           names.addSuppressed,
                           List.of(make.Ident(catchException))));

    // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
    JCBlock tryBlock =
        make.Block(0L, List.of(makeResourceCloseInvocation(resource)));
    JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
    JCBlock catchBlock = make.Block(0L, List.of(addSuppressionStatement));
    List<JCCatch> catchClauses = List.of(make.Catch(catchExceptionDecl, catchBlock));
    JCTry tryTree = make.Try(tryBlock, catchClauses, null);
    tryTree.finallyCanCompleteNormally = true;

    // if (primaryException != null) {try...} else resourceClose;
    JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
                                    tryTree,
                                    makeResourceCloseInvocation(resource));

    return closeIfStatement;
}
 
Example #13
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Definition for this$n field.
 *  @param pos        The source code position of the definition.
 *  @param owner      The method in which the definition goes.
 */
JCVariableDecl outerThisDef(int pos, MethodSymbol owner) {
    ClassSymbol c = owner.enclClass();
    boolean isMandated =
        // Anonymous constructors
        (owner.isConstructor() && owner.isAnonymous()) ||
        // Constructors of non-private inner member classes
        (owner.isConstructor() && c.isInner() &&
         !c.isPrivate() && !c.isStatic());
    long flags =
        FINAL | (isMandated ? MANDATED : SYNTHETIC) | PARAMETER;
    VarSymbol outerThis = makeOuterThisVarSymbol(owner, flags);
    owner.extraParams = owner.extraParams.prepend(outerThis);
    return makeOuterThisVarDecl(pos, outerThis);
}
 
Example #14
Source File: JavacTrees.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public TypeMirror getLub(CatchTree tree) {
    JCCatch ct = (JCCatch) tree;
    JCVariableDecl v = ct.param;
    if (v.type != null && v.type.getKind() == TypeKind.UNION) {
        UnionClassType ut = (UnionClassType) v.type;
        return ut.getLub();
    } else {
        return v.type;
    }
}
 
Example #15
Source File: HandleUtilityClass.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void createPrivateDefaultConstructor(JavacNode typeNode) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	JCModifiers mods = maker.Modifiers(Flags.PRIVATE, List.<JCAnnotation>nil());
	
	Name name = typeNode.toName("<init>");
	JCBlock block = maker.Block(0L, createThrowStatement(typeNode, maker));
	JCMethodDecl methodDef = maker.MethodDef(mods, name, null, List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), block, null);
	JCMethodDecl constructor = recursiveSetGeneratedBy(methodDef, typeNode.get(), typeNode.getContext());
	JavacHandlerUtil.injectMethod(typeNode, constructor);
}
 
Example #16
Source File: GenStubs.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * field definitions: replace initializers with 0, 0.0, false etc
 * when possible -- i.e. leave public, protected initializers alone
 */
@Override
public void visitVarDef(JCVariableDecl tree) {
    tree.mods = translate(tree.mods);
    tree.vartype = translate(tree.vartype);
    if (tree.init != null) {
        if ((tree.mods.flags & (Flags.PUBLIC | Flags.PROTECTED)) != 0)
            tree.init = translate(tree.init);
        else {
            String t = tree.vartype.toString();
            if (t.equals("boolean"))
                tree.init = new JCLiteral(TypeTag.BOOLEAN, 0) { };
            else if (t.equals("byte"))
                tree.init = new JCLiteral(TypeTag.BYTE, 0) { };
            else if (t.equals("char"))
                tree.init = new JCLiteral(TypeTag.CHAR, 0) { };
            else if (t.equals("double"))
                tree.init = new JCLiteral(TypeTag.DOUBLE, 0.d) { };
            else if (t.equals("float"))
                tree.init = new JCLiteral(TypeTag.FLOAT, 0.f) { };
            else if (t.equals("int"))
                tree.init = new JCLiteral(TypeTag.INT, 0) { };
            else if (t.equals("long"))
                tree.init = new JCLiteral(TypeTag.LONG, 0) { };
            else if (t.equals("short"))
                tree.init = new JCLiteral(TypeTag.SHORT, 0) { };
            else
                tree.init = new JCLiteral(TypeTag.BOT, null) { };
        }
    }
    result = tree;
}
 
Example #17
Source File: TypeAnnotations.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitLambda(JCLambda tree) {
    JCLambda prevLambda = currentLambda;
    try {
        currentLambda = tree;

        int i = 0;
        for (JCVariableDecl param : tree.params) {
            if (!param.mods.annotations.isEmpty()) {
                // Nothing to do for separateAnnotationsKinds if
                // there are no annotations of either kind.
                final TypeAnnotationPosition pos =  TypeAnnotationPosition
                        .methodParameter(tree, i, param.vartype.pos);
                push(param);
                try {
                    separateAnnotationsKinds(param.vartype, param.sym.type, param.sym, pos);
                } finally {
                    pop();
                }
            }
            ++i;
        }

        scan(tree.body);
        scan(tree.params);
    } finally {
        currentLambda = prevLambda;
    }
}
 
Example #18
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildMethod(JCMethodDecl method) {
	if (setAndGetAsHandled(method)) return null;
	List<JavacNode> childNodes = new ArrayList<JavacNode>();
	for (JCAnnotation annotation : method.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, false));
	for (JCVariableDecl param : method.params) addIfNotNull(childNodes, buildLocalVar(param, Kind.ARGUMENT));
	if (method.body != null && method.body.stats != null) {
		for (JCStatement statement : method.body.stats) addIfNotNull(childNodes, buildStatement(statement));
	}
	return putInMap(new JavacNode(this, method, childNodes, Kind.METHOD));
}
 
Example #19
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
/**
 * Returns if a field is marked deprecated, either by {@code @Deprecated} or in javadoc
 * @param field the field to check
 * @return {@code true} if a field is marked deprecated, either by {@code @Deprecated} or in javadoc, otherwise {@code false}
 */
public static boolean isFieldDeprecated(JavacNode field) {
	JCVariableDecl fieldNode = (JCVariableDecl) field.get();
	if ((fieldNode.mods.flags & Flags.DEPRECATED) != 0) {
		return true;
	}
	for (JavacNode child : field.down()) {
		if (annotationTypeMatches(Deprecated.class, child)) {
			return true;
		}
	}
	return false;
}
 
Example #20
Source File: MemberEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
    Env<AttrContext> mEnv = methodEnv(tree, env);
    mEnv.info.lint = mEnv.info.lint.augment(tree.sym);
    for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
        mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
    for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
        mEnv.info.scope.enterIfAbsent(l.head.sym);
    return mEnv;
}
 
Example #21
Source File: MemberEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Create a fresh environment for a variable's initializer.
 *  If the variable is a field, the owner of the environment's scope
 *  is be the variable itself, otherwise the owner is the method
 *  enclosing the variable definition.
 *
 *  @param tree     The variable definition.
 *  @param env      The environment current outside of the variable definition.
 */
Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
    Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
    if (tree.sym.owner.kind == TYP) {
        localEnv.info.scope = env.info.scope.dupUnshared(tree.sym);
    }
    if ((tree.mods.flags & STATIC) != 0 ||
            ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
        localEnv.info.staticLevel++;
    return localEnv;
}
 
Example #22
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private Field convertFieldDeclaration(JCVariableDecl fieldDeclaration) {
  Expression initializer;
  VariableElement variableElement = fieldDeclaration.sym;
  if (variableElement.getConstantValue() == null) {
    initializer = convertExpressionOrNull(fieldDeclaration.getInitializer());
  } else {
    initializer = convertConstantToLiteral(variableElement);
  }
  return Field.Builder.from(
          environment.createFieldDescriptor(variableElement, fieldDeclaration.type))
      .setInitializer(initializer)
      .setSourcePosition(getSourcePosition(fieldDeclaration))
      .setNameSourcePosition(Optional.of(getNamePosition(fieldDeclaration)))
      .build();
}
 
Example #23
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
LambdaTranslationContext(JCLambda tree) {
    super(tree);
    Frame frame = frameStack.head;
    switch (frame.tree.getTag()) {
        case VARDEF:
            assignedTo = self = ((JCVariableDecl) frame.tree).sym;
            break;
        case ASSIGN:
            self = null;
            assignedTo = TreeInfo.symbol(((JCAssign) frame.tree).getVariable());
            break;
        default:
            assignedTo = self = null;
            break;
     }

    // This symbol will be filled-in in complete
    this.translatedSym = makePrivateSyntheticMethod(0, null, null, owner.enclClass());

    translatedSymbols = new EnumMap<>(LambdaSymbolKind.class);

    translatedSymbols.put(PARAM, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(LOCAL_VAR, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(CAPTURED_VAR, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(CAPTURED_THIS, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(CAPTURED_OUTER_THIS, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(TYPE_VAR, new LinkedHashMap<Symbol, Symbol>());

    freeVarProcessedLocalClasses = new HashSet<>();
}
 
Example #24
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public java.util.List<JavacNode> generateFields(SingularData data, JavacNode builderType, JCTree source) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	JCExpression type = JavacHandlerUtil.chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "Builder");
	type = addTypeArgs(isMap() ? 2 : 1, false, builderType, type, data.getTypeArgs(), source);
	
	JCVariableDecl buildField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), data.getPluralName(), type, null);
	return Collections.singletonList(injectFieldAndMarkGenerated(builderType, buildField));
}
 
Example #25
Source File: DeferredAttr.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
boolean canLambdaBodyCompleteNormally(JCLambda tree) {
    List<JCVariableDecl> oldParams = tree.params;
    LocalCacheContext localCacheContext = argumentAttr.withLocalCacheContext();
    try {
        tree.params = StreamSupport.stream(tree.params)
                .map(vd -> make.VarDef(vd.mods, vd.name, make.Erroneous(), null))
                .collect(List.collector());
        return attribSpeculativeLambda(tree, env, attr.unknownExprInfo).canCompleteNormally;
    } finally {
        localCacheContext.leave();
        tree.params = oldParams;
    }
}
 
Example #26
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("fallthrough")
private Symbol owner(boolean skipLambda) {
    List<Frame> frameStack2 = frameStack;
    while (frameStack2.nonEmpty()) {
        switch (frameStack2.head.tree.getTag()) {
            case VARDEF:
                if (((JCVariableDecl)frameStack2.head.tree).sym.isLocal()) {
                    frameStack2 = frameStack2.tail;
                    break;
                }
                JCClassDecl cdecl = (JCClassDecl)frameStack2.tail.head.tree;
                return initSym(cdecl.sym,
                        ((JCVariableDecl)frameStack2.head.tree).sym.flags() & STATIC);
            case BLOCK:
                JCClassDecl cdecl2 = (JCClassDecl)frameStack2.tail.head.tree;
                return initSym(cdecl2.sym,
                        ((JCBlock)frameStack2.head.tree).flags & STATIC);
            case CLASSDEF:
                return ((JCClassDecl)frameStack2.head.tree).sym;
            case METHODDEF:
                return ((JCMethodDecl)frameStack2.head.tree).sym;
            case LAMBDA:
                if (!skipLambda)
                    return ((LambdaTranslationContext)contextMap
                            .get(frameStack2.head.tree)).translatedSym;
            default:
                frameStack2 = frameStack2.tail;
        }
    }
    Assert.error();
    return null;
}
 
Example #27
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Analyze results of local variable inference.
 */
void processVar(JCVariableDecl oldTree, JCVariableDecl newTree, boolean hasErrors) {
    if (!hasErrors) {
        if (types.isSameType(oldTree.type, newTree.type)) {
            log.warning(oldTree, Warnings.LocalRedundantType);
        }
    }
}
 
Example #28
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void visitVarDef(JCVariableDecl tree) {
    TranslationContext<?> context = context();
    LambdaTranslationContext ltc = (context != null && context instanceof LambdaTranslationContext)?
            (LambdaTranslationContext)context :
            null;
    if (ltc != null) {
        if (frameStack.head.tree.hasTag(LAMBDA)) {
            ltc.addSymbol(tree.sym, LOCAL_VAR);
        }
        // Check for type variables (including as type arguments).
        // If they occur within class nested in a lambda, mark for erasure
        Type type = tree.sym.asType();
        if (inClassWithinLambda() && !types.isSameType(types.erasure(type), type)) {
            ltc.addSymbol(tree.sym, TYPE_VAR);
        }
    }

    List<Frame> prevStack = frameStack;
    try {
        if (tree.sym.owner.kind == MTH) {
            frameStack.head.addLocal(tree.sym);
        }
        frameStack = frameStack.prepend(new Frame(tree));
        super.visitVarDef(tree);
    }
    finally {
        frameStack = prevStack;
    }
}
 
Example #29
Source File: GenStubs.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * field definitions: replace initializers with 0, 0.0, false etc
 * when possible -- i.e. leave public, protected initializers alone
 */
@Override
public void visitVarDef(JCVariableDecl tree) {
    tree.mods = translate(tree.mods);
    tree.vartype = translate(tree.vartype);
    if (tree.init != null) {
        if ((tree.mods.flags & (Flags.PUBLIC | Flags.PROTECTED)) != 0)
            tree.init = translate(tree.init);
        else {
            String t = tree.vartype.toString();
            if (t.equals("boolean"))
                tree.init = new JCLiteral(TypeTag.BOOLEAN, 0) { };
            else if (t.equals("byte"))
                tree.init = new JCLiteral(TypeTag.BYTE, 0) { };
            else if (t.equals("char"))
                tree.init = new JCLiteral(TypeTag.CHAR, 0) { };
            else if (t.equals("double"))
                tree.init = new JCLiteral(TypeTag.DOUBLE, 0.d) { };
            else if (t.equals("float"))
                tree.init = new JCLiteral(TypeTag.FLOAT, 0.f) { };
            else if (t.equals("int"))
                tree.init = new JCLiteral(TypeTag.INT, 0) { };
            else if (t.equals("long"))
                tree.init = new JCLiteral(TypeTag.LONG, 0) { };
            else if (t.equals("short"))
                tree.init = new JCLiteral(TypeTag.SHORT, 0) { };
            else
                tree.init = new JCLiteral(TypeTag.BOT, null) { };
        }
    }
    result = tree;
}
 
Example #30
Source File: TreePruner.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static boolean isFinal(JCClassDecl enclClass, JCVariableDecl tree) {
  if ((tree.mods.flags & Flags.FINAL) == Flags.FINAL) {
    return true;
  }
  if (enclClass != null && (enclClass.mods.flags & (Flags.ANNOTATION | Flags.INTERFACE)) != 0) {
    // Fields in annotation declarations and interfaces are implicitly final
    return true;
  }
  return false;
}