Java Code Examples for com.sun.tools.javac.tree.JCTree.JCMethodDecl

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCMethodDecl. These examples are extracted from open source projects. 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 Project: TencentKona-8   Author: Tencent   File: GenStubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #2
Source Project: jdk8u60   Author: chenghanpeng   File: GenStubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #3
Source Project: jdk8u60   Author: chenghanpeng   File: TypeAnnotations.java    License: GNU General Public License v2.0 6 votes vote down vote up
private int methodParamIndex(List<JCTree> path, JCTree param) {
    List<JCTree> curr = path;
    while (curr.head.getTag() != Tag.METHODDEF &&
            curr.head.getTag() != Tag.LAMBDA) {
        curr = curr.tail;
    }
    if (curr.head.getTag() == Tag.METHODDEF) {
        JCMethodDecl method = (JCMethodDecl)curr.head;
        return method.params.indexOf(param);
    } else if (curr.head.getTag() == Tag.LAMBDA) {
        JCLambda lambda = (JCLambda)curr.head;
        return lambda.params.indexOf(param);
    } else {
        Assert.error("methodParamIndex expected to find method or lambda for param: " + param);
        return -1;
    }
}
 
Example #4
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: GenStubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #5
Source Project: EasyMPermission   Author: mobmead   File: JavacJavaUtilListSetSingularizer.java    License: MIT License 6 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "add");
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getSingularName())));
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("add", name.toString()));
	JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #6
Source Project: EasyMPermission   Author: mobmead   File: HandleEqualsAndHashCode.java    License: MIT License 6 votes vote down vote up
public JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source, List<JCAnnotation> onParam) {
	/* public boolean canEqual(final java.lang.Object other) {
	 *     return other instanceof Outer.Inner.MyType;
	 * }
	 */
	JavacTreeMaker maker = typeNode.getTreeMaker();
	
	JCModifiers mods = maker.Modifiers(Flags.PROTECTED, List.<JCAnnotation>nil());
	JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
	Name canEqualName = typeNode.toName("canEqual");
	JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
	Name otherName = typeNode.toName("other");
	long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
	List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(flags, onParam), otherName, objectType, null));
	
	JCBlock body = maker.Block(0, List.<JCStatement>of(
			maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode)))));
	
	return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
 
Example #7
Source Project: EasyMPermission   Author: mobmead   File: HandleSneakyThrows.java    License: MIT License 6 votes vote down vote up
@Override public void handle(AnnotationValues<SneakyThrows> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.SNEAKY_THROWS_FLAG_USAGE, "@SneakyThrows");
	
	deleteAnnotationIfNeccessary(annotationNode, SneakyThrows.class);
	Collection<String> exceptionNames = annotation.getRawExpressions("value");
	if (exceptionNames.isEmpty()) {
		exceptionNames = Collections.singleton("java.lang.Throwable");
	}
	
	java.util.List<String> exceptions = new ArrayList<String>();
	for (String exception : exceptionNames) {
		if (exception.endsWith(".class")) exception = exception.substring(0, exception.length() - 6);
		exceptions.add(exception);
	}
	
	JavacNode owner = annotationNode.up();
	switch (owner.getKind()) {
	case METHOD:
		handleMethod(annotationNode, (JCMethodDecl)owner.get(), exceptions);
		break;
	default:
		annotationNode.addError("@SneakyThrows is legal only on methods and constructors.");
		break;
	}
}
 
Example #8
Source Project: EasyMPermission   Author: mobmead   File: JavacAST.java    License: 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 #9
Source Project: EasyMPermission   Author: mobmead   File: JavacHandlerUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Checks if there is a (non-default) constructor. In case of multiple constructors (overloading), only
 * the first constructor decides if EXISTS_BY_USER or EXISTS_BY_LOMBOK is returned.
 * 
 * @param node Any node that represents the Type (JCClassDecl) to look in, or any child node thereof.
 */
public static MemberExistsResult constructorExists(JavacNode node) {
	node = upToTypeNode(node);
	
	if (node != null && node.get() instanceof JCClassDecl) {
		top: for (JCTree def : ((JCClassDecl)node.get()).defs) {
			if (def instanceof JCMethodDecl) {
				JCMethodDecl md = (JCMethodDecl) def;
				if (md.name.contentEquals("<init>")) {
					if ((md.mods.flags & Flags.GENERATEDCONSTR) != 0) continue;
					List<JCAnnotation> annotations = md.getModifiers().getAnnotations();
					if (annotations != null) for (JCAnnotation anno : annotations) {
						if (typeMatches(Tolerate.class, node, anno.getAnnotationType())) continue top;
					}
					return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK;
				}
			}
		}
	}
	
	return MemberExistsResult.NOT_EXISTS;
}
 
