Java Code Examples for lombok.javac.JavacTreeMaker#Binary
The following examples show how to use
lombok.javac.JavacTreeMaker#Binary .
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: JavacSingularsRecipes.java From EasyMPermission with MIT License | 5 votes |
/** Generates 'this.<em>name</em>.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */ protected JCExpression getSize(JavacTreeMaker maker, JavacNode builderType, Name name, boolean nullGuard) { Name thisName = builderType.toName("this"); JCExpression fn = maker.Select(maker.Select(maker.Ident(thisName), name), builderType.toName("size")); JCExpression sizeInvoke = maker.Apply(List.<JCExpression>nil(), fn, List.<JCExpression>nil()); if (nullGuard) { JCExpression isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(thisName), name), maker.Literal(CTC_BOT, 0)); return maker.Conditional(isNull, maker.Literal(CTC_INT, 0), sizeInvoke); } return sizeInvoke; }
Example 2
Source File: HandleEqualsAndHashCode.java From EasyMPermission with MIT License | 5 votes |
public JCExpressionStatement createResultCalculation(JavacNode typeNode, JCExpression expr) { /* result = result * PRIME + (expr); */ JavacTreeMaker maker = typeNode.getTreeMaker(); Name resultName = typeNode.toName(RESULT_NAME); JCExpression mult = maker.Binary(CTC_MUL, maker.Ident(resultName), maker.Ident(typeNode.toName(PRIME_NAME))); JCExpression add = maker.Binary(CTC_PLUS, mult, expr); return maker.Exec(maker.Assign(maker.Ident(resultName), add)); }
Example 3
Source File: HandleEqualsAndHashCode.java From EasyMPermission with MIT License | 5 votes |
/** The 2 references must be clones of each other. */ public JCExpression longToIntForHashCode(JavacTreeMaker maker, JCExpression ref1, JCExpression ref2) { /* (int)(ref >>> 32 ^ ref) */ JCExpression shift = maker.Binary(CTC_UNSIGNED_SHIFT_RIGHT, ref1, maker.Literal(32)); JCExpression xorBits = maker.Binary(CTC_BITXOR, shift, ref2); return maker.TypeCast(maker.TypeIdent(CTC_INT), xorBits); }
Example 4
Source File: HandleEqualsAndHashCode.java From EasyMPermission with MIT License | 5 votes |
public JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField, JavacTreeMaker maker, JavacNode node, boolean isDouble) { /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */ JCExpression clazz = genJavaLangTypeRef(node, isDouble ? "Double" : "Float"); List<JCExpression> args = List.of(thisDotField, otherDotField); JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply( List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0)); return maker.If(compareCallEquals0, returnBool(maker, false), null); }
Example 5
Source File: JavacGuavaSingularizer.java From EasyMPermission with MIT License | 5 votes |
@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) { JavacTreeMaker maker = builderType.getTreeMaker(); List<JCExpression> jceBlank = List.nil(); boolean mapMode = isMap(); JCExpression varType = chainDotsString(builderType, data.getTargetFqn()); varType = addTypeArgs(mapMode ? 2 : 1, false, builderType, varType, data.getTypeArgs(), source); JCExpression empty; { //ImmutableX.of() JCExpression emptyMethod = chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "of"); List<JCExpression> invokeTypeArgs = createTypeArgs(mapMode ? 2 : 1, false, builderType, data.getTypeArgs(), source); empty = maker.Apply(invokeTypeArgs, emptyMethod, jceBlank); } JCExpression invokeBuild; { //this.pluralName.build(); invokeBuild = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName().toString(), "build"), jceBlank); } JCExpression isNull; { //this.pluralName == null isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), maker.Literal(CTC_BOT, null)); } JCExpression init = maker.Conditional(isNull, empty, invokeBuild); // this.pluralName == null ? ImmutableX.of() : this.pluralName.build() JCStatement jcs = maker.VarDef(maker.Modifiers(0), data.getPluralName(), varType, init); statements.append(jcs); }
Example 6
Source File: JavacGuavaSingularizer.java From EasyMPermission with MIT License | 5 votes |
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 7
Source File: JavacJavaUtilSingularizer.java From EasyMPermission with MIT License | 5 votes |
protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) { List<JCExpression> jceBlank = List.nil(); Name v1Name = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName(); Name v2Name = mapMode ? builderType.toName(data.getPluralName() + "$value") : null; JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name); JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null)); thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name); JCExpression v1Type = chainDots(builderType, "java", "util", "ArrayList"); v1Type = addTypeArgs(1, false, builderType, v1Type, data.getTypeArgs(), source); JCExpression constructArrayList = maker.NewClass(null, jceBlank, v1Type, jceBlank, null); JCStatement initV1 = maker.Exec(maker.Assign(thisDotField, constructArrayList)); JCStatement thenPart; if (mapMode) { thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v2Name); JCExpression v2Type = chainDots(builderType, "java", "util", "ArrayList"); List<JCExpression> tArgs = data.getTypeArgs(); if (tArgs != null && tArgs.tail != null) tArgs = tArgs.tail; else tArgs = List.nil(); v2Type = addTypeArgs(1, false, builderType, v2Type, tArgs, source); constructArrayList = maker.NewClass(null, jceBlank, v2Type, jceBlank, null); JCStatement initV2 = maker.Exec(maker.Assign(thisDotField, constructArrayList)); thenPart = maker.Block(0, List.of(initV1, initV2)); } else { thenPart = initV1; } return maker.If(cond, thenPart, null); }
Example 8
Source File: HandleToString.java From EasyMPermission with MIT License | 4 votes |
static JCMethodDecl createToString(JavacNode typeNode, Collection<JavacNode> fields, boolean includeFieldNames, boolean callSuper, FieldAccess fieldAccess, JCTree source) { JavacTreeMaker maker = typeNode.getTreeMaker(); JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); JCExpression returnType = genJavaLangTypeRef(typeNode, "String"); boolean first = true; String typeName = getTypeName(typeNode); String infix = ", "; String suffix = ")"; String prefix; if (callSuper) { prefix = typeName + "(super="; } else if (fields.isEmpty()) { prefix = typeName + "()"; } else if (includeFieldNames) { prefix = typeName + "(" + ((JCVariableDecl)fields.iterator().next().get()).name.toString() + "="; } else { prefix = typeName + "("; } JCExpression current = maker.Literal(prefix); if (callSuper) { JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")), List.<JCExpression>nil()); current = maker.Binary(CTC_PLUS, current, callToSuper); first = false; } for (JavacNode fieldNode : fields) { JCExpression expr; JCExpression fieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess); JCExpression fieldType = getFieldType(fieldNode, fieldAccess); // The distinction between primitive and object will be useful if we ever add a 'hideNulls' option. boolean fieldIsPrimitive = fieldType instanceof JCPrimitiveTypeTree; boolean fieldIsPrimitiveArray = fieldType instanceof JCArrayTypeTree && ((JCArrayTypeTree) fieldType).elemtype instanceof JCPrimitiveTypeTree; boolean fieldIsObjectArray = !fieldIsPrimitiveArray && fieldType instanceof JCArrayTypeTree; @SuppressWarnings("unused") boolean fieldIsObject = !fieldIsPrimitive && !fieldIsPrimitiveArray && !fieldIsObjectArray; if (fieldIsPrimitiveArray || fieldIsObjectArray) { JCExpression tsMethod = chainDots(typeNode, "java", "util", "Arrays", fieldIsObjectArray ? "deepToString" : "toString"); expr = maker.Apply(List.<JCExpression>nil(), tsMethod, List.<JCExpression>of(fieldAccessor)); } else expr = fieldAccessor; if (first) { current = maker.Binary(CTC_PLUS, current, expr); first = false; continue; } if (includeFieldNames) { current = maker.Binary(CTC_PLUS, current, maker.Literal(infix + fieldNode.getName() + "=")); } else { current = maker.Binary(CTC_PLUS, current, maker.Literal(infix)); } current = maker.Binary(CTC_PLUS, current, expr); } if (!first) current = maker.Binary(CTC_PLUS, current, maker.Literal(suffix)); JCStatement returnStatement = maker.Return(current); JCBlock body = maker.Block(0, List.of(returnStatement)); return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("toString"), returnType, List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null), source, typeNode.getContext()); }
Example 9
Source File: HandleWither.java From EasyMPermission with MIT License | 4 votes |
public JCMethodDecl createWither(long access, JavacNode field, JavacTreeMaker maker, JavacNode source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { String witherName = toWitherName(field); if (witherName == null) return null; JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>(); List<JCAnnotation> nonNulls = findAnnotations(field, NON_NULL_PATTERN); List<JCAnnotation> nullables = findAnnotations(field, NULLABLE_PATTERN); Name methodName = field.toName(witherName); List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables); long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext()); JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); JCExpression selfType = cloneSelfType(field); if (selfType == null) return null; ListBuffer<JCExpression> args = new ListBuffer<JCExpression>(); for (JavacNode child : field.up().down()) { if (child.getKind() != Kind.FIELD) continue; JCVariableDecl childDecl = (JCVariableDecl) child.get(); // Skip fields that start with $ if (childDecl.name.toString().startsWith("$")) continue; long fieldFlags = childDecl.mods.flags; // Skip static fields. if ((fieldFlags & Flags.STATIC) != 0) continue; // Skip initialized final fields. if (((fieldFlags & Flags.FINAL) != 0) && childDecl.init != null) continue; if (child.get() == field.get()) { args.append(maker.Ident(fieldDecl.name)); } else { args.append(createFieldAccessor(maker, child, FieldAccess.ALWAYS_FIELD)); } } JCNewClass newClass = maker.NewClass(null, List.<JCExpression>nil(), selfType, args.toList(), null); JCExpression identityCheck = maker.Binary(CTC_EQUAL, createFieldAccessor(maker, field, FieldAccess.ALWAYS_FIELD), maker.Ident(fieldDecl.name)); JCConditional conditional = maker.Conditional(identityCheck, maker.Ident(field.toName("this")), newClass); JCReturn returnStatement = maker.Return(conditional); if (nonNulls.isEmpty()) { statements.append(returnStatement); } else { JCStatement nullCheck = generateNullCheck(maker, field, source); if (nullCheck != null) statements.append(nullCheck); statements.append(returnStatement); } JCExpression returnType = cloneSelfType(field); JCBlock methodBody = maker.Block(0, statements.toList()); List<JCTypeParameter> methodGenericParams = List.nil(); List<JCVariableDecl> parameters = List.of(param); List<JCExpression> throwsClauses = List.nil(); JCExpression annotationMethodDefaultValue = null; List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod); if (isFieldDeprecated(field)) { annsOnMethod = annsOnMethod.prepend(maker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil())); } JCMethodDecl decl = recursiveSetGeneratedBy(maker.MethodDef(maker.Modifiers(access, annsOnMethod), methodName, returnType, methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext()); copyJavadoc(field, decl, CopyJavadoc.WITHER); return decl; }
Example 10
Source File: HandleCleanup.java From EasyMPermission with MIT License | 4 votes |
@Override public void handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup"); if (inNetbeansEditor(annotationNode)) return; deleteAnnotationIfNeccessary(annotationNode, Cleanup.class); String cleanupName = annotation.getInstance().value(); if (cleanupName.length() == 0) { annotationNode.addError("cleanupName cannot be the empty string."); return; } if (annotationNode.up().getKind() != Kind.LOCAL) { annotationNode.addError("@Cleanup is legal only on local variable declarations."); return; } JCVariableDecl decl = (JCVariableDecl)annotationNode.up().get(); if (decl.init == null) { annotationNode.addError("@Cleanup variable declarations need to be initialized."); return; } JavacNode ancestor = annotationNode.up().directUp(); JCTree blockNode = ancestor.get(); final List<JCStatement> statements; if (blockNode instanceof JCBlock) { statements = ((JCBlock)blockNode).stats; } else if (blockNode instanceof JCCase) { statements = ((JCCase)blockNode).stats; } else if (blockNode instanceof JCMethodDecl) { statements = ((JCMethodDecl)blockNode).body.stats; } else { annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block."); return; } boolean seenDeclaration = false; ListBuffer<JCStatement> newStatements = new ListBuffer<JCStatement>(); ListBuffer<JCStatement> tryBlock = new ListBuffer<JCStatement>(); for (JCStatement statement : statements) { if (!seenDeclaration) { if (statement == decl) seenDeclaration = true; newStatements.append(statement); } else { tryBlock.append(statement); } } if (!seenDeclaration) { annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent."); return; } doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name); JavacTreeMaker maker = annotationNode.getTreeMaker(); JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName)); List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec( maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil()))); JCExpression preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name)); JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null)); JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null); Context context = annotationNode.getContext(); JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast, context); newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast, context), List.<JCCatch>nil(), finalizer), ast, context)); if (blockNode instanceof JCBlock) { ((JCBlock)blockNode).stats = newStatements.toList(); } else if (blockNode instanceof JCCase) { ((JCCase)blockNode).stats = newStatements.toList(); } else if (blockNode instanceof JCMethodDecl) { ((JCMethodDecl)blockNode).body.stats = newStatements.toList(); } else throw new AssertionError("Should not get here"); ancestor.rebuild(); }
Example 11
Source File: JavacJavaUtilSingularizer.java From EasyMPermission with MIT License | 4 votes |
protected List<JCStatement> createJavaUtilSimpleCreationAndFillStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, boolean defineVar, boolean addInitialCapacityArg, boolean nullGuard, String targetType, JCTree source) { List<JCExpression> jceBlank = List.nil(); Name thisName = builderType.toName("this"); JCStatement createStat; { // pluralName = new java.util.TargetType(initialCap); List<JCExpression> constructorArgs = List.nil(); if (addInitialCapacityArg) { Name varName = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName(); // this.varName.size() < MAX_POWER_OF_2 ? 1 + this.varName.size() + (this.varName.size() - 3) / 3 : Integer.MAX_VALUE; // lessThanCutOff = this.varName.size() < MAX_POWER_OF_2 JCExpression lessThanCutoff = maker.Binary(CTC_LESS_THAN, getSize(maker, builderType, varName, nullGuard), maker.Literal(CTC_INT, 0x40000000)); JCExpression integerMaxValue = genJavaLangTypeRef(builderType, "Integer", "MAX_VALUE"); JCExpression sizeFormulaLeft = maker.Binary(CTC_PLUS, maker.Literal(CTC_INT, 1), getSize(maker, builderType, varName, nullGuard)); JCExpression sizeFormulaRightLeft = maker.Binary(CTC_MINUS, getSize(maker, builderType, varName, nullGuard), maker.Literal(CTC_INT, 3)); JCExpression sizeFormulaRight = maker.Binary(CTC_DIV, sizeFormulaRightLeft, maker.Literal(CTC_INT, 3)); JCExpression sizeFormula = maker.Binary(CTC_PLUS, sizeFormulaLeft, sizeFormulaRight); constructorArgs = List.<JCExpression>of(maker.Conditional(lessThanCutoff, sizeFormula, integerMaxValue)); } JCExpression targetTypeExpr = chainDots(builderType, "java", "util", targetType); targetTypeExpr = addTypeArgs(mapMode ? 2 : 1, false, builderType, targetTypeExpr, data.getTypeArgs(), source); JCExpression constructorCall = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null); if (defineVar) { JCExpression localShadowerType = chainDotsString(builderType, data.getTargetFqn()); localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs(), source); createStat = maker.VarDef(maker.Modifiers(0), data.getPluralName(), localShadowerType, constructorCall); } else { createStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), constructorCall)); } } JCStatement fillStat; { if (mapMode) { // for (int $i = 0; $i < this.pluralname$key.size(); i++) pluralname.put(this.pluralname$key.get($i), this.pluralname$value.get($i)); Name ivar = builderType.toName("$i"); Name keyVarName = builderType.toName(data.getPluralName() + "$key"); JCExpression pluralnameDotPut = maker.Select(maker.Ident(data.getPluralName()), builderType.toName("put")); JCExpression arg1 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$key", "get"), List.<JCExpression>of(maker.Ident(ivar))); JCExpression arg2 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$value", "get"), List.<JCExpression>of(maker.Ident(ivar))); JCStatement putStatement = maker.Exec(maker.Apply(jceBlank, pluralnameDotPut, List.of(arg1, arg2))); JCStatement forInit = maker.VarDef(maker.Modifiers(0), ivar, maker.TypeIdent(CTC_INT), maker.Literal(CTC_INT, 0)); JCExpression checkExpr = maker.Binary(CTC_LESS_THAN, maker.Ident(ivar), getSize(maker, builderType, keyVarName, nullGuard)); JCExpression incrementExpr = maker.Unary(CTC_POSTINC, maker.Ident(ivar)); fillStat = maker.ForLoop(List.of(forInit), checkExpr, List.of(maker.Exec(incrementExpr)), putStatement); } else { // pluralname.addAll(this.pluralname); JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName()); fillStat = maker.Exec(maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("addAll")), List.of(thisDotPluralName))); } if (nullGuard) { JCExpression thisDotField = maker.Select(maker.Ident(thisName), mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName()); JCExpression nullCheck = maker.Binary(CTC_NOT_EQUAL, thisDotField, maker.Literal(CTC_BOT, null)); fillStat = maker.If(nullCheck, fillStat, null); } } JCStatement unmodifiableStat; { // pluralname = Collections.unmodifiableInterfaceType(pluralname); JCExpression arg = maker.Ident(data.getPluralName()); JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiable" + data.getTargetSimpleType()), List.of(arg)); unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke)); } return List.of(createStat, fillStat, unmodifiableStat); }
Example 12
Source File: HandleRuntimePermission.java From EasyMPermission with MIT License | 4 votes |
private JCMethodDecl createOnRequestPermissionMethod(JavacNode typeNode, List<PermissionAnnotatedItem> permissionList) { JavacTreeMaker treeMaker = typeNode.getTreeMaker(); ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>(); JCTree.JCExpression returnType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID)); List<JCVariableDecl> paramList = List.of( Variable(typeNode) .modifiers(Flags.PARAMETER) .name("requestCode") .type(treeMaker.TypeIdent(CTC_INT)) .value(null) .build(), Variable(typeNode) .modifiers(Flags.PARAMETER) .name("permissions") .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String"))) .value(null) .build(), Variable(typeNode) .modifiers(Flags.PARAMETER) .name("grantResults") .type(treeMaker.TypeArray(treeMaker.TypeIdent(CTC_INT))) .value(null) .build() ); for (PermissionAnnotatedItem item : permissionList) { JCReturn jcReturn = treeMaker.Return(null); JCBinary cmpRequestCode = treeMaker.Binary(CTC_EQUAL, treeMaker.Ident(typeNode.toName("requestCode")), treeMaker.Literal(CTC_INT, item.getRequestCode())); JCBinary cmpGrantResult = treeMaker.Binary(CTC_NOT_EQUAL, treeMaker.Indexed(treeMaker.Ident(typeNode.toName("grantResults")), treeMaker.Literal(CTC_INT, 0)), JavacHandlerUtil.chainDots(typeNode, "android", "content", "pm", "PackageManager", "PERMISSION_GRANTED")); JCExpression toastMethod = JavacHandlerUtil.chainDots(typeNode, "android", "widget", "Toast", "makeText"); List<JCExpression> toastArgs = List.<JCTree.JCExpression>of( treeMaker.Ident(typeNode.toName("this")), treeMaker.Literal(MESSAGE_PERMISSIONS_WERE_NOT_GRANTED), treeMaker.Literal(CTC_INT, 1)); JCMethodInvocation printlnInvocation = treeMaker.Apply(List.<JCTree.JCExpression>nil(), toastMethod, toastArgs); JCExpressionStatement thenPart = treeMaker.Exec( treeMaker.Apply(List.<JCTree.JCExpression>nil(), treeMaker.Select(printlnInvocation, typeNode.toName("show")), List.<JCExpression>nil())); toastArgs = List.<JCTree.JCExpression>of( treeMaker.Ident(typeNode.toName("this")), treeMaker.Literal(MESSAGE_PERMISSIONS_HAVE_BEEN_GRANTED), treeMaker.Literal(CTC_INT, 1)); printlnInvocation = treeMaker.Apply(List.<JCTree.JCExpression>nil(), toastMethod, toastArgs); JCExpressionStatement elsePart = treeMaker.Exec( treeMaker.Apply(List.<JCTree.JCExpression>nil(), treeMaker.Select(printlnInvocation, typeNode.toName("show")), List.<JCExpression>nil())); JCIf jcIfGrantResult = If(typeNode) .condition(cmpGrantResult) .withThen(Block(typeNode).last(thenPart).build()) .withElse(Block(typeNode).last(elsePart).build()) .build(); JCIf jcIfRequestCode = If(typeNode) .condition(cmpRequestCode) .onlyThen(Block(typeNode).add(jcIfGrantResult).last(jcReturn).build()) .build(); statements.append(jcIfRequestCode); } JCBlock body = Block(typeNode) .last(statements.toList()) .build(); return Method(typeNode) .modifiers(Flags.PUBLIC) .returnType(returnType) .name("onRequestPermissionsResult") .paramType() .parameters(paramList) .thrown() .body(body) .build(); }
Example 13
Source File: HandleRuntimePermission.java From EasyMPermission with MIT License | 4 votes |
private JCMethodDecl createIsPermissionGrantedMethod(JavacNode typeNode) { JavacTreeMaker treeMaker = typeNode.getTreeMaker(); ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>(); statements.append(Variable(typeNode) .modifiers(0) .name("ok") .type(treeMaker.TypeIdent(CTC_BOOLEAN)) .value(treeMaker.Literal(CTC_BOOLEAN, 1)) .build()); statements.append(Variable(typeNode) .modifiers(0) .name("failed") .type(treeMaker.TypeIdent(CTC_BOOLEAN)) .value(treeMaker.Literal(CTC_BOOLEAN, 0)) .build()); JCTree.JCExpression returnType = treeMaker.TypeIdent(CTC_BOOLEAN); List<JCTypeParameter> typleList = List.nil(); List<JCVariableDecl> paramList = List.of( Variable(typeNode) .modifiers(Flags.PARAMETER) .name("permissions") .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String"))) .value(null) .build() ); JCVariableDecl v = Variable(typeNode) .modifiers(Flags.PARAMETER) .name("permission") .type(genJavaLangTypeRef(typeNode, "String")) .value(null) .build(); JCExpression checkMethod = JavacHandlerUtil.chainDots(typeNode, "this", "checkSelfPermission"); List<JCExpression> checkArgs = List.<JCExpression>of(treeMaker.Ident(typeNode.toName("permission"))); JCMethodInvocation checkInvocation = treeMaker.Apply(List.<JCExpression>nil(), checkMethod, checkArgs); JCExpression cmp = treeMaker.Binary(CTC_NOT_EQUAL, checkInvocation, JavacHandlerUtil.chainDots(typeNode, "android", "content", "pm", "PackageManager", "PERMISSION_GRANTED")); JCBlock body = Block(typeNode) .last(treeMaker.Return(treeMaker.Ident(typeNode.toName("failed")))) .build(); JCIf jcIf = If(typeNode) .condition(cmp) .onlyThen(body) .build(); JCEnhancedForLoop block = treeMaker.ForeachLoop(v, treeMaker.Ident(typeNode.toName("permissions")), jcIf); statements.append(block); statements.append(treeMaker.Return(treeMaker.Ident(typeNode.toName("ok")))); body = Block(typeNode) .last(statements.toList()) .build(); return Method(typeNode) .modifiers(Flags.PRIVATE) .returnType(returnType) .name(IS_PERMISSION_GRANTED_METHOD) .paramType(typleList) .parameters(paramList) .thrown() .body(body) .build(); }
Example 14
Source File: HandleRuntimePermission.java From EasyMPermission with MIT License | 4 votes |
private JCBlock createPermissionCheckedBlock(JavacNode typeNode, PermissionAnnotatedItem permissionAnnotatedItem) { JavacTreeMaker treeMaker = typeNode.getTreeMaker(); // Create permission list ListBuffer<JCExpression> permissionArgs = new ListBuffer<JCExpression>(); for (String permission : permissionAnnotatedItem.getPermissions()) { permissionArgs.append(treeMaker.Literal(permission)); } String permissionVarName = "_permissions_" + permissionAnnotatedItem.getMethod().getName(); JCExpression v = treeMaker.NewArray(null, List.<JCExpression>nil(), permissionArgs.toList()); JCVariableDecl permissions = Variable(typeNode) .modifiers(Flags.PRIVATE) .name(permissionVarName) .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String"))) .value(v) .build(); injectField(typeNode, permissions); JCExpression checkMethod = JavacHandlerUtil.chainDots(typeNode, "this", IS_PERMISSION_GRANTED_METHOD); List<JCExpression> checkArgs = List.<JCExpression>of(treeMaker.Ident(typeNode.toName(permissionVarName))); JCMethodInvocation checkInvocation = treeMaker.Apply(List.<JCExpression>nil(), checkMethod, checkArgs); JCExpression permissionCmp = treeMaker.Binary(CTC_EQUAL, checkInvocation, treeMaker.Literal(CTC_BOOLEAN, 1)); JCExpression requestMethod = JavacHandlerUtil.chainDots(typeNode, "this", "requestPermissions"); List<JCExpression> requestArgs = List.<JCExpression>of( treeMaker.Ident(typeNode.toName(permissionVarName)), treeMaker.Literal(CTC_INT, permissionAnnotatedItem.getRequestCode())); JCMethodInvocation requestInvocation = treeMaker.Apply(List.<JCExpression>nil(), requestMethod, requestArgs); JCBlock body = Block(typeNode) .last(treeMaker.Exec(requestInvocation)) .build(); JCIf jcCheckPermissionIf = If(typeNode) .condition(permissionCmp) .withThen(permissionAnnotatedItem.getMethod().getBody()) .withElse(body) .build(); JCBlock checkPermissionBlock = Block(typeNode) .last(jcCheckPermissionIf) .build(); JCExpression versionCmp = treeMaker.Binary(CTC_LESS_THAN, JavacHandlerUtil.chainDots(typeNode, "android", "os", "Build", "VERSION", "SDK_INT"), treeMaker.Literal(CTC_INT, 23)); JCIf jcIf = If(typeNode) .condition(versionCmp) .withThen(permissionAnnotatedItem.getMethod().getBody()) .withElse(checkPermissionBlock) .build(); return Block(typeNode) .last(jcIf) .build(); }