proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/graph/ClassVertex.java
ClassVertex
equals
class ClassVertex<G extends WorkspaceGraph> extends Vertex<ClassReader> { protected final G graph; private ClassReader clazz; /** * Constructs a class vertex from the containing graph and class reader. * * @param graph * The containing graph. * @param clazz * The vertex data. */ public ClassVertex(G graph, ClassReader clazz) { this.clazz = clazz; this.graph = graph; } /** * @return Name of class stored by the vertex. */ public String getClassName() { return clazz.getClassName(); } @Override public ClassReader getData() { return clazz; } @Override public void setData(ClassReader clazz) { this.clazz = clazz; } @Override public int hashCode() { return getData().getClassName().hashCode(); } @Override public boolean equals(Object other) {<FILL_FUNCTION_BODY>} @Override public String toString() { return getClassName(); } // ============================== UTILITY =================================== // /** * @param names * Stream of names of classes. * * @return Mapped stream where names are replaced with instances. * If a name has no instance mapping, it is discarded. */ protected Stream<ClassReader> getReadersFromNames(Stream<String> names) { return names.map(name -> { // Try loading from workspace ClassReader reader = graph.getWorkspace().getClassReader(name); if(reader != null) return reader; // Try loading from runtime return ClassUtil.fromRuntime(name); }).filter(Objects::nonNull); } }
if(other == null) throw new IllegalStateException("ClassVertex should not be compared to null"); if(this == other) return true; if(other instanceof ClassVertex) { ClassVertex otherVertex = (ClassVertex) other; return getData().getClassName().equals(otherVertex.getData().getClassName()); } return false;
457
96
553
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public Stream<Vertex<ClassReader>> getAllDirectedChildren(boolean) ,public Stream<Vertex<ClassReader>> getAllDirectedParents(boolean) ,public Stream<Vertex<ClassReader>> getAllLeaves() ,public Stream<Vertex<ClassReader>> getAllRoots() ,public Stream<Edge<ClassReader>> getApplicableEdges(boolean) ,public abstract ClassReader getData() ,public Stream<Vertex<ClassReader>> getDirectedChildren() ,public Stream<DirectedEdge<ClassReader>> getDirectedEdges(boolean) ,public Stream<Vertex<ClassReader>> getDirectedParents() ,public abstract Set<Edge<ClassReader>> getEdges() ,public Stream<Edge<ClassReader>> getUndirectedEdges() ,public abstract int hashCode() ,public boolean isLeaf() ,public boolean isRoot() ,public abstract void setData(ClassReader) <variables>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/graph/DepthFirstSearch.java
DepthFirstSearch
find
class DepthFirstSearch<T> implements Search<T> { private final Set<Vertex<T>> visted = new HashSet<>(); @Override public Set<Vertex<T>> visited() { return visted; } @Override public SearchResult<T> find(Vertex<T> vertex, Vertex<T> target) { return find(vertex, target, new ArrayList<>()); } private SearchResult<T> find(Vertex<T> vertex, Vertex<T> target, List<Vertex<T>> path) {<FILL_FUNCTION_BODY>} /** * @param vertex * Analyzed vertex. * * @return {@code true} if the search should continue using the given vertex's edges. {@code * false} to ignore this vertex's edges. */ protected boolean shouldSkip(Vertex<T> vertex) { return visited().contains(vertex); } /** * Called when the given vertex is visited. * * @param currentPath * Current path. * @param vertex * Vertex visted. */ protected void onVisit(List<Vertex<T>> currentPath, Vertex<T> vertex) { visited().add(vertex); } /** * @param vertex * Vertex to fetch edges from. * * @return Directed edges of the given vertex where the vertex is the parent. */ protected Stream<Edge<T>> edges(Vertex<T> vertex) { return vertex.getApplicableEdges(true); } /** * @param path * Path visited to complete the search. * * @return Result wrapper of the path. */ protected SearchResult<T> createResult(List<Vertex<T>> path) { return new SearchResult<>(path); } }
// Verify parameters if (vertex == null) throw new IllegalArgumentException("Cannot search with a null initial vertex!"); if (target == null) throw new IllegalArgumentException("Cannot search with a null target vertex!"); // Skip already visited vertices if(shouldSkip(vertex)) return null; // Mark as visited onVisit(path, vertex); // Update path path.add(vertex); // Check for match if(vertex.equals(target)) return createResult(path); // Iterate over edges Optional<SearchResult<T>> res = edges(vertex) .map(edge -> find(edge.getOther(vertex), target, new ArrayList<>(path))) .filter(Objects::nonNull) .findFirst(); // Result found? return res.orElse(null);
465
216
681
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/graph/Vertex.java
Vertex
getDirectedEdges
class Vertex<T> { /** * @return Contained data. */ public abstract T getData(); /** * @param data * New data to contain. */ public abstract void setData(T data); /** * @return Hash of {@link #getData() data}. */ public abstract int hashCode(); /** * @param other * Other item to check. * * @return {@code true} if this vertex's {@link #getData() data} matches the given object. */ public abstract boolean equals(Object other); /** * @return Collection of edges connected to this vertex. */ public abstract Set<Edge<T>> getEdges(); /** * @return Edges that are not directed. */ public Stream<Edge<T>> getUndirectedEdges() { return getEdges().stream() .filter(e -> !(e instanceof DirectedEdge)); } /** * @param isParent * Flag for if the current vertex is the parent in the directed edge relation. * * @return Edges where the current vertex is a parent or is a child depending on the given flag. */ public Stream<DirectedEdge<T>> getDirectedEdges(boolean isParent) {<FILL_FUNCTION_BODY>} /** * @return Vertices that are direct descendants of this vertex in a directed graph. */ public Stream<Vertex<T>> getDirectedChildren() { return getDirectedEdges(true) .map(DirectedEdge::getChild); } /** * @return Vertices that are direct descendants of this vertex in a directed graph. */ public Stream<Vertex<T>> getDirectedParents() { return getDirectedEdges(false) .map(DirectedEdge::getParent); } /** * @param includeSelf * Flag for if the current vertex is to be included in the results. * * @return Vertices that are descendants of this vertex in a directed graph. */ public Stream<Vertex<T>> getAllDirectedChildren(boolean includeSelf) { return includeSelf ? Stream.concat(Stream.of(this), getAllDirectedChildren()) : getAllDirectedChildren(); } /** * @return Vertices that are descendants of this vertex in a directed graph. */ private Stream<Vertex<T>> getAllDirectedChildren() { return Stream.concat(getDirectedChildren(), getDirectedChildren().flatMap(Vertex::getAllDirectedChildren)); } /** * @param includeSelf * Flag for if the current vertex is to be included in the results. * * @return Vertices that this vertex inherits from in a directed graph. */ public Stream<Vertex<T>> getAllDirectedParents(boolean includeSelf) { return includeSelf ? Stream.concat(Stream.of(this), getAllDirectedParents()) : getAllDirectedParents(); } /** * @return Vertices that this vertex inherits from in a directed graph. */ private Stream<Vertex<T>> getAllDirectedParents() { return Stream.concat(getDirectedParents(), getDirectedParents().flatMap(Vertex::getAllDirectedParents)); } /** * @param isParent * Flag for if the current vertex is the parent in directed edge relations. * * @return Edges where the relation is undirected, or if directed that the current vertex is a * parent or is a child depending on the given flag. */ public Stream<Edge<T>> getApplicableEdges(boolean isParent) { return Stream.concat(getUndirectedEdges(), getDirectedEdges(isParent)); } /** * @return {@code true} if the vertex has no directed parent edges. */ public boolean isRoot() { return getDirectedParents().count() == 0; } /** * @return {@code true} if the vertex has no directed children edges. */ public boolean isLeaf() { return getDirectedChildren().count() == 0; } /** * @return {@code this} if the current vertex is a root. Otherwise a set of roots in the graph * this vertex resides in. */ public Stream<Vertex<T>> getAllRoots() { return getAllDirectedParents(true).filter(Vertex::isRoot); } /** * @return {@code this} if the current vertex is a leaf. Otherwise a set of leaves in the graph * this vertex resides in. */ public Stream<Vertex<T>> getAllLeaves() { return getAllDirectedChildren(true).filter(Vertex::isLeaf); } }
return getEdges().stream() .filter(e -> e instanceof DirectedEdge) .map(e -> (DirectedEdge<T>) e) .filter(di -> isParent ? equals(di.getParent()) : equals(di.getChild()));
1,207
70
1,277
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/graph/flow/FlowReference.java
FlowReference
equals
class FlowReference { private final FlowVertex vertex; private final String name; private final String desc; /** * Constructs a method call reference for flow graphing. * * @param vertex * Vertex of the class containing the called method. * @param name * Name of the method called. * @param desc * Descriptor of the method called. */ public FlowReference(FlowVertex vertex, String name, String desc) { this.vertex = vertex; this.name = name; this.desc = desc; } /** * @return Vertex of the class containing the called method. */ public FlowVertex getVertex() { return vertex; } /** * @return Name of the method called. */ public String getName() { return name; } /** * @return Descriptor of the method called. */ public String getDesc() { return desc; } @Override public String toString() { return vertex.getData().getClassName() + "." + name + desc; } @Override public int hashCode() { return Objects.hash(vertex.getData().getClassName(), name, desc); } @Override public boolean equals(Object other) {<FILL_FUNCTION_BODY>} }
if (this == other) return true; if (other instanceof FlowReference) { FlowReference frOther = (FlowReference) other; return vertex.equals(frOther.vertex) && name.equals(frOther.name) && desc.equals(frOther.desc); } return false;
337
86
423
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/graph/inheritance/ClassHierarchyBuilder.java
ClassHierarchyBuilder
equals
class ClassHierarchyBuilder extends ClassDfsSearch implements ExhaustiveSearch<HierarchyVertex, ClassReader> { /** * Constructs a class hierarchy builder. */ public ClassHierarchyBuilder() { this(ClassDfsSearch.Type.ALL); } /** * Constructs a class hierarchy builder. * * @param type * Allowed edge type. */ public ClassHierarchyBuilder(ClassDfsSearch.Type type) { super(type); } @Override public Vertex<ClassReader> dummy() { return new HierarchyVertex(null, new ClassReader(DUMMY_CLASS_BYTECODE)) { @Override public Set<Edge<ClassReader>> getEdges() { return Collections.emptySet(); } @Override public int hashCode() { return -1; } @Override public boolean equals(Object other) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "[[Dummy]]"; } }; } }
if(other instanceof HierarchyVertex) return hashCode() == other.hashCode(); return this == other;
282
33
315
<methods>public void <init>(me.coley.recaf.graph.ClassDfsSearch.Type) <variables>private final non-sealed me.coley.recaf.graph.ClassDfsSearch.Type edgeType
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/graph/inheritance/HierarchyVertex.java
HierarchyVertex
getEdges
class HierarchyVertex extends ClassVertex<HierarchyGraph> { /** * Constructs a hierarchy vertex from the containing hierarchy and class reader. * * @param graph * The containing hierarchy. * @param clazz * The vertex data. */ public HierarchyVertex(HierarchyGraph graph, ClassReader clazz) { super(graph, clazz); } @Override public Set<Edge<ClassReader>> getEdges() {<FILL_FUNCTION_BODY>} }
// Get names of parents/children Stream<String> parents = graph.getParents(getData().getClassName()); Stream<String> children = graph.getDescendants(getData().getClassName()); // Get values of parents/children Stream<ClassReader> parentValues = getReadersFromNames(parents); Stream<ClassReader> childrenValues = getReadersFromNames(children); // Get edges of parents/children Stream<Edge<ClassReader>> parentEdges = parentValues.map(node -> { HierarchyVertex other = graph.getVertex(node.getClassName()); if(other == null) { other = new HierarchyVertex(graph, node); } return new DirectedEdge<>(other, HierarchyVertex.this); }); Stream<Edge<ClassReader>> childrenEdges = childrenValues.map(node -> { HierarchyVertex other = graph.getVertex(node.getClassName()); return new DirectedEdge<>(HierarchyVertex.this, other); }); // Concat edges and return as set. return Stream.concat(parentEdges, childrenEdges).collect(Collectors.toSet());
132
302
434
<methods>public void <init>(me.coley.recaf.graph.inheritance.HierarchyGraph, ClassReader) ,public boolean equals(java.lang.Object) ,public java.lang.String getClassName() ,public ClassReader getData() ,public int hashCode() ,public void setData(ClassReader) ,public java.lang.String toString() <variables>private ClassReader clazz,protected final non-sealed me.coley.recaf.graph.inheritance.HierarchyGraph graph
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/metadata/Comments.java
Comments
parse
class Comments { public static final String TYPE = "Lme/coley/recaf/metadata/InsnComment;"; public static final String KEY_PREFIX = "At_"; private final Map<Integer, String> indexToComment = new TreeMap<>(); /** * Create an empty comments handler. */ public Comments() { } /** * Create a comments handler that populates existing entries from the given method. * * @param method * Method with comments. */ public Comments(MethodNode method) { parse(method); } private void parse(MethodNode method) {<FILL_FUNCTION_BODY>} /** * Adds a comment at the current instruction offset. * * @param index * Method instruction index to insert the comment at. * @param comment * Comment string to add. */ public void addComment(int index, String comment) { String existing = indexToComment.get(index); if (existing != null) { comment = existing + "\n" + comment; } indexToComment.put(index, comment); } /** * Write comments to the method. * * @param method * Method to write to. */ public void applyTo(MethodNode method) { if (method.visibleAnnotations == null) method.visibleAnnotations = new ArrayList<>(); // Remove old comments removeComments(method); // Add new comments indexToComment.forEach((index, comment) -> { AnnotationNode commentNode = new AnnotationNode(Comments.TYPE); commentNode.visit(Comments.KEY_PREFIX + index, comment); method.visibleAnnotations.add(commentNode); }); } /** * @param offset * Instruction offset. * * @return Comment at offset. */ public String get(int offset) { return indexToComment.get(offset); } /** * Removes comments from the given method. * * @param method * Method that may contain comments. */ public static void removeComments(MethodNode method) { if (method.visibleAnnotations == null) return; method.visibleAnnotations.removeIf(node -> node.desc.equals(Comments.TYPE)); } }
if (method.visibleAnnotations == null) return; List<AnnotationNode> invalidAnnos = new ArrayList<>(); for (AnnotationNode anno : method.visibleAnnotations) { if (anno.desc.equals(Comments.TYPE) && anno.values.size() % 2 == 0) { for (int i = 0; i < anno.values.size(); i += 2) { Object keyInfo = anno.values.get(i); Object comment = anno.values.get(i + 1); // Skip malformed comments. boolean validTypes = keyInfo instanceof String && comment instanceof String; if (!validTypes || keyInfo.toString().length() <= KEY_PREFIX.length()) { invalidAnnos.add(anno); continue; } String key = ((String)keyInfo).substring(Comments.KEY_PREFIX.length()); if (key.matches("\\d+")) indexToComment.put(Integer.parseInt(key), (String) comment); } } } // Prune invalid annos method.visibleAnnotations.removeIf(invalidAnnos::contains);
606
297
903
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/MethodAnalyzer.java
MethodAnalyzer
createTypeResolver
class MethodAnalyzer extends SimAnalyzer { /** * Create method analyzer. * * @param interpreter * Interpreter to use. */ public MethodAnalyzer(SimInterpreter interpreter) { super(interpreter); } @Override protected TypeChecker createTypeChecker() { return (parent, child) -> getGraph() .getAllParents(child.getInternalName()) .anyMatch(n -> n != null && n.equals(parent.getInternalName())); } @Override protected TypeResolver createTypeResolver() {<FILL_FUNCTION_BODY>} private static HierarchyGraph getGraph() { return Recaf.getCurrentWorkspace().getHierarchyGraph(); } }
return new TypeResolver() { @Override public Type common(Type type1, Type type2) { String common = getGraph().getCommon(type1.getInternalName(), type2.getInternalName()); if (common != null) return Type.getObjectType(common); return TypeUtil.OBJECT_TYPE; } @Override public Type commonException(Type type1, Type type2) { String common = getGraph().getCommon(type1.getInternalName(), type2.getInternalName()); if (common != null) return Type.getObjectType(common); return TypeUtil.EXCEPTION_TYPE; } };
198
173
371
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/Parse.java
Parse
parse
class Parse { private static final Map<Integer, Supplier<AbstractParser>> insnTypeToParser = new HashMap<>(); static { Parse.insnTypeToParser.put(AbstractInsnNode.LINE, LineInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.INSN, InsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.INT_INSN, IntInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.VAR_INSN, VarInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.TYPE_INSN, TypeInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.IINC_INSN, IincInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.MULTIANEWARRAY_INSN, MultiArrayParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.FIELD_INSN, FieldInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.METHOD_INSN, MethodInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.LDC_INSN, LdcInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.JUMP_INSN, JumpInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.TABLESWITCH_INSN, TableSwitchInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.LOOKUPSWITCH_INSN, LookupSwitchInsnParser::new); Parse.insnTypeToParser.put(AbstractInsnNode.INVOKE_DYNAMIC_INSN, InvokeDynamicParser::new); } /** * @param text * Text to visit. * * @return Parse result wrapper of generated AST. */ public static ParseResult<RootAST> parse(String text) {<FILL_FUNCTION_BODY>} /** * @param lineNo * Line the token appears on. * @param token * First token on line. * * @return Parser associated with the token. * * @throws ASTParseException * When the token is not valid. */ public static AbstractParser<?> getParser(int lineNo, String token) throws ASTParseException { if (token.startsWith("//")) return new CommentParser(); if(token.endsWith(":")) return new LabelParser(); if (token.equals("DEFINE")) return new DefinitionParser(); if (token.equals("VALUE")) return new DefaultValueParser(); if(token.equals("THROWS")) return new ThrowsParser(); if(token.equals("TRY")) return new TryCatchParser(); if(token.equals("ALIAS")) return new AliasDeclarationParser(); if(token.equals("SIGNATURE")) return new SignatureParser(); if(token.equals("EXPR")) return new ExpressionParser(); // Get opcode from token (opcode?) then get the opcode's group // Lookup group's parser try { int opcode = OpcodeUtil.nameToOpcode(token); int type = OpcodeUtil.opcodeToType(opcode); return getInsnParser(type); } catch(NullPointerException ex) { // Thrown when the opcode name isn't a real opcode throw new ASTParseException(lineNo, "Not a real opcode: " + token); } } /** * @param type * Instruction type, see {@link AbstractInsnNode#getType()}. * * @return Parser for type. */ public static AbstractParser<?> getInsnParser(int type) { Supplier<AbstractParser> supplier = insnTypeToParser.get(type); if(supplier == null) return null; return supplier.get(); } }
List<ASTParseException> problems = new ArrayList<>(); RootAST root = new RootAST(); int lineNo = 0; String[] lines = text.split("[\n\r]"); // Collect aliases List<AliasAST> aliases = new ArrayList<>(); for(String line : lines) { lineNo++; // Skip empty lines if(line.trim().isEmpty()) continue; // Check for alias String token = line.trim().split("\\s")[0].toUpperCase(); try { if (token.equals("ALIAS")) { // Why? Because we want to support aliases-in-aliases when they // are defined in order. String lineCopy = line; for (AliasAST alias : aliases) lineCopy = lineCopy.replace("${" + alias.getName().getName() + "}", alias.getValue().getValue()); // Parse alias aliases.add((AliasAST) getParser(lineNo, token).visit(lineNo, lineCopy)); } } catch(ClassCastException | ASTParseException ex) { /* ignored, we will collect the error on the second pass */ } } // Parse again lineNo = 0; for(String line : lines) { lineNo++; // Skip empty lines String trim = line.trim(); if(trim.isEmpty()) continue; // Determine parse action from starting token String token = trim.split("\\s")[0].toUpperCase(); try { AbstractParser parser = getParser(lineNo, token); if(parser == null) throw new ASTParseException(lineNo, "Unknown identifier: " + token); // Apply aliases String lineCopy = line; for (AliasAST alias : aliases) lineCopy = lineCopy.replace("${" + alias.getName().getName() + "}", alias.getValue().getValue()); // Parse and add to root AST ast = parser.visit(lineNo, lineCopy); root.addChild(ast); } catch(ASTParseException ex) { problems.add(ex); } } return new ParseResult<>(root, problems);
1,069
589
1,658
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/AST.java
AST
search
class AST { private final int line; private final int start; private final List<AST> children = new ArrayList<>(); private AST parent; private AST next; private AST prev; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. */ public AST(int line, int start) { this.line = line; this.start = start; } /** * @return Line number this node is written on<i>(1-indexed)</i>. */ public int getLine() { return line; } /** * @return Offset from line start this node starts at. */ public int getStart() { return start; } /** * @return Children nodes. */ public List<AST> getChildren() { return children; } /** * @param ast * Child node to add. */ public void addChild(AST ast) { // Link parent/child getChildren().add(ast); ast.setParent(this); // Link prev/next for children if (getChildren().size() > 1) { AST prev = getChildren().get(getChildren().size() - 2); prev.setNext(ast); ast.setPrev(prev); } } /** * @param type * Class of AST node type. * @param <T> * Type of AST node. * * @return List of AST nodes of the given class type in the AST. */ public <T> List<T> search(Class<T> type) { return search(type, new ArrayList<>()); } @SuppressWarnings("unchecked") private <T> List<T> search(Class<T> type, List<T> list) {<FILL_FUNCTION_BODY>} /** * @return Parent node. */ public AST getParent() { return parent; } /** * @param parent * Parent node. */ public void setParent(AST parent) { this.parent = parent; } /** * @return Adjacent node. */ public AST getNext() { return next; } /** * @param next * Adjacent node. */ public void setNext(AST next) { this.next = next; } /** * @return Adjacent node. */ public AST getPrev() { return prev; } /** * @param prev * Adjacent node. */ public void setPrev(AST prev) { this.prev = prev; } /** * @return String representation of this node. */ public abstract String print(); @Override public String toString() { return print(); } }
for(AST ast : getChildren()) if(type.isAssignableFrom(ast.getClass())) list.add((T) ast); else ast.search(type, list); return list;
764
60
824
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/AliasAST.java
AliasAST
print
class AliasAST extends InsnAST { private final NameAST name; private final StringAST value; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param opcode * Opcode AST. * @param name * Alias name AST. * @param value * Increment value AST. */ public AliasAST(int line, int start, OpcodeAST opcode, NameAST name, StringAST value) { super(line, start, opcode); this.name = name; this.value = value; addChild(name); addChild(value); } /** * @return Alias name AST. */ public NameAST getName() { return name; } /** * @return Increment value AST. */ public StringAST getValue() { return value; } @Override public String print() {<FILL_FUNCTION_BODY>} @Override public void compile(MethodCompilation compilation) throws AssemblerException { // No-op: this is not compilable. } }
return getOpcode().print() + " " + name.print() + " " + value.print();
319
28
347
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.OpcodeAST) ,public void compile(me.coley.recaf.parse.bytecode.MethodCompilation) throws me.coley.recaf.parse.bytecode.exception.AssemblerException,public me.coley.recaf.parse.bytecode.ast.OpcodeAST getOpcode() ,public java.lang.String print() <variables>private final non-sealed me.coley.recaf.parse.bytecode.ast.OpcodeAST opcode
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/FieldDefinitionAST.java
FieldDefinitionAST
print
class FieldDefinitionAST extends DefinitionAST { private final DescAST type; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param name * Field name. * @param type * Field return type. */ public FieldDefinitionAST(int line, int start, NameAST name, DescAST type) { super(line, start, name); this.type = type; } /** * @return Field access modifier nodes. */ public List<DefinitionModifierAST> getModifiers() { return modifiers; } /** * @param modifier * Modifier node to add. */ public void addModifier(DefinitionModifierAST modifier) { modifiers.add(modifier); addChild(modifier); } /** * @return Field type. */ public DescAST getType() { return type; } @Override public String getDescriptor() { return getType().getDesc(); } @Override public String print() {<FILL_FUNCTION_BODY>} }
String modifiersStr = getModifiers().stream().map(AST::print).collect(joining(" ")); return "DEFINE " + modifiersStr + " " + getType().print() + " " + getName().print();
307
58
365
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.NameAST) ,public abstract java.lang.String getDescriptor() ,public me.coley.recaf.parse.bytecode.ast.NameAST getName() <variables>protected final List<me.coley.recaf.parse.bytecode.ast.DefinitionModifierAST> modifiers,protected final non-sealed me.coley.recaf.parse.bytecode.ast.NameAST name
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/HandleAST.java
HandleAST
print
class HandleAST extends AST { private final TagAST tag; private final TypeAST owner; private final NameAST name; private final DescAST desc; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param tag * Handle tag AST. * @param owner * Handle reference owner type AST. * @param name * Handle reference name AST. * @param desc * Handle reference descriptor AST. */ public HandleAST(int line, int start, TagAST tag, TypeAST owner, NameAST name, DescAST desc) { super(line, start); this.tag = tag; this.owner = owner; this.name = name; this.desc = desc; addChild(tag); addChild(owner); addChild(name); addChild(desc); } /** * @return Handle tag AST. */ public TagAST getTag() { return tag; } /** * @return Type AST of reference owner. */ public TypeAST getOwner() { return owner; } /** * @return Name AST of reference name. */ public NameAST getName() { return name; } /** * @return Desc AST of reference descriptor. */ public DescAST getDesc() { return desc; } @Override public String print() {<FILL_FUNCTION_BODY>} /** * @return ASM handle from AST data. */ public Handle compile() { return new Handle(getTag().getTag(), getOwner().getUnescapedType(), getName().getUnescapedName(), getDesc().getUnescapedDesc(), getTag().getTag() == Opcodes.H_INVOKEINTERFACE); } }
String split = getTag().isMethod() ? "" : " "; return "handle[" + getTag().print() + " " + owner.print() + "." + name.print() + split + desc.print() + "]";
495
61
556
<methods>public void <init>(int, int) ,public void addChild(me.coley.recaf.parse.bytecode.ast.AST) ,public List<me.coley.recaf.parse.bytecode.ast.AST> getChildren() ,public int getLine() ,public me.coley.recaf.parse.bytecode.ast.AST getNext() ,public me.coley.recaf.parse.bytecode.ast.AST getParent() ,public me.coley.recaf.parse.bytecode.ast.AST getPrev() ,public int getStart() ,public abstract java.lang.String print() ,public List<T> search(Class<T>) ,public void setNext(me.coley.recaf.parse.bytecode.ast.AST) ,public void setParent(me.coley.recaf.parse.bytecode.ast.AST) ,public void setPrev(me.coley.recaf.parse.bytecode.ast.AST) ,public java.lang.String toString() <variables>private final List<me.coley.recaf.parse.bytecode.ast.AST> children,private final non-sealed int line,private me.coley.recaf.parse.bytecode.ast.AST next,private me.coley.recaf.parse.bytecode.ast.AST parent,private me.coley.recaf.parse.bytecode.ast.AST prev,private final non-sealed int start
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/IincInsnAST.java
IincInsnAST
print
class IincInsnAST extends InsnAST implements VariableReference { private final NameAST variable; private final NumberAST incr; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param opcode * Opcode AST. * @param variable * Variable name AST. * @param incr * Increment value AST. */ public IincInsnAST(int line, int start, OpcodeAST opcode, NameAST variable, NumberAST incr) { super(line, start, opcode); this.variable = variable; this.incr = incr; addChild(variable); addChild(incr); } @Override public NameAST getVariableName() { return variable; } @Override public int getVariableSort() { return Type.INT; } /** * @return Increment value AST. */ public NumberAST getIncrement() { return incr; } @Override public String print() {<FILL_FUNCTION_BODY>} @Override public void compile(MethodCompilation compilation) throws AssemblerException { compilation.addInstruction(new IincInsnNode(getVariableIndex(compilation.getVariableNameCache()), getIncrement().getIntValue()), this); } }
return getOpcode().print() + " " + variable.print() + " " + incr.print();
373
29
402
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.OpcodeAST) ,public void compile(me.coley.recaf.parse.bytecode.MethodCompilation) throws me.coley.recaf.parse.bytecode.exception.AssemblerException,public me.coley.recaf.parse.bytecode.ast.OpcodeAST getOpcode() ,public java.lang.String print() <variables>private final non-sealed me.coley.recaf.parse.bytecode.ast.OpcodeAST opcode
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/JumpInsnAST.java
JumpInsnAST
compile
class JumpInsnAST extends InsnAST implements FlowController { private final NameAST label; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param opcode * Opcode AST. * @param label * Label name AST. */ public JumpInsnAST(int line, int start, OpcodeAST opcode, NameAST label) { super(line, start, opcode); this.label = label; addChild(label); } /** * @return Label name AST. */ public NameAST getLabel() { return label; } @Override public String print() { return getOpcode().print() + " " + label.print(); } @Override public void compile(MethodCompilation compilation) throws AssemblerException {<FILL_FUNCTION_BODY>} @Override public List<String> targets() { return Collections.singletonList(getLabel().getName()); } }
LabelNode label = compilation.getLabel(getLabel().getName()); if (label == null) throw new AssemblerException("Specified destination label '" + getLabel().getName() + "' does not exist", getLine()); compilation.addInstruction(new JumpInsnNode(getOpcode().getOpcode(), label), this);
280
91
371
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.OpcodeAST) ,public void compile(me.coley.recaf.parse.bytecode.MethodCompilation) throws me.coley.recaf.parse.bytecode.exception.AssemblerException,public me.coley.recaf.parse.bytecode.ast.OpcodeAST getOpcode() ,public java.lang.String print() <variables>private final non-sealed me.coley.recaf.parse.bytecode.ast.OpcodeAST opcode
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/LineInsnAST.java
LineInsnAST
print
class LineInsnAST extends InsnAST { private final NameAST label; private final NumberAST lineNumber; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param opcode * Opcode AST. * @param label * Label name AST. * @param lineNumber * Line number AST. */ public LineInsnAST(int line, int start, OpcodeAST opcode, NameAST label, NumberAST lineNumber) { super(line, start, opcode); this.label = label; this.lineNumber = lineNumber; addChild(label); addChild(lineNumber); } /** * @return Label name AST. */ public NameAST getLabel() { return label; } /** * @return Line number AST. */ public NumberAST getLineNumber() { return lineNumber; } @Override public String print() {<FILL_FUNCTION_BODY>} @Override public void compile(MethodCompilation compilation) throws AssemblerException { compilation.addInstruction(new LineNumberNode(getLineNumber().getIntValue(), compilation.getLabel(getLabel().getName())), this); } }
return getOpcode().print() + " " + label.print() + " " + lineNumber.print();
350
29
379
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.OpcodeAST) ,public void compile(me.coley.recaf.parse.bytecode.MethodCompilation) throws me.coley.recaf.parse.bytecode.exception.AssemblerException,public me.coley.recaf.parse.bytecode.ast.OpcodeAST getOpcode() ,public java.lang.String print() <variables>private final non-sealed me.coley.recaf.parse.bytecode.ast.OpcodeAST opcode
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/LookupSwitchInsnAST.java
LookupSwitchInsnAST
compile
class LookupSwitchInsnAST extends InsnAST implements FlowController { private final Map<NumberAST, NameAST> mapping; private final NameAST dfltLabel; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param opcode * Opcode AST. * @param mapping * Mapping of values to labels. * @param dfltLabel * Default fallback label AST. */ public LookupSwitchInsnAST(int line, int start, OpcodeAST opcode, Map<NumberAST, NameAST> mapping, NameAST dfltLabel) { super(line, start, opcode); this.mapping = mapping; this.dfltLabel = dfltLabel; mapping.forEach((k, v) -> { addChild(k); addChild(v); }); addChild(dfltLabel); } /** * @return Mapping of values to labels. */ public Map<NumberAST, NameAST> getMapping() { return mapping; } /** * @return Default fallback label AST. */ public NameAST getDfltLabel() { return dfltLabel; } @Override public String print() { String map = mapping.entrySet().stream() .map(e -> e.getKey().print() + "=" + e.getValue().print()) .sorted() .collect(Collectors.joining(", ")); return getOpcode().print() + " mapping[" + map + "]" + " default[" + dfltLabel.print() + "]"; } @Override public void compile(MethodCompilation compilation) throws AssemblerException {<FILL_FUNCTION_BODY>} @Override public List<String> targets() { List<String> targets = new ArrayList<>(); targets.add(getDfltLabel().getName()); targets.addAll(getMapping().values().stream().map(NameAST::getName).collect(Collectors.toList())); return targets; } }
int[] keys = new int[mapping.size()]; LabelNode[] lbls = new LabelNode[mapping.size()]; int i = 0; for(Map.Entry<NumberAST, NameAST> entry : mapping.entrySet()) { int key = entry.getKey().getIntValue(); LabelNode lbl = compilation.getLabel(entry.getValue().getName()); keys[i] = key; lbls[i] = lbl; i++; } LabelNode dflt = compilation.getLabel(getDfltLabel().getName()); compilation.addInstruction(new LookupSwitchInsnNode(dflt, keys, lbls), this);
562
184
746
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.OpcodeAST) ,public void compile(me.coley.recaf.parse.bytecode.MethodCompilation) throws me.coley.recaf.parse.bytecode.exception.AssemblerException,public me.coley.recaf.parse.bytecode.ast.OpcodeAST getOpcode() ,public java.lang.String print() <variables>private final non-sealed me.coley.recaf.parse.bytecode.ast.OpcodeAST opcode
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/MethodDefinitionAST.java
MethodDefinitionAST
getDescriptor
class MethodDefinitionAST extends DefinitionAST { private final List<DefinitionArgAST> arguments = new ArrayList<>(); private final DescAST retType; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param name * Method name. * @param retType * Method return type. */ public MethodDefinitionAST(int line, int start, NameAST name, DescAST retType) { super(line, start, name); this.retType = retType; } /** * @return Method access modifier nodes. */ public List<DefinitionModifierAST> getModifiers() { return modifiers; } /** * @param modifier * Modifier node to add. */ public void addModifier(DefinitionModifierAST modifier) { modifiers.add(modifier); addChild(modifier); } /** * @return Combined modifiers. */ public int getModifierMask() { return search(DefinitionModifierAST.class).stream() .mapToInt(DefinitionModifierAST::getValue) .reduce(0, (a, b) -> a | b); } /** * @return Method parameter nodes. */ public List<DefinitionArgAST> getArguments() { return arguments; } /** * @param arg * Argument node to add. */ public void addArgument(DefinitionArgAST arg) { arguments.add(arg); addChild(arg); } /** * @return Method return type. */ public DescAST getReturnType() { return retType; } /** * @return Combined method descriptor of argument children and return type child. */ @Override public String getDescriptor() {<FILL_FUNCTION_BODY>} @Override public String print() { String modifiersStr = getModifiers().stream().map(AST::print).collect(joining(" ")); String argumentsStr = getArguments().stream().map(AST::print).collect(joining(", ")); String ret = getReturnType().print(); return "DEFINE " + modifiersStr + " " + getName().print() + "(" + argumentsStr + ")" + ret; } }
String args = search(DefinitionArgAST.class).stream() .map(ast -> ast.getDesc().getDesc()) .collect(Collectors.joining()); String end = getReturnType().getDesc(); return "(" + args + ")" + end;
599
70
669
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.NameAST) ,public abstract java.lang.String getDescriptor() ,public me.coley.recaf.parse.bytecode.ast.NameAST getName() <variables>protected final List<me.coley.recaf.parse.bytecode.ast.DefinitionModifierAST> modifiers,protected final non-sealed me.coley.recaf.parse.bytecode.ast.NameAST name
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/NumberAST.java
NumberAST
print
class NumberAST extends AST { private final Number value; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param value * Numeric value. */ public NumberAST(int line, int start, Number value) { super(line, start); this.value = value; } /** * @return value. */ public Number getValue() { return value; } /** * @return value as int. */ public int getIntValue() { return value.intValue(); } /** * @return value as long. */ public long getLongValue() { return value.longValue(); } /** * @return value as float. */ public float getFloatValue() { return value.floatValue(); } /** * @return value as double. */ public double getDoubleValue() { return value.doubleValue(); } @Override public String print() {<FILL_FUNCTION_BODY>} }
String val = String.valueOf(value); String suffix = ""; if (value instanceof Long) suffix = "L"; else if (value instanceof Float) suffix = "F"; return val + suffix;
291
64
355
<methods>public void <init>(int, int) ,public void addChild(me.coley.recaf.parse.bytecode.ast.AST) ,public List<me.coley.recaf.parse.bytecode.ast.AST> getChildren() ,public int getLine() ,public me.coley.recaf.parse.bytecode.ast.AST getNext() ,public me.coley.recaf.parse.bytecode.ast.AST getParent() ,public me.coley.recaf.parse.bytecode.ast.AST getPrev() ,public int getStart() ,public abstract java.lang.String print() ,public List<T> search(Class<T>) ,public void setNext(me.coley.recaf.parse.bytecode.ast.AST) ,public void setParent(me.coley.recaf.parse.bytecode.ast.AST) ,public void setPrev(me.coley.recaf.parse.bytecode.ast.AST) ,public java.lang.String toString() <variables>private final List<me.coley.recaf.parse.bytecode.ast.AST> children,private final non-sealed int line,private me.coley.recaf.parse.bytecode.ast.AST next,private me.coley.recaf.parse.bytecode.ast.AST parent,private me.coley.recaf.parse.bytecode.ast.AST prev,private final non-sealed int start
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/TableSwitchInsnAST.java
TableSwitchInsnAST
print
class TableSwitchInsnAST extends InsnAST implements FlowController { private final NumberAST rangeMin; private final NumberAST rangeMax; private final List<NameAST> labels; private final NameAST dfltLabel; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param opcode * Opcode AST. * @param rangeMin * Min switch range value AST. * @param rangeMax * Max switch range value AST. * @param labels * Labels (AST) that link to value in range. * @param dfltLabel * Default fallback label AST. */ public TableSwitchInsnAST(int line, int start, OpcodeAST opcode, NumberAST rangeMin, NumberAST rangeMax, List<NameAST> labels, NameAST dfltLabel) { super(line, start, opcode); this.rangeMin = rangeMin; this.rangeMax = rangeMax; this.labels = labels; this.dfltLabel = dfltLabel; addChild(rangeMin); addChild(rangeMax); labels.forEach(this::addChild); addChild(dfltLabel); } /** * @return Min switch range value AST. */ public NumberAST getRangeMin() { return rangeMin; } /** * @return Max switch range value AST. */ public NumberAST getRangeMax() { return rangeMax; } /** * @return Labels (AST) that link to value in range. */ public List<NameAST> getLabels() { return labels; } /** * @return Default fallback label AST. */ public NameAST getDfltLabel() { return dfltLabel; } @Override public String print() {<FILL_FUNCTION_BODY>} @Override public void compile(MethodCompilation compilation) throws AssemblerException { LabelNode[] lbls = getLabels().stream() .map(ast -> compilation.getLabel(ast.getName())) .toArray(LabelNode[]::new); LabelNode dflt = compilation.getLabel(getDfltLabel().getName()); compilation.addInstruction(new TableSwitchInsnNode(getRangeMin().getIntValue(), getRangeMax().getIntValue(), dflt, lbls), this); } @Override public List<String> targets() { List<String> targets = new ArrayList<>(); targets.add(getDfltLabel().getName()); targets.addAll(getLabels().stream().map(NameAST::getName).collect(Collectors.toList())); return targets; } }
String lbls = labels.stream() .map(NameAST::print) .collect(Collectors.joining(", ")); return getOpcode().print() + " range[" + rangeMin.print() +":" + rangeMax.print() + "]" + " offsets[" + lbls + "]" + " default[" + dfltLabel.print() + "]";
732
102
834
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.OpcodeAST) ,public void compile(me.coley.recaf.parse.bytecode.MethodCompilation) throws me.coley.recaf.parse.bytecode.exception.AssemblerException,public me.coley.recaf.parse.bytecode.ast.OpcodeAST getOpcode() ,public java.lang.String print() <variables>private final non-sealed me.coley.recaf.parse.bytecode.ast.OpcodeAST opcode
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/TagAST.java
TagAST
isField
class TagAST extends AST { private final String name; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param name * Tag display name. */ public TagAST(int line, int start, String name) { super(line, start); this.name = name; } /** * @return Opcode display name. */ public String getName() { return name; } /** * @return Opcode value. */ public int getTag() { return OpcodeUtil.nameToTag(getName()); } /** * @return {@code true} if the tag is for a field reference. */ public boolean isField() {<FILL_FUNCTION_BODY>} /** * @return {@code true} if the tag is for a method reference. */ public boolean isMethod() { return !isField(); } @Override public String print() { return name; } }
int tag = getTag(); return tag >= Opcodes.H_GETFIELD && tag <= Opcodes.H_PUTSTATIC;
277
37
314
<methods>public void <init>(int, int) ,public void addChild(me.coley.recaf.parse.bytecode.ast.AST) ,public List<me.coley.recaf.parse.bytecode.ast.AST> getChildren() ,public int getLine() ,public me.coley.recaf.parse.bytecode.ast.AST getNext() ,public me.coley.recaf.parse.bytecode.ast.AST getParent() ,public me.coley.recaf.parse.bytecode.ast.AST getPrev() ,public int getStart() ,public abstract java.lang.String print() ,public List<T> search(Class<T>) ,public void setNext(me.coley.recaf.parse.bytecode.ast.AST) ,public void setParent(me.coley.recaf.parse.bytecode.ast.AST) ,public void setPrev(me.coley.recaf.parse.bytecode.ast.AST) ,public java.lang.String toString() <variables>private final List<me.coley.recaf.parse.bytecode.ast.AST> children,private final non-sealed int line,private me.coley.recaf.parse.bytecode.ast.AST next,private me.coley.recaf.parse.bytecode.ast.AST parent,private me.coley.recaf.parse.bytecode.ast.AST prev,private final non-sealed int start
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/TryCatchAST.java
TryCatchAST
print
class TryCatchAST extends AST { private final TypeAST type; private final NameAST lblStart; private final NameAST lblEnd; private final NameAST lblHandler; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param lblStart * Try block starting label. * @param lblEnd * Try block ending label. * @param type * Type of exception caught. * @param lblHandler * Catch block starting label. */ public TryCatchAST(int line, int start, NameAST lblStart, NameAST lblEnd, TypeAST type, NameAST lblHandler) { super(line, start); this.lblStart = lblStart; this.lblEnd = lblEnd; this.type = type; this.lblHandler = lblHandler; addChild(lblStart); addChild(lblEnd); addChild(type); addChild(lblHandler); } /** * @return Type of exception caught. */ public TypeAST getType() { return type; } /** * @return Try block starting label name AST. */ public NameAST getLblStart() { return lblStart; } /** * @return Try block ending label name AST. */ public NameAST getLblEnd() { return lblEnd; } /** * @return Catch block starting label name AST. */ public NameAST getLblHandler() { return lblHandler; } @Override public String print() {<FILL_FUNCTION_BODY>} }
return "TRY " + lblStart.getName() + " " + lblEnd.getName() + " CATCH(" + type.getType() + ") " + lblHandler.getName();
462
49
511
<methods>public void <init>(int, int) ,public void addChild(me.coley.recaf.parse.bytecode.ast.AST) ,public List<me.coley.recaf.parse.bytecode.ast.AST> getChildren() ,public int getLine() ,public me.coley.recaf.parse.bytecode.ast.AST getNext() ,public me.coley.recaf.parse.bytecode.ast.AST getParent() ,public me.coley.recaf.parse.bytecode.ast.AST getPrev() ,public int getStart() ,public abstract java.lang.String print() ,public List<T> search(Class<T>) ,public void setNext(me.coley.recaf.parse.bytecode.ast.AST) ,public void setParent(me.coley.recaf.parse.bytecode.ast.AST) ,public void setPrev(me.coley.recaf.parse.bytecode.ast.AST) ,public java.lang.String toString() <variables>private final List<me.coley.recaf.parse.bytecode.ast.AST> children,private final non-sealed int line,private me.coley.recaf.parse.bytecode.ast.AST next,private me.coley.recaf.parse.bytecode.ast.AST parent,private me.coley.recaf.parse.bytecode.ast.AST prev,private final non-sealed int start
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/ast/VarInsnAST.java
VarInsnAST
getVariableSort
class VarInsnAST extends InsnAST implements VariableReference { private final NameAST variable; /** * @param line * Line number this node is written on. * @param start * Offset from line start this node starts at. * @param opcode * Opcode AST. * @param variable * Variable name AST. */ public VarInsnAST(int line, int start, OpcodeAST opcode, NameAST variable) { super(line, start, opcode); this.variable = variable; addChild(variable); } @Override public NameAST getVariableName() { return variable; } @Override public int getVariableSort() {<FILL_FUNCTION_BODY>} @Override public String print() { return getOpcode().print() + " " + variable.print(); } @Override public void compile(MethodCompilation compilation) throws AssemblerException { compilation.addInstruction(new VarInsnNode(getOpcode().getOpcode(), getVariableIndex(compilation.getVariableNameCache())), this); } }
int opcode = getOpcode().getOpcode(); switch (opcode) { case Opcodes.ILOAD: case Opcodes.ISTORE: return Type.INT; case Opcodes.LLOAD: case Opcodes.LSTORE: return Type.LONG; case Opcodes.DLOAD: case Opcodes.DSTORE: return Type.DOUBLE; case Opcodes.FLOAD: case Opcodes.FSTORE: return Type.FLOAT; case Opcodes.ALOAD: case Opcodes.ASTORE: default: return Type.OBJECT; }
294
185
479
<methods>public void <init>(int, int, me.coley.recaf.parse.bytecode.ast.OpcodeAST) ,public void compile(me.coley.recaf.parse.bytecode.MethodCompilation) throws me.coley.recaf.parse.bytecode.exception.AssemblerException,public me.coley.recaf.parse.bytecode.ast.OpcodeAST getOpcode() ,public java.lang.String print() <variables>private final non-sealed me.coley.recaf.parse.bytecode.ast.OpcodeAST opcode
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/AliasDeclarationParser.java
AliasDeclarationParser
visit
class AliasDeclarationParser extends AbstractParser<AliasAST> { @Override public AliasAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // name NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(trim[1])); NameAST name = nameParser.visit(lineNo, trim[1]); // content StringParser stringParser = new StringParser(); stringParser.setOffset(line.indexOf("\"")); StringAST content = stringParser.visit(lineNo, line.substring(line.indexOf("\""))); return new AliasAST(lineNo, start, op, name, content); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for var instruction"); }
52
287
339
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.AliasAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/ArgParser.java
ArgParser
visit
class ArgParser extends AbstractParser<DefinitionArgAST> { @Override public DefinitionArgAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); if (!trim.matches(".+\\s+.+")) throw new IllegalStateException(); int start = line.indexOf(trim); String[] split = trim.split("\\s+"); String typeStr = split[0]; String nameStr = split[1]; DescParser descParser = new DescParser(); descParser.setOffset(start); DescAST descAST = descParser.visit(lineNo, typeStr); NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(nameStr)); NameAST nameAST = nameParser.visit(lineNo, nameStr); return new DefinitionArgAST(lineNo, getOffset() + start, descAST, nameAST); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for arg, expected \"<type> <name>\""); }
50
245
295
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.DefinitionArgAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/CommentParser.java
CommentParser
visit
class CommentParser extends AbstractParser<CommentAST> { @Override public CommentAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); String content = trim.substring(2); int start = line.indexOf(trim); return new CommentAST(lineNo, start, content); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for comment, expected \"//\" at beginning"); }
48
94
142
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.CommentAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/DefaultValueParser.java
DefaultValueParser
visit
class DefaultValueParser extends AbstractParser<DefaultValueAST> { private static final String PREFIX = "VALUE "; @Override public DefaultValueAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { return Collections.emptyList(); } }
try { int offset = PREFIX.length(); String content = line.substring(offset).trim(); AST ast = null; if(content.contains("\"")) { // String StringParser parser = new StringParser(); parser.setOffset(offset); ast = parser.visit(lineNo, content); } else if(content.contains("[") || content.contains(";")) { // Type DescParser parser = new DescParser(); parser.setOffset(offset); ast = parser.visit(lineNo, content); } else if(content.endsWith("F") || content.endsWith("f")) { // Float FloatParser parser = new FloatParser(); parser.setOffset(offset); ast = parser.visit(lineNo, content); } else if(content.endsWith("L") || content.endsWith("l") || content.endsWith("J") || content.endsWith("j")) { // Long LongParser parser = new LongParser(); parser.setOffset(offset); ast = parser.visit(lineNo, content); } else if(content.contains(".")) { // Double DoubleParser parser = new DoubleParser(); parser.setOffset(offset); ast = parser.visit(lineNo, content); } else { // Integer IntParser parser = new IntParser(); parser.setOffset(offset); ast = parser.visit(lineNo, content); } return new DefaultValueAST(lineNo, 0, ast); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for LDC"); }
100
447
547
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.DefaultValueAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/DefinitionParser.java
DefinitionParser
visit
class DefinitionParser extends AbstractParser<DefinitionAST> { public static final String DEFINE = "DEFINE"; public static final int DEFINE_LEN = (DEFINE + " ").length(); @Override public DefinitionAST visit(int lineNo, String text) throws ASTParseException {<FILL_FUNCTION_BODY>} }
if (text.contains("(")) return new MethodDefinitionParser().visit(lineNo, text); else return new FieldDefinitionParser().visit(lineNo, text);
83
48
131
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.DefinitionAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/DescParser.java
DescParser
visit
class DescParser extends AbstractParser<DescAST> { @Override public DescAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { if(text.contains("(")) return Collections.emptyList(); // Suggest field types return AutoCompleteUtil.descriptorName(text.trim()); } private static boolean validate(String token) { // Void check if(token.equals("V")) return true; // Ensure type is not an array Type type = Type.getType(token); while(type.getSort() == Type.ARRAY) type = type.getElementType(); // Check for primitives if(type.getSort() < Type.ARRAY) return true; // Verify L...; pattern // - getDescriptor doesn't modify the original element type (vs getInternalName) String desc = type.getDescriptor(); return desc.startsWith("L") && desc.endsWith(";"); } }
try { String trim = line.trim(); trim = EscapeUtil.unescape(trim); // Verify if(trim.contains("(")) { Type type = Type.getMethodType(trim); if(!validate(type.getReturnType().getDescriptor())) throw new ASTParseException(lineNo, "Invalid method return type " + type.getReturnType().getDescriptor()); for(Type arg : type.getArgumentTypes()) if(!validate(arg.getDescriptor())) throw new ASTParseException(lineNo, "Invalid method arg type " + arg.getDescriptor()); } else { if(!validate(trim)) throw new ASTParseException(lineNo, "Invalid field descriptor: " + trim); } // Create AST int start = line.indexOf(trim); return new DescAST(lineNo, getOffset() + start, trim); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for descriptor: " + ex.getMessage()); }
284
270
554
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.DescAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/DoubleParser.java
DoubleParser
visit
class DoubleParser extends AbstractParser<NumberAST> { @Override public NumberAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); // Check standard numbers, then exponential form form if that fails int start = line.indexOf(trim); if(!trim.matches("-?[.\\d]+[Dd]?")) if (trim.equals("Infinity")) return new NumberAST(lineNo, getOffset() + start, Double.POSITIVE_INFINITY); else if (trim.equals("-Infinity")) return new NumberAST(lineNo, getOffset() + start, Double.NEGATIVE_INFINITY); else if (trim.equals("NaN")) return new NumberAST(lineNo, getOffset() + start, Double.NaN); else if (!trim.matches("-?[\\d.]+(?:[eE]-?\\d+)?[dD]?")) throw new ASTParseException(lineNo, "Invalid double: " + trim); return new NumberAST(lineNo, getOffset() + start, Double.valueOf(trim)); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for number"); }
48
289
337
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.NumberAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/ExpressionParser.java
ExpressionParser
visit
class ExpressionParser extends AbstractParser<ExpressionAST> { private static final int EXPR_OFFSET = "EXPR ".length(); @Override public ExpressionAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { return Collections.emptyList(); } }
try { String trim = line.trim().substring(EXPR_OFFSET); int start = line.indexOf(EXPR_OFFSET); return new ExpressionAST(lineNo, start, trim); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for expression"); }
104
89
193
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.ExpressionAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/FieldDefinitionParser.java
FieldDefinitionParser
visit
class FieldDefinitionParser extends AbstractParser<FieldDefinitionAST> { @Override public FieldDefinitionAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // If we have a space (after the FIELD part) and have not started writing the descriptor // then we can suggest access modifiers or the type if (text.contains(" ") && !text.contains(";")) { String[] parts = text.split("\\s+"); String last = parts[parts.length - 1]; if(last.charAt(0) == 'L') { // Complete type return AutoCompleteUtil.descriptorName(last); } else { // Complete modifier return new ModifierParser().suggest(lastParse, last); } } return Collections.emptyList(); } }
try { String trim = line.trim(); // Fetch the name first, even though it appears after the access modifiers String[] split = trim.split("\\s+"); if(split.length < 2) throw new ASTParseException(lineNo, "Bad format for FIELD, missing arguments"); String name = split[split.length - 1]; String desc = split[split.length - 2]; int nameStart = trim.lastIndexOf(name); int descStart = trim.lastIndexOf(" " + desc); int start = line.indexOf(trim); NameParser nameParser = new NameParser(this); nameParser.setOffset(nameStart); NameAST nameAST = nameParser.visit(lineNo, name); DescParser descParser = new DescParser(); descParser.setOffset(descStart); DescAST descAST = descParser.visit(lineNo, desc); FieldDefinitionAST def = new FieldDefinitionAST(lineNo, start, nameAST, descAST); def.addChild(nameAST); // Parse access modifiers if (descStart > DefinitionParser.DEFINE_LEN) { String modifiersSection = trim.substring(DefinitionParser.DEFINE_LEN, descStart); while(!modifiersSection.trim().isEmpty()) { // Get current modifier start = line.indexOf(modifiersSection); int space = modifiersSection.indexOf(' '); int end = space; if(end == -1) end = modifiersSection.length(); String modStr = modifiersSection.substring(0, end); // Parse modifier ModifierParser modifierParser = new ModifierParser(); modifierParser.setOffset(start); DefinitionModifierAST modifierAST = modifierParser.visit(lineNo, modStr); def.addModifier(modifierAST); // cut section to fit next modifier if(space == -1) break; else modifiersSection = modifiersSection.substring(modStr.length()).trim(); } } def.addChild(descAST); return def; } catch(IndexOutOfBoundsException ex) { throw new ASTParseException(ex, lineNo, "Bad format for FIELD"); }
234
592
826
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.FieldDefinitionAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/FieldInsnParser.java
FieldInsnParser
visit
class FieldInsnParser extends AbstractParser<FieldInsnAST> { @Override public FieldInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // DEFINE owner.name desc int space = text.indexOf(' '); if (space >= 0) { String sub = text.substring(space + 1); int dot = sub.indexOf('.'); if (dot == -1) return new TypeParser().suggest(lastParse, sub); return AutoCompleteUtil.field(sub); } return Collections.emptyList(); } }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 3) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // owner & name String typeAndName = trim[1]; int dot = typeAndName.indexOf('.'); if (dot == -1) throw new ASTParseException(lineNo, "Format error: expecting '<Owner>.<Name> <Desc>'" + " - missing '.'"); String typeS = typeAndName.substring(0, dot); String nameS = typeAndName.substring(dot + 1); // owner TypeParser typeParser = new TypeParser(); typeParser.setOffset(line.indexOf(typeAndName)); TypeAST owner = typeParser.visit(lineNo, typeS); // name NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf('.')); NameAST name = nameParser.visit(lineNo, nameS); // desc DescParser descParser = new DescParser(); descParser.setOffset(line.lastIndexOf(trim[2])); DescAST desc = descParser.visit(lineNo, trim[2]); return new FieldInsnAST(lineNo, start, op, owner, name, desc); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for field instruction"); }
181
447
628
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.FieldInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/FloatParser.java
FloatParser
visit
class FloatParser extends AbstractParser<NumberAST> { @Override public NumberAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); int start = line.indexOf(trim); if(!trim.matches("-?[.\\d]+[Ff]?")) if (trim.matches("Infinity[Ff]")) return new NumberAST(lineNo, getOffset() + start, Float.POSITIVE_INFINITY); else if (trim.matches("-Infinity[Ff]")) return new NumberAST(lineNo, getOffset() + start, Float.NEGATIVE_INFINITY); else if (trim.matches("NaN[Ff]")) return new NumberAST(lineNo, getOffset() + start, Float.NaN); else if (!trim.matches("-?[\\d.]+(?:[eE]-?\\d+)?[Ff]?")) throw new ASTParseException(lineNo, "Invalid float: " + trim); return new NumberAST(lineNo, getOffset() + start, Float.valueOf(trim)); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for number"); }
49
294
343
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.NumberAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/HandleParser.java
HandleParser
suggest
class HandleParser extends AbstractParser<HandleAST> { // This handle is what's used 90% of the time so lets just provide a helpful alias. public static final Handle DEFAULT_HANDLE = new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;" + "Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)" + "Ljava/lang/invoke/CallSite;", false); public static final String DEFAULT_HANDLE_ALIAS = "H_META"; @Override public HandleAST visit(int lineNo, String line) throws ASTParseException { try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op TagParser opParser = new TagParser(); opParser.setOffset(line.indexOf(trim[0])); TagAST tag = opParser.visit(lineNo, trim[0]); // owner & name & desc String data = trim[1]; int dot = data.indexOf('.'); if (dot == -1) throw new ASTParseException(lineNo, "Format error: Missing '.' after owner type"); // Determine split index, for field or method type int descSplit = data.indexOf('('); if(descSplit < dot) { descSplit = data.indexOf(' '); if(descSplit < dot) throw new ASTParseException(lineNo, "Format error: Missing valid handle descriptor"); } String typeS = data.substring(0, dot); String nameS = data.substring(dot + 1, descSplit); String descS = data.substring(descSplit); // owner TypeParser typeParser = new TypeParser(); typeParser.setOffset(line.indexOf(data)); TypeAST owner = typeParser.visit(lineNo, typeS); // name NameParser nameParser = new NameParser(this); nameParser.setOffset(dot + 1); NameAST name = nameParser.visit(lineNo, nameS); // desc DescParser descParser = new DescParser(); descParser.setOffset(descSplit); DescAST desc = descParser.visit(lineNo, descS); return new HandleAST(lineNo, start, tag, owner, name, desc); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for handle "); } } @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) {<FILL_FUNCTION_BODY>} }
// TAG owner.name+desc int space = text.indexOf(' '); if (space > 0) { String sub = text.substring(space + 1); int dot = sub.indexOf('.'); if (dot == -1) return new TypeParser().suggest(lastParse, sub); // Determine if we need to suggest fields or methods based on tag boolean isMethod = false; try { TagParser opParser = new TagParser(); TagAST tag = opParser.visit(0, text.substring(0, space)); isMethod = tag.isMethod(); } catch(Exception ex) { /* ignored */ } if(isMethod) return AutoCompleteUtil.method(sub); else return AutoCompleteUtil.field(sub); } else // No space, so must be typing the tag. Suggest tag names. return new TagParser().suggest(lastParse, text);
752
238
990
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.HandleAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/IincInsnParser.java
IincInsnParser
suggest
class IincInsnParser extends AbstractParser<IincInsnAST> { @Override public IincInsnAST visit(int lineNo, String line) throws ASTParseException { try { String[] trim = line.trim().split("\\s+"); if (trim.length < 3) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // variable NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(trim[1])); NameAST variable = nameParser.visit(lineNo, trim[1]); // incr IntParser numParser = new IntParser(); numParser.setOffset(line.indexOf(trim[2])); NumberAST incr = numParser.visit(lineNo, trim[2]); return new IincInsnAST(lineNo, start, op, variable, incr); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for increment instruction"); } } @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) {<FILL_FUNCTION_BODY>} }
try { NameParser nameParser = new NameParser(this); String[] parts = text.trim().split("\\s+"); // last word is the 'variable' portion if(parts.length == 2) return nameParser.suggest(lastParse, parts[parts.length - 1]); } catch(Exception ex) { /* ignored */ } return Collections.emptyList();
371
101
472
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.IincInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/InsnParser.java
InsnParser
visit
class InsnParser extends AbstractParser<InsnAST> { @Override public InsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim)); OpcodeAST op = opParser.visit(lineNo, trim); int start = line.indexOf(trim); return new InsnAST(lineNo, start, op); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for basic instruction"); }
51
125
176
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.InsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/IntInsnParser.java
IntInsnParser
visit
class IntInsnParser extends AbstractParser<IntInsnAST> { @Override public IntInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // TODO: For NEWARRAY, using types instead of magic number values would be intuitive String valueStr = trim[1]; int valueStrStart = line.indexOf(valueStr); NumberAST num = null; if (op.getOpcode() == Opcodes.NEWARRAY) { // Type to value DescParser descParser = new DescParser(); descParser.setOffset(line.indexOf(valueStr)); DescAST desc = descParser.visit(lineNo, valueStr); if (!TypeUtil.isPrimitiveDesc(desc.getDesc())) { throw new ASTParseException(lineNo, "Expected primitive descriptor for NEWARRAY"); } num = new NumberAST(lineNo, valueStrStart, TypeUtil.typeToNewArrayArg(Type.getType(desc.getDesc()))); } else { // Value IntParser numParser = new IntParser(); numParser.setOffset(valueStrStart); num = numParser.visit(lineNo, valueStr); } return new IntInsnAST(lineNo, start, op, num); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for int instruction"); }
54
436
490
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.IntInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/IntParser.java
IntParser
visit
class IntParser extends AbstractParser<NumberAST> { @Override public NumberAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); if(!trim.matches("-?\\d+")) throw new ASTParseException(lineNo, "Invalid integer: " + trim); int start = line.indexOf(trim); return new NumberAST(lineNo, getOffset() + start, Integer.valueOf(trim)); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for number, value not a valid int"); }
48
126
174
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.NumberAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/InvokeDynamicParser.java
InvokeDynamicParser
visit
class InvokeDynamicParser extends AbstractParser<InvokeDynamicAST> { private static String BRACKET_WRAPPING = "\\w*\\[.+]"; private static String BRACKET_WRAPPING_OR_EMPTY = "\\w*\\[.*]"; @Override public InvokeDynamicAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} /** * @param lineNo * Line number. * @param arg * Arg text. * * @return BSM arg ast value. * * @throws ASTParseException * When the arg cannot be parsed. */ private static AST parseArg(int lineNo, String arg) throws ASTParseException { AbstractParser parser = null; if(arg.contains("\"")) parser = new StringParser(); else if(arg.matches("-?\\d+")) parser = new IntParser(); else if(arg.matches("-?\\d+[LlJj]?")) parser = new LongParser(); else if(arg.matches("-?\\d+\\.\\d+[Ff]?")) parser = new FloatParser(); else if(arg.matches("-?\\d+\\.\\d+[Dd]?")) parser = new DoubleParser(); else if(arg.matches(BRACKET_WRAPPING)) { parser = new HandleParser(); arg = arg.substring(arg.indexOf('[') + 1, arg.indexOf(']')); } else parser = new DescParser(); return parser.visit(lineNo, arg); } @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // INVOKEDYNAMIC name desc handle[...] args[...] // - Can only really suggest the handle... int b1 = text.indexOf('['); int b2 = text.lastIndexOf('['); if(b1 == -1) // not at handle yet return Collections.emptyList(); else if(b2 != b1) // past handle, at args return Collections.emptyList(); else // in the handle return new HandleParser().suggest(lastParse, text.substring(b1 + 1)); } }
try { // Split here: // v v v // INVOKEDYNAMIC name desc handle[...] args[...] String[] trim = line.trim().split("\\s+(?=.*\\[(?=.*\\[))"); if (trim.length < 4) throw new ASTParseException(lineNo, "Not enough parameters"); // 0 = op // 1 = name // 2 = desc int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // name NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(trim[1])); NameAST name = nameParser.visit(lineNo, trim[1]); // desc DescParser descParser = new DescParser(); descParser.setOffset(line.indexOf(trim[2])); DescAST desc = descParser.visit(lineNo, trim[2]); // handle & args // - Split space between handle and args trim = line.substring(RegexUtil.indexOf("(?:(?<=\\s)handle|handle|\\s)\\[\\s*H_", line)) .split("(?<=\\])\\s+(?=.*\\[)"); // handle String handleS = trim[0]; if (!handleS.matches(BRACKET_WRAPPING)) throw new ASTParseException(lineNo, "Invalid handle, require wrapping in '[' and ']'"); handleS = handleS.substring(handleS.indexOf('[') + 1, handleS.indexOf(']')); HandleParser handleParser = new HandleParser(); handleParser.setOffset(line.indexOf(trim[0])); HandleAST handle = handleParser.visit(lineNo, handleS); // args String argsS = trim[1]; if (!argsS.matches(BRACKET_WRAPPING_OR_EMPTY)) throw new ASTParseException(lineNo, "Invalid args, require wrapping in '[' and ']'"); argsS = argsS.substring(argsS.indexOf('[') + 1, argsS.lastIndexOf(']')); // if the args has a string with commas, this will break... // we'll fix that whenever it happens List<AST> args = new ArrayList<>(); if (!argsS.isEmpty()) { String[] argsSplit = argsS.split(",\\s*(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)"); for(String arg : argsSplit) { AST ast = parseArg(lineNo, arg); if(ast == null) throw new ASTParseException(lineNo, "Failed parsing BSM arg: " + arg); args.add(ast); } } return new InvokeDynamicAST(lineNo, start, op, name, desc, handle, args); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for invokedynamic instruction"); }
603
844
1,447
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.InvokeDynamicAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/JumpInsnParser.java
JumpInsnParser
visit
class JumpInsnParser extends AbstractParser<JumpInsnAST> { @Override public JumpInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { if (text.contains(" ")) { String[] parts = text.split("\\s+"); return new NameParser(this).suggest(lastParse, parts[parts.length - 1]); } return Collections.emptyList(); } }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // label NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(trim[1])); NameAST label = nameParser.visit(lineNo, trim[1]); return new JumpInsnAST(lineNo, start, op, label); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for var instruction"); }
144
231
375
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.JumpInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/LabelParser.java
LabelParser
visit
class LabelParser extends AbstractParser<LabelAST> { @Override public LabelAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); String name = trim.substring(0, trim.indexOf(':')); NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(name)); NameAST ast = nameParser.visit(lineNo, name); int start = line.indexOf(trim); return new LabelAST(lineNo, start, ast); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for label, expected colon(:) at end"); }
48
147
195
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.LabelAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/LdcInsnParser.java
LdcInsnParser
visit
class LdcInsnParser extends AbstractParser<LdcInsnAST> { @Override public LdcInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // Attempt to complete content for Type values if (text.contains(" ") && !text.contains("\"")) { String[] parts = text.split("\\s+"); return new TypeParser().suggest(lastParse, parts[parts.length - 1]); } return Collections.emptyList(); } }
try { String trim = line.trim(); int ti = line.indexOf(trim); int space = line.indexOf(' '); String opS = trim.substring(0, space); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(opS)); OpcodeAST op = opParser.visit(lineNo, opS); // content String content = trim.substring(space + 1); AST ast = null; if(content.contains("\"")) { // String StringParser parser = new StringParser(); parser.setOffset(ti + space + 1); ast = parser.visit(lineNo, content); } else if(content.contains("H_") && content.contains("]")) { // Handle HandleParser parser = new HandleParser(); parser.setOffset(ti + space + 1); ast = parser.visit(lineNo, content.substring(content.indexOf('[') + 1, content.lastIndexOf(']'))); } else if(content.startsWith("(") || content.contains("[") || content.contains(";")) { // Type DescParser parser = new DescParser(); parser.setOffset(ti + space + 1); ast = parser.visit(lineNo, content); } else if(content.matches("-?(?:(?:Infinity|NaN)|-?(?:\\d+\\.\\d+))[Ff]") || content.matches("-?[\\d.]+[eE](?:-?\\d+)?[Ff]")) { // Float FloatParser parser = new FloatParser(); parser.setOffset(ti + space + 1); ast = parser.visit(lineNo, content); } else if(content.matches("-?\\d+[LlJj]")) { // Long LongParser parser = new LongParser(); parser.setOffset(ti + space + 1); ast = parser.visit(lineNo, content); } else if(content.matches("-?(?:Infinity|NaN)|-?(?:\\d+\\.\\d+[Dd]?)") || content.matches("-?[\\d.]+[eE](?:-?\\d+)?[dD]?")) { // Double DoubleParser parser = new DoubleParser(); parser.setOffset(ti + space + 1); ast = parser.visit(lineNo, content); } else { // Integer IntParser parser = new IntParser(); parser.setOffset(ti + space + 1); ast = parser.visit(lineNo, content); } return new LdcInsnAST(lineNo, ti, op, ast); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for LDC"); }
160
761
921
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.LdcInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/LineInsnParser.java
LineInsnParser
visit
class LineInsnParser extends AbstractParser<LineInsnAST> { @Override public LineInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // LINE label number if (text.contains(" ")) { String[] parts = text.split("\\s+"); // Only complete if we're on the label portion if (parts.length == 2) return new NameParser(this).suggest(lastParse, parts[parts.length - 1]); } return Collections.emptyList(); } }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 3) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // label NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(trim[1])); NameAST label = nameParser.visit(lineNo, trim[1]); // line IntParser numParser = new IntParser(); numParser.setOffset(line.indexOf(trim[2])); NumberAST lineNum = numParser.visit(lineNo, trim[2]); return new LineInsnAST(lineNo, start, op, label, lineNum); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for line-number instruction"); }
170
290
460
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.LineInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/LongParser.java
LongParser
visit
class LongParser extends AbstractParser<NumberAST> { @Override public NumberAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); if(!trim.matches("-?\\d+[LlJj]?")) if (!trim.matches("-?[\\d.]+(?:[eE]-?\\d+)?[LlJj]?")) throw new ASTParseException(lineNo, "Invalid long: " + trim); char last = trim.charAt(trim.length() - 1); if (!(last > '0' && last < '9')) trim = trim.substring(0, trim.length() - 1); int start = line.indexOf(trim); return new NumberAST(lineNo, getOffset() + start, Long.valueOf(trim)); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for number"); }
48
217
265
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.NumberAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/LookupSwitchInsnParser.java
LookupSwitchInsnParser
suggest
class LookupSwitchInsnParser extends AbstractParser<LookupSwitchInsnAST> { @Override public LookupSwitchInsnAST visit(int lineNo, String line) throws ASTParseException { try { String trim = line.trim(); String opS = RegexUtil.getFirstWord(trim); if (opS == null) throw new ASTParseException(lineNo, "Missing TABLESWITCH opcode"); int start = line.indexOf(opS); OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(start); OpcodeAST op = opParser.visit(lineNo, opS); // Collect parameters String[] data = RegexUtil.allMatches(line, "(?<=\\[).*?(?=\\])"); if (data.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); // mapping String mapS = data[0]; Map<NumberAST, NameAST> mapping = new LinkedHashMap<>(); if (!mapS.isEmpty()) { NameParser nameParser = new NameParser(this); IntParser intParser = new IntParser(); String[] mapS2 = mapS.split(",\\s*"); for (String map : mapS2) { // map: Value=Label if (!map.contains("=")) throw new ASTParseException(lineNo, "Invalid mapping format, expected: <Value>=<Label>"); nameParser.setOffset(line.indexOf(map)); intParser.setOffset(line.indexOf(map)); String[] mapKV = map.split("="); mapping.put(intParser.visit(lineNo, mapKV[0]), nameParser.visit(lineNo, mapKV[1])); } } // dflt String dfltS = data[1]; if (mapS.isEmpty()) { // Handle case where mapping is empty dfltS = trim.substring(trim.lastIndexOf('[') + 1, trim.lastIndexOf(']')); } NameParser nameParser = new NameParser(this); nameParser.setOffset(line.lastIndexOf(dfltS)); NameAST dflt = nameParser.visit(lineNo, dfltS); return new LookupSwitchInsnAST(lineNo, start, op, mapping, dflt); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for table-switch instruction"); } } @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) {<FILL_FUNCTION_BODY>} }
if (text.matches(".*[\\[=]\\w+")) { String last = RegexUtil.getLastToken("\\w+", text); return new NameParser(this).suggest(lastParse, last); } return Collections.emptyList();
691
70
761
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.LookupSwitchInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/MethodDefinitionParser.java
MethodDefinitionParser
visit
class MethodDefinitionParser extends AbstractParser<MethodDefinitionAST> { @Override public MethodDefinitionAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // If we have a space (after the DEFINE part) and have not started writing the descriptor // then we can suggest access modifiers if (text.contains(" ") && !text.contains("(")) { String[] parts = text.split("\\s+"); return new ModifierParser().suggest(lastParse, parts[parts.length - 1]); } // TODO: Arg desc suggestions return Collections.emptyList(); } }
try { String trim = line.trim(); if(!trim.matches(".+(.*).+")) throw new ASTParseException(lineNo, "Bad format for DEFINE, bad method descriptor"); // Fetch the name first, even though it appears after the access modifiers String name = trim.substring(0, trim.indexOf('(')); int nameStart = name.lastIndexOf(' ') + 1; name = name.substring(nameStart); int descStart = line.indexOf(')') + 1; String desc = line.substring(descStart); int start = line.indexOf(trim); NameParser nameParser = new NameParser(this); nameParser.setOffset(nameStart); NameAST nameAST = nameParser.visit(lineNo, name); DescParser descParser = new DescParser(); descParser.setOffset(descStart); DescAST descAST = descParser.visit(lineNo, desc); MethodDefinitionAST def = new MethodDefinitionAST(lineNo, start, nameAST, descAST); def.addChild(nameAST); // Parse access modifiers String modifiersSection = trim.substring(DefinitionParser.DEFINE_LEN, nameStart); while(!modifiersSection.trim().isEmpty()) { // Get current modifier start = line.indexOf(modifiersSection); int space = modifiersSection.indexOf(' '); int end = space; if (end == -1) end = modifiersSection.length(); String modStr = modifiersSection.substring(0, end); // Parse modifier ModifierParser modifierParser = new ModifierParser(); modifierParser.setOffset(start); DefinitionModifierAST modifierAST = modifierParser.visit(lineNo, modStr); def.addModifier(modifierAST); // cut section to fit next modifier if (space == -1) break; else modifiersSection = modifiersSection.substring(modStr.length()).trim(); } // Parse argument types String argsSection = trim.substring(trim.indexOf('(') + 1, trim.indexOf(')')); while(!argsSection.trim().isEmpty()) { // Get current arg int comma = argsSection.indexOf(','); int end = comma; if(end == -1) end = argsSection.length(); start = line.indexOf(argsSection); String argString = argsSection.substring(0, end); // Parse arg ArgParser argParser = new ArgParser(); argParser.setOffset(start); DefinitionArgAST argAST = argParser.visit(lineNo, argString); def.addArgument(argAST); // cut section to fit next arg if(comma == -1) break; else argsSection = argsSection.substring(end + 1).trim(); } def.addChild(descAST); return def; } catch(IndexOutOfBoundsException ex) { throw new ASTParseException(ex, lineNo, "Bad format for DEFINE"); }
185
810
995
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.MethodDefinitionAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/MethodInsnParser.java
MethodInsnParser
visit
class MethodInsnParser extends AbstractParser<MethodInsnAST> { @Override public MethodInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // METHOD owner.name+desc [itf] int space = text.indexOf(' '); if (space >= 0) { int secondSpace = text.indexOf(' ', space + 1); if (secondSpace >= 0) { if ("INVOKESTATIC".equals(text.substring(0, space))) { return Collections.singletonList("itf"); } else { return Collections.emptyList(); } } String sub = text.substring(space + 1); int dot = sub.indexOf('.'); if (dot == -1) return new TypeParser().suggest(lastParse, sub); return AutoCompleteUtil.method(sub); } return Collections.emptyList(); } }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // owner & name & desc String data = trim[1]; int dot = data.indexOf('.'); if (dot == -1) throw new ASTParseException(lineNo, "Format error: expecting '<Owner>.<Name><Desc>'" + " - missing '.'"); int parenthesis = data.indexOf('('); if (parenthesis < dot) throw new ASTParseException(lineNo, "Format error: Missing valid method descriptor"); String typeS = data.substring(0, dot); String nameS = data.substring(dot + 1, parenthesis); String descS = data.substring(parenthesis); // owner TypeParser typeParser = new TypeParser(); typeParser.setOffset(line.indexOf(data)); TypeAST owner = typeParser.visit(lineNo, typeS); // name NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf('.')); NameAST name = nameParser.visit(lineNo, nameS); // desc DescParser descParser = new DescParser(); descParser.setOffset(line.indexOf('(')); DescAST desc = descParser.visit(lineNo, descS); // itf ItfAST itf = null; if (op.getOpcode() == Opcodes.INVOKESTATIC) { if (trim.length > 2 && "itf".equals(trim[2])) { itf = new ItfAST(lineNo, line.indexOf("itf", desc.getStart() + desc.getDesc().length())); } } return new MethodInsnAST(lineNo, start, op, owner, name, desc, itf); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for method instruction"); }
266
596
862
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.MethodInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/ModifierParser.java
ModifierParser
visit
class ModifierParser extends AbstractParser<DefinitionModifierAST> { private static final List<String> ALLOWED_NAMES = Arrays.stream(AccessFlag.values()) .map(AccessFlag::getName) .collect(Collectors.toList()); @Override public DefinitionModifierAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { String trim = text.trim(); return ALLOWED_NAMES.stream().filter(n -> n.startsWith(trim)).collect(Collectors.toList()); } }
try { String trim = line.trim().toLowerCase(); if(!ALLOWED_NAMES.contains(trim)) throw new ASTParseException(lineNo, "Illegal method modifier '" + trim + "'"); int start = line.indexOf(trim); return new DefinitionModifierAST(lineNo, getOffset() + start, trim); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for modifier"); }
170
126
296
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.DefinitionModifierAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/MultiArrayParser.java
MultiArrayParser
suggest
class MultiArrayParser extends AbstractParser<MultiArrayInsnAST> { @Override public MultiArrayInsnAST visit(int lineNo, String line) throws ASTParseException { try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // desc DescParser descParser = new DescParser(); descParser.setOffset(line.indexOf(trim[1])); DescAST type = descParser.visit(lineNo, trim[1]); // dims IntParser numParser = new IntParser(); numParser.setOffset(line.indexOf(trim[2])); NumberAST dims = numParser.visit(lineNo, trim[2]); return new MultiArrayInsnAST(lineNo, start, op, type, dims); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for MultiANewArray instruction"); } } @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) {<FILL_FUNCTION_BODY>} }
// MULTI type number if (text.contains(" ")) { String[] parts = text.split("\\s+"); // Only complete if we're on the type portion if (parts.length == 2) return new DescParser().suggest(lastParse, parts[parts.length - 1]); } return Collections.emptyList();
370
92
462
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.MultiArrayInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/NameParser.java
NameParser
suggest
class NameParser extends AbstractParser<NameAST> { /** * Create name parser with parent context. * * @param parent * Parent parser. */ public NameParser(AbstractParser parent) { super(parent); } @Override public NameAST visit(int lineNo, String line) throws ASTParseException { try { String trim = line.trim(); if (trim.isEmpty()) throw new ASTParseException(lineNo, "Name cannot be empty!"); trim = EscapeUtil.unescape(trim); int start = line.indexOf(trim); return new NameAST(lineNo, getOffset() + start, trim); } catch (Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for name"); } } @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) {<FILL_FUNCTION_BODY>} }
// No context of last parse, can't pull names from last parsed AST // No context parent parser, unsure what to suggest if (lastParse == null || parent == null) return Collections.emptyList(); // Complete labels if we belong to a label parser boolean tableParent = parent instanceof TableSwitchInsnParser || parent instanceof LookupSwitchInsnParser; if (parent instanceof TryCatchParser || parent instanceof JumpInsnParser || parent instanceof LineInsnParser || tableParent) { return lastParse.getRoot().search(LabelAST.class).stream() .map(l -> l.getName().getName()) .filter(n -> n.startsWith(text)) .collect(Collectors.toList()); } // Complete variable names if we belong to a variable parser else if (parent instanceof VarInsnParser || parent instanceof IincInsnParser) { return lastParse.getRoot().search(NameAST.class).stream() .filter(ast -> ast.getName().startsWith(text)) .filter(ast -> ast.getParent() instanceof VarInsnAST || ast.getParent() instanceof DefinitionArgAST) .map(NameAST::getName) .distinct() .sorted() .collect(Collectors.toList()); } return Collections.emptyList();
245
331
576
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.NameAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/NumericParser.java
NumericParser
visit
class NumericParser extends AbstractParser<NumberAST> { @Override public NumberAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String content = line.trim(); NumberAST ast = null; if(content.endsWith("F") || content.endsWith("f")) { // Float FloatParser parser = new FloatParser(); ast = parser.visit(lineNo, content); } else if(content.endsWith("L") || content.endsWith("l") || content.endsWith("J") || content.endsWith("j")) { // Long LongParser parser = new LongParser(); ast = parser.visit(lineNo, content); } else if(content.contains(".")) { // Double DoubleParser parser = new DoubleParser(); ast = parser.visit(lineNo, content); } else { // Integer IntParser parser = new IntParser(); ast = parser.visit(lineNo, content); } return ast; } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for number"); }
50
268
318
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.NumberAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/OpcodeParser.java
OpcodeParser
visit
class OpcodeParser extends AbstractParser<OpcodeAST> { public static final Set<String> ALLOWED_NAMES = OpcodeUtil.getInsnNames(); @Override public OpcodeAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { String trim = text.trim(); return ALLOWED_NAMES.stream().filter(n -> n.startsWith(trim)).collect(Collectors.toList()); } }
try { String trim = line.trim().toUpperCase(); if(!ALLOWED_NAMES.contains(trim)) throw new ASTParseException(lineNo, "Illegal opcode '" + trim + "'"); int start = line.indexOf(trim); return new OpcodeAST(lineNo, getOffset() + start, trim); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for opcode"); }
146
125
271
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.OpcodeAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/SignatureParser.java
SignatureParser
suggest
class SignatureParser extends AbstractParser<SignatureAST> { @Override public SignatureAST visit(int lineNo, String line) throws ASTParseException { try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); String sig = trim[1]; // TODO: Verify signature? // - Technically you can put in garbage data in here... // Create AST int start = line.indexOf(sig); return new SignatureAST(lineNo, getOffset() + start, sig); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for descriptor"); } } @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) {<FILL_FUNCTION_BODY>} }
if(text.contains("(")) return Collections.emptyList(); // Suggest field types return AutoCompleteUtil.descriptorName(text.trim());
229
44
273
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.SignatureAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/StringParser.java
StringParser
visit
class StringParser extends AbstractParser<StringAST> { @Override public StringAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} }
try { String trim = line.trim(); if(!(trim.charAt(0) == '"' && trim.charAt(trim.length() - 1) == '"')) throw new ASTParseException(lineNo, "Invalid string: " + trim); int start = line.indexOf(trim); return new StringAST(lineNo, getOffset() + start, trim.substring(1, trim.length() - 1)); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for number"); }
48
146
194
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.StringAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/TableSwitchInsnParser.java
TableSwitchInsnParser
visit
class TableSwitchInsnParser extends AbstractParser<TableSwitchInsnAST> { @Override public TableSwitchInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { if (text.contains(" ")) { String last = RegexUtil.getLastToken("\\w+", text); return new NameParser(this).suggest(lastParse, last); } return Collections.emptyList(); } }
try { String trim = line.trim(); String opS = RegexUtil.getFirstWord(trim); if (opS == null) throw new ASTParseException(lineNo, "Missing TABLESWITCH opcode"); int start = line.indexOf(opS); OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(start); OpcodeAST op = opParser.visit(lineNo, opS); // Collect parameters String[] data = RegexUtil.allMatches(line, "(?<=\\[).*?(?=\\])"); if (data.length < 3) throw new ASTParseException(lineNo, "Not enough parameters"); // min & max String minMaxS = data[0]; if (!minMaxS.contains(":")) throw new ASTParseException(lineNo, "Bad range format, expected <MIN>:<MAX>"); int minMaxStart = line.indexOf(minMaxS); String[] minMaxS2 = minMaxS.split(":"); IntParser intParser = new IntParser(); intParser.setOffset(minMaxStart); NumberAST min = intParser.visit(lineNo, minMaxS2[0]); NumberAST max = intParser.visit(lineNo, minMaxS2[1]); // labels List<NameAST> labels = new ArrayList<>(); String labelsS = data[1]; int labelsStart = line.indexOf(labelsS); NameParser parser = new NameParser(this); String[] labelsS2 = labelsS.split(",\\s*"); for (String name : labelsS2) { parser.setOffset(labelsStart + labelsS.indexOf(name)); labels.add(parser.visit(lineNo, name)); } // dflt String dfltS = data[2]; parser.setOffset(line.lastIndexOf(dfltS)); NameAST dflt = parser.visit(lineNo, dfltS); return new TableSwitchInsnAST(lineNo, start, op, min, max, labels, dflt); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for table-switch instruction"); }
142
588
730
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.TableSwitchInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/TagParser.java
TagParser
visit
class TagParser extends AbstractParser<TagAST> { private static final Set<String> ALLOWED_NAMES = OpcodeUtil.getTagNames(); @Override public TagAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { String trim = text.trim(); return ALLOWED_NAMES.stream().filter(n -> n.startsWith(trim)).collect(Collectors.toList()); } }
try { String trim = line.trim().toUpperCase(); if(!ALLOWED_NAMES.contains(trim)) throw new ASTParseException(lineNo, "Illegal tag '" + trim + "'"); int start = line.indexOf(trim); return new TagAST(lineNo, getOffset() + start, trim); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for tag"); }
142
122
264
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.TagAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/ThrowsParser.java
ThrowsParser
visit
class ThrowsParser extends AbstractParser<ThrowsAST> { private static final int THROWS_LEN = "THROWS ".length(); @Override public ThrowsAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { if (text.length() <= THROWS_LEN) return Collections.emptyList(); return new TypeParser().suggest(lastParse, text.substring(THROWS_LEN)); } }
try { String trim = line.trim(); int start = line.indexOf(trim); // Sub-parser, set offset so it starts after THROWS's ' ', so error reporting yields // the correct character offset. TypeParser typeParser = new TypeParser(); typeParser.setOffset(start + THROWS_LEN); TypeAST type = typeParser.visit(lineNo, trim.substring(THROWS_LEN)); return new ThrowsAST(lineNo, start, type); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for THROWS"); }
147
168
315
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.ThrowsAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/TryCatchParser.java
TryCatchParser
visit
class TryCatchParser extends AbstractParser<TryCatchAST> { private static final int TRY_LEN = "TRY ".length(); @Override public TryCatchAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { // Suggest exception type int start = text.indexOf('(') + 1; int end = text.indexOf(')'); if (start > 0 && end == -1) { String type = text.substring(start).trim(); return new TypeParser().suggest(lastParse, type); } // No context of last parse, can't pull names from last parsed AST if(lastParse == null) return Collections.emptyList(); // Suggest label names try { String trim = text.trim(); NameParser nameParser = new NameParser(this); String[] parts = trim.split("\\s+"); return nameParser.suggest(lastParse, parts[parts.length - 1]); } catch(Exception ex) { return Collections.emptyList(); } } }
try { // TRY start end CATCH(type) handler String trim = line.trim(); int start = line.indexOf(trim); NameParser nameParser = new NameParser(this); if (!trim.contains("CATCH")) throw new ASTParseException(lineNo, "Missing CATCH(<type>) <handler>"); int catchIndex = trim.indexOf("CATCH"); String[] parts = trim.substring(0, catchIndex).split("\\s+"); // 0 = TRY // 1 = start // 2 = end NameAST lblStart = nameParser.visit(lineNo, parts[1]); nameParser.setOffset(start + TRY_LEN); nameParser.setOffset(trim.indexOf(parts[2])); NameAST lblEnd = nameParser.visit(lineNo, parts[2]); // parse type String typeS = RegexUtil.getFirstToken("(?<=\\().+(?=\\))", trim); if (typeS == null) throw new ASTParseException(lineNo, "Missing type in CATCH(<type>)"); typeS = typeS.trim(); TypeAST type = null; if (!typeS.equals("*")) { TypeParser typeParser = new TypeParser(); typeParser.setOffset(line.indexOf(typeS)); type = typeParser.visit(lineNo, typeS.trim()); } else { // Wildcard, type is null internally type = new TypeAST(lineNo, line.indexOf(typeS), "*") { @Override public String getType() { return null; } }; } // handler label int typeEnd = trim.indexOf(')'); nameParser.setOffset(typeEnd + 1); NameAST lblHandler = nameParser.visit(lineNo, trim.substring(typeEnd + 1).trim()); return new TryCatchAST(lineNo, start, lblStart, lblEnd, type, lblHandler); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for TRY"); }
302
563
865
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.TryCatchAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/TypeInsnParser.java
TypeInsnParser
visit
class TypeInsnParser extends AbstractParser<TypeInsnAST> { @Override public TypeInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { if (text.contains(" ")) { String[] parts = text.split("\\s+"); return new TypeParser().suggest(lastParse, parts[parts.length - 1]); } return Collections.emptyList(); } }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // type TypeParser typeParser = new TypeParser(); typeParser.setOffset(line.indexOf(trim[1])); TypeAST type = typeParser.visit(lineNo, trim[1]); return new TypeInsnAST(lineNo, start, op, type); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for type instruction"); }
139
228
367
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.TypeInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/TypeParser.java
TypeParser
visit
class TypeParser extends AbstractParser<TypeAST> { @Override public TypeAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { String trim = text.trim(); if (trim.isEmpty()) return Collections.emptyList(); return AutoCompleteUtil.internalName(trim); } }
try { String trim = line.trim(); trim = EscapeUtil.unescape(trim); if (trim.charAt(0) == '[') { // Handle array types if (!trim.matches("\\S+")) throw new ASTParseException(lineNo, "Name cannot contain whitespace characters"); } else { // Handle normal types, cannot have any '[' or ';' in it if(!trim.matches("[^\\[;]+")) throw new ASTParseException(lineNo, "Contains illegal characters"); if (!trim.matches("\\S+")) throw new ASTParseException(lineNo, "Name cannot contain whitespace characters"); } int start = line.indexOf(trim); return new TypeAST(lineNo, getOffset() + start, trim); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for type"); }
113
244
357
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.TypeAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/bytecode/parser/VarInsnParser.java
VarInsnParser
visit
class VarInsnParser extends AbstractParser<VarInsnAST> { @Override public VarInsnAST visit(int lineNo, String line) throws ASTParseException {<FILL_FUNCTION_BODY>} @Override public List<String> suggest(ParseResult<RootAST> lastParse, String text) { try { NameParser nameParser = new NameParser(this); String[] parts = text.trim().split("\\s+"); return nameParser.suggest(lastParse, parts[parts.length - 1]); } catch(Exception ex) { return Collections.emptyList(); } } }
try { String[] trim = line.trim().split("\\s+"); if (trim.length < 2) throw new ASTParseException(lineNo, "Not enough parameters"); int start = line.indexOf(trim[0]); // op OpcodeParser opParser = new OpcodeParser(); opParser.setOffset(line.indexOf(trim[0])); OpcodeAST op = opParser.visit(lineNo, trim[0]); // variable NameParser nameParser = new NameParser(this); nameParser.setOffset(line.indexOf(trim[1])); NameAST variable = nameParser.visit(lineNo, trim[1]); return new VarInsnAST(lineNo, start, op, variable); } catch(Exception ex) { throw new ASTParseException(ex, lineNo, "Bad format for var instruction"); }
157
230
387
<methods>public void <init>() ,public void <init>(AbstractParser#RAW) ,public int getOffset() ,public void setOffset(int) ,public List<java.lang.String> suggest(ParseResult<me.coley.recaf.parse.bytecode.ast.RootAST>, java.lang.String) ,public abstract me.coley.recaf.parse.bytecode.ast.VarInsnAST visit(int, java.lang.String) throws me.coley.recaf.parse.bytecode.exception.ASTParseException<variables>private int offset,protected final non-sealed AbstractParser#RAW parent
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/parse/javadoc/FormattingVisitor.java
FormattingVisitor
head
class FormattingVisitor implements NodeVisitor { private final StringBuilder sb = new StringBuilder(); @Override public void head(Node node, int depth) {<FILL_FUNCTION_BODY>} @Override public void tail(Node node, int depth) { String name = node.nodeName(); if(StringUtil.in(name, "br", "dd", "dt", "p", "h1", "h2", "h3", "h4", "h5", "ul", "ol", "table")) spacing(node); } @Override public String toString() { return sb.toString(); } private void text(String text) { // Don't add empty lines first if(text.trim().isEmpty() && sb.length() == 0) return; sb.append(text); } private void spacing(Node node) { // Common for <li><p> patterns, causing additional uneeded space if (node.nodeName().equals("p") && node.parent().nodeName().equals("li")) return; // Add spacing text("\n"); } }
String name = node.nodeName(); // TextNodes carry all user-readable text in the DOM. if(node instanceof TextNode) text(((TextNode) node).text()); // Other nodes are used only for formatting, not content else if(name.equals("li")) text("\n * "); else if(name.equals("dt")) text(" "); else if(StringUtil.in(name, "p", "h1", "h2", "h3", "h4", "h5", "tr")) spacing(node);
285
147
432
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/ClassResult.java
ClassResult
equals
class ClassResult extends SearchResult { private final int access; private final String name; /** * Constructs a class result. * * @param access * Class modifiers. * @param name * Name of class. */ public ClassResult(int access, String name) { this.access = access; this.name = name; } /** * @return Class modifiers. */ public int getAccess() { return access; } /** * @return Name of class. */ public String getName() { return name; } @Override public String toString() { return name; } @Override public int hashCode() { return Objects.hash(name, access); } @Override public boolean equals(Object other) {<FILL_FUNCTION_BODY>} @Override public int compareTo(SearchResult other) { int ret = super.compareTo(other); if (ret == 0) { if (other instanceof ClassResult) { ClassResult otherResult = (ClassResult) other; return name.compareTo(otherResult.name); } } return ret; } }
if (other instanceof ClassResult) return hashCode() == other.hashCode(); return false;
312
29
341
<methods>public non-sealed void <init>() ,public int compareTo(me.coley.recaf.search.SearchResult) ,public Context<?> getContext() ,public boolean isContextSimilar(me.coley.recaf.search.SearchResult) ,public void setContext(Context<?>) ,public java.lang.String toString() <variables>private Context<?> context
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/Context.java
ClassContext
contains
class ClassContext extends Context<Context> { private final int access; private final String name; /** * @param access * Class modifiers. * @param name * Name of class. */ ClassContext(int access, String name) { this.access = access; this.name = name; } /** * @return Class modifiers. */ public int getAccess() { return access; } /** * @return Name of class. */ public String getName() { return name; } /** * Appends a member context. * * @param access * Member modifiers. * @param name * Name of member. * @param desc * Descriptor of member. * * @return Member context. */ public MemberContext withMember(int access, String name, String desc) { return new MemberContext(this, access, name, desc); } @Override public int compareTo(Context<?> other) { if(other instanceof ClassContext) { ClassContext otherClass = (ClassContext) other; return name.compareTo(otherClass.name); } return WIDER_SCOPE; } @Override public boolean contains(Context<?> other) {<FILL_FUNCTION_BODY>} @Override public String toString() { return name; } }
// Check if member is in class if (other instanceof MemberContext) return (other.getParent().compareTo(this) == 0); else { // Get root context of other while (other.getParent() != null) other = other.getParent(); // Check for match against this class return (other.compareTo(this) == 0); }
395
100
495
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/InsnResult.java
InsnResult
equals
class InsnResult extends SearchResult { private final int index; private final List<String> lines; /** * Constructs a insn result. * * @param index * Index of first matched item. * @param lines * Lines of matched dissasembled method code. */ public InsnResult(int index, List<String> lines) { this.index = index; this.lines = lines; } /** * @return Matched Lines of dissasembled method code. */ public List<String> getLines() { return lines; } @Override public String toString() { return String.join("\n", lines); } @Override public int hashCode() { return Objects.hash(lines); } @Override public boolean equals(Object other) {<FILL_FUNCTION_BODY>} @Override @SuppressWarnings("unchecked") public int compareTo(SearchResult other) { int ret = super.compareTo(other); if (ret == 0) { if (other instanceof InsnResult) { InsnResult otherResult = (InsnResult) other; ret = getContext().getParent().compareTo(otherResult.getContext().getParent()); // Same method -> sort by index if (ret == 0) return Integer.compare(index, otherResult.index); // Different method return ret; } } return ret; } }
if (other instanceof InsnResult) return hashCode() == other.hashCode(); return false;
383
30
413
<methods>public non-sealed void <init>() ,public int compareTo(me.coley.recaf.search.SearchResult) ,public Context<?> getContext() ,public boolean isContextSimilar(me.coley.recaf.search.SearchResult) ,public void setContext(Context<?>) ,public java.lang.String toString() <variables>private Context<?> context
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/InsnTextQuery.java
InsnTextQuery
match
class InsnTextQuery extends Query { private final List<String> lines; /** * Constructs a instruction text query. * * @param lines * Consecutive lines to match. * @param stringMode * How to match strings. */ public InsnTextQuery(List<String> lines, StringMatchMode stringMode) { super(QueryType.INSTRUCTION_TEXT, stringMode); this.lines = lines; } /** * Adds a result if the given class matches the specified name pattern. * * @param code * Disassembled method code. */ public void match(String code) {<FILL_FUNCTION_BODY>} }
String[] codeLines = StringUtil.splitNewline(code); int max = codeLines.length - lines.size(); // Ensure search query is shorter than method code if (max <= 0) return; // Iterate over method code for (int i = 0; i < max; i++) { boolean match = true; List<String> ret = new ArrayList<>(); // Iterate over query code // - Assert each line matches the query input // - If matching for all lines, return the match // - If a line doesn't match skip to the next method insn starting point for (int j = 0; j < lines.size(); j++) { String line = lines.get(j); String lineDis = codeLines[i+j]; ret.add(lineDis); if (!stringMode.match(line, lineDis)) { match = false; break; } } // Add result and continue to next line if(match) { getMatched().add(new InsnResult(i, ret)); i += lines.size() - 1; } }
186
297
483
<methods>public void <init>(me.coley.recaf.search.QueryType, me.coley.recaf.search.StringMatchMode) ,public List<me.coley.recaf.search.SearchResult> getMatched() ,public me.coley.recaf.search.QueryType getType() ,public boolean isType(me.coley.recaf.search.QueryType) <variables>protected final List<me.coley.recaf.search.SearchResult> matched,protected final non-sealed me.coley.recaf.search.StringMatchMode stringMode,private final non-sealed me.coley.recaf.search.QueryType type
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/MemberDefinitionQuery.java
MemberDefinitionQuery
match
class MemberDefinitionQuery extends Query { private final String owner; private final String name; private final String desc; /** * Constructs a member definition query. * * @param owner * Name of class containing the member. May be {@code null} to match members of any class. * @param name * Member name. May be {@code null} to match members of any name. * @param desc * Member descriptor. May be {@code null} to match members of any type. * @param stringMode * How to match strings. */ public MemberDefinitionQuery(String owner, String name, String desc, StringMatchMode stringMode) { super(QueryType.MEMBER_DEFINITION, stringMode); if(owner == null && name == null && desc == null) { throw new IllegalArgumentException("At least one query parameter must be non-null!"); } this.owner = owner; this.name = name; this.desc = desc; } /** * Adds a result if the given member matches the specified member. * * @param access * Member modifers. * @param owner * Name of class containing the member. * @param name * Member name. * @param desc * Member descriptor. */ public void match(int access, String owner, String name, String desc) {<FILL_FUNCTION_BODY>} }
boolean hasOwner = this.owner == null || stringMode.match(this.owner, owner); boolean hasName = this.name == null || stringMode.match(this.name, name); boolean hasDesc = this.desc == null || stringMode.match(this.desc, desc); if(hasOwner && hasName && hasDesc) { getMatched().add(new MemberResult(access, owner, name, desc)); }
375
113
488
<methods>public void <init>(me.coley.recaf.search.QueryType, me.coley.recaf.search.StringMatchMode) ,public List<me.coley.recaf.search.SearchResult> getMatched() ,public me.coley.recaf.search.QueryType getType() ,public boolean isType(me.coley.recaf.search.QueryType) <variables>protected final List<me.coley.recaf.search.SearchResult> matched,protected final non-sealed me.coley.recaf.search.StringMatchMode stringMode,private final non-sealed me.coley.recaf.search.QueryType type
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/MemberReferenceQuery.java
MemberReferenceQuery
match
class MemberReferenceQuery extends Query { private final String owner; private final String name; private final String desc; /** * Constructs a member references query. * * @param owner * Name of class containing the member. May be {@code null} to match members of any class. * @param name * Member name. May be {@code null} to match members of any name. * @param desc * Member descriptor. May be {@code null} to match members of any type. * @param stringMode * How to match strings. */ public MemberReferenceQuery(String owner, String name, String desc, StringMatchMode stringMode) { super(QueryType.MEMBER_REFERENCE, stringMode); if(owner == null && name == null && desc == null) { throw new IllegalArgumentException("At least one query parameter must be non-null!"); } this.owner = owner; this.name = name; this.desc = desc; } /** * Adds a result if the given member matches the specified member. * * @param access * Member modifers. * @param owner * Name of class containing the member. * @param name * Member name. * @param desc * Member descriptor. */ public void match(IntSupplier access, String owner, String name, String desc) {<FILL_FUNCTION_BODY>} }
boolean hasOwner = this.owner == null || stringMode.match(this.owner, owner); boolean hasName = this.name == null || stringMode.match(this.name, name); boolean hasDesc = this.desc == null || stringMode.match(this.desc, desc); if(hasOwner && hasName && hasDesc) { getMatched().add(new MemberResult(access.getAsInt(), owner, name, desc)); }
377
117
494
<methods>public void <init>(me.coley.recaf.search.QueryType, me.coley.recaf.search.StringMatchMode) ,public List<me.coley.recaf.search.SearchResult> getMatched() ,public me.coley.recaf.search.QueryType getType() ,public boolean isType(me.coley.recaf.search.QueryType) <variables>protected final List<me.coley.recaf.search.SearchResult> matched,protected final non-sealed me.coley.recaf.search.StringMatchMode stringMode,private final non-sealed me.coley.recaf.search.QueryType type
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/MemberResult.java
MemberResult
compareTo
class MemberResult extends SearchResult { private final int access; private final String owner; private final String name; private final String desc; /** * Constructs a member result. * * @param access * Member modifers. * @param owner * Name of class containing the member. * @param name * Member name. * @param desc * Member descriptor. */ public MemberResult(int access, String owner, String name, String desc) { this.access = access; this.owner = owner; this.name = name; this.desc = desc; } /** * @return Member modifiers. */ public int getAccess() { return access; } /** * @return Name of class containing the member. */ public String getOwner() { return owner; } /** * @return Member name. */ public String getName() { return name; } /** * @return Member descriptor. */ public String getDesc() { return desc; } /** * @return {@code true} if the {@link #getDesc() descriptor} outlines a field type. */ public boolean isField() { return !isMethod(); } /** * @return {@code true} if the {@link #getDesc() descriptor} outlines a method type. */ public boolean isMethod() { return desc.contains("("); } @Override public String toString() { if(isMethod()) { return owner + "." + name + desc; } else { return owner + "." + name + " " + desc; } } @Override public int hashCode() { return Objects.hash(owner, name, desc); } @Override public boolean equals(Object other) { if(other instanceof MemberResult) return hashCode() == other.hashCode(); return false; } @Override public int compareTo(SearchResult other) {<FILL_FUNCTION_BODY>} }
int ret = super.compareTo(other); if (ret == 0) { if (other instanceof MemberResult) { MemberResult otherResult = (MemberResult) other; if (isField() && otherResult.isMethod()) return 1; if (isMethod() && otherResult.isField()) return -1; return toString().compareTo(otherResult.toString()); } } return ret;
530
113
643
<methods>public non-sealed void <init>() ,public int compareTo(me.coley.recaf.search.SearchResult) ,public Context<?> getContext() ,public boolean isContextSimilar(me.coley.recaf.search.SearchResult) ,public void setContext(Context<?>) ,public java.lang.String toString() <variables>private Context<?> context
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/SearchResult.java
SearchResult
isContextSimilar
class SearchResult implements Comparable<SearchResult> { private Context<?> context; /** * Sets the context <i>(Where the result is located)</i> of the search result. * * @param context * Context of the result. */ public void setContext(Context<?> context) { this.context = context; } /** * @return Context of the result. */ public Context<?> getContext() { return context; } @Override public int compareTo(SearchResult other) { return context.compareTo(other.context); } /** * @param other * Result to be compared * * @return {@code true} if both contexts are considered similar. * * @see Context#isSimilar(Context) */ public boolean isContextSimilar(SearchResult other) {<FILL_FUNCTION_BODY>} @Override public String toString() { throw new UnsupportedOperationException("Unimplemented result string representation"); } }
return context != null && other.context != null && context.isSimilar(other.context);
268
27
295
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/StringResult.java
StringResult
compareTo
class StringResult extends SearchResult { private final String text; /** * Constructs a class result. * * @param text * Matched text. */ public StringResult(String text) { this.text = text; } /** * @return Matched text. */ public String getText() { return text; } @Override public int compareTo(SearchResult other) {<FILL_FUNCTION_BODY>} @Override public String toString() { return text.replace("\n", "\\n").replace("\t", "\\t"); } }
int ret = super.compareTo(other); if(ret == 0) { if(other instanceof StringResult) { StringResult otherResult = (StringResult) other; return text.compareTo(otherResult.text); } } return ret;
158
71
229
<methods>public non-sealed void <init>() ,public int compareTo(me.coley.recaf.search.SearchResult) ,public Context<?> getContext() ,public boolean isContextSimilar(me.coley.recaf.search.SearchResult) ,public void setContext(Context<?>) ,public java.lang.String toString() <variables>private Context<?> context
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/search/ValueResult.java
ValueResult
compareTo
class ValueResult extends SearchResult { private final Object value; /** * Constructs a value result. * * @param value * Matched value. */ public ValueResult(Object value) { this.value = value; } /** * @return Matched value. */ public Object getValue() { return value; } @Override @SuppressWarnings("unchecked") public int compareTo(SearchResult other) {<FILL_FUNCTION_BODY>} }
int ret = super.compareTo(other); if (ret == 0) { if (other instanceof ValueResult) { ValueResult otherResult = (ValueResult) other; if (value instanceof Comparable && otherResult.value instanceof Comparable) { Comparable compValue = (Comparable) value; Comparable compOtherValue = (Comparable) otherResult.value; return compValue.compareTo(compOtherValue); } } } return ret;
135
131
266
<methods>public non-sealed void <init>() ,public int compareTo(me.coley.recaf.search.SearchResult) ,public Context<?> getContext() ,public boolean isContextSimilar(me.coley.recaf.search.SearchResult) ,public void setContext(Context<?>) ,public java.lang.String toString() <variables>private Context<?> context
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/Themes.java
Themes
get
class Themes { /** * Open the custom theme editor. * * @param controller * Current controller. */ public static void showThemeEditor(GuiController controller) { Stage stage = controller.windows().getThemeEditorWindow(); if(stage == null) { stage = controller.windows().window(translate("ui.menubar.themeeditor"), new CssThemeEditorPane(controller)); controller.windows().setThemeEditorWindow(stage); } stage.show(); stage.toFront(); } /** * @return List of application-wide styles. */ public static List<Resource> getStyles() { List<Resource> resources = SelfReferenceUtil.get().getStyles(); resources.addAll(get("ui-", ".css")); return resources; } /** * @return List of text-editor styles. */ public static List<Resource> getTextThemes() { List<Resource> resources = SelfReferenceUtil.get().getTextThemes(); resources.addAll(get("text-", ".css")); return resources; } private static Collection<Resource> get(String prefix, String suffix) {<FILL_FUNCTION_BODY>} }
List<Resource> resources = new ArrayList<>(); File styleDirectory = Recaf.getDirectory("style").toFile(); if (!styleDirectory.exists()) styleDirectory.mkdir(); for (File file : styleDirectory.listFiles()) { String name = file.getName(); if (name.startsWith(prefix) && name.endsWith(suffix)) resources.add(Resource.external(file.getPath().replace('\\', '/'))); } return resources;
319
127
446
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/NullableText.java
NullableText
get
class NullableText extends TextField { /** * @return Wrapper of standard 'getText' but empty strings are returned as {@code null}. */ public String get() {<FILL_FUNCTION_BODY>} }
String text = super.getText(); if(text == null || text.trim().isEmpty()) return null; return text;
57
36
93
<methods>public void <init>() ,public void <init>(java.lang.String) ,public final javafx.geometry.Pos getAlignment() ,public java.lang.CharSequence getCharacters() ,public static List<CssMetaData<? extends javafx.css.Styleable,?>> getClassCssMetaData() ,public List<CssMetaData<? extends javafx.css.Styleable,?>> getControlCssMetaData() ,public final EventHandler<javafx.event.ActionEvent> getOnAction() ,public final int getPrefColumnCount() ,public final ObjectProperty<EventHandler<javafx.event.ActionEvent>> onActionProperty() ,public final void setAlignment(javafx.geometry.Pos) ,public final void setOnAction(EventHandler<javafx.event.ActionEvent>) ,public final void setPrefColumnCount(int) <variables>public static final int DEFAULT_PREF_COLUMN_COUNT,private ObjectProperty<javafx.geometry.Pos> alignment,private ObjectProperty<EventHandler<javafx.event.ActionEvent>> onAction,private javafx.beans.property.IntegerProperty prefColumnCount
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/NumericText.java
NumericText
get
class NumericText extends TextField { /** * @return Generic number, {@code null} if text does not represent any number format. */ public Number get() {<FILL_FUNCTION_BODY>} }
String text = getText(); // Normal int if(text.matches("-?\\d+")) return Integer.parseInt(text); // Double else if(text.matches("-?\\d+\\.?\\d*[dD]?")) { if(text.toLowerCase().contains("d")) return Double.parseDouble(text.substring(0, text.length() - 1)); else return Double.parseDouble(text); } // Float else if(text.matches("-?\\d+\\.?\\d*[fF]")) return Float.parseFloat(text.substring(0, text.length() - 1)); // Long else if(text.matches("-?\\d+\\.?\\d*[lL]")) return Long.parseLong(text.substring(0, text.length() - 1)); // Hex int else if(text.matches("-?0x\\d+")) return (int) Long.parseLong(text.replace("0x", ""), 16); // Hex long else if(text.matches("-?0x\\d+[lL]")) return Long.parseLong(text.substring(0, text.length() - 1).replace("0x", ""), 16); return null;
57
349
406
<methods>public void <init>() ,public void <init>(java.lang.String) ,public final javafx.geometry.Pos getAlignment() ,public java.lang.CharSequence getCharacters() ,public static List<CssMetaData<? extends javafx.css.Styleable,?>> getClassCssMetaData() ,public List<CssMetaData<? extends javafx.css.Styleable,?>> getControlCssMetaData() ,public final EventHandler<javafx.event.ActionEvent> getOnAction() ,public final int getPrefColumnCount() ,public final ObjectProperty<EventHandler<javafx.event.ActionEvent>> onActionProperty() ,public final void setAlignment(javafx.geometry.Pos) ,public final void setOnAction(EventHandler<javafx.event.ActionEvent>) ,public final void setPrefColumnCount(int) <variables>public static final int DEFAULT_PREF_COLUMN_COUNT,private ObjectProperty<javafx.geometry.Pos> alignment,private ObjectProperty<EventHandler<javafx.event.ActionEvent>> onAction,private javafx.beans.property.IntegerProperty prefColumnCount
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/SplitableTabPane.java
SplitableTabPane
createTabStage
class SplitableTabPane extends TabPane { private static final SnapshotParameters SNAPSHOT_PARAMETERS; private static final String DROP_TARGET_STYLE = "drag-target"; private static final String TAB_DRAG_KEY = "split-tab"; private static final ObjectProperty<Tab> draggedTab = new SimpleObjectProperty<>(); /** * Creates the splittable tab pane. */ public SplitableTabPane() { TabPane selfPane = this; // Allow this pane to accept transfers setOnDragOver(dragEvent -> { Dragboard dragboard = dragEvent.getDragboard(); if (dragboard.hasString() && TAB_DRAG_KEY.equals(dragboard.getString()) && draggedTab.get() != null && draggedTab.get().getTabPane() != selfPane) { dragEvent.acceptTransferModes(TransferMode.MOVE); dragEvent.consume(); } }); // Setup start drag setOnDragDetected(mouseEvent -> { if (mouseEvent.getSource() instanceof TabPane) { Pane rootPane = (Pane) getScene().getRoot(); rootPane.setOnDragOver(dragEvent -> { dragEvent.acceptTransferModes(TransferMode.MOVE); dragEvent.consume(); }); draggedTab.setValue(getSelectionModel().getSelectedItem()); WritableImage snapshot = draggedTab.get().getContent().snapshot(SNAPSHOT_PARAMETERS, null); ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.put(DataFormat.PLAIN_TEXT, TAB_DRAG_KEY); Dragboard db = startDragAndDrop(TransferMode.MOVE); db.setDragView(snapshot, 40, 40); db.setContent(clipboardContent); } mouseEvent.consume(); }); // Setup end dragging in the case where there is no tab-pane target setOnDragDone(dragEvent -> { Tab dragged = draggedTab.get(); if (!dragEvent.isDropCompleted() && dragged != null) { createTabStage(dragged).show(); setCursor(Cursor.DEFAULT); dragEvent.consume(); removeStyle(); } }); // Setup end dragging in the case where this is the tab-pane target setOnDragDropped(dragEvent -> { Dragboard dragboard = dragEvent.getDragboard(); Tab dragged = draggedTab.get(); if (dragboard.hasString() && TAB_DRAG_KEY.equals(dragboard.getString()) && dragged != null) { if (dragged.getTabPane() != selfPane) { SplitableTabPane owner = (SplitableTabPane) dragged.getTabPane(); owner.closeTab(dragged); getTabs().add(dragged); getSelectionModel().select(dragged); } dragEvent.setDropCompleted(true); draggedTab.set(null); dragEvent.consume(); removeStyle(); } }); // Highlighting with style classes setOnDragEntered(dragEvent -> { Dragboard dragboard = dragEvent.getDragboard(); if (dragboard.hasString() && TAB_DRAG_KEY.equals(dragboard.getString()) && draggedTab.get() != null && draggedTab.get().getTabPane() != selfPane) { addStyle(); } }); setOnDragExited(dragEvent -> { Dragboard dragboard = dragEvent.getDragboard(); if (dragboard.hasString() && TAB_DRAG_KEY.equals(dragboard.getString()) && draggedTab.get() != null && draggedTab.get().getTabPane() != selfPane) { removeStyle(); } }); } /** * @param tab * Tab to remove. */ public void closeTab(Tab tab) { getTabs().remove(tab); } /** * Create a new tab with the given title and content. * * @param title * Tab title. * @param content * Tab content. * * @return New tab. */ protected Tab createTab(String title, Node content) { Tab tab = new Tab(title, content); tab.setClosable(true); return tab; } /** * Create a new stage for the given tab when it is dropped outside of the scope of a {@link SplitableTabPane} * * @param tab * Tab to wrap in a new stage. * * @return New stage. */ protected Stage createTabStage(Tab tab) {<FILL_FUNCTION_BODY>} /** * Create a basic stage with the given title and scene. * * @param title * Title for stage. * @param scene * Stage content. * * @return New stage. */ protected Stage createStage(String title, Scene scene) { Stage stage = new Stage(); stage.setScene(scene); stage.setTitle(title); return stage; } /** * @return New instance of {@link SplitableTabPane} to be used in a newly created {@link Stage}. */ protected SplitableTabPane newTabPane() { return new SplitableTabPane(); } private void addStyle() { getStyleClass().add(DROP_TARGET_STYLE); } private void removeStyle() { getStyleClass().remove(DROP_TARGET_STYLE); } static { SNAPSHOT_PARAMETERS = new SnapshotParameters(); SNAPSHOT_PARAMETERS.setTransform(Transform.scale(0.4, 0.4)); } }
// Validate content Pane content = (Pane) tab.getContent(); if (content == null) throw new IllegalArgumentException("Cannot detach '" + tab.getText() + "' because content is null"); // Remove content from tab closeTab(tab); // Create stage SplitableTabPane tabPaneCopy = newTabPane(); tabPaneCopy.getTabs().add(tab); BorderPane root = new BorderPane(tabPaneCopy); Scene scene = new Scene(root, root.getPrefWidth(), root.getPrefHeight()); Stage stage = createStage(tab.getText(), scene); // Set location to mouse Point mouseLocation = MouseInfo.getPointerInfo().getLocation(); stage.setX(mouseLocation.getX()); stage.setY(mouseLocation.getY()); return stage;
1,601
220
1,821
<methods>public void <init>() ,public transient void <init>(javafx.scene.control.Tab[]) ,public static List<CssMetaData<? extends javafx.css.Styleable,?>> getClassCssMetaData() ,public List<CssMetaData<? extends javafx.css.Styleable,?>> getControlCssMetaData() ,public final SingleSelectionModel<javafx.scene.control.Tab> getSelectionModel() ,public final double getTabMaxHeight() ,public final double getTabMaxWidth() ,public final double getTabMinHeight() ,public final double getTabMinWidth() ,public final ObservableList<javafx.scene.control.Tab> getTabs() ,public final boolean isRotateGraphic() ,public javafx.scene.Node lookup(java.lang.String) ,public Set<javafx.scene.Node> lookupAll(java.lang.String) ,public final ObjectProperty<SingleSelectionModel<javafx.scene.control.Tab>> selectionModelProperty() ,public final void setRotateGraphic(boolean) ,public final void setSelectionModel(SingleSelectionModel<javafx.scene.control.Tab>) ,public final void setSide(javafx.geometry.Side) ,public final void setTabClosingPolicy(javafx.scene.control.TabPane.TabClosingPolicy) ,public final void setTabDragPolicy(javafx.scene.control.TabPane.TabDragPolicy) ,public final void setTabMaxHeight(double) ,public final void setTabMaxWidth(double) ,public final void setTabMinHeight(double) ,public final void setTabMinWidth(double) ,public final ObjectProperty<javafx.geometry.Side> sideProperty() ,public final ObjectProperty<javafx.scene.control.TabPane.TabClosingPolicy> tabClosingPolicyProperty() ,public final ObjectProperty<javafx.scene.control.TabPane.TabDragPolicy> tabDragPolicyProperty() ,public final javafx.beans.property.DoubleProperty tabMaxWidthProperty() ,public final javafx.beans.property.DoubleProperty tabMinHeightProperty() ,public final javafx.beans.property.DoubleProperty tabMinWidthProperty() <variables>private static final javafx.css.PseudoClass BOTTOM_PSEUDOCLASS_STATE,private static final double DEFAULT_TAB_MAX_HEIGHT,private static final double DEFAULT_TAB_MAX_WIDTH,private static final double DEFAULT_TAB_MIN_HEIGHT,private static final double DEFAULT_TAB_MIN_WIDTH,private static final javafx.css.PseudoClass LEFT_PSEUDOCLASS_STATE,private static final javafx.css.PseudoClass RIGHT_PSEUDOCLASS_STATE,public static final java.lang.String STYLE_CLASS_FLOATING,private static final javafx.css.PseudoClass TOP_PSEUDOCLASS_STATE,private javafx.beans.property.BooleanProperty rotateGraphic,private ObjectProperty<SingleSelectionModel<javafx.scene.control.Tab>> selectionModel,private ObjectProperty<javafx.geometry.Side> side,private ObjectProperty<javafx.scene.control.TabPane.TabClosingPolicy> tabClosingPolicy,private ObjectProperty<javafx.scene.control.TabPane.TabDragPolicy> tabDragPolicy,private javafx.beans.property.DoubleProperty tabMaxHeight,private javafx.beans.property.DoubleProperty tabMaxWidth,private javafx.beans.property.DoubleProperty tabMinHeight,private javafx.beans.property.DoubleProperty tabMinWidth,private ObservableList<javafx.scene.control.Tab> tabs
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/TableViewExtra.java
TableViewExtra
recomputeVisibleIndexes
class TableViewExtra<T> { private final LinkedHashSet<TableRow<T>> rows = new LinkedHashSet<>(); private final TableView<T> table; private int firstIndex; /** * @param tableView * Table to wrap. */ public TableViewExtra(TableView<T> tableView) { this.table = tableView; // Callback to monitor row creation and to identify visible screen rows final Callback<TableView<T>, TableRow<T>> rf = tableView.getRowFactory(); final Callback<TableView<T>, TableRow<T>> modifiedRowFactory = param -> { TableRow<T> r = rf != null ? rf.call(param) : new TableRow<>(); // Save row, this implementation relies on JaxaFX re-using TableRow efficiently rows.add(r); return r; }; tableView.setRowFactory(modifiedRowFactory); } private void recomputeVisibleIndexes() {<FILL_FUNCTION_BODY>} /** * Find the first row in the table which is visible on the display * * @return {@code -1} if none visible or the index of the first visible row (wholly or fully) */ public int getFirstVisibleIndex() { recomputeVisibleIndexes(); return firstIndex; } }
firstIndex = -1; // Work out which of the rows are visible double tblViewHeight = table.getHeight(); double headerHeight = table.lookup(".column-header-background").getBoundsInLocal().getHeight(); double viewPortHeight = tblViewHeight - headerHeight; for(TableRow<T> r : rows) { if(!r.isVisible()) continue; double minY = r.getBoundsInParent().getMinY(); double maxY = r.getBoundsInParent().getMaxY(); boolean hidden = (maxY < 0) || (minY > viewPortHeight); if(hidden) continue; if(firstIndex < 0 || r.getIndex() < firstIndex) firstIndex = r.getIndex(); }
347
209
556
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/pane/ColumnPane.java
ColumnPane
add
class ColumnPane extends BorderPane { protected final GridPane grid = new GridPane(); protected int row; /** * Setup grid. * * @param insets * Padding between container and border. * @param leftPercent * Percent of the space for the left column to fill. * @param rightPercent * Percent of the space for right column to fill. * @param vgap * Vertical spacing between items. */ public ColumnPane(Insets insets, double leftPercent, double rightPercent, double vgap) { setCenter(grid); setPadding(insets); ColumnConstraints column1 = new ColumnConstraints(); ColumnConstraints column2 = new ColumnConstraints(); column1.setPercentWidth(leftPercent); column2.setPercentWidth(rightPercent); column2.setFillWidth(true); column2.setHgrow(Priority.ALWAYS); column2.setHalignment(HPos.RIGHT); grid.getColumnConstraints().addAll(column1, column2); grid.setVgap(vgap); } /** * Setup grid. */ public ColumnPane() { this(new Insets(5, 10, 5, 10), 70, 30, 5); } /** * Add row of controls. * * @param left * Smaller left control. * @param right * Larger right control. */ public void add(Node left, Node right) {<FILL_FUNCTION_BODY>} }
// Dummy SubLabeled for proper sizing. Otherwise, a Region would suffice. if (left == null) left = new SubLabeled(" ", " "); // Add controls grid.add(left, 0, row); grid.add(right, 1, row); row++; // Force allow HGrow, using Region instead of Node due to inconsistent behavior using Node if (right instanceof Region) ((Region) right).setMaxWidth(Double.MAX_VALUE);
439
131
570
<methods>public void <init>() ,public void <init>(javafx.scene.Node) ,public void <init>(javafx.scene.Node, javafx.scene.Node, javafx.scene.Node, javafx.scene.Node, javafx.scene.Node) ,public final ObjectProperty<javafx.scene.Node> centerProperty() ,public static void clearConstraints(javafx.scene.Node) ,public final javafx.scene.Node getBottom() ,public final javafx.scene.Node getCenter() ,public javafx.geometry.Orientation getContentBias() ,public final javafx.scene.Node getLeft() ,public static javafx.geometry.Insets getMargin(javafx.scene.Node) ,public final javafx.scene.Node getRight() ,public final javafx.scene.Node getTop() ,public final ObjectProperty<javafx.scene.Node> leftProperty() ,public final ObjectProperty<javafx.scene.Node> rightProperty() ,public static void setAlignment(javafx.scene.Node, javafx.geometry.Pos) ,public final void setBottom(javafx.scene.Node) ,public final void setCenter(javafx.scene.Node) ,public final void setLeft(javafx.scene.Node) ,public static void setMargin(javafx.scene.Node, javafx.geometry.Insets) ,public final void setRight(javafx.scene.Node) ,public final void setTop(javafx.scene.Node) ,public final ObjectProperty<javafx.scene.Node> topProperty() <variables>private static final java.lang.String ALIGNMENT,private static final java.lang.String MARGIN,private ObjectProperty<javafx.scene.Node> bottom,private ObjectProperty<javafx.scene.Node> center,private ObjectProperty<javafx.scene.Node> left,private ObjectProperty<javafx.scene.Node> right,private ObjectProperty<javafx.scene.Node> top
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/tree/AnnoItem.java
AnnoItem
compareTo
class AnnoItem extends DirectoryItem { private final String name; /** * @param resource * The resource associated with the item. * @param local * Local item name. * @param name * Full annotation name. */ public AnnoItem(JavaResource resource, String local, String name) { super(resource, local); this.name = name; } /** * @return Contained class name. */ public String getAnnoName() { return name; } @Override public int compareTo(DirectoryItem o) {<FILL_FUNCTION_BODY>} }
if(o instanceof AnnoItem) { AnnoItem c = (AnnoItem) o; return name.compareTo(c.name); } return 1;
165
50
215
<methods>public void <init>(me.coley.recaf.workspace.JavaResource, java.lang.String) ,public void addChild(java.lang.String, me.coley.recaf.ui.controls.tree.DirectoryItem, boolean) ,public int compareTo(me.coley.recaf.ui.controls.tree.DirectoryItem) ,public void expandParents() ,public me.coley.recaf.ui.controls.tree.DirectoryItem getChild(java.lang.String, boolean) ,public me.coley.recaf.ui.controls.tree.DirectoryItem getDeepChild(java.lang.String) ,public java.lang.String getLocalName() ,public void removeSourceChild(TreeItem<me.coley.recaf.workspace.JavaResource>) <variables>private final non-sealed java.lang.String local,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToDir,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToLeaf
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/tree/ClassItem.java
ClassItem
compareTo
class ClassItem extends DirectoryItem { private final String name; /** * @param resource * The resource associated with the item. * @param local * Local item name. * @param name * Full class name. */ public ClassItem(JavaResource resource, String local, String name) { super(resource, local); this.name = name; } /** * @return Contained class name. */ public String getClassName() { return name; } @Override public int compareTo(DirectoryItem o) {<FILL_FUNCTION_BODY>} }
if(o instanceof ClassItem) { ClassItem c = (ClassItem) o; return name.compareTo(c.name); } return 1;
162
47
209
<methods>public void <init>(me.coley.recaf.workspace.JavaResource, java.lang.String) ,public void addChild(java.lang.String, me.coley.recaf.ui.controls.tree.DirectoryItem, boolean) ,public int compareTo(me.coley.recaf.ui.controls.tree.DirectoryItem) ,public void expandParents() ,public me.coley.recaf.ui.controls.tree.DirectoryItem getChild(java.lang.String, boolean) ,public me.coley.recaf.ui.controls.tree.DirectoryItem getDeepChild(java.lang.String) ,public java.lang.String getLocalName() ,public void removeSourceChild(TreeItem<me.coley.recaf.workspace.JavaResource>) <variables>private final non-sealed java.lang.String local,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToDir,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToLeaf
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/tree/DirectoryItem.java
DirectoryItem
getDeepChild
class DirectoryItem extends BaseItem implements Comparable<DirectoryItem> { // Differentiate directories and leaves to account for overlapping names. private final Map<String, DirectoryItem> localToDir = new HashMap<>(); private final Map<String, DirectoryItem> localToLeaf = new HashMap<>(); private final String local; /** * @param resource * The resource associated with the item. * @param local * Partial name of item. */ public DirectoryItem(JavaResource resource, String local) { super(resource); this.local = local; } @Override public void removeSourceChild(TreeItem<JavaResource> child) { boolean isClass = child instanceof ClassItem; boolean isDir = child instanceof PackageItem; if (isClass || isDir) { String childLocal = ((DirectoryItem) child).local; if (isClass) localToLeaf.remove(childLocal); else localToDir.remove(childLocal); } super.removeSourceChild(child); } /** * Used for display. * * @return Get local item name. */ public String getLocalName() { return local; } /** * Add a child by the local name. * * @param local * Local name of child. * @param child * Child to add. * @param isLeaf * Indicator that the added child is the final element. */ public void addChild(String local, DirectoryItem child, boolean isLeaf) { if (isLeaf) localToLeaf.put(local, child); else localToDir.put(local, child); addSourceChild(child); } /** * @param local * Local name of child. * @param isLeaf * Does the local name belong to a leaf. * * @return Child item by local name. */ public DirectoryItem getChild(String local, boolean isLeaf) { if (isLeaf) return localToLeaf.get(local); return localToDir.get(local); } /** * A path is specified as multiple local names joined by '/'. * * @param path * Path to child. * * @return Child item by path. */ public DirectoryItem getDeepChild(String path) {<FILL_FUNCTION_BODY>} /** * Expand all parents to this item. */ public void expandParents() { TreeItem<?> item = this; while ((item = item.getParent()) != null) item.setExpanded(true); } @Override public int compareTo(DirectoryItem o) { // Ensure classes do not appear above adjacent packages if (this instanceof ClassItem && !(o instanceof ClassItem)) return 1; else if (o instanceof ClassItem && !(this instanceof ClassItem)) return -1; // Compare local name return local.compareTo(o.local); } }
DirectoryItem item = this; List<String> parts = new ArrayList<>(Arrays.asList(path.split("/"))); while(!parts.isEmpty() && item != null) { String part = parts.remove(0); item = item.getChild(part, parts.isEmpty()); } return item;
796
88
884
<methods>public void <init>(me.coley.recaf.workspace.JavaResource) <variables>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/tree/FileItem.java
FileItem
compareTo
class FileItem extends DirectoryItem { private final String name; /** * @param resource * The resource associated with the item. * @param local * Local file name. * @param name * Full file name. */ public FileItem(JavaResource resource, String local, String name) { super(resource, local); this.name = name; } /** * @return Contained file name. */ public String getFileName() { return name; } @Override public int compareTo(DirectoryItem o) {<FILL_FUNCTION_BODY>} }
if(o instanceof FileItem) { FileItem c = (FileItem) o; return name.compareTo(c.name); } return 1;
161
47
208
<methods>public void <init>(me.coley.recaf.workspace.JavaResource, java.lang.String) ,public void addChild(java.lang.String, me.coley.recaf.ui.controls.tree.DirectoryItem, boolean) ,public int compareTo(me.coley.recaf.ui.controls.tree.DirectoryItem) ,public void expandParents() ,public me.coley.recaf.ui.controls.tree.DirectoryItem getChild(java.lang.String, boolean) ,public me.coley.recaf.ui.controls.tree.DirectoryItem getDeepChild(java.lang.String) ,public java.lang.String getLocalName() ,public void removeSourceChild(TreeItem<me.coley.recaf.workspace.JavaResource>) <variables>private final non-sealed java.lang.String local,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToDir,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToLeaf
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/tree/FilterableTreeItem.java
FilterableTreeItem
addSourceChild
class FilterableTreeItem<T> extends TreeItem<T> { private final ObservableList<TreeItem<T>> sourceChildren = FXCollections.observableArrayList(); private final ObjectProperty<Predicate<TreeItem<T>>> predicate = new SimpleObjectProperty<>(); /** * @param value * Item value */ public FilterableTreeItem(T value) { super(value); // Support filtering by using a filtered list backing. // - Apply predicate to items FilteredList<TreeItem<T>> filteredChildren = new FilteredList<>(sourceChildren); filteredChildren.predicateProperty().bind(Bindings.createObjectBinding(() -> child -> { if(child instanceof FilterableTreeItem) ((FilterableTreeItem<T>) child).predicateProperty().set(predicate.get()); if(predicate.get() == null || !child.getChildren().isEmpty()) return true; return predicate.get().test(child); }, predicate)); // Reflection hackery setUnderlyingChildren(filteredChildren); } /** * Use reflection to directly set the underlying {@link TreeItem#children} field. * The javadoc for that field literally says: * <pre> * It is important that interactions with this list go directly into the * children property, rather than via getChildren(), as this may be * a very expensive call. * </pre> * This will additionally add the current tree-item's {@link TreeItem#childrenListener} to * the given list's listeners. * * @param list * Children list. */ @SuppressWarnings("unchecked") private void setUnderlyingChildren(ObservableList<TreeItem<T>> list) { try { // Add our change listener to the passed list. Field childrenListener = TreeItem.class.getDeclaredField("childrenListener"); childrenListener.setAccessible(true); list.addListener((ListChangeListener<? super TreeItem<T>>) childrenListener.get(this)); // Directly set "TreeItem.children" Field children = TreeItem.class.getDeclaredField("children"); children.setAccessible(true); children.set(this, list); } catch(ReflectiveOperationException ex) { Log.error(ex, "Failed to update filterable children"); } } /** * Add an unfiltered child to this item. * * @param item * Child item to add. */ public void addSourceChild(TreeItem<T> item) {<FILL_FUNCTION_BODY>} /** * Remove an unfiltered child from this item. * * @param child * Child item to remove. */ public void removeSourceChild(TreeItem<T> child) { sourceChildren.remove(child); } /** * @return Predicate property. */ public ObjectProperty<Predicate<TreeItem<T>>> predicateProperty() { return predicate; } }
int index = Arrays.binarySearch(getChildren().toArray(), item); if(index < 0) index = -(index + 1); sourceChildren.add(index, item);
773
53
826
<methods>public void <init>() ,public void <init>(T) ,public void <init>(T, javafx.scene.Node) ,public void addEventFilter(EventType<E>, EventHandler<? super E>) ,public void addEventHandler(EventType<E>, EventHandler<? super E>) ,public static EventType<TreeModificationEvent<T>> branchCollapsedEvent() ,public static EventType<TreeModificationEvent<T>> branchExpandedEvent() ,public javafx.event.EventDispatchChain buildEventDispatchChain(javafx.event.EventDispatchChain) ,public static EventType<TreeModificationEvent<T>> childrenModificationEvent() ,public static EventType<TreeModificationEvent<T>> expandedItemCountChangeEvent() ,public final javafx.beans.property.BooleanProperty expandedProperty() ,public ObservableList<TreeItem<T>> getChildren() ,public final javafx.scene.Node getGraphic() ,public final TreeItem<T> getParent() ,public final T getValue() ,public static EventType<TreeModificationEvent<T>> graphicChangedEvent() ,public final ObjectProperty<javafx.scene.Node> graphicProperty() ,public final boolean isExpanded() ,public boolean isLeaf() ,public final javafx.beans.property.ReadOnlyBooleanProperty leafProperty() ,public TreeItem<T> nextSibling() ,public TreeItem<T> nextSibling(TreeItem<T>) ,public final ReadOnlyObjectProperty<TreeItem<T>> parentProperty() ,public TreeItem<T> previousSibling() ,public TreeItem<T> previousSibling(TreeItem<T>) ,public void removeEventFilter(EventType<E>, EventHandler<? super E>) ,public void removeEventHandler(EventType<E>, EventHandler<? super E>) ,public final void setExpanded(boolean) ,public final void setGraphic(javafx.scene.Node) ,public final void setValue(T) ,public java.lang.String toString() ,public static EventType<TreeModificationEvent<T>> treeNotificationEvent() ,public static EventType<TreeModificationEvent<T>> valueChangedEvent() ,public final ObjectProperty<T> valueProperty() <variables>private static final EventType<?> BRANCH_COLLAPSED_EVENT,private static final EventType<?> BRANCH_EXPANDED_EVENT,private static final EventType<?> CHILDREN_MODIFICATION_EVENT,private static final EventType<?> EXPANDED_ITEM_COUNT_CHANGE_EVENT,private static final EventType<?> GRAPHIC_CHANGED_EVENT,private static final EventType<?> TREE_NOTIFICATION_EVENT,private static final EventType<?> VALUE_CHANGED_EVENT,ObservableList<TreeItem<T>> children,private ListChangeListener<TreeItem<T>> childrenListener,private final com.sun.javafx.event.EventHandlerManager eventHandlerManager,private javafx.beans.property.BooleanProperty expanded,private int expandedDescendentCount,private boolean expandedDescendentCountDirty,private ObjectProperty<javafx.scene.Node> graphic,private boolean ignoreSortUpdate,private final EventHandler<TreeModificationEvent<java.lang.Object>> itemListener,Comparator<TreeItem<T>> lastComparator,javafx.scene.control.TreeSortMode lastSortMode,private javafx.beans.property.ReadOnlyBooleanWrapper leaf,private ReadOnlyObjectWrapper<TreeItem<T>> parent,private int parentLinkCount,int previousExpandedDescendentCount,private ObjectProperty<T> value
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/tree/MemberItem.java
MemberItem
compareTo
class MemberItem extends DirectoryItem { private final String name; private final String desc; private final int access; /** * @param resource * The resource associated with the item. * @param local * Local name in tree. * @param name * Member name. * @param desc * Member descriptor. * @param access * Member access modifiers. */ public MemberItem(JavaResource resource, String local, String name, String desc, int access) { super(resource, local); this.name = name; this.desc = desc; this.access = access; } /** * @return Contained member name. */ public String getMemberName() { return name; } /** * @return Contained member descriptor. */ public String getMemberDesc() { return desc; } /** * @return Contained member access modifiers. */ public int getMemberAccess() { return access; } /** * @return {@code true} if the member represents a method. */ public boolean isMethod() { return desc.indexOf('(') == 0; } /** * @return {@code true} if the member represents a field. */ public boolean isField() { return !isMethod(); } @Override public int compareTo(DirectoryItem o) {<FILL_FUNCTION_BODY>} }
if(o instanceof MemberItem) { MemberItem c = (MemberItem) o; if (isField() && c.isMethod()) return -1; else if (isMethod() && c.isField()) return 1; return getLocalName().compareTo(c.getLocalName()); } return 1;
371
90
461
<methods>public void <init>(me.coley.recaf.workspace.JavaResource, java.lang.String) ,public void addChild(java.lang.String, me.coley.recaf.ui.controls.tree.DirectoryItem, boolean) ,public int compareTo(me.coley.recaf.ui.controls.tree.DirectoryItem) ,public void expandParents() ,public me.coley.recaf.ui.controls.tree.DirectoryItem getChild(java.lang.String, boolean) ,public me.coley.recaf.ui.controls.tree.DirectoryItem getDeepChild(java.lang.String) ,public java.lang.String getLocalName() ,public void removeSourceChild(TreeItem<me.coley.recaf.workspace.JavaResource>) <variables>private final non-sealed java.lang.String local,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToDir,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToLeaf
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/ui/controls/tree/MiscItem.java
MiscItem
compareTo
class MiscItem extends DirectoryItem { /** * @param resource * The resource associated with the item. * @param local * Local item name. */ public MiscItem(JavaResource resource, String local) { super(resource, local); } @Override public int compareTo(DirectoryItem o) {<FILL_FUNCTION_BODY>} }
if(o instanceof MiscItem) { MiscItem c = (MiscItem) o; return super.compareTo(o); } return 1;
100
48
148
<methods>public void <init>(me.coley.recaf.workspace.JavaResource, java.lang.String) ,public void addChild(java.lang.String, me.coley.recaf.ui.controls.tree.DirectoryItem, boolean) ,public int compareTo(me.coley.recaf.ui.controls.tree.DirectoryItem) ,public void expandParents() ,public me.coley.recaf.ui.controls.tree.DirectoryItem getChild(java.lang.String, boolean) ,public me.coley.recaf.ui.controls.tree.DirectoryItem getDeepChild(java.lang.String) ,public java.lang.String getLocalName() ,public void removeSourceChild(TreeItem<me.coley.recaf.workspace.JavaResource>) <variables>private final non-sealed java.lang.String local,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToDir,private final Map<java.lang.String,me.coley.recaf.ui.controls.tree.DirectoryItem> localToLeaf
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/AutoCompleteUtil.java
AutoCompleteUtil
matchSignatures
class AutoCompleteUtil { /** * A sorted list of class names for auto-completion, * including {@linkplain ClasspathUtil#getSystemClassNames() the system's} and * {@linkplain Workspace#getClassNames()} the current input's}. */ private static Set<String> cachedClassNames; /** * Computes and/or returns a sorted list of class names available for completion. */ private static Stream<String> classNames() { Set<String> systemClassNames = ClasspathUtil.getSystemClassNames(); Optional<Workspace> opt = Optional.ofNullable(Recaf.getCurrentWorkspace()); if (opt.isPresent()) { Set<String> inputClasses = opt.get().getClassNames(); int totalSize = inputClasses.size() + systemClassNames.size(); cachedClassNames = Collections.unmodifiableSet(Stream .concat(inputClasses.stream(), systemClassNames.stream()) .distinct() .sorted(Comparator.naturalOrder()) // Pre-sort to save some time .collect(Collectors.toCollection(() -> new LinkedHashSet<>(totalSize)))); } else { cachedClassNames = systemClassNames; } return cachedClassNames.stream(); } // =================================================================== // /** * Completes internal names. * * @param part * current token to complete on * * @return a list of internal name completions, ordered alphabetically */ public static List<String> internalName(String part) { String key = part.trim(); if (part.isEmpty()) return Collections.emptyList(); return classNames() .filter(name -> name.startsWith(key) && !name.equals(key)) .collect(Collectors.toList()); } /** * Completes descriptors. * * @param part * Current token to complete on * * @return List of descriptor completions, ordered alphabetically. */ public static List<String> descriptorName(String part) { part = part.trim(); if (part.isEmpty()) return Collections.emptyList(); StringBuilder prefixBuilder = new StringBuilder(1); StringBuilder keyBuilder = new StringBuilder(part.length() - 1); for (char c : part.toCharArray()) { if (keyBuilder.length() == 0) { // Separate the prefix (`L` or `[L` etc) from the actual token for matching if(c == 'L' || c == '[') { prefixBuilder.append(c); continue; } } else if (c == ';') { // Already completed, don't bother return Collections.emptyList(); } keyBuilder.append(c); } // No tokens to complete or no valid prefix found. if (prefixBuilder.length() == 0 || prefixBuilder.indexOf("L") == -1 || keyBuilder.length() == 0) return Collections.emptyList(); // String prefix = prefixBuilder.toString(); String key = keyBuilder.toString(); return classNames() .filter(name -> name.startsWith(key)) // .sorted() // Input stream is already sorted .map(name -> prefix + name + ";") // Re-adds the prefix and the suffix to the suggestions .collect(Collectors.toList()); } // =================================================================== // /** * Completes methods. * * @param line * Current line to complete. * * @return List of method completions, ordered alphabetically. */ public static List<String> method(String line) { return matchSignatures(line, c -> Arrays.stream(c.getDeclaredMethods()) .map(md -> md.getName().concat(Type.getMethodDescriptor(md))), cr -> ClassUtil.getMethodDefs(cr).stream() .map(p -> p.getKey() + p.getValue())); } /** * Completes fields. * @param line * Current line to complete. * * @return List of field completions, ordered alphabetically. */ public static List<String> field(String line) { return matchSignatures(line, c -> Arrays.stream(c.getDeclaredFields()) .map(fd -> fd.getName() + " " + Type.getType(fd.getType())), cr -> ClassUtil.getFieldDefs(cr).stream() .map(p -> p.getKey() + " " + p.getValue())); } /** * Completes signatures. * * @param line * Current line to complete. * @param signaturesFromClass * The function used to map {@link Class classes} to signatures. * @param signaturesFromNode * The function used to map {@link ClassReader}s to signatures. * * @return List of signature completions, ordered alphabetically. */ private static List<String> matchSignatures(String line, Function<Class<?>, Stream<String>> signaturesFromClass, Function<ClassReader, Stream<String>> signaturesFromNode) {<FILL_FUNCTION_BODY>} }
int dot = line.indexOf('.'); if (dot == -1) return Collections.emptyList(); String owner = line.substring(0, dot).trim(); String member = line.substring(dot + 1); // Assembler should have already run the parse chain, so we can fetch values Stream<String> signatures = null; // Attempt to check against workspace classes, fallback using runtime classes Optional<Workspace> opt = Optional.ofNullable(Recaf.getCurrentWorkspace()); if (opt.isPresent()) { Workspace in = opt.get(); ClassReader cr = in.getClassReader(owner); if (cr != null) signatures = signaturesFromNode.apply(cr); } if (signatures == null) { // Check runtime Optional<Class<?>> c = ClasspathUtil.getSystemClassIfExists(owner.replace('/', '.')); signatures = c.map(signaturesFromClass).orElse(null); } if (signatures != null) { return signatures .filter(s -> s.startsWith(member)) .sorted(Comparator.naturalOrder()) .collect(Collectors.toList()); } else { return Collections.emptyList(); }
1,351
332
1,683
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/ClasspathUtil.java
ClasspathUtil
scanBootstrapClasses
class ClasspathUtil { private static final String RECAF_CL = "me.coley.recaf.util.RecafClassLoader"; /** * The system classloader, provided by {@link ClassLoader#getSystemClassLoader()}. */ public static final ClassLoader scl = ClassLoader.getSystemClassLoader(); /** * A sorted, unmodifiable list of all class names */ private static final Set<String> systemClassNames; static { try { systemClassNames = Collections.unmodifiableSet(scanBootstrapClasses()); } catch (Exception ex) { throw new ExceptionInInitializerError(ex); } if (!areBootstrapClassesFound()) { Log.warn("Bootstrap classes are missing!"); } } /** * Check if a resource exists in the current classpath. * * @param path * Path to resource. * @return {@code true} if resource exists. {@code false} otherwise. */ public static boolean resourceExists(String path) { if (!path.startsWith("/")) path = "/" + path; return ClasspathUtil.class.getResource(path) != null; } /** * Fetch a resource as a stream in the current classpath. * * @param path * Path to resource. * * @return Stream of resource. */ public static InputStream resource(String path) { if (!path.startsWith("/")) path = "/" + path; return ClasspathUtil.class.getResourceAsStream(path); } /** * @return A sorted, unmodifiable list of all class names in the system classpath. */ public static Set<String> getSystemClassNames() { return systemClassNames; } /** * Checks if bootstrap classes is found in {@link #getSystemClassNames()}. * @return {@code true} if they do, {@code false} if they don't */ public static boolean areBootstrapClassesFound() { return checkBootstrapClassExists(getSystemClassNames()); } /** * Returns the class associated with the specified name, using * {@linkplain #scl the system class loader}. * <br> The class will not be initialized if it has not been initialized earlier. * <br> This is equivalent to {@code Class.forName(className, false, ClassLoader * .getSystemClassLoader())} * * @param className * The fully qualified class name. * * @return class object representing the desired class * * @throws ClassNotFoundException * if the class cannot be located by the system class loader * @see Class#forName(String, boolean, ClassLoader) */ public static Class<?> getSystemClass(String className) throws ClassNotFoundException { return forName(className, false, ClasspathUtil.scl); } /** * Check if a class by the given name exists and is accessible by the system classloader. * * @param name * The fully qualified class name. * * @return {@code true} if the class exists, {@code false} otherwise. */ public static boolean classExists(String name) { try { getSystemClass(name); return true; } catch(Exception ex) { return false; } } /** * Returns the class associated with the specified name, using * {@linkplain #scl the system class loader}. * <br> The class will not be initialized if it has not been initialized earlier. * <br> This is equivalent to {@code Class.forName(className, false, ClassLoader * .getSystemClassLoader())} * * @param className * The fully qualified class name. * * @return class object representing the desired class, * or {@code null} if it cannot be located by the system class loader * * @see Class#forName(String, boolean, ClassLoader) */ public static Optional<Class<?>> getSystemClassIfExists(String className) { try { return Optional.of(getSystemClass(className)); } catch (ClassNotFoundException | NullPointerException ex) { return Optional.empty(); } } /** * @param loader * Loader to check. * * @return {@code true} if loader belongs to Recaf. */ public static boolean isRecafLoader(ClassLoader loader) { // Why are all good features only available in JDK9+? // See java.lang.ClassLoader#getName(). if (loader == Recaf.class.getClassLoader()) { return true; } return loader != null && RECAF_CL.equals(loader.getClass().getName()); } /** * @param clazz * Class to check. * * @return {@code true} if class is loaded by Recaf. */ public static boolean isRecafClass(Class<?> clazz) { return isRecafLoader(clazz.getClassLoader()); } /** * Internal utility to check if bootstrap classes exist in a list of class names. */ private static boolean checkBootstrapClassExists(Collection<String> names) { String name = Object.class.getName(); return names.contains(name) || names.contains(name.replace('.', '/')); } private static Set<String> scanBootstrapClasses() throws Exception {<FILL_FUNCTION_BODY>} }
int vmVersion = VMUtil.getVmVersion(); Set<String> classes = new LinkedHashSet<>(4096, 1F); if (vmVersion < 9) { Method method = ClassLoader.class.getDeclaredMethod("getBootstrapClassPath"); method.setAccessible(true); Field field = URLClassLoader.class.getDeclaredField("ucp"); field.setAccessible(true); Object bootstrapClasspath = method.invoke(null); URLClassLoader dummyLoader = new URLClassLoader(new URL[0]); Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); // Change the URLClassPath in the dummy loader to the bootstrap one. field.set(dummyLoader, bootstrapClasspath); URL[] urls = dummyLoader.getURLs(); for (URL url : urls) { String protocol = url.getProtocol(); JarFile jar = null; if ("jar".equals(protocol)) { jar = ((JarURLConnection)url.openConnection()).getJarFile(); } else if ("file".equals(protocol)) { File file = new File(url.toURI()); if (!file.isFile()) continue; jar = new JarFile(file); } if (jar == null) continue; try { Enumeration<? extends JarEntry> enumeration = jar.entries(); while (enumeration.hasMoreElements()) { JarEntry entry = enumeration.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { classes.add(name.substring(0, name.length() - 6)); } } } finally { jar.close(); } } return classes; } else { Set<ModuleReference> references = ModuleFinder.ofSystem().findAll(); for (ModuleReference ref : references) { try (ModuleReader mr = ref.open()) { mr.list().forEach(s -> { classes.add(s.substring(0, s.length() - 6)); }); } } } return classes;
1,384
612
1,996
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/CollectionUtil.java
CollectionUtil
invert
class CollectionUtil { /** * Copies a collection into a set. * * @param original * Original collection. * @param <T> * Type of item in collection. * * @return Copied set. */ public static <T> Set<T> copySet(Collection<T> original) { return new HashSet<>(original); } /** * Copies a collection into a list. * * @param original * Original collection. * @param <T> * Type of item in collection. * * @return Copied list */ public static <T> Set<T> copyList(Collection<T> original) { return new HashSet<>(original); } /** * Copies a map into another map. * * @param original * Original collection. * @param <K> * Type of key items. * @param <V> * Type of value items. * * @return Copied map. */ public static <K, V> Map<K, V> copyMap(Map<K, V> original) { return new HashMap<>(original); } /** * @param original * Original map. * @param <K> * Type of key items. * @param <V> * Type of value items. * * @return Inverted map. */ public static <V, K> Map<V, K> invert(Map<K, V> original) {<FILL_FUNCTION_BODY>} }
Map<V, K> inv = new HashMap<>(); for (Map.Entry<K, V> entry : original.entrySet()) inv.put(entry.getValue(), entry.getKey()); return inv;
424
59
483
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/DefineUtil.java
DefineUtil
create
class DefineUtil { /** * Define a class of the give name via its bytecode. * * @param name * Name of the class to define. * @param bytecode * Bytecode of the class. * @return Instance of the class <i>(Default constructor)</i> * @throws ClassNotFoundException * Not thrown, only there to satisfy compiler enforced * exception. * @throws NoSuchMethodException * Thrown if there is no default constructor in the class. * @throws ReflectiveOperationException * Thrown if the constructor could not be called. */ public static Object create(String name, byte[] bytecode) throws ClassNotFoundException, NoSuchMethodException, ReflectiveOperationException {<FILL_FUNCTION_BODY>} /** * Define a class of the give name via its bytecode. * * @param name * Name of the class to define. * @param bytecode * Bytecode of the class. * @param argTypes * Constructor type arguments. * @param argValues * Constructor argument values. * @return Instance of the class. * @throws ClassNotFoundException * Not thrown, only there to satisfy compiler enforced * exception. * @throws NoSuchMethodException * Thrown if a constructor defined by the given type array does * not exist. * @throws ReflectiveOperationException * Thrown if the constructor could not be called. */ public static Object create(String name, byte[] bytecode, Class<?>[] argTypes, Object[] argValues) throws ClassNotFoundException, NoSuchMethodException, ReflectiveOperationException { Class<?> c = new ClassDefiner(name, bytecode).findClass(name); Constructor<?> con = c.getDeclaredConstructor(argTypes); return con.newInstance(argValues); } /** * Simple loader that exposes defineClass. Will only load the supplied * class. * * @author Matt */ static class ClassDefiner extends ClassLoader { private final byte[] bytecode; private final String name; public ClassDefiner(String name, byte[] bytecode) { super(ClasspathUtil.scl); this.name = name; this.bytecode = bytecode; } @Override public final Class<?> findClass(String name) throws ClassNotFoundException { if (this.name.equals(name)) { return defineClass(name, bytecode, 0, bytecode.length, null); } return super.findClass(name); } } }
Class<?> c = new ClassDefiner(name, bytecode).findClass(name); Constructor<?> con = c.getDeclaredConstructor(); return con.newInstance();
688
51
739
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/IllegalBytecodePatcherUtil.java
IllegalBytecodePatcherUtil
fix
class IllegalBytecodePatcherUtil { /** * @param classes * Successfully loaded classes in the input. * @param invalidClasses * The complete map of invalid classes in the input. * @param value * Raw bytecode of a class that crashes ASM. * * @return Modified bytecode, hopefully that yields valid ASM parsable class. * If any exception is thrown the original bytecode is returned. */ public static byte[] fix(Map<String, byte[]> classes, Map<String, byte[]> invalidClasses, byte[] value) {<FILL_FUNCTION_BODY>} }
try { ClassFile cf = new ClassFileReader().read(value); new IllegalStrippingTransformer(cf).transform(); // Patch oak classes (pre-java) // - CafeDude does this by default if (cf.getVersionMajor() < 45 ||(cf.getVersionMajor() == 45 && cf.getVersionMinor() <= 2)) { // Bump version into range where class file format uses full length values cf.setVersionMajor(45); cf.setVersionMinor(3); } return new ClassFileWriter().write(cf); } catch (Throwable t) { // Fallback, yield original value Log.error(t, "Failed to patch class"); return value; }
160
200
360
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/InsnUtil.java
InsnUtil
index
class InsnUtil { private static Field INSN_INDEX; /** * @param opcode * Instruction opcode. Should be of type * {@link org.objectweb.asm.tree.AbstractInsnNode#INSN}. * * @return value represented by the instruction. * * @throws IllegalArgumentException * Thrown if the opcode does not have a known value. */ public static int getValue(int opcode) { switch(opcode) { case ICONST_M1: return -1; case FCONST_0: case LCONST_0: case DCONST_0: case ICONST_0: return 0; case FCONST_1: case LCONST_1: case DCONST_1: case ICONST_1: return 1; case FCONST_2: case ICONST_2: return 2; case ICONST_3: return 3; case ICONST_4: return 4; case ICONST_5: return 5; default: throw new IllegalArgumentException("Invalid opcode, does not have a known value: " + opcode); } } /** * Calculate the index of an instruction. * * @param ain * instruction. * * @return Instruction index. */ public static int index(AbstractInsnNode ain) {<FILL_FUNCTION_BODY>} /** * Get the first insn connected to the given one. * * @param insn * instruction * * @return First insn in the insn-list. */ public static AbstractInsnNode getFirst(AbstractInsnNode insn) { while(insn.getPrevious() != null) insn = insn.getPrevious(); return insn; } static { try { INSN_INDEX = AbstractInsnNode.class.getDeclaredField("index"); INSN_INDEX.setAccessible(true); } catch(Exception ex) { Log.warn("Failed to fetch AbstractInsnNode index field!"); } } }
try { int v = (int) INSN_INDEX.get(ain); // Can return -1 if (v >= 0) return v; } catch(Exception ex) { /* Fail */ } // Fallback int index = 0; while(ain.getPrevious() != null) { ain = ain.getPrevious(); index++; } return index;
590
110
700
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/Java9Util.java
Java9Util
getClassModule
class Java9Util { private static final MethodHandle CLASS_MODULE; private static final MethodHandle CLASS_LOADER_MODULE; private static final MethodHandle METHOD_MODIFIERS; /** * Deny all constructions. */ private Java9Util() { } /** * @param klass {@link Class} to get module from. * @return {@link Module} of the class. */ static Module getClassModule(Class<?> klass) {<FILL_FUNCTION_BODY>} /** * @param loader {@link ClassLoader} to get module from. * @return {@link Module} of the class. */ static Module getLoaderModule(ClassLoader loader) { try { return (Module) CLASS_LOADER_MODULE.invokeExact(loader); } catch (Throwable t) { // That should never happen. throw new AssertionError(t); } } /** * @param method {@link Method} to change modifiers for. * @param modifiers new modifiers. */ static void setMethodModifiers(Method method, int modifiers) { try { METHOD_MODIFIERS.invokeExact(method, modifiers); } catch (Throwable t) { // That should never happen. throw new AssertionError(t); } } static { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); Unsafe unsafe = (Unsafe) field.get(null); field = Lookup.class.getDeclaredField("IMPL_LOOKUP"); MethodHandles.publicLookup(); Lookup lookup = (Lookup) unsafe.getObject(unsafe.staticFieldBase(field), unsafe.staticFieldOffset(field)); MethodType type = MethodType.methodType(Module.class); CLASS_MODULE = lookup.findVirtual(Class.class, "getModule", type); CLASS_LOADER_MODULE = lookup.findVirtual(ClassLoader.class, "getUnnamedModule", type); METHOD_MODIFIERS = lookup.findSetter(Method.class, "modifiers", Integer.TYPE); } catch (NoSuchMethodException | IllegalAccessException | NoSuchFieldException ex) { throw new ExceptionInInitializerError(ex); } } }
try { return (Module) CLASS_MODULE.invokeExact(klass); } catch (Throwable t) { // That should never happen. throw new AssertionError(t); }
606
55
661
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/MavenUtil.java
MavenUtil
verifyArtifactOnCentral
class MavenUtil { private static final String CENTRAL_URL = "https://repo1.maven.org/maven2/"; /** * Verifies that the maven artifact can be located on maven central. * * @param groupId * Maven artifact group. * @param artifactId * Maven artifact identifier. * @param version * Maven artifact version. * * @throws IOException * Thrown if at any point a faulty URL is generated or if there is no data to read <i>(No * such group/artifact/version existing on central)</i> */ public static void verifyArtifactOnCentral(String groupId, String artifactId, String version) throws IOException {<FILL_FUNCTION_BODY>} /** * @param groupId * Maven artifact group. * @param artifactId * Maven artifact identifier. * @param version * Maven artifact version. * * @return URL pointing to the online maven central artifact. * * @throws MalformedURLException * Thrown if any of the components result given result in a malformed generated URL. */ public static URL getArtifactUrl(String groupId, String artifactId, String version) throws MalformedURLException { return getArtifactUrl(groupId, artifactId, version, ""); } /** * @param groupId * Maven artifact group. * @param artifactId * Maven artifact identifier. * @param version * Maven artifact version. * @param suffix * Url suffix. * Used to specify other maven jars such as <i>"-source"</i> and <i>"-javadoc"</i> * * @return URL pointing to the online maven central artifact. * * @throws MalformedURLException * Thrown if any of the components result given result in a malformed generated URL. */ public static URL getArtifactUrl(String groupId, String artifactId, String version, String suffix) throws MalformedURLException { String url = CENTRAL_URL + groupId.replace(".", "/") + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + suffix + ".jar"; return new URL(url); } /** * @param groupId * Maven artifact group. * @param artifactId * Maven artifact identifier. * @param version * Maven artifact version. * * @return File pointing to the local artifact. */ public static Path getLocalArtifactUrl(String groupId, String artifactId, String version) { return getLocalArtifactUrl(groupId, artifactId, version, ""); } /** * @param groupId * Maven artifact group. * @param artifactId * Maven artifact identifier. * @param version * Maven artifact version. * @param suffix * File name suffix. * Used to specify other maven jars such as <i>"-source"</i> and <i>"-javadoc"</i> * * @return File pointing to the local artifact. */ public static Path getLocalArtifactUrl(String groupId, String artifactId, String version, String suffix) { String path = groupId.replace('.', separatorChar) + separator + artifactId + separator + version + separator + artifactId + "-" + version + suffix + ".jar"; return getMavenHome().resolve(path); } /** * @return Local directory containing downloaded maven artifacts. */ public static Path getMavenHome() { return Paths.get(System.getProperty("user.home"), ".m2", "repository"); } }
String groupUrl; String artifactUrl; String versionUrl; String jarUrl; // Test connection to maven central try { NetworkUtil.verifyUrlContent(CENTRAL_URL); } catch(MalformedURLException ex) { throw new IOException("Central URL is malformed, this should NOT happen", ex); } catch(IOException ex) { throw new IOException("Maven central is down or has migrated to a new URL: " + CENTRAL_URL, ex); } // Test connection to the group try { groupUrl = CENTRAL_URL + groupId.replace(".", "/") + "/"; NetworkUtil.verifyUrlContent(groupUrl); } catch(MalformedURLException ex) { throw new IOException("Invalid group, generates invalid URL: " + groupId, ex); } catch(IOException ex) { throw new IOException("Invalid group, does not exist on central: " + groupId, ex); } // Test connection to the artifact try { artifactUrl = groupUrl + artifactId + "/"; NetworkUtil.verifyUrlContent(artifactUrl); } catch(MalformedURLException ex) { throw new IOException("Invalid artifact, generates invalid URL: " + groupId + ":" + artifactId, ex); } catch(IOException ex) { throw new IOException("Invalid artifact, does not exist on central: " + groupId + ":" + artifactId, ex); } // Test connection to the version try { versionUrl = artifactUrl + version + "/"; NetworkUtil.verifyUrlContent(versionUrl); } catch(MalformedURLException ex) { throw new IOException("Invalid version, generates invalid URL: " + groupId + ":" + artifactId + ":" + version, ex); } catch(IOException ex) { throw new IOException("Invalid version, does not exist on central: " + groupId + ":" + artifactId + ":" + version, ex); } // Test connection to the full url try { jarUrl = versionUrl + artifactId + "-" + version + ".jar"; NetworkUtil.verifyUrlContent(jarUrl); // TODO: In some cases there are OS-specific jars: // https://repo1.maven.org/maven2/org/openjfx/javafx-controls/13-ea+10/ } catch(MalformedURLException ex) { throw new IOException("Failed to generate maven jar url: " + groupId + ":" + artifactId + ":" + version, ex); } catch(IOException ex) { throw new IOException("Jar does not match expected name on maven central: " + groupId + ":" + artifactId + ":" + version, ex); }
991
716
1,707
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/Natives.java
Natives
loadAttach
class Natives { private static final String VM_CLASS = "com.sun.tools.attach.VirtualMachine"; /** * Disallow public constructions. */ private Natives() { } /** * Attempts to load attach library. * * @return {@link Optional} result containing {@link Throwable} * if any error occurred. */ public static Optional<Throwable> loadAttach() {<FILL_FUNCTION_BODY>} }
if (ClasspathUtil.classExists(VM_CLASS)) return Optional.empty(); try { System.loadLibrary("attach"); try { Class.forName(VM_CLASS, true, null); return Optional.empty(); } catch (ClassNotFoundException ignored) { // expected, see below } if (VMUtil.getVmVersion() < 9) { Path toolsPath = Paths.get("lib", "tools.jar"); Path jrePath = Paths.get(System.getProperty("java.home")); Path maybePath = jrePath.resolve(toolsPath); if (Files.notExists(maybePath)) { // CD .. -> CD toolsPath maybePath = jrePath.getParent().resolve(toolsPath); } if (Files.notExists(maybePath)) { return Optional.of(new FileNotFoundException("Could not locate tools.jar")); } ClassLoader cl = Natives.class.getClassLoader(); if (!(cl instanceof URLClassLoader)) { cl = ClassLoader.getSystemClassLoader(); } VMUtil.addURL(cl, maybePath.toUri().toURL()); } return Optional.empty(); } catch (UnsatisfiedLinkError ignored) { // attach library not found, that's ok. return Optional.empty(); } catch (Throwable t) { return Optional.of(t); }
128
360
488
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/NetworkUtil.java
NetworkUtil
verifyUrlContent
class NetworkUtil { /** * Timeout for URL verification. One second should be enough to do a simple length check. */ private static final int TIMEOUT = 1000; /** * Verify that the URL points to a valid file. * * @param url * The URL to verify. * * @throws IOException * Thrown if the url times out or there is no content at the URL. * @throws MalformedURLException * Thrown if the url given is not formatted properly. */ public static void verifyUrlContent(String url) throws MalformedURLException, IOException { verifyUrlContent(new URL(url)); } /** * Verify that the URL points to a valid file. * * @param url * The URL to verify. * * @throws IOException * When the url times out or there is no content at the URL. */ public static void verifyUrlContent(URL url) throws IOException {<FILL_FUNCTION_BODY>} }
try { URLConnection conn = url.openConnection(); conn.setReadTimeout(TIMEOUT); conn.setConnectTimeout(TIMEOUT); // Online check if(url.toString().startsWith("http")) { HttpURLConnection hconn = (HttpURLConnection) conn; hconn.setRequestMethod("GET"); hconn.connect(); // Request must be a "200 OK" int response = hconn.getResponseCode(); if(response != 200) throw new IOException("File at URL \"" + url + "\" could not be loaded, gave response code: " + response); } // Local url check fallback else if (conn.getContentLength() == -1) throw new IOException("File at URL \"" + url + "\" does not exist!"); } catch(Exception ex) { throw new IOException("File at URL \"" + url + "\" could not be reached!"); }
266
252
518
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/ProcessUtil.java
ProcessUtil
waitFor
class ProcessUtil { /** * Deny all constructions. */ private ProcessUtil() { } /** * Waits for process to finish. * * @param process * Process to wait for. * @param timeout * The maximum time to wait. * @param unit * The time unit of the {@code timeout} argument. * * @return {@code true} if process was terminated. */ public static boolean waitFor(Process process, long timeout, TimeUnit unit) {<FILL_FUNCTION_BODY>} /** * Reads <i>stderr</i> of the process. * * @param process * Process to read error from. * @return * Content of process's <i>stderr</i>. * * @throws IOException * When any I/O error occur. */ public static List<String> readProcessError(Process process) throws IOException { List<String> result = new LinkedList<>(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { result.add(line); } } return result; } }
long now = System.currentTimeMillis(); while (timeout > 0L) { try { return process.waitFor(timeout, unit); } catch (InterruptedException ex) { timeout -= (System.currentTimeMillis() - now); } } return false;
351
79
430
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/ReflectUtil.java
ReflectUtil
quietNew
class ReflectUtil { /** * @param type * Class to construct. * @param argTypes * Argument types. * @param args * Argument values. * @param <T> * Assumed class type. * * @return New instance of class. */ public static <T> T quietNew(Class<T> type, Class<?>[] argTypes, Object[] args) {<FILL_FUNCTION_BODY>} }
try { Constructor<T> constructor = type.getDeclaredConstructor(argTypes); constructor.setAccessible(true); return constructor.newInstance(args); } catch (ReflectiveOperationException ex) { throw new IllegalStateException("Constructor failure: " + type.getName(), ex); }
130
84
214
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/RegexUtil.java
RegexUtil
wordSplit
class RegexUtil { private static final Pattern WORD = new Pattern("\\s*(\\S+)\\s*"); private static final String[] EMPTY = new String[0]; private static final Map<String, Pattern> PATTERNS = new HashMap<>(); /** * @param text * Some text containing at least one word character. * * @return The first sequence of connected word characters. * {@code null} if no word characters are found. */ public static String getFirstWord(String text) { Matcher m = WORD.matcher(text); if(m.find()) return m.group(1); return null; } /** * @param text * Some text containing at least one word character. * * @return The last sequence of connected word characters. * {@code null} if no word characters are found. */ public static String getLastWord(String text) { Matcher m = WORD.matcher(text); String f = null; while(m.find()) f = m.group(0); return f; } /** * @param pattern * Pattern to match. * @param text * Some text containing a match for the given pattern. * * @return First matching sequence from the text. */ public static String getFirstToken(String pattern, String text) { Matcher m = getMatcher(pattern, text); if(m.find()) return m.group(0); return null; } /** * @param pattern * Pattern to match. * @param text * Some text containing at least one word character. * * @return The last sequence of connected word characters. {@code null} if no word characters * are found. */ public static String getLastToken(String pattern, String text) { Matcher m = getMatcher(pattern, text); String f = null; while(m.find()) f = m.group(0); return f; } /** * @param pattern * Pattern to match. * @param text * Some text containing at least one word character. * * @return Index of the first match. */ public static int indexOf(String pattern, String text) { Matcher m = getMatcher(pattern, text); if(m.find()) return text.indexOf(m.group(0)); return -1; } /** * @param pattern * Pattern to match. * @param text * Some text containing a match for the given pattern. * * @return Text matcher. */ public static Matcher getMatcher(String pattern, String text) { return new Pattern(pattern).matcher(text); } /** * @param text * Text to split, unless splitter chars reside in a single-quote range. * * @return Matched words. */ public static String[] wordSplit(String text) {<FILL_FUNCTION_BODY>} /** * @param text * Text to split. * @param pattern * Pattern to match words of. * * @return Matched words. */ public static String[] allMatches(String text, String pattern) { List<String> list = new ArrayList<>(); Matcher m = getMatcher(pattern, text); while(m.find()) list.add(m.group(0)); return list.toArray(EMPTY); } /** * Creates new {@link Pattern} or gets it from cache. * * @param regex pattern's regex * @return {@link Pattern} */ public static Pattern pattern(String regex) { return PATTERNS.computeIfAbsent(regex, Pattern::new); } /** * Checks if the entire input matches a pattern. * * @param pattern pattern * @param input an input to verify * * @return {@code true} if input matches. */ public static boolean matches(String pattern, String input) { return pattern(pattern).matches(input); } }
List<String> list = new ArrayList<>(); Matcher m = getMatcher("([^\\']\\S*|\\'.+?\\')\\s*", text); while(m.find()) { String word = m.group(1); if (word.matches("'.+'")) word = word.substring(1, word.length() - 1); list.add(word); } return list.toArray(EMPTY);
1,097
125
1,222
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/Resource.java
Resource
getFileName
class Resource { private final String path; private final boolean internal; /** * Create a resource wrapper. * * @param path * Path to resource. * @param internal * {@code true} if the resource is in the classpath, {@code false} if it is external. */ private Resource(String path, boolean internal) { this.path = path; this.internal = internal; } /** * Create an internal resource. * @param path Path to resource. * @return Internal resource wrapper. */ public static Resource internal(String path) { return new Resource(path, true); } /** * Create an external resource. * @param path Path to resource. * @return External resource wrapper. */ public static Resource external(String path) { return new Resource(path, false); } /** * @return Resource path. */ public String getPath() { return path; } /** * @return {@code true} if the resource is in the classpath, {@code false} if it is external. */ public boolean isInternal() { return internal; } /** * @return Name of resource file. */ public String getFileName() {<FILL_FUNCTION_BODY>} /** * Creates a URL path to resource, * * @return URL path to resource. * * @throws IOException When the path cannot be created. */ public URL getURL() throws IOException { return new File(getPath()).toURI().toURL(); } }
String name = getPath(); int sep = name.lastIndexOf('/'); if (sep > 0) name = name.substring(sep + 1); return name;
404
50
454
<no_super_class>