Example #10
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: TypeAnnotations.java    License: GNU General Public License v2.0 6 votes vote down vote up
private int methodParamIndex(List<JCTree> path, JCTree param) {
    List<JCTree> curr = path;
    while (curr.head.getTag() != Tag.METHODDEF &&
            curr.head.getTag() != Tag.LAMBDA) {
        curr = curr.tail;
    }
    if (curr.head.getTag() == Tag.METHODDEF) {
        JCMethodDecl method = (JCMethodDecl)curr.head;
        return method.params.indexOf(param);
    } else if (curr.head.getTag() == Tag.LAMBDA) {
        JCLambda lambda = (JCLambda)curr.head;
        return lambda.params.indexOf(param);
    } else {
        Assert.error("methodParamIndex expected to find method or lambda for param: " + param);
        return -1;
    }
}
 
Example #11
Source Project: javaide   Author: tranleduy2000   File: ExpressionResolver.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private Expression getExpressionFromMethod(JCMethodDecl method) {
    System.out.println("CompleteExpression.getExpressionFromMethod");

    Expression expression;
    List<JCVariableDecl> parameters = method.getParameters();

    for (JCVariableDecl parameter : parameters) {
        expression = getExpressionFromStatement(parameter);
        if (expression != null) {
            expression.addRoot(method);
            return expression;
        }
    }

    expression = getExpressionFromStatement(method.getBody());

    return addRootIfNeeded(method, expression);
}
 
Example #12
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: GenStubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #13
Source Project: annotation-tools   Author: typetools   File: TreeFinder.java    License: MIT License 6 votes vote down vote up
@Override
public Pair<ASTRecord, Integer> visitMethod(MethodTree node, Insertion ins) {
  dbug.debug("TypePositionFinder.visitMethod%n");
  super.visitMethod(node, ins);

  JCMethodDecl jcnode = (JCMethodDecl) node;
  JCVariableDecl jcvar = (JCVariableDecl) node.getReceiverParameter();
  if (jcvar != null) { return pathAndPos(jcvar); }

  int pos = Position.NOPOS;
  ASTRecord astPath = astRecord(jcnode)
      .extend(Tree.Kind.METHOD, ASTPath.PARAMETER, -1);

  if (node.getParameters().isEmpty()) {
    // no parameters; find first (uncommented) '(' after method name
    pos = findMethodName(jcnode);
    if (pos >= 0) { pos = getFirstInstanceAfter('(', pos); }
    if (++pos <= 0) {
      throw new RuntimeException("Couldn't find param opening paren for: "
          + jcnode);
    }
  } else {
    pos = ((JCTree) node.getParameters().get(0)).getStartPosition();
  }
  return Pair.of(astPath, pos);
}
 
Example #14
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TypeAnnotations.java    License: GNU General Public License v2.0 6 votes vote down vote up
private int methodParamIndex(List<JCTree> path, JCTree param) {
    List<JCTree> curr = path;
    while (curr.head.getTag() != Tag.METHODDEF &&
            curr.head.getTag() != Tag.LAMBDA) {
        curr = curr.tail;
    }
    if (curr.head.getTag() == Tag.METHODDEF) {
        JCMethodDecl method = (JCMethodDecl)curr.head;
        return method.params.indexOf(param);
    } else if (curr.head.getTag() == Tag.LAMBDA) {
        JCLambda lambda = (JCLambda)curr.head;
        return lambda.params.indexOf(param);
    } else {
        Assert.error("methodParamIndex expected to find method or lambda for param: " + param);
        return -1;
    }
}
 
Example #15
Source Project: hottub   Author: dsrg-uoft   File: GenStubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #16
Source Project: hottub   Author: dsrg-uoft   File: TypeAnnotations.java    License: GNU General Public License v2.0 6 votes vote down vote up
private int methodParamIndex(List<JCTree> path, JCTree param) {
    List<JCTree> curr = path;
    while (curr.head.getTag() != Tag.METHODDEF &&
            curr.head.getTag() != Tag.LAMBDA) {
        curr = curr.tail;
    }
    if (curr.head.getTag() == Tag.METHODDEF) {
        JCMethodDecl method = (JCMethodDecl)curr.head;
        return method.params.indexOf(param);
    } else if (curr.head.getTag() == Tag.LAMBDA) {
        JCLambda lambda = (JCLambda)curr.head;
        return lambda.params.indexOf(param);
    } else {
        Assert.error("methodParamIndex expected to find method or lambda for param: " + param);
        return -1;
    }
}
 
