List of usage examples for org.objectweb.asm.tree FieldNode FieldNode
public FieldNode(final int access, final String name, final String descriptor, final String signature, final Object value)
From source file:blue.origami.asm.OClassWriter.java
License:Apache License
public final void addField(OAnno anno, String name, OType ty, String signature, Object value) { // String signature = ty.desc(); FieldNode fn = new FieldNode(anno.acc(), name, ty.typeDesc(0), signature, value); if (ty.isNullable()) { anno.setAnnotation(ONullable.class); }//from w ww. j ava 2s .c o m if (ty.isMutable()) { anno.setAnnotation(OMutable.class); } anno.asm(fn); fn.accept(this); }
From source file:ca.weblite.mirah.ant.mirrors.ClassReader.java
/** * Generates the the mirah mirrors for a specific java source file. This * file must be a .java file. It cannot be a directory. * // w w w . j a v a 2 s . c om * @param javaSourceFile * @throws IOException */ public void parse() throws IOException { File javaSourceFile = sourceFile; JavaCompiler compiler = JavacTool.create(); MyFileObject[] fos = new MyFileObject[] { new MyFileObject(javaSourceFile) }; JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, Arrays.asList(fos)); Iterable<? extends CompilationUnitTree> asts = task.parse(); final Stack<Set<String>> typeParams = new Stack<Set<String>>(); TreePathScanner scanner; scanner = new TreePathScanner() { private boolean isGenericType(String type) { Stack<Set> desk = new Stack<Set>(); boolean found = false; while (!typeParams.empty()) { Set params = typeParams.pop(); desk.push(params); if (params.contains(type)) { found = true; break; } } while (!desk.empty()) { typeParams.push(desk.pop()); } return found; } String formatType(String type) { int pos = type.indexOf("<"); if (pos >= 0) { type = type.substring(0, pos); } if (isGenericType(type)) { return "Object"; } return type; } @Override public Object visitCompilationUnit(CompilationUnitTree cut, Object p) { PackageScope scope = new PackageScope(scopeStack.peek(), cut.getPackageName().toString()); scope.addImport(scope.getPackageName() + ".*"); scope.addImport("java.lang.*"); scope.addImport("*"); packageScope = scope; scopeStack.push(scope); return super.visitCompilationUnit(cut, p); } @Override public Object visitImport(ImportTree it, Object p) { String path = it.getQualifiedIdentifier().toString(); packageScope.addImport(path); return super.visitImport(it, p); } private void decorateClassNode(ClassTree ct, ClassNode classNode) { int flags = getFlags(ct.getModifiers().getFlags()); switch (ct.getKind()) { case INTERFACE: flags |= Opcodes.ACC_INTERFACE; break; case ENUM: flags |= Opcodes.ACC_ENUM; break; } classNode.access = flags; classNode.sourceFile = sourceFile.getPath(); String extendsClause = "java.lang.Object"; if (ct.getExtendsClause() != null) { extendsClause = ct.getExtendsClause().toString(); } String superPath = scopeStack.peek().resolveName(extendsClause, false); ClassIndex.Node superNode = scopeStack.peek().getLoader().find(superPath); if (superNode == null) { throw new RuntimeException("Failed to find super class " + superPath); } classNode.superName = superNode.internalName; classNode.interfaces = new ArrayList<String>(); String impl = ct.getImplementsClause().toString(); if (!"".equals(impl)) { String[] interfaces = impl.split(","); for (String iface : interfaces) { iface = iface.trim(); String ipath = scopeStack.peek().resolveName(iface, false); ClassIndex.Node iNode = scopeStack.peek().getLoader().find(ipath); if (iNode == null) { throw new RuntimeException("Failed to load " + "interface " + ipath); } classNode.interfaces.add(iNode.internalName); } } } @Override public Object visitClass(ClassTree ct, Object p) { ClassScope clsScope = null; ClassNode currClassNode = null; if (scopeStack.peek() == packageScope) { String path = packageScope.getPackageName() + "." + ct.getSimpleName(); ClassIndex.Node n = packageScope.getLoader().find(path); if (n == null) { throw new RuntimeException("Failed to find class " + path); } node.name = n.internalName; currClassNode = node; decorateClassNode(ct, node); clsScope = new ClassScope(scopeStack.peek(), n); } else { // This must be an internal class ClassNode parentClass = classNodeStack.peek(); if (parentClass.innerClasses == null) { parentClass.innerClasses = new ArrayList<>(); } String path = scopeStack.peek().resolveName(ct.getSimpleName().toString(), false); ClassIndex.Node n = packageScope.getLoader().find(path); if (n == null) { throw new RuntimeException("Failed to find class " + path); } InnerClassNode innerNode = new InnerClassNode(n.internalName, parentClass.name, n.simpleName, getFlags(ct.getModifiers().getFlags())); parentClass.innerClasses.add(innerNode); ClassNode cls = new ClassNode(); cls.name = n.internalName; cls.outerClass = parentClass.name; decorateClassNode(ct, cls); clsScope = new ClassScope(scopeStack.peek(), n); currClassNode = cls; } scopeStack.push(clsScope); classNodeStack.push(currClassNode); Object out = super.visitClass(ct, p); classNodeStack.pop(); scopeStack.pop(); return out; } /** * Converts modifier flags from Javac Tree into int flags usable in * TypeMirror * @param mods * @return */ int getFlags(Set<Modifier> mods) { int flags = 0; for (Modifier m : mods) { switch (m) { case ABSTRACT: flags |= Opcodes.ACC_ABSTRACT; break; case FINAL: flags |= Opcodes.ACC_FINAL; break; case PRIVATE: flags |= Opcodes.ACC_PRIVATE; break; case PROTECTED: flags |= Opcodes.ACC_PROTECTED; break; case PUBLIC: flags |= Opcodes.ACC_PUBLIC; break; case STATIC: flags |= Opcodes.ACC_STATIC; break; } } return flags; } @Override public Object visitVariable(final VariableTree vt, Object p) { String typeName = vt.getType().toString(); String typePath = scopeStack.peek().resolveName(vt.getType().toString(), false); String typeDescriptor = scopeStack.peek().resolveName(vt.getType().toString(), true); String name = vt.getName().toString(); int flags = getFlags(vt.getModifiers().getFlags()); FieldNode fieldNode = new FieldNode(flags, name, typeDescriptor, null, null); ClassNode cls = classNodeStack.peek(); if (cls.fields == null) { cls.fields = new ArrayList<FieldNode>(); } cls.fields.add(fieldNode); return super.visitVariable(vt, p); } String generateMethodDescriptor(MethodTree mt) { StringBuilder sb = new StringBuilder(); sb.append("("); for (VariableTree v : mt.getParameters()) { String type = scopeStack.peek().resolveName(v.getType().toString(), true); sb.append(type); } sb.append(")"); String returnType = scopeStack.peek().resolveName(mt.getReturnType().toString(), true); sb.append(returnType); return sb.toString(); } @Override public Object visitMethod(final MethodTree mt, Object p) { MethodNode m = new MethodNode(); int flags = getFlags(mt.getModifiers().getFlags()); m.access = flags; m.desc = generateMethodDescriptor(mt); m.name = mt.getName().toString(); ClassNode cls = classNodeStack.peek(); if (cls.methods == null) { cls.methods = new ArrayList<MethodNode>(); } cls.methods.add(m); return mt; } }; scanner.scan(asts, null); }
From source file:com.alibaba.hotswap.processor.front.FieldNodeHolderVisitor.java
License:Open Source License
@Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (!HotswapRuntime.getClassInitialized(className)) { classMeta.putFieldMeta(access, name, desc, signature, value); }//from w w w.ja v a 2 s.c om FieldNode fn = new FieldNode(access, name, desc, signature, value); fieldNodes.add(fn); return fn; }
From source file:com.facebook.swift.codec.internal.compiler.byteCode.FieldDefinition.java
License:Apache License
public FieldNode getFieldNode() { return new FieldNode(toAccessModifier(access), name, type.getType(), type.getGenericSignature(), null); }
From source file:com.github.antag99.retinazer.weaver.SystemProcessor.java
License:Open Source License
private void processMethod(MethodNode methodNode) { InsnList insns = methodNode.instructions; // Filter out debugging nodes/labels int count = 0; int maxCount = insns.size(); AbstractInsnNode[] nodes = new AbstractInsnNode[maxCount]; for (AbstractInsnNode node = insns.getFirst(); node != null; node = node.getNext()) if (node.getOpcode() > 0) nodes[count++] = node;// ww w .j a va2 s . c o m // Find mapper get() calls and create an own flyweight instance for each for (int i = 0; i <= count - 4; i++) { if (!(nodes[i + 0] instanceof VarInsnNode)) continue; if (!(nodes[i + 1] instanceof FieldInsnNode)) continue; if (!(nodes[i + 2] instanceof VarInsnNode)) continue; if (!(nodes[i + 3] instanceof MethodInsnNode)) continue; VarInsnNode loadThis = (VarInsnNode) nodes[i + 0]; FieldInsnNode getField = (FieldInsnNode) nodes[i + 1]; VarInsnNode loadEntity = (VarInsnNode) nodes[i + 2]; MethodInsnNode getMethod = (MethodInsnNode) nodes[i + 3]; if (loadThis.var != 0 || loadThis.getOpcode() != ALOAD) continue; if (!getField.owner.equals(metadata.internalName) || !getField.desc.equals("L" + WeaverConstants.MAPPER_NAME + ";") || !metadata.mappersByName.containsKey(getField.name)) continue; if (loadEntity.getOpcode() != ILOAD) continue; if (!getMethod.owner.equals(WeaverConstants.MAPPER_NAME) || !getMethod.desc.equals("(I)L" + WeaverConstants.COMPONENT_NAME + ";") || !getMethod.name.equals("get")) continue; SystemMapper mapper = metadata.mappersByName.get(getField.name); // Add field to hold the flyweight String fieldName = "flyweight$" + flyweightFields.size(); String fieldDesc = mapper.componentType.getDescriptor(); FieldNode fieldNode = new FieldNode(ACC_PRIVATE, fieldName, fieldDesc, null, null); fieldNode.visitAnnotation("Lcom/github/antag99/retinazer/SkipWire;", true); FlyweightField flyweightField = new FlyweightField(); flyweightField.fieldNode = fieldNode; flyweightField.mapper = mapper; flyweightFields.add(flyweightField); // Rewrite access to use the flyweight getField.owner = metadata.internalName; getField.name = fieldName; getField.desc = fieldDesc; insns.insert(getField, new InsnNode(DUP)); insns.insert(loadEntity, new FieldInsnNode(PUTFIELD, mapper.componentType.getInternalName(), WeaverConstants.INDEX_FIELD_NAME, WeaverConstants.INDEX_FIELD_DESC)); insns.remove(getMethod); } }
From source file:com.github.fge.grappa.transform.process.CachingGenerator.java
License:Open Source License
private void generateGetFromCache(CodeBlock block) { Type[] paramTypes = Type.getArgumentTypes(method.desc); cacheFieldName = findUnusedCacheFieldName(); // if we have no parameters we use a simple Rule field as cache, // otherwise a HashMap String cacheFieldDesc = paramTypes.length == 0 ? CodegenUtils.ci(Rule.class) : CodegenUtils.ci(HashMap.class); FieldNode field = new FieldNode(ACC_PRIVATE, cacheFieldName, cacheFieldDesc, null, null); classNode.fields.add(field);/*from www . j a va 2s . c om*/ block.aload(0).getfield(classNode.name, cacheFieldName, cacheFieldDesc); if (paramTypes.length == 0) return; // if we have no parameters we are done // generate: if (<cache> == null) <cache> = new HashMap<Object, Rule>(); LabelNode alreadyInitialized = new LabelNode(); block.dup().ifnonnull(alreadyInitialized).pop().aload(0).newobj(CodegenUtils.p(HashMap.class)).dup_x1() .dup().invokespecial(CodegenUtils.p(HashMap.class), "<init>", CodegenUtils.sig(void.class)) .putfield(classNode.name, cacheFieldName, cacheFieldDesc).label(alreadyInitialized); // if we have more than one parameter or the parameter is an array we // have to wrap with our Arguments class since we need to unroll all // inner arrays and apply custom hashCode(...) and equals(...) // implementations if (paramTypes.length > 1 || paramTypes[0].getSort() == Type.ARRAY) { // generate: push new Arguments(new Object[] {<params>}) block.newobj(CodegenUtils.p(CacheArguments.class)).dup(); generatePushNewParameterObjectArray(block, paramTypes); block.invokespecial(CodegenUtils.p(CacheArguments.class), "<init>", CodegenUtils.sig(void.class, Object[].class)); } else { generatePushParameterAsObject(block, paramTypes, 0); } // generate: <hashMap>.get(...) block.dup().astore(method.maxLocals).invokevirtual(CodegenUtils.p(HashMap.class), "get", CodegenUtils.sig(Object.class, Object.class)); }
From source file:com.github.fge.grappa.transform.process.InstructionGroupPreparer.java
License:Apache License
private static void extractFields(InstructionGroup group) { List<FieldNode> fields = group.getFields(); VarInsnNode insn;//from w ww. j a v a 2 s .c o m for (InstructionGraphNode node : group.getNodes()) { if (!node.isXLoad()) continue; insn = (VarInsnNode) node.getInstruction(); // check whether we already have a field for the var with this index int index; for (index = 0; index < fields.size(); index++) if (fields.get(index).access == insn.var) break; // if we don't, create a new field for the var if (index == fields.size()) { /* * TODO: fix hack below * * CAUTION, HACK!: for brevity we reuse the access field and * the value field of the FieldNode for keeping track of the * original var index as well as the FieldNodes Type * (respectively) so we need to make sure that we correct * for this when the field is actually written */ Type type = node.getResultValue().getType(); fields.add(new FieldNode(insn.var, "field$" + index, type.getDescriptor(), null, type)); } // normalize the instruction so instruction groups that are // identical except for the variable indices are still mapped to // the same group class (name) insn.var = index; } }
From source file:com.googlecode.ddom.weaver.mixin.MixinInfoBuilder.java
License:Apache License
@Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { FieldNode field = new FieldNode(access, name, desc, signature, value); fields.add(field);/*from w w w .ja v a 2s.c om*/ return field; }
From source file:com.lodgon.parboiled.transform.CachingGenerator.java
License:Open Source License
@SuppressWarnings({ "unchecked" })
private void generateGetFromCache() {
Type[] paramTypes = Type.getArgumentTypes(method.desc);
cacheFieldName = findUnusedCacheFieldName();
// if we have no parameters we use a simple Rule field as cache, otherwise a HashMap
String cacheFieldDesc = paramTypes.length == 0 ? Types.RULE_DESC : "Ljava/util/HashMap;";
classNode.fields.add(new FieldNode(ACC_PRIVATE, cacheFieldName, cacheFieldDesc, null, null));
// stack:/*from ww w. ja v a2s. c o m*/
insert(new VarInsnNode(ALOAD, 0));
// stack: <this>
insert(new FieldInsnNode(GETFIELD, classNode.name, cacheFieldName, cacheFieldDesc));
// stack: <cache>
if (paramTypes.length == 0)
return; // if we have no parameters we are done
// generate: if (<cache> == null) <cache> = new HashMap<Object, Rule>();
// stack: <hashMap>
insert(new InsnNode(DUP));
// stack: <hashMap> :: <hashMap>
LabelNode alreadyInitialized = new LabelNode();
insert(new JumpInsnNode(IFNONNULL, alreadyInitialized));
// stack: <null>
insert(new InsnNode(POP));
// stack:
insert(new VarInsnNode(ALOAD, 0));
// stack: <this>
insert(new TypeInsnNode(NEW, "java/util/HashMap"));
// stack: <this> :: <hashMap>
insert(new InsnNode(DUP_X1));
// stack: <hashMap> :: <this> :: <hashMap>
insert(new InsnNode(DUP));
// stack: <hashMap> :: <this> :: <hashMap> :: <hashMap>
insert(new MethodInsnNode(INVOKESPECIAL, "java/util/HashMap", "<init>", "()V"));
// stack: <hashMap> :: <this> :: <hashMap>
insert(new FieldInsnNode(PUTFIELD, classNode.name, cacheFieldName, cacheFieldDesc));
// stack: <hashMap>
insert(alreadyInitialized);
// stack: <hashMap>
// if we have more than one parameter or the parameter is an array we have to wrap with our Arguments class
// since we need to unroll all inner arrays and apply custom hashCode(...) and equals(...) implementations
if (paramTypes.length > 1 || paramTypes[0].getSort() == Type.ARRAY) {
// generate: push new Arguments(new Object[] {<params>})
String arguments = Type.getInternalName(Arguments.class);
// stack: <hashMap>
insert(new TypeInsnNode(NEW, arguments));
// stack: <hashMap> :: <arguments>
insert(new InsnNode(DUP));
// stack: <hashMap> :: <arguments> :: <arguments>
generatePushNewParameterObjectArray(paramTypes);
// stack: <hashMap> :: <arguments> :: <arguments> :: <array>
insert(new MethodInsnNode(INVOKESPECIAL, arguments, "<init>", "([Ljava/lang/Object;)V"));
// stack: <hashMap> :: <arguments>
} else {
// stack: <hashMap>
generatePushParameterAsObject(paramTypes, 0);
// stack: <hashMap> :: <param>
}
// generate: <hashMap>.get(...)
// stack: <hashMap> :: <mapKey>
insert(new InsnNode(DUP));
// stack: <hashMap> :: <mapKey> :: <mapKey>
insert(new VarInsnNode(ASTORE, method.maxLocals));
// stack: <hashMap> :: <mapKey>
insert(new MethodInsnNode(INVOKEVIRTUAL, "java/util/HashMap", "get",
"(Ljava/lang/Object;)Ljava/lang/Object;"));
// stack: <object>
insert(new TypeInsnNode(CHECKCAST, Types.RULE.getInternalName()));
// stack: <rule>
}
From source file:com.lodgon.parboiled.transform.InstructionGroupPreparer.java
License:Apache License
private void extractFields(InstructionGroup group) { List<FieldNode> fields = group.getFields(); for (InstructionGraphNode node : group.getNodes()) { if (node.isXLoad()) { VarInsnNode insn = (VarInsnNode) node.getInstruction(); // check whether we already have a field for the var with this index int index; for (index = 0; index < fields.size(); index++) { if (fields.get(index).access == insn.var) break; }// w w w .j a v a 2s . co m // if we don't, create a new field for the var if (index == fields.size()) { // CAUTION, HACK!: for brevity we reuse the access field and the value field of the FieldNode // for keeping track of the original var index as well as the FieldNodes Type (respectively) // so we need to make sure that we correct for this when the field is actually written Type type = node.getResultValue().getType(); fields.add(new FieldNode(insn.var, "field$" + index, type.getDescriptor(), null, type)); } // normalize the instruction so instruction groups that are identical except for the variable // indexes are still mapped to the same group class (name) insn.var = index; } } }