Example #17
Source Project: openjdk-8   Author: bpupadhyaya   File: GenStubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #18
Source Project: openjdk-8   Author: bpupadhyaya   File: TypeAnnotations.java    License: GNU General Public License v2.0 6 votes vote down vote up
private int methodParamIndex(List<JCTree> path, JCTree param) {
    List<JCTree> curr = path;
    while (curr.head.getTag() != Tag.METHODDEF &&
            curr.head.getTag() != Tag.LAMBDA) {
        curr = curr.tail;
    }
    if (curr.head.getTag() == Tag.METHODDEF) {
        JCMethodDecl method = (JCMethodDecl)curr.head;
        return method.params.indexOf(param);
    } else if (curr.head.getTag() == Tag.LAMBDA) {
        JCLambda lambda = (JCLambda)curr.head;
        return lambda.params.indexOf(param);
    } else {
        Assert.error("methodParamIndex expected to find method or lambda for param: " + param);
        return -1;
    }
}
 
Example #19
Source Project: EasyMPermission   Author: mobmead   File: HandleRuntimePermission.java    License: MIT License 5 votes vote down vote up
@Override
public void handle(AnnotationValues<RuntimePermission> annotation, JCAnnotation ast, JavacNode annotationNode) {

    deleteAnnotationIfNeccessary(annotationNode, RuntimePermission.class);
    JavacNode typeNode = annotationNode.up();
    boolean notAClass = !isClass(typeNode);

    if (notAClass) {
        annotationNode.addError("@RuntimePermission is only supported on a class.");
        return;
    }

    JCMethodDecl method;

    List<PermissionAnnotatedItem> permissionList = findAllAnnotatedMethods(typeNode);
    for (PermissionAnnotatedItem item : permissionList) {
        method = createPermissionCheckedMethod(typeNode, item);
        removeMethod(typeNode, item.getMethod());
        injectMethod(typeNode, recursiveSetGeneratedBy(method, annotationNode.get(), typeNode.getContext()));
    }

    method = recursiveSetGeneratedBy(createIsPermissionGrantedMethod(typeNode), annotationNode.get(), typeNode.getContext());
    injectMethod(typeNode, method);

    method = recursiveSetGeneratedBy(createOnRequestPermissionMethod(typeNode, permissionList), annotationNode.get(), typeNode.getContext());
    injectMethod(typeNode, method);
}
 
Example #20
Source Project: EasyMPermission   Author: mobmead   File: JavacHandlerUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Adds the given new method declaration to the provided type AST Node.
 * Can also inject constructors.
 * 
 * Also takes care of updating the JavacAST.
 */
public static void injectMethod(JavacNode typeNode, JCMethodDecl method) {
	JCClassDecl type = (JCClassDecl) typeNode.get();
	
	if (method.getName().contentEquals("<init>")) {
		//Scan for default constructor, and remove it.
		int idx = 0;
		for (JCTree def : type.defs) {
			if (def instanceof JCMethodDecl) {
				if ((((JCMethodDecl)def).mods.flags & Flags.GENERATEDCONSTR) != 0) {
					JavacNode tossMe = typeNode.getNodeFor(def);
					if (tossMe != null) tossMe.up().removeChild(tossMe);
					type.defs = addAllButOne(type.defs, idx);
					if (type.sym != null && type.sym.members_field != null) {
						 type.sym.members_field.remove(((JCMethodDecl)def).sym);
					}
					break;
				}
			}
			idx++;
		}
	}
	
	addSuppressWarningsAll(method.mods, typeNode, method.pos, getGeneratedBy(method), typeNode.getContext());
	addGenerated(method.mods, typeNode, method.pos, getGeneratedBy(method), typeNode.getContext());
	type.defs = type.defs.append(method);
	
	typeNode.add(method, Kind.METHOD);
}
 
Example #21
Source Project: jdk8u60   Author: chenghanpeng   File: TestInvokeDynamic.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree node, Void p) {
    super.visitMethod(node, p);
    if (node.getName().toString().equals("bsm")) {
        bsm = ((JCMethodDecl)node).sym;
    }
    return null;
}
 
Example #22
Source Project: annotation-tools   Author: typetools   File: JVMNames.java    License: MIT License 5 votes vote down vote up
/**
 * Converts a MethodTree into a JVML format method signature.
 * There is probably an API to do this, but I couldn't find it.
 *
 * @param methodTree the tree to convert
 * @return a String signature of methodTree in JVML format
 */
public static String getJVMMethodSignature(MethodTree methodTree) {
    ExecutableElement methodElement = ((JCMethodDecl) methodTree).sym;
    StringBuilder builder = new StringBuilder();
    String returnTypeStr;
    builder.append(methodTree.getName());
    builder.append("(");

    if (methodElement == null) {
        // use source AST in lieu of symbol table
        List<JCVariableDecl> params = ((JCMethodDecl) methodTree).params;
        JCVariableDecl param = params.head;
        JCExpression typeTree = ((JCMethodDecl) methodTree).restype;
        returnTypeStr = treeToJVMLString(typeTree);
        while (param != null) {
            builder.append(treeToJVMLString(param.vartype));
            params = params.tail;
            param = params.head;
        }
    } else {
        TypeMirror returnType = methodElement.getReturnType();
        returnTypeStr = typeToJvmlString((Type)returnType);
        for (VariableElement ve : methodElement.getParameters()) {
            Type vt = (Type) ve.asType();
            if (vt.getTag() == TypeTag.TYPEVAR) {
                vt = vt.getUpperBound();
            }
            builder.append(typeToJvmlString(vt));
        }
    }
    builder.append(")");
    builder.append(returnTypeStr);
    return builder.toString();
}
 
Example #23
Source Project: bazel   Author: bazelbuild   File: TreePruner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethodDef(JCMethodDecl tree) {
  if (tree.body == null) {
    return;
  }
  if (tree.getReturnType() == null && delegatingConstructor(tree.body.stats)) {
    // if the first statement of a constructor declaration delegates to another
    // constructor, it needs to be preserved to satisfy checks in Resolve
    tree.body.stats = com.sun.tools.javac.util.List.of(tree.body.stats.get(0));
    return;
  }
  tree.body.stats = com.sun.tools.javac.util.List.nil();
}
 
Example #24
Source Project: EasyMPermission   Author: mobmead   File: HandleRuntimePermission.java    License: MIT License 5 votes vote down vote up
private void removeMethod(JavacNode typeNode, JCMethodDecl method) {
    typeNode = upToTypeNode(typeNode);
    ListBuffer<JCTree> newList = new ListBuffer<JCTree>();
    for (JCTree def : ((JCTree.JCClassDecl)typeNode.get()).defs) {
        if (!(def instanceof JCMethodDecl && def == method)) {
            newList.append(def);
        }
    }
    ((JCTree.JCClassDecl)typeNode.get()).defs = newList.toList();
}
 
Example #25
Source Project: annotation-tools   Author: typetools   File: TreeFinder.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the start position of the method's name.  In particular,
 * works properly for constructors, for which the name field in the
 * AST is always "<init>" instead of the name from the source.
 *
 * @param node AST node of method declaration
 * @return position of method name (from {@link JCMethodDecl#sym}) in source
 */
private int findMethodName(JCMethodDecl node) {
  String sym = node.sym.toString();
  String name = sym.substring(0, sym.indexOf('('));
  JCModifiers mods = node.getModifiers();
  JCBlock body = node.body;
  if ((mods.flags & Flags.GENERATEDCONSTR) != 0) { return Position.NOPOS; }
  int nodeStart = node.getStartPosition();
  int nodeEnd = node.getEndPosition(tree.endPositions);
  int nodeLength = nodeEnd - nodeStart;
  int modsLength = mods.getEndPosition(tree.endPositions)
      - mods.getStartPosition();  // can't trust string length!
  int bodyLength = body == null ? 1
      : body.getEndPosition(tree.endPositions) - body.getStartPosition();
  int start = nodeStart + modsLength;
  int end = nodeStart + nodeLength - bodyLength;
  int angle = name.lastIndexOf('>');  // check for type params
  if (angle >= 0) { name = name.substring(angle + 1); }

  try {
    CharSequence s = tree.getSourceFile().getCharContent(true);
    String regex = "\\b" + Pattern.quote(name) + "\\b";  // sufficient?
    Pattern pat = Pattern.compile(regex, Pattern.MULTILINE);
    Matcher mat = pat.matcher(s).region(start, end);
    return mat.find() ? mat.start() : Position.NOPOS;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #26
public void visitMethodDef(JCMethodDecl node) {
    // remove super constructor call that may have been added during attribution:
    if (TreeInfo.isConstructor(node) && node.sym != null && node.sym.owner.isEnum() &&
        node.body.stats.nonEmpty() && TreeInfo.isSuperCall(node.body.stats.head) &&
        node.body.stats.head.pos == node.body.pos) {
        node.body.stats = node.body.stats.tail;
    }
    node.sym = null;
    super.visitMethodDef(node);
}
 
Example #27
Source Project: EasyMPermission   Author: mobmead   File: JavacJavaUtilMapSingularizer.java    License: 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 #28
Source Project: lua-for-android   Author: qtiuto   File: Check.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
    MethodSymbol m = tree.sym;
    if (!allowSimplifiedVarargs) return;
    boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
    Type varargElemType = null;
    if (m.isVarArgs()) {
        varargElemType = types.elemtype(tree.params.last().type);
    }
    if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
        if (varargElemType != null) {
            JCDiagnostic msg = allowPrivateSafeVarargs ?
                    diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargs(m)) :
                    diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargsFinalOnly(m));
            log.error(tree,
                      Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
                                                       msg));
        } else {
            log.error(tree,
                      Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
                                                       Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
        }
    } else if (hasTrustMeAnno && varargElemType != null &&
                        types.isReifiable(varargElemType)) {
        warnUnsafeVararg(tree,
                        "varargs.redundant.trustme.anno",
                        syms.trustMeType.tsym,
                        diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType)));
    }
    else if (!hasTrustMeAnno && varargElemType != null &&
            !types.isReifiable(varargElemType)) {
        warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
    }
}
 
Example #29
Source Project: EasyMPermission   Author: mobmead   File: JavacGuavaSingularizer.java    License: MIT License 5 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	Name keyName = !mapMode ? data.getSingularName() : builderType.toName(data.getSingularName() + "$key");
	Name valueName = !mapMode ? null : builderType.toName(data.getSingularName() + "$value");
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "put" : "add");
	List<JCExpression> invokeAddExpr;
	if (mapMode) {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName), maker.Ident(valueName));
	} else {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName));
	}
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, invokeAddExpr);
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "put" : "add", methodName.toString()));
	List<JCVariableDecl> params;
	if (mapMode) {
		JCExpression keyType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		JCExpression valueType = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
		JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, keyType, null);
		JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, valueType, null);
		params = List.of(paramKey, paramValue);
	} else {
		JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		params = List.of(maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null));
	}
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #30
Source Project: lua-for-android   Author: qtiuto   File: Lower.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitMethodDef(JCMethodDecl tree) {
    if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
        // Add "String $enum$name, int $enum$ordinal" to the beginning of the
        // argument list for each constructor of an enum.
        JCVariableDecl nameParam = make_at(tree.pos()).
            Param(names.fromString(target.syntheticNameChar() +
                                   "enum" + target.syntheticNameChar() + "name"),
                  syms.stringType, tree.sym);
        nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
        JCVariableDecl ordParam = make.
            Param(names.fromString(target.syntheticNameChar() +
                                   "enum" + target.syntheticNameChar() +
                                   "ordinal"),
                  syms.intType, tree.sym);
        ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;

        MethodSymbol m = tree.sym;
        tree.params = tree.params.prepend(ordParam).prepend(nameParam);

        m.extraParams = m.extraParams.prepend(ordParam.sym);
        m.extraParams = m.extraParams.prepend(nameParam.sym);
        Type olderasure = m.erasure(types);
        m.erasure_field = new MethodType(
            olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
            olderasure.getReturnType(),
            olderasure.getThrownTypes(),
            syms.methodClass);
    }

    JCMethodDecl prevMethodDef = currentMethodDef;
    MethodSymbol prevMethodSym = currentMethodSym;
    try {
        currentMethodDef = tree;
        currentMethodSym = tree.sym;
        visitMethodDefInternal(tree);
    } finally {
        currentMethodDef = prevMethodDef;
        currentMethodSym = prevMethodSym;
    }
}