repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/ActionsIoUtils.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.io;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import com.google.gson.stream.JsonWriter;
import gumtreediff.actions.model.Action;
import gumtreediff.actions.model.Delete;
import gumtreediff.actions.model.Insert;
import gumtreediff.actions.model.Move;
import gumtreediff.actions.model.Update;
import gumtreediff.io.TreeIoUtils.AbstractSerializer;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
public final class ActionsIoUtils {
private ActionsIoUtils() {
}
public static ActionSerializer getSerial(TreeContext sctx, List<Action> actions,
MappingStore mappings) throws IOException {
return new ActionSerializer(sctx, mappings, actions) {
@Override
protected ActionFormatter newFormatter(TreeContext ctx, Writer writer) throws Exception {
return new XmlFormatter(ctx, writer);
}
};
}
public static ActionSerializer toText(TreeContext sctx, List<Action> actions,
MappingStore mappings) throws IOException {
return new ActionSerializer(sctx, mappings, actions) {
@Override
protected ActionFormatter newFormatter(TreeContext ctx, Writer writer) throws Exception {
return new TextFormatter(ctx, writer);
}
};
}
public static ActionSerializer toXml(TreeContext sctx, List<Action> actions,
MappingStore mappings) throws IOException {
return new ActionSerializer(sctx, mappings, actions) {
@Override
protected ActionFormatter newFormatter(TreeContext ctx, Writer writer) throws Exception {
return new XmlFormatter(ctx, writer);
}
};
}
public static ActionSerializer toJson(TreeContext sctx, List<Action> actions,
MappingStore mappings) throws IOException {
return new ActionSerializer(sctx, mappings, actions) {
@Override
protected ActionFormatter newFormatter(TreeContext ctx, Writer writer) throws Exception {
return new JsonFormatter(ctx, writer);
}
};
}
public abstract static class ActionSerializer extends AbstractSerializer {
final TreeContext context;
final MappingStore mappings;
final List<Action> actions;
ActionSerializer(TreeContext context, MappingStore mappings, List<Action> actions) {
this.context = context;
this.mappings = mappings;
this.actions = actions;
}
protected abstract ActionFormatter newFormatter(TreeContext ctx, Writer writer) throws Exception;
@Override
public void writeTo(Writer writer) throws Exception {
ActionFormatter fmt = newFormatter(context, writer);
// Start the output
fmt.startOutput();
// Write the matches
fmt.startMatches();
for (Mapping m: mappings) {
fmt.match(m.getFirst(), m.getSecond());
}
fmt.endMatches();
// Write the actions
fmt.startActions();
for (Action a : actions) {
ITree src = a.getNode();
if (a instanceof Move) {
ITree dst = mappings.getDst(src);
fmt.moveAction(src, dst.getParent(), ((Move) a).getPosition());
} else if (a instanceof Update) {
ITree dst = mappings.getDst(src);
fmt.updateAction(src, dst);
} else if (a instanceof Insert) {
ITree dst = a.getNode();
if (dst.isRoot())
fmt.insertRoot(src);
else
fmt.insertAction(src, dst.getParent(), dst.getParent().getChildPosition(dst));
} else if (a instanceof Delete) {
fmt.deleteAction(src);
}
}
fmt.endActions();
// Finish up
fmt.endOutput();
}
}
interface ActionFormatter {
void startOutput() throws Exception;
void endOutput() throws Exception;
void startMatches() throws Exception;
void match(ITree srcNode, ITree destNode) throws Exception;
void endMatches() throws Exception;
void startActions() throws Exception;
void insertRoot(ITree node) throws Exception;
void insertAction(ITree node, ITree parent, int index) throws Exception;
void moveAction(ITree src, ITree dst, int index) throws Exception;
void updateAction(ITree src, ITree dst) throws Exception;
void deleteAction(ITree node) throws Exception;
void endActions() throws Exception;
}
static class XmlFormatter implements ActionFormatter {
final TreeContext context;
final XMLStreamWriter writer;
XmlFormatter(TreeContext context, Writer w) throws XMLStreamException {
XMLOutputFactory f = XMLOutputFactory.newInstance();
writer = new IndentingXMLStreamWriter(f.createXMLStreamWriter(w));
this.context = context;
}
@Override
public void startOutput() throws XMLStreamException {
writer.writeStartDocument();
}
@Override
public void endOutput() throws XMLStreamException {
writer.writeEndDocument();
}
@Override
public void startMatches() throws XMLStreamException {
writer.writeStartElement("matches");
}
@Override
public void match(ITree srcNode, ITree destNode) throws XMLStreamException {
writer.writeEmptyElement("match");
writer.writeAttribute("src", Integer.toString(srcNode.getId()));
writer.writeAttribute("dest", Integer.toString(destNode.getId()));
}
@Override
public void endMatches() throws XMLStreamException {
writer.writeEndElement();
}
@Override
public void startActions() throws XMLStreamException {
writer.writeStartElement("actions");
}
@Override
public void insertRoot(ITree node) throws Exception {
start(Insert.class, node);
end(node);
}
@Override
public void insertAction(ITree node, ITree parent, int index) throws Exception {
start(Insert.class, node);
writer.writeAttribute("parent", Integer.toString(parent.getId()));
writer.writeAttribute("at", Integer.toString(index));
end(node);
}
@Override
public void moveAction(ITree src, ITree dst, int index) throws XMLStreamException {
start(Move.class, src);
writer.writeAttribute("parent", Integer.toString(dst.getId()));
writer.writeAttribute("at", Integer.toString(index));
end(src);
}
@Override
public void updateAction(ITree src, ITree dst) throws XMLStreamException {
start(Update.class, src);
writer.writeAttribute("label", dst.getLabel());
end(src);
}
@Override
public void deleteAction(ITree node) throws Exception {
start(Delete.class, node);
end(node);
}
@Override
public void endActions() throws XMLStreamException {
writer.writeEndElement();
}
private void start(Class<? extends Action> name, ITree src) throws XMLStreamException {
writer.writeEmptyElement(name.getSimpleName().toLowerCase());
writer.writeAttribute("tree", Integer.toString(src.getId()));
}
private void end(ITree node) throws XMLStreamException {
// writer.writeEndElement();
}
}
static class TextFormatter implements ActionFormatter {
final Writer writer;
final TreeContext context;
public TextFormatter(TreeContext ctx, Writer writer) {
this.context = ctx;
this.writer = writer;
}
@Override
public void startOutput() throws Exception {
}
@Override
public void endOutput() throws Exception {
}
@Override
public void startMatches() throws Exception {
}
@Override
public void match(ITree srcNode, ITree destNode) throws Exception {
write("Match %s to %s", toS(srcNode), toS(destNode));
}
@Override
public void endMatches() throws Exception {
}
@Override
public void startActions() throws Exception {
}
@Override
public void insertRoot(ITree node) throws Exception {
write("Insert root %s", toS(node));
}
@Override
public void insertAction(ITree node, ITree parent, int index) throws Exception {
write("Insert %s into %s at %d", toS(node), toS(parent), index);
}
@Override
public void moveAction(ITree src, ITree dst, int position) throws Exception {
write("Move %s into %s at %d", toS(src), toS(dst), position);
}
@Override
public void updateAction(ITree src, ITree dst) throws Exception {
write("Update %s to %s", toS(src), dst.getLabel());
}
@Override
public void deleteAction(ITree node) throws Exception {
write("Delete %s", toS(node));
}
@Override
public void endActions() throws Exception {
}
private void write(String fmt, Object... objs) throws IOException {
writer.append(String.format(fmt, objs));
writer.append("\n");
}
private String toS(ITree node) {
return String.format("%s(%d)", node.toPrettyString(context), node.getId());
}
}
static class JsonFormatter implements ActionFormatter {
private final JsonWriter writer;
JsonFormatter(TreeContext ctx, Writer writer) {
this.writer = new JsonWriter(writer);
this.writer.setIndent(" ");
}
@Override
public void startOutput() throws IOException {
writer.beginObject();
}
@Override
public void endOutput() throws IOException {
writer.endObject();
}
@Override
public void startMatches() throws Exception {
writer.name("matches").beginArray();
}
@Override
public void match(ITree srcNode, ITree destNode) throws Exception {
writer.beginObject();
writer.name("src").value(srcNode.getId());
writer.name("dest").value(destNode.getId());
writer.endObject();
}
@Override
public void endMatches() throws Exception {
writer.endArray();
}
@Override
public void startActions() throws IOException {
writer.name("actions").beginArray();
}
@Override
public void insertRoot(ITree node) throws IOException {
start(Insert.class, node);
end(node);
}
@Override
public void insertAction(ITree node, ITree parent, int index) throws IOException {
start(Insert.class, node);
writer.name("parent").value(parent.getId());
writer.name("at").value(index);
end(node);
}
@Override
public void moveAction(ITree src, ITree dst, int index) throws IOException {
start(Move.class, src);
writer.name("parent").value(dst.getId());
writer.name("at").value(index);
end(src);
}
@Override
public void updateAction(ITree src, ITree dst) throws IOException {
start(Update.class, src);
writer.name("label").value(dst.getLabel());
end(src);
}
@Override
public void deleteAction(ITree node) throws IOException {
start(Delete.class, node);
end(node);
}
private void start(Class<? extends Action> name, ITree src) throws IOException {
writer.beginObject();
writer.name("action").value(name.getSimpleName().toLowerCase());
writer.name("tree").value(src.getId());
}
private void end(ITree node) throws IOException {
writer.endObject();
}
@Override
public void endActions() throws Exception {
writer.endArray();
}
}
}
| 13,835
| 31.176744
| 105
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/DetailedDotFormatter.java
|
package gumtreediff.io;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import gumtreediff.actions.model.Action;
import gumtreediff.actions.model.Delete;
import gumtreediff.actions.model.Insert;
import gumtreediff.actions.model.Move;
import gumtreediff.actions.model.Update;
import gumtreediff.io.TreeIoUtils.TreeFormatterAdapter;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
public class DetailedDotFormatter extends TreeFormatterAdapter {
protected final Writer writer;
protected MappingStore map;
protected HashMap<Integer, Integer> mapping = new HashMap<>();
protected HashMap<Integer, Action> id2acts = new HashMap<>();
protected HashMap<Integer, Action> updates = new HashMap<>();
protected HashMap<Integer, Action> deletes = new HashMap<>();
protected HashMap<Integer, Action> moves = new HashMap<>();
protected HashMap<Integer, Action> inserts = new HashMap<>();
protected Boolean isSrc;
protected DetailedDotFormatter(Writer w, TreeContext ctx, MappingStore m ,
List<Action> acts, Boolean Ifsrc) {
super(ctx);
writer = w;
isSrc = Ifsrc;
map = m;
for(Mapping map : map) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
mapping.put(src.getId(), dst.getId());
}
System.out.println("mapSize:"+mapping.size());
System.out.println("ActionSize:" + acts.size());
for (Action a : acts) {
ITree node = a.getNode();
id2acts.put(node.getId(), a);
if (a instanceof Move) {
moves.put(node.getId(), a);
} else if (a instanceof Update) {
updates.put(node.getId(), a);
} else if (a instanceof Insert) {
inserts.put(node.getId(), a);
} else if (a instanceof Delete) {
deletes.put(node.getId(), a);
}
}
}
public String formate(String label) {
if (label.contains("\"") || label.contains("\\s"))
label = label.replaceAll("\"", "").replaceAll("\\s", "").replaceAll("\\\\", "");
if (label.contains("\"") || label.contains("\\n"))
label = label.replaceAll("\"", "").replaceAll("(\r\n|\n)", "");
if (label.length() > 30)
label = label.substring(0, 30);
return label;
}
@Override
public void startSerialization() throws Exception {
writer.write("digraph G {\n");
}
@Override
public void startTree(ITree tree) throws Exception {
int id = tree.getId();
String label = id+" "+context.getTypeLabel(tree);
if (tree.hasLabel())
label = label+":"+tree.getLabel();
label = formate(label);
Action a = id2acts.get(id);
int start_line = tree.getLine();
int end_line = tree.getLastLine();
int start_col = tree.getColumn();
int end_col = tree.getLastColumn();
String location = String.valueOf(start_line)+","+String.valueOf(end_line)+","+
String.valueOf(start_col)+","+String.valueOf(end_col);
if(isSrc) {
if(mapping.get(id)!=null){
if (a instanceof Delete) {
writer.write(id + " [label=\"" + label+ "\\n"+location+
"\", style=dashed,"+ " color=red];\n");
}else if (a instanceof Update) {
Update upt = (Update)a;
writer.write(id + " [label=\"" + label+"\\n update to " +formate(upt.getValue())
+"\\n"+location+ "\", color=red];\n");
}else if (a instanceof Move) {
Move mov = (Move)a;
int parId = mov.getParent().getId();
int pos = mov.getPosition();
if(id!=mov.getNode().getId())
throw new Exception("not equal mvoe id");
writer.write(id + " [label=\"" + label+"\\n move to "+parId+","+pos
+"\\n"+location+ "\", color=red];\n");
}else
writer.write(id + " [label=\"" + label +"\\n"+location+ "\", color=red];\n");
}else if(mapping.get(id)==null){
if (a instanceof Delete) {
writer.write(id + " [label=\"" + label+ "\\n"+location+ "\", style=dashed];\n");
}else
writer.write(id + " [label=\"" + label + "\\n"+location+ "\", color=red];\n");
}
}else if(mapping.containsValue(id)) {
if (a instanceof Insert) {
Insert ins = (Insert)a;
int parId = ins.getParent().getId();
int pos = ins.getPosition();
if(id!=ins.getNode().getId())
throw new Exception("not equal mvoe id");
writer.write(id + " [label=\"" + label+"\\n insert to "+parId+","+pos
+"\\n"+location+ "\", color=red];\n");
}else
writer.write(id + " [label=\"" + label +"\\n"+location+ "\", color=red];\n");
}else {
if (a instanceof Insert) {
Insert ins = (Insert)a;
int parId = ins.getParent().getId();
int pos = ins.getPosition();
if(id!=ins.getNode().getId())
throw new Exception("not equal mvoe id");
writer.write(id + " [label=\"" + label+"\\n insert to "+parId+","+pos
+"\\n"+location+ "\", color=red];\n");
}else
writer.write(id + " [label=\"" + label +"\\n"+location+ "\"];\n");
}
if (tree.getParent() != null)
writer.write(tree.getParent().getId() + " -> " + id + ";\n");
}
@Override
public void stopSerialization() throws Exception {
writer.write("}");
}
}
| 5,887
| 39.606897
| 92
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/DirectoryComparator.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.io;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import gumtreediff.utils.Pair;
public class DirectoryComparator {
private Path src;
public Path getSrc() {
return src;
}
public Path getDst() {
return dst;
}
private Path dst;
private List<Pair<File, File>> modifiedFiles;
private Set<File> deletedFiles;
private Set<File> addedFiles;
private boolean dirMode = true;
public DirectoryComparator(String src, String dst) {
modifiedFiles = new ArrayList<>();
addedFiles = new HashSet<>();
deletedFiles = new HashSet<>();
this.src = Paths.get(src);
this.dst = Paths.get(dst);
if (!Files.exists(this.src) || !Files.exists(this.dst))
throw new RuntimeException();
else {
if (!Files.isDirectory(this.src) && !Files.isDirectory(this.dst)) {
this.modifiedFiles.add(new Pair<>(this.src.toFile(), this.dst.toFile()));
this.src = this.src.getParent();
this.dst = this.dst.getParent();
this.dirMode = false;
} else if (!(Files.isDirectory(this.src) && Files.isDirectory(this.dst))) {
throw new RuntimeException();
}
}
}
public void compare() {
if (!dirMode) return;
AllFilesVisitor vSrc = new AllFilesVisitor(src);
AllFilesVisitor vDst = new AllFilesVisitor(dst);
try {
Files.walkFileTree(src, vSrc);
Files.walkFileTree(dst, vDst);
Set<String> addedFiles = new HashSet<>();
addedFiles.addAll(vDst.files);
addedFiles.removeAll(vSrc.files);
for (String file : addedFiles) this.addedFiles.add(toDstFile(file));
Set<String> deletedFiles = new HashSet<>();
deletedFiles.addAll(vSrc.files);
deletedFiles.removeAll(vDst.files);
for (String file : deletedFiles) this.deletedFiles.add(toSrcFile(file));
Set<String> commonFiles = new HashSet<>();
commonFiles.addAll(vSrc.files);
commonFiles.retainAll(vDst.files);
for (String file : commonFiles)
if (hasChanged(file, file))
modifiedFiles.add(new Pair<>(toSrcFile(file), toDstFile(file)));
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isDirMode() {
return dirMode;
}
public List<Pair<File, File>> getModifiedFiles() {
return modifiedFiles;
}
public Set<File> getDeletedFiles() {
return deletedFiles;
}
public Set<File> getAddedFiles() {
return addedFiles;
}
private File toSrcFile(String s) {
return new File(src.toFile(), s);
}
private File toDstFile(String s) {
return new File(dst.toFile(), s);
}
public boolean hasChanged(String s1, String s2) throws IOException {
File f1 = toSrcFile(s1);
File f2 = toDstFile(s2);
long l1 = Files.size(f1.toPath());
long l2 = Files.size(f2.toPath());
if (l1 != l2) return true;
else {
try (DataInputStream dis1 = new DataInputStream(new FileInputStream(f1));
DataInputStream dis2 = new DataInputStream(new FileInputStream(f2))) {
int c1, c2;
while ((c1 = dis1.read()) != -1) {
c2 = dis2.read();
if (c1 != c2)
return true;
}
return false;
}
}
}
public static class AllFilesVisitor extends SimpleFileVisitor<Path> {
private Set<String> files = new HashSet<>();
private Path root;
public AllFilesVisitor(Path root) {
this.root = root;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!file.getFileName().startsWith("."))
files.add(root.relativize(file).toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return (dir.getFileName().toString().startsWith("."))
? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
}
}
}
| 5,639
| 29.819672
| 99
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/Indentation.java
|
/*
* Copyright (c) 2006, John Kristian
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of StAX-Utils nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package gumtreediff.io;
/**
* Characters that represent line breaks and indentation. These are represented
* as String-valued JavaBean properties.
*/
public interface Indentation {
/** Two spaces; the default indentation. */
public static final String DEFAULT_INDENT = " ";
/**
* Set the characters used for one level of indentation. The default is
* {@link #DEFAULT_INDENT}. "\t" is a popular alternative.
*/
void setIndent(String indent);
/** The characters used for one level of indentation. */
String getIndent();
/**
* "\n"; the normalized representation of end-of-line in <a
* href="http://www.w3.org/TR/xml11/#sec-line-ends">XML</a>.
*/
public static final String NORMAL_END_OF_LINE = "\n";
/**
* Set the characters that introduce a new line. The default is
* {@link #NORMAL_END_OF_LINE}.
* {@link IndentingXMLStreamWriter#getLineSeparator}() is a popular
* alternative.
*/
public void setNewLine(String newLine);
/** The characters that introduce a new line. */
String getNewLine();
}
| 2,733
| 38.057143
| 80
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/IndentingXMLStreamWriter.java
|
/*
* Copyright (c) 2006, John Kristian
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of StAX-Utils nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package gumtreediff.io;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* A filter that indents an XML stream. To apply it, construct a filter that
* contains another {@link XMLStreamWriter}, which you pass to the constructor.
* Then call methods of the filter instead of the contained stream. For example:
*
* <pre>
* {@link XMLStreamWriter} stream = ...
* stream = new {@link IndentingXMLStreamWriter}(stream);
* stream.writeStartDocument();
* ...
* </pre>
*
* <p>
* The filter inserts characters to format the document as an outline, with
* nested elements indented. Basically, it inserts a line break and whitespace
* before:
* <ul>
* <li>each DTD, processing instruction or comment that's not preceded by data</li>
* <li>each starting tag that's not preceded by data</li>
* <li>each ending tag that's preceded by nested elements but not data</li>
* </ul>
* This works well with 'data-oriented' XML, wherein each element contains
* either data or nested elements but not both. It can work badly with other
* styles of XML. For example, the data in a 'mixed content' document are apt to
* be polluted with indentation characters.
*
* <p>
* Indentation can be adjusted by setting the newLine and indent properties. But
* set them to whitespace only, for best results. Non-whitespace is apt to cause
* problems, for example when this class attempts to insert newLine before the
* root element.
*
* @author <a href="mailto:jk2006@engineer.com">John Kristian</a>
*/
public class IndentingXMLStreamWriter extends StreamWriterDelegate implements Indentation {
public IndentingXMLStreamWriter(XMLStreamWriter out) {
super(out);
}
/** How deeply nested the current scope is. The root element is depth 1. */
private int depth = 0; // document scope
/** stack[depth] indicates what's been written into the current scope. */
private int[] stack = new int[] { 0, 0, 0, 0 }; // nothing written yet
private static final int WROTE_MARKUP = 1;
private static final int WROTE_DATA = 2;
private String indent = DEFAULT_INDENT;
private String newLine = NORMAL_END_OF_LINE;
/** newLine followed by copies of indent. */
private char[] linePrefix = null;
@Override
public void setIndent(String indent) {
if (!indent.equals(this.indent)) {
this.indent = indent;
linePrefix = null;
}
}
@Override
public String getIndent() {
return indent;
}
@Override
public void setNewLine(String newLine) {
if (!newLine.equals(this.newLine)) {
this.newLine = newLine;
linePrefix = null;
}
}
/**
* @return System.getProperty("line.separator"); or
* {@link #NORMAL_END_OF_LINE} if that fails.
*/
public static String getLineSeparator() {
try {
return System.getProperty("line.separator");
} catch (SecurityException ignored) {
ignored.printStackTrace();
}
return NORMAL_END_OF_LINE;
}
@Override
public String getNewLine() {
return newLine;
}
@Override
public void writeStartDocument() throws XMLStreamException {
beforeMarkup();
out.writeStartDocument();
afterMarkup();
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
beforeMarkup();
out.writeStartDocument(version);
afterMarkup();
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
beforeMarkup();
out.writeStartDocument(encoding, version);
afterMarkup();
}
@Override
public void writeDTD(String dtd) throws XMLStreamException {
beforeMarkup();
out.writeDTD(dtd);
afterMarkup();
}
@Override
public void writeProcessingInstruction(String target) throws XMLStreamException {
beforeMarkup();
out.writeProcessingInstruction(target);
afterMarkup();
}
@Override
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
beforeMarkup();
out.writeProcessingInstruction(target, data);
afterMarkup();
}
@Override
public void writeComment(String data) throws XMLStreamException {
beforeMarkup();
out.writeComment(data);
afterMarkup();
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
beforeMarkup();
out.writeEmptyElement(localName);
afterMarkup();
}
@Override
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
beforeMarkup();
out.writeEmptyElement(namespaceURI, localName);
afterMarkup();
}
@Override
public void writeEmptyElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException {
beforeMarkup();
out.writeEmptyElement(prefix, localName, namespaceURI);
afterMarkup();
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
beforeStartElement();
out.writeStartElement(localName);
afterStartElement();
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
beforeStartElement();
out.writeStartElement(namespaceURI, localName);
afterStartElement();
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException {
beforeStartElement();
out.writeStartElement(prefix, localName, namespaceURI);
afterStartElement();
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
out.writeCharacters(text);
afterData();
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
out.writeCharacters(text, start, len);
afterData();
}
@Override
public void writeCData(String data) throws XMLStreamException {
out.writeCData(data);
afterData();
}
@Override
public void writeEntityRef(String name) throws XMLStreamException {
out.writeEntityRef(name);
afterData();
}
@Override
public void writeEndElement() throws XMLStreamException {
beforeEndElement();
out.writeEndElement();
afterEndElement();
}
@Override
public void writeEndDocument() throws XMLStreamException {
try {
while (depth > 0) {
writeEndElement(); // indented
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
out.writeEndDocument();
afterEndDocument();
}
/** Prepare to write markup, by writing a new line and indentation. */
protected void beforeMarkup() {
int soFar = stack[depth];
if ((soFar & WROTE_DATA) == 0 // no data in this scope
&& (depth > 0 || soFar != 0)) {
try {
writeNewLine(depth);
if (depth > 0 && getIndent().length() > 0) {
afterMarkup(); // indentation was written
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** Note that markup or indentation was written. */
protected void afterMarkup() {
stack[depth] |= WROTE_MARKUP;
}
/** Note that data were written. */
protected void afterData() {
stack[depth] |= WROTE_DATA;
}
/** Prepare to start an element, by allocating stack space. */
protected void beforeStartElement() {
beforeMarkup();
if (stack.length <= depth + 1) {
// Allocate more space for the stack:
int[] newStack = new int[stack.length * 2];
System.arraycopy(stack, 0, newStack, 0, stack.length);
stack = newStack;
}
stack[depth + 1] = 0; // nothing written yet
}
/** Note that an element was started. */
protected void afterStartElement() {
afterMarkup();
++depth;
}
/** Prepare to end an element, by writing a new line and indentation. */
protected void beforeEndElement() {
if (depth > 0 && stack[depth] == WROTE_MARKUP) { // but not data
try {
writeNewLine(depth - 1);
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
}
/** Note that an element was ended. */
protected void afterEndElement() {
if (depth > 0) {
--depth;
}
}
/** Note that a document was ended. */
protected void afterEndDocument() {
if (stack[depth = 0] == WROTE_MARKUP) { // but not data
try {
writeNewLine(0);
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
stack[depth] = 0; // start fresh
}
/** Write a line separator followed by indentation. */
protected void writeNewLine(int indentation) throws XMLStreamException {
final int newLineLength = getNewLine().length();
final int prefixLength = newLineLength + (getIndent().length() * indentation);
if (prefixLength > 0) {
if (linePrefix == null) {
linePrefix = (getNewLine() + getIndent()).toCharArray();
}
while (prefixLength > linePrefix.length) {
// make linePrefix longer:
char[] newPrefix = new char[newLineLength
+ ((linePrefix.length - newLineLength) * 2)];
System.arraycopy(linePrefix, 0, newPrefix, 0, linePrefix.length);
System.arraycopy(linePrefix, newLineLength, newPrefix, linePrefix.length,
linePrefix.length - newLineLength);
linePrefix = newPrefix;
}
out.writeCharacters(linePrefix, 0, prefixLength);
}
}
}
| 11,929
| 31.595628
| 100
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/LineReader.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.io;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
public class LineReader extends Reader {
private Reader reader;
private int currentPos = 0;
private ArrayList<Integer> lines = new ArrayList<>(Arrays.asList(0));
public LineReader(Reader parent) {
reader = parent;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int r = reader.read(cbuf, off, len);
for (int i = 0; i < len; i ++)
if (cbuf[off + i] == '\n')
lines.add(currentPos + i);
currentPos += len;
return r;
}
// Line and column starts at 1
public int positionFor(int line, int column) {
return lines.get(line - 1) + column - 1;
}
// public int[] positionFor(int offset) { // TODO write this method
// Arrays.binarySearch(lines., null, null)
// }
@Override
public void close() throws IOException {
reader.close();
}
}
| 1,868
| 28.666667
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/MatrixDebugger.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.io;
public final class MatrixDebugger {
private MatrixDebugger() {
}
public static void dump(Object[][] mat) {
for (Object[] r : mat) {
for (Object l: r) System.out.print(l + "\t");
System.out.println();
}
}
public static void dump(boolean[][] mat) {
for (boolean[] r : mat) {
for (boolean l: r) System.out.print(l + "\t");
System.out.println();
}
}
public static void dump(double[][] mat) {
System.out.println("---");
for (double[] r : mat) {
for (double l: r) System.out.print(l + "\t");
System.out.println();
}
System.out.println("---");
}
}
| 1,563
| 29.076923
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/StreamWriterDelegate.java
|
/*
* Copyright (c) 2006, John Kristian
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of StAX-Utils nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package gumtreediff.io;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* Abstract class for writing filtered XML streams. This class provides methods
* that merely delegate to the contained stream. Subclasses should override some
* of these methods, and may also provide additional methods and fields.
*
* @author <a href="mailto:jk2006@engineer.com">John Kristian</a>
*/
public abstract class StreamWriterDelegate implements XMLStreamWriter {
protected StreamWriterDelegate(XMLStreamWriter out) {
this.out = out;
}
protected XMLStreamWriter out;
@Override
public Object getProperty(String name) throws IllegalArgumentException {
return out.getProperty(name);
}
@Override
public NamespaceContext getNamespaceContext() {
return out.getNamespaceContext();
}
@Override
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
out.setNamespaceContext(context);
}
@Override
public void setDefaultNamespace(String uri) throws XMLStreamException {
out.setDefaultNamespace(uri);
}
@Override
public void writeStartDocument() throws XMLStreamException {
out.writeStartDocument();
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
out.writeStartDocument(version);
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
out.writeStartDocument(encoding, version);
}
@Override
public void writeDTD(String dtd) throws XMLStreamException {
out.writeDTD(dtd);
}
@Override
public void writeProcessingInstruction(String target) throws XMLStreamException {
out.writeProcessingInstruction(target);
}
@Override
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
out.writeProcessingInstruction(target, data);
}
@Override
public void writeComment(String data) throws XMLStreamException {
out.writeComment(data);
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
out.writeEmptyElement(localName);
}
@Override
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
out.writeEmptyElement(namespaceURI, localName);
}
@Override
public void writeEmptyElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException {
out.writeEmptyElement(prefix, localName, namespaceURI);
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
out.writeStartElement(localName);
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
out.writeStartElement(namespaceURI, localName);
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException {
out.writeStartElement(prefix, localName, namespaceURI);
}
@Override
public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
out.writeDefaultNamespace(namespaceURI);
}
@Override
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
out.writeNamespace(prefix, namespaceURI);
}
@Override
public String getPrefix(String uri) throws XMLStreamException {
return out.getPrefix(uri);
}
@Override
public void setPrefix(String prefix, String uri) throws XMLStreamException {
out.setPrefix(prefix, uri);
}
@Override
public void writeAttribute(String localName, String value) throws XMLStreamException {
out.writeAttribute(localName, value);
}
@Override
public void writeAttribute(String namespaceURI, String localName, String value)
throws XMLStreamException {
out.writeAttribute(namespaceURI, localName, value);
}
@Override
public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
throws XMLStreamException {
out.writeAttribute(prefix, namespaceURI, localName, value);
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
out.writeCharacters(text);
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
out.writeCharacters(text, start, len);
}
@Override
public void writeCData(String data) throws XMLStreamException {
out.writeCData(data);
}
@Override
public void writeEntityRef(String name) throws XMLStreamException {
out.writeEntityRef(name);
}
@Override
public void writeEndElement() throws XMLStreamException {
out.writeEndElement();
}
@Override
public void writeEndDocument() throws XMLStreamException {
out.writeEndDocument();
}
@Override
public void flush() throws XMLStreamException {
out.flush();
}
@Override
public void close() throws XMLStreamException {
out.close();
}
}
| 7,023
| 31.220183
| 100
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/io/TreeIoUtils.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.io;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import com.google.gson.stream.JsonWriter;
import gumtreediff.actions.model.Action;
import gumtreediff.actions.model.Delete;
import gumtreediff.actions.model.Insert;
import gumtreediff.actions.model.Move;
import gumtreediff.actions.model.Update;
import gumtreediff.gen.Register;
import gumtreediff.gen.TreeGenerator;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import gumtreediff.tree.TreeContext.MetadataSerializers;
import gumtreediff.tree.TreeContext.MetadataUnserializers;
import gumtreediff.tree.TreeUtils;
public final class TreeIoUtils {
private TreeIoUtils() {} // Forbids instantiation of TreeIOUtils
public static TreeGenerator fromXml() {
return new XmlInternalGenerator();
}
public static TreeGenerator fromXml(MetadataUnserializers unserializers) {
XmlInternalGenerator generator = new XmlInternalGenerator();
generator.getUnserializers().addAll(unserializers);
return generator;
}
public static TreeSerializer toXml(TreeContext ctx) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializers, Writer writer)
throws XMLStreamException {
return new XmlFormatter(writer, ctx);
}
};
}
public static TreeSerializer toAnnotatedXml(TreeContext ctx, boolean isSrc, MappingStore m) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializers, Writer writer)
throws XMLStreamException {
return new XmlAnnotatedFormatter(writer, ctx, isSrc, m);
}
};
}
public static TreeSerializer toCompactXml(TreeContext ctx) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializers, Writer writer)
throws Exception {
return new XmlCompactFormatter(writer, ctx);
}
};
}
public static TreeSerializer toJson(TreeContext ctx) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializers, Writer writer)
throws Exception {
return new JsonFormatter(writer, ctx);
}
};
}
public static TreeSerializer toLisp(TreeContext ctx) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializers, Writer writer)
throws Exception {
return new LispFormatter(writer, ctx);
}
};
}
public static TreeSerializer toDot(TreeContext ctx, MappingStore m, List<Action> acts, Boolean Ifsrc) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializer, Writer writer)
throws Exception {
return new DotFormatter(writer, ctx, m, acts, Ifsrc);
}
};
}
public static TreeSerializer toDetailedDot(TreeContext ctx, MappingStore m, List<Action> acts, Boolean Ifsrc) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializer, Writer writer)
throws Exception {
return new DetailedDotFormatter(writer, ctx, m, acts, Ifsrc);
}
};
}
public static TreeSerializer toDot2(TreeContext ctx) {
return new TreeSerializer(ctx) {
@Override
protected TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializer, Writer writer)
throws Exception {
return new DotFormatter2(writer, ctx);
}
};
}
public abstract static class AbstractSerializer {
public abstract void writeTo(Writer writer) throws Exception;
public void writeTo(OutputStream writer) throws Exception {
// FIXME Since the stream is already open, we should not close it, however due to semantic issue
// it should stay like this
try (OutputStreamWriter os = new OutputStreamWriter(writer, "UTF-8")) {
writeTo(os);
}
}
@Override
public String toString() {
try (StringWriter s = new StringWriter()) {
writeTo(s);
return s.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void writeTo(String file) throws Exception {
try (Writer w = Files.newBufferedWriter(Paths.get(file), Charset.forName("UTF-8"))) {
writeTo(w);
}
}
public void writeTo(File file) throws Exception {
try (Writer w = Files.newBufferedWriter(file.toPath(), Charset.forName("UTF-8"))) {
writeTo(w);
}
}
}
public abstract static class TreeSerializer extends AbstractSerializer {
final TreeContext context;
final MetadataSerializers serializers = new MetadataSerializers();
public TreeSerializer(TreeContext ctx) {
context = ctx;
serializers.addAll(ctx.getSerializers());
}
protected abstract TreeFormatter newFormatter(TreeContext ctx, MetadataSerializers serializers, Writer writer)
throws Exception;
@Override
public void writeTo(Writer writer) throws Exception {
TreeFormatter formatter = newFormatter(context, serializers, writer);
try {
writeTree(formatter, context.getRoot());
} finally {
formatter.close();
}
}
private void forwardException(Exception e) {
throw new FormatException(e);
}
protected void writeTree(TreeFormatter formatter, ITree root) throws Exception {
formatter.startSerialization();
writeAttributes(formatter, context.getMetadata());
formatter.endProlog();
try {
TreeUtils.visitTree(root, new TreeUtils.TreeVisitor() {
@Override
public void startTree(ITree tree) {
try {
assert tree != null;
formatter.startTree(tree);
writeAttributes(formatter, tree.getMetadata());
formatter.endTreeProlog(tree);
} catch (Exception e) {
forwardException(e);
}
}
@Override
public void endTree(ITree tree) {
try {
formatter.endTree(tree);
} catch (Exception e) {
forwardException(e);
}
}
});
} catch (FormatException e) {
throw e.getCause();
}
formatter.stopSerialization();
}
protected void writeAttributes(TreeFormatter formatter, Iterator<Entry<String, Object>> it) throws Exception {
while (it.hasNext()) {
Entry<String, Object> entry = it.next();
serializers.serialize(formatter, entry.getKey(), entry.getValue());
}
}
public TreeSerializer export(String name, MetadataSerializer serializer) {
serializers.add(name, serializer);
return this;
}
public TreeSerializer export(String... name) {
for (String n: name)
serializers.add(n, Object::toString);
return this;
}
}
public interface TreeFormatter {
void startSerialization() throws Exception;
void endProlog() throws Exception;
void stopSerialization() throws Exception;
void startTree(ITree tree) throws Exception;
void endTreeProlog(ITree tree) throws Exception;
void endTree(ITree tree) throws Exception;
void close() throws Exception;
void serializeAttribute(String name, String value) throws Exception;
}
@FunctionalInterface
public interface MetadataSerializer {
String toString(Object object);
}
@FunctionalInterface
public interface MetadataUnserializer {
Object fromString(String value);
}
static class FormatException extends RuntimeException {
private static final long serialVersionUID = 593766540545763066L;
Exception cause;
public FormatException(Exception cause) {
super(cause);
this.cause = cause;
}
@Override
public synchronized Exception getCause() {
return cause;
}
}
static class TreeFormatterAdapter implements TreeFormatter {
protected final TreeContext context;
protected TreeFormatterAdapter(TreeContext ctx) {
context = ctx;
}
public TreeFormatterAdapter(TreeContext ctx, MappingStore m) {
context = ctx;
}
@Override
public void startSerialization() throws Exception { }
@Override
public void endProlog() throws Exception { }
@Override
public void startTree(ITree tree) throws Exception { }
@Override
public void endTreeProlog(ITree tree) throws Exception { }
@Override
public void endTree(ITree tree) throws Exception { }
@Override
public void stopSerialization() throws Exception { }
@Override
public void close() throws Exception { }
@Override
public void serializeAttribute(String name, String value) throws Exception { }
}
abstract static class AbsXmlFormatter extends TreeFormatterAdapter {
protected final XMLStreamWriter writer;
protected AbsXmlFormatter(Writer w, TreeContext ctx) throws XMLStreamException {
super(ctx);
XMLOutputFactory f = XMLOutputFactory.newInstance();
writer = new IndentingXMLStreamWriter(f.createXMLStreamWriter(w));
}
@Override
public void startSerialization() throws XMLStreamException {
writer.writeStartDocument();
}
@Override
public void stopSerialization() throws XMLStreamException {
writer.writeEndDocument();
}
@Override
public void close() throws XMLStreamException {
writer.close();
}
}
static class XmlFormatter extends AbsXmlFormatter {
public XmlFormatter(Writer w, TreeContext ctx) throws XMLStreamException {
super(w, ctx);
}
@Override
public void startSerialization() throws XMLStreamException {
super.startSerialization();
writer.writeStartElement("root");
writer.writeStartElement("context");
}
@Override
public void endProlog() throws XMLStreamException {
writer.writeEndElement();
}
@Override
public void stopSerialization() throws XMLStreamException {
writer.writeEndElement();
super.stopSerialization();
}
@Override
public void serializeAttribute(String name, String value) throws XMLStreamException {
writer.writeStartElement(name);
writer.writeCharacters(value);
writer.writeEndElement();
}
@Override//��AST�����
public void startTree(ITree tree) throws XMLStreamException {
writer.writeStartElement("tree");
writer.writeAttribute("type", Integer.toString(tree.getType()));
writer.writeAttribute("id", Integer.toString(tree.getId()));
if (tree.hasLabel()) writer.writeAttribute("label", tree.getLabel());
if (context.hasLabelFor(tree.getType()))
writer.writeAttribute("typeLabel", context.getTypeLabel(tree.getType()));
if (ITree.NO_VALUE != tree.getPos()) {
writer.writeAttribute("pos", Integer.toString(tree.getPos()));
writer.writeAttribute("length", Integer.toString(tree.getLength()));
}
}
@Override
public void endTree(ITree tree) throws XMLStreamException {
writer.writeEndElement();
}
}
static class XmlAnnotatedFormatter extends XmlFormatter {
final SearchOther searchOther;
public XmlAnnotatedFormatter(Writer w, TreeContext ctx, boolean isSrc,
MappingStore m) throws XMLStreamException {
super(w, ctx);
if (isSrc)
searchOther = (tree) -> m.hasSrc(tree) ? m.getDst(tree) : null;
else
searchOther = (tree) -> m.hasDst(tree) ? m.getSrc(tree) : null;
}
interface SearchOther {
ITree lookup(ITree tree);
}
@Override
public void startTree(ITree tree) throws XMLStreamException {
super.startTree(tree);
ITree o = searchOther.lookup(tree);
if (o != null) {
if (ITree.NO_VALUE != o.getPos()) {
writer.writeAttribute("other_pos", Integer.toString(o.getPos()));
writer.writeAttribute("other_length", Integer.toString(o.getLength()));
}
}
}
}
static class XmlCompactFormatter extends AbsXmlFormatter {
public XmlCompactFormatter(Writer w, TreeContext ctx) throws XMLStreamException {
super(w, ctx);
}
@Override
public void startSerialization() throws XMLStreamException {
super.startSerialization();
writer.writeStartElement("root");
}
@Override
public void stopSerialization() throws XMLStreamException {
writer.writeEndElement();
super.stopSerialization();
}
@Override
public void serializeAttribute(String name, String value) throws XMLStreamException {
writer.writeAttribute(name, value);
}
@Override
public void startTree(ITree tree) throws XMLStreamException {
if (tree.getChildren().size() == 0)
writer.writeEmptyElement(context.getTypeLabel(tree.getType()));
else
writer.writeStartElement(context.getTypeLabel(tree.getType()));
if (tree.hasLabel())
writer.writeAttribute("label", tree.getLabel());
}
@Override
public void endTree(ITree tree) throws XMLStreamException {
if (tree.getChildren().size() > 0)
writer.writeEndElement();
}
}
static class LispFormatter extends TreeFormatterAdapter {
protected final Writer writer;
protected final Pattern replacer = Pattern.compile("[\\\\\"]");
int level = 0;
protected LispFormatter(Writer w, TreeContext ctx) {
super(ctx);
writer = w;
}
@Override
public void startSerialization() throws IOException {
writer.write("((");
}
@Override
public void startTree(ITree tree) throws IOException {
if (!tree.isRoot())
writer.write("\n");
for (int i = 0; i < level; i ++)
writer.write(" ");
level ++;
String pos = (ITree.NO_VALUE == tree.getPos() ? "" : String.format("(%d %d)",
tree.getPos(), tree.getLength()));
writer.write(String.format("(%d %s %s (%s",
tree.getType(), protect(context.getTypeLabel(tree)), protect(tree.getLabel()), pos));
}
@Override
public void endProlog() throws Exception {
writer.append(") ");
}
@Override
public void endTreeProlog(ITree tree) throws Exception {
writer.append(") (");
}
@Override
public void serializeAttribute(String name, String value) throws Exception {
writer.append(String.format("(:%s %s) ", name, protect(value)));
}
protected String protect(String val) {
return String.format("\"%s\"", replacer.matcher(val).replaceAll("\\\\$0"));
}
@Override
public void endTree(ITree tree) throws IOException {
writer.write(")");
level --;
}
@Override
public void stopSerialization() throws IOException {
writer.write(")");
}
}
static class DotFormatter extends TreeFormatterAdapter {
protected final Writer writer;
protected MappingStore map;
protected HashMap<Integer, Integer> mapping = new HashMap<>();
protected HashMap<Integer, Action> udActions = new HashMap<>();
protected HashMap<Integer, Action> amActions = new HashMap<>();
protected Boolean isSrc;
protected DotFormatter(Writer w, TreeContext ctx, MappingStore m ,
List<Action> acts, Boolean Ifsrc) {
super(ctx);
writer = w;
isSrc = Ifsrc;
map = m;
for(Mapping map : map) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
mapping.put(src.getId(), dst.getId());
}
System.out.println("mapSize:"+mapping.size());
System.out.println("ActionSize:" + acts.size());
for (Action a : acts) {
ITree src = a.getNode();
if (a instanceof Move) {
amActions.put(src.getId(), a);
} else if (a instanceof Update) {
udActions.put(src.getId(), a);
} else if (a instanceof Insert) {
amActions.put(src.getId(), a);
} else if (a instanceof Delete) {
udActions.put(src.getId(), a);
}
}
}
public String formate(String label) {
if (label.contains("\"") || label.contains("\\s"))
label = label.replaceAll("\"", "").replaceAll("\\s", "").replaceAll("\\\\", "");
if (label.contains("\"") || label.contains("\\n"))
label = label.replaceAll("\"", "").replaceAll("(\r\n|\n)", "");
if (label.length() > 30)
label = label.substring(0, 30);
return label;
}
@Override
public void startSerialization() throws Exception {
writer.write("digraph G {\n");
}
@Override
public void startTree(ITree tree) throws Exception {
int id = tree.getId();
String label = id+" "+context.getTypeLabel(tree);
if (tree.hasLabel())
label = label+":"+tree.getLabel();
label = formate(label);
if(isSrc) {
if(udActions.get(id)!=null&&mapping.get(id)!=null){
Action a = udActions.get(id);
if (a instanceof Delete) {
writer.write(id + " [label=\"" + label+ "\", style=dashed,"
+ " color=red];\n");
}
else if (a instanceof Update) {
Update upt = (Update)a;
writer.write(id + " [label=\"" + label+"\\n update to " +formate(upt.getValue())
+ "\", color=red];\n");
}else
writer.write(id + " [label=\"" + label + "\", color=red];\n");
}else if(mapping.get(id)==null){
Action a = udActions.get(id);
if (a instanceof Delete) {
writer.write(id + " [label=\"" + label+ "\", style=dashed];\n");
}
else if(a instanceof Update) {
Update upt = (Update)a;
writer.write(id + " [label=\"" + label+"\\n update to " +formate(upt.getValue())
+ "\"];\n");
}else
writer.write(id + " [label=\"" + label + "\", color=red];\n");
}else
writer.write(id + " [label=\"" + label + "\", color=red];\n");
}
else if(mapping.containsValue(id)) {
writer.write(id + " [label=\"" + label + "\", color=red];\n");
}else
writer.write(id + " [label=\"" + label + "\"];\n");
if (tree.getParent() != null)
writer.write(tree.getParent().getId() + " -> " + id + ";\n");
// if(isSrc==true&&actions.get(id)!=null) {
// Action a = actions.get(id);
// if (a instanceof Move) {
// Move mov = (Move)a;
// writer.write(mov.getNode().getId()+" -> "+mov.getParent().getId()
// +" [style=dashed, label=\"mov "+mov.getNode().getId()
// +" to "+mov.getParent().getId()+","+mov.getPosition()+"\"];\n");
// } else if (a instanceof Insert) {
// Insert ins = (Insert)a;
// writer.write(ins.getNode().getId()+" -> "+ins.getParent().getId()
// +" [style=dashed, label=\"ins "+ins.getNode().getId()
// +" to "+ins.getParent().getId()+","+ins.getPosition()+"\"];\n");
// }
// }
}
@Override
public void stopSerialization() throws Exception {
writer.write("}");
}
}
static class JsonFormatter extends TreeFormatterAdapter {
private final JsonWriter writer;
public JsonFormatter(Writer w, TreeContext ctx) {
super(ctx);
writer = new JsonWriter(w);
writer.setIndent(" ");
}
@Override
public void startTree(ITree t) throws IOException {
writer.beginObject();
writer.name("type").value(Integer.toString(t.getType()));
if (t.hasLabel()) writer.name("label").value(t.getLabel());
if (context.hasLabelFor(t.getType())) writer.name("typeLabel").value(context.getTypeLabel(t.getType()));
// if (ITree.NO_VALUE != t.getPos()) {
// writer.name("pos").value(Integer.toString(t.getPos()));
// writer.name("length").value(Integer.toString(t.getLength()));
// }
if (t.getId()>=0) writer.name("id").value(t.getId());
}
@Override
public void endTreeProlog(ITree tree) throws IOException {
writer.name("children");
writer.beginArray();
}
@Override
public void endTree(ITree tree) throws IOException {
writer.endArray();
writer.endObject();
}
@Override
public void startSerialization() throws IOException {
writer.beginObject();
writer.setIndent("\t");
}
@Override
public void endProlog() throws IOException {
writer.name("root");
}
@Override
public void serializeAttribute(String key, String value) throws IOException {
writer.name(key).value(value);
}
@Override
public void stopSerialization() throws IOException {
writer.endObject();
}
@Override
public void close() throws IOException {
writer.close();
}
}
@Register(id = "xml", accept = "\\.gxml$")
// TODO Since it is not in the right package, I'm not even sure it is visible in the registry
// TODO should we move this class elsewhere (another package)
public static class XmlInternalGenerator extends TreeGenerator {
static MetadataUnserializers defaultUnserializers = new MetadataUnserializers();
final MetadataUnserializers unserializers = new MetadataUnserializers(); // FIXME should it be pushed up or not?
private static final QName TYPE = new QName("type");
private static final QName LABEL = new QName("label");
private static final QName TYPE_LABEL = new QName("typeLabel");
private static final String POS = "pos";
private static final String LENGTH = "length";
static {
defaultUnserializers.add(POS, Integer::parseInt);
defaultUnserializers.add(LENGTH, Integer::parseInt);
}
public XmlInternalGenerator() {
unserializers.addAll(defaultUnserializers);
}
@Override
protected TreeContext generate(Reader source) throws IOException {
XMLInputFactory fact = XMLInputFactory.newInstance();
TreeContext context = new TreeContext();
try {
ArrayDeque<ITree> trees = new ArrayDeque<>();
XMLEventReader r = fact.createXMLEventReader(source);
while (r.hasNext()) {
XMLEvent e = r.nextEvent();
if (e instanceof StartElement) {
StartElement s = (StartElement) e;
if (!s.getName().getLocalPart().equals("tree")) // FIXME need to deal with options
continue;
int type = Integer.parseInt(s.getAttributeByName(TYPE).getValue());
ITree t = context.createTree(type,
labelForAttribute(s, LABEL), labelForAttribute(s, TYPE_LABEL));
// FIXME this iterator has no type, due to the API. We have to cast it later
Iterator<?> it = s.getAttributes();
while (it.hasNext()) {
Attribute a = (Attribute) it.next();
unserializers.load(t, a.getName().getLocalPart(), a.getValue());
}
if (trees.isEmpty())
context.setRoot(t);
else
t.setParentAndUpdateChildren(trees.peekFirst());
trees.addFirst(t);
} else if (e instanceof EndElement) {
if (!((EndElement)e).getName().getLocalPart().equals("tree")) // FIXME need to deal with options
continue;
trees.removeFirst();
}
}
context.validate();
return context;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String labelForAttribute(StartElement s, QName attrName) {
Attribute attr = s.getAttributeByName(attrName);
return attr == null ? ITree.NO_LABEL : attr.getValue();
}
public MetadataUnserializers getUnserializers() {
return unserializers;
}
}
static class DotFormatter2 extends TreeFormatterAdapter {
protected final Writer writer;
protected MappingStore map;
protected HashMap<Integer, Integer> mapping = new HashMap<>();
protected HashMap<Integer, Action> udActions = new HashMap<>();
protected HashMap<Integer, Action> amActions = new HashMap<>();
protected Boolean isSrc;
protected DotFormatter2(Writer w, TreeContext ctx) {
super(ctx);
writer = w;
}
public String formate(String label) {
if (label.contains("\"") || label.contains("\\s"))
label = label.replaceAll("\"", "").replaceAll("\\s", "").replaceAll("\\\\", "");
if (label.contains("\"") || label.contains("\\n"))
label = label.replaceAll("\"", "").replaceAll("(\r\n|\n)", "");
// if (label.length() > 30)
// label = label.substring(0, 30);
return label;
}
@Override
public void startSerialization() throws Exception {
writer.write("digraph G {\n");
}
@Override
public void startTree(ITree tree) throws Exception {
int id = tree.getId();
String label = id+" "+context.getTypeLabel(tree);
if (tree.hasLabel())
label = label+":"+tree.getLabel();
label = formate(label);
writer.write(id + " [label=\"" + label + "\"];\n");
if (tree.getParent() != null)
writer.write(tree.getParent().getId() + " -> " + id + ";\n");
}
@Override
public void stopSerialization() throws Exception {
writer.write("}");
}
}
}
| 30,900
| 34.848028
| 120
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/CompositeMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import gumtreediff.tree.ITree;
public class CompositeMatcher extends Matcher {
protected final Matcher[] matchers;
public CompositeMatcher(ITree src, ITree dst, MappingStore store, Matcher[] matchers) {
super(src, dst, store);
this.matchers = matchers;
}
@Override
public void match() {
for (Matcher matcher : matchers) {
matcher.match();
}
}
}
| 1,273
| 29.333333
| 91
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/CompositeMatchers.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import gumtreediff.gen.Registry;
import gumtreediff.matchers.heuristic.XyBottomUpMatcher;
import gumtreediff.matchers.heuristic.cd.ChangeDistillerBottomUpMatcher;
import gumtreediff.matchers.heuristic.cd.ChangeDistillerLeavesMatcher;
import gumtreediff.matchers.heuristic.gt.CliqueSubtreeMatcher;
import gumtreediff.matchers.heuristic.gt.CompleteBottomUpMatcher;
import gumtreediff.matchers.heuristic.gt.GreedyBottomUpMatcher;
import gumtreediff.matchers.heuristic.gt.GreedySubtreeMatcher;
import gumtreediff.tree.ITree;
public class CompositeMatchers {
@Register(id = "gumtree", defaultMatcher = true, priority = Registry.Priority.HIGH)
public static class ClassicGumtree extends CompositeMatcher {
public ClassicGumtree(ITree src, ITree dst, MappingStore store) {
super(src, dst, store, new Matcher[]{
new GreedySubtreeMatcher(src, dst, store),
new GreedyBottomUpMatcher(src, dst, store)
});
System.out.println("ClassicGumtree");
}
}
@Register(id = "gumtree-topdown", defaultMatcher = true, priority = Registry.Priority.HIGH)
public static class GumtreeTopDown extends CompositeMatcher {
public GumtreeTopDown(ITree src, ITree dst, MappingStore store) {
super(src, dst, store, new Matcher[]{
new GreedySubtreeMatcher(src, dst, store)
});
System.out.println("GumtreeTopDown");
}
}
@Register(id = "gumtree-complete")
public static class CompleteGumtreeMatcher extends CompositeMatcher {
public CompleteGumtreeMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store, new Matcher[]{
new CliqueSubtreeMatcher(src, dst, store),
new CompleteBottomUpMatcher(src, dst, store)
});
System.out.println("CompleteGumtreeMatcher");
}
}
@Register(id = "change-distiller")
public static class ChangeDistiller extends CompositeMatcher {
public ChangeDistiller(ITree src, ITree dst, MappingStore store) {
super(src, dst, store, new Matcher[]{
new ChangeDistillerLeavesMatcher(src, dst, store),
new ChangeDistillerBottomUpMatcher(src, dst, store)
});
System.out.println("change-distiller");
}
}
@Register(id = "xy")
public static class XyMatcher extends CompositeMatcher {
public XyMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store, new Matcher[]{
new GreedySubtreeMatcher(src, dst, store),
new XyBottomUpMatcher(src, dst, store)
});
System.out.println("xy");
}
}
}
| 3,655
| 38.311828
| 95
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/Mapping.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import gumtreediff.tree.ITree;
import gumtreediff.utils.Pair;
public class Mapping extends Pair<ITree, ITree> {
public Mapping(ITree a, ITree b) {
super(a, b);
}
}
| 1,038
| 30.484848
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/MappingStore.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import gumtreediff.tree.ITree;
import java.util.*;
public class MappingStore implements Iterable<Mapping> {
private Map<ITree, ITree> srcs;
private Map<ITree, ITree> dsts;
public MappingStore(Set<Mapping> mappings) {
this();
for (Mapping m: mappings) link(m.getFirst(), m.getSecond());
}
public MappingStore() {
srcs = new HashMap<>();
dsts = new HashMap<>();
}
public Set<Mapping> asSet() {
return new AbstractSet<Mapping>() {
@Override
public Iterator<Mapping> iterator() {
Iterator<ITree> it = srcs.keySet().iterator();
return new Iterator<Mapping>() {
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public Mapping next() {
ITree src = it.next();
if (src == null) return null;
return new Mapping(src, srcs.get(src));
}
};
}
@Override
public int size() {
return srcs.keySet().size();
}
};
}
public MappingStore copy() {
return new MappingStore(asSet());
}
public void link(ITree src, ITree dst) {
srcs.put(src, dst);
dsts.put(dst, src);
}
public void unlink(ITree src, ITree dst) {
srcs.remove(src);
dsts.remove(dst);
}
public ITree firstMappedSrcParent(ITree src) {
ITree p = src.getParent();
if (p == null) return null;
else {
while (!hasSrc(p)) {
p = p.getParent();
if (p == null) return p;
}
return p;
}
}
public ITree firstMappedDstParent(ITree dst) {
ITree p = dst.getParent();
if (p == null) return null;
else {
while (!hasDst(p)) {
p = p.getParent();
if (p == null) return p;
}
return p;
}
}
public ITree getDst(ITree src) {
return srcs.get(src);
}
public ITree getSrc(ITree dst) {
return dsts.get(dst);
}
public boolean hasSrc(ITree src) {
return srcs.containsKey(src);
}
public boolean hasDst(ITree dst) {
return dsts.containsKey(dst);
}
public boolean has(ITree src, ITree dst) {
return srcs.get(src) == dst;
}
/**
* Indicate whether or not a tree is mappable to another given tree.
* @return true if both trees are not mapped and if the trees have the same type, false either.
*/
public boolean isMatchable(ITree src, ITree dst) {
return src.hasSameType(dst) && !(srcs.containsKey(src) || dsts.containsKey(dst));
}
@Override
public Iterator<Mapping> iterator() {
return asSet().iterator();
}
@Override
public String toString() {
return asSet().toString();
}
}
| 3,943
| 25.829932
| 99
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/Matcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import gumtreediff.tree.ITree;
import org.atteo.classindex.IndexSubclasses;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
@IndexSubclasses
public abstract class Matcher {
public static final Logger LOGGER = Logger.getLogger("com.github.gumtreediff.matchers");
protected final ITree src;
protected final ITree dst;
protected final MappingStore mappings;
public Matcher(ITree src, ITree dst, MappingStore mappings) {
this.src = src;
this.dst = dst;
this.mappings = mappings;
}
public abstract void match();
public MappingStore getMappings() {
return mappings;
}
public Set<Mapping> getMappingsAsSet() {
return mappings.asSet();
}
public ITree getSrc() {
return src;
}
public ITree getDst() {
return dst;
}
protected void addMapping(ITree src, ITree dst) {
mappings.link(src, dst);
}
protected void addMappingRecursively(ITree src, ITree dst) {
// System.out.println("mapsize:"+mappings.asSet().size());
List<ITree> srcTrees = src.getTrees();
List<ITree> dstTrees = dst.getTrees();
for (int i = 0; i < srcTrees.size(); i++) {
ITree currentSrcTree = srcTrees.get(i);
ITree currentDstTree = dstTrees.get(i);
addMapping(currentSrcTree, currentDstTree);
}
}
protected double chawatheSimilarity(ITree src, ITree dst) {
int max = Math.max(src.getDescendants().size(), dst.getDescendants().size());
return (double) numberOfCommonDescendants(src, dst) / (double) max;
}
protected double overlapSimilarity(ITree src, ITree dst, MappingStore mappings) {
int min = Math.min(src.getDescendants().size(), dst.getDescendants().size());
return (double) numberOfCommonDescendants(src, dst) / (double) min;
}
protected double diceSimilarity(ITree src, ITree dst) {
double c = numberOfCommonDescendants(src, dst);
return (2D * c) / ((double) src.getDescendants().size() + (double) dst.getDescendants().size());
}
protected double jaccardSimilarity(ITree src, ITree dst) {
double num = numberOfCommonDescendants(src, dst);
double den = (double) src.getDescendants().size() + (double) dst.getDescendants().size() - num;
return num / den;
}
protected int numberOfCommonDescendants(ITree src, ITree dst) {
Set<ITree> dstDescendants = new HashSet<>(dst.getDescendants());
int common = 0;
for (ITree t : src.getDescendants()) {
ITree m = mappings.getDst(t);
if (m != null && dstDescendants.contains(m))
common++;
}
return common;
}
public boolean isMappingAllowed(ITree src, ITree dst) {
return src.hasSameType(dst) && !(mappings.hasSrc(src) || mappings.hasDst(dst));
}
}
| 3,800
| 30.941176
| 104
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/Matchers.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import gumtreediff.gen.Registry;
import gumtreediff.tree.ITree;
public class Matchers extends Registry<String, Matcher, Register> {
private static Matchers registry;
private Factory<? extends Matcher> defaultMatcherFactory; // FIXME shouln't be removed and use priority instead ?
public static Matchers getInstance() {
if (registry == null)
registry = new Matchers();
return registry;
}
private Matchers() {
install(CompositeMatchers.ClassicGumtree.class);
install(CompositeMatchers.ChangeDistiller.class);
install(CompositeMatchers.XyMatcher.class);
install(CompositeMatchers.GumtreeTopDown.class);
}
private void install(Class<? extends Matcher> clazz) {
Register a = clazz.getAnnotation(Register.class);
if (a == null)
throw new RuntimeException("Expecting @Register annotation on " + clazz.getName());
if (defaultMatcherFactory == null && a.defaultMatcher())
defaultMatcherFactory = defaultFactory(clazz, ITree.class, ITree.class, MappingStore.class);
install(clazz, a);
}
public Matcher getMatcher(String id, ITree src, ITree dst) {
return get(id, src, dst, new MappingStore());
}
public Matcher getMatcher(ITree src, ITree dst) {
return defaultMatcherFactory.instantiate(new Object[]{src, dst, new MappingStore()});
}
protected String getName(Register annotation, Class<? extends Matcher> clazz) {
return annotation.id();
}
@Override
protected Entry newEntry(Class<? extends Matcher> clazz, Register annotation) {
return new Entry(annotation.id(), clazz,
defaultFactory(clazz, ITree.class, ITree.class, MappingStore.class), annotation.priority()) {
@Override
protected boolean handle(String key) {
return annotation.id().equals(key); // Fixme remove
}
};
}
}
| 2,822
| 35.662338
| 117
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/MultiMappingStore.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import gumtreediff.tree.ITree;
public class MultiMappingStore implements Iterable<Mapping> {
private Map<ITree, Set<ITree>> srcs;
private Map<ITree, Set<ITree>> dsts;
public MultiMappingStore(Set<Mapping> mappings) {
this();
for (Mapping m: mappings) link(m.getFirst(), m.getSecond());
}
public MultiMappingStore() {
srcs = new HashMap<>();
dsts = new HashMap<>();
}
public Set<Mapping> getMappings() {
Set<Mapping> mappings = new HashSet<>();
for (ITree src : srcs.keySet())
for (ITree dst: srcs.get(src))
mappings.add(new Mapping(src, dst));
return mappings;
}
public void link(ITree src, ITree dst) {
if (!srcs.containsKey(src)) srcs.put(src, new HashSet<ITree>());
srcs.get(src).add(dst);
if (!dsts.containsKey(dst)) dsts.put(dst, new HashSet<ITree>());
dsts.get(dst).add(src);
}
public void unlink(ITree src, ITree dst) {
srcs.get(src).remove(dst);
dsts.get(dst).remove(src);
}
public Set<ITree> getDst(ITree src) {
return srcs.get(src);
}
public Set<ITree> getSrcs() {
return srcs.keySet();
}
public Set<ITree> getDsts() {
return dsts.keySet();
}
public Set<ITree> getSrc(ITree dst) {
return dsts.get(dst);
}
public boolean hasSrc(ITree src) {
return srcs.containsKey(src);
}
public boolean hasDst(ITree dst) {
return dsts.containsKey(dst);
}
public boolean has(ITree src, ITree dst) {
return srcs.get(src).contains(dst);
}
public boolean isSrcUnique(ITree src) {
return srcs.get(src).size() == 1 && dsts.get(srcs.get(src).iterator().next()).size() == 1;
}
public boolean isDstUnique(ITree dst) {
return dsts.get(dst).size() == 1 && srcs.get(dsts.get(dst).iterator().next()).size() == 1;
}
@Override
public Iterator<Mapping> iterator() {
return getMappings().iterator();
}
}
| 3,024
| 26.752294
| 98
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/OptimizedVersions.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers;
import gumtreediff.matchers.heuristic.cd.ChangeDistillerBottomUpMatcher;
import gumtreediff.matchers.heuristic.cd.ChangeDistillerLeavesMatcher;
import gumtreediff.matchers.heuristic.cd.ChangeDistillerParallelLeavesMatcher;
import gumtreediff.matchers.heuristic.gt.GreedyBottomUpMatcher;
import gumtreediff.matchers.heuristic.gt.GreedySubtreeMatcher;
import gumtreediff.matchers.optimal.rted.RtedMatcher;
import gumtreediff.matchers.optimizations.CrossMoveMatcherThetaF;
import gumtreediff.matchers.optimizations.IdenticalSubtreeMatcherThetaA;
import gumtreediff.matchers.optimizations.InnerNodesMatcherThetaD;
import gumtreediff.matchers.optimizations.LcsOptMatcherThetaB;
import gumtreediff.matchers.optimizations.LeafMoveMatcherThetaE;
import gumtreediff.matchers.optimizations.UnmappedLeavesMatcherThetaC;
import gumtreediff.tree.ITree;
public class OptimizedVersions {
public static class CdabcdefSeq extends CompositeMatcher {
/**
* Instantiates the sequential ChangeDistiller version with Theta A-F.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public CdabcdefSeq(ITree src, ITree dst, MappingStore store) {
super(src, dst, store,
new Matcher[] { new IdenticalSubtreeMatcherThetaA(src, dst, store),
new ChangeDistillerLeavesMatcher(src, dst, store),
new ChangeDistillerBottomUpMatcher(src, dst, store),
new LcsOptMatcherThetaB(src, dst, store),
new UnmappedLeavesMatcherThetaC(src, dst, store),
new InnerNodesMatcherThetaD(src, dst, store),
new LeafMoveMatcherThetaE(src, dst, store),
new CrossMoveMatcherThetaF(src, dst, store) });
}
}
public static class CdabcdefPar extends CompositeMatcher {
/**
* Instantiates the parallel ChangeDistiller version with Theta A-F.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public CdabcdefPar(ITree src, ITree dst, MappingStore store) {
super(src, dst, store,
new Matcher[] { new IdenticalSubtreeMatcherThetaA(src, dst, store),
new ChangeDistillerParallelLeavesMatcher(src, dst, store),
new ChangeDistillerBottomUpMatcher(src, dst, store),
new LcsOptMatcherThetaB(src, dst, store),
new UnmappedLeavesMatcherThetaC(src, dst, store),
new InnerNodesMatcherThetaD(src, dst, store),
new LeafMoveMatcherThetaE(src, dst, store),
new CrossMoveMatcherThetaF(src, dst, store)
});
}
}
public static class Gtbcdef extends CompositeMatcher {
/**
* Instantiates GumTree with Theta B-F.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public Gtbcdef(ITree src, ITree dst, MappingStore store) {
super(src, dst, store,
new Matcher[] { new GreedySubtreeMatcher(src, dst, store),
new GreedyBottomUpMatcher(src, dst, store),
new LcsOptMatcherThetaB(src, dst, store),
new UnmappedLeavesMatcherThetaC(src, dst, store),
new InnerNodesMatcherThetaD(src, dst, store),
new LeafMoveMatcherThetaE(src, dst, store),
new CrossMoveMatcherThetaF(src, dst, store) });
}
}
public static class Rtedacdef extends CompositeMatcher {
/**
* Instantiates RTED with Theta A-F.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public Rtedacdef(ITree src, ITree dst, MappingStore store) {
super(src, dst, store,
new Matcher[] { new IdenticalSubtreeMatcherThetaA(src, dst, store),
new RtedMatcher(src, dst, store),
new LcsOptMatcherThetaB(src, dst, store),
new UnmappedLeavesMatcherThetaC(src, dst, store),
new InnerNodesMatcherThetaD(src, dst, store),
new LeafMoveMatcherThetaE(src, dst, store),
new CrossMoveMatcherThetaF(src, dst, store)
});
}
}
}
| 5,550
| 42.031008
| 87
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/Register.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.atteo.classindex.IndexAnnotated;
import gumtreediff.gen.Registry;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@IndexAnnotated
public @interface Register {
String id();
int priority() default Registry.Priority.MEDIUM;
boolean defaultMatcher() default false;
}
| 1,321
| 30.47619
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/LcsMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic;
import java.util.List;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Register;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeUtils;
import gumtreediff.utils.StringAlgorithms;
@Register(id = "lcs")
public class LcsMatcher extends Matcher {
public LcsMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void match() {
List<ITree> srcSeq = TreeUtils.preOrder(src);
List<ITree> dstSeq = TreeUtils.preOrder(dst);
List<int[]> lcs = StringAlgorithms.lcss(srcSeq, dstSeq);
System.out.println(lcs.size());
for (int[] x: lcs) {
ITree t1 = srcSeq.get(x[0]);
ITree t2 = dstSeq.get(x[1]);
addMapping(t1, t2);
}
}
}
| 1,701
| 31.113208
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/XyBottomUpMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
/**
* Match the nodes using a bottom-up approach. It browse the nodes of the source and destination trees
* using a post-order traversal, testing if the two selected trees might be mapped. The two trees are mapped
* if they are mappable and have a dice coefficient greater than SIM_THRESHOLD. Whenever two trees are mapped
* a exact ZS algorithm is applied to look to possibly forgotten nodes.
*/
public class XyBottomUpMatcher extends Matcher {
private static final double SIM_THRESHOLD = Double.parseDouble(System.getProperty("gt.xym.sim", "0.5"));
public XyBottomUpMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void match() {
for (ITree src: this.src.postOrder()) {
if (src.isRoot()) {
addMapping(src, this.dst);
lastChanceMatch(src, this.dst);
} else if (!(mappings.hasSrc(src) || src.isLeaf())) {
Set<ITree> candidates = getDstCandidates(src);
ITree best = null;
double max = -1D;
for (ITree cand: candidates ) {
double sim = jaccardSimilarity(src, cand);
if (sim > max && sim >= SIM_THRESHOLD) {
max = sim;
best = cand;
}
}
if (best != null) {
lastChanceMatch(src, best);
addMapping(src, best);
}
}
}
}
private Set<ITree> getDstCandidates(ITree src) {
Set<ITree> seeds = new HashSet<>();
for (ITree c: src.getDescendants()) {
ITree m = mappings.getDst(c);
if (m != null) seeds.add(m);
}
Set<ITree> candidates = new HashSet<>();
Set<ITree> visited = new HashSet<>();
for (ITree seed: seeds) {
while (seed.getParent() != null) {
ITree parent = seed.getParent();
if (visited.contains(parent))
break;
visited.add(parent);
if (parent.getType() == src.getType() && !mappings.hasDst(parent))
candidates.add(parent);
seed = parent;
}
}
return candidates;
}
private void lastChanceMatch(ITree src, ITree dst) {
Map<Integer,List<ITree>> srcKinds = new HashMap<>();
Map<Integer,List<ITree>> dstKinds = new HashMap<>();
for (ITree c: src.getChildren()) {
if (!srcKinds.containsKey(c.getType())) srcKinds.put(c.getType(), new ArrayList<>());
srcKinds.get(c.getType()).add(c);
}
for (ITree c: dst.getChildren()) {
if (!dstKinds.containsKey(c.getType())) dstKinds.put(c.getType(), new ArrayList<>());
dstKinds.get(c.getType()).add(c);
}
for (int t: srcKinds.keySet())
if (dstKinds.get(t) != null && srcKinds.get(t).size() == dstKinds.get(t).size()
&& srcKinds.get(t).size() == 1)
addMapping(srcKinds.get(t).get(0), dstKinds.get(t).get(0));
}
}
| 4,300
| 35.760684
| 109
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/cd/ChangeDistillerBottomUpMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.cd;
import java.util.List;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeUtils;
public class ChangeDistillerBottomUpMatcher extends Matcher {
public static final double STRUCT_SIM_THRESHOLD_1 = Double.parseDouble(System.getProperty("gt.cd.ssim1", "0.6"));
public static final double STRUCT_SIM_THRESHOLD_2 = Double.parseDouble(System.getProperty("gt.cd.ssim2", "0.4"));
public static final int MAX_NUMBER_OF_LEAVES = Integer.parseInt(System.getProperty("gt.cd.ml", "4"));
public ChangeDistillerBottomUpMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void match() {
List<ITree> dstTrees = TreeUtils.postOrder(this.dst);
for (ITree currentSrcTree: this.src.postOrder()) {
int numberOfLeaves = numberOfLeaves(currentSrcTree);
for (ITree currentDstTree: dstTrees) {
if (isMappingAllowed(currentSrcTree, currentDstTree)
&& !(currentSrcTree.isLeaf() || currentDstTree.isLeaf())) {
double similarity = chawatheSimilarity(currentSrcTree, currentDstTree);
if ((numberOfLeaves > MAX_NUMBER_OF_LEAVES && similarity >= STRUCT_SIM_THRESHOLD_1)
|| (numberOfLeaves <= MAX_NUMBER_OF_LEAVES && similarity >= STRUCT_SIM_THRESHOLD_2)) {
addMapping(currentSrcTree, currentDstTree);
break;
}
}
}
}
}
private int numberOfLeaves(ITree root) {
int numberOfLeaves = 0;
for (ITree tree : root.getDescendants())
if (tree.isLeaf())
numberOfLeaves++;
return numberOfLeaves;
}
}
| 2,713
| 38.333333
| 118
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/cd/ChangeDistillerLeavesMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.cd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.simmetrics.StringMetrics;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeUtils;
public class ChangeDistillerLeavesMatcher extends Matcher {
public static final double LABEL_SIM_THRESHOLD = Double.parseDouble(System.getProperty("gt.cd.lsim", "0.5"));
public ChangeDistillerLeavesMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void match() {
List<Mapping> leavesMappings = new ArrayList<>();
List<ITree> dstLeaves = retainLeaves(TreeUtils.postOrder(dst));
for (Iterator<ITree> srcLeaves = TreeUtils.leafIterator(
TreeUtils.postOrderIterator(src)); srcLeaves.hasNext();) {
ITree srcLeaf = srcLeaves.next();
for (ITree dstLeaf: dstLeaves) {
if (isMappingAllowed(srcLeaf, dstLeaf)) {
double sim = StringMetrics.qGramsDistance().compare(srcLeaf.getLabel(), dstLeaf.getLabel());
if (sim > LABEL_SIM_THRESHOLD)
leavesMappings.add(new Mapping(srcLeaf, dstLeaf));
}
}
}
Set<ITree> ignoredSrcTrees = new HashSet<>();
Set<ITree> ignoredDstTrees = new HashSet<>();
Collections.sort(leavesMappings, new LeafMappingComparator());
while (leavesMappings.size() > 0) {
Mapping bestMapping = leavesMappings.remove(0);
if (!(ignoredSrcTrees.contains(bestMapping.getFirst())
|| ignoredDstTrees.contains(bestMapping.getSecond()))) {
addMapping(bestMapping.getFirst(),bestMapping.getSecond());
ignoredSrcTrees.add(bestMapping.getFirst());
ignoredDstTrees.add(bestMapping.getSecond());
}
}
}
public List<ITree> retainLeaves(List<ITree> trees) {
Iterator<ITree> treeIterator = trees.iterator();
while (treeIterator.hasNext()) {
ITree tree = treeIterator.next();
if (!tree.isLeaf())
treeIterator.remove();
}
return trees;
}
private static class LeafMappingComparator implements Comparator<Mapping> {
@Override
public int compare(Mapping m1, Mapping m2) {
return Double.compare(sim(m1), sim(m2));
}
public double sim(Mapping m) {
return StringMetrics.qGramsDistance().compare(m.getFirst().getLabel(), m.getSecond().getLabel());
}
}
}
| 3,667
| 35.68
| 113
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/cd/ChangeDistillerParallelLeavesMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers.heuristic.cd;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.simmetrics.StringMetrics;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeUtils;
/**
* Parallel variant of the ChangeDistiller leaves matcher.
*/
public class ChangeDistillerParallelLeavesMatcher extends Matcher {
private class ChangeDistillerCallableResult {
public final List<Mapping> leafMappings;
public final HashMap<Mapping, Double> simMap;
public ChangeDistillerCallableResult(List<Mapping> leafMappings,
HashMap<Mapping, Double> simMap) {
this.leafMappings = leafMappings;
this.simMap = simMap;
}
}
private class ChangeDistillerLeavesMatcherCallable
implements Callable<ChangeDistillerCallableResult> {
HashMap<String, Double> cacheResults = new HashMap<>();
private int cores;
private List<ITree> dstLeaves;
List<Mapping> leafMappings = new LinkedList<>();
HashMap<Mapping, Double> simMap = new HashMap<>();
private List<ITree> srcLeaves;
private int start;
public ChangeDistillerLeavesMatcherCallable(List<ITree> srcLeaves, List<ITree> dstLeaves,
int cores, int start) {
this.srcLeaves = srcLeaves;
this.dstLeaves = dstLeaves;
this.cores = cores;
this.start = start;
}
@Override
public ChangeDistillerCallableResult call() throws Exception {
for (int i = start; i < srcLeaves.size(); i += cores) {
ITree srcLeaf = srcLeaves.get(i);
for (ITree dstLeaf : dstLeaves) {
if (isMappingAllowed(srcLeaf, dstLeaf)) {
double sim = 0f;
// TODO: Use a unique string instead of @@
if (cacheResults.containsKey(srcLeaf.getLabel() + "@@" + dstLeaf.getLabel())) {
sim = cacheResults.get(srcLeaf.getLabel() + "@@" + dstLeaf.getLabel());
} else {
sim = StringMetrics.qGramsDistance().compare(srcLeaf.getLabel(), dstLeaf.getLabel());
cacheResults.put(srcLeaf.getLabel() + "@@" + dstLeaf.getLabel(), sim);
}
if (sim > LABEL_SIM_THRESHOLD) {
Mapping mapping = new Mapping(srcLeaf, dstLeaf);
leafMappings.add(new Mapping(srcLeaf, dstLeaf));
simMap.put(mapping, sim);
}
}
}
}
return new ChangeDistillerCallableResult(leafMappings, simMap);
}
}
private class LeafMappingComparator implements Comparator<Mapping> {
HashMap<Mapping, Double> simMap = null;
public LeafMappingComparator(HashMap<Mapping, Double> simMap) {
this.simMap = simMap;
}
@Override
public int compare(Mapping m1, Mapping m2) {
return Double.compare(sim(m1), sim(m2));
}
public double sim(Mapping mapping) {
return simMap.get(mapping);
}
}
private static final double LABEL_SIM_THRESHOLD = 0.5D;
public ChangeDistillerParallelLeavesMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
/**
* Match.
*/
@Override
public void match() {
List<ITree> dstLeaves = retainLeaves(TreeUtils.postOrder(dst));
List<ITree> srcLeaves = retainLeaves(TreeUtils.postOrder(src));
List<Mapping> leafMappings = new LinkedList<>();
HashMap<Mapping, Double> simMap = new HashMap<>();
int cores = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(cores);
@SuppressWarnings("unchecked")
Future<ChangeDistillerCallableResult>[] futures = new Future[cores];
for (int i = 0; i < cores; i++) {
futures[i] =
service.submit(new ChangeDistillerLeavesMatcherCallable(srcLeaves, dstLeaves, cores, i));
}
for (int i = 0; i < cores; i++) {
try {
ChangeDistillerCallableResult result = futures[i].get();
leafMappings.addAll(result.leafMappings);
simMap.putAll(result.simMap);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
service.shutdown();
try {
service.awaitTermination(10, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
Set<ITree> srcIgnored = new HashSet<>();
Set<ITree> dstIgnored = new HashSet<>();
Collections.sort(leafMappings, new LeafMappingComparator(simMap));
while (leafMappings.size() > 0) {
Mapping best = leafMappings.remove(0);
if (!(srcIgnored.contains(best.getFirst()) || dstIgnored.contains(best.getSecond()))) {
addMapping(best.getFirst(), best.getSecond());
srcIgnored.add(best.getFirst());
dstIgnored.add(best.getSecond());
}
}
}
private List<ITree> retainLeaves(List<ITree> trees) {
Iterator<ITree> tit = trees.iterator();
while (tit.hasNext()) {
ITree tree = tit.next();
if (!tree.isLeaf()) {
tit.remove();
}
}
return trees;
}
}
| 7,034
| 35.640625
| 113
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/AbstractBottomUpMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2016 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2016 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.optimal.zs.ZsMatcher;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeMap;
public abstract class AbstractBottomUpMatcher extends Matcher {
//TODO make final?
public static int SIZE_THRESHOLD =
Integer.parseInt(System.getProperty("gt.bum.szt", "100"));
//seems SIZE_THRESHOLD will significantly affect the speed and scalability of analysis
public static final double SIM_THRESHOLD =
Double.parseDouble(System.getProperty("gt.bum.smt", "0.5"));
protected TreeMap srcIds;
protected TreeMap dstIds;
protected TreeMap mappedSrc;
protected TreeMap mappedDst;
public AbstractBottomUpMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
srcIds = new TreeMap(src);
dstIds = new TreeMap(dst);
mappedSrc = new TreeMap();
mappedDst = new TreeMap();
for (Mapping m : store.asSet()) {
mappedSrc.putTrees(m.getFirst());
mappedDst.putTrees(m.getSecond());
}
}
protected List<ITree> getDstCandidates(ITree src) {
List<ITree> seeds = new ArrayList<>();
for (ITree c: src.getDescendants()) {
ITree m = mappings.getDst(c);
if (m != null) seeds.add(m);
}
List<ITree> candidates = new ArrayList<>();
Set<ITree> visited = new HashSet<>();
for (ITree seed: seeds) {
while (seed.getParent() != null) {
ITree parent = seed.getParent();
if (visited.contains(parent))
break;
visited.add(parent);
if (parent.getType() == src.getType() && !isDstMatched(parent) && !parent.isRoot())
candidates.add(parent);
seed = parent;
}
}
return candidates;
}
//FIXME checks if it is better or not to remove the already found mappings.
protected void lastChanceMatch(ITree src, ITree dst) {
ITree cSrc = src.deepCopy();
ITree cDst = dst.deepCopy();
removeMatched(cSrc, true);
removeMatched(cDst, false);
HashMap<ITree, ITree> newcandidates = new HashMap<>();
if (cSrc.getSize() < AbstractBottomUpMatcher.SIZE_THRESHOLD
|| cDst.getSize() < AbstractBottomUpMatcher.SIZE_THRESHOLD) {
Matcher m = new ZsMatcher(cSrc, cDst, new MappingStore());
m.match();
for (Mapping candidate: m.getMappings()) {
ITree left = srcIds.getTree(candidate.getFirst().getId());
ITree right = dstIds.getTree(candidate.getSecond().getId());
// System.out.println("ZsMatcher"+src.getId()+" :"+left.getId()+","+right.getId());
if (left.getId() == src.getId() || right.getId() == dst.getId()) {
// System.err.printf("Trying to map already mapped source node (%d == %d || %d == %d)\n",
// left.getId(), src.getId(), right.getId(), dst.getId());
continue;
} else if (!isMappingAllowed(left, right)) {
// System.err.printf("Trying to map incompatible nodes (%s, %s)\n",
// left.toShortString(), right.toShortString());
continue;
} else {
// if(left.getId()==514) {
// System.err.println("find514");
// Matcher m1 = new ZsMatcher(left, right, new MappingStore());
// m1.match();
// System.out.println("514size:"+m1.getMappings().asSet().size());
// for (Mapping map: m1.getMappings()) {
// ITree left1 = map.first;
// ITree right1 = map.second;
// System.out.println("Recover:"+left1.getId()+","+right1.getId());
// }
// }
double sim = diceSimilarity(left, right);
if(!left.isLeaf()){
if(sim >= SIM_THRESHOLD) {
addMapping(left, right);
// System.out.println("ZsMatcher"+src.getId()+" :"+left.getId()+","+right.getId());
}else {
newcandidates.put(left, right);
}
}else {
addMapping(left, right);
// System.out.println("ZsMatcher"+src.getId()+" :"+left.getId()+","+right.getId());
}
}
}
for(Map.Entry<ITree, ITree> entry : newcandidates.entrySet()) {
ITree left = entry.getKey();
ITree right = entry.getValue();
double sim = diceSimilarity(left, right);
if(sim >= SIM_THRESHOLD) {
addMapping(left, right);
}
}
}
// mappedSrc.putTrees(src);
// mappedDst.putTrees(dst);
}
/**
* Remove mapped nodes from the tree. Be careful this method will invalidate
* all the metrics of this tree and its descendants. If you need them, you need
* to recompute them.
*/
public ITree removeMatched(ITree tree, boolean isSrc) {
for (ITree t: tree.getTrees()) {
if ((isSrc && isSrcMatched(t)) || ((!isSrc) && isDstMatched(t))) {
if (t.getParent() != null) t.getParent().getChildren().remove(t);
t.setParent(null);
}
}
tree.refresh();
return tree;
}
@Override
public boolean isMappingAllowed(ITree src, ITree dst) {
return src.hasSameType(dst)
&& !(isSrcMatched(src) || isDstMatched(dst));
}
@Override
protected void addMapping(ITree src, ITree dst) {
mappedSrc.putTree(src);
mappedDst.putTree(dst);
super.addMapping(src, dst);
}
boolean isSrcMatched(ITree tree) {
return mappedSrc.contains(tree);
}
boolean isDstMatched(ITree tree) {
return mappedDst.contains(tree);
}
}
| 7,172
| 36.952381
| 108
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/AbstractMappingComparator.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2016 Jean-Rémy Falleri <jr.falleri@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
public abstract class AbstractMappingComparator implements Comparator<Mapping> {
protected List<Mapping> ambiguousMappings;
protected Map<Mapping, Double> similarities = new HashMap<>();
protected int maxTreeSize;
protected MappingStore mappings;
public AbstractMappingComparator(List<Mapping> ambiguousMappings, MappingStore mappings, int maxTreeSize) {
this.maxTreeSize = maxTreeSize;
this.mappings = mappings;
this.ambiguousMappings = ambiguousMappings;
// System.out.println("AbstractMappingComparator");
}
@Override
public int compare(Mapping m1, Mapping m2) {
if (similarities.get(m2).compareTo(similarities.get(m1)) != 0) {
return Double.compare(similarities.get(m2), similarities.get(m1));
}
if (m1.first.getId() != m2.first.getId()) {
return Integer.compare(m1.first.getId(), m2.first.getId());
}
return Integer.compare(m1.second.getId(), m2.second.getId());
}
protected abstract double similarity(ITree src, ITree dst);
protected double posInParentSimilarity(ITree src, ITree dst) {
int posSrc = (src.isRoot()) ? 0 : src.getParent().getChildPosition(src);
int posDst = (dst.isRoot()) ? 0 : dst.getParent().getChildPosition(dst);
int maxSrcPos = (src.isRoot()) ? 1 : src.getParent().getChildren().size();
int maxDstPos = (dst.isRoot()) ? 1 : dst.getParent().getChildren().size();
int maxPosDiff = Math.max(maxSrcPos, maxDstPos);
return 1D - ((double) Math.abs(posSrc - posDst) / (double) maxPosDiff);
}
protected double numberingSimilarity(ITree src, ITree dst) {
return 1D - ((double) Math.abs(src.getId() - dst.getId())
/ (double) maxTreeSize);
}
}
| 2,809
| 35.973684
| 111
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/AbstractSubtreeMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.MultiMappingStore;
import gumtreediff.tree.ITree;
public abstract class AbstractSubtreeMatcher extends Matcher {
public static int MIN_HEIGHT = Integer.parseInt(
System.getProperty("gt.stm.mh", System.getProperty("gumtree.match.gt.minh", "2"))
);
public AbstractSubtreeMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
private void popLarger(PriorityTreeList srcTrees, PriorityTreeList dstTrees) {
if (srcTrees.peekHeight() > dstTrees.peekHeight())
srcTrees.open();
else
dstTrees.open();
}
@Override
public void match() {
MultiMappingStore multiMappings = new MultiMappingStore();
PriorityTreeList srcTrees = new PriorityTreeList(src);
PriorityTreeList dstTrees = new PriorityTreeList(dst);
while (srcTrees.peekHeight() != -1 && dstTrees.peekHeight() != -1) {
while (srcTrees.peekHeight() != dstTrees.peekHeight())
popLarger(srcTrees, dstTrees);
List<ITree> currentHeightSrcTrees = srcTrees.pop();
List<ITree> currentHeightDstTrees = dstTrees.pop();
// for(ITree node : currentHeightSrcTrees) {
// System.out.print(node.getId()+",");
// }
// for(ITree node : currentHeightDstTrees) {
// System.out.print(node.getId()+",");
// }
boolean[] marksForSrcTrees = new boolean[currentHeightSrcTrees.size()];
boolean[] marksForDstTrees = new boolean[currentHeightDstTrees.size()];
for (int i = 0; i < currentHeightSrcTrees.size(); i++) {
for (int j = 0; j < currentHeightDstTrees.size(); j++) {
ITree src = currentHeightSrcTrees.get(i);
ITree dst = currentHeightDstTrees.get(j);
if (src.isIsomorphicTo(dst)) {
// System.out.println("Iso ID:"+src.getId());
multiMappings.link(src, dst);
marksForSrcTrees[i] = true;
marksForDstTrees[j] = true;
}
}
}
for (int i = 0; i < marksForSrcTrees.length; i++)
if (!marksForSrcTrees[i])
srcTrees.open(currentHeightSrcTrees.get(i));
for (int j = 0; j < marksForDstTrees.length; j++)
if (!marksForDstTrees[j])
dstTrees.open(currentHeightDstTrees.get(j));
srcTrees.updateHeight();
dstTrees.updateHeight();
}
Set<Mapping> mappings = multiMappings.getMappings();
for(Mapping map : mappings) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
// System.out.println("greedyDownMap ID:"+src.getId()+"->"+dst.getId());
}
filterMappings(multiMappings);
}
public abstract void filterMappings(MultiMappingStore multiMappings);
protected double sim(ITree src, ITree dst) {
double jaccard = jaccardSimilarity(src.getParent(), dst.getParent());
int posSrc = (src.isRoot()) ? 0 : src.getParent().getChildPosition(src);
int posDst = (dst.isRoot()) ? 0 : dst.getParent().getChildPosition(dst);
int maxSrcPos = (src.isRoot()) ? 1 : src.getParent().getChildren().size();
int maxDstPos = (dst.isRoot()) ? 1 : dst.getParent().getChildren().size();
int maxPosDiff = Math.max(maxSrcPos, maxDstPos);
double pos = 1D - ((double) Math.abs(posSrc - posDst) / (double) maxPosDiff);
double po = 1D - ((double) Math.abs(src.getId() - dst.getId()) / (double) this.getMaxTreeSize());
return 100 * jaccard + 10 * pos + po;
}
protected int getMaxTreeSize() {
return Math.max(src.getSize(), dst.getSize());
}
protected void retainBestMapping(List<Mapping> mappings, Set<ITree> srcIgnored, Set<ITree> dstIgnored) {
while (mappings.size() > 0) {
Mapping mapping = mappings.remove(0);
if (!(srcIgnored.contains(mapping.getFirst()) || dstIgnored.contains(mapping.getSecond()))) {
addMappingRecursively(mapping.getFirst(), mapping.getSecond());
// System.out.println("retainBestMapping:"+mapping.getFirst().getId()+","+mapping.getSecond().getId());
srcIgnored.add(mapping.getFirst());
srcIgnored.addAll(mapping.first.getDescendants());
dstIgnored.add(mapping.getSecond());
dstIgnored.addAll(mapping.second.getDescendants());
}
}
}
private static class PriorityTreeList {
private List<ITree>[] trees;
private int maxHeight;
private int currentIdx;
@SuppressWarnings("unchecked")
public PriorityTreeList(ITree tree) {
int listSize = tree.getHeight() - MIN_HEIGHT + 1;
if (listSize < 0)
listSize = 0;
if (listSize == 0)
currentIdx = -1;
trees = new ArrayList[listSize];
maxHeight = tree.getHeight();
addTree(tree);
}
private int idx(ITree tree) {
return idx(tree.getHeight());
}
private int idx(int height) {
return maxHeight - height;
}
private int height(int idx) {
return maxHeight - idx;
}
private void addTree(ITree tree) {
if (tree.getHeight() >= MIN_HEIGHT) {
int idx = idx(tree);
if (trees[idx] == null) trees[idx] = new ArrayList<>();
trees[idx].add(tree);
}
}
public List<ITree> open() {
List<ITree> pop = pop();
if (pop != null) {
for (ITree tree: pop) open(tree);
updateHeight();
return pop;
} else return null;
}
public List<ITree> pop() {
if (currentIdx == -1)
return null;
else {
List<ITree> pop = trees[currentIdx];
trees[currentIdx] = null;
return pop;
}
}
public void open(ITree tree) {
for (ITree c: tree.getChildren()) addTree(c);
}
public int peekHeight() {
return (currentIdx == -1) ? -1 : height(currentIdx);
}
public void updateHeight() {
currentIdx = -1;
for (int i = 0; i < trees.length; i++) {
if (trees[i] != null) {
currentIdx = i;
break;
}
}
}
}
}
| 7,787
| 34.889401
| 118
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/CliqueSubtreeMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import gnu.trove.map.hash.TIntObjectHashMap;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.MultiMappingStore;
import gumtreediff.tree.ITree;
import gumtreediff.utils.Pair;
public class CliqueSubtreeMatcher extends AbstractSubtreeMatcher {
public CliqueSubtreeMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void filterMappings(MultiMappingStore multiMappings) {
TIntObjectHashMap<Pair<List<ITree>, List<ITree>>> cliques = new TIntObjectHashMap<>();
for (Mapping m : multiMappings) {
int hash = m.getFirst().getHash();
if (!cliques.containsKey(hash))
cliques.put(hash, new Pair<>(new ArrayList<>(), new ArrayList<>()));
cliques.get(hash).getFirst().add(m.getFirst());
cliques.get(hash).getSecond().add(m.getSecond());
}
List<Pair<List<ITree>, List<ITree>>> ccliques = new ArrayList<>();
for (int hash : cliques.keys()) {
Pair<List<ITree>, List<ITree>> clique = cliques.get(hash);
if (clique.getFirst().size() == 1 && clique.getSecond().size() == 1) {
addMappingRecursively(clique.getFirst().get(0), clique.getSecond().get(0));
cliques.remove(hash);
} else
ccliques.add(clique);
}
Collections.sort(ccliques, new CliqueComparator());
for (Pair<List<ITree>, List<ITree>> clique : ccliques) {
List<Mapping> cliqueAsMappings = fromClique(clique);
Collections.sort(cliqueAsMappings, new MappingComparator(cliqueAsMappings));
Set<ITree> srcIgnored = new HashSet<>();
Set<ITree> dstIgnored = new HashSet<>();
retainBestMapping(cliqueAsMappings, srcIgnored, dstIgnored);
}
}
private List<Mapping> fromClique(Pair<List<ITree>, List<ITree>> clique) {
List<Mapping> cliqueAsMappings = new ArrayList<>();
for (ITree src: clique.getFirst())
for (ITree dst: clique.getFirst())
cliqueAsMappings.add(new Mapping(src, dst));
return cliqueAsMappings;
}
private static class CliqueComparator implements Comparator<Pair<List<ITree>, List<ITree>>> {
@Override
public int compare(Pair<List<ITree>, List<ITree>> l1,
Pair<List<ITree>, List<ITree>> l2) {
int minDepth1 = minDepth(l1);
int minDepth2 = minDepth(l2);
if (minDepth1 != minDepth2)
return -1 * Integer.compare(minDepth1, minDepth2);
else {
int size1 = size(l1);
int size2 = size(l2);
return -1 * Integer.compare(size1, size2);
}
}
private int minDepth(Pair<List<ITree>, List<ITree>> trees) {
int depth = Integer.MAX_VALUE;
for (ITree t : trees.getFirst())
if (depth > t.getDepth())
depth = t.getDepth();
for (ITree t : trees.getSecond())
if (depth > t.getDepth())
depth = t.getDepth();
return depth;
}
private int size(Pair<List<ITree>, List<ITree>> trees) {
return trees.getFirst().size() + trees.getSecond().size();
}
}
private class MappingComparator implements Comparator<Mapping> {
private Map<Mapping, double[]> simMap = new HashMap<>();
public MappingComparator(List<Mapping> mappings) {
for (Mapping mapping: mappings)
simMap.put(mapping, sims(mapping.getFirst(), mapping.getSecond()));
}
@Override
public int compare(Mapping m1, Mapping m2) {
double[] sims1 = simMap.get(m1);
double[] sims2 = simMap.get(m2);
for (int i = 0; i < sims1.length; i++) {
if (sims1[i] != sims2[i])
return -1 * Double.compare(sims2[i], sims2[i]);
}
return 0;
}
private Map<ITree, List<ITree>> srcDescendants = new HashMap<>();
private Map<ITree, Set<ITree>> dstDescendants = new HashMap<>();
protected int numberOfCommonDescendants(ITree src, ITree dst) {
if (!srcDescendants.containsKey(src))
srcDescendants.put(src, src.getDescendants());
if (!dstDescendants.containsKey(dst))
dstDescendants.put(dst, new HashSet<>(dst.getDescendants()));
int common = 0;
for (ITree t: srcDescendants.get(src)) {
ITree m = mappings.getDst(t);
if (m != null && dstDescendants.get(dst).contains(m)) common++;
}
return common;
}
protected double[] sims(ITree src, ITree dst) {
double[] sims = new double[4];
sims[0] = jaccardSimilarity(src.getParent(), dst.getParent());
sims[1] = src.positionInParent() - dst.positionInParent();
sims[2] = src.getId() - dst.getId();
sims[3] = src.getId();
return sims;
}
protected double jaccardSimilarity(ITree src, ITree dst) {
double num = numberOfCommonDescendants(src, dst);
double den = (double) srcDescendants.get(src).size() + (double) dstDescendants.get(dst).size() - num;
return num / den;
}
}
}
| 6,554
| 36.244318
| 113
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/CompleteBottomUpMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.List;
import java.util.stream.Collectors;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
/**
* Match the nodes using a bottom-up approach. It browse the nodes of the source and destination trees
* using a post-order traversal, testing if the two selected trees might be mapped. The two trees are mapped
* if they are mappable and have a dice coefficient greater than SIM_THRESHOLD. Whenever two trees are mapped
* a exact ZS algorithm is applied to look to possibly forgotten nodes.
*/
public class CompleteBottomUpMatcher extends AbstractBottomUpMatcher {
public CompleteBottomUpMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void match() {
for (ITree t: src.postOrder()) {
if (t.isRoot()) {
addMapping(t, this.dst);
lastChanceMatch(t, this.dst);
break;
} else if (!(isSrcMatched(t) || t.isLeaf())) {
List<ITree> srcCandidates = t.getParents().stream()
.filter(p -> p.getType() == t.getType())
.collect(Collectors.toList());
List<ITree> dstCandidates = getDstCandidates(t);
ITree srcBest = null;
ITree dstBest = null;
double max = -1D;
for (ITree srcCand: srcCandidates) {
for (ITree dstCand: dstCandidates) {
double sim = jaccardSimilarity(srcCand, dstCand);
if (sim > max && sim >= SIM_THRESHOLD) {
max = sim;
srcBest = srcCand;
dstBest = dstCand;
}
}
}
if (srcBest != null) {
lastChanceMatch(srcBest, dstBest);
addMapping(srcBest, dstBest);
}
}
}
}
}
| 2,883
| 36.454545
| 109
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/FirstMatchBottomUpMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
/**
* Match the nodes using a bottom-up approach. It browse the nodes of the source and destination trees
* using a post-order traversal, testing if the two selected trees might be mapped. The two trees are mapped
* if they are mappable and have a dice coefficient greater than SIM_THRESHOLD. Whenever two trees are mapped
* a exact ZS algorithm is applied to look to possibly forgotten nodes.
*/
public class FirstMatchBottomUpMatcher extends AbstractBottomUpMatcher {
public FirstMatchBottomUpMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void match() {
match(removeMatched(src, true), removeMatched(dst, false));
}
private void match(ITree src, ITree dst) {
for (ITree s: src.postOrder()) {
for (ITree d: dst.postOrder()) {
if (isMappingAllowed(s, d) && !(s.isLeaf() || d.isLeaf())) {
double sim = jaccardSimilarity(s, d);
if (sim >= SIM_THRESHOLD || (s.isRoot() && d.isRoot()) ) {
if (!(areDescendantsMatched(s, true) || areDescendantsMatched(d, false)))
lastChanceMatch(s, d);
addMapping(s, d);
break;
}
}
}
}
}
/**
* Indicate whether or not all the descendants of the trees are already mapped.
*/
public boolean areDescendantsMatched(ITree tree, boolean isSrc) {
for (ITree c: tree.getDescendants())
if (!((isSrc && isSrcMatched(c)) || (!isSrc && isDstMatched(tree)))) // FIXME ugly but this class is unused
return false;
return true;
}
}
| 2,689
| 37.428571
| 119
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/GreedyBottomUpMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-R茅my Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Flor茅al Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.List;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
/**
* Match the nodes using a bottom-up approach. It browse the nodes of the source and destination trees
* using a post-order traversal, testing if the two selected trees might be mapped. The two trees are mapped
* if they are mappable and have a dice coefficient greater than SIM_THRESHOLD. Whenever two trees are mapped
* a exact ZS algorithm is applied to look to possibly forgotten nodes.
*/
public class GreedyBottomUpMatcher extends AbstractBottomUpMatcher {
public GreedyBottomUpMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
System.out.println("GreedyBottomUpMatcher");
}
@Override
public void match() {
for (ITree t: src.postOrder()) {
if (t.isRoot()) {
addMapping(t, this.dst);
lastChanceMatch(t, this.dst);
break;
} else if (!(isSrcMatched(t) || t.isLeaf())) {
List<ITree> candidates = getDstCandidates(t);
ITree best = null;
double max = -1D;
// if(t.getId()==38) {
// System.out.println("candiNum:"+candidates.size());
// for (ITree cand: candidates) {
// double sim = diceSimilarity(t, cand);
// System.out.println("candiID:"+cand.getId()+","+sim);
// }
// }
for (ITree cand: candidates) {
double sim = diceSimilarity(t, cand);
if (sim > max && sim >= SIM_THRESHOLD) {
max = sim;
best = cand;
}//如果sim=max,是否应有多个候选集
}
if (best != null) {
lastChanceMatch(t, best);
addMapping(t, best);
// System.out.println("AddMatcher:"+t.getId()+","+best.getId());
}
}
}
//RecoveryMatcher
for (ITree t: src.postOrder()) {
if (t.isRoot()) {
break;
} else if (!(isSrcMatched(t) || t.isLeaf())) {
List<ITree> candidates = getDstCandidates(t);
ITree best = null;
double max = -1D;
for (ITree cand: candidates) {
double sim = diceSimilarity(t, cand);
if (sim > max && sim >= SIM_THRESHOLD) {
max = sim;
best = cand;
}
}
if (best != null) {
addMapping(t, best);
// System.out.println("RecoveryMatcher:"+t.getId()+","+best.getId());
}
}
}
}
}
| 3,728
| 34.855769
| 109
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/GreedySubtreeMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.MultiMappingStore;
import gumtreediff.tree.ITree;
public class GreedySubtreeMatcher extends AbstractSubtreeMatcher {
public GreedySubtreeMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
// System.out.println("GreedySubtreeMatcher");
}
@Override
public void filterMappings(MultiMappingStore multiMappings) {
// Select unique mappings first and extract ambiguous mappings.
List<Mapping> ambiguousList = new ArrayList<>();
Set<ITree> ignored = new HashSet<>();
for (ITree src: multiMappings.getSrcs()) {
boolean isMappingUnique = false;
if (multiMappings.isSrcUnique(src)) {
if (multiMappings.isSrcUnique(src)) {
ITree dst = multiMappings.getDst(src).iterator().next();
if (multiMappings.isDstUnique(dst)) {
addMappingRecursively(src, dst);
isMappingUnique = true;
}
}
}
if (!(ignored.contains(src) || isMappingUnique)) {
Set<ITree> adsts = multiMappings.getDst(src);
Set<ITree> asrcs = multiMappings.getSrc(multiMappings.getDst(src).iterator().next());
for (ITree asrc : asrcs)
for (ITree adst: adsts)
ambiguousList.add(new Mapping(asrc, adst));
ignored.addAll(asrcs);
}
}
for(Mapping map : ambiguousList) {
ITree src = map.first;
ITree dst = map.second;
// System.out.println("ambiguousMap:"+src.getId()+","+dst.getId());
}
// Rank the mappings by score.
Set<ITree> srcIgnored = new HashSet<>();
Set<ITree> dstIgnored = new HashSet<>();
Collections.sort(ambiguousList, new SiblingsMappingComparator(ambiguousList, mappings, getMaxTreeSize()));
// Select the best ambiguous mappings
retainBestMapping(ambiguousList, srcIgnored, dstIgnored);
}
}
| 3,151
| 37.439024
| 114
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/HungarianSubtreeMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.MultiMappingStore;
import gumtreediff.tree.ITree;
import gumtreediff.utils.HungarianAlgorithm;
public class HungarianSubtreeMatcher extends AbstractSubtreeMatcher {
public HungarianSubtreeMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void filterMappings(MultiMappingStore multiMappings) {
List<MultiMappingStore> ambiguousList = new ArrayList<>();
Set<ITree> ignored = new HashSet<>();
for (ITree src: multiMappings.getSrcs())
if (multiMappings.isSrcUnique(src))
addMappingRecursively(src, multiMappings.getDst(src).iterator().next());
else if (!ignored.contains(src)) {
MultiMappingStore ambiguous = new MultiMappingStore();
Set<ITree> adsts = multiMappings.getDst(src);
Set<ITree> asrcs = multiMappings.getSrc(multiMappings.getDst(src).iterator().next());
for (ITree asrc : asrcs)
for (ITree adst: adsts)
ambiguous.link(asrc ,adst);
ambiguousList.add(ambiguous);
ignored.addAll(asrcs);
}
Collections.sort(ambiguousList, new MultiMappingComparator());
for (MultiMappingStore ambiguous: ambiguousList) {
System.out.println("hungarian try.");
List<ITree> lstSrcs = new ArrayList<>(ambiguous.getSrcs());
List<ITree> lstDsts = new ArrayList<>(ambiguous.getDsts());
double[][] matrix = new double[lstSrcs.size()][lstDsts.size()];
for (int i = 0; i < lstSrcs.size(); i++)
for (int j = 0; j < lstDsts.size(); j++)
matrix[i][j] = cost(lstSrcs.get(i), lstDsts.get(j));
HungarianAlgorithm hgAlg = new HungarianAlgorithm(matrix);
int[] solutions = hgAlg.execute();
for (int i = 0; i < solutions.length; i++) {
int dstIdx = solutions[i];
if (dstIdx != -1) addMappingRecursively(lstSrcs.get(i), lstDsts.get(dstIdx));
}
}
}
private double cost(ITree src, ITree dst) {
return 111D - sim(src, dst);
}
private static class MultiMappingComparator implements Comparator<MultiMappingStore> {
@Override
public int compare(MultiMappingStore m1, MultiMappingStore m2) {
return Integer.compare(impact(m1), impact(m2));
}
public int impact(MultiMappingStore m) {
int impact = 0;
for (ITree src: m.getSrcs()) {
int pSize = src.getParents().size();
if (pSize > impact) impact = pSize;
}
for (ITree src: m.getDsts()) {
int pSize = src.getParents().size();
if (pSize > impact) impact = pSize;
}
return impact;
}
}
}
| 4,002
| 36.764151
| 101
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/ParentsMappingComparator.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2016 Jean-Rémy Falleri <jr.falleri@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.List;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
import gumtreediff.utils.StringAlgorithms;
public final class ParentsMappingComparator extends AbstractMappingComparator {
public ParentsMappingComparator(List<Mapping> ambiguousMappings, MappingStore mappings, int maxTreeSize) {
super(ambiguousMappings, mappings, maxTreeSize);
for (Mapping ambiguousMapping: ambiguousMappings)
similarities.put(ambiguousMapping, similarity(ambiguousMapping.getFirst(), ambiguousMapping.getSecond()));
}
@Override
protected double similarity(ITree src, ITree dst) {
return 100D * parentsJaccardSimilarity(src, dst)
+ 10D * posInParentSimilarity(src, dst) + numberingSimilarity(src , dst);
}
protected double parentsJaccardSimilarity(ITree src, ITree dst) {
List<ITree> srcParents = src.getParents();
List<ITree> dstParents = dst.getParents();
double numerator = StringAlgorithms.lcss(srcParents, dstParents).size();
double denominator = (double) srcParents.size() + (double) dstParents.size() - numerator;
return numerator / denominator;
}
}
| 2,036
| 38.941176
| 118
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/heuristic/gt/SiblingsMappingComparator.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2016 Jean-Rémy Falleri <jr.falleri@gmail.com>
*/
package gumtreediff.matchers.heuristic.gt;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
public final class SiblingsMappingComparator extends AbstractMappingComparator {
private Map<ITree, List<ITree>> srcDescendants = new HashMap<>();
private Map<ITree, Set<ITree>> dstDescendants = new HashMap<>();
public SiblingsMappingComparator(List<Mapping> ambiguousMappings, MappingStore mappings, int maxTreeSize) {
super(ambiguousMappings, mappings, maxTreeSize);
for (Mapping ambiguousMapping: ambiguousMappings)
similarities.put(ambiguousMapping, similarity(ambiguousMapping.getFirst(), ambiguousMapping.getSecond()));
}
@Override
protected double similarity(ITree src, ITree dst) {
return 100D * siblingsJaccardSimilarity(src.getParent(), dst.getParent())
+ 10D * posInParentSimilarity(src, dst) + numberingSimilarity(src , dst);
}
protected double siblingsJaccardSimilarity(ITree src, ITree dst) {
double num = numberOfCommonDescendants(src, dst);
double den = (double) srcDescendants.get(src).size() + (double) dstDescendants.get(dst).size() - num;
return num / den;
}
protected int numberOfCommonDescendants(ITree src, ITree dst) {
if (!srcDescendants.containsKey(src))
srcDescendants.put(src, src.getDescendants());
if (!dstDescendants.containsKey(dst))
dstDescendants.put(dst, new HashSet<>(dst.getDescendants()));
int common = 0;
for (ITree t: srcDescendants.get(src)) {
ITree m = mappings.getDst(t);
if (m != null && dstDescendants.get(dst).contains(m))
common++;
}
return common;
}
}
| 2,675
| 35.657534
| 118
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimal/rted/InfoTree.java
|
// Copyright (C) 2012 Mateusz Pawlik and Nikolaus Augsten
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package gumtreediff.matchers.optimal.rted;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import gumtreediff.tree.ITree;
/**
* Stores all needed information about a single tree in several indeces.
*
* @author Mateusz Pawlik
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class InfoTree {
private ITree inputTree;
private static final byte LEFT = 0;
private static final byte RIGHT = 1;
private static final byte HEAVY = 2;
private static final byte BOTH = 3;
//private static final byte REVLEFT = 4;
//private static final byte REVRIGHT = 5;
//private static final byte REVHEAVY = 6;
// constants for indeces numbers
public static final byte POST2_SIZE = 0;
public static final byte POST2_KR_SUM = 1;
public static final byte POST2_REV_KR_SUM = 2;
public static final byte POST2_DESC_SUM = 3; // number of subforests in full decomposition
public static final byte POST2_PRE = 4;
public static final byte POST2_PARENT = 5;
public static final byte POST2_LABEL = 6;
public static final byte KR = 7; // key root nodes (size of this array = leaf count)
public static final byte POST2_LLD = 8; // left-most leaf descendants
public static final byte POST2_MIN_KR = 9; // minimum key root nodes index in KR array
public static final byte RKR = 10; // reversed key root nodes
public static final byte RPOST2_RLD = 11; // reversed postorer 2 right-most leaf descendants
public static final byte RPOST2_MIN_RKR = 12;
public static final byte RPOST2_POST = 13; // reversed postorder -> postorder
public static final byte POST2_STRATEGY = 14; // strategy for Demaine (is there sth on the left/right of the heavy node)
public static final byte PRE2_POST = 15;
public int[][] info; // an array with all the indeces
private LabelDictionary ld; // dictionary with labels - common for two input trees
public boolean[][] nodeType; // store the type of a node: for every node stores three boolean values (L, R, H)
// paths and rel subtrees are inside 2D arrays to be able to get them by paths/relsubtrees[L/R/H][node]
private int[][] paths;
private int[][][] relSubtrees;
// temporal variables
private int sizeTmp = 0; // temporal value of size of a subtree
private int descSizesTmp = 0; // temporal value of sum of descendat sizes
private int krSizesSumTmp = 0; // temporal value of sum of key roots sizes
private int revkrSizesSumTmp = 0; // temporal value of sum of reversed hey roots sizes
private int preorderTmp = 0; // temporal value of preorder
// remembers what is the current node's postorder (current in the TED recursion)
private int currentNode = -1;
// remembers if the trees order was switched during the recursion (in comparison with the order of input trees)
private boolean switched = false;
// as the names say
private int leafCount = 0;
private int treeSize = 0;
public static void main(String[] args) {
}
/**
* Creates an InfoTree object, gathers all information about aInputTree and stores in indexes.
* aInputTree is not needed any more.
* Remember to pass the same LabelDictionary object to both trees which are compared.
*
* @param aInputTree an LblTree object
* @param aLd a LabelDictionary object
*/
public InfoTree(ITree aInputTree, LabelDictionary aLd) {
this.inputTree = aInputTree;
treeSize = inputTree.getSize();
this.info = new int[16][treeSize];
Arrays.fill(info[POST2_PARENT], -1);
Arrays.fill(info[POST2_MIN_KR], -1);
Arrays.fill(info[RPOST2_MIN_RKR], -1);
Arrays.fill(info[POST2_STRATEGY], -1);
this.paths = new int[3][treeSize]; Arrays.fill(paths[LEFT], -1); Arrays.fill(paths[RIGHT], -1); Arrays.fill(paths[HEAVY], -1);
this.relSubtrees = new int[3][treeSize][];
this.nodeType = new boolean[3][treeSize];
this.ld = aLd;
this.currentNode = treeSize - 1;
gatherInfo(inputTree, -1);
postTraversalProcessing();
}
/**
* Returns the size of the tree.
*
* @return
*/
public int getSize() {
return treeSize;
}
public boolean ifNodeOfType(int postorder, int type) {
return nodeType[type][postorder];
}
public boolean[] getNodeTypeArray(int type) {
return nodeType[type];
}
/**
* For given infoCode and postorder of a node returns requested information of that node.
*
* @param infoCode
* @param nodesPostorder postorder of a node
* @return a value of requested information
*/
public int getInfo(int infoCode, int nodesPostorder) {
// return info under infoCode and nodesPostorder
return info[infoCode][nodesPostorder];
}
/**
* For given infoCode returns an info array (index array)
*
* @param infoCode
* @return array with requested index
*/
public int[] getInfoArray(int infoCode) {
return info[infoCode];
}
/**
* Returns relevant subtrees for given node. Assuming that child v of given node belongs to given path,
* all children of given node are returned but node v.
*
* @param pathType
* @param nodePostorder postorder of a node
* @return an array with relevant subtrees of a given node
*/
public int[] getNodeRelSubtrees(int pathType, int nodePostorder) {
return relSubtrees[pathType][nodePostorder];
}
/**
* Returns an array representation of a given path's type.
*
* @param pathType
* @return an array with a requested path
*/
public int[] getPath(int pathType) {
return paths[pathType];
}
/**
* Returns the postorder of current root node.
*
* @return
*/
public int getCurrentNode() {
return currentNode;
}
/**
* Sets postorder of the current node in the recursion.
*
* @param postorder
*/
public void setCurrentNode(int postorder) {
currentNode = postorder;
}
/**
* Gathers information of a given tree in corresponding arrays.
*
* At this point the given tree is traversed once, but there is a loop over current nodes children
* to assign them their parents.
*
* @param aT
* @param postorder
* @return
*/
private int gatherInfo(ITree aT, int postorder) {
int currentSize = 0;
int childrenCount = 0;
int descSizes = 0;
int krSizesSum = 0;
int revkrSizesSum = 0;
int preorder = preorderTmp;
int heavyChild = -1;
int leftChild = -1;
int rightChild = -1;
int weight = -1;
int maxWeight = -1;
int currentPostorder = -1;
int oldHeavyChild = -1;
ArrayList heavyRelSubtreesTmp = new ArrayList();
ArrayList leftRelSubtreesTmp = new ArrayList();
ArrayList rightRelSubtreesTmp = new ArrayList();
ArrayList<Integer> childrenPostorders = new ArrayList<>();
preorderTmp++;
// enumerate over children of current node
for (Enumeration<?> e = Collections.enumeration(aT.getChildren()); e.hasMoreElements();) {
childrenCount++;
postorder = gatherInfo((ITree) e.nextElement(), postorder);
childrenPostorders.add(postorder);
currentPostorder = postorder;
// heavy path
weight = sizeTmp + 1;
if (weight >= maxWeight) {
maxWeight = weight;
oldHeavyChild = heavyChild;
heavyChild = currentPostorder;
} else heavyRelSubtreesTmp.add(currentPostorder);
if (oldHeavyChild != -1) {
heavyRelSubtreesTmp.add(oldHeavyChild);
oldHeavyChild = -1;
}
// left path
if (childrenCount == 1) leftChild = currentPostorder;
else leftRelSubtreesTmp.add(currentPostorder);
// right path
rightChild = currentPostorder;
if (e.hasMoreElements()) rightRelSubtreesTmp.add(currentPostorder);
// subtree size
currentSize += 1 + sizeTmp;
descSizes += descSizesTmp;
if (childrenCount > 1) krSizesSum += krSizesSumTmp + sizeTmp + 1;
else {
krSizesSum += krSizesSumTmp;
nodeType[LEFT][currentPostorder] = true;
}
if (e.hasMoreElements()) revkrSizesSum += revkrSizesSumTmp + sizeTmp + 1;
else {
revkrSizesSum += revkrSizesSumTmp;
nodeType[RIGHT][currentPostorder] = true;
}
}
postorder++;
int currentDescSizes = descSizes + currentSize + 1;
info[POST2_DESC_SUM][postorder] = (currentSize + 1) * (currentSize + 1 + 3) / 2 - currentDescSizes;
info[POST2_KR_SUM][postorder] = krSizesSum + currentSize + 1;
info[POST2_REV_KR_SUM][postorder] = revkrSizesSum + currentSize + 1;
// POST2_LABEL
//labels[rootNumber] = ld.store(aT.getLabel());
info[POST2_LABEL][postorder] = ld.store(aT.getLabel());
// POST2_PARENT
for (Integer i : childrenPostorders) info[POST2_PARENT][i] = postorder;
// POST2_SIZE
info[POST2_SIZE][postorder] = currentSize + 1;
if (currentSize == 0) leafCount++;
// POST2_PRE
info[POST2_PRE][postorder] = preorder;
// PRE2_POST
info[PRE2_POST][preorder] = postorder;
// RPOST2_POST
info[RPOST2_POST][treeSize - 1 - preorder] = postorder;
// heavy path
if (heavyChild != -1) {
paths[HEAVY][postorder] = heavyChild;
nodeType[HEAVY][heavyChild] = true;
if (leftChild < heavyChild && heavyChild < rightChild) {
info[POST2_STRATEGY][postorder] = BOTH;
} else if (heavyChild == leftChild) {
info[POST2_STRATEGY][postorder] = RIGHT;
} else if (heavyChild == rightChild) {
info[POST2_STRATEGY][postorder] = LEFT;
}
} else {
info[POST2_STRATEGY][postorder] = RIGHT;
}
// left path
if (leftChild != -1) {
paths[LEFT][postorder] = leftChild;
}
// right path
if (rightChild != -1) {
paths[RIGHT][postorder] = rightChild;
}
// heavy/left/right relevant subtrees
relSubtrees[HEAVY][postorder] = toIntArray(heavyRelSubtreesTmp);
relSubtrees[RIGHT][postorder] = toIntArray(rightRelSubtreesTmp);
relSubtrees[LEFT][postorder] = toIntArray(leftRelSubtreesTmp);
descSizesTmp = currentDescSizes;
sizeTmp = currentSize;
krSizesSumTmp = krSizesSum;
revkrSizesSumTmp = revkrSizesSum;
return postorder;
}
/**
* Gathers information, that couldn't be collected while tree traversal.
*/
private void postTraversalProcessing() {
int nc1 = treeSize;
info[KR] = new int[leafCount];
info[RKR] = new int[leafCount];
int nc = nc1;
int lc = leafCount;
int i = 0;
// compute left-most leaf descendants
// go along the left-most path, remember each node and assign to it the path's leaf
// compute right-most leaf descendants (in reversed postorder)
for (i = 0; i < treeSize; i++) {
if (paths[LEFT][i] == -1) {
info[POST2_LLD][i] = i;
} else {
info[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];
}
if (paths[RIGHT][i] == -1) {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] = (treeSize - 1 - info[POST2_PRE][i]);
} else {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] = info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][paths[RIGHT][i]]];
}
}
// compute key root nodes
// compute reversed key root nodes (in revrsed postorder)
boolean[] visited = new boolean[nc];
boolean[] visitedR = new boolean[nc];
Arrays.fill(visited, false);
int k = lc - 1;
int kR = lc - 1;
for (i = nc - 1; i >= 0; i--) {
if (!visited[info[POST2_LLD][i]]) {
info[KR][k] = i;
visited[info[POST2_LLD][i]] = true;
k--;
}
if (!visitedR[info[RPOST2_RLD][i]]) {
info[RKR][kR] = i;
visitedR[info[RPOST2_RLD][i]] = true;
kR--;
}
}
// compute minimal key roots for every subtree
// compute minimal reversed key roots for every subtree (in reversed postorder)
int parent = -1;
int parentR = -1;
for (i = 0; i < leafCount; i++) {
parent = info[KR][i];
while (parent > -1 && info[POST2_MIN_KR][parent] == -1) {
info[POST2_MIN_KR][parent] = i;
parent = info[POST2_PARENT][parent];
}
parentR = info[RKR][i];
while (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {
info[RPOST2_MIN_RKR][parentR] = i;
parentR = info[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder
if (parentR > -1) {
parentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its rev. postorder
}
}
}
}
/**
* Transforms a list of Integer objects to an array of primitive int values.
* @param integers
* @return
*/
public static int[] toIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
}
public void setSwitched(boolean value) {
switched = value;
}
public boolean isSwitched() {
return switched;
}
}
| 14,981
| 32.972789
| 136
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimal/rted/LabelDictionary.java
|
// Copyright (C) 2012 Mateusz Pawlik and Nikolaus Augsten
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package gumtreediff.matchers.optimal.rted;
import java.util.HashMap;
import java.util.Map;
/**
* This provides a way of using small int values to represent String labels,
* as opposed to storing the labels directly.
*
* @author Denilson Barbosa, Nikolaus Augsten from approxlib, available at http://www.inf.unibz.it/~augsten/src/
*/
public class LabelDictionary {
public static final int KEY_DUMMY_LABEL = -1;
private int count;
private Map<String, Integer> strInt;
private Map<Integer, String> intStr;
private boolean newLabelsAllowed = true;
/**
* Creates a new blank dictionary.
*/
public LabelDictionary() {
count = 0;
strInt = new HashMap<>();
intStr = new HashMap<>();
}
/**
* Adds a new label to the dictionary if it has not been added yet.
* Returns the ID of the new label in the dictionary.
*
* @param label add this label to the dictionary if it does not exist yet
* @return ID of label in the dictionary
*/
public int store(String label) {
if (strInt.containsKey(label)) {
return (strInt.get(label).intValue());
} else if (!newLabelsAllowed) {
return KEY_DUMMY_LABEL;
} else { // store label
Integer intKey = count++;
strInt.put(label, intKey);
intStr.put(intKey, label);
return intKey.intValue();
}
}
/**
* Returns the label with a given ID in the dictionary.
*
* @param labelID
* @return the label with the specified labelID, or null if this dictionary contains no label for labelID
*/
public String read(int labelID) {
return intStr.get(Integer.valueOf(labelID));
}
/**
* @return true iff new labels can be stored into this label dictinoary
*/
public boolean isNewLabelsAllowed() {
return newLabelsAllowed;
}
/**
* @param newLabelsAllowed the newLabelsAllowed to set
*/
public void setNewLabelsAllowed(boolean newLabelsAllowed) {
this.newLabelsAllowed = newLabelsAllowed;
}
}
| 2,887
| 31.088889
| 113
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimal/rted/RtedAlgorithm.java
|
// Copyright (C) 2012 Mateusz Pawlik and Nikolaus Augsten
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package gumtreediff.matchers.optimal.rted;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import gumtreediff.tree.ITree;
/**
* Computes the tree edit distance using RTED algorithm.
*
* @author Mateusz Pawlik, Nikolaus Augsten
*/
public class RtedAlgorithm {
// constants
private static final byte LEFT = 0;
private static final byte RIGHT = 1;
private static final byte HEAVY = 2;
private static final byte BOTH = 3;
private static final byte REVLEFT = 4;
private static final byte REVRIGHT = 5;
private static final byte REVHEAVY = 6;
private static final byte POST2_SIZE = 0;
private static final byte POST2_KR_SUM = 1;
private static final byte POST2_REV_KR_SUM = 2;
private static final byte POST2_DESC_SUM = 3; // number of subforests in
// full decomposition
private static final byte POST2_PRE = 4;
private static final byte POST2_PARENT = 5;
private static final byte POST2_LABEL = 6;
private static final byte KR = 7; // key root nodes (size of this array =
// leaf count)
private static final byte POST2_LLD = 8; // left-most leaf descendants
private static final byte POST2_MIN_KR = 9; // minimum key root nodes index
// in KR array
private static final byte RKR = 10; // reversed key root nodes
private static final byte RPOST2_RLD = 11; // reversed postorer 2 right-most
// leaf descendants
private static final byte RPOST2_MIN_RKR = 12; // minimum key root nodes
// index in RKR array
private static final byte RPOST2_POST = 13; // reversed postorder ->
// postorder
private static final byte POST2_STRATEGY = 14; // strategy for Demaine (is
// there sth on the
// left/right of the heavy
// node)
private static final byte PRE2_POST = 15; // preorder to postorder
// trees
private InfoTree it1;
private InfoTree it2;
private int size1;
private int size2;
private LabelDictionary ld;
// arrays
private int[][] str; // strategy array
private double[][] delta; // an array for storing the distances between
// every pair of subtrees
private byte[][] deltaBit; // stores the distances difference of a form
// delta(F,G)-delta(F°,G°) for every pair of
// subtrees, which is at most 1
private int[][] ij; // stores a forest preorder for given i and j
private long[][][] costV;
private long[][] costW;
private double[][] t; // T array from Demaine's algorithm, stores
// delta(Fv,Gij), v on heavy path. Values are
// written to t.
private double[][] tCOPY; // tCOPY serves for writing values. It may happen
// that in single computePeriod values are
// overwritten before they are read because of
// the change of forest ordering.
private double[][] tTMP;
private double[][] s;
private double[] q;
private double da, db, dc;
private int previousStrategy;
private int[] strStat = new int[5]; // statistics for strategies
// LEFT,RIGHT,HEAVY,SUM
private double costDel, costIns, costMatch; // edit operations costs
/**
* The constructor. Parameters passed are the edit operation costs.
*
* @param delCost
* @param insCost
* @param matchCost
*/
public RtedAlgorithm(double delCost, double insCost, double matchCost) {
this.costDel = delCost;
this.costIns = insCost;
this.costMatch = matchCost;
}
/**
* Computes the tree edit distance between trees t1 and t2.
*
* @param t1
* @param t2
* @return tree edit distance between trees t1 and t2
*/
public double nonNormalizedTreeDist(ITree t1, ITree t2) {
init(t1, t2);
str = new int[size1][size2];
computeOptimalStrategy();
return computeDistUsingStrArray(it1, it2);
}
public double nonNormalizedTreeDist() {
if (it1 == null || it2 == null) {
System.err.println("No stored trees to compare.");
}
if (str == null) {
System.err.println("No strategy to use.");
}
return computeDistUsingStrArray(it1, it2);
}
/**
* Initialization method.
*
* @param t1
* @param t2
*/
public void init(ITree t1, ITree t2) {
ld = new LabelDictionary();
it1 = new InfoTree(t1, ld);
it2 = new InfoTree(t2, ld);
size1 = it1.getSize();
size2 = it2.getSize();
ij = new int[Math.max(size1, size2)][Math.max(size1, size2)];
delta = new double[size1][size2];
deltaBit = new byte[size1][size2];
costV = new long[3][size1][size2];
costW = new long[3][size2];
// Calculate delta between every leaf in G (empty tree) and all the
// nodes in F.
// Calculate it both sides: leafs of F and nodes of G & leafs of G and
// nodes of F.
int[] labels1 = it1.getInfoArray(POST2_LABEL);
int[] labels2 = it2.getInfoArray(POST2_LABEL);
int[] sizes1 = it1.getInfoArray(POST2_SIZE);
int[] sizes2 = it2.getInfoArray(POST2_SIZE);
for (int x = 0; x < sizes1.length; x++) { // for all nodes of initially
// left tree
for (int y = 0; y < sizes2.length; y++) { // for all nodes of
// initially right tree
// This is an attempt for distances of single-node subtree and
// anything alse
// The differences between pairs of labels are stored
if (labels1[x] == labels2[y]) {
deltaBit[x][y] = 0;
} else {
deltaBit[x][y] = 1; // if this set, the labels differ, cost
// of relabeling is set to costMatch
}
if (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs
delta[x][y] = 0;
} else {
if (sizes1[x] == 1) {
delta[x][y] = sizes2[y] - 1;
}
if (sizes2[y] == 1) {
delta[x][y] = sizes1[x] - 1;
}
}
}
}
}
/**
* A method for computing and storing the optimal strategy
*/
public void computeOptimalStrategy() {
long heavyMin, revHeavyMin, leftMin, revLeftMin, rightMin, revRightMin;
long min = -1;
int strategy = -1;
int parent1 = -1;
int parent2 = -1;
boolean[] nodeTypeLeft1 = it1.nodeType[LEFT];
boolean[] nodeTypeLeft2 = it2.nodeType[LEFT];
boolean[] nodeTypeRigt1 = it1.nodeType[RIGHT];
boolean[] nodeTypeRight2 = it2.nodeType[RIGHT];
boolean[] nodeTypeHeavy1 = it1.nodeType[HEAVY];
boolean[] nodeTypeHeavy2 = it2.nodeType[HEAVY];
int[] post2size1 = it1.info[POST2_SIZE];
int[] post2size2 = it2.info[POST2_SIZE];
int[] post2descSum1 = it1.info[POST2_DESC_SUM];
int[] post2descSum2 = it2.info[POST2_DESC_SUM];
int[] post2krSum1 = it1.info[POST2_KR_SUM];
int[] post2krSum2 = it2.info[POST2_KR_SUM];
int[] post2revkrSum1 = it1.info[POST2_REV_KR_SUM];
int[] post2revkrSum2 = it2.info[POST2_REV_KR_SUM];
int[] post2parent1 = it1.info[POST2_PARENT];
int[] post2parent2 = it2.info[POST2_PARENT];
str = new int[size1][size2];
// v represents nodes of left input tree in postorder
// w represents nodes of right input tree in postorder
for (int v = 0; v < size1; v++) {
Arrays.fill(costW[0], 0);
Arrays.fill(costW[1], 0);
Arrays.fill(costW[2], 0);
for (int w = 0; w < size2; w++) {
if (post2size2[w] == 1) {
// putTree zeros into arrays
costW[LEFT][w] = 0;
costW[RIGHT][w] = 0;
costW[HEAVY][w] = 0;
}
if (post2size1[v] == 1) {
// putTree zeros into arrays
costV[LEFT][v][w] = 0;
costV[RIGHT][v][w] = 0;
costV[HEAVY][v][w] = 0;
}
// TODO: some things below may be putTree to outer loop
// count the minimum + get the strategy
heavyMin = (long) post2size1[v] * (long) post2descSum2[w]
+ costV[HEAVY][v][w];
revHeavyMin = (long) post2size2[w] * (long) post2descSum1[v]
+ costW[HEAVY][w];
leftMin = (long) post2size1[v] * (long) post2krSum2[w]
+ costV[LEFT][v][w];
revLeftMin = (long) post2size2[w] * (long) post2krSum1[v]
+ costW[LEFT][w];
rightMin = (long) post2size1[v] * (long) post2revkrSum2[w]
+ costV[RIGHT][v][w];
revRightMin = (long) post2size2[w] * (long) post2revkrSum1[v]
+ costW[RIGHT][w];
long[] mins = { leftMin, rightMin, heavyMin, Long.MAX_VALUE,
revLeftMin, revRightMin, revHeavyMin };
min = leftMin;
strategy = 0;
for (int i = 1; i <= 6; i++) {
if (mins[i] < min) {
min = mins[i];
strategy = i;
}
}
// store the strategy for the minimal cost
str[v][w] = strategy;
// fill the cost arrays
parent1 = post2parent1[v];
if (parent1 != -1) {
costV[HEAVY][parent1][w] += nodeTypeHeavy1[v] ? costV[HEAVY][v][w]
: min;
costV[RIGHT][parent1][w] += nodeTypeRigt1[v] ? costV[RIGHT][v][w]
: min;
costV[LEFT][parent1][w] += nodeTypeLeft1[v] ? costV[LEFT][v][w]
: min;
}
parent2 = post2parent2[w];
if (parent2 != -1) {
costW[HEAVY][parent2] += nodeTypeHeavy2[w] ? costW[HEAVY][w]
: min;
costW[LEFT][parent2] += nodeTypeLeft2[w] ? costW[LEFT][w]
: min;
costW[RIGHT][parent2] += nodeTypeRight2[w] ? costW[RIGHT][w]
: min;
}
}
}
}
/**
* The recursion step according to the optimal strategy.
*
* @param it1
* @param it2
* @return
*/
private double computeDistUsingStrArray(InfoTree it1, InfoTree it2) {
int postorder1 = it1.getCurrentNode();
int postorder2 = it2.getCurrentNode();
int stepStrategy = str[postorder1][postorder2];
int tmpPostorder;
int[] stepPath;
int[] stepRelSubtrees;
ArrayList<Integer> heavyPath;
switch (stepStrategy) {
case LEFT:
tmpPostorder = postorder1;
stepPath = it1.getPath(LEFT);
// go along the path
while (stepPath[postorder1] > -1) {
stepRelSubtrees = it1.getNodeRelSubtrees(LEFT, postorder1);
if (stepRelSubtrees != null) {
// iterate over rel subtrees for a specific node on the path
for (int rs : stepRelSubtrees) {
it1.setCurrentNode(rs);
// make the recursion
computeDistUsingStrArray(it1, it2);
}
}
postorder1 = stepPath[postorder1];
}
// set current node
it1.setCurrentNode(tmpPostorder);
it1.setSwitched(false);
it2.setSwitched(false);
// count the distance using a single-path function
strStat[3]++;
strStat[LEFT]++;
return spfL(it1, it2);
case RIGHT:
tmpPostorder = postorder1;
stepPath = it1.getPath(RIGHT);
while (stepPath[postorder1] > -1) {
stepRelSubtrees = it1.getNodeRelSubtrees(RIGHT, postorder1);
if (stepRelSubtrees != null) {
for (int rs : stepRelSubtrees) {
it1.setCurrentNode(rs);
computeDistUsingStrArray(it1, it2);
}
}
postorder1 = stepPath[postorder1];
}
it1.setCurrentNode(tmpPostorder);
it1.setSwitched(false);
it2.setSwitched(false);
strStat[3]++;
strStat[RIGHT]++;
return spfR(it1, it2);
case HEAVY:
tmpPostorder = postorder1;
stepPath = it1.getPath(HEAVY);
heavyPath = new ArrayList<>();
heavyPath.add(postorder1);
while (stepPath[postorder1] > -1) {
stepRelSubtrees = it1.getNodeRelSubtrees(HEAVY, postorder1);
if (stepRelSubtrees != null) {
for (int rs : stepRelSubtrees) {
it1.setCurrentNode(rs);
computeDistUsingStrArray(it1, it2);
}
}
postorder1 = stepPath[postorder1];
heavyPath.add(postorder1);
}
it1.setCurrentNode(tmpPostorder);
it1.setSwitched(false);
it2.setSwitched(false);
strStat[3]++;
strStat[HEAVY]++;
return spfH(it1, it2, InfoTree.toIntArray(heavyPath));
case REVLEFT:
tmpPostorder = postorder2;
stepPath = it2.getPath(LEFT);
while (stepPath[postorder2] > -1) {
stepRelSubtrees = it2.getNodeRelSubtrees(LEFT, postorder2);
if (stepRelSubtrees != null) {
for (int rs : stepRelSubtrees) {
it2.setCurrentNode(rs);
computeDistUsingStrArray(it1, it2);
}
}
postorder2 = stepPath[postorder2];
}
it2.setCurrentNode(tmpPostorder);
it1.setSwitched(true);
it2.setSwitched(true);
strStat[3]++;
strStat[LEFT]++;
return spfL(it2, it1);
case REVRIGHT:
tmpPostorder = postorder2;
stepPath = it2.getPath(RIGHT);
while (stepPath[postorder2] > -1) {
stepRelSubtrees = it2.getNodeRelSubtrees(RIGHT, postorder2);
if (stepRelSubtrees != null) {
for (int rs : stepRelSubtrees) {
it2.setCurrentNode(rs);
computeDistUsingStrArray(it1, it2);
}
}
postorder2 = stepPath[postorder2];
}
it2.setCurrentNode(tmpPostorder);
it1.setSwitched(true);
it2.setSwitched(true);
strStat[3]++;
strStat[RIGHT]++;
return spfR(it2, it1);
case REVHEAVY:
tmpPostorder = postorder2;
stepPath = it2.getPath(HEAVY);
heavyPath = new ArrayList<>();
heavyPath.add(postorder2);
while (stepPath[postorder2] > -1) {
stepRelSubtrees = it2.getNodeRelSubtrees(HEAVY, postorder2);
if (stepRelSubtrees != null) {
for (int rs : stepRelSubtrees) {
it2.setCurrentNode(rs);
computeDistUsingStrArray(it1, it2);
}
}
postorder2 = stepPath[postorder2];
heavyPath.add(postorder2);
}
it2.setCurrentNode(tmpPostorder);
it1.setSwitched(true);
it2.setSwitched(true);
strStat[3]++;
strStat[HEAVY]++;
return spfH(it2, it1, InfoTree.toIntArray(heavyPath));
default:
return -1;
}
}
/**
* Single-path function for the left-most path based on Zhang and Shasha
* algorithm.
*
* @param it1
* @param it2
* @return distance between subtrees it1 and it2
*/
private double spfL(InfoTree it1, InfoTree it2) {
int fPostorder = it1.getCurrentNode();
int gPostorder = it2.getCurrentNode();
int minKR = it2.info[POST2_MIN_KR][gPostorder];
int[] kr = it2.info[KR];
if (minKR > -1) {
for (int j = minKR; kr[j] < gPostorder; j++) {
treeEditDist(it1, it2, fPostorder, kr[j]);
}
}
treeEditDist(it1, it2, fPostorder, gPostorder);
return it1.isSwitched() ? delta[gPostorder][fPostorder]
+ deltaBit[gPostorder][fPostorder] * costMatch
: delta[fPostorder][gPostorder]
+ deltaBit[fPostorder][gPostorder] * costMatch;
}
private void treeEditDist(InfoTree it1, InfoTree it2, int i, int j) {
int m = i - it1.info[POST2_LLD][i] + 2;
int n = j - it2.info[POST2_LLD][j] + 2;
double[][] forestdist = new double[m][n];
int ioff = it1.info[POST2_LLD][i] - 1;
int joff = it2.info[POST2_LLD][j] - 1;
boolean switched = it1.isSwitched();
forestdist[0][0] = 0;
for (int i1 = 1; i1 <= i - ioff; i1++) forestdist[i1][0] = forestdist[i1 - 1][0] + 1;
for (int j1 = 1; j1 <= j - joff; j1++) forestdist[0][j1] = forestdist[0][j1 - 1] + 1;
for (int i1 = 1; i1 <= i - ioff; i1++) {
for (int j1 = 1; j1 <= j - joff; j1++) {
if ((it1.info[POST2_LLD][i1 + ioff] == it1.info[POST2_LLD][i]) && (it2.info[POST2_LLD][j1 + joff] == it2.info[POST2_LLD][j])) {
double u = 0;
if (it1.info[POST2_LABEL][i1 + ioff] != it2.info[POST2_LABEL][j1 + joff]) u = costMatch;
da = forestdist[i1 - 1][j1] + costDel;
db = forestdist[i1][j1 - 1] + costIns;
dc = forestdist[i1 - 1][j1 - 1] + u;
forestdist[i1][j1] = (da < db) ? ((da < dc) ? da : dc) : ((db < dc) ? db : dc);
setDeltaValue(i1 + ioff, j1 + joff, forestdist[i1 - 1][j1 - 1], switched);
setDeltaBitValue(i1 + ioff, j1 + joff, (byte) ((forestdist[i1][j1] - forestdist[i1 - 1][j1 - 1] > 0) ? 1 : 0), switched);
} else {
double u = 0;
u = switched ? deltaBit[j1 + joff][i1 + ioff] * costMatch : deltaBit[i1 + ioff][j1 + joff] * costMatch;
da = forestdist[i1 - 1][j1] + costDel;
db = forestdist[i1][j1 - 1] + costIns;
dc = forestdist[it1.info[POST2_LLD][i1 + ioff] - 1 - ioff][it2.info[POST2_LLD][j1 + joff]
- 1 - joff] + (switched ? delta[j1 + joff][i1 + ioff] : delta[i1 + ioff][j1 + joff]) + u;
forestdist[i1][j1] = (da < db) ? ((da < dc) ? da : dc) : ((db < dc) ? db : dc);
}
}
}
}
/**
* Single-path function for right-most path based on symmetric version of
* Zhang and Shasha algorithm.
*
* @param it1
* @param it2
* @return distance between subtrees it1 and it2
*/
private double spfR(InfoTree it1, InfoTree it2) {
int fReversedPostorder = it1.getSize() - 1 - it1.info[POST2_PRE][it1.getCurrentNode()];
int gReversedPostorder = it2.getSize() - 1 - it2.info[POST2_PRE][it2.getCurrentNode()];
int minRKR = it2.info[RPOST2_MIN_RKR][gReversedPostorder];
int[] rkr = it2.info[RKR];
if (minRKR > -1) for (int j = minRKR; rkr[j] < gReversedPostorder; j++) treeEditDistRev(it1, it2, fReversedPostorder, rkr[j]);
treeEditDistRev(it1, it2, fReversedPostorder, gReversedPostorder);
return it1.isSwitched() ? delta[it2.getCurrentNode()][it1
.getCurrentNode()]
+ deltaBit[it2.getCurrentNode()][it1.getCurrentNode()]
* costMatch : delta[it1.getCurrentNode()][it2.getCurrentNode()]
+ deltaBit[it1.getCurrentNode()][it2.getCurrentNode()]
* costMatch;
}
private void treeEditDistRev(InfoTree it1, InfoTree it2, int i, int j) {
int m = i - it1.info[RPOST2_RLD][i] + 2;
int n = j - it2.info[RPOST2_RLD][j] + 2;
double[][] forestdist = new double[m][n];
int ioff = it1.info[RPOST2_RLD][i] - 1;
int joff = it2.info[RPOST2_RLD][j] - 1;
boolean switched = it1.isSwitched();
forestdist[0][0] = 0;
for (int i1 = 1; i1 <= i - ioff; i1++) forestdist[i1][0] = forestdist[i1 - 1][0] + 1;
for (int j1 = 1; j1 <= j - joff; j1++) forestdist[0][j1] = forestdist[0][j1 - 1] + 1;
for (int i1 = 1; i1 <= i - ioff; i1++) {
for (int j1 = 1; j1 <= j - joff; j1++) {
if ((it1.info[RPOST2_RLD][i1 + ioff] == it1.info[RPOST2_RLD][i])
&& (it2.info[RPOST2_RLD][j1 + joff] == it2.info[RPOST2_RLD][j])) {
double u = 0;
if (it1.info[POST2_LABEL][it1.info[RPOST2_POST][i1 + ioff]] != it2.info[POST2_LABEL][it2.info[RPOST2_POST][j1 + joff]])
u = costMatch;
da = forestdist[i1 - 1][j1] + costDel;
db = forestdist[i1][j1 - 1] + costIns;
dc = forestdist[i1 - 1][j1 - 1] + u;
forestdist[i1][j1] = (da < db) ? ((da < dc) ? da : dc) : ((db < dc) ? db : dc);
setDeltaValue(it1.info[RPOST2_POST][i1 + ioff], it2.info[RPOST2_POST][j1 + joff], forestdist[i1 - 1][j1 - 1], switched);
setDeltaBitValue(it1.info[RPOST2_POST][i1 + ioff], it2.info[RPOST2_POST][j1 + joff],
(byte) ((forestdist[i1][j1] - forestdist[i1 - 1][j1 - 1] > 0) ? 1 : 0), switched);
} else {
double u = 0;
u = switched ? deltaBit[it2.info[RPOST2_POST][j1 + joff]][it1.info[RPOST2_POST][i1
+ ioff]]
* costMatch
: deltaBit[it1.info[RPOST2_POST][i1 + ioff]][it2.info[RPOST2_POST][j1
+ joff]]
* costMatch;
da = forestdist[i1 - 1][j1] + costDel;
db = forestdist[i1][j1 - 1] + costIns;
dc = forestdist[it1.info[RPOST2_RLD][i1 + ioff] - 1 - ioff][it2.info[RPOST2_RLD][j1
+ joff]
- 1 - joff]
+ (switched ? delta[it2.info[RPOST2_POST][j1 + joff]][it1.info[RPOST2_POST][i1
+ ioff]]
: delta[it1.info[RPOST2_POST][i1 + ioff]][it2.info[RPOST2_POST][j1
+ joff]]) + u;
forestdist[i1][j1] = (da < db) ? ((da < dc) ? da : dc)
: ((db < dc) ? db : dc);
}
}
}
}
/**
* Single-path function for heavy path based on Klein/Demaine algorithm.
*
* @param it1
* @param it2
* @param heavyPath
* @return distance between subtrees it1 and it2
*/
private double spfH(InfoTree it1, InfoTree it2, int[] heavyPath) {
int fSize = it1.info[POST2_SIZE][it1.getCurrentNode()];
int gSize = it2.info[POST2_SIZE][it2.getCurrentNode()];
int gRevPre = it2.getSize() - 1 - it2.getCurrentNode();
int gPre = it2.info[POST2_PRE][it2.getCurrentNode()];
int gTreeSize = it2.getSize();
int strategy;
int jOfi;
// Initialize arrays to their maximal possible size for current pairs of
// subtrees.
t = new double[gSize][gSize];
tCOPY = new double[gSize][gSize];
s = new double[fSize][gSize];
q = new double[fSize];
int vp = -1;
int nextVp = -1;
for (int it = heavyPath.length - 1; it >= 0; it--) {
vp = heavyPath[it];
strategy = it1.info[POST2_STRATEGY][vp];
if (strategy != BOTH) {
if (it1.info[POST2_SIZE][vp] == 1) {
for (int i = gSize - 1; i >= 0; i--) {
jOfi = jOfI(it2, i, gSize, gRevPre, gPre, strategy,
gTreeSize);
for (int j = jOfi; j >= 0; j--) {
t[i][j] = (gSize - (i + j)) * costIns;
}
}
previousStrategy = strategy;
}
computePeriod(it1, vp, nextVp, it2, strategy);
} else {
if (it1.info[POST2_SIZE][vp] == 1) {
for (int i = gSize - 1; i >= 0; i--) {
jOfi = jOfI(it2, i, gSize, gRevPre, gPre, LEFT,
gTreeSize);
for (int j = jOfi; j >= 0; j--) {
t[i][j] = (gSize - (i + j)) * costIns;
}
}
previousStrategy = LEFT;
}
computePeriod(it1, vp, nextVp, it2, LEFT);
if (it1.info[POST2_SIZE][vp] == 1) {
for (int i = gSize - 1; i >= 0; i--) {
jOfi = jOfI(it2, i, gSize, gRevPre, gPre, RIGHT,
gTreeSize);
for (int j = jOfi; j >= 0; j--) {
t[i][j] = (gSize - (i + j)) * costIns;
}
}
previousStrategy = RIGHT;
}
computePeriod(it1, vp, nextVp, it2, RIGHT);
}
nextVp = vp;
}
return t[0][0];
}
/**
* Compute period method.
*
* @param it1
* @param aVp
* @param aNextVp
* @param it2
* @param aStrategy
*/
private void computePeriod(InfoTree it1, int aVp, int aNextVp, InfoTree it2, int aStrategy) {
int fTreeSize = it1.getSize();
int gTreeSize = it2.getSize();
int vpPreorder = it1.info[POST2_PRE][aVp];
int vpRevPreorder = fTreeSize - 1 - aVp;
int vpSize = it1.info[POST2_SIZE][aVp];
int gSize = it2.info[POST2_SIZE][it2.getCurrentNode()];
int gPreorder = it2.info[POST2_PRE][it2.getCurrentNode()];
int gRevPreorder = gTreeSize - 1 - it2.getCurrentNode();
int nextVpPreorder = -1;
int nextVpRevPreorder = -1;
int nextVpSize = -1;
// count k and assign next vp values
int k;
if (aNextVp != -1) {
nextVpPreorder = it1.info[POST2_PRE][aNextVp];
nextVpRevPreorder = fTreeSize - 1 - aNextVp;
nextVpSize = it1.info[POST2_SIZE][aNextVp];
// if strategy==LEFT use preorder to count number of left deletions
// from vp to vp-1
// if strategy==RIGHT use reversed preorder
k = aStrategy == LEFT ? nextVpPreorder - vpPreorder
: nextVpRevPreorder - vpRevPreorder;
if (aStrategy != previousStrategy) {
computeIJTable(it2, gPreorder, gRevPreorder, gSize, aStrategy,
gTreeSize);
}
} else {
k = 1;
computeIJTable(it2, gPreorder, gRevPreorder, gSize, aStrategy, gTreeSize);
}
int realStrategy = it1.info[POST2_STRATEGY][aVp];
boolean switched = it1.isSwitched();
tTMP = tCOPY;
tCOPY = t;
t = tTMP;
// if aVp is a leaf => precompute table T - edit distance betwen EMPTY
// and all subforests of G
// check if nextVp is the only child of vp
if (vpSize - nextVpSize == 1) {
// update delta from T table => dist between Fvp-1 and G was
// computed in previous compute period
if (gSize == 1) {
setDeltaValue(it1.info[PRE2_POST][vpPreorder], it2.info[PRE2_POST][gPreorder], vpSize - 1, switched);
} else {
setDeltaValue(it1.info[PRE2_POST][vpPreorder], it2.info[PRE2_POST][gPreorder], t[1][0], switched);
}
}
int gijForestPreorder;
int previousI;
int fForestPreorderKPrime;
int jPrime;
int kBis;
int jOfIminus1;
int gijOfIMinus1Preorder;
int jOfI;
double deleteFromLeft;
double deleteFromRight;
double match;
int fLabel;
int gLabel;
// Q and T are visible for every i
for (int i = gSize - 1; i >= 0; i--) {
// jOfI was already computed once in spfH
jOfI = jOfI(it2, i, gSize, gRevPreorder, gPreorder, aStrategy,
gTreeSize);
// when strategy==BOTH first LEFT then RIGHT is done
//counter += realStrategy == BOTH && aStrategy == LEFT ? (k - 1)
//* (jOfI + 1) : k * (jOfI + 1);
// S - visible for current i
for (int kPrime = 1; kPrime <= k; kPrime++) {
fForestPreorderKPrime = aStrategy == LEFT ? vpPreorder
+ (k - kPrime) : it1.info[POST2_PRE][fTreeSize - 1
- (vpRevPreorder + (k - kPrime))];
kBis = kPrime
- it1.info[POST2_SIZE][it1.info[PRE2_POST][fForestPreorderKPrime]];
// reset the minimum arguments' values
deleteFromRight = costIns;
deleteFromLeft = costDel;
match = 0;
match += aStrategy == LEFT ? kBis + nextVpSize : vpSize - k
+ kBis;
if ((i + jOfI) == (gSize - 1)) {
deleteFromRight += (vpSize - (k - kPrime));
} else {
deleteFromRight += q[kPrime - 1];
}
fLabel = it1.info[POST2_LABEL][it1.info[PRE2_POST][fForestPreorderKPrime]];
for (int j = jOfI; j >= 0; j--) {
// count dist(FkPrime, Gij) with min
// delete from left
gijForestPreorder = aStrategy == LEFT ? ij[i][j]
: it2.info[POST2_PRE][gTreeSize - 1 - ij[i][j]];
if (kPrime == 1) {
// if the direction changed from the previous period to
// this one use i and j of previous strategy
// since T is overwritten continuously, thus use copy of
// T for getting values from previous period
if (aStrategy != previousStrategy) {
if (aStrategy == LEFT) {
previousI = gijForestPreorder - gPreorder; // minus
// preorder
// of
// G
} else {
previousI = gTreeSize
- 1
- it2.info[RPOST2_POST][gTreeSize - 1
- gijForestPreorder]
- gRevPreorder; // minus rev preorder of
// G
}
deleteFromLeft += tCOPY[previousI][i + j
- previousI];
} else {
deleteFromLeft += tCOPY[i][j];
}
} else {
deleteFromLeft += s[kPrime - 1 - 1][j];
}
// match
match += switched ? delta[it2.info[PRE2_POST][gijForestPreorder]][it1.info[PRE2_POST][fForestPreorderKPrime]]
: delta[it1.info[PRE2_POST][fForestPreorderKPrime]][it2.info[PRE2_POST][gijForestPreorder]];
jPrime = j
+ it2.info[POST2_SIZE][it2.info[PRE2_POST][gijForestPreorder]];
// if root nodes of L/R Fk' and L/R Gij have different
// labels add the match cost
gLabel = it2.info[POST2_LABEL][it2.info[PRE2_POST][gijForestPreorder]];
if (fLabel != gLabel) {
match += costMatch;
}
// this condition is checked many times but is not satisfied
// only once
if (j != jOfI) {
// delete from right
deleteFromRight += s[kPrime - 1][j + 1];
if (kBis == 0) {
if (aStrategy != previousStrategy) {
previousI = aStrategy == LEFT ? ij[i][jPrime]
- gPreorder : ij[i][jPrime]
- gRevPreorder;
match += tCOPY[previousI][i + jPrime
- previousI];
} else {
match += tCOPY[i][jPrime];
}
} else if (kBis > 0) {
match += s[kBis - 1][jPrime];
} else {
match += gSize - (i + jPrime);
}
}
// fill S table
s[kPrime - 1][j] = (deleteFromLeft < deleteFromRight) ? ((deleteFromLeft < match) ? deleteFromLeft
: match)
: ((deleteFromRight < match) ? deleteFromRight
: match);
// reset the minimum arguments' values
deleteFromRight = costIns;
deleteFromLeft = costDel;
match = 0;
}
}
// compute table T => add row to T
// if (realStrategy == BOTH && aStrategy == LEFT) {
// // t[i] has to be of correct length
// // assigning pointer of a row in s to t[i] is wrong
// // t[i] = Arrays.copyOf(s[k-1-1], jOfI+1);//sTable[k - 1 - 1];
// // System.arraycopy(s[k-1-1], 0, t[i], 0, jOfI+1);
// t[i] = s[k-1-1].clone();
// } else {
// // t[i] = Arrays.copyOf(s[k-1], jOfI+1);//sTable[k - 1];
// // System.arraycopy(s[k-1], 0, t[i], 0, jOfI+1);
// t[i] = s[k-1].clone();
// }
// compute table T => add row to T
// we have to copy the values, otherwise they may be overwritten t
// early
t[i] = (realStrategy == BOTH && aStrategy == LEFT) ? s[k - 1 - 1]
.clone() : s[k - 1].clone();
if (i > 0) {
// compute table Q
jOfIminus1 = jOfI(it2, i - 1, gSize, gRevPreorder, gPreorder,
aStrategy, gTreeSize);
if (jOfIminus1 <= jOfI) {
for (int x = 0; x < k; x++) { // copy whole column |
// qTable.length=k
q[x] = s[x][jOfIminus1];
}
}
// fill table delta
if (i + jOfIminus1 < gSize) {
gijOfIMinus1Preorder = aStrategy == LEFT ? it2.info[POST2_PRE][gTreeSize
- 1 - (gRevPreorder + (i - 1))]
: gPreorder + (i - 1);
// If Fk from Fk-1 differ with a single node,
// then Fk without the root node is Fk-1 and the distance
// value has to be taken from previous T table.
if (k - 1 - 1 < 0) {
if (aStrategy != previousStrategy) {
previousI = aStrategy == LEFT ? ij[i][jOfIminus1]
- gPreorder : ij[i][jOfIminus1]
- gRevPreorder;
setDeltaValue(
it1.info[PRE2_POST][vpPreorder],
it2.info[PRE2_POST][gijOfIMinus1Preorder],
tCOPY[previousI][i + jOfIminus1 - previousI],
switched);
} else {
setDeltaValue(it1.info[PRE2_POST][vpPreorder],
it2.info[PRE2_POST][gijOfIMinus1Preorder],
tCOPY[i][jOfIminus1], switched);
}
} else {
setDeltaValue(it1.info[PRE2_POST][vpPreorder],
it2.info[PRE2_POST][gijOfIMinus1Preorder],
s[k - 1 - 1][jOfIminus1], switched);
}
}
}
}
previousStrategy = aStrategy;
}
/**
* Computes an array where preorder/rev.preorder of a subforest of given
* subtree is stored and can be accessed for given i and j.
*
* @param it
* @param subtreePreorder
* @param subtreeRevPreorder
* @param subtreeSize
* @param aStrategy
* @param treeSize
*/
private void computeIJTable(InfoTree it, int subtreePreorder,
int subtreeRevPreorder, int subtreeSize, int aStrategy, int treeSize) {
int change;
int[] post2pre = it.info[POST2_PRE];
int[] rpost2post = it.info[RPOST2_POST];
if (aStrategy == LEFT) {
for (int x = 0; x < subtreeSize; x++) {
ij[0][x] = x + subtreePreorder;
}
for (int x = 1; x < subtreeSize; x++) {
change = post2pre[(treeSize - 1 - (x - 1 + subtreeRevPreorder))];
for (int z = 0; z < subtreeSize; z++) {
if (ij[x - 1][z] >= change) {
ij[x][z] = ij[x - 1][z] + 1;
} else {
ij[x][z] = ij[x - 1][z];
}
}
}
} else { // if (aStrategy == RIGHT) {
for (int x = 0; x < subtreeSize; x++) {
ij[0][x] = x + subtreeRevPreorder;
}
for (int x = 1; x < subtreeSize; x++) {
change = treeSize
- 1
- rpost2post[(treeSize - 1 - (x - 1 + subtreePreorder))];
for (int z = 0; z < subtreeSize; z++) {
if (ij[x - 1][z] >= change) {
ij[x][z] = ij[x - 1][z] + 1;
} else {
ij[x][z] = ij[x - 1][z];
}
}
}
}
}
/**
* Returns j for given i, result of j(i) form Demaine's algorithm.
*
* @param it
* @param aI
* @param aSubtreeWeight
* @param aSubtreeRevPre
* @param aSubtreePre
* @param aStrategy
* @param treeSize
* @return j for given i
*/
private int jOfI(InfoTree it, int aI, int aSubtreeWeight,
int aSubtreeRevPre, int aSubtreePre, int aStrategy, int treeSize) {
return aStrategy == LEFT ? aSubtreeWeight - aI
- it.info[POST2_SIZE][treeSize - 1 - (aSubtreeRevPre + aI)]
: aSubtreeWeight
- aI
- it.info[POST2_SIZE][it.info[RPOST2_POST][treeSize - 1
- (aSubtreePre + aI)]];
}
private void setDeltaValue(int a, int b, double value, boolean switched) {
if (switched) {
delta[b][a] = value;
} else {
delta[a][b] = value;
}
}
private void setDeltaBitValue(int a, int b, byte value, boolean switched) {
if (switched) {
deltaBit[b][a] = value;
} else {
deltaBit[a][b] = value;
}
}
public void setCustomCosts(double costDel, double costIns, double costMatch) {
this.costDel = costDel;
this.costIns = costIns;
this.costMatch = costMatch;
}
public void setCustomStrategy(int[][] strategyArray) {
str = strategyArray;
}
public void setCustomStrategy(int strategy, boolean ifSwitch) {
str = new int[size1][size2];
if (ifSwitch) {
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
str[i][j] = it1.info[POST2_SIZE][i] >= it2.info[POST2_SIZE][j] ? strategy
: strategy + 4;
}
}
} else {
for (int i = 0; i < size1; i++) {
Arrays.fill(str[i], strategy);
}
}
}
/**
* Compute the minimal edit mapping between two trees. There might be
* multiple minimal edit mappings. This function computes only one of them.
*
* The first step of this function is to compute the tree edit distance.
* Based on the tree distance matrix the mapping is computed.
*
* @return all pairs (ted1.node,ted2.node) of the minimal edit mapping. Each
* element in the collection is an integer array A of size 2, where
* A[0]=ted1.node is the postorderID (starting with 1) of the nodes
* in ted1 and A[1]=ted2.node is the postorderID in ted2. The
* postorderID of the empty node (insertion, deletion) is zero.
*/
public ArrayDeque<int[]> computeEditMapping() {
// initialize tree and forest distance arrays
double[][] treedist = new double[size1 + 1][size2 + 1];
double[][] forestdist = new double[size1 + 1][size2 + 1];
boolean rootNodePair = true;
// treedist was already computed - the result is in delta and deltaBit
for (int i = 0; i < size1; i++) {
treedist[i][0] = i;
}
for (int j = 0; j < size2; j++) {
treedist[0][j] = j;
}
for (int i = 1; i <= size1; i++) {
for (int j = 1; j <= size2; j++) {
treedist[i][j] = delta[i - 1][j - 1] + deltaBit[i - 1][j - 1];
}
}
// forestdist for input trees has to be computed
forestDist(it1, it2, size1, size2, treedist, forestdist);
// empty edit mapping
ArrayDeque<int[]> editMapping = new ArrayDeque<>();
// empty stack of tree Pairs
ArrayDeque<int[]> treePairs = new ArrayDeque<>();
// push the pair of trees (ted1,ted2) to stack
treePairs.addFirst(new int[] { size1, size2 });
while (!treePairs.isEmpty()) {
// get next tree pair to be processed
int[] treePair = treePairs.removeFirst();
int lastRow = treePair[0];
int lastCol = treePair[1];
// compute forest distance matrix
if (!rootNodePair) {
forestDist(it1, it2, lastRow, lastCol, treedist, forestdist);
}
rootNodePair = false;
// compute mapping for current forest distance matrix
int firstRow = it1.getInfo(POST2_LLD, lastRow - 1) + 1 - 1;
int firstCol = it2.getInfo(POST2_LLD, lastCol - 1) + 1 - 1;
int row = lastRow;
int col = lastCol;
while ((row > firstRow) || (col > firstCol)) {
if ((row > firstRow)
&& (forestdist[row - 1][col] + costDel == forestdist[row][col])) {
// node with postorderID row is deleted from ted1
editMapping.addFirst(new int[] { row, 0 });
row--;
} else if ((col > firstCol)
&& (forestdist[row][col - 1] + costIns == forestdist[row][col])) {
// node with postorderID col is inserted into ted2
editMapping.addFirst(new int[] { 0, col });
col--;
} else {
// node with postorderID row in ted1 is renamed to node col
// in ted2
if ((it1.getInfo(POST2_LLD, row - 1) == it1.getInfo(POST2_LLD, lastRow - 1))
&& (it2.getInfo(POST2_LLD, col - 1) == it2.getInfo(POST2_LLD, lastCol - 1))) {
// if both subforests are trees, map nodes
editMapping.addFirst(new int[] { row, col });
row--;
col--;
} else {
// pop subtree pair
treePairs.addFirst(new int[] { row, col });
// continue with forest to the left of the popped
// subtree pair
row = it1.getInfo(POST2_LLD, row - 1) + 1 - 1;
col = it2.getInfo(POST2_LLD, col - 1) + 1 - 1;
}
}
}
}
return editMapping;
}
private void forestDist(InfoTree ted1, InfoTree ted2, int i, int j, double[][] treedist, double[][] forestdist) {
forestdist[ted1.getInfo(POST2_LLD, i - 1) + 1 - 1][ted2.getInfo(POST2_LLD, j - 1) + 1 - 1] = 0;
for (int di = ted1.getInfo(POST2_LLD, i - 1) + 1; di <= i; di++) {
forestdist[di][ted2.getInfo(POST2_LLD, j - 1) + 1 - 1] = forestdist[di - 1][ted2.getInfo(POST2_LLD, j - 1) + 1 - 1] + costDel;
for (int dj = ted2.getInfo(POST2_LLD, j - 1) + 1; dj <= j; dj++) {
forestdist[ted1.getInfo(POST2_LLD, i - 1) + 1 - 1][dj] = forestdist[ted1.getInfo(POST2_LLD, i - 1) + 1 - 1][dj - 1] + costIns;
if ((ted1.getInfo(POST2_LLD, di - 1) == ted1.getInfo(POST2_LLD, i - 1))
&& (ted2.getInfo(POST2_LLD, dj - 1) == ted2.getInfo(POST2_LLD, j - 1))) {
double costRen = 0;
if (!(ted1.getInfo(POST2_LABEL, di - 1) == ted2.getInfo(POST2_LABEL, dj - 1))) {
costRen = costMatch;
}
forestdist[di][dj] = Math.min(Math.min(
forestdist[di - 1][dj] + costDel,
forestdist[di][dj - 1] + costIns),
forestdist[di - 1][dj - 1] + costRen);
treedist[di][dj] = forestdist[di][dj];
} else {
forestdist[di][dj] = Math.min(Math.min(
forestdist[di - 1][dj] + costDel,
forestdist[di][dj - 1] + costIns),
forestdist[ted1.getInfo(POST2_LLD, di - 1) + 1 - 1][ted2.getInfo(POST2_LLD, dj - 1) + 1 - 1]
+ treedist[di][dj]);
}
}
}
}
}
| 37,783
| 30.939138
| 131
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimal/rted/RtedMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.optimal.rted;
import java.util.ArrayDeque;
import java.util.List;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeUtils;
public class RtedMatcher extends Matcher {
public RtedMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
public void match() {
RtedAlgorithm a = new RtedAlgorithm(1D, 1D, 1D);
a.init(src, dst);
a.computeOptimalStrategy();
a.nonNormalizedTreeDist();
ArrayDeque<int[]> arrayMappings = a.computeEditMapping();
List<ITree> srcs = TreeUtils.postOrder(src);
List<ITree> dsts = TreeUtils.postOrder(dst);
for (int[] m: arrayMappings) {
if (m[0] != 0 && m[1] != 0) {
ITree src = srcs.get(m[0] - 1);
ITree dst = dsts.get(m[1] - 1);
if (isMappingAllowed(src, dst))
addMapping(src, dst);
}
}
}
}
| 1,882
| 32.625
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimal/zs/ZsMatcher.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.matchers.optimal.zs;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.simmetrics.StringMetrics;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
public class ZsMatcher extends Matcher {
private ZsTree zsSrc;
private ZsTree zsDst;
private double[][] treeDist;
private double[][] forestDist;
private static ITree getFirstLeaf(ITree t) {
ITree current = t;
while (!current.isLeaf())
current = current.getChild(0);
return current;
}
public ZsMatcher(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
this.zsSrc = new ZsTree(src);
this.zsDst = new ZsTree(dst);
}
private double[][] computeTreeDist() {
treeDist = new double[zsSrc.nodeCount + 1][zsDst.nodeCount + 1];
forestDist = new double[zsSrc.nodeCount + 1][zsDst.nodeCount + 1];
for (int i = 1; i < zsSrc.kr.length; i++) {
for (int j = 1; j < zsDst.kr.length; j++) {
forestDist(zsSrc.kr[i], zsDst.kr[j]);
}
}
return treeDist;
}
private void forestDist(int i, int j) {
forestDist[zsSrc.lld(i) - 1][zsDst.lld(j) - 1] = 0;
for (int di = zsSrc.lld(i); di <= i; di++) {
double costDel = getDeletionCost(zsSrc.tree(di));
forestDist[di][zsDst.lld(j) - 1] = forestDist[di - 1][zsDst.lld(j) - 1] + costDel;
for (int dj = zsDst.lld(j); dj <= j; dj++) {
double costIns = getInsertionCost(zsDst.tree(dj));
forestDist[zsSrc.lld(i) - 1][dj] = forestDist[zsSrc.lld(i) - 1][dj - 1] + costIns;
if ((zsSrc.lld(di) == zsSrc.lld(i) && (zsDst.lld(dj) == zsDst.lld(j)))) {
double costUpd = getUpdateCost(zsSrc.tree(di), zsDst.tree(dj));
forestDist[di][dj] = Math.min(Math.min(forestDist[di - 1][dj] + costDel,
forestDist[di][dj - 1] + costIns),
forestDist[di - 1][dj - 1] + costUpd);
treeDist[di][dj] = forestDist[di][dj];
} else {
forestDist[di][dj] = Math.min(Math.min(forestDist[di - 1][dj] + costDel,
forestDist[di][dj - 1] + costIns),
forestDist[zsSrc.lld(di) - 1][zsDst.lld(dj) - 1]
+ treeDist[di][dj]);
}
}
}
}
@Override
public void match() {
computeTreeDist();
boolean rootNodePair = true;
ArrayDeque<int[]> treePairs = new ArrayDeque<>();
// push the pair of trees (ted1,ted2) to stack
treePairs.addFirst(new int[] { zsSrc.nodeCount, zsDst.nodeCount });
while (!treePairs.isEmpty()) {
int[] treePair = treePairs.removeFirst();
int lastRow = treePair[0];
int lastCol = treePair[1];
// compute forest distance matrix
if (!rootNodePair)
forestDist(lastRow, lastCol);
rootNodePair = false;
// compute mapping for current forest distance matrix
int firstRow = zsSrc.lld(lastRow) - 1;
int firstCol = zsDst.lld(lastCol) - 1;
int row = lastRow;
int col = lastCol;
while ((row > firstRow) || (col > firstCol)) {
if ((row > firstRow)
&& (forestDist[row - 1][col] + 1D == forestDist[row][col])) {
// node with postorderID row is deleted from ted1
row--;
} else if ((col > firstCol)
&& (forestDist[row][col - 1] + 1D == forestDist[row][col])) {
// node with postorderID col is inserted into ted2
col--;
} else {
// node with postorderID row in ted1 is renamed to node col
// in ted2
if ((zsSrc.lld(row) - 1 == zsSrc.lld(lastRow) - 1)
&& (zsDst.lld(col) - 1 == zsDst.lld(lastCol) - 1)) {
// if both subforests are trees, map nodes
ITree tSrc = zsSrc.tree(row);
ITree tDst = zsDst.tree(col);
if (tSrc.getType() == tDst.getType())
addMapping(tSrc, tDst);
else
throw new RuntimeException("Should not map incompatible nodes.");
row--;
col--;
} else {
// pop subtree pair
treePairs.addFirst(new int[] { row, col });
// continue with forest to the left of the popped
// subtree pair
row = zsSrc.lld(row) - 1;
col = zsDst.lld(col) - 1;
}
}
}
}
}
private double getDeletionCost(ITree n) {
return 1D;
}
private double getInsertionCost(ITree n) {
return 1D;
}
private double getUpdateCost(ITree n1, ITree n2) {
if (n1.getType() == n2.getType())
if ("".equals(n1.getLabel()) || "".equals(n2.getLabel()))
return 1D;
else
return 1D - StringMetrics.qGramsDistance().compare(n1.getLabel(), n2.getLabel());
else
return Double.MAX_VALUE;
}
private static final class ZsTree {
private int start; // internal array position of leafmost leaf descendant of the root node
private int nodeCount; // number of nodes
private int leafCount;
private int[] llds; // llds[i] stores the postorder-ID of the
// left-most leaf descendant of the i-th node in postorder
private ITree[] labels; // labels[i] is the tree of the i-th node in postorder
private int[] kr;
private ZsTree(ITree t) {
this.start = 0;
this.nodeCount = t.getSize();
this.leafCount = 0;
this.llds = new int[start + nodeCount];
this.labels = new ITree[start + nodeCount];
int idx = 1;
Map<ITree,Integer> tmpData = new HashMap<>();
for (ITree n: t.postOrder()) {
tmpData.put(n, idx);
this.setITree(idx, n);
this.setLld(idx, tmpData.get(ZsMatcher.getFirstLeaf(n)));
if (n.isLeaf())
leafCount++;
idx++;
}
setKeyRoots();
}
public void setITree(int i, ITree tree) {
labels[i + start - 1] = tree;
if (nodeCount < i)
nodeCount = i;
}
public void setLld(int i, int lld) {
llds[i + start - 1] = lld + start - 1;
if (nodeCount < i)
nodeCount = i;
}
public boolean isLeaf(int i) {
return this.lld(i) == i;
}
public int lld(int i) {
return llds[i + start - 1] - start + 1;
}
public ITree tree(int i) {
return labels[i + start - 1];
}
public void setKeyRoots() {
kr = new int[leafCount + 1];
boolean[] visited = new boolean[nodeCount + 1];
Arrays.fill(visited, false);
int k = kr.length - 1;
for (int i = nodeCount; i >= 1; i--) {
if (!visited[lld(i)]) {
kr[k] = i;
visited[lld(i)] = true;
k--;
}
}
}
}
}
| 8,700
| 33.121569
| 98
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimizations/CrossMoveMatcherThetaF.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers.optimizations;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
/**
* This implements the cross move matcher Theta F.
*
*/
public class CrossMoveMatcherThetaF extends Matcher {
private class BfsComparator implements Comparator<Mapping> {
private HashMap<Integer, Integer> positionSrc;
private HashMap<Integer, Integer> positionDst;
private HashMap<Integer, Integer> getHashSet(ITree tree) {
HashMap<Integer, Integer> map = new HashMap<>();
ArrayList<ITree> list = new ArrayList<>();
LinkedList<ITree> workList = new LinkedList<>();
workList.add(tree);
while (!workList.isEmpty()) {
ITree node = workList.removeFirst();
list.add(node);
workList.addAll(node.getChildren());
}
for (int i = 0; i < list.size(); i++) {
map.put(list.get(i).getId(), i);
}
return map;
}
public BfsComparator(ITree src, ITree dst) {
positionSrc = getHashSet(src);
positionDst = getHashSet(dst);
}
@Override
public int compare(Mapping o1, Mapping o2) {
if (o1.first.getId() != o2.first.getId()) {
return Integer.compare(positionSrc.get(o1.first.getId()),
positionSrc.get(o2.first.getId()));
}
return Integer.compare(positionDst.get(o1.second.getId()),
positionDst.get(o2.second.getId()));
}
}
/**
* Instantiates a new matcher for Theta F.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public CrossMoveMatcherThetaF(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
protected void addMapping(ITree src, ITree dst) {
assert (src != null);
assert (dst != null);
super.addMapping(src, dst);
}
/**
* Match.
*/
@Override
public void match() {
thetaF();
}
private void thetaF() {
LinkedList<Mapping> workList = new LinkedList<>(mappings.asSet());
Collections.sort(workList, new BfsComparator(src, dst));
for (Mapping pair : workList) {
ITree parentOld = pair.getFirst().getParent();
ITree parentNew = pair.getSecond().getParent();
if (mappings.hasSrc(parentOld) && mappings.getDst(parentOld) != parentNew) {
if (mappings.hasDst(parentNew) && mappings.getSrc(parentNew) != parentOld) {
ITree parentOldOther = mappings.getSrc(parentNew);
ITree parentNewOther = mappings.getDst(parentOld);
if (parentOld.getLabel().equals(parentNewOther.getLabel())
&& parentNew.getLabel().equals(parentOldOther.getLabel())) {
boolean done = false;
for (ITree childOldOther : parentOldOther.getChildren()) {
if (mappings.hasSrc(childOldOther)) {
ITree childNewOther = mappings.getDst(childOldOther);
if (pair.getFirst().getLabel().equals(childNewOther.getLabel())
&& childOldOther.getLabel()
.equals(pair.getSecond().getLabel())
|| !(pair.getFirst().getLabel()
.equals(pair.getSecond().getLabel())
|| childOldOther.getLabel()
.equals(childNewOther.getLabel()))) {
if (childNewOther.getParent() == parentNewOther) {
if (childOldOther.getType() == pair.getFirst().getType()) {
mappings.unlink(pair.getFirst(), pair.getSecond());
mappings.unlink(childOldOther, childNewOther);
addMapping(pair.getFirst(), childNewOther);
addMapping(childOldOther, pair.getSecond());
// done = true;
}
}
}
}
}
if (!done) {
for (ITree childNewOther : parentNewOther.getChildren()) {
if (mappings.hasDst(childNewOther)) {
ITree childOldOther = mappings.getSrc(childNewOther);
if (childOldOther.getParent() == parentOldOther) {
if (childNewOther.getType() == pair.getSecond().getType()) {
if (pair.getFirst().getLabel()
.equals(childNewOther.getLabel())
&& childOldOther.getLabel()
.equals(pair.getSecond().getLabel())
|| !(pair.getFirst().getLabel()
.equals(pair.getSecond().getLabel())
|| childOldOther.getLabel().equals(
childNewOther.getLabel()))) {
mappings.unlink(pair.getFirst(), pair.getSecond());
mappings.unlink(childOldOther, childNewOther);
addMapping(childOldOther, pair.getSecond());
addMapping(pair.getFirst(), childNewOther);
}
}
}
}
}
}
}
}
}
}
}
}
| 7,482
| 43.017647
| 100
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimizations/IdenticalSubtreeMatcherThetaA.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers.optimizations;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
/**
* This implements the identical subtree optimization Theta A.
*
*/
public class IdenticalSubtreeMatcherThetaA extends Matcher {
public IdenticalSubtreeMatcherThetaA(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@SuppressWarnings({ "checkstyle:AvoidEscapedUnicodeCharacters" })
private String getHash(ITree node, HashMap<ITree, Integer> quickFind,
HashMap<ITree, String> stringMap) {
String tmp = node.getType() + node.getLabel();
for (ITree child : node.getChildren()) {
tmp += getHash(child, quickFind, stringMap);
}
tmp += "\\u2620";
quickFind.put(node, tmp.hashCode());
stringMap.put(node, tmp);
return tmp;
}
private List<ITree> getNodeStream(ITree root) {
LinkedList<ITree> nodes = new LinkedList<>();
LinkedList<ITree> workList = new LinkedList<>();
workList.add(root);
while (!workList.isEmpty()) {
ITree node = workList.removeFirst();
nodes.add(node);
for (int i = node.getChildren().size() - 1; i >= 0; i--) {
workList.addFirst(node.getChildren().get(i));
}
}
return nodes;
}
/**
* Match with Theta A.
*/
@Override
public void match() {
newUnchangedMatching();
}
private void newUnchangedMatching() {
HashMap<ITree, Integer> quickFind = new HashMap<>();
HashMap<ITree, String> stringMap = new HashMap<>();
getHash(src, quickFind, stringMap);
getHash(dst, quickFind, stringMap);
HashMap<String, LinkedList<ITree>> nodeMapOld = new HashMap<>();
List<ITree> streamOld = getNodeStream(src);
List<ITree> streamNew = getNodeStream(dst);
for (ITree node : streamOld) {
String hashString = stringMap.get(node);
LinkedList<ITree> nodeList = nodeMapOld.get(hashString);
if (nodeList == null) {
nodeList = new LinkedList<>();
nodeMapOld.put(hashString, nodeList);
}
nodeList.add(node);
}
HashMap<String, LinkedList<ITree>> nodeMapNew = new HashMap<>();
for (ITree node : streamNew) {
String hashString = stringMap.get(node);
LinkedList<ITree> nodeList = nodeMapNew.get(hashString);
if (nodeList == null) {
nodeList = new LinkedList<>();
nodeMapNew.put(hashString, nodeList);
}
nodeList.add(node);
}
HashSet<Mapping> pairs = new HashSet<>();
LinkedList<ITree> workList = new LinkedList<>();
workList.add(src);
while (!workList.isEmpty()) {
ITree node = workList.removeFirst();
LinkedList<ITree> oldList = nodeMapOld.get(stringMap.get(node));
assert (oldList != null);
LinkedList<ITree> newList = nodeMapNew.get(stringMap.get(node));
if (oldList.size() == 1 && newList != null && newList.size() == 1) {
if (node.getChildren().size() > 0) {
assert (stringMap.get(node).equals(stringMap.get(newList.getFirst())));
pairs.add(new Mapping(node, newList.getFirst()));
oldList.remove(node);
newList.removeFirst();
}
} else {
workList.addAll(node.getChildren());
}
}
for (Mapping mapping : pairs) {
List<ITree> stream1 = getNodeStream(mapping.getFirst());
List<ITree> stream2 = getNodeStream(mapping.getSecond());
stream1 = new ArrayList<>(stream1);
stream2 = new ArrayList<>(stream2);
assert (stream1.size() == stream2.size());
for (int i = 0; i < stream1.size(); i++) {
ITree oldNode = stream1.get(i);
ITree newNode = stream2.get(i);
assert (oldNode.getType() == newNode.getType());
assert (oldNode.getLabel().equals(newNode.getLabel()));
this.addMapping(oldNode, newNode);
}
}
}
}
| 5,340
| 34.606667
| 91
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimizations/InnerNodesMatcherThetaD.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers.optimizations;
import java.util.Collections;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
/**
* This implements the unmapped leaves optimization (Theta C), the inner node repair optimization
* (Theta D) and the leaf move optimization (Theta E).
*
*/
public class InnerNodesMatcherThetaD extends Matcher {
private class ChangeMapComparator
implements Comparator<Entry<ITree, IdentityHashMap<ITree, Integer>>> {
@Override
public int compare(Entry<ITree, IdentityHashMap<ITree, Integer>> o1,
Entry<ITree, IdentityHashMap<ITree, Integer>> o2) {
return Integer.compare(o1.getKey().getId(), o2.getKey().getId());
}
}
/**
* Instantiates a new matcher for Theta A-E.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public InnerNodesMatcherThetaD(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
protected void addMapping(ITree src, ITree dst) {
assert (src != null);
assert (dst != null);
super.addMapping(src, dst);
}
private boolean allowedMatching(ITree key, ITree maxNodePartner) {
while (key != null) {
if (key == maxNodePartner) {
return false;
}
key = key.getParent();
}
return true;
}
/**
* Match.
*/
@Override
public void match() {
thetaD();
}
private void thetaD() {
IdentityHashMap<ITree, IdentityHashMap<ITree, Integer>> parentCount =
new IdentityHashMap<>();
for (Mapping pair : mappings.asSet()) {
ITree parent = pair.first.getParent();
ITree parentPartner = pair.second.getParent();
if (parent != null && parentPartner != null) {
IdentityHashMap<ITree, Integer> countMap = parentCount.get(parent);
if (countMap == null) {
countMap = new IdentityHashMap<>();
parentCount.put(parent, countMap);
}
Integer count = countMap.get(parentPartner);
if (count == null) {
count = new Integer(0);
}
countMap.put(parentPartner, count + 1);
}
}
LinkedList<Entry<ITree, IdentityHashMap<ITree, Integer>>> list =
new LinkedList<>(parentCount.entrySet());
Collections.sort(list, new ChangeMapComparator());
for (Entry<ITree, IdentityHashMap<ITree, Integer>> countEntry : list) {
int max = Integer.MIN_VALUE;
int maxCount = 0;
ITree maxNode = null;
for (Entry<ITree, Integer> newNodeEntry : countEntry.getValue().entrySet()) {
if (newNodeEntry.getValue() > max) {
max = newNodeEntry.getValue();
maxCount = 1;
maxNode = newNodeEntry.getKey();
} else if (newNodeEntry.getValue() == max) {
maxCount++;
}
}
if (maxCount == 1) {
if (mappings.getDst(countEntry.getKey()) != null
&& mappings.getSrc(maxNode) != null) {
ITree partner = mappings.getDst(countEntry.getKey());
ITree maxNodePartner = mappings.getSrc(maxNode);
if (partner != maxNode) {
if (max > countEntry.getKey().getChildren().size() / 2
|| countEntry.getKey().getChildren().size() == 1) {
ITree parentPartner = mappings.getDst(countEntry.getKey().getParent());
if (parentPartner != null && parentPartner == partner.getParent()) {
continue;
}
if (allowedMatching(countEntry.getKey(), maxNodePartner)) {
if (countEntry.getKey().getType() == maxNode.getType()) {
if (maxNodePartner != null) {
mappings.unlink(maxNodePartner, maxNode);
}
if (partner != null) {
mappings.unlink(countEntry.getKey(), partner);
}
addMapping(countEntry.getKey(), maxNode);
}
if (maxNodePartner != null) {
if (maxNodePartner.getType() == partner.getType()) {
addMapping(maxNodePartner, partner);
}
}
}
}
}
}
}
}
}
}
| 6,070
| 36.245399
| 99
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimizations/LcsOptMatcherThetaB.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers.optimizations;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
/**
* This implements the lcs optimization Theta B.
*
*/
public class LcsOptMatcherThetaB extends Matcher {
/**
* Instantiates a new lcs matcher.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public LcsOptMatcherThetaB(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
private void advancedLcsMatching() {
List<ITree> allNodesSrc = src.getTrees();
List<ITree> allNodesDst = dst.getTrees();
Set<ITree> unmatchedNodes1 = new HashSet<>();
Set<ITree> unmatchedNodes2 = new HashSet<>();
for (ITree node : allNodesSrc) {
if (!mappings.hasSrc(node)) {
unmatchedNodes1.add(node);
}
}
for (ITree node : allNodesDst) {
if (!mappings.hasDst(node)) {
unmatchedNodes2.add(node);
}
}
if (unmatchedNodes1.size() > 0 && unmatchedNodes2.size() > 0) {
ArrayList<ITree> workList = new ArrayList<>();
getUnmatchedNodeListInPostOrder(src, workList);
HashSet<ITree> checkedParent = new HashSet<>();
for (ITree node : workList) {
if (!unmatchedNodes1.contains(node)) {
continue;
}
ITree parent = node.getParent();
if (parent == null) {
continue;
}
ITree partner = null;
if (parent == src) {
partner = dst;
} else {
partner = mappings.getDst(parent);
}
while (parent != null && partner == null) {
parent = parent.getParent();
partner = mappings.getDst(parent);
}
if (parent != null && partner != null) {
if (checkedParent.contains(parent)) {
// System.out.println("continue checked");
continue;
}
checkedParent.add(parent);
ArrayList<ITree> list1 = new ArrayList<>();
ArrayList<ITree> list2 = new ArrayList<>();
getNodeListInPostOrder(parent, list1);
getNodeListInPostOrder(partner, list2);
List<Mapping> lcsMatch = lcs(list1, list2, unmatchedNodes1, unmatchedNodes2);
for (Mapping match : lcsMatch) {
if (!mappings.hasSrc(match.first) && !mappings.hasDst(match.second)) {
addMapping(match.first, match.second);
unmatchedNodes1.remove(match.first);
unmatchedNodes2.remove(match.second);
}
}
}
}
}
}
private void backtrack(ArrayList<ITree> list1, ArrayList<ITree> list2,
LinkedList<Mapping> resultList, int[][] matrix, int ipar, int jpar,
Set<ITree> unmatchedNodes1, Set<ITree> unmatchedNodes2) {
assert (ipar >= 0);
assert (jpar >= 0);
while (ipar > 0 && jpar > 0) {
if (testCondition(list1.get(ipar - 1), list2.get(jpar - 1), unmatchedNodes1,
unmatchedNodes2)) {
if (!mappings.hasSrc(list1.get(ipar - 1))) {
resultList.add(new Mapping(list1.get(ipar - 1), list2.get(jpar - 1)));
}
}
if (matrix[ipar][jpar - 1] > matrix[ipar - 1][jpar]) {
jpar--;
} else {
ipar--;
}
}
}
private void getNodeListInPostOrder(ITree tree, ArrayList<ITree> nodes) {
if (tree != null) {
for (ITree child : tree.getChildren()) {
getNodeListInPostOrder(child, nodes);
}
nodes.add(tree);
}
}
private void getUnmatchedNodeListInPostOrder(ITree tree, ArrayList<ITree> nodes) {
if (tree != null) {
for (ITree child : tree.getChildren()) {
getNodeListInPostOrder(child, nodes);
}
if (!mappings.hasSrc(tree) && !mappings.hasDst(tree)) {
nodes.add(tree);
}
}
}
private List<Mapping> lcs(ArrayList<ITree> list1, ArrayList<ITree> list2,
Set<ITree> unmatchedNodes1, Set<ITree> unmatchedNodes2) {
int[][] matrix = new int[list1.size() + 1][list2.size() + 1];
for (int i = 1; i < list1.size() + 1; i++) {
for (int j = 1; j < list2.size() + 1; j++) {
if (testCondition(list1.get(i - 1), list2.get(j - 1), unmatchedNodes1,
unmatchedNodes2)) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
} else {
matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);
}
}
}
LinkedList<Mapping> resultList = new LinkedList<>();
backtrack(list1, list2, resultList, matrix, list1.size(), list2.size(), unmatchedNodes1,
unmatchedNodes2);
return resultList;
}
/**
* Match with Theta B.
*/
@Override
public void match() {
advancedLcsMatching();
}
/**
* Compare two nodes to test lcs condition.
*
* @param node1 the node1
* @param node2 the node2
* @param unmatchedNodes1 the unmatched nodes1
* @param unmatchedNodes2 the unmatched nodes2
* @return true, if successful
*/
public boolean testCondition(ITree node1, ITree node2, Set<ITree> unmatchedNodes1,
Set<ITree> unmatchedNodes2) {
if (node1.getType() != node2.getType()) {
return false;
}
if ((mappings.hasSrc(node1) && mappings.getDst(node1) == node2) || (unmatchedNodes1.contains(node1) && unmatchedNodes2.contains(node2))) {
return true;
}
return false;
}
}
| 7,208
| 34.165854
| 146
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimizations/LeafMoveMatcherThetaE.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers.optimizations;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
/**
* This implements the unmapped leaves optimization (Theta C), the inner node repair optimization
* (Theta D) and the leaf move optimization (Theta E).
*
*/
public class LeafMoveMatcherThetaE extends Matcher {
private class MappingComparator implements Comparator<Mapping> {
@Override
public int compare(Mapping o1, Mapping o2) {
if (o1.first.getId() != o2.first.getId()) {
return Integer.compare(o1.first.getId(), o2.first.getId());
}
return Integer.compare(o1.second.getId(), o2.second.getId());
}
}
/**
* Instantiates a new matcher for Theta A-E.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public LeafMoveMatcherThetaE(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
protected void addMapping(ITree src, ITree dst) {
assert (src != null);
assert (dst != null);
super.addMapping(src, dst);
}
/**
* Match.
*/
@Override
public void match() {
thetaE();
}
private void thetaE() {
LinkedList<Mapping> workList = new LinkedList<>();
LinkedList<Mapping> workListTmp = null;
LinkedList<Mapping> changeMap = new LinkedList<>();
for (Mapping pair : mappings.asSet()) {
if (pair.first.isLeaf() && pair.second.isLeaf()) {
if (!pair.first.getLabel().equals(pair.second.getLabel())) {
workList.add(pair);
}
}
}
while (!workList.isEmpty()) {
Collections.sort(workList, new MappingComparator());
workListTmp = new LinkedList<>();
for (Mapping pair : workList) {
ITree firstParent = pair.first.getParent();
if (!mappings.hasDst(firstParent)) {
continue;
}
ITree secondParent = mappings.getDst(pair.first.getParent());
reevaluateLeaves(firstParent, secondParent, pair, changeMap);
}
Collections.sort(changeMap, new MappingComparator());
for (Mapping entry : changeMap) {
if (!mappings.hasSrc(entry.first) && !mappings.hasDst(entry.second)) {
addMapping(entry.first, entry.second);
}
if (!entry.first.getLabel().equals(entry.second.getLabel()) && entry.first.isLeaf()
&& entry.second.isLeaf()) {
workListTmp.add(new Mapping(entry.first, entry.second));
}
}
changeMap.clear();
workList = workListTmp;
}
workList = new LinkedList<>();
workListTmp = null;
for (Mapping pair : mappings.asSet()) {
if (pair.first.isLeaf() && pair.second.isLeaf()) {
if (!pair.first.getLabel().equals(pair.second.getLabel())) {
workList.add(pair);
}
}
}
while (!workList.isEmpty()) {
Collections.sort(workList, new MappingComparator());
workListTmp = new LinkedList<>();
for (Mapping pair : workList) {
ITree firstParent = pair.first.getParent();
ITree secondParent = pair.second.getParent();
reevaluateLeaves(firstParent, secondParent, pair, changeMap);
}
Collections.sort(changeMap, new MappingComparator());
for (Mapping entry : changeMap) {
if (!mappings.hasSrc(entry.first) && !mappings.hasDst(entry.second)) {
addMapping(entry.first, entry.second);
}
if (!entry.first.getLabel().equals(entry.second.getLabel()) && entry.first.isLeaf()
&& entry.second.isLeaf()) {
workListTmp.add(new Mapping(entry.first, entry.second));
}
}
changeMap.clear();
workList = workListTmp;
}
}
private void reevaluateLeaves(ITree firstParent, ITree secondParent, Mapping pair,
List<Mapping> changeMap) {
int count = 0;
ITree foundDstNode = null;
ITree foundPosDstNode = null;
int pos = firstParent.getChildren().indexOf(pair.first);
for (int i = 0; i < secondParent.getChildren().size(); i++) {
ITree child = secondParent.getChildren().get(i);
if (child.getType() == pair.first.getType()
&& child.getLabel().equals(pair.first.getLabel())) {
count++;
foundDstNode = child;
if (i == pos) {
foundPosDstNode = child;
}
}
}
Mapping addedMappingKey = null;
if ((count == 1 && foundDstNode != null) || foundPosDstNode != null) {
if (count != 1 && foundPosDstNode != null) {
foundDstNode = foundPosDstNode;
}
if (mappings.hasDst(foundDstNode)) {
ITree foundSrc = mappings.getSrc(foundDstNode);
if (!foundSrc.getLabel().equals(foundDstNode.getLabel())) {
mappings.unlink(pair.first, pair.second);
mappings.unlink(foundSrc, foundDstNode);
changeMap.add(new Mapping(pair.first, foundDstNode));
addedMappingKey = new Mapping(foundSrc, foundDstNode);
if (foundDstNode != pair.second && foundSrc != pair.first) {
changeMap.add(new Mapping(foundSrc, pair.second));
}
}
} else {
mappings.unlink(pair.first, pair.second);
if (pair.first.getLabel().equals(foundDstNode.getLabel())) {
LinkedList<Mapping> toRemove = new LinkedList<>();
for (Mapping mapPair : changeMap) {
if (mapPair.first == pair.first) {
if (!mapPair.first.getLabel().equals(mapPair.second.getLabel())) {
toRemove.add(mapPair);
}
} else if (mapPair.second == foundDstNode) {
if (!mapPair.first.getLabel().equals(mapPair.second.getLabel())) {
toRemove.add(mapPair);
}
}
}
changeMap.removeAll(toRemove);
}
changeMap.add(new Mapping(pair.first, foundDstNode));
for (ITree child : firstParent.getChildren()) {
if (child.isLeaf() && !mappings.hasDst(child)
&& child.getType() == pair.second.getType()
&& child.getLabel().equals(pair.second.getLabel())) {
addMapping(child, pair.second);
break;
}
}
}
}
ITree foundSrcNode = null;
ITree foundPosSrcNode = null;
pos = secondParent.getChildren().indexOf(pair.second);
for (int i = 0; i < firstParent.getChildren().size(); i++) {
ITree child = firstParent.getChildren().get(i);
if (child.getType() == pair.second.getType()
&& child.getLabel().equals(pair.second.getLabel())) {
count++;
foundSrcNode = child;
if (i == pos) {
foundPosSrcNode = child;
}
}
}
if ((count == 1 && foundSrcNode != null) || foundPosSrcNode != null) {
if (count != 1 && foundPosSrcNode != null) {
foundSrcNode = foundPosSrcNode;
} else if (foundSrcNode == null) {
foundSrcNode = foundPosSrcNode;
}
if (addedMappingKey != null) {
changeMap.remove(addedMappingKey);
}
if (mappings.hasSrc(foundSrcNode)) {
ITree foundDst = mappings.getSrc(foundSrcNode);
if (foundDst != null && foundSrcNode != null
&& !foundDst.getLabel().equals(foundSrcNode.getLabel())) {
mappings.unlink(pair.first, pair.second);
mappings.unlink(foundSrcNode, foundDst);
changeMap.add(new Mapping(foundSrcNode, pair.second));
if (addedMappingKey == null && foundDst != null) {
if (foundSrcNode != pair.first && foundDst != pair.second) {
changeMap.add(new Mapping(pair.first, foundDst));
}
}
}
} else {
mappings.unlink(pair.first, pair.second);
if (foundSrcNode.getLabel().equals(pair.second.getLabel())) {
LinkedList<Mapping> toRemove = new LinkedList<>();
for (Mapping mapPair : changeMap) {
if (mapPair.first == foundSrcNode) {
if (!mapPair.first.getLabel().equals(mapPair.second.getLabel())) {
toRemove.add(mapPair);
}
} else if (mapPair.second == pair.second) {
if (!mapPair.first.getLabel().equals(mapPair.second.getLabel())) {
toRemove.add(mapPair);
}
}
}
changeMap.removeAll(toRemove);
}
changeMap.add(new Mapping(foundSrcNode, pair.second));
for (ITree child : secondParent.getChildren()) {
if (child.isLeaf() && !mappings.hasSrc(child)
&& child.getType() == pair.first.getType()
&& child.getLabel().equals(pair.first.getLabel())) {
addMapping(pair.first, child);
break;
}
}
}
}
}
}
| 11,385
| 39.233216
| 99
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/matchers/optimizations/UnmappedLeavesMatcherThetaC.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 Georg Dotzler <georg.dotzler@fau.de>
* Copyright 2015-2016 Marius Kamp <marius.kamp@fau.de>
*/
package gumtreediff.matchers.optimizations;
import java.util.LinkedList;
import java.util.List;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.tree.ITree;
/**
* This implements the unmapped leaves optimization (Theta C).
*
*/
public class UnmappedLeavesMatcherThetaC extends Matcher {
/**
* Instantiates a new matcher for Theta C.
*
* @param src the src
* @param dst the dst
* @param store the store
*/
public UnmappedLeavesMatcherThetaC(ITree src, ITree dst, MappingStore store) {
super(src, dst, store);
}
@Override
protected void addMapping(ITree src, ITree dst) {
assert (src != null);
assert (dst != null);
super.addMapping(src, dst);
}
/**
* Match.
*/
@Override
public void match() {
thetaC();
}
private void thetaC() {
List<ITree> allNodesSrc = src.getTrees();
List<ITree> allNodesDst = dst.getTrees();
List<ITree> unmatchedNodes1 = new LinkedList<>();
List<ITree> unmatchedNodes2 = new LinkedList<>();
for (ITree node : allNodesSrc) {
if (!mappings.hasSrc(node)) {
unmatchedNodes1.add(node);
}
}
for (ITree node : allNodesDst) {
if (!mappings.hasDst(node)) {
unmatchedNodes2.add(node);
}
}
for (ITree node : unmatchedNodes1) {
if (node.getChildren().size() == 0) {
ITree parent = node.getParent();
if (mappings.getDst(parent) != null) {
ITree partner = mappings.getDst(parent);
int pos = parent.getChildren().indexOf(node);
if (pos < partner.getChildren().size()) {
ITree child = partner.getChildren().get(pos);
if (child.getType() == node.getType()) {
if (child.getLabel().equals(node.getLabel())) {
ITree childPartner = mappings.getSrc(child);
if (childPartner != null) {
if (!childPartner.getLabel().equals(node.getLabel())) {
mappings.unlink(childPartner, child);
addMapping(node, child);
}
} else {
addMapping(node, child);
}
} else {
ITree childPartner = mappings.getSrc(child);
if (childPartner != null) {
if (mappings.getDst(childPartner.getParent()) == null) {
if (!childPartner.getLabel().equals(child.getLabel())) {
mappings.unlink(childPartner, child);
addMapping(node, child);
}
}
} else {
addMapping(node, child);
}
}
} else {
if (child.getChildren().size() == 1) {
child = child.getChildren().get(0);
if (child.getType() == node.getType()
&& child.getLabel().equals(node.getLabel())) {
ITree childPartner = mappings.getSrc(child);
if (childPartner != null) {
if (!childPartner.getLabel().equals(node.getLabel())) {
mappings.unlink(childPartner, child);
addMapping(node, child);
} else if (mappings
.getDst(childPartner.getParent()) == null) {
mappings.unlink(childPartner, child);
addMapping(node, child);
}
}
}
} else {
for (ITree possibleMatch : partner.getChildren()) {
if (possibleMatch.getType() == node.getType()
&& possibleMatch.getLabel().equals(node.getLabel())) {
ITree possibleMatchSrc = mappings.getSrc(possibleMatch);
if (possibleMatchSrc == null) {
addMapping(node, possibleMatch);
break;
} else {
if (!possibleMatchSrc.getLabel()
.equals(possibleMatch.getLabel())) {
mappings.unlink(possibleMatchSrc, possibleMatch);
addMapping(node, possibleMatch);
break;
}
}
}
}
}
}
}
}
}
}
for (ITree node : unmatchedNodes2) {
if (mappings.hasSrc(node)) {
continue;
}
if (node.getChildren().size() == 0) {
ITree parent = node.getParent();
if (mappings.getSrc(parent) != null) {
ITree partner = mappings.getSrc(parent);
int pos = parent.getChildren().indexOf(node);
if (pos < partner.getChildren().size()) {
ITree child = partner.getChildren().get(pos);
if (child.getType() == node.getType()) {
if (child.getLabel().equals(node.getLabel())) {
ITree tree = mappings.getDst(child);
if (tree != null) {
if (!tree.getLabel().equals(node.getLabel())) {
mappings.unlink(child, tree);
addMapping(child, node);
}
} else {
addMapping(child, node);
}
} else {
ITree childPartner = mappings.getDst(child);
if (childPartner != null) {
if (mappings.getSrc(childPartner.getParent()) == null) {
if (!childPartner.getLabel().equals(child.getLabel())) {
mappings.unlink(child, childPartner);
addMapping(child, node);
}
}
} else {
addMapping(child, node);
}
}
} else {
if (child.getChildren().size() == 1) {
child = child.getChildren().get(0);
if (child.getType() == node.getType()
&& child.getLabel().equals(node.getLabel())) {
ITree childPartner = mappings.getDst(child);
if (childPartner != null) {
if (!childPartner.getLabel().equals(node.getLabel())) {
mappings.unlink(child, childPartner);
addMapping(child, node);
} else if (mappings
.getSrc(childPartner.getParent()) == null) {
mappings.unlink(childPartner, child);
addMapping(node, child);
}
}
}
} else {
for (ITree possibleMatch : partner.getChildren()) {
if (possibleMatch.getType() == node.getType()
&& possibleMatch.getLabel().equals(node.getLabel())) {
ITree possibleMatchDst = mappings.getDst(possibleMatch);
if (possibleMatchDst == null) {
addMapping(possibleMatch, node);
break;
} else {
if (!possibleMatchDst.getLabel()
.equals(possibleMatch.getLabel())) {
mappings.unlink(possibleMatch, possibleMatchDst);
addMapping(possibleMatch, node);
break;
}
}
}
}
}
}
}
} else if (unmatchedNodes2.contains(parent)) {
ITree oldParent = parent;
parent = parent.getParent();
if (mappings.getSrc(parent) != null) {
ITree partner = mappings.getSrc(parent);
int pos = parent.getChildren().indexOf(oldParent);
if (pos < partner.getChildren().size()) {
ITree child = partner.getChildren().get(pos);
if (child.getType() == node.getType()
&& child.getLabel().equals(node.getLabel())) {
ITree tree = mappings.getDst(child);
if (tree != null) {
if (!tree.getLabel().equals(node.getLabel())) {
mappings.unlink(child, tree);
addMapping(child, node);
}
} else {
addMapping(child, node);
}
}
}
}
}
}
}
}
}
| 12,279
| 47.346457
| 98
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/AbstractTree.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import gumtreediff.tree.hash.HashUtils;
public abstract class AbstractTree implements ITree {
protected int id;
protected ITree parent;
protected List<ITree> children;
protected int height;
protected int line;
protected int column;
protected int lastLine;
protected int lastColumn;
protected int size;
protected int depth;
protected int hash;
@Override
public int getChildPosition(ITree child) {
return getChildren().indexOf(child);
}
@Override
public ITree getChild(int position) {
return getChildren().get(position);
}
@Override
public int getDepth() {
return depth;
}
@Override
public List<ITree> getDescendants() {
List<ITree> trees = TreeUtils.preOrder(this);
trees.remove(0);
return trees;
}
@Override
public int getHash() {
return hash;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getId() {
return id;
}
@Override
public boolean hasLabel() {
return !NO_LABEL.equals(getLabel());
}
@Override
public ITree getParent() {
return parent;
}
@Override
public void setParent(ITree parent) {
this.parent = parent;
}
@Override
public List<ITree> getParents() {
List<ITree> parents = new ArrayList<>();
if (getParent() == null)
return parents;
else {
parents.add(getParent());
parents.addAll(getParent().getParents());
}
return parents;
}
@Override
public int getSize() {
return size;
}
@Override
public List<ITree> getTrees() {
return TreeUtils.preOrder(this);
}
private String indent(ITree t) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < t.getDepth(); i++)
b.append("\t");
return b.toString();
}
@Override
public boolean isIsomorphicTo(ITree tree) {
if (!hasSameTypeAndLabel(tree) || (getChildren().size() != tree.getChildren().size()))
return false;
for (int i = 0; i < getChildren().size(); i++) {
boolean isChildrenIsomophic = getChild(i).isIsomorphicTo(tree.getChild(i));
if (!isChildrenIsomophic)
return false;
}
return true;
}
@Override
public boolean hasSameType(ITree t) {
return getType() == t.getType();
}
@Override
public boolean isLeaf() {
return getChildren().size() == 0;
}
@Override
public boolean isRoot() {
return getParent() == null;
}
@Override
public boolean hasSameTypeAndLabel(ITree t) {
if (!hasSameType(t))
return false;
else if (!getLabel().equals(t.getLabel()))
return false;
return true;
}
@Override
public Iterable<ITree> preOrder() {
return new Iterable<ITree>() {
@Override
public Iterator<ITree> iterator() {
return TreeUtils.preOrderIterator(AbstractTree.this);
}
};
}
@Override
public Iterable<ITree> postOrder() {
return new Iterable<ITree>() {
@Override
public Iterator<ITree> iterator() {
return TreeUtils.postOrderIterator(AbstractTree.this);
}
};
}
@Override
public Iterable<ITree> breadthFirst() {
return new Iterable<ITree>() {
@Override
public Iterator<ITree> iterator() {
return TreeUtils.breadthFirstIterator(AbstractTree.this);
}
};
}
@Override
public int positionInParent() {
ITree p = getParent();
if (p == null)
return -1;
else
return p.getChildren().indexOf(this);
}
@Override
public void refresh() {
TreeUtils.computeSize(this);
TreeUtils.computeDepth(this);
TreeUtils.computeHeight(this);
HashUtils.DEFAULT_HASH_GENERATOR.hash(this);
}
@Override
public void setDepth(int depth) {
this.depth = depth;
}
@Override
public void setHash(int digest) {
this.hash = digest;
}
@Override
public void setHeight(int height) {
this.height = height;
}
@Override
public void setId(int id) {
this.id = id;
}
@Override
public void setSize(int size) {
this.size = size;
}
@Override
public void setLine(int line) {
this.line = line;
}
@Override
public void setColumn(int column) {
this.column = column;
}
@Override
public void setLastLine(int lastLine) {
this.lastLine = lastLine;
}
@Override
public void setLastColumn(int lastColumn) {
this.lastColumn = lastColumn;
}
@Override
public String toStaticHashString() {
StringBuilder b = new StringBuilder();
b.append(OPEN_SYMBOL);
b.append(this.toShortString());
for (ITree c: this.getChildren())
b.append(c.toStaticHashString());
b.append(CLOSE_SYMBOL);
return b.toString();
}
@Override
public String toString() {
System.err.println("This method should currently not be used (please use toShortString())");
return toShortString();
}
@Override
public String toShortString() {
return String.format("%d%s%s", getId(), SEPARATE_SYMBOL, getLabel());
}
@Override
public String toTreeString() {
StringBuilder b = new StringBuilder();
for (ITree t : TreeUtils.preOrder(this))
b.append(indent(t) + t.toShortString() + "\n");
return b.toString();
}
@Override
public String toPrettyString(TreeContext ctx) {
if (hasLabel())
return ctx.getTypeLabel(this) + ": " + getLabel();
else
return ctx.getTypeLabel(this);
}
public static class FakeTree extends AbstractTree {
public FakeTree(ITree... trees) {
children = new ArrayList<>(trees.length);
children.addAll(Arrays.asList(trees));
}
private RuntimeException unsupportedOperation() {
return new UnsupportedOperationException("This method should not be called on a fake tree");
}
@Override
public void addChild(ITree t) {
throw unsupportedOperation();
}
@Override
public void insertChild(ITree t, int position) {
throw unsupportedOperation();
}
@Override
public ITree deepCopy() {
throw unsupportedOperation();
}
@Override
public List<ITree> getChildren() {
return children;
}
@Override
public String getLabel() {
return NO_LABEL;
}
@Override
public int getLength() {
return getEndPos() - getPos();
}
@Override
public int getPos() {
return Collections.min(children, (t1, t2) -> t2.getPos() - t1.getPos()).getPos();
}
@Override
public int getLine() {
throw unsupportedOperation();
}
@Override
public int getColumn() {
throw unsupportedOperation();
}
@Override
public int getLastLine() {
throw unsupportedOperation();
}
@Override
public int getLastColumn() {
throw unsupportedOperation();
}
@Override
public int getEndPos() {
return Collections.max(children, (t1, t2) -> t2.getPos() - t1.getPos()).getEndPos();
}
@Override
public int getType() {
return -1;
}
@Override
public void setChildren(List<ITree> children) {
throw unsupportedOperation();
}
@Override
public void setLabel(String label) {
throw unsupportedOperation();
}
@Override
public void setLength(int length) {
throw unsupportedOperation();
}
@Override
public void setParentAndUpdateChildren(ITree parent) {
throw unsupportedOperation();
}
@Override
public void setPos(int pos) {
throw unsupportedOperation();
}
@Override
public void setType(int type) {
throw unsupportedOperation();
}
@Override
public String toPrettyString(TreeContext ctx) {
return "FakeTree";
}
/**
* fake nodes have no metadata
*/
@Override
public Object getMetadata(String key) {
return null;
}
/**
* fake node store no metadata
*/
@Override
public Object setMetadata(String key, Object value) {
return null;
}
/**
* Since they have no metadata they do not iterate on nothing
*/
@Override
public Iterator<Map.Entry<String, Object>> getMetadata() {
return new EmptyEntryIterator();
}
}
protected static class EmptyEntryIterator implements Iterator<Map.Entry<String, Object>> {
@Override
public boolean hasNext() {
return false;
}
@Override
public Map.Entry<String, Object> next() {
throw new NoSuchElementException();
}
}
}
| 10,686
| 22.591611
| 104
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/AssociationMap.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map.Entry;
public class AssociationMap {
// FIXME or not, should we inline this class ? or use Entry to only have one list ? ... or both
ArrayList<Object> values = new ArrayList<>();
ArrayList<String> keys = new ArrayList<>();
public Object get(String key) {
int idx = keys.indexOf(key);
if (idx == -1)
return null;
return values.get(idx);
}
/**
* set metadata `key` with `value` and returns the previous value
* This method won't remove if value == null
*/
public Object set(String key, Object value) {
int idx = keys.indexOf(key);
if (idx == -1) {
keys.add(key);
values.add(value);
return null;
}
return values.set(idx, value);
}
public Object remove(String key) {
int idx = keys.indexOf(key);
if (idx == -1)
return null;
if (idx == keys.size() - 1) {
keys.remove(idx);
return values.remove(idx);
}
keys.set(idx, keys.remove(keys.size() - 1));
return values.set(idx, values.remove(values.size() - 1));
}
public Iterator<Entry<String, Object>> iterator() {
return new Iterator<Entry<String, Object>>() {
int currentPos = 0;
@Override
public boolean hasNext() {
return currentPos < keys.size();
}
@Override
public Entry<String, Object> next() {
Entry<String, Object> e = new AbstractMap.SimpleEntry<>(keys.get(currentPos), values.get(currentPos));
currentPos++;
return e;
}
};
}
}
| 2,654
| 31.378049
| 118
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/ITree.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-R��my Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Flor��al Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
/**
* Interface to represent abstract syntax trees.
*/
public interface ITree {
String OPEN_SYMBOL = "[(";
String CLOSE_SYMBOL = ")]";
String SEPARATE_SYMBOL = "@@";
int NO_ID = Integer.MIN_VALUE;
String NO_LABEL = "";
int NO_VALUE = -1;
/**
* @see gumtreediff.tree.hash.HashGenerator
* @return a hash (probably unique) representing the tree
*/
int getHash();
void setHash(int hash);
/**
* @return all the nodes contained in the tree, using a pre-order.
*/
List<ITree> getTrees();
Iterable<ITree> preOrder();
Iterable<ITree> postOrder();
Iterable<ITree> breadthFirst();
/**
* Add the given tree as a child, and update its parent.
*/
void addChild(ITree t);
/**
* Insert the given tree as the position-th child, and update its parent.
*/
void insertChild(ITree t, int position);
void setChildren(List<ITree> children);
/**
* @return the position of the child, or -1 if the given child is not in the children list.
*/
int getChildPosition(ITree child);
/**
* @param position the child position, starting at 0
*/
ITree getChild(int position);
List<ITree> getChildren();
/**
* @return a boolean indicating if the tree has at least one child or not
*/
boolean isLeaf();
/**
* @return all the descendants (children, children of children, etc.) of the tree,
* using a pre-order.
*/
List<ITree> getDescendants();
/**
* Set the parent of this node. The parent won't have this node in its
* children list
*/
void setParent(ITree parent);
/**
* Set the parent of this node. The parent will have this node in its
* children list, at the last position
*/
void setParentAndUpdateChildren(ITree parent);
/**
* @return a boolean indicating if the tree has a parent or not
*/
boolean isRoot();
ITree getParent();
/**
* @return the list of all parents of the node (parent, parent of parent, etc.)
*/
List<ITree> getParents();
/**
* @return the position of the node in its parent children list
*/
int positionInParent();
/**
* Make a deep copy of the tree.
* Deep copy of node however shares Metadata
* @return a deep copy of the tree.
*/
ITree deepCopy();
/**
* @see TreeUtils#computeDepth(ITree)
* @return the depth of the tree, defined as the distance to the root
*/
int getDepth();
void setDepth(int depth);
/**
* @see TreeUtils#computeHeight(ITree)
* @return the height of the tree, defined as the maximal depth of its descendants.
*/
int getHeight();
void setHeight(int height);
/**
* @see TreeUtils#numbering(Iterable)
* @see TreeUtils#preOrderNumbering(ITree)
* @see TreeUtils#postOrderNumbering(ITree)
* @see TreeUtils#breadthFirstNumbering(ITree)
* @return the number of the node
*/
int getId();
void setId(int id);
boolean hasLabel();
String getLabel();
void setLabel(String label);
int getPos();
void setPos(int pos);
/**
* @return the line number of the node (0 if not exists in source code).
*/
int getLine();
void setLine(int line);
/**
* @return the last line number of the node (0 if not exists in source code).
*/
int getLastLine();
void setLastLine(int lastLine);
/**
* @return the last column number of the node (0 if not exists in source code).
*/
int getLastColumn();
/**
* @return the column number of the node (0 if not exists in source code).
*/
void setLastColumn(int lastColumn);
int getColumn();
void setColumn(int column);
int getLength();
void setLength(int length);
/**
* @return the absolute character index where the tree ends
*/
default int getEndPos() {
return getPos() + getLength();
}
/**
* @see TreeUtils#computeSize(ITree)
* @return the number of all nodes contained in the tree
*/
int getSize();
void setSize(int size);
int getType();
void setType(int type);
/**
* @return a boolean indicating if the trees have the same type.
*/
boolean hasSameType(ITree t);
/**
* @see #toStaticHashString()
* @see #getHash()
* @return a boolean indicating if the two trees are isomorphics, defined has
* having the same hash and the same hash serialization.
*/
boolean isIsomorphicTo(ITree tree);
/**
* Indicate whether or not the tree is similar to the given tree.
* @return true if they are compatible and have same label, false either
*/
boolean hasSameTypeAndLabel(ITree t);
/**
* Refresh hash, size, depth and height of the tree.
* @see gumtreediff.tree.hash.HashGenerator
* @see TreeUtils#computeDepth(ITree)
* @see TreeUtils#computeHeight(ITree)
* @see TreeUtils#computeSize(ITree)
*/
void refresh();
String toStaticHashString();
String toShortString();
String toTreeString();
String toPrettyString(TreeContext ctx);
Object getMetadata(String key);
Object setMetadata(String key, Object value);
Iterator<Entry<String, Object>> getMetadata();
}
| 6,316
| 22.92803
| 95
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/IterableEnumeration.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import java.util.Enumeration;
import java.util.Iterator;
public abstract class IterableEnumeration<T> implements Iterable<T> {
public static <T> Iterable<T> make(Enumeration<T> en) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return en.hasMoreElements();
}
@Override
public T next() {
return en.nextElement();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
| 1,691
| 31.538462
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/Tree.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
public class Tree extends AbstractTree implements ITree {
private int type;
private String label;
// Begin position of the tree in terms of absolute character index and length
private int pos;
private int length;
// End position
private int line;
private int column;
private int lastLine;
private int lastColumn;
private AssociationMap metadata;
/**
* Constructs a new node. If you need type labels corresponding to the integer
* @see TreeContext#createTree(int, String, String)
*/
public Tree(int type, String label) {
this.type = type;
this.label = (label == null) ? NO_LABEL : label.intern();
this.id = NO_ID;
this.depth = NO_VALUE;
this.hash = NO_VALUE;
this.height = NO_VALUE;
this.depth = NO_VALUE;
this.size = NO_VALUE;
this.pos = NO_VALUE;
this.length = NO_VALUE;
this.children = new ArrayList<>();
}
// Only used for cloning ...
private Tree(Tree other) {
this.type = other.type;
this.label = other.getLabel();
this.id = other.getId();
this.pos = other.getPos();
this.length = other.getLength();
this.height = other.getHeight();
this.size = other.getSize();
this.depth = other.getDepth();
this.hash = other.getHash();
this.depth = other.getDepth();
this.children = new ArrayList<>();
this.metadata = other.metadata;
}
@Override
public void addChild(ITree t) {
children.add(t);
t.setParent(this);
}
@Override
public void insertChild(ITree t, int position) {
children.add(position, t);
t.setParent(this);
}
@Override
public Tree deepCopy() {
Tree copy = new Tree(this);
for (ITree child : getChildren())
copy.addChild(child.deepCopy());
return copy;
}
@Override
public List<ITree> getChildren() {
return children;
}
@Override
public String getLabel() {
return label;
}
@Override
public int getLength() {
return length;
}
@Override
public ITree getParent() {
return parent;
}
@Override
public int getPos() {
return pos;
}
@Override
public int getType() {
return type;
}
@Override
public void setChildren(List<ITree> children) {
this.children = children;
for (ITree c : children)
c.setParent(this);
}
@Override
public void setLabel(String label) {
this.label = label;
}
@Override
public void setLength(int length) {
this.length = length;
}
@Override
public void setParent(ITree parent) {
this.parent = parent;
}
@Override
public void setParentAndUpdateChildren(ITree parent) {
if (this.parent != null)
this.parent.getChildren().remove(this);
this.parent = parent;
if (this.parent != null)
parent.getChildren().add(this);
}
@Override
public void setPos(int pos) {
this.pos = pos;
}
@Override
public void setLine(int line) {
this.line = line;
}
@Override
public void setColumn(int column) {
this.column = column;
}
@Override
public void setLastLine(int lastLine) {
this.lastLine = lastLine;
}
@Override
public void setLastColumn(int lastColumn) {
this.lastColumn = lastColumn;
}
@Override
public void setType(int type) {
this.type = type;
}
@Override
public Object getMetadata(String key) {
if (metadata == null)
return null;
return metadata.get(key);
}
@Override
public Object setMetadata(String key, Object value) {
if (value == null) {
if (metadata == null)
return null;
else
return metadata.remove(key);
}
if (metadata == null)
metadata = new AssociationMap();
return metadata.set(key, value);
}
@Override
public Iterator<Entry<String, Object>> getMetadata() {
if (metadata == null)
return new EmptyEntryIterator();
return metadata.iterator();
}
@Override
public int getLine() {
// TODO Auto-generated method stub
return line;
}
@Override
public int getColumn() {
// TODO Auto-generated method stub
return column;
}
@Override
public int getLastLine() {
// TODO Auto-generated method stub
return lastLine;
}
@Override
public int getLastColumn() {
// TODO Auto-generated method stub
return lastColumn;
}
}
| 5,694
| 22.533058
| 82
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/TreeContext.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import gumtreediff.io.TreeIoUtils;
import gumtreediff.io.TreeIoUtils.MetadataSerializer;
import gumtreediff.io.TreeIoUtils.MetadataUnserializer;
import gumtreediff.io.TreeIoUtils.TreeFormatter;
public class TreeContext{
private Map<Integer, String> typeLabels = new HashMap<>();
private final Map<String, Object> metadata = new HashMap<>();
private final MetadataSerializers serializers = new MetadataSerializers();
private ITree root;
private int size = 0;
@Override
public String toString() {
return TreeIoUtils.toLisp(this).toString();
}
public void setRoot(ITree root) {
this.root = root;
}
public ITree getRoot() {
return root;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getTypeLabel(ITree tree) {
return getTypeLabel(tree.getType());
}
public String getTypeLabel(int type) {
String tl = typeLabels.get(type);
if (tl == null)
tl = Integer.toString(type);
return tl;
}
public void registerTypeLabel(int type, String name) {
if (name == null || name.equals(ITree.NO_LABEL))
return;
String typeLabel = typeLabels.get(type);
if (typeLabel == null)
typeLabels.put(type, name);
else if (!typeLabel.equals(name))
throw new RuntimeException(String.format("Redefining type %d: '%s' with '%s'", type, typeLabel, name));
}
public void importTypeLabels(TreeContext ctx) {
for (Map.Entry<Integer, String> label : ctx.typeLabels.entrySet()) {
if (!typeLabels.containsValue(label.getValue())) {
typeLabels.put(label.getKey(), label.getValue());
}
}
}
public ITree createTree(int type, String label, String typeLabel) {
registerTypeLabel(type, typeLabel);
return new Tree(type, label);
}
public ITree createTree(ITree... trees) {
return new AbstractTree.FakeTree(trees);
}
public void validate() {
root.refresh();
TreeUtils.postOrderNumbering(root);
}
public boolean hasLabelFor(int type) {
return typeLabels.containsKey(type);
}
/**
* Get a global metadata.
* There is no way to know if the metadata is really null or does not exists.
*
* @param key of metadata
* @return the metadata or null if not found
*/
public Object getMetadata(String key) {
return metadata.get(key);
}
/**
* Get a local metadata, if available. Otherwise get a global metadata.
* There is no way to know if the metadata is really null or does not exists.
*
* @param key of metadata
* @return the metadata or null if not found
*/
public Object getMetadata(ITree node, String key) {
Object metadata;
if (node == null || (metadata = node.getMetadata(key)) == null)
return getMetadata(key);
return metadata;
}
/**
* Store a global metadata.
*
* @param key of the metadata
* @param value of the metadata
* @return the previous value of metadata if existed or null
*/
public Object setMetadata(String key, Object value) {
return metadata.put(key, value);
}
/**
* Store a local metadata
*
* @param key of the metadata
* @param value of the metadata
* @return the previous value of metadata if existed or null
*/
public Object setMetadata(ITree node, String key, Object value) {
if (node == null)
return setMetadata(key, value);
else {
Object res = node.setMetadata(key, value);
if (res == null)
return getMetadata(key);
return res;
}
}
/**
* Get an iterator on global metadata only
*/
public Iterator<Entry<String, Object>> getMetadata() {
return metadata.entrySet().iterator();
}
/**
* Get serializers for this tree context
*/
public MetadataSerializers getSerializers() {
return serializers;
}
public TreeContext export(MetadataSerializers s) {
serializers.addAll(s);
return this;
}
public TreeContext export(String key, MetadataSerializer s) {
serializers.add(key, s);
return this;
}
public TreeContext export(String... name) {
for (String n : name)
serializers.add(n, x -> x.toString());
return this;
}
public TreeContext deriveTree() { // FIXME Should we refactor TreeContext class to allow shared metadata etc ...
TreeContext newContext = new TreeContext();
newContext.setRoot(getRoot().deepCopy());
newContext.typeLabels = typeLabels;
newContext.metadata.putAll(metadata);
newContext.serializers.addAll(serializers);
return newContext;
}
/**
* Get an iterator on local and global metadata.
* To only get local metadata, simply use : `node.getMetadata()`
*/
public Iterator<Entry<String, Object>> getMetadata(ITree node) {
if (node == null)
return getMetadata();
return new Iterator<Entry<String, Object>>() {
final Iterator<Entry<String, Object>> localIterator = node.getMetadata();
final Iterator<Entry<String, Object>> globalIterator = getMetadata();
final Set<String> seenKeys = new HashSet<>();
Iterator<Entry<String, Object>> currentIterator = localIterator;
Entry<String, Object> nextEntry;
{
next();
}
@Override
public boolean hasNext() {
return nextEntry != null;
}
@Override
public Entry<String, Object> next() {
Entry<String, Object> n = nextEntry;
if (currentIterator == localIterator) {
if (localIterator.hasNext()) {
nextEntry = localIterator.next();
seenKeys.add(nextEntry.getKey());
return n;
} else {
currentIterator = globalIterator;
}
}
nextEntry = null;
while (globalIterator.hasNext()) {
Entry<String, Object> e = globalIterator.next();
if (!(seenKeys.contains(e.getKey()) || (e.getValue() == null))) {
nextEntry = e;
seenKeys.add(nextEntry.getKey());
break;
}
}
return n;
}
};
}
public static class Marshallers<E> {
Map<String, E> serializers = new HashMap<>();
public static final Pattern valid_id = Pattern.compile("[a-zA-Z0-9_]*");
public void addAll(Marshallers<E> other) {
addAll(other.serializers);
}
public void addAll(Map<String, E> serializers) {
serializers.forEach((k, s) -> add(k, s));
}
public void add(String name, E serializer) {
if (!valid_id.matcher(name).matches()) // TODO I definitely don't like this rule, we should think twice
throw new RuntimeException("Invalid key for serialization");
serializers.put(name, serializer);
}
public void remove(String key) {
serializers.remove(key);
}
public Set<String> exports() {
return serializers.keySet();
}
}
public static class MetadataSerializers extends Marshallers<MetadataSerializer> {
public void serialize(TreeFormatter formatter, String key, Object value) throws Exception {
MetadataSerializer s = serializers.get(key);
if (s != null)
formatter.serializeAttribute(key, s.toString(value));
}
}
public static class MetadataUnserializers extends Marshallers<MetadataUnserializer> {
public void load(ITree tree, String key, String value) throws Exception {
MetadataUnserializer s = serializers.get(key);
if (s != null) {
if (key.equals("pos"))
tree.setPos(Integer.parseInt(value));
else if (key.equals("length"))
tree.setLength(Integer.parseInt(value));
else
tree.setMetadata(key, s.fromString(value));
}
}
}
}
| 9,661
| 30.067524
| 116
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/TreeMap.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
public final class TreeMap {
private TIntObjectMap<ITree> trees;
public TreeMap(ITree tree) {
this();
putTrees(tree);
}
public TreeMap() {
trees = new TIntObjectHashMap<>();
}
public ITree getTree(int id) {
return trees.get(id);
}
public boolean contains(ITree tree) {
return contains(tree.getId());
}
public boolean contains(int id) {
return trees.containsKey(id);
}
public void putTrees(ITree tree) {
for (ITree t: tree.getTrees())
trees.put(t.getId(), t);
}
public void putTree(ITree t) {
trees.put(t.getId(), t);
}
}
| 1,598
| 25.65
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/TreeUtils.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import gumtreediff.utils.Pair;
public final class TreeUtils {
private TreeUtils() {
}
/**
* Compute the depth of every node of the tree. The size is set
* directly on the nodes and is then accessible using {@link Tree#getSize()}.
* @param tree a Tree
*/
public static void computeSize(ITree tree) {
for (ITree t: tree.postOrder()) {
int size = 1;
if (!t.isLeaf())
for (ITree c: t.getChildren())
size += c.getSize();
t.setSize(size);
}
}
/**
* Compute the depth of every node of the tree. The depth is set
* directly on the nodes and is then accessible using {@link Tree#getDepth()}.
* @param tree a Tree
*/
public static void computeDepth(ITree tree) {
List<ITree> trees = preOrder(tree);
for (ITree t: trees) {
int depth = 0;
if (!t.isRoot()) depth = t.getParent().getDepth() + 1;
t.setDepth(depth);
}
}
/**
* Compute the height of every node of the tree. The height is set
* directly on the nodes and is then accessible using {@link Tree#getHeight()}.
* @param tree a Tree.
*/
public static void computeHeight(ITree tree) {
for (ITree t: tree.postOrder()) {
int height = 0;
if (!t.isLeaf()) {
for (ITree c: t.getChildren()) {
int cHeight = c.getHeight();
if (cHeight > height) height = cHeight;
}
height++;
}
t.setHeight(height);
}
}
/**
* Returns a list of every subtrees and the tree ordered using a pre-order.
* @param tree a Tree.
*/
public static List<ITree> preOrder(ITree tree) {
List<ITree> trees = new ArrayList<>();
preOrder(tree, trees);
return trees;
}
private static void preOrder(ITree tree, List<ITree> trees) {
trees.add(tree);
if (!tree.isLeaf())
for (ITree c: tree.getChildren())
preOrder(c, trees);
}
public static void preOrderNumbering(ITree tree) {
numbering(tree.preOrder());
}
/**
* Returns a list of every subtrees and the tree ordered using a breadth-first order.
* @param tree a Tree.
*/
public static List<ITree> breadthFirst(ITree tree) {
List<ITree> trees = new ArrayList<>();
List<ITree> currents = new ArrayList<>();
currents.add(tree);
while (currents.size() > 0) {
ITree c = currents.remove(0);
trees.add(c);
currents.addAll(c.getChildren());
}
return trees;
}
public static Iterator<ITree> breadthFirstIterator(final ITree tree) {
return new Iterator<ITree>() {
Deque<Iterator<ITree>> fifo = new ArrayDeque<>();
{
addLasts(new AbstractTree.FakeTree(tree));
}
@Override
public boolean hasNext() {
return !fifo.isEmpty();
}
@Override
public ITree next() {
while (!fifo.isEmpty()) {
Iterator<ITree> it = fifo.getFirst();
if (it.hasNext()) {
ITree item = it.next();
if (!it.hasNext())
fifo.removeFirst();
addLasts(item);
return item;
}
}
throw new NoSuchElementException();
}
private void addLasts(ITree item) {
List<ITree> children = item.getChildren();
if (!children.isEmpty())
fifo.addLast(children.iterator());
}
@Override
public void remove() {
throw new RuntimeException("Not yet implemented implemented.");
}
};
}
public static void breadthFirstNumbering(ITree tree) {
numbering(tree.breadthFirst());
}
public static void numbering(Iterable<ITree> iterable) {
int i = 0;
for (ITree t: iterable)
t.setId(i++);
}
/**
* Returns a list of every subtrees and the tree ordered using a post-order.
* @param tree a Tree.
*/
public static List<ITree> postOrder(ITree tree) {
List<ITree> trees = new ArrayList<>();
postOrder(tree, trees);
return trees;
}
private static void postOrder(ITree tree, List<ITree> trees) {
if (!tree.isLeaf())
for (ITree c: tree.getChildren())
postOrder(c, trees);
trees.add(tree);
}
public static Iterator<ITree> postOrderIterator(final ITree tree) {
return new Iterator<ITree>() {
Deque<Pair<ITree, Iterator<ITree>>> stack = new ArrayDeque<>();
{
push(tree);
}
@Override
public boolean hasNext() {
return stack.size() > 0;
}
@Override
public ITree next() {
if (stack.isEmpty())
throw new NoSuchElementException();
return selectNextChild(stack.peek().getSecond());
}
ITree selectNextChild(Iterator<ITree> it) {
if (!it.hasNext())
return stack.pop().getFirst();
ITree item = it.next();
if (item.isLeaf())
return item;
return selectNextChild(push(item));
}
private Iterator<ITree> push(ITree item) {
Iterator<ITree> it = item.getChildren().iterator();
stack.push(new Pair<>(item, it));
return it;
}
@Override
public void remove() {
throw new RuntimeException("Not yet implemented implemented.");
}
};
}
public static void visitTree(ITree root, TreeVisitor visitor) {
Deque<Pair<ITree, Iterator<ITree>>> stack = new ArrayDeque<>();
stack.push(new Pair<>(root, root.getChildren().iterator()));
visitor.startTree(root);
while (!stack.isEmpty()) {
Pair<ITree, Iterator<ITree>> it = stack.peek();
if (!it.second.hasNext()) {
visitor.endTree(it.first);
stack.pop();
} else {
ITree child = it.second.next();
stack.push(new Pair<>(child, child.getChildren().iterator()));
visitor.startTree(child);
}
}
}
public interface TreeVisitor {
void startTree(ITree tree);
void endTree(ITree tree);
}
public static Iterator<ITree> preOrderIterator(ITree tree) {
return new Iterator<ITree>() {
Deque<Iterator<ITree>> stack = new ArrayDeque<>();
{
push(new AbstractTree.FakeTree(tree));
}
@Override
public boolean hasNext() {
return stack.size() > 0;
}
@Override
public ITree next() {
Iterator<ITree> it = stack.peek();
if (it == null)
throw new NoSuchElementException();
ITree t = it.next();
while (it != null && !it.hasNext()) {
stack.pop();
it = stack.peek();
}
push(t);
return t;
}
private void push(ITree tree) {
if (!tree.isLeaf())
stack.push(tree.getChildren().iterator());
}
@Override
public void remove() {
throw new RuntimeException("Not yet implemented implemented.");
}
};
}
public static Iterator<ITree> leafIterator(final Iterator<ITree> it) {
return new Iterator<ITree>() {
ITree current = it.hasNext() ? it.next() : null;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public ITree next() {
ITree val = current;
while (it.hasNext()) {
current = it.next();
if (current.isLeaf())
break;
}
if (!it.hasNext()) {
current = null;
}
return val;
}
@Override
public void remove() {
throw new RuntimeException("Not yet implemented implemented.");
}
};
}
public static void postOrderNumbering(ITree tree) {
numbering(tree.postOrder());
}
}
| 9,971
| 29.588957
| 89
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/hash/HashGenerator.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree.hash;
import gumtreediff.tree.ITree;
public interface HashGenerator {
public void hash(ITree t);
}
| 956
| 30.9
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/hash/HashUtils.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree.hash;
import java.security.MessageDigest;
import gumtreediff.tree.ITree;
public class HashUtils {
private HashUtils() {}
public static final int BASE = 33;
public static final HashGenerator DEFAULT_HASH_GENERATOR = new RollingHashGenerator.Md5RollingHashGenerator();
public static int byteArrayToInt(byte[] b) {
return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24;
}
public static int standardHash(ITree t) {
return Integer.hashCode(t.getType()) + HashUtils.BASE * t.getLabel().hashCode();
}
public static String inSeed(ITree t) {
return ITree.OPEN_SYMBOL + t.getLabel() + ITree.SEPARATE_SYMBOL + t.getType();
}
public static String outSeed(ITree t) {
return t.getType() + ITree.SEPARATE_SYMBOL + t.getLabel() + ITree.CLOSE_SYMBOL;
}
public static int md5(String s) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(s.getBytes("UTF-8"));
return byteArrayToInt(digest);
} catch (Exception e) {
e.printStackTrace();
}
return ITree.NO_VALUE;
}
public static int fpow(int a, int b) {
if (b == 1)
return a;
int result = 1;
while (b > 0) {
if ((b & 1) != 0)
result *= a;
b >>= 1;
a *= a;
}
return result;
}
}
| 2,313
| 29.447368
| 114
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/hash/RollingHashGenerator.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree.hash;
import static gumtreediff.tree.hash.HashUtils.BASE;
import static gumtreediff.tree.hash.HashUtils.fpow;
import static gumtreediff.tree.hash.HashUtils.md5;
import java.util.HashMap;
import java.util.Map;
import gumtreediff.tree.ITree;
public abstract class RollingHashGenerator implements HashGenerator {
@Override
public void hash(ITree t) {
for (ITree n: t.postOrder())
if (n.isLeaf())
n.setHash(leafHash(n));
else
n.setHash(innerNodeHash(n));
}
public abstract int hashFunction(String s);
public int leafHash(ITree t) {
return BASE * hashFunction(HashUtils.inSeed(t)) + hashFunction(HashUtils.outSeed(t));
}
public int innerNodeHash(ITree t) {
int size = t.getSize() * 2 - 1;
int hash = hashFunction(HashUtils.inSeed(t)) * fpow(BASE, size);
for (ITree c: t.getChildren()) {
size = size - c.getSize() * 2;
hash += c.getHash() * fpow(BASE, size);
}
hash += hashFunction(HashUtils.outSeed(t));
return hash;
}
public static class JavaRollingHashGenerator extends RollingHashGenerator {
@Override
public int hashFunction(String s) {
return s.hashCode();
}
}
public static class Md5RollingHashGenerator extends RollingHashGenerator {
@Override
public int hashFunction(String s) {
return md5(s);
}
}
public static class RandomRollingHashGenerator extends RollingHashGenerator {
private static final Map<String, Integer> digests = new HashMap<>();
@Override
public int hashFunction(String s) {
return rdmHash(s);
}
public static int rdmHash(String s) {
if (!digests.containsKey(s)) {
int digest = (int) (Math.random() * (Integer.MAX_VALUE - 1));
digests.put(s, digest);
return digest;
} else return digests.get(s);
}
}
}
| 2,896
| 27.97
| 93
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/tree/hash/StaticHashGenerator.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.tree.hash;
import gumtreediff.tree.ITree;
public abstract class StaticHashGenerator implements HashGenerator {
@Override
public void hash(ITree t) {
for (ITree n: t.postOrder())
n.setHash(nodeHash(n));
}
public abstract int nodeHash(ITree t);
public static class StdHashGenerator extends StaticHashGenerator {
@Override
public int nodeHash(ITree t) {
return t.toStaticHashString().hashCode();
}
}
public static class Md5HashGenerator extends StaticHashGenerator {
@Override
public int nodeHash(ITree t) {
return HashUtils.md5(t.toStaticHashString());
}
}
}
| 1,536
| 27.462963
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/utils/HungarianAlgorithm.java
|
/* Copyright (c) 2012 Kevin L. Stern
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gumtreediff.utils;
import java.util.Arrays;
/**
* An implementation of the Hungarian algorithm for solving the assignment
* problem. An instance of the assignment problem consists of a number of
* workers along with a number of jobs and a cost matrix which gives the cost of
* assigning the i'th worker to the j'th job at position (i, j). The goal is to
* find an assignment of workers to jobs so that no job is assigned more than
* one worker and so that no worker is assigned to more than one job in such a
* manner so as to minimize the total cost of completing the jobs.
* An assignment for a cost matrix that has more workers than jobs will
* necessarily include unassigned workers, indicated by an assignment value of
* -1; in no other circumstance will there be unassigned workers. Similarly, an
* assignment for a cost matrix that has more jobs than workers will necessarily
* include unassigned jobs; in no other circumstance will there be unassigned
* jobs. For completeness, an assignment for a square cost matrix will give
* exactly one unique worker to each job.
* This version of the Hungarian algorithm runs in time O(n^3), where n is the
* maximum among the number of workers and the number of jobs.
*
* @author Kevin L. Stern
*/
public class HungarianAlgorithm {
private final double[][] costMatrix;
private final int rows;
private final int cols;
private final int dim;
private final double[] labelByWorker;
private final double[] labelByJob;
private final int[] minSlackWorkerByJob;
private final double[] minSlackValueByJob;
private final int[] matchJobByWorker;
private final int[] matchWorkerByJob;
private final int[] parentWorkerByCommittedJob;
private final boolean[] committedWorkers;
/**
* Construct an instance of the algorithm.
*
* @param costMatrix
* the cost matrix, where matrix[i][j] holds the cost of
* assigning worker i to job j, for all i, j. The cost matrix
* must not be irregular in the sense that all rows must be the
* same length.
*/
public HungarianAlgorithm(double[][] costMatrix) {
this.dim = Math.max(costMatrix.length, costMatrix[0].length);
this.rows = costMatrix.length;
this.cols = costMatrix[0].length;
this.costMatrix = new double[this.dim][this.dim];
for (int w = 0; w < this.dim; w++) {
if (w < costMatrix.length) {
if (costMatrix[w].length != this.cols) {
throw new IllegalArgumentException("Irregular cost matrix");
}
this.costMatrix[w] = Arrays.copyOf(costMatrix[w], this.dim);
} else {
this.costMatrix[w] = new double[this.dim];
}
}
labelByWorker = new double[this.dim];
labelByJob = new double[this.dim];
minSlackWorkerByJob = new int[this.dim];
minSlackValueByJob = new double[this.dim];
committedWorkers = new boolean[this.dim];
parentWorkerByCommittedJob = new int[this.dim];
matchJobByWorker = new int[this.dim];
Arrays.fill(matchJobByWorker, -1);
matchWorkerByJob = new int[this.dim];
Arrays.fill(matchWorkerByJob, -1);
}
/**
* Compute an initial feasible solution by assigning zero labels to the
* workers and by assigning to each job a label equal to the minimum cost
* among its incident edges.
*/
protected void computeInitialFeasibleSolution() {
for (int j = 0; j < dim; j++) {
labelByJob[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < labelByJob[j]) {
labelByJob[j] = costMatrix[w][j];
}
}
}
}
/**
* Execute the algorithm.
*
* @return the minimum cost matching of workers to jobs based upon the
* provided cost matrix. A matching value of -1 indicates that the
* corresponding worker is unassigned.
*/
public int[] execute() {
/*
* Heuristics to improve performance: Reduce rows and columns by their
* smallest element, compute an initial non-zero dual feasible solution
* and create a greedy matching from workers to jobs of the cost matrix.
*/
reduce();
computeInitialFeasibleSolution();
greedyMatch();
int w = fetchUnmatchedWorker();
while (w < dim) {
initializePhase(w);
executePhase();
w = fetchUnmatchedWorker();
}
int[] result = Arrays.copyOf(matchJobByWorker, rows);
for (w = 0; w < result.length; w++) {
if (result[w] >= cols) {
result[w] = -1;
}
}
return result;
}
/**
* Execute a single phase of the algorithm. A phase of the Hungarian
* algorithm consists of building a set of committed workers and a set of
* committed jobs from a root unmatched worker by following alternating
* unmatched/matched zero-slack edges. If an unmatched job is encountered,
* then an augmenting path has been found and the matching is grown. If the
* connected zero-slack edges have been exhausted, the labels of committed
* workers are increased by the minimum slack among committed workers and
* non-committed jobs to create more zero-slack edges (the labels of
* committed jobs are simultaneously decreased by the same amount in order
* to maintain a feasible labeling).
* The runtime of a single phase of the algorithm is O(n^2), where n is the
* dimension of the internal square cost matrix, since each edge is visited
* at most once and since increasing the labeling is accomplished in time
* O(n) by maintaining the minimum slack values among non-committed jobs.
* When a phase completes, the matching will have increased in size.
*/
protected void executePhase() {
while (true) {
int minSlackWorker = -1, minSlackJob = -1;
double minSlackValue = Double.POSITIVE_INFINITY;
for (int j = 0; j < dim; j++) {
if (parentWorkerByCommittedJob[j] == -1) {
if (minSlackValueByJob[j] < minSlackValue) {
minSlackValue = minSlackValueByJob[j];
minSlackWorker = minSlackWorkerByJob[j];
minSlackJob = j;
}
}
}
if (minSlackValue > 0) {
updateLabeling(minSlackValue);
}
parentWorkerByCommittedJob[minSlackJob] = minSlackWorker;
if (matchWorkerByJob[minSlackJob] == -1) {
int committedJob = minSlackJob;
int parentWorker = parentWorkerByCommittedJob[committedJob];
while (true) {
int temp = matchJobByWorker[parentWorker];
match(parentWorker, committedJob);
committedJob = temp;
if (committedJob == -1) {
break;
}
parentWorker = parentWorkerByCommittedJob[committedJob];
}
return;
} else {
int worker = matchWorkerByJob[minSlackJob];
committedWorkers[worker] = true;
for (int j = 0; j < dim; j++) {
if (parentWorkerByCommittedJob[j] == -1) {
double slack = costMatrix[worker][j]
- labelByWorker[worker] - labelByJob[j];
if (minSlackValueByJob[j] > slack) {
minSlackValueByJob[j] = slack;
minSlackWorkerByJob[j] = worker;
}
}
}
}
}
}
/*
* @return the first unmatched worker or {@link #dim} if none.
*/
protected int fetchUnmatchedWorker() {
int w;
for (w = 0; w < dim; w++) {
if (matchJobByWorker[w] == -1) {
break;
}
}
return w;
}
/**
* Find a valid matching by greedily selecting among zero-cost matchings.
* This is a heuristic to jump-start the augmentation algorithm.
*/
protected void greedyMatch() {
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (matchJobByWorker[w] == -1
&& matchWorkerByJob[j] == -1
&& costMatrix[w][j] - labelByWorker[w] - labelByJob[j] == 0) {
match(w, j);
}
}
}
}
/**
* Initialize the next phase of the algorithm by clearing the committed
* workers and jobs sets and by initializing the slack arrays to the values
* corresponding to the specified root worker.
*
* @param w
* the worker at which to root the next phase.
*/
protected void initializePhase(int w) {
Arrays.fill(committedWorkers, false);
Arrays.fill(parentWorkerByCommittedJob, -1);
committedWorkers[w] = true;
for (int j = 0; j < dim; j++) {
minSlackValueByJob[j] = costMatrix[w][j] - labelByWorker[w]
- labelByJob[j];
minSlackWorkerByJob[j] = w;
}
}
/**
* Helper method to record a matching between worker w and job j.
*/
protected void match(int w, int j) {
matchJobByWorker[w] = j;
matchWorkerByJob[j] = w;
}
/**
* Reduce the cost matrix by subtracting the smallest element of each row
* from all elements of the row as well as the smallest element of each
* column from all elements of the column. Note that an optimal assignment
* for a reduced cost matrix is optimal for the original cost matrix.
*/
protected void reduce() {
for (int w = 0; w < dim; w++) {
double min = Double.POSITIVE_INFINITY;
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < min) {
min = costMatrix[w][j];
}
}
for (int j = 0; j < dim; j++) {
costMatrix[w][j] -= min;
}
}
double[] min = new double[dim];
for (int j = 0; j < dim; j++) {
min[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < min[j]) {
min[j] = costMatrix[w][j];
}
}
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
costMatrix[w][j] -= min[j];
}
}
}
/**
* Update labels with the specified slack by adding the slack value for
* committed workers and by subtracting the slack value for committed jobs.
* In addition, update the minimum slack values appropriately.
*/
protected void updateLabeling(double slack) {
for (int w = 0; w < dim; w++) {
if (committedWorkers[w]) {
labelByWorker[w] += slack;
}
}
for (int j = 0; j < dim; j++) {
if (parentWorkerByCommittedJob[j] != -1) {
labelByJob[j] -= slack;
} else {
minSlackValueByJob[j] -= slack;
}
}
}
}
| 12,833
| 38.733746
| 86
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/utils/Pair.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.utils;
public class Pair<T1, T2> {
public final T1 first;
public final T2 second;
public Pair(T1 a, T2 b) {
this.first = a;
this.second = b;
}
public T1 getFirst() {
return first;
}
public T2 getSecond() {
return second;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (!first.equals(pair.first)) return false;
return second.equals(pair.second);
}
@Override
public int hashCode() {
int result = first.hashCode();
result = 31 * result + second.hashCode();
return result;
}
@Override
public String toString() {
return "(" + getFirst().toString() + "," + getSecond().toString() + ")";
}
}
| 1,737
| 24.940299
| 80
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/gumtreediff/utils/StringAlgorithms.java
|
/*
* This file is part of GumTree.
*
* GumTree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GumTree is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com>
* Copyright 2011-2015 Floréal Morandat <florealm@gmail.com>
*/
package gumtreediff.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import gumtreediff.tree.ITree;
public final class StringAlgorithms {
private StringAlgorithms() {}
public static List<int[]> lcss(String s0, String s1) {
int[][] lengths = new int[s0.length() + 1][s1.length() + 1];
for (int i = 0; i < s0.length(); i++)
for (int j = 0; j < s1.length(); j++)
if (s0.charAt(i) == (s1.charAt(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
List<int[]> indexes = new ArrayList<>();
for (int x = s0.length(), y = s1.length(); x != 0 && y != 0; ) {
if (lengths[x][y] == lengths[x - 1][y]) x--;
else if (lengths[x][y] == lengths[x][y - 1]) y--;
else {
indexes.add(new int[] {x - 1, y - 1});
x--;
y--;
}
}
Collections.reverse(indexes);
return indexes;
}
public static List<int[]> hunks(String s0, String s1) {
List<int[]> lcs = lcss(s0 ,s1);
List<int[]> hunks = new ArrayList<>();
int inf0 = -1;
int inf1 = -1;
int last0 = -1;
int last1 = -1;
for (int i = 0; i < lcs.size(); i++) {
int[] match = lcs.get(i);
if (inf0 == -1 || inf1 == -1) {
inf0 = match[0];
inf1 = match[1];
} else if (last0 + 1 != match[0] || last1 + 1 != match[1]) {
hunks.add(new int[] {inf0, last0 + 1, inf1, last1 + 1});
inf0 = match[0];
inf1 = match[1];
} else if (i == lcs.size() - 1) {
hunks.add(new int[] {inf0, match[0] + 1, inf1, match[1] + 1});
break;
}
last0 = match[0];
last1 = match[1];
}
return hunks;
}
public static String lcs(String s1, String s2) {
int start = 0;
int max = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
int x = 0;
while (s1.charAt(i + x) == s2.charAt(j + x)) {
x++;
if (((i + x) >= s1.length()) || ((j + x) >= s2.length())) break;
}
if (x > max) {
max = x;
start = i;
}
}
}
return s1.substring(start, (start + max));
}
public static List<int[]> lcss(List<ITree> s0, List<ITree> s1) {
int[][] lengths = new int[s0.size() + 1][s1.size() + 1];
for (int i = 0; i < s0.size(); i++)
for (int j = 0; j < s1.size(); j++)
if (s0.get(i).hasSameTypeAndLabel(s1.get(j)))
lengths[i + 1][j + 1] = lengths[i][j] + 1;
else
lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]);
List<int[]> indexes = new ArrayList<>();
for (int x = s0.size(), y = s1.size(); x != 0 && y != 0; ) {
if (lengths[x][y] == lengths[x - 1][y]) x--;
else if (lengths[x][y] == lengths[x][y - 1]) y--;
else {
indexes.add(new int[] {x - 1, y - 1});
x--;
y--;
}
}
Collections.reverse(indexes);
return indexes;
}
}
| 4,373
| 33.440945
| 91
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/main/MainProcess.java
|
package main;
import java.util.ArrayList;
import split.Split;
import structure.Migration;
public class MainProcess {
public static void main (String args[]) throws Exception{
Split sp = new Split();
String path = "migrations";
ArrayList<Migration> migrats = new ArrayList<>();
migrats = sp.readMigration(path, "talker");
sp.storeTrans(migrats);
String inputPath = "input.cpp";
sp.suggestion(inputPath);
System.out.println();
}
}
| 453
| 18.73913
| 58
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/nodecluster/ActionFormatter.java
|
package nodecluster;
import gumtreediff.tree.ITree;
public interface ActionFormatter {
void startOutput() throws Exception;
void endOutput() throws Exception;
void startMatches() throws Exception;
void match(ITree srcNode, ITree destNode) throws Exception;
void endMatches() throws Exception;
void startActions() throws Exception;
void insertRoot(ITree node) throws Exception;
void insertAction(ITree node, ITree parent, int index) throws Exception;
void moveAction(ITree src, ITree dst, int index) throws Exception;
void updateAction(ITree src, ITree dst) throws Exception;
void deleteAction(ITree node) throws Exception;
void endActions() throws Exception;
}
| 776
| 24.064516
| 80
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/nodecluster/Cluster.java
|
package nodecluster;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import gumtreediff.actions.model.Action;
import gumtreediff.actions.model.Delete;
import gumtreediff.actions.model.Insert;
import gumtreediff.actions.model.Move;
import gumtreediff.actions.model.Update;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import structure.Migration;
import utils.Utils;
public class Cluster {
private TreeContext tc1;
private TreeContext tc2;
private MappingStore mapping;
private HashMap<ITree, ITree> node2rootMap = new HashMap<>();//insert专用
private HashMap<ITree, ITree> parMap = new HashMap<>();//insert专用
private Boolean hasBuildMap = false;
public static void main (String args[]) throws Exception{
String path = "talker.cpp";
File cppfile = new File(path);
TreeContext tc1 = new SrcmlCppTreeGenerator().generateFromFile(cppfile);
String path2 = "talker2.cpp";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlCppTreeGenerator().generateFromFile(cppfile2);
Cluster cl = new Cluster(tc1, tc2);
cl.clusterActions(tc1, tc2);
}
public Cluster(TreeContext tC1, TreeContext tC2) {
this.tc1 = tC1;
this.tc2 = tC2;
Matcher m = Matchers.getInstance().getMatcher(tc1.getRoot(), tc2.getRoot());
m.match();
this.mapping = m.getMappings();
}
public Cluster(TreeContext tC1, TreeContext tC2, MappingStore mappings) {
this.tc1 = tC1;
this.tc2 = tC2;
this.mapping = mappings;
}
public ArrayList<String> extraceUPD(ArrayList<Migration> migrates) {
ArrayList<String> commonUPD = new ArrayList<>();
ArrayList<String> updStrings = new ArrayList<>();
for(Migration m : migrates) {
TreeContext tc1 = m.getSrcT();
TreeContext tc2 = m.getDstT();
HashMap<String, LinkedList<Action>> actions = Utils.collectAction(tc1, tc2, mapping);
LinkedList<Action> updates = actions.get("update");
for(Action a : updates) {
String src = tc1.getTypeLabel(a.getNode());
String dst = a.getName();
String updString = src+"->"+dst;
if(updStrings.contains(updString))
commonUPD.add(updString);
else
updStrings.add(updString);
}
}
return commonUPD;
}
public void clusterActions(TreeContext tC1, TreeContext tC2) throws Exception {
HashMap<String, LinkedList<Action>> actions = Utils.collectAction(tc1, tc2, mapping);
for(Mapping map : mapping) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
System.out.println("Mapping:"+src.getId()+"->"+dst.getId());
}
LinkedList<Action> updates = actions.get("update");
System.out.println("updsize:"+updates.size());
LinkedList<Action> deletes = actions.get("delete");
System.out.println("delsize:"+deletes.size());
LinkedList<Action> inserts = actions.get("insert");
System.out.println("addsize:"+inserts.size());
LinkedList<Action> moves = actions.get("move");
System.out.println("movsize:"+moves.size());
HashMap<Integer, ArrayList<Action>> uptParentIds = new HashMap<>();
HashMap<Integer, ArrayList<Action>> uptClusters = new HashMap<>();
HashMap<Integer, ArrayList<Action>> delParentIds = new HashMap<>();
HashMap<Integer, ArrayList<Action>> delClusters = new HashMap<>();
HashMap<Integer, ArrayList<Action>> addParentIds = new HashMap<>();
HashMap<Integer, ArrayList<Action>> addClusters = new HashMap<>();
HashMap<Integer, ArrayList<Action>> movParentIds = new HashMap<>();
HashMap<Integer, ArrayList<Action>> movClusters = new HashMap<>();
for(Action a : updates) {
System.out.println("-----findUptRoot-----");
ITree sRoot = traverseSRoot(a);
System.out.println("rootname:"+tc1.getTypeLabel(sRoot));
int id = sRoot.getId();
if(uptParentIds.get(id)==null) {
ArrayList<Action> acts = new ArrayList<>();
acts.add(a);
uptParentIds.put(id, acts);
}else {
ArrayList<Action> acts = uptParentIds.get(id);
acts.add(a);
uptClusters.put(id, acts);
}
}
for(Action a : deletes) {
System.out.println("-----findDelRoot-----");
ITree sRoot = traverseSRoot(a);
System.out.println("rootname:"+tc1.getTypeLabel(sRoot));
int id = sRoot.getId();
if(delParentIds.get(id)==null) {
ArrayList<Action> acts = new ArrayList<>();
acts.add(a);
delParentIds.put(id, acts);
}else {
ArrayList<Action> acts = delParentIds.get(id);
acts.add(a);
delClusters.put(id, acts);
}
}
for(Action a : inserts) {
System.out.println("-----findAddRoot-----");
ITree sRoot = traverseSRoot(a);
System.out.println("rootname:"+tc1.getTypeLabel(sRoot));
int id = sRoot.getId();
if(addParentIds.get(id)==null) {
ArrayList<Action> acts = new ArrayList<>();
acts.add(a);
addParentIds.put(id, acts);
}else {
ArrayList<Action> acts = addParentIds.get(id);
acts.add(a);
addClusters.put(id, acts);
}
}
for(Action a : moves) {
System.out.println("-----findMovRoot-----");
ITree sRoot = findMovRoot(a);
System.out.println("rootname:"+tc1.getTypeLabel(sRoot));
int id = sRoot.getId();
if(movParentIds.get(id)==null) {
ArrayList<Action> acts = new ArrayList<>();
acts.add(a);
movParentIds.put(id, acts);
}else {
ArrayList<Action> acts = movParentIds.get(id);
acts.add(a);
movClusters.put(id, acts);
}
}
System.out.println("=====UPDCluster====="+uptClusters.size());
for(Map.Entry<Integer, ArrayList<Action>> entry : uptClusters.entrySet()) {
ArrayList<Action> acts = entry.getValue();
ITree newRoot = downRoot(acts);
System.out.println("downRootname:"+tc1.getTypeLabel(newRoot));
printPath(newRoot);
}
System.out.println("=====DELCluster====="+delClusters.size());
for(Map.Entry<Integer, ArrayList<Action>> entry : delClusters.entrySet()) {
ArrayList<Action> acts = entry.getValue();
ITree newRoot = downRoot(acts);
System.out.println("downRootname:"+tc1.getTypeLabel(newRoot));
printPath(newRoot);
}
System.out.println("=====ADDCluster====="+addClusters.size());
for(Map.Entry<Integer, ArrayList<Action>> entry : addClusters.entrySet()) {
ArrayList<Action> acts = entry.getValue();
ITree newRoot = downRoot(acts);
System.out.println("downRootname:"+tc1.getTypeLabel(newRoot));
printPath(newRoot);
}
System.out.println("=====MOVCluster====="+movClusters.size());
for(Map.Entry<Integer, ArrayList<Action>> entry : movClusters.entrySet()) {
ArrayList<Action> acts = entry.getValue();
ITree newRoot = downRoot(acts);
System.out.println("downRootname:"+tc1.getTypeLabel(newRoot));
printPath(newRoot);
}
}//需要debug
public void printPath(ITree newRoot) {//打印从newRoot到SRoot
ITree SRoot = newRoot;
String typeLabel = tc1.getTypeLabel(newRoot);
String allPath = typeLabel;
while(!Utils.ifSRoot(typeLabel)) {//可能有问题,要注意循环条件
typeLabel = tc1.getTypeLabel(SRoot.getParent());
allPath = allPath+"<-"+typeLabel;
SRoot = SRoot.getParent();
}
System.out.println(allPath);
}
public void buildInsertMap(LinkedList<Action> inserts) throws Exception {
for(Action act : inserts) {//insert方法不涉及src节点,只在dst树中插入
if(!(act instanceof Insert))
throw new Exception("Action type error!");
ITree dst = act.getNode();
ITree par1 = null;
ITree par2 = dst.getParent();
ITree map_par2 = mapping.getSrc(par2);//the mapping node of par2 if exists
// if(par2.getId()==3134) {
// if(map_par2!=null)
// System.err.println("exist!"+map_par2.getId());
// else
// System.err.println("not exist!");
// }
if(map_par2!=null) {//说明直接连接在insert_root上且有对应的src_root
par1 = map_par2;
parMap.put(dst, par2);
node2rootMap.put(dst, par1);
}else {//说明连接在insert_par上,不是insert_root
if(parMap.get(dst)==null) {
parMap.put(dst, par2);//映射链全部放入map,指向insert_root
}else
throw new Exception("error exist parMap!");
}
}
for(Map.Entry<ITree, ITree> entry : parMap.entrySet()) {
ITree dst = entry.getKey();
ITree par = entry.getValue();
// System.out.println("Insert:"+dst.getId()+","+par.getId());
if(node2rootMap.get(dst)!=null) {
continue;
}else {//说明连接在insert_par上,不是insert_root
ITree map_par = parMap.get(par);
if(map_par==null)
throw new Exception("check the null error!"+dst.getId()+","+par.getId());
while(map_par!=null) {
par = map_par;
map_par = parMap.get(map_par);
}//par is insert_root
// System.out.println("mapped par:"+par.getId());
ITree mapped_insert_root = mapping.getSrc(par);
if(mapped_insert_root==null)
throw new Exception("check the null error!");
node2rootMap.put(dst, mapped_insert_root);
}
}
hasBuildMap = true;
}//insert方法有非常多节点连接的父亲节点属于dst树,需预先建立这些节点与src_root之间的map
public ITree findMovRoot(Action a) throws Exception {
if(!(a instanceof Move))
throw new Exception("action is not move!");
if(!hasBuildMap)
throw new Exception("InsertMap should be built firstly!");
ITree dst = ((Move)a).getParent();
if(node2rootMap.get(dst)==null) {
ITree sRoot = mapping.getDst(dst);
if(sRoot == null)
System.err.println("error id:"+dst.getId());
return sRoot;
}//发现另一种情况,move连接的节点不在insert结果中,直接从mapping中找
ITree sRoot = node2rootMap.get(dst);
//move连接的父亲是tc2中节点,直接从insert结果中找,必然因为insert插入到tc1中了
if(sRoot==null)
throw new Exception("sRoot is not exist!");
return sRoot;
}
public ITree traverseRealParent(Action act) throws Exception {
if(!hasBuildMap)
throw new Exception("InsertMap should be built firstly!");
// System.out.println("parMapSize:"+parMap.size());
ITree dst = act.getNode();
ITree mapped_insert_root = node2rootMap.get(dst);
return mapped_insert_root;
}//搜索该action根节点insert_root在src树上的映射, Insert专用
public ITree traverseSRoot(Action a) throws Exception {
ITree target = a.getNode();
if(a instanceof Update||a instanceof Delete) {
ITree src = a.getNode();
String typeLabel = tc1.getTypeLabel(src);
while(!Utils.ifSRoot(typeLabel)) {//可能有问题,要注意循环条件
ITree par = src.getParent();
typeLabel = tc1.getTypeLabel(par);
// System.out.println("typeLabel:"+typeLabel);
src = par;
}
target = src;
}
if(a instanceof Insert) {//insert 方法需要搜索tc2中的insert root节点
ITree dst = ((Insert)a).getNode();
String typeLabel = tc2.getTypeLabel(dst);
// System.out.println(dst.getId()+"typeLabel:"+typeLabel);
ITree par1 = null;
ITree par2 = dst.getParent();
// System.out.println(par2.getId());
// int pos = ((Insert)a).getPosition();
for(Mapping map : mapping) {
ITree first = map.getFirst();
ITree second = map.getSecond();
if(second.equals(par2)) {
System.out.println("getMap:"+first.getId()+"->"+second.getId());
par1 = first;
typeLabel = tc1.getTypeLabel(par1);
while(!Utils.ifSRoot(typeLabel)) {//可能有问题,要注意循环条件
// System.out.println("LabelID:"+par1.getId());
if(par1.isRoot())
break;//发现有直接连接在总树根节点的情况
else {
ITree tmpPar = par1.getParent();
typeLabel = tc1.getTypeLabel(tmpPar);
// System.out.println("typeLabel:"+typeLabel);
par1 = tmpPar;
}
}
node2rootMap.put(dst, par1);//绑定子节点用
break;
}
}
if(par1 == null) {//仍然为-1说明不在mapping中,action为insert子树中的节点
if(node2rootMap.get(par2)!=null) {
par1 = node2rootMap.get(par2);
node2rootMap.put(dst, par1);
}else {
System.err.println("error id:"+par2.getId());
// throw new Exception("error childAction!");
}
}
target = par1;
}
if(a instanceof Move) {
ITree src = ((Move) a).getNode();
ITree dst = ((Move) a).getParent();
String typeLabel = tc1.getTypeLabel(src);
// System.out.println(dst.getId()+"typeLabel:"+typeLabel);
// System.out.println("dstPar:"+dst.getParent().getId());
while(!Utils.ifSRoot(typeLabel)) {//可能有问题,要注意循环条件
ITree par = dst.getParent();
typeLabel = tc1.getTypeLabel(par);
// System.out.println(dst.getId()+"typeLabel:"+typeLabel);
dst = par;
}
target = dst;
}
return target;
}//搜索该action根语句root
public ITree downRoot(ArrayList<Action> actions) throws Exception {//topdown or downtop?
ITree sRoot = null;
List<Integer> parents = new ArrayList<>();
Boolean ifChild = true;
Action exampleA = actions.get(0);
if(exampleA instanceof Update) {
sRoot = traverseSRoot(actions.get(0));
for(Action a : actions) {
parents.add(a.getNode().getParent().getId());
Update act = (Update)a;
System.out.println("Upt:"+act.getNode().getId()+","+act.getValue());
}
}else if(exampleA instanceof Delete) {
sRoot = traverseSRoot(actions.get(0));
for(Action a : actions) {
parents.add(a.getNode().getParent().getId());
Delete act = (Delete)a;
System.out.println("Del:"+act.getNode().getId());
}
}else if(exampleA instanceof Insert) {
sRoot = traverseSRoot(actions.get(0));
for(Action a : actions) {
ITree realPar = traverseRealParent(a);
parents.add(realPar.getId());
Insert act = (Insert)a;
String out = "Add:"+act.getNode().getId()+"->"+act.getNode().getParent().getId();
if(act.getParent().getId()!=act.getNode().getParent().getId())
out = out+"("+act.getParent().getId()+")";
out = out+","+act.getPosition();
System.out.println(out);
}
}else if(exampleA instanceof Move) {
ITree dst = ((Move)actions.get(0)).getParent();
sRoot = node2rootMap.get(dst);
String typeLabel = tc1.getTypeLabel(sRoot);
System.out.println(sRoot.getId()+"sRootLabel:"+typeLabel);
for(Action a : actions) {
Move act = (Move)a;
parents.add(act.getParent().getId());
System.out.println("Mov:"+act.getNode().getId()+"->"+act.getParent().getId()
+","+act.getPosition());
}
}
while(ifChild) {//下降根节点必须保证覆盖所有actionNode
System.out.println("par:"+sRoot.getId());
if(parents.contains(sRoot.getId())) {
break;//如果下降到只比action的父节点高一层,break
}
List<ITree> childs = sRoot.getChildren();
if(childs.isEmpty())
throw new Exception("Error!");
else if(childs.size()==1)
sRoot = childs.get(0);
else {
ITree tmpPar = null;
for (ITree child : childs) {
tmpPar = child;
for(Action a : actions) {
ITree target = a.getNode();
ifChild = Utils.ifChild(tmpPar, target);
System.out.println(Boolean.toString(ifChild)+" "+target.getId()+","+tmpPar.getId());
if(!ifChild)
break;
}
if(ifChild)
break;
else
continue;
}
if(ifChild)
sRoot = tmpPar;
}
}
return sRoot;
}//从根语句root下降rootnode,取所有action的公有最下方root
}
| 14,997
| 31.393089
| 90
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/split/PruneTuple.java
|
package split;
import gumtreediff.tree.ITree;
public class PruneTuple {
public final ITree par;
public final ITree child;
public final int position;
public PruneTuple(ITree par, ITree child, int pos) {
this.par = par;
this.child = child;
this.position = pos;
}
@Override
public String toString(){
return "("+par.getId()+","+child.getId()+","+position+")";
}
public ITree getPar() {
return par;
}
public ITree getChild() {
return child;
}
public int getPosition() {
return position;
}
}
| 531
| 14.647059
| 66
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/split/Pruning.java
|
package split;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import utils.Utils;
/*
* Prune the tree, clean up the data to extract accurate rules.
*/
public class Pruning {
private TreeContext srcT;
private TreeContext dstT;
private MappingStore mappings;
private ArrayList<PruneTuple> pts1 = new ArrayList<>();
private ArrayList<PruneTuple> pts2 = new ArrayList<>();
public static void main (String args[]) throws Exception{
String path = "astra_driver.cpp";
File cppfile = new File(path);
TreeContext tc1 = new SrcmlCppTreeGenerator().generateFromFile(cppfile);
ITree root1 = tc1.getRoot();
String path2 = "astra_driver2.cpp";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlCppTreeGenerator().generateFromFile(cppfile2);
ITree root2 = tc2.getRoot();
Matcher m = Matchers.getInstance().getMatcher(root1, root2);
m.match();
MappingStore mappings = m.getMappings();
Pruning pr = new Pruning(tc1, tc2, mappings);
pr.pruneTree();
}
public Pruning(TreeContext tc1, TreeContext tc2, MappingStore mappings) {
this.srcT = tc1;
this.dstT = tc2;
this.mappings = mappings;
}
public void pruneTree() throws Exception {
System.out.println("Start Pruning");
if(pts1.size()!=0||pts2.size()!=0) {
throw new Exception("wrong action!");
}
ITree root1 = srcT.getRoot();
ITree root2 = dstT.getRoot();
List<ITree> before1 = root1.getDescendants();
List<ITree> before2 = root2.getDescendants();
ITree root_copy1 = root1.deepCopy();
ITree root_copy2 = root2.deepCopy();
List<ITree> before3 = root_copy1.getDescendants();
List<ITree> before4 = root_copy2.getDescendants();
System.out.println("Before Pruning:"+before1.size()+","+before2.size()
+","+before3.size()+","+before4.size());
List<ITree> results1 = new ArrayList<>();
List<ITree> results2 = new ArrayList<>();
results1 = traverse(root1, results1, "src");
results2 = traverse(root2, results2, "dst");
for(ITree node : results1) {
int id = node.getId();
// System.out.println("Prun1:"+id);
ITree par = node.getParent();
List<ITree> children = par.getChildren();
int pos = children.indexOf(node);
children.remove(node);//断开父亲和所有block node的连接
PruneTuple pt = new PruneTuple(par, node, pos);
pts1.add(pt);
node.setParent(null);//是否需要断开block node跟父亲的连接呢?
}
for(ITree node : results2) {
int id = node.getId();
// System.out.println("Prun2:"+id);
ITree par = node.getParent();
List<ITree> children = par.getChildren();
int pos = children.indexOf(node);
children.remove(node);//断开父亲和所有block node的连接
PruneTuple pt = new PruneTuple(par, node, pos);
pts2.add(pt);
node.setParent(null);//是否需要断开block node跟父亲的连接呢?
}
List<ITree> after1 = root1.getDescendants();
List<ITree> after2 = root2.getDescendants();
List<ITree> after3 = root_copy1.getDescendants();
List<ITree> after4 = root_copy2.getDescendants();
System.out.println("After Pruning:"+after1.size()+","+after2.size()
+","+after3.size()+","+after4.size());
}
public void recoverTree() {
for(PruneTuple pt : pts1) {
ITree par = pt.getPar();
ITree child = pt.getChild();
int pos = pt.getPosition();
// System.out.println("RecoverPrun1:"+pt.toString());
List<ITree> children = par.getChildren();
children.add(pos, child);
child.setParent(par);
}
for(PruneTuple pt : pts2) {
ITree par = pt.getPar();
ITree child = pt.getChild();
int pos = pt.getPosition();
// System.out.println("RecoverPrun1:"+pt.toString());
List<ITree> children = par.getChildren();
children.add(pos, child);
child.setParent(par);
}
}
public List<ITree> traverse(ITree node, List<ITree> results, String source) throws Exception {
if(node.isLeaf()) {
Boolean fullMatch = false;
if(source.equals("src")) {
ITree target = mappings.getDst(node);
if(target!=null) {
fullMatch = isFullMatching(node, target);
}else
fullMatch = false;
}else if(source.equals("dst")) {
ITree target = mappings.getSrc(node);
if(target!=null) {
fullMatch = isFullMatching(target, node);
}else
fullMatch = false;
}
if(fullMatch) {
ITree par = node.getParent();
List<ITree> childs = par.getChildren();
int height = node.getHeight();
for(ITree tmp : childs) {
int tmpH = tmp.getHeight();
if(tmpH>height) {
if(!results.contains(node)) {
results.add(node);
}
}
}
}
}else {
List<ITree> childs = node.getChildren();
if(source.equals("src")) {
ITree target = mappings.getDst(node);
Boolean fullMatch = false;
if(target!=null) {
fullMatch = isFullMatching(node, target);
}
if(fullMatch) {
if(!results.contains(node)) {
results.add(node);
}
}else {
for(ITree tmp : childs) {
traverse(tmp, results, "src");
}
}
}else if(source.equals("dst")) {
ITree target = mappings.getSrc(node);
Boolean fullMatch = false;
if(target!=null) {
fullMatch = isFullMatching(target, node);
}
if(fullMatch) {
if(!results.contains(node)) {
results.add(node);
}
}else {
for(ITree tmp : childs) {
traverse(tmp, results, "dst");
}
}
}else
throw new Exception("error!");
}
return results;
}//search for pruneable nodes
public Boolean isFullMatching(ITree node1, ITree node2) {
List<ITree> des1 = node1.getDescendants();
List<ITree> des2 = node2.getDescendants();
boolean result = true;
String parsString1 = Utils.printParents(node1, srcT);
String parsString2 = Utils.printParents(node2, dstT);
// System.out.println(parsString1+","+parsString2);
float sim = utils.Levenshtein.getSimilarityRatio(parsString1, parsString2);
if(sim==1) {
if(des1.size()==0&&des2.size()==0) {
String type1 = srcT.getTypeLabel(node1);
String type2 = dstT.getTypeLabel(node2);
String value1 = node1.getLabel();
String value2 = node2.getLabel();
int pos1 = node1.positionInParent();
int pos2 = node2.positionInParent();
if(type1.equals(type2)&&value1.equals(value2)) {
if(pos1==pos2)
result = true;
}else {
result = false;
}
}else if(des1.size()!=0&&des2.size()!=0) {
for(ITree tmp: des1) {
ITree dstNode = mappings.getDst(tmp);
if(dstNode!=null&&des2.contains(dstNode)) {
String type1 = srcT.getTypeLabel(tmp);
String type2 = dstT.getTypeLabel(dstNode);
String value1 = tmp.getLabel();
String value2 = dstNode.getLabel();
int pos1 = tmp.positionInParent();
int pos2 = dstNode.positionInParent();
if(type1.equals(type2)&&value1.equals(value2)) {
if(pos1==pos2)
continue;
}else {
result = false;
break;
}
}else {
result = false;
break;
}
}
for(ITree tmp: des2) {
ITree srcNode = mappings.getSrc(tmp);
if(srcNode!=null&&des1.contains(srcNode)) {
String type1 = srcT.getTypeLabel(srcNode);
String type2 = dstT.getTypeLabel(tmp);
String value1 = srcNode.getLabel();
String value2 = tmp.getLabel();
if(type1.equals(type2)&&value1.equals(value2)) {
continue;
}else {
result = false;
break;
}
}else {
result = false;
break;
}
}
}else {
result = false;
}
}else
result = false;
return result;
}//FullMatching means all descendants and parents of the two nodes have the same type and value.
}
| 7,799
| 29.350195
| 97
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/split/Split.java
|
package split;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import gumtreediff.actions.model.Action;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.gen.srcml.SrcmlJavaTreeGenerator;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import gumtreediff.tree.TreeUtils;
import nodecluster.Cluster;
import structure.ChangeTuple;
import structure.DTree;
import structure.Migration;
import structure.SubTree;
import structure.Transform;
import utils.Levenshtein;
import utils.Similarity;
import utils.Utils;
public class Split {
public ArrayList<Transform> trans = new ArrayList<>();
private int count = 0;
public static void main (String args[]) throws Exception{
Split sp = new Split();
String path = "migrations_test";
ArrayList<Migration> migrats = new ArrayList<>();
migrats = sp.readMigration(path, "");
sp.storeTrans(migrats);
sp.splitSnippets();
// String inputPath = "talker.cpp";
// sp.suggestion(inputPath);
}
public void suggestion(String input) throws Exception {//每个statement给5个suggestion
File cppfile = new File(input);
// String miName = input.split("/")[input.split("/").length-1];//标记文件名
String miName = input.split("\\\\")[input.split("\\\\").length-1];//标记文件名
TreeContext inputT = new SrcmlCppTreeGenerator().generateFromFile(cppfile);
ArrayList<SubTree> sts = splitSubTree(inputT, miName);
System.out.println("subSize:"+sts.size());
System.out.println("allTranSize:"+trans.size());
// String output = input.substring(0, input.length()-4)+".txt";
String output = miName.substring(0, miName.length()-4)+".txt";
BufferedWriter wr = new BufferedWriter(new FileWriter(new File(output)));
for(SubTree st : sts) {
HashMap<Transform, Double> sugs = new HashMap<>();
String inputTree = Similarity.transfer2string(st);
if(trans.isEmpty()) {
wr.close();
throw new Exception("trans null error!");
}
for (Transform ts : trans) {
SubTree tmpSt = ts.getSTree();
// String tmpTree = Similarity.transfer2string(tmpSt);
// System.out.println(inputTree);
// System.out.println(tmpTree);
double sim = Similarity.getSimilarity(st, tmpSt);
if(sugs.size()<5) {
sugs.put(ts, sim);
}else if(sugs.size()==5) {
Transform delTs = null;
Double delSim = 1.0;
for(Map.Entry<Transform, Double> entry : sugs.entrySet()) {
Transform candiTs = entry.getKey();
Double candiSim = entry.getValue();
if(candiSim<sim&&candiSim<delSim) {//找到五个suggestion中sim最小的扔了
delSim = candiSim;
delTs = candiTs;
}
}
if(delTs!=null) {
// System.out.println("putin:"+sim);
sugs.remove(delTs, delSim);
sugs.put(ts, sim);
}
}else if(sugs.size()>5) {
wr.close();
throw new Exception("Map size error!");
}
}
// System.out.println("====================================");
for(Map.Entry<Transform, Double> entry : sugs.entrySet()) {
Transform candiTs = entry.getKey();
SubTree sTree = candiTs.getSTree();
SubTree dTree = candiTs.getDTree();
String stringSTree = Similarity.transfer2string(sTree);
String stringDTree = "null";
if(dTree!=null)
stringDTree = Similarity.transfer2string(dTree);
Double candiSim = entry.getValue();
int lineNum = sTree.getStNum();
String name = sTree.getMiName();
wr.append(stringSTree+"\n");
wr.append(stringDTree+"\n");
wr.append(inputTree+"\n");
wr.append(candiSim+","+lineNum+","+name+"\n");
wr.flush();
// System.out.println(stringSTree);
// System.out.println(stringDTree);
// System.out.println(inputTree);
// System.out.println(candiSim+","+lineNum+","+name);
}
wr.append(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
wr.newLine();
wr.flush();
// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}
wr.close();
}
public void splitSnippets() throws Exception {//finer-grained split statement into type snippets
for (Transform tf : trans) {
SubTree srcST = tf.getSTree();
SubTree dstST = tf.getDTree();
HashMap<DTree, DTree> dtMap = new HashMap<>();
ITree root = srcST.getRoot();
if(root.getDescendants().size()==0)
continue;//有剪枝和切断block之后while function类似节点只有节点本身的情况,跳过
TreeContext tc = srcST.getTC();
String type = tc.getTypeLabel(root);
int id = root.getId();
// if(type.equals("if")) {
// List<ITree> childs = root.getDescendants();
// for(ITree node : childs) {
// if(tc.getTypeLabel(node).equals("block"))
// System.err.println("find block!");
// }
// }
searchDTmap(tf);
//find different kinds of actions
// for(int i=0;i<sDTs.size();i++) {
// DTree sDT = sDTs.get(i);
//
// }
}
}
public HashMap<DTree, DTree> searchDTmap(Transform tf) throws Exception{
System.out.println("----getDTmap----");
HashMap<DTree, DTree> dtMap = new HashMap<>();
SubTree srcST = tf.getSTree();
SubTree dstST = tf.getDTree();
if(srcST==null) {
System.out.println("srcST is null!");
dtMap = addCondition(tf);
return dtMap;
}
if(dstST==null) {
System.out.println("dstST is null!");
dtMap = delCondition(tf);
return dtMap;
}
TreeContext srcT = tf.getSrcT();
System.out.println("srcRootID:"+srcST.getRoot().getId());
TreeContext dstT = tf.getDstT();//单叶子节点,不同value,no matching情况
HashMap<Integer, Integer> subMap = tf.getSubMap();
HashMap<String, ArrayList<Action>> actMap = tf.getActMap();
ArrayList<Action> updates = actMap.get("update");
String miName = tf.getMiName();
System.out.println("TF:"+miName);
ArrayList<DTree> sDTs = getDwarfTrees(srcST);
ArrayList<DTree> dDTs = getDwarfTrees(dstST);
System.out.println("sDTsize:"+sDTs.size());
System.out.println("dDTsize:"+dDTs.size());
ArrayList<DTree> mappedsDTs = getDwarfTrees(srcST);
ArrayList<DTree> mappeddDTs = getDwarfTrees(dstST);
ArrayList<Integer> updIds = new ArrayList<>();
for(Action act : updates) {
ITree node = act.getNode();
int id = node.getId();
updIds.add(id);
}
for(DTree sdt : sDTs) {
System.out.println(sdt.getRoot().getId());
}
for(int i=0;i<sDTs.size();i++) {//Dwarf-tree level
DTree sDT = sDTs.get(i);
List<ITree> leaves = sDT.getLeaves();
String sDTString = Utils.printLeaf(sDT);//因为结构原因,可能有部分root的子节点不是DT的叶子
int size1 = leaves.size();
double sim1 = 0.0;
double sim2 = 0.0;
DTree candidateDT1 = null;
DTree candidateDT2 = null;
for(int j=0;j<dDTs.size();j++) {
DTree dDT = dDTs.get(j);
List<ITree> leaves2 = dDT.getLeaves();
int size2 = leaves2.size();
//two ways of similarity
int tmpNum1 = 0;
int tmpNum2 = 0;
for(ITree leaf : leaves) {
int srcId = leaf.getId();
String value = leaf.getLabel();//maybe some leaves do not have values
for(ITree leaf2 : leaves2) {
String value2 = leaf2.getLabel();
int dstId = leaf2.getId();
if(leaves.size()==1&&leaves2.size()==1) {
if(updIds.contains(srcId)&&dstId == subMap.get(srcId)) {
tmpNum1++;
continue;
}//If it contains a UPD action, it should be matched.
}//In some cases, A DTree only has one leaf. It should be discussed separately.
if(value2.equals(value)) {
tmpNum1++;
break;
}//search for equivalent value.
}
for(ITree leaf2 : leaves2) {
int dstId = leaf2.getId();
if(subMap.get(srcId)!=null) {
if(dstId==subMap.get(srcId)) {//search mapping
tmpNum2++;
break;
}
}
}
}
double tmpSim1 = (2.0*tmpNum1)/(size1+size2);
double tmpSim2 = (2.0*tmpNum2)/(size1+size2);
if(sim2<tmpSim1) {
candidateDT1 = dDT;
sim2=tmpSim1;
}
if(sim1<tmpSim2) {
candidateDT2 = dDT;
sim1=tmpSim2;
}
// if(sDT.getRoot().getId()==821) {
// System.out.println(Utils.printDTree(sDT));
// System.out.println("dDT:"+dDT.getRoot().getId()+Utils.printDTree(dDT));
// System.out.println("sim:"+sim1+","+tmpNum1+","+sim2+","+tmpNum2);
// if(candidateDT1!=null) {
// System.out.println("CandidateId1:"+candidateDT1.getRoot().getId());
// }
// if(candidateDT2!=null) {
// System.out.println("CandidateId2:"+candidateDT2.getRoot().getId());
// }
// }
}
if(sim1==1) {
String dDTString = Utils.printLeaf(candidateDT2);
if(!sDTString.equals(dDTString)) {
System.out.println("Change3:"+sDTString+"->"+dDTString);
ChangeTuple ct = Utils.filterChange(sDT, candidateDT2);
System.out.println("AfterFilter:"+ct.toString());
if((dtMap.containsKey(sDT)&&!dtMap.containsValue(candidateDT2))) {
throw new Exception("error candidateDT!");
}else if(!dtMap.containsKey(sDT)&&dtMap.containsValue(candidateDT2)){
throw new Exception("error sDT!");
}else {
dtMap.put(sDT, candidateDT2);
}
if(!(mappedsDTs.contains(sDT)||mappeddDTs.contains(candidateDT2))) {
mappedsDTs.add(sDT);
mappeddDTs.add(candidateDT2);
}else if(mappedsDTs.contains(sDT)&&!mappeddDTs.contains(candidateDT2)) {
throw new Exception("error situation");
}else if(!mappedsDTs.contains(sDT)&&mappeddDTs.contains(candidateDT2)) {
throw new Exception("error situation");
}
}
else {
List<ITree> leaves2 = candidateDT2.getLeaves();
Boolean ifMatch = false;
for(int j=0;j<leaves.size();j++) {
ITree srcNode = leaves.get(j);
String sType = srcT.getTypeLabel(srcNode);
String sValue = srcNode.getLabel();
ITree dstNode = leaves2.get(j);
String dType = dstT.getTypeLabel(dstNode);
String dValue = dstNode.getLabel();
if(sType.equals(dType)&&sValue.equals(dValue)) {
ifMatch = true;
}else
ifMatch = false;
}
if(ifMatch) {
mappedsDTs.add(sDT);
mappeddDTs.add(candidateDT2);
}
}
}//全部matching,若叶子完全相同,移除,不然是全部需要改的特殊情况
if(sim1>=0.5&&sim1!=1) {
String dstTString = Utils.printLeaf(candidateDT2);
System.out.println("Change1:"+sDTString+"->"+dstTString);
ChangeTuple ct = Utils.filterChange(sDT, candidateDT2);
System.out.println("AfterFilter:"+ct.toString());
// System.out.println("Map:"+sDT.getRoot().getId()+"->"+candidateDT2.getRoot().getId());
if((dtMap.containsKey(sDT)&&!dtMap.containsValue(candidateDT2))) {
throw new Exception("error candidateDT!");
}else if(!dtMap.containsKey(sDT)&&dtMap.containsValue(candidateDT2)){
throw new Exception("error sDT!");
}else {
dtMap.put(sDT, candidateDT2);
}
if(!(mappedsDTs.contains(sDT)||mappeddDTs.contains(candidateDT2))) {
mappedsDTs.add(sDT);
mappeddDTs.add(candidateDT2);
}else if(mappedsDTs.contains(sDT)&&!mappeddDTs.contains(candidateDT2)) {
throw new Exception("error situation");
}else if(!mappedsDTs.contains(sDT)&&mappeddDTs.contains(candidateDT2)) {
throw new Exception("error situation");
}
}
if(sim2==1) {
if(leaves.size()==1&&candidateDT1.getLeaves().size()==1) {
int srcId = leaves.get(0).getId();
int candidateId = candidateDT1.getLeaves().get(0).getId();
System.out.println("Size1id:"+srcId+","+candidateId);
if(updIds.contains(srcId)) {
System.out.println("dtMapsize:"+dtMap.size());
String dstTString = Utils.printLeaf(candidateDT1);
System.out.println(sDT.getRoot().getId());
System.out.println("Change4:"+sDTString+"->"+dstTString);
ChangeTuple ct = Utils.filterChange(sDT, candidateDT1);
System.out.println("AfterFilter:"+ct.toString());
dtMap.put(sDT, candidateDT1);
if(!(mappedsDTs.contains(sDT)||mappeddDTs.contains(candidateDT1))) {
mappedsDTs.add(sDT);
mappeddDTs.add(candidateDT1);
}else if(mappedsDTs.contains(sDT)&&!mappeddDTs.contains(candidateDT1)) {
throw new Exception("error situation");
}else if(!mappedsDTs.contains(sDT)&&mappeddDTs.contains(candidateDT1)) {
throw new Exception("error situation");
}
}
}
}//In some cases, A DTree only has one leaf. It should be discussed separately.
if(sim2>=0.3&&sim2!=1) {
System.out.println("dtMapsize:"+dtMap.size());
String dDTString = Utils.printLeaf(candidateDT1);
// System.out.println("Map:"+sDT.getRoot().getId()+"->"+candidateDT1.getRoot().getId());
if(!(dtMap.containsKey(sDT)||dtMap.containsValue(candidateDT1))) {
System.out.println(sDT.getRoot().getId());
System.out.println("Change2:"+sDTString+"->"+dDTString);
ChangeTuple ct = Utils.filterChange(sDT, candidateDT1);
System.out.println("AfterFilter:"+ct.toString());
dtMap.put(sDT, candidateDT1);
}else {
System.out.println("existing sDT or candidateDT");
}
if(!(mappedsDTs.contains(sDT)||mappeddDTs.contains(candidateDT1))) {
mappedsDTs.add(sDT);
mappeddDTs.add(candidateDT1);
}else{
System.out.println("existing maapingDT");
}
}
}
for(DTree dt : mappedsDTs) {
sDTs.remove(dt);
}
for(DTree dt : mappeddDTs) {
dDTs.remove(dt);
}//unmapped DTrees
for(DTree sDT: sDTs) {
Boolean ifMatch = false;
ITree sRoot = sDT.getRoot();
List<ITree> leaves = sDT.getLeaves();
for(ITree leaf : leaves) {
int id = leaf.getId();
if(subMap.containsKey(id)) {
ifMatch = true;
}
}
if(ifMatch)
continue;//若是match上且不需要修改的DTree,不要记录直接continue
String sRootType = srcT.getTypeLabel(sRoot);
String sParsString = sRootType+Utils.printParents(sRoot, srcT);
float sim = 0;
String sDTString = Utils.printLeaf(sDT);
DTree candidateDT = null;
for(DTree dDT: dDTs) {
float tmpSim = 0;
ITree dRoot = dDT.getRoot();
String dRootType = dstT.getTypeLabel(dRoot);
if(sRootType.equals(dRootType)) {
String dParsString = dRootType+Utils.printParents(dRoot, dstT);
tmpSim = Levenshtein.getSimilarityRatio(sParsString, dParsString);
if(tmpSim>sim) {
candidateDT = dDT;
sim = tmpSim;
}
}
}
if(sim>0.7) {
String dDTString = Utils.printLeaf(candidateDT);
if(!sDTString.equals(dDTString)) {
System.out.println("Levenshtein:"+sim);
System.out.println("Change5:"+sDTString+"->"+dDTString);
ChangeTuple ct = Utils.filterChange(sDT, candidateDT);
System.out.println("AfterFilter:"+ct.toString());
// System.out.println("Map:"+sDT.getRoot().getId()+"->"+candidateDT2.getRoot().getId());
}
if(!(dtMap.containsKey(sDT)||dtMap.containsValue(candidateDT))) {
dtMap.put(sDT, candidateDT);
}else {
System.out.println("existing sDT or candidate");
}
if(!(mappedsDTs.contains(sDT)||mappeddDTs.contains(candidateDT))) {
mappedsDTs.add(sDT);
mappeddDTs.add(candidateDT);
}else {
System.out.println("existing maapingDT");
}
}
}
for(DTree dt : mappedsDTs) {
sDTs.remove(dt);
}
for(DTree dt : mappeddDTs) {
dDTs.remove(dt);
}//unmapped DTrees
System.out.println("sDTSize:"+sDTs.size());
System.out.println("dDTSize:"+dDTs.size());
for(DTree sDT: sDTs) {
ITree sRoot = sDT.getRoot();
String sRootType = srcT.getTypeLabel(sRoot);
String sDTString = Utils.printLeaf(sDT);
boolean ifDEL = true;
for(DTree dDT: dDTs) {
ITree dRoot = dDT.getRoot();
String dRootType = dstT.getTypeLabel(dRoot);
if(sRootType.equals(dRootType)) {
ifDEL = false;
System.out.println("why not matching?"+sDTString);
}else
continue;
}
if(ifDEL&&!sDTString.equals("")) {
System.out.println("Del:"+sDTString);
}
}
for(DTree dDT: dDTs) {
ITree dRoot = dDT.getRoot();
String dRootType = dstT.getTypeLabel(dRoot);
String dDTString = Utils.printLeaf(dDT);
boolean ifADD = true;
for(DTree sDT: sDTs) {
ITree sRoot = sDT.getRoot();
String sRootType = srcT.getTypeLabel(sRoot);
if(sRootType.equals(dRootType)) {
ifADD = false;
System.out.println("why not matching?"+dDTString);
}else
continue;
}
if(ifADD&&!(dDTString.equals(""))) {
System.out.println("ADD:"+dDTString);
}
}
return dtMap;
}//Matching sDTs and dDTs
public ArrayList<DTree> getDwarfTrees(SubTree st) throws Exception{
ArrayList<DTree> orderedDTs = new ArrayList<>();
ITree root = st.getRoot();
TreeContext tc = st.getTC();
if(root.getHeight()<2)
throw new Exception("error subtree id "+root.getId()+", plz check!");
List<ITree> leaves = new ArrayList<>();
leaves = Utils.traverse2Leaf(root, leaves);
ArrayList<DTree> dwarfTrees = new ArrayList<>();
HashMap<ITree, ArrayList<ITree>> parMap = new HashMap<>();
for (ITree leaf : leaves) {
String type = tc.getTypeLabel(leaf);
ITree par = leaf.getParent();
if(par==null) {
System.out.println("par is null, maybe leaf is block node");
continue;
}
String parType = tc.getTypeLabel(par);
if(type.equals("argument_list"))
continue;//"argument_list"的叶子节点不包含任何信息,还可能扰乱匹配
//leaf nodes have many situations, need to consider one by one.
else if(type.equals("name")||type.equals("operator")) {
while(parType.equals("name")) {
par = par.getParent();
parType = tc.getTypeLabel(par);
}//name或operator的parent不能为name
}//考虑name DTree发现的特殊情况, 不然多个name leaf的par跟单个name leaf会匹配异常
if(parMap.get(par)==null) {
ArrayList<ITree> leafList = new ArrayList<>();
leafList.add(leaf);
parMap.put(par, leafList);
}else {
parMap.get(par).add(leaf);
}
}
for(Map.Entry<ITree, ArrayList<ITree>> entry : parMap.entrySet()) {
ITree par = entry.getKey();
Stack<String> trace = new Stack<>();
ITree tmp = par;
String type = tc.getTypeLabel(tmp);
while(!Utils.ifSRoot(type)) {
trace.push(type);
tmp = tmp.getParent();
type = tc.getTypeLabel(tmp);
}
ArrayList<ITree> leafList = entry.getValue();
if(leafList.size()>0) {
DTree dt = new DTree(par, leafList, trace, tc);
dwarfTrees.add(dt);
}else
throw new Exception("error par!!");
}
while(orderedDTs.size()!=dwarfTrees.size()) {
int max = Integer.MAX_VALUE;
DTree candidate = null;
for(DTree DT : dwarfTrees) {
int id = DT.getRoot().getId();
if(!orderedDTs.contains(DT)&&id<max) {
candidate = DT;
max = id;
}
}
orderedDTs.add(candidate);
}
return orderedDTs;
}//sub-subtree whose height is 2
public ArrayList<Migration> readMigration(String path, String input) throws Exception {
ArrayList<Migration> migrats = new ArrayList<>();
File rootFile = new File(path);
File[] dirs = rootFile.listFiles();
for(File dir : dirs) {
if(dir.getName().equals(input)) {
System.out.println("Skip File:"+dir.getName());
continue;
}
System.out.println("Reading File:"+dir.getName());
// Thread.sleep(1000);
File[] pair = dir.listFiles();
if(pair.length!=2)
throw new Exception("error pair! "+dir.getName());
File srcFile = pair[0];
File dstFile = pair[1];
TreeContext tc1 = new SrcmlJavaTreeGenerator().generateFromFile(srcFile);
TreeContext tc2 = new SrcmlJavaTreeGenerator().generateFromFile(dstFile);
Matcher m = Matchers.getInstance().getMatcher(tc1.getRoot(), tc2.getRoot());
m.match();
MappingStore mappings = m.getMappings();
Migration mi = new Migration(tc1, tc2, mappings, srcFile.getAbsolutePath(), dstFile.getAbsolutePath());
migrats.add(mi);
}
System.out.println("Migration size:"+migrats.size());
return migrats;
}
public void storeTrans(ArrayList<Migration> migrats) throws Exception {
for(Migration migrat : migrats) {
String miName = migrat.getMiName();
TreeContext srcT = migrat.getSrcT();
TreeContext dstT = migrat.getDstT();
MappingStore mappings = migrat.getMappings();
// ArrayList<SubTree> sub2 = splitSubTree(dstT, miName);
// double similarity = Similarity.getSimilarity(sub1.get(0), sub2.get(0));
// System.out.println("sime:"+similarity);//testing
ArrayList<Transform> singleTrans = splitTransform(srcT, dstT, mappings, miName);
trans.addAll(singleTrans);
System.out.println("TransSize:"+singleTrans.size());
}
}
public ArrayList<Transform> splitTransform(TreeContext srcT, TreeContext dstT, MappingStore mappings, String miName) throws Exception {
System.out.println("Analyse:"+miName);
Matcher m = Matchers.getInstance().getMatcher(srcT.getRoot(), dstT.getRoot());
m.match();
ArrayList<Transform> trans = new ArrayList<>();
ArrayList<SubTree> actSubTree = new ArrayList<>();
HashMap<String, LinkedList<Action>> actions = Utils.collectAction(srcT, dstT, mappings);
// HashMap<SubTree, Integer> st2lineNum = new HashMap<>();
LinkedList<Action> updates = actions.get("update");
LinkedList<Action> deletes = actions.get("delete");
LinkedList<Action> inserts = actions.get("insert");
LinkedList<Action> moves = actions.get("move");
ArrayList<Integer> srcActIds = Utils.collectSrcActNodeIds(srcT, dstT, mappings, actions);
// System.out.println("IdNum:"+srcActIds.size());
// Pruning pt = new Pruning(srcT, dstT, mappings);
// pt.pruneTree();//Prune the ContextTree in order to get accurate matching rules.
Cluster cl = new Cluster(srcT, dstT);
ArrayList<SubTree> sub1 = splitSubTree(srcT, miName);//Subtree中割裂过block,注意
ArrayList<SubTree> sub2 = splitSubTree(dstT, miName);//先计算action,再split ST
for(SubTree st : sub1) {
ITree t = st.getRoot();
List<ITree> nodeList = new ArrayList<>();
nodeList = Utils.collectNode(t, nodeList);
for(ITree node : nodeList) {
int id = node.getId();
if(srcActIds.contains(id)) {
actSubTree.add(st);
// System.out.println("find a action subtree!");
break;
}
}
}//先找包含action的subtree
// for(int j=0;j<updates.size();j++) {
// Action a = updates.get(j);
// ITree node = a.getNode();
// int id = node.getId();
// System.out.println("UPDid:"+id);
// }
for(int i=0;i<actSubTree.size();i++) {
SubTree st = actSubTree.get(i);
ITree t = st.getRoot();
ArrayList<Action> subUpdates = new ArrayList<>();
ArrayList<Action> subDeletes = new ArrayList<>();
ArrayList<Action> subInserts = new ArrayList<>();
ArrayList<Action> subMoves = new ArrayList<>();
List<ITree> nodeList = new ArrayList<>();
nodeList = Utils.collectNode(t, nodeList);
// System.out.println("nodelistSize:"+nodeList.size());
HashMap<String, ArrayList<Action>> subActions = new HashMap<>();
for (Action a : updates) {
ITree node = a.getNode();
int id = node.getId();
// System.out.println("UPDid:"+id);
for(ITree tmp : nodeList) {
// System.out.println(id+":"+tmp.getId());
if(tmp.getId()==id) {
// System.out.println("map:"+tmp.getId());
subUpdates.add(a);
// updates.remove(a);
}
}
}
for (Action a : deletes) {
ITree node = a.getNode();
int id = node.getId();
for(ITree tmp : nodeList) {
if(tmp.getId()==id) {
subDeletes.add(a);
// deletes.remove(a);
}
}
}
// for(int j=0;j<inserts.size();j++) {
// Action a = inserts.get(j);
// ITree sRoot = cl.traverseSRoot(a);
// if(nodeList.contains(sRoot)) {
// subInserts.add(a);
//// inserts.remove(a);
// }
// }
// for(int j=0;j<moves.size();j++) {
// Action a = moves.get(j);
// ITree sRoot = cl.findMovRoot(a);
// if(nodeList.contains(sRoot)) {
// subMoves.add(a);
//// moves.remove(a);
// }
// }
// System.out.println("subupdsize:"+subUpdates.size());
// System.out.println("subdelsize:"+subDeletes.size());
// System.out.println("subaddsize:"+subInserts.size());
// System.out.println("submovsize:"+subMoves.size());
// System.out.println("--------------------------------");
subActions.put("update", subUpdates);
subActions.put("delete", subDeletes);
subActions.put("insert", subInserts);
subActions.put("move", subMoves);
ITree srcStRoot = st.getRoot();
ITree dstStRoot = mappings.getDst(srcStRoot);
SubTree dstSt = null;
if(dstStRoot==null) {
System.out.println("SID:"+srcStRoot.getId()); //发现有整颗srcSr删除的情况
}else {
for(SubTree st2 : sub2) {
ITree root = st2.getRoot();
if(root.equals(dstStRoot)) {
dstSt = st2;
break;
}
}
}//是否会漏掉src中没有语句,dst中加入的情况
List<ITree> nodes = TreeUtils.preOrder(st.getRoot());
HashMap<Integer, Integer> subMap = new HashMap<>();
for(ITree src : nodes) {
ITree dst = mappings.getDst(src);
if(dst!=null) {
subMap.put(src.getId(), dst.getId());
}
}//Mapping between srcId and dstId.
Transform tf = new Transform(st, dstSt, subMap, subActions, miName);
trans.add(tf);
}
System.out.println("updsize:"+updates.size());
System.out.println("delsize:"+deletes.size());
System.out.println("addsize:"+inserts.size());
System.out.println("movsize:"+moves.size());
System.out.println("stSize:"+sub1.size());
return trans;
}
public ArrayList<SubTree> splitSubTree(TreeContext tc, String miName) {//split subtree from AST tree
count = 0;
ITree totalRoot = tc.getRoot();
List<ITree> orderList = TreeUtils.preOrder(totalRoot);
ArrayList<SubTree> subTreeList = new ArrayList<>();
ArrayList<ITree> subRootList = new ArrayList<>();
for(ITree t : orderList) {
String typeLabel = tc.getTypeLabel(t);
if(Utils.ifSRoot(typeLabel)) {
ITree subRoot = t;
List<ITree> pars = t.getParents();
ArrayList<ITree> parBlocks = new ArrayList<>();
for(ITree par : pars) {
String type = tc.getTypeLabel(par);
if(type.equals("block")) {
parBlocks.add(par);
}
}//将sRoot所有父亲节点中的block节点备份
SubTree st = new SubTree(subRoot, tc, count, miName);
st.setParBlocks(parBlocks);
st.setPars(pars);//因为subtree同父亲已断开,计算pars调用这个List
subTreeList.add(st);
subRootList.add(subRoot);
count++;
}//if是否考虑typeLabel=="return"?
}
for(ITree subRoot : subRootList) {
String typeLabel = tc.getTypeLabel(subRoot);
subRoot.getParent().getChildren().remove(subRoot);//断开父亲和stRoot的连接
subRoot.setParent(null);//断开父亲和stRoot的连接
if(typeLabel.equals("class")||typeLabel.equals("function")) {
List<ITree> list = subRoot.getChildren();
ITree delete_node = null;
for(ITree tmp : list) {
String type = tc.getTypeLabel(tmp);
if(type.equals("block")) {//search block node
delete_node = tmp;
}
}
if(delete_node!=null) {
subRoot.getChildren().remove(delete_node);//断开subRoot和所有block node的连接
delete_node.setParent(null);//断开subRoot和所有block node的连接
}
}
}
// System.out.println("subTreeNum:"+count);
return subTreeList;
}
public HashMap<DTree, DTree> delCondition(Transform tf) throws Exception {
HashMap<DTree, DTree> dtMap = new HashMap<>();
SubTree srcST = tf.getSTree();
String code = Utils.subtree2src(srcST);
System.out.println("DELStmt:"+code);
return null;
}//dstST为空的特殊情况,代表srcST找不到对应的dstST,直接删除整颗srcST即可
public HashMap<DTree, DTree> addCondition(Transform tf) throws Exception {
HashMap<DTree, DTree> dtMap = new HashMap<>();
SubTree dstST = tf.getDTree();
String code = Utils.subtree2src(dstST);
System.out.println("ADDStmt:"+code);
return null;
}//dstST为空的特殊情况,代表srcST找不到对应的dstST,直接删除整颗srcST即可
}
| 27,780
| 33.339926
| 136
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/split/Statistic.java
|
package split;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import structure.Migration;
import utils.Utils;
public class Statistic {
public static void main (String args[]) throws Exception{
String path = "migrations";
// givenStatistic(path);
collectSpecificLeaves(path, "call");
}
public static void givenStatistic(String path) throws Exception {
String inputName = "";
File[] dirs = (new File(path)).listFiles();
for(File dir : dirs) {
Split sp = new Split();
ArrayList<Migration> migrats = new ArrayList<>();
inputName = dir.getName();
File[] files = dir.listFiles();
String testName = files[0].getAbsolutePath();
String miName = testName.split("\\\\")[testName.split("\\\\").length-1];//标记文件名
String output = miName.substring(0, miName.length()-4)+".txt";
System.out.println(output);
File[] fileList = (new File("D:\\workspace\\eclipse2018\\gumtree")).listFiles();
Boolean ifExist = false;
for(File tmp : fileList) {
String name = tmp.getName();
if(name.equals(output)) {
ifExist = true;
break;
}
}
if(ifExist)
continue;
migrats = sp.readMigration(path, inputName);
sp.storeTrans(migrats);
if(files.length!=2)
throw new Exception("error dir!!");
sp.suggestion(testName);
}
}
public static void collectSpecificLeaves(String path, String parType) throws Exception {
ArrayList<Migration> migrats = new ArrayList<>();
Split sp = new Split();
migrats = sp.readMigration(path, "");
ArrayList<String> types1 = new ArrayList<>();
ArrayList<String> types2 = new ArrayList<>();
for(Migration m : migrats) {
TreeContext tc1 = m.getSrcT();
TreeContext tc2 = m.getDstT();
ITree root1 = tc1.getRoot();
ITree root2 = tc2.getRoot();
List<ITree> leaves1 = new ArrayList<>();
List<ITree> leaves2 = new ArrayList<>();
leaves1 = Utils.traverse2Leaf(root1, leaves1);
leaves2 = Utils.traverse2Leaf(root2, leaves2);
for(ITree tmp : leaves1) {
String parType1 = tc1.getTypeLabel(tmp.getParent());
if(!parType1.equals(parType))
continue;
String type = tc1.getTypeLabel(tmp);
if(!types1.contains(type)) {
types1.add(type);
}
}
for(ITree tmp : leaves2) {
String parType2 = tc2.getTypeLabel(tmp.getParent());
if(!parType2.equals(parType))
continue;
String type = tc2.getTypeLabel(tmp);
if(!types2.contains(type)) {
types2.add(type);
}
}
}
for(String type : types2) {
if(!types1.contains(type)) {
types1.add(type);
}
}
for(String type : types1) {
System.out.println(type);
}
}
}
| 2,689
| 26.731959
| 89
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/Boundary.java
|
package structure;
import gumtreediff.tree.ITree;
public class Boundary {
private ITree root;
private int beginLine;
private int lastLine;
private int beginCol;
private int lastCol;
public Boundary(ITree root, int beginLine, int lastLine, int beginCol, int lastCol) {
this.root = root;
this.beginLine = beginLine;
this.lastLine = lastLine;
this.beginCol = beginCol;
this.lastCol = lastCol;
}
public Boundary() {}
public ITree getRoot() {
return root;
}
public void setRoot(ITree root) {
this.root = root;
}
public int getBeginLine() {
return beginLine;
}
public void setBeginLine(int beginLine) {
this.beginLine = beginLine;
}
public int getLastLine() {
return lastLine;
}
public void setLastLine(int lastLine) {
this.lastLine = lastLine;
}
public int getBeginCol() {
return beginCol;
}
public void setBeginCol(int beginCol) {
this.beginCol = beginCol;
}
public int getLastCol() {
return lastCol;
}
public void setLastCol(int lastCol) {
this.lastCol = lastCol;
}
}
| 1,039
| 15.25
| 86
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/ChangeTuple.java
|
package structure;
public class ChangeTuple {
private String src;
private String dst;
public ChangeTuple() {
}
public ChangeTuple(String src, String dst) {
this.src = src;
this.dst = dst;
}
public String getSrc() {
return src;
}
public String getDst() {
return dst;
}
public void setSrc(String src) {
this.src = src;
}
public void setDst(String dst) {
this.dst = dst;
}
@Override
public String toString() {
String change = src+"->"+dst;
return change;
}
}
| 500
| 11.525
| 45
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/DTree.java
|
package structure;
import java.util.List;
import java.util.Stack;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
public class DTree {
private ITree root;
private List<ITree> leaves;
private TreeContext treeContext;
private Stack<String> trace;
public DTree(ITree root, List<ITree> leaves, Stack<String> trace, TreeContext treeContext) {
this.root = root;
this.leaves = leaves;
this.trace = trace;
this.treeContext = treeContext;
}
public ITree getRoot() {
return root;
}
public String getRootType() {
String type = treeContext.getTypeLabel(root);
return type;
}
public Stack<String> getTrace() {
return trace;
}
public List<ITree> getLeaves() {
return leaves;
}
public TreeContext getTreeContext() {
return treeContext;
}
}
| 792
| 16.622222
| 93
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/Definition.java
|
package structure;
import java.util.List;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
public class Definition {
private int defLabelID;
private ITree root;
private String type;
private String varName;
private ITree block;
private List<ITree> parBlocks;
private List<ITree> parList;
private TreeContext tc;
public int getDefLabelID() {
return defLabelID;
}
public ITree getRoot() {
return root;
}
public String getType() {
return type;
}
public String getVarName() {
return varName;
}
public ITree getBlock() {
return block;
}
public List<ITree> getParBlocks() {
return parBlocks;
}
public List<ITree> getParList() {
return parList;
}
public void setDefLabelID(int defLabelID) {
this.defLabelID = defLabelID;
}
public void setRoot(ITree root) {
this.root = root;
}
public void setType(String type) {
this.type = type;
}
public void setVarName(String varName) {
this.varName = varName;
}
public void setBlock(ITree block) {
this.block = block;
}
public void setParBlocks(List<ITree> parBlocks) {
this.parBlocks = parBlocks;
}
public void setParList(List<ITree> parList) {
this.parList = parList;
}
public TreeContext getTc() {
return tc;
}
public void setTc(TreeContext tc) {
this.tc = tc;
}
}
| 1,294
| 17.768116
| 50
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/Edge.java
|
package structure;
public class Edge {
public int source;//source
private int target;//target
private int weight;//weight of this edge
public Edge(int source, int target) {
this.source = source;
this.target = target;
}
public int getSource(){
return source;
}
public int getTarget(){
return target;
}
public void setWeight(int weight){
this.weight = weight;
}
public int getWeight(){
return weight;
}
@Override
public boolean equals(Object obj) {
// TODO 自动生成的方法存根
Edge edge = (Edge)obj;
if(edge.source==this.source&&edge.target==this.target){
return true;
}
else
return false;
//return super.equals(obj);
}
}
| 663
| 15.195122
| 57
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/Migration.java
|
package structure;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.TreeContext;
public class Migration {
private TreeContext srcT;
private TreeContext dstT;
private MappingStore mappings;
private String repoName;
private String miName_src;
private String miName_dst;
private String srcHash;
private String dstHash;
public Migration(TreeContext tc1, TreeContext tc2, MappingStore mappings, String src, String dst) {
this.srcT = tc1;
this.dstT = tc2;
this.mappings = mappings;
this.miName_src = src;
this.miName_dst = dst;
}
public TreeContext getSrcT() {
return srcT;
}
public TreeContext getDstT() {
return dstT;
}
public MappingStore getMappings() {
return mappings;
}
public String getRepoName() {
return repoName;
}
public void setRepoName(String repoName) {
this.repoName = repoName;
}
public String getMiName() {
String[] tmps = miName_src.split("\\");
return tmps[tmps.length-1];
}
public String getMiName_src() {
return miName_src;
}
public String getMiName_dst() {
return miName_dst;
}
public String getSrcHash() {
return srcHash;
}
public String getDstHash() {
return dstHash;
}
public void setSrcHash(String srcHash) {
this.srcHash = srcHash;
}
public void setDstHash(String dstHash) {
this.dstHash = dstHash;
}
}
| 1,329
| 16.733333
| 100
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/SubTree.java
|
package structure;
import java.util.ArrayList;
import java.util.List;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
public class SubTree {
private ITree root;
private TreeContext tc;
private int stNum;
private String miName;
private ArrayList<ITree> parBlocks;
private List<ITree> pars;//因为subtree同父亲已断开,计算pars调用这个List
public SubTree(ITree node, TreeContext context, int count, String name) {
root = node;
tc = context;
stNum = count;
miName = name;
}
public ITree getRoot() {
return root;
}
public TreeContext getTC() {
return tc;
}
public int getStNum() {
return stNum;
}
public String getMiName() {
return miName;
}
public ArrayList<ITree> getParBlocks() {
return parBlocks;
}
public void setParBlocks(ArrayList<ITree> parBlocks) {
this.parBlocks = parBlocks;
}
public List<ITree> getPars() {
return pars;
}
public void setPars(List<ITree> pars) {
this.pars = pars;
}
}
| 957
| 15.517241
| 74
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/structure/Transform.java
|
package structure;
import java.util.ArrayList;
import java.util.HashMap;
import gumtreediff.actions.model.Action;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
public class Transform {
private SubTree sTree;
private SubTree dTree;
private HashMap<Integer, Integer> subMap;
private HashMap<String, ArrayList<Action>> actMap;
private String miName;
public Transform(SubTree st, SubTree dt, HashMap<Integer, Integer> map,
HashMap<String, ArrayList<Action>> actions, String name) {
this.sTree = st;
this.dTree = dt;
this.subMap = map;
this.actMap = actions;
this.miName = name;
}
public ITree getSRoot() {
return sTree.getRoot();
}
public ITree getDRoot() {
return dTree.getRoot();
}
public SubTree getSTree() {
return sTree;
}
public SubTree getDTree() {
return dTree;
}
public TreeContext getSrcT() {
return sTree.getTC();
}
public TreeContext getDstT() {
return dTree.getTC();
}
public int getlineNum() {
return sTree.getStNum();
}
public HashMap<Integer, Integer> getSubMap() {
return subMap;
}
public HashMap<String, ArrayList<Action>> getActMap() {
return actMap;
}
public String getMiName() {
return miName;
}
}
| 1,215
| 16.371429
| 72
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/DefuseTest.java
|
package test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import gumtreediff.actions.model.Action;
import gumtreediff.gen.srcml.SrcmlJavaTreeGenerator;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import split.Split;
import structure.Definition;
import structure.SubTree;
import utils.Defuse;
import utils.Output;
import utils.Utils;
public class DefuseTest {
public static void main (String args[]) throws Exception{
String path = "migrations_test1";
DefuseTest deftest = new DefuseTest();
deftest.collectDiffwithDefUse(path, "", true, false, "");
}
public void collectDiffwithDefUse(String path, String outMode,
Boolean ifOnlyChange, Boolean ifPrintDef, String filter) throws Exception {//获取DefUse
Split sp = new Split();
Defuse defuse = new Defuse();
String path1 = "java_test\\ClassLoadingAwareObjectInputStream.java";
String miName = path1;
File javafile1 = new File(path1);
TreeContext sTC = new SrcmlJavaTreeGenerator().generateFromFile(javafile1);
String path2 = "java_test\\ClassLoadingAwareObjectInputStream2.java";
File javafile2 = new File(path2);
TreeContext dTC = new SrcmlJavaTreeGenerator().generateFromFile(javafile2);
Matcher m = Matchers.getInstance().getMatcher(sTC.getRoot(), dTC.getRoot());
m.match();
MappingStore mappings = m.getMappings();
System.out.println("Analyse:"+miName);
String jpath = "jsons\\";
File jFile = new File(jpath);
if(!jFile.exists())
jFile.mkdirs();
int count = 0;//计数
if(jFile.listFiles().length!=0) {
throw new Exception("Plz clean dir!");
}
File output = new File("defuse.txt");
BufferedWriter wr = new BufferedWriter(new FileWriter(output));
File output1 = new File("src-val.txt");
File output2 = new File("tgt-val.txt");
BufferedWriter wr1 = new BufferedWriter(new FileWriter(output1));
BufferedWriter wr2 = new BufferedWriter(new FileWriter(output2));
int errCount = 0;
String tmpName = "";
ArrayList<SubTree> changedSTree = new ArrayList<>();
HashMap<String, LinkedList<Action>> actions = Utils.collectAction(sTC, dTC, mappings);
ArrayList<Integer> srcActIds = Utils.collectSrcActNodeIds(sTC, dTC, mappings, actions);
ArrayList<Definition> defs1 = defuse.getDef(sTC, "src");//先计算action,再收集defs
ArrayList<Definition> defs2 = defuse.getDef(dTC, "tgt");
HashMap<String, ArrayList<Definition>> defMap1 = defuse.transferDefs(defs1);
HashMap<String, ArrayList<Definition>> defMap2 = defuse.transferDefs(defs2);
HashMap<ITree, ArrayList<Definition>> blockMap1 = defuse.transferBlockMap(defs1, sTC, "src");
HashMap<ITree, ArrayList<Definition>> blockMap2 = defuse.transferBlockMap(defs2, dTC, "tgt");
ArrayList<SubTree> sub1 = sp.splitSubTree(sTC, miName);//Subtree中割裂过block,注意
ArrayList<SubTree> sub2 = sp.splitSubTree(dTC, miName);//先计算action,再split ST
System.out.println(defs1.size());
System.out.println(defs2.size());
System.out.println(defMap1.size());
System.out.println(defMap2.size());
System.out.println(blockMap1.size());
System.out.println(blockMap2.size());
for(SubTree st : sub1) {
ITree root = st.getRoot();
System.out.println("StID:"+root.getId());
if(root.getId()==822) {
List<ITree> des = root.getDescendants();
for(ITree node : des) {
System.out.println(node.getId()+","+sTC.getTypeLabel(node)+","+node.getLabel());
}
}
}
for(SubTree st : sub2) {
ITree root = st.getRoot();
// System.out.println("StID:"+root.getId());
if(root.getId()==986) {
List<ITree> des = root.getDescendants();
for(ITree node : des) {
System.out.println(node.getId()+","+dTC.getTypeLabel(node)+","+node.getLabel());
}
}
}
if(ifOnlyChange) {
for(SubTree st : sub1) {
ITree t = st.getRoot();
List<ITree> nodeList = t.getDescendants();
nodeList.add(t);
for(ITree node : nodeList) {
int id = node.getId();
if(srcActIds.contains(id)) {
changedSTree.add(st);
// System.out.println("find a action subtree!");
if(t.getId()==2256) {
System.err.println("action id:"+id);
}
break;
}
}
}//先找包含action的subtree
}else {
changedSTree = sub1;
}
System.out.println("subSize:"+sub1.size());
System.out.println("changeSize:"+changedSTree.size());
for(SubTree srcT : changedSTree) {
System.out.println("===================");
HashSet<Definition> usedDefs1 = new HashSet<>();
HashSet<Definition> usedDefs2 = new HashSet<>();
ITree sRoot = srcT.getRoot();
System.out.println("CheckMapping "+sRoot.getId()+":"+srcT.getMiName());
String src = Output.subtree2src(srcT);
if(outMode=="txt") {
if(src.contains("error")&&src.contains("situation")) {
errCount++;
continue;
}
}
Boolean same = false;
ArrayList<ITree> leaves1 = new ArrayList<>();
Utils.traverse2Leaf(sRoot, leaves1);
int labelCount = 0;
for(ITree leaf : leaves1) {
String label = leaf.getLabel();
System.out.println("label:"+label);
if(!label.equals(""))
labelCount++;
String type = sTC.getTypeLabel(leaf);
if(type.equals("literal")) {
leaf.setLabel(Output.deleteLiteral(leaf, sTC));
}
ArrayList<Definition> stringList = defMap1.get(label);
if(stringList!=null) {
ITree parBlock = defuse.searchBlock(leaf, sTC);
ArrayList<Definition> blockList = blockMap1.get(parBlock);
for(Definition def1 : stringList) {
if(blockList!=null) {
if(blockList.contains(def1)) {
if(leaf.getId()>def1.getDefLabelID()) {
leaf.setLabel("var");
usedDefs1.add(def1);
}
}
}
if(def1.getDefLabelID()==leaf.getId()) {
leaf.setLabel("var");
}
System.out.println(leaf.getId()+","+def1.getDefLabelID());
System.out.println("Def:"+def1.getType()+","+def1.getVarName());
}
}
}
if(labelCount<=0)
continue;
SubTree dstT = defuse.checkMapping(srcT, mappings, dTC, sub2);
if(dstT==null)
continue;//子树没有对应子树,被删除
ITree dRoot = dstT.getRoot();
System.out.println(sRoot.getId()+"->"+dRoot.getId());
ArrayList<ITree> leaves2 = new ArrayList<>();
Utils.traverse2Leaf(dRoot, leaves2);
for(ITree leaf : leaves2) {
String label = leaf.getLabel();
String type = dTC.getTypeLabel(leaf);
if(type.equals("literal")) {
leaf.setLabel(Output.deleteLiteral(leaf, dTC));
}
if(dRoot.getId()==226) {
System.err.println(label);
}
ArrayList<Definition> stringList = defMap2.get(label);
if(stringList!=null) {
ITree parBlock = defuse.searchBlock(leaf, dTC);
ArrayList<Definition> blockList = blockMap2.get(parBlock);
if(dRoot.getId()==226) {
System.err.println(blockList.size());
}
for(Definition def2 : stringList) {
if(blockList!=null) {
if(blockList.contains(def2)) {
if(leaf.getId()>def2.getDefLabelID()) {
usedDefs2.add(def2);
leaf.setLabel("var");
}
System.out.println(leaf.getId()+","+def2.getDefLabelID());
System.out.println(def2.getType()+","+def2.getVarName());
}
}
if(def2.getDefLabelID()==leaf.getId()) {
leaf.setLabel("var");
}
}
}
if(!same) {
for(ITree leaf1 : leaves1) {
String label1 = leaf1.getLabel();
if(label.equals(label1)) {
same = true;
}
}
}
}
src = Output.subtree2src(srcT);
String tar = Output.subtree2src(dstT);
if(outMode=="txt") {
if(tar.contains("error")&&tar.contains("situation")) {
errCount++;
continue;
}
}
if(ifOnlyChange) {
if(src.equals(tar))
continue;
}
//长度相差太多的句子直接跳过
if(((float)src.length()/(float)tar.length())<0.25||((float)tar.length()/(float)src.length())<0.25 || !same)
continue;//no leaf is the same
if(outMode=="txt") {
if(ifPrintDef) {
String buffer = "";
String buffer1 = "";
String buffer2 = "";
for(Definition def : usedDefs1) {
SubTree st = new SubTree(def.getRoot(), sTC, 0, "");
String stat = Output.subtree2src(st);
buffer = buffer +stat+" ; ";
buffer1 = buffer1 +stat+" ; ";
}
src = Output.subtree2src(srcT);
// src += String.valueOf(srcT.getRoot().getId());
buffer = buffer + src+"\t";
buffer1 += src;
for(Definition def : usedDefs2) {
SubTree st = new SubTree(def.getRoot(), dTC, 0, "");
String stat = Output.subtree2src(st);
buffer += stat+" ; ";
buffer2 += stat+" ; ";
}
tar = Output.subtree2src(dstT);
// tar += String.valueOf(dstT.getRoot().getId());
buffer += tar;
buffer2 += tar;
if(buffer.contains("error")&&buffer.contains("situation"))
continue;
wr.append(buffer);
wr1.append(buffer1);
wr2.append(buffer2);
wr1.newLine();
wr1.flush();
wr2.newLine();
wr2.flush();
wr.newLine();
wr.flush();
}else {
src += String.valueOf(srcT.getRoot().getId());
tar += String.valueOf(dstT.getRoot().getId());
String buffer = src+"\t"+tar;
if(buffer.contains("error")&&buffer.contains("situation"))
continue;
wr.append(buffer);
wr1.append(src);
wr2.append(tar);
wr1.newLine();
wr1.flush();
wr2.newLine();
wr2.flush();
wr.newLine();
wr.flush();
}
}else if(outMode=="json") {
TreeContext st = defuse.buildTC(srcT);
TreeContext dt = defuse.buildTC(dstT);
defuse.printJson(jpath, count, st, dt);
count++;
}
}
wr.close();
wr1.close();
wr2.close();
System.out.println("miname:"+tmpName);
System.out.println("errCount:"+errCount);
}
}
| 10,509
| 32.578275
| 111
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/DuplicateTest.java
|
package test;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import gumtreediff.actions.ActionGenerator;
import gumtreediff.actions.model.Action;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import split.Split;
import structure.SubTree;
import utils.Defuse;
public class DuplicateTest {
public static void main(String args[]) throws Exception{
String path = "talker.cpp";
File cppfile = new File(path);
TreeContext tc = new SrcmlCppTreeGenerator().generateFromFile(cppfile);
ITree root = tc.getRoot();
String path2 = "talker.cpp";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlCppTreeGenerator().generateFromFile(cppfile2);
ITree root2 = tc2.getRoot();
Matcher m = Matchers.getInstance().getMatcher(tc.getRoot(), tc2.getRoot());
m.match();
MappingStore mappings = m.getMappings();
HashMap<Integer, Integer> mapping = new HashMap<>();
for(Mapping map : mappings) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
// System.out.println("Mapping:"+src.getId()+"->"+dst.getId());
mapping.put(src.getId(), dst.getId());
}
System.out.println("mapSize:"+mapping.size());
Split sp = new Split();
Defuse defuse = new Defuse();
ArrayList<SubTree> sub1 = sp.splitSubTree(tc, "test");//子树相似度测试
ArrayList<SubTree> sub2 = sp.splitSubTree(tc2, "test1");//子树相似度测试
for(SubTree st1 : sub1) {
ITree sRoot1 = st1.getRoot();
ITree sRoot2 = mappings.getDst(sRoot1);
SubTree st2 = null;
for(SubTree st : sub2) {
if(st.getRoot()==sRoot2) {
st2 = st;
break;
}
}
TreeContext newTC1 = defuse.buildTC(st1);
TreeContext newTC2 = defuse.buildTC(st2);
Matcher m1 = Matchers.getInstance().getMatcher(newTC1.getRoot(), newTC2.getRoot());
m1.match();
MappingStore mappings1 = m1.getMappings();
ActionGenerator g = new ActionGenerator(newTC1.getRoot(), newTC2.getRoot(), mappings1);
List<Action> actions = g.generate();
System.out.println("ACsize:"+actions.size());
}
}
}
| 2,488
| 33.569444
| 99
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/FindBugTest.java
|
package test;
public class FindBugTest {
private static String string;
public static void main(String[] args) {
string = null;
if(string.equals("0")) {
System.out.println(string);
}
}
}
| 201
| 13.428571
| 41
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/LocateSrc.java
|
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import gumtreediff.actions.model.Action;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import split.Split;
import structure.Migration;
import structure.SubTree;
import utils.Output;
import utils.Utils;
public class LocateSrc {
public static void main (String args[]) throws Exception{
String path = "tmp\\output";
String src = "var = boost :: make_shared < du :: Updater > ( var , var , getName )";
String tgt = "this -> set_on_parameters_set_callback ( std :: bind ( & FeedforwardPid :: ReconfigCb , this , std :: placeholders :: _1 ) FeedforwardPid :: ReconfigCb , this , std :: placeholders :: _1 )";
locateSrc(path, src, tgt);
}
public static void locateSrc(String path, String srcString, String tgtString) throws Exception {
Split sp = new Split();
ArrayList<Migration> migrats = sp.readMigration(path, "");
for(Migration migrat : migrats) {
HashMap<String, ArrayList<Integer>> sDefMap = new HashMap<>();
HashMap<String, ArrayList<Integer>> dDefMap = new HashMap<>();
HashMap<Integer, SubTree> stMap = new HashMap<>();
HashMap<Integer, SubTree> dtMap = new HashMap<>();
String miName = migrat.getMiName();
TreeContext sTC = migrat.getSrcT();
TreeContext dTC = migrat.getDstT();
MappingStore mappings = migrat.getMappings();
System.out.println("Analyse:"+miName);
Matcher m = Matchers.getInstance().getMatcher(sTC.getRoot(), dTC.getRoot());
m.match();
ArrayList<SubTree> changedSTree = new ArrayList<>();
HashMap<String, LinkedList<Action>> actions = Utils.collectAction(sTC, dTC, mappings);
ArrayList<Integer> srcActIds = Utils.collectSrcActNodeIds(sTC, dTC, mappings, actions);
ArrayList<SubTree> sub1 = sp.splitSubTree(sTC, miName);//Subtree中割裂过block,注意
ArrayList<SubTree> sub2 = sp.splitSubTree(dTC, miName);//先计算action,再split ST
for(SubTree st : sub1) {
ITree t = st.getRoot();
List<ITree> nodeList = t.getDescendants();
nodeList.add(t);
for(ITree node : nodeList) {
int id = node.getId();
if(srcActIds.contains(id)) {
changedSTree.add(st);
// System.out.println("find a action subtree!");
break;
}
}
}//先找包含action的subtree
for(SubTree st : sub1) {
ITree sRoot = st.getRoot();
String sType = sTC.getTypeLabel(sRoot);
if(sType.equals("decl_stmt")) {
List<ITree> children = sRoot.getChildren();
for(ITree root : children) {
if(sTC.getTypeLabel(root).equals("decl")) {
List<ITree> childs = root.getChildren();
for(ITree child : childs) {
String type = sTC.getTypeLabel(child);
if(type.equals("name")) {//只有decl下的name节点的value才被认为是一条def
String label = child.getLabel();
int sID = sRoot.getId();
stMap.put(sID, st);
if(sDefMap.get(label)==null) {
ArrayList<Integer> ids = new ArrayList<>();
ids.add(sID);
sDefMap.put(label, ids);
}else {
sDefMap.get(label).add(sID);
}
}
}
}else {
throw new Exception("error type!"+sTC.getTypeLabel(root));
}
}
}
}
for(SubTree dt : sub2) {
ITree dRoot = dt.getRoot();
String dType = sTC.getTypeLabel(dRoot);
if(dType.equals("decl_stmt")) {
List<ITree> children = dRoot.getChildren();
for(ITree root : children) {
if(sTC.getTypeLabel(root).equals("decl")) {
List<ITree> childs = root.getChildren();
for(ITree child : childs) {
String type = dTC.getTypeLabel(child);
if(type.equals("name")) {//只有decl下的name节点的value才被认为是一条def
String label = child.getLabel();
int dID = dRoot.getId();
dtMap.put(dID, dt);
if(dDefMap.get(label)==null) {
ArrayList<Integer> ids = new ArrayList<>();
ids.add(dID);
dDefMap.put(label, ids);
}else {
dDefMap.get(label).add(dID);
}
}
}
}
}
}
}
for(SubTree srcT : changedSTree) {
HashMap<String, SubTree> sMap = new HashMap<>();
HashMap<String, SubTree> dMap = new HashMap<>();
ArrayList<SubTree> sDef = new ArrayList<>();
ArrayList<SubTree> dDef = new ArrayList<>();
ArrayList<String> commonDef = new ArrayList<>();//change pair的def交集
HashMap<String, String> varMap = new HashMap<>();//change pair的def总集
ITree sRoot = srcT.getRoot();
ITree dRoot = mappings.getDst(sRoot);
SubTree dstT = null;
if(dRoot==null) {
continue;
}else {//根据mapping来找dt
for(SubTree dt : sub2) {
ITree root = dt.getRoot();
if(root.equals(dRoot)) {
dstT = dt;
break;
}
}
}
if(dstT==null) {
throw new Exception("why is null?");
}
String src = Output.subtree2src(srcT);
String tar = Output.subtree2src(dstT);
if((src.contains("error")&&src.contains("situation")) || (tar.contains("error")&&tar.contains("situation")))
continue;
if(((float)src.length()/(float)tar.length())<0.25||((float)tar.length()/(float)src.length())<0.25) {
continue;
}//长度相差太多的句子直接跳过
String sType = sTC.getTypeLabel(sRoot);
String dType = dTC.getTypeLabel(dRoot);
if(!sType.equals("decl_stmt")&&!dType.equals("decl_stmt")) {
List<ITree> sLeaves = new ArrayList<>();
Utils.traverse2Leaf(sRoot, sLeaves);
List<ITree> dLeaves = new ArrayList<>();
Utils.traverse2Leaf(dRoot, dLeaves);
for(ITree leaf : sLeaves) {
String type = sTC.getTypeLabel(leaf);
if(type.equals("name")) {
String label = leaf.getLabel();
ArrayList<Integer> map = sDefMap.get(label);
if(map!=null) {
if(map.size()==1) {
int defID = map.get(0);
SubTree st = stMap.get(defID);
sMap.put(label, st);
}else {//发现有多个def line同一个关键字的情况,可能发生在不同的method
Collections.sort(map);
ArrayList<Integer> subMap = new ArrayList<>();
for(int id : map) {//只取该条语句之前的subtree,抛弃掉之后的
if(id<sRoot.getId())
subMap.add(id);
}
if(subMap.size()==0)
continue;//好像有defid全在rootid之后的情况,跳过
int defID = subMap.get(subMap.size()-1);//取离该def最近的
SubTree st = stMap.get(defID);
sMap.put(label, st);
}
}
}
}
for(ITree leaf : dLeaves) {
String type = dTC.getTypeLabel(leaf);
if(type.equals("name")) {
String label = leaf.getLabel();
ArrayList<Integer> map = dDefMap.get(label);
if(map!=null) {
if(map.size()==1) {
int defID = map.get(0);
SubTree st = dtMap.get(defID);
dMap.put(label, st);
}else {
Collections.sort(map);
ArrayList<Integer> subMap = new ArrayList<>();
for(int id : map) {//只取该条语句之前的subtree,抛弃掉之后的
if(id<dRoot.getId())
subMap.add(id);
}
if(subMap.size()==0)
continue;//好像有defid全在rootid之后的情况,跳过
int defID = subMap.get(subMap.size()-1);//取离该def最近的
SubTree st = dtMap.get(defID);
dMap.put(label, st);
}
}
}
}
if(sMap.size()>dMap.size()) {
for(Map.Entry<String, SubTree> entry : dMap.entrySet()) {
String keyword = entry.getKey();
SubTree dt = entry.getValue();
if(sMap.containsKey(keyword)) {//sMap和dMap取keyword交集
sDef.add(sMap.get(keyword));
dDef.add(dt);
commonDef.add(keyword);//共有的keyword放到commonDef
String absVarName = "var";
varMap.put(keyword, absVarName);//共有的keyword放到varMap
}
}
}else {
for(Map.Entry<String, SubTree> entry : sMap.entrySet()) {
String keyword = entry.getKey();
SubTree st = entry.getValue();
if(dMap.containsKey(keyword)) {//sMap和dMap取keyword交集
dDef.add(dMap.get(keyword));
sDef.add(st);
commonDef.add(keyword);//共有的keyword放到commonDef
String absVarName = "var";
varMap.put(keyword, absVarName);//共有的keyword放到varMap
}
}
}//change pair的DefMap取交集
for(Map.Entry<String, SubTree> entry : dMap.entrySet()) {
String keyword = entry.getKey();
if(!varMap.containsKey(keyword)) {
String absVarName = "var";
varMap.put(keyword, absVarName);//共有的keyword放到varMap
}
}
for(Map.Entry<String, SubTree> entry : sMap.entrySet()) {
String keyword = entry.getKey();
if(!varMap.containsKey(keyword)) {//sMap和dMap取keyword交集
String absVarName = "var";
varMap.put(keyword, absVarName);//共有的keyword放到varMap
}
}//私有def分别放入varMap
String sLine = Output.subtree2src(srcT);
sLine = Output.absVariable(sLine, varMap);
if(sLine.equals(srcString)) {
System.out.println("Find src");
System.out.println(srcT.getMiName());
System.out.println(srcT.getRoot().getLine()+","+srcT.getRoot().getColumn());
}
String dLine = Output.subtree2src(dstT);
dLine = Output.absVariable(dLine, varMap);
if(dLine.equals(tgtString)) {
System.out.println("Find tgt");
System.out.println(dstT.getMiName());
System.out.println(dstT.getRoot().getLine()+","+dstT.getRoot().getColumn());
}
}else {
List<ITree> sLeaves = new ArrayList<>();
Utils.traverse2Leaf(sRoot, sLeaves);
List<ITree> dLeaves = new ArrayList<>();
Utils.traverse2Leaf(dRoot, dLeaves);
for(ITree leaf : sLeaves) {
String label = leaf.getLabel();
if(sDefMap.containsKey(label)) {
ArrayList<Integer> map = sDefMap.get(label);
if(map!=null) {
if(map.size()==1) {
int defID = map.get(0);
SubTree st = stMap.get(defID);
sMap.put(label, st);
}else {//发现有多个def line同一个关键字的情况,可能发生在不同的method
for(int id : map) {//只取该条语句的subtree
if(id==sRoot.getId()) {
SubTree st = stMap.get(id);
sMap.put(label, st);
break;
}
}
}
}
}
}
for(ITree leaf : dLeaves) {
String label = leaf.getLabel();
if(dDefMap.containsKey(label)) {
ArrayList<Integer> map = dDefMap.get(label);
if(map!=null) {
if(map.size()==1) {
int defID = map.get(0);
SubTree dt = dtMap.get(defID);
dMap.put(label, dt);
}else {//发现有多个def line同一个关键字的情况,可能发生在不同的method
for(int id : map) {//只取该条语句的subtree
if(id==dRoot.getId()) {
SubTree dt = dtMap.get(id);
dMap.put(label, dt);
break;
}
}
}
}
}
}
for(Map.Entry<String, SubTree> entry : sMap.entrySet()) {
String keyword = entry.getKey();
if(!varMap.containsKey(keyword)) {//sMap和dMap取keyword交集
String absVarName = "var";
varMap.put(keyword, absVarName);//共有的keyword放到varMap
}
}
for(Map.Entry<String, SubTree> entry : dMap.entrySet()) {
String keyword = entry.getKey();
if(!varMap.containsKey(keyword)) {
String absVarName = "var";
varMap.put(keyword, absVarName);//共有的keyword放到varMap
}
}//私有def分别放入varMap
String sLine = Output.subtree2src(srcT);
sLine = Output.absVariable(sLine, varMap);
if(sLine.equals(srcString)) {
System.out.println("Find src");
System.out.println(srcT.getMiName());
System.out.println(srcT.getRoot().getLine()+","+srcT.getRoot().getColumn());
}
String dLine = Output.subtree2src(dstT);
dLine = Output.absVariable(dLine, varMap);
if(dLine.equals(tgtString)) {
System.out.println("Find tgt");
System.out.println(dstT.getMiName());
System.out.println(dstT.getRoot().getLine()+","+dstT.getRoot().getColumn());
}
}
}
}
}
}
| 12,132
| 33.46875
| 207
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/RandomTest.java
|
package test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import split.Split;
import structure.Migration;
import structure.SubTree;
import structure.Transform;
import utils.Output;
public class RandomTest {
public static void main (String args[]) throws Exception{
Split sp = new Split();
ArrayList<Migration> migrats = new ArrayList<>();
migrats = sp.readMigration("migrations", "");
sp.storeTrans(migrats);
ArrayList<Transform> trans = sp.trans;
ArrayList<String> counts = new ArrayList<>();
File file1 = new File("srcTest.txt");
BufferedWriter wr1 = new BufferedWriter(new FileWriter(file1));
File file2 = new File("dstTest.txt");
BufferedWriter wr2 = new BufferedWriter(new FileWriter(file2));
if(trans.size()<100) {
System.err.println("error");
}else {
int[] randoms = randomNumber(0, trans.size()-1, 150);
for (int random : randoms) {
Transform tf = trans.get(random);
SubTree sDT = tf.getSTree();
SubTree dDT = tf.getDTree();
if(sDT!=null&&dDT!=null) {
if(sDT.getTC()!=null&&dDT.getTC()!=null) {
String srcLine = Output.subtree2src(sDT);
String dstLine = Output.subtree2src(dDT);
if(((float)srcLine.length()/(float)dstLine.length())<0.25||((float)srcLine.length()/(float)dstLine.length())<0.25) {
continue;
}//长度相差太多的句子直接跳过
wr1.append(srcLine);
wr1.newLine();
wr1.flush();
wr2.append(dstLine);
wr2.newLine();
wr2.flush();
counts.add(srcLine);
if (counts.size()==100) {
break;
}
}
}
}
}
wr1.close();
wr2.close();
}
/**
* 功能:产生min-max中的n个不重复的随机数
*
* min:产生随机数的其实位置
* mab:产生随机数的最大位置
* n: 所要产生多少个随机数
*
*/
public static int[] randomNumber(int min,int max,int n){
//判断是否已经达到索要输出随机数的个数
if(n>(max-min+1) || max <min){
return null;
}
int[] result = new int[n]; //用于存放结果的数组
int count = 0;
while(count <n){
int num = (int)(Math.random()*(max-min))+min;
boolean flag = true;
for(int j=0;j<count;j++){
if(num == result[j]){
flag = false;
break;
}
}
if(flag){
result[count] = num;
count++;
}
}
return result;
}
}
| 2,599
| 26.083333
| 131
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/SubtreeTest.java
|
package test;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.gen.srcml.SrcmlJavaTreeGenerator;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import gumtreediff.tree.TreeUtils;
import split.Split;
import structure.SubTree;
import utils.Similarity;
import utils.Utils;
public class SubtreeTest {
public static void main (String args[]) throws Exception{
String path1 = "java_test\\BZip2CompressorOutputStream.java";
File cppfile = new File(path1);
TreeContext tc1 = new SrcmlJavaTreeGenerator().generateFromFile(cppfile);
ITree root1 = tc1.getRoot();
List<ITree> des1 = root1.getDescendants();
String miName = path1.split("/")[path1.split("/").length-1];//标记文件名
String path2 = "java_test\\BZip2CompressorOutputStream2.java";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlJavaTreeGenerator().generateFromFile(cppfile2);
Split sp = new Split();
Matcher m = Matchers.getInstance().getMatcher(tc1.getRoot(), tc2.getRoot());
m.match();
MappingStore mappings = m.getMappings();
ArrayList<SubTree> sts1 = sp.splitSubTree(tc1, miName);
ArrayList<SubTree> sts2 = sp.splitSubTree(tc2, miName);
String search_string = "blockSort";
String[] tmps = search_string.split(" ");
List<String> labels = Arrays.asList(tmps);
searchSubtree(labels, sts1);
// ITree sRoot = searchNode(69, des1);
// ITree dRoot = mappings.getDst(sRoot);
// System.out.println(dRoot.getId());
// BufferedWriter wr = new BufferedWriter(new FileWriter(new File("mapping.txt")));
// for(Mapping map : mappings) {
// ITree src = map.getFirst();
// ITree dst = map.getSecond();
// wr.append(src.getId()+"->"+dst.getId());
// wr.newLine();
//// System.out.println("Mapping:"+src.getId()+"->"+dst.getId());
//// if(dst.getId()==553) {
//// System.err.println("find it!"+src.getId());
//// }
// }
// wr.close();
// System.out.println("Msize:"+mappings.asSet().size());
// for(SubTree st : sts1) {
// ITree root = st.getRoot();
// System.out.println("StID:"+root.getId()+":"+root.getLine()+","+root.getColumn()+
// "->"+root.getLastLine()+","+root.getLastColumn()+" Len:"+root.getLength());
// List<ITree> des = root.getDescendants();
// for(ITree node : des) {
// System.out.println(node.getId()+":"+node.getLine()+","+node.getColumn()+
// "->"+node.getLastLine()+","+node.getLastColumn()+" Len:"+node.getLength());
// }
//// if(root.getId()==41) {
//// for(ITree node : root.postOrder()) {
//// System.out.println("ID:"+node.getId());
//// }
//// List<ITree> des = root.getDescendants();
//// for(ITree node : des) {
//// System.out.println(node.getId());
//// ITree dst = mappings.getDst(node);
//// if(dst!=null)
//// System.out.println(node.getId()+"->"+dst.getId());
//// }
//// }
// }
// System.out.println("-----");
// for(SubTree st : sts2) {
// ITree root = st.getRoot();
// String dst = Output.subtree2src(st);
//// System.out.println(dst);
// }
}
public static ITree searchNode(int id, List<ITree> des) {
for(ITree node : des) {
int nodeID = node.getId();
if(id==nodeID)
return node;
}
return null;
}
public static void searchSubtree(List<String> labels, ArrayList<SubTree> sts) throws Exception {
for(SubTree st : sts) {
float matchNum = 0;
ITree sRoot = st.getRoot();
List<ITree> leaves = new ArrayList<>();
String print = "";
leaves = Utils.traverse2Leaf(sRoot, leaves);
for(ITree leaf : leaves) {
String label = leaf.getLabel();
if (labels.contains(label)) {
matchNum++;
}
}
float sim = matchNum/leaves.size();
if(sim>0.9) {
System.err.println("Find matched subtree: "+sRoot.getId());
for(ITree leaf : leaves) {
print += leaf.getLabel()+" ";
}
System.out.println(print);
}
}
}
public static void breakBlock() throws Exception {
String path = "talker.cpp";
File cppfile = new File(path);
TreeContext tc1 = new SrcmlCppTreeGenerator().generateFromFile(cppfile);
Split sp = new Split();
ArrayList<SubTree> sts = sp.splitSubTree(tc1, path);
System.out.println(sts.size());
for(SubTree st : sts) {
ITree sRoot = st.getRoot();
if(tc1.getTypeLabel(sRoot).equals("while")) {
String srcTree = Similarity.transfer2string(st);
System.out.println(srcTree);
List<ITree> list = TreeUtils.preOrder(st.getRoot());
for(ITree tmp : list) {
String type = tc1.getTypeLabel(tmp);
if(type.equals("block")) {
List<ITree> childs = sRoot.getChildren();
System.out.println(childs.size());
childs.remove(tmp);
System.out.println(sRoot.getChildren().size());
sRoot.setChildren(childs);
tmp.setParent(null);//断开所有block node和父亲的连接
}
}
String srcTree1 = Similarity.transfer2string(st);
System.out.println(srcTree1);
}
}
}
}
| 5,403
| 33.864516
| 97
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/Test.java
|
package test;
import java.io.File;
import java.util.List;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
public class Test {
public static void main (String args[]) throws Exception{
String path = "talker.cpp";
File cppfile = new File(path);
TreeContext tc1 = new SrcmlCppTreeGenerator().generateFromFile(cppfile);
ITree root1 = tc1.getRoot();
String path2 = "talker2.cpp";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlCppTreeGenerator().generateFromFile(cppfile2);
ITree root2 = tc2.getRoot();
Matcher m = Matchers.getInstance().getMatcher(tc1.getRoot(), tc2.getRoot());
m.match();
MappingStore mappings = m.getMappings();
List<ITree> list1 = root1.getDescendants();
for(ITree tmp : list1) {
if(tmp.getId()==87) {
ITree dst = mappings.getDst(tmp);
if(tmp.isIsomorphicTo(dst))
System.out.println("Is iso");
else
System.out.println("Not iso");
String type1 = tc1.getTypeLabel(tmp);
String type2 = tc2.getTypeLabel(dst);
String value1 = tmp.getLabel();
String value2 = dst.getLabel();
System.out.println(type1+","+type2+","+value1+","+value2);
if(type1.equals(type2)&&value1.equals(value2)) {
System.out.println(true);
}else {
System.out.println(false);
}
}
}
String test1 = "";
String test2 = null;
if(test1.equals(test2))
System.out.println(true);
else
System.out.println(false);
String test3 = "test st";
test3 = test3.substring(0, test3.length()-1);
System.out.println(test3);
}
}
| 1,733
| 27.42623
| 84
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/TestGeneration.java
|
package test;
import gumtreediff.actions.ActionGenerator;
import gumtreediff.actions.model.Action;
import gumtreediff.gen.srcml.SrcmlJavaTreeGenerator;
import gumtreediff.io.ActionsIoUtils;
import gumtreediff.io.TreeIoUtils;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import utils.Utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TestGeneration {
public static void main(String args[]) throws Exception{
String path = "AbstractBuild1.java";
// String path = "AccountInstance.java";
// String path = "migrations_test\\astra_driver\\astra_driver.cpp";
File cppfile = new File(path);
TreeContext tc = new SrcmlJavaTreeGenerator().generateFromFile(cppfile);
ITree root = tc.getRoot();
String json = "src.json";
BufferedWriter wr_json1 = new BufferedWriter(new FileWriter(new File(json)));
wr_json1.append(TreeIoUtils.toJson(tc).toString());
wr_json1.flush();
wr_json1.close();
System.out.println(root.getId()+","+tc.getTypeLabel(root)+","+root.getChildren().size());
String path2 = "AbstractBuild2.java";
// String path2 = "AccountInstance2.java";
// String path2 = "migrations_test\\astra_driver\\astra_driver2.cpp";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlJavaTreeGenerator().generateFromFile(cppfile2);
ITree root2 = tc2.getRoot();
// json = "des.json";
// BufferedWriter wr_json2 = new BufferedWriter(new FileWriter(new File(json)));
// wr_json2.append(TreeIoUtils.toJson(tc2).toString());
// wr_json2.flush();
// wr_json2.close();
// System.out.println(root2.getId()+","+tc2.getTypeLabel(root2));
Matcher m = Matchers.getInstance().getMatcher(tc.getRoot(), tc2.getRoot());
m.match();
MappingStore mappings = m.getMappings();
HashMap<Integer, Integer> mapping = new HashMap<>();
for(Mapping map : mappings) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
// System.out.println("Mapping:"+src.getId()+"->"+dst.getId());
mapping.put(src.getId(), dst.getId());
}
System.out.println("mapSize:"+mapping.size());
HashMap<Integer, Integer> mapping1 = new HashMap<>();
for(Mapping map : m.getMappings()) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
// System.out.println(src.getId()+"->"+dst.getId());
mapping1.put(src.getId(), dst.getId());
}
System.out.println("mapSize:"+mapping1.size());
ActionGenerator g = new ActionGenerator(tc.getRoot(), tc2.getRoot(), m.getMappings());
List<Action> actions = g.generate();
String out1 = "testMapping.txt";
BufferedWriter wr1 = new BufferedWriter(new FileWriter(out1));
// System.out.println(ActionsIoUtils.toJson(tc, g.getActions(), m.getMappings()).toString());
wr1.append(ActionsIoUtils.toXml(tc, g.getActions(), m.getMappings()).toString());
wr1.flush();
wr1.close();
// ITree root3 = tc2.getRoot();
// System.out.println(root3.getId()+","+tc2.getTypeLabel(root3));
// if(root3.getParent()==null)
// System.out.println(true);
// else System.out.println(false);
Utils.checkTCRoot(tc);
Utils.checkTCRoot(tc2);
// Pruning pt = new Pruning(tc, tc2, mappings);
// pt.pruneTree();//Prune the tree.
String out = "testGraph.txt";
BufferedWriter wr = new BufferedWriter(new FileWriter(out));
wr.append(TreeIoUtils.toDetailedDot(tc, mappings, actions, true).toString());
// wr.append(TreeIoUtils.toDot2(tc).toString());
wr.flush();
wr.close();
String out2 = "testGraph2.txt";
BufferedWriter wr2 = new BufferedWriter(new FileWriter(out2));
wr2.append(TreeIoUtils.toDetailedDot(tc2, mappings, actions, false).toString());
// wr2.append(TreeIoUtils.toDot2(tc2).toString());
wr2.flush();
wr2.close();
// System.out.println(TreeIoUtils.toDot(tc, mappings, actions, true).toString());
// System.out.println(TreeIoUtils.toDot(tc2, mappings, actions, false).toString());
// System.out.println(TreeIoUtils.toXml(tc).toString());
// for(Map.Entry<Integer, Integer> entry : mapping.entrySet()) {
// System.out.println(entry.getKey()+"->"+entry.getValue());
// }
System.out.println("ActionSize:" + actions.size());
// for (Action a : actions) {
// ITree src = a.getNode();
// if (a instanceof Move) {
// ITree dst = mappings.getDst(src);
// System.out.println(((Move)a).toString());
// } else if (a instanceof Update) {
// ITree dst = mappings.getDst(src);
// System.out.println(((Update)a).toString());
// } else if (a instanceof Insert) {
// ITree dst = a.getNode();
// System.out.println(((Insert)a).toString());
// } else if (a instanceof Delete) {
// System.out.println(((Delete)a).toString());
// }
// }
// System.out.println(ActionsIoUtils.toXml(tc, g.getActions(), m.getMappings()).toString());
// System.out.println(ActionsIoUtils.toText(tc, g.getActions(), m.getMappings()).toString());
// for(ITree c : t.getChildren()) {
// if(c.getLabel()!=null)
// System.out.println(c.getLabel());
// }
List<ITree> nodes = new ArrayList<>();
nodes = Utils.collectNode(tc2.getRoot(), nodes);
System.out.println(nodes.size());
}
}
| 5,823
| 39.165517
| 100
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/TestJdtCore.java
|
package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
public class TestJdtCore {
public static void main(String args[]) throws Exception{
String path = "AccountInstance.java";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
char[] test = ReadFileToCharArray(path);
parser.setSource(test); // set source
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit cu = (CompilationUnit) parser.createAST(null /* IProgressMonitor */); // parse
System.out.println(cu);
}
public static char[] ReadFileToCharArray(String filePath) throws IOException {
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[10];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
System.out.println(numRead);
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString().toCharArray();
}
}
| 1,250
| 28.785714
| 96
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/TestJdtGeneration.java
|
package test;
import gumtreediff.actions.ActionGenerator;
import gumtreediff.actions.model.Action;
import gumtreediff.gen.srcml.SrcmlJavaTreeGenerator;
import gumtreediff.io.ActionsIoUtils;
import gumtreediff.io.TreeIoUtils;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import utils.Utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TestJdtGeneration {
public static void main(String args[]) throws Exception{
String path = "java_test\\SimpleBindRequest.java";
File javafile = new File(path);
TreeContext tc = new SrcmlJavaTreeGenerator().generateFromFile(javafile);
String json = "testGraph.json";
BufferedWriter jw = new BufferedWriter(new FileWriter(json));
jw.append(TreeIoUtils.toXml(tc).toString());
jw.close();
ITree root = tc.getRoot();
System.out.println(root.getId()+","+tc.getTypeLabel(root));
String path2 = "java_test\\SimpleBindRequest2.java";
File javafile2 = new File(path2);
TreeContext tc2 = new SrcmlJavaTreeGenerator().generateFromFile(javafile2);
ITree root2 = tc2.getRoot();
System.out.println(root2.getId()+","+tc2.getTypeLabel(root2));
Matcher m = Matchers.getInstance().getMatcher(tc.getRoot(), tc2.getRoot());
m.match();
MappingStore mappings = m.getMappings();
HashMap<Integer, Integer> mapping = new HashMap<>();
for(Mapping map : mappings) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
// System.out.println("Mapping:"+src.getId()+"->"+dst.getId());
mapping.put(src.getId(), dst.getId());
}
System.out.println("mapSize:"+mapping.size());
ActionGenerator g = new ActionGenerator(tc.getRoot(), tc2.getRoot(), m.getMappings());
List<Action> actions = g.generate();
String out1 = "testMapping.txt";
BufferedWriter wr1 = new BufferedWriter(new FileWriter(out1));
// System.out.println(ActionsIoUtils.toJson(tc, g.getActions(), m.getMappings()).toString());
wr1.append(ActionsIoUtils.toXml(tc, g.getActions(), m.getMappings()).toString());
wr1.flush();
wr1.close();
// ITree root3 = tc2.getRoot();
// System.out.println(root3.getId()+","+tc2.getTypeLabel(root3));
// if(root3.getParent()==null)
// System.out.println(true);
// else System.out.println(false);
// Pruning pt = new Pruning(tc, tc2, mappings);
// pt.pruneTree();//Prune the tree.
String out = "testGraph.txt";
BufferedWriter wr = new BufferedWriter(new FileWriter(out));
// wr.append(TreeIoUtils.toXml(tc).toString());
wr.append(TreeIoUtils.toDot(tc, mappings, actions, true).toString());
wr.flush();
wr.close();
String out2 = "testGraph2.txt";
BufferedWriter wr2 = new BufferedWriter(new FileWriter(out2));
wr2.append(TreeIoUtils.toDot(tc2, mappings, actions, false).toString());
wr2.flush();
wr2.close();
// for (Action a : actions) {
// ITree src = a.getNode();
// if (a instanceof Move) {
// ITree dst = mappings.getDst(src);
// System.out.println(((Move)a).toString());
// } else if (a instanceof Update) {
// ITree dst = mappings.getDst(src);
// System.out.println(((Update)a).toString());
// } else if (a instanceof Insert) {
// ITree dst = a.getNode();
// System.out.println(((Insert)a).toString());
// } else if (a instanceof Delete) {
// System.out.println(((Delete)a).toString());
// }
// }
// System.out.println(ActionsIoUtils.toXml(tc, g.getActions(), m.getMappings()).toString());
// System.out.println(ActionsIoUtils.toText(tc, g.getActions(), m.getMappings()).toString());
// for(ITree c : t.getChildren()) {
// if(c.getLabel()!=null)
// System.out.println(c.getLabel());
// }
List<ITree> nodes = new ArrayList<>();
nodes = Utils.collectNode(tc2.getRoot(), nodes);
System.out.println(nodes.size());
}
}
| 4,405
| 38.693694
| 100
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/TestPrediction.java
|
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class TestPrediction {
public static void main(String args[]) throws Exception{
ArrayList<String> preds = new ArrayList<>();
ArrayList<String> tgts = new ArrayList<>();
BufferedWriter wr = new BufferedWriter(new FileWriter(new File("check.txt")));
BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File("validate.txt")));
File pred = new File("pred.txt");
BufferedReader br = new BufferedReader(new FileReader(pred));
String tmpline = "";
while((tmpline = br.readLine())!=null) {
preds.add(tmpline);
}
File tgt = new File("tgt-train.txt");
BufferedReader br1 = new BufferedReader(new FileReader(tgt));
while((tmpline = br1.readLine())!=null) {
tgts.add(tmpline);
}
for(int i=0;i<preds.size();i++) {
String tmp1 = preds.get(i);
String tmp2 = tgts.get(i);
if(!tmp1.equals(tmp2)) {
wr.append(tmp1);
wr.newLine();
wr1.append(tmp2);
wr1.newLine();
}
}
br.close();
br1.close();
wr.close();
wr1.close();
}
}
| 1,173
| 25.681818
| 84
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/test/test1.java
|
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class test1 {
public static void main(String args[]) throws Exception{
Map<String, Integer> map = new TreeMap<>();
map.put("a", 2);
map.put("b", 3);
map.put("c", 1);
// 通过ArrayList构造函数把map.entrySet()转换成list
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
// 通过比较器实现比较排序
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> mapping1, Map.Entry<String, Integer> mapping2) {
return mapping2.getValue().compareTo(mapping1.getValue());
}
});
for(Map.Entry<String,Integer> mapping:list){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
}
}
| 973
| 25.324324
| 97
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/Defuse.java
|
package utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import gumtreediff.actions.model.Action;
import gumtreediff.io.TreeIoUtils;
import gumtreediff.matchers.MappingStore;
import gumtreediff.tree.ITree;
import gumtreediff.tree.Tree;
import gumtreediff.tree.TreeContext;
import split.Split;
import structure.Definition;
import structure.Migration;
import structure.SubTree;
public class Defuse {
public ArrayList<ITree> blocks1 = new ArrayList<>();
public ArrayList<ITree> blocks2 = new ArrayList<>();
public HashMap<ITree, ArrayList<ITree>> parBlockMap1 = new HashMap<>();
public HashMap<ITree, ArrayList<ITree>> parBlockMap2 = new HashMap<>();
public ArrayList<Definition> globalDefs1 = new ArrayList<>();
public ArrayList<Definition> globalDefs2 = new ArrayList<>();
public ArrayList<Definition> defs1 = new ArrayList<>();
public ArrayList<Definition> defs2 = new ArrayList<>();
public static void main (String args[]) throws Exception{
String path = "migrations_test1";
Defuse defuse = new Defuse();
defuse.collectDiffwithDefUse(path, "txt", true, false, "");
}
public void collectDiffwithDefUse(String path, String outMode,
Boolean ifOnlyChange, Boolean ifPrintDef, String filter) throws Exception {//获取DefUse
Split sp = new Split();
ArrayList<Migration> migrats = sp.readMigration(path, filter);
String jpath = "jsons\\";
File jFile = new File(jpath);
if(!jFile.exists())
jFile.mkdirs();
int count = 0;//计数
if(jFile.listFiles().length!=0) {
throw new Exception("Plz clean dir!");
}
File output = new File("defuse.txt");
BufferedWriter wr = new BufferedWriter(new FileWriter(output));
File output1 = new File("src-val.txt");
File output2 = new File("tgt-val.txt");
BufferedWriter wr1 = new BufferedWriter(new FileWriter(output1));
BufferedWriter wr2 = new BufferedWriter(new FileWriter(output2));
// ArrayList<String> includes1 = readIncludes("src");
// ArrayList<String> includes2 = readIncludes("dst");
// for(String include : includes1) {
// wr1.append(include);
// wr1.newLine();
// wr1.flush();
// }
// for(String include : includes2) {
// wr2.append(include);
// wr2.newLine();
// wr2.flush();
// }
int errCount = 0;
String tmpName = "";
for(Migration migrat : migrats) {
blocks1.clear();
blocks2.clear();
parBlockMap1.clear();
parBlockMap2.clear();
String miName = migrat.getMiName();
TreeContext sTC = migrat.getSrcT();
TreeContext dTC = migrat.getDstT();
MappingStore mappings = migrat.getMappings();
System.out.println("Analyse:"+miName);
ArrayList<SubTree> changedSTree = new ArrayList<>();
HashMap<String, LinkedList<Action>> actions = Utils.collectAction(sTC, dTC, mappings);
ArrayList<Integer> srcActIds = Utils.collectSrcActNodeIds(sTC, dTC, mappings, actions);
ArrayList<Definition> defs1 = getDef(sTC, "src");//先计算action,再收集defs
ArrayList<Definition> defs2 = getDef(dTC, "tgt");
HashMap<String, ArrayList<Definition>> defMap1 = transferDefs(defs1);
HashMap<String, ArrayList<Definition>> defMap2 = transferDefs(defs2);
HashMap<ITree, ArrayList<Definition>> blockMap1 = transferBlockMap(defs1, sTC, "src");
HashMap<ITree, ArrayList<Definition>> blockMap2 = transferBlockMap(defs2, dTC, "tgt");
ArrayList<SubTree> sub1 = sp.splitSubTree(sTC, miName);//Subtree中割裂过block,注意
ArrayList<SubTree> sub2 = sp.splitSubTree(dTC, miName);//先计算action,再split ST
System.out.println(defs1.size());
System.out.println(defs2.size());
System.out.println(defMap1.size());
System.out.println(defMap2.size());
System.out.println(blockMap1.size());
System.out.println(blockMap2.size());
for(SubTree st : sub1) {
ITree root = st.getRoot();
System.out.println("StID:"+root.getId());
}
if(ifOnlyChange) {
for(SubTree st : sub1) {
ITree t = st.getRoot();
List<ITree> nodeList = t.getDescendants();
nodeList.add(t);
for(ITree node : nodeList) {
int id = node.getId();
if(srcActIds.contains(id)) {
changedSTree.add(st);
// System.out.println("find a action subtree!");
break;
}
}
}//先找包含action的subtree
}else {
changedSTree = sub1;
}
System.out.println("subSize:"+sub1.size());
System.out.println("changeSize:"+changedSTree.size());
for(SubTree srcT : changedSTree) {
System.out.println("===================");
HashSet<Definition> usedDefs1 = new HashSet<>();
HashSet<Definition> usedDefs2 = new HashSet<>();
ITree sRoot = srcT.getRoot();
System.out.println("CheckMapping "+sRoot.getId()+":"+srcT.getMiName());
String src = Output.subtree2src(srcT);
if(outMode=="txt") {
if(src.contains("error")&&src.contains("situation")) {
errCount++;
continue;
}
}
Boolean same = false;
ArrayList<ITree> leaves1 = new ArrayList<>();
Utils.traverse2Leaf(sRoot, leaves1);
int labelCount = 0;
for(ITree leaf : leaves1) {
String label = leaf.getLabel();
System.out.println("label"+label);
if(!label.equals(""))
labelCount++;
String type = sTC.getTypeLabel(leaf);
if(type.equals("literal")) {
leaf.setLabel(Output.deleteLiteral(leaf, sTC));
}
ArrayList<Definition> stringList = defMap1.get(label);
if(stringList!=null) {
ITree parBlock = searchBlock(leaf, sTC);
ArrayList<Definition> blockList = blockMap1.get(parBlock);
for(Definition def1 : stringList) {
if(blockList!=null) {
if(blockList.contains(def1)) {
if(leaf.getId()>def1.getDefLabelID()) {
leaf.setLabel("var");
usedDefs1.add(def1);
}
}
}
if(def1.getDefLabelID()==leaf.getId()) {
leaf.setLabel("var");
}
System.out.println(leaf.getId()+","+def1.getDefLabelID());
System.out.println(def1.getType()+","+def1.getVarName());
}
}
}
if(labelCount<=1)
continue;
SubTree dstT = checkMapping(srcT, mappings, dTC, sub2);
if(dstT==null)
continue;//子树没有对应子树,被删除
ITree dRoot = dstT.getRoot();
System.out.println(sRoot.getId()+"->"+dRoot.getId());
ArrayList<ITree> leaves2 = new ArrayList<>();
Utils.traverse2Leaf(dRoot, leaves2);
for(ITree leaf : leaves2) {
String label = leaf.getLabel();
String type = dTC.getTypeLabel(leaf);
if(type.equals("literal")) {
leaf.setLabel(Output.deleteLiteral(leaf, dTC));
}
ArrayList<Definition> stringList = defMap2.get(label);
if(stringList!=null) {
ITree parBlock = searchBlock(leaf, dTC);
ArrayList<Definition> blockList = blockMap2.get(parBlock);
for(Definition def2 : stringList) {
if(blockList!=null) {
if(blockList.contains(def2)) {
if(leaf.getId()>def2.getDefLabelID()) {
usedDefs2.add(def2);
leaf.setLabel("var");
}
System.out.println(leaf.getId()+","+def2.getDefLabelID());
System.out.println(def2.getType()+","+def2.getVarName());
}
}
if(def2.getDefLabelID()==leaf.getId()) {
leaf.setLabel("var");
}
}
}
if(!same) {
for(ITree leaf1 : leaves1) {
String label1 = leaf1.getLabel();
if(label.equals(label1)) {
same = true;
}
}
}
}
src = Output.subtree2src(srcT);
String tar = Output.subtree2src(dstT);
if(outMode=="txt") {
if(tar.contains("error")&&tar.contains("situation")) {
errCount++;
continue;
}
}
if(ifOnlyChange) {
if(src.equals(tar))
continue;
}
//长度相差太多的句子直接跳过
if(((float)src.length()/(float)tar.length())<0.25||((float)tar.length()/(float)src.length())<0.25 || !same)
continue;//no leaf is the same
if(outMode=="txt") {
if(ifPrintDef) {
String buffer = "";
String buffer1 = "";
String buffer2 = "";
for(Definition def : usedDefs1) {
SubTree st = new SubTree(def.getRoot(), sTC, 0, "");
String stat = Output.subtree2src(st);
buffer = buffer +stat+" ; ";
buffer1 = buffer1 +stat+" ; ";
}
src = Output.subtree2src(srcT);
// src += String.valueOf(srcT.getRoot().getId());
buffer = buffer + src+"\t";
buffer1 += src;
for(Definition def : usedDefs2) {
SubTree st = new SubTree(def.getRoot(), dTC, 0, "");
String stat = Output.subtree2src(st);
buffer += stat+" ; ";
buffer2 += stat+" ; ";
}
tar = Output.subtree2src(dstT);
// tar += String.valueOf(dstT.getRoot().getId());
buffer += tar;
buffer2 += tar;
if(buffer.contains("error")&&buffer.contains("situation"))
continue;
wr.append(buffer);
wr1.append(buffer1);
wr2.append(buffer2);
wr1.newLine();
wr1.flush();
wr2.newLine();
wr2.flush();
wr.newLine();
wr.flush();
}else {
src += String.valueOf(srcT.getRoot().getId());
tar += String.valueOf(dstT.getRoot().getId());
String buffer = src+"\t"+tar;
if(buffer.contains("error")&&buffer.contains("situation"))
continue;
wr.append(buffer);
wr1.append(src);
wr2.append(tar);
wr1.newLine();
wr1.flush();
wr2.newLine();
wr2.flush();
wr.newLine();
wr.flush();
}
}else if(outMode=="json") {
TreeContext st = buildTC(srcT);
TreeContext dt = buildTC(dstT);
printJson(jpath, count, st, dt);
count++;
}
}
}
wr.close();
wr1.close();
wr2.close();
System.out.println("miname:"+tmpName);
System.out.println("errCount:"+errCount);
}
static private ArrayList<ArrayList<SubTree>> searchQueue(Queue<SubTree> qe, ArrayList<SubTree> changedSTree, HashMap<String, ArrayList<Integer>> sDefMap) throws Exception {
ArrayList<ArrayList<SubTree>> resultList = new ArrayList<>();
HashMap<Integer, ArrayList<SubTree>> resultMap = new HashMap<>();
for(SubTree st : qe) {
TreeContext tc = st.getTC();
if(!changedSTree.contains(st))
continue;//只考虑需要修改的语句
ITree sRoot = st.getRoot();
List<ITree> sLeaves = new ArrayList<>();
Utils.traverse2Leaf(sRoot, sLeaves);
for(ITree leaf : sLeaves) {
String type = tc.getTypeLabel(leaf);
if(type.equals("name")) {
String label = leaf.getLabel();
ArrayList<Integer> map = sDefMap.get(label);
if(map!=null) {
if(map.size()==1) {
int defID = map.get(0);
if(resultMap.get(defID)==null) {
ArrayList<SubTree> stList = new ArrayList<>();
stList.add(st);
resultMap.put(defID, stList);
}else {
resultMap.get(defID).add(st);
}
}else {//发现有多个def line同一个关键字的情况,可能发生在不同的method
Collections.sort(map);
ArrayList<Integer> subMap = new ArrayList<>();
for(int id : map) {//只取该条语句之前的subtree,抛弃掉之后的
if(id<sRoot.getId())
subMap.add(id);
}
if(subMap.size()==0)
continue;//好像有defid全在rootid之后的情况,跳过
int defID = subMap.get(subMap.size()-1);//取离该def最近的
if(resultMap.get(defID)==null) {
ArrayList<SubTree> stList = new ArrayList<>();
stList.add(st);
resultMap.put(defID, stList);
}else {
resultMap.get(defID).add(st);
}
System.out.println("mLine");
}
}
}
}
}
for(Map.Entry<Integer, ArrayList<SubTree>> entry : resultMap.entrySet()) {
ArrayList<SubTree> list = entry.getValue();
if(list.size()>=2) {
resultList.add(list);
}
}
return resultList;
}//搜索队列,找到有data dependency的语句
private static Definition searchPramDef(ArrayList<Definition> defs, ITree node) {
for(Definition def : defs) {
ITree root = def.getRoot();
if(root.equals(node))
return def;
}
return null;
}
public HashMap<ITree, ITree> searchBlockMap(TreeContext tc) throws Exception{
HashMap<ITree, ITree> leaf2parblock_map = new HashMap<>();
ITree root = tc.getRoot();
List<ITree> leaves = new ArrayList<>();
leaves = Utils.traverse2Leaf(root, leaves);
for(ITree leaf : leaves) {
ITree parBlock = searchBlock(leaf, tc);
if(parBlock!=null) {
leaf2parblock_map.put(leaf, parBlock);
}
}
return leaf2parblock_map;
}
public ITree searchBlock(ITree node, TreeContext tc) {
List<ITree> pars = node.getParents();
for(ITree par : pars) {
if(tc.getTypeLabel(par).equals("block")) {
return par;
}
}
return null;
}
private static ArrayList<ITree> searchNextBlocks(Definition def, TreeContext tc) throws Exception {
ITree defRoot = def.getRoot();
List<ITree> pars = defRoot.getParents();
ITree func = null;
if(!isParameter(def, tc))
throw new Exception("Only used for parameters");
// System.out.println("--------------");
for(ITree par : pars) {
String type = tc.getTypeLabel(par);
// System.out.println(type);
if(type.equals("function")||type.equals("constructor")||type.equals("function_decl")||
type.equals("catch")||type.equals("lambda")) {
func = par;
break;
}
}
ArrayList<ITree> childBlocks = new ArrayList<>();
if(func==null)
// throw new Exception("Error def"+defRoot.getId()+tc.getTypeLabel(defRoot));
return childBlocks;
List<ITree> des = func.getDescendants();
for(ITree node : des) {
String type = tc.getTypeLabel(node);
if(type.equals("block"))
childBlocks.add(node);
}
return childBlocks;
}
public SubTree checkMapping(SubTree st, MappingStore map, TreeContext tc2, List<SubTree> sub2) throws Exception {
ITree root = st.getRoot();
int sSize = st.getTC().getSize();
int dSize = tc2.getSize();
ITree dstRoot = map.getDst(root);
List<ITree> desList = root.getDescendants();
ArrayList<ITree> seeds = new ArrayList<>();
Boolean sameLeaf = false;
HashMap<ITree, Integer> dRootCandidates = new HashMap<>();
int max_frequency = 0;
int print_seedID = 0;
for(ITree node : desList) {
ITree dst = map.getDst(node);
if(dst!=null) {
if(node.isLeaf()&&dst.isLeaf()) {
if(legalLebelMap(node, sSize, dst, tc2.getSize())) {
sameLeaf = true;
}
}
seeds.add(dst);
}
}
// System.out.println("SameLeaf:"+sameLeaf);
// System.out.println("Seeds:"+seeds.size());
if(!sameLeaf || (seeds.size()==0))
return null;
// System.out.println("sRootID:"+root.getId());
if(dstRoot==null) {
for(ITree seed : seeds) {
print_seedID = seed.getId();
List<ITree> pars = seed.getParents();
// System.out.println(pars.size());
for(ITree par : pars) {
// System.out.println(seed.getId()+","+tc2.getTypeLabel(par));
if(Utils.ifSRoot(tc2.getTypeLabel(par))) {
Integer frequency = dRootCandidates.get(par);
if(frequency==null) {
dRootCandidates.put(par, 1);
}else {
frequency++;
dRootCandidates.put(par, frequency);
}
break;
}
}
}
for(Map.Entry<ITree, Integer> entry : dRootCandidates.entrySet()) {
ITree candi = entry.getKey();
int frequency = entry.getValue();
if(frequency>max_frequency) {
dstRoot = candi;
max_frequency = frequency;
}else if(frequency==max_frequency) {
float sLocation = (float)root.getId()/(float)sSize;
float dLocation_old = (float)dstRoot.getId()/(float)dSize;
float dLocation_new = (float)candi.getId()/(float)dSize;
if(Math.abs(dLocation_new-sLocation)<Math.abs(dLocation_old)-sLocation) {
dstRoot = candi;
max_frequency = frequency;
}//如果frequcency相等,取location位置与sRoot更接近的dRoot
}
}//发现在subtree中有dst node分布在多棵subtree中的情况
if(dstRoot==null) {
System.err.println("error dstRoot:"+print_seedID);
return null;
}
List<ITree> desList2 = dstRoot.getDescendants();
for(ITree node : seeds) {
if(!desList2.contains(node)) {
return null;
}
}//是否允许两个子树中分布有不在这两颗子树内的mapping?
}
for(SubTree dstT : sub2) {
ITree candi = dstT.getRoot();
if(candi.equals(dstRoot))
return dstT;
}
return null;
}//检查与srcST符合的dstST mapping
private static Boolean legalLebelMap(ITree src, int sSize, ITree dst, int dSize) {
String label1 = src.getLabel();
String label2 = dst.getLabel();
boolean isSame = false;
if(label1==null||label2==null) {
System.err.println("error label:"+src.getId());
return isSame;
}
float sLocation = (float)src.getId()/(float)sSize;
float dLocation = (float)dst.getId()/(float)dSize;
if(Math.abs(sLocation-dLocation)>=0.33)
return isSame;//如果两个label在两份code中位置相差过远,不考虑相同
if(label1.equals(label2)&&!label1.equals("::")&&!label2.equals("::"))
isSame = true;
if(label1.equals("ros")&&label2.equals("rclcpp"))
isSame = true;
if(label1.equals("tf")&&label2.equals("tf2"))
isSame = true;
return isSame;
}//label是否相同的相关规则
public static TreeContext abstraSubTree(SubTree st, HashMap<String, String> varMap) {
TreeContext origin = st.getTC();
TreeContext subT = new TreeContext();
subT.importTypeLabels(origin);
ITree subRoot = st.getRoot();
subT.setRoot(subRoot);
List<ITree> descendants = subRoot.getDescendants();
for(ITree node : descendants) {
String label = node.getLabel();
String type = subT.getTypeLabel(node);
if (varMap.containsKey(label)) {
System.out.println("find it!");
node.setLabel("var");
}
if(type.equals("literal")) {
if (label.contains("\"")) {
label = "stringliteral";
}else {
label = "intliteral";
}
node.setLabel(label);
}
}
return subT;
}
static private TreeContext abstraTotalTC(ArrayList<SubTree> stList, HashMap<String, String> varMap) {
TreeContext origin = stList.get(0).getTC();
TreeContext subT = new TreeContext();
subT.importTypeLabels(origin);
subT.registerTypeLabel(000, "Block");
Tree blockRoot = new gumtreediff.tree.Tree(000, null);
List<ITree> children = new ArrayList<>();
for(SubTree st : stList) {
children.add(st.getRoot());
}
blockRoot.setChildren(children);
subT.setRoot(blockRoot);
List<ITree> descendants = blockRoot.getDescendants();
for(ITree node : descendants) {
String label = node.getLabel();
String type = subT.getTypeLabel(node);
if (varMap.containsKey(label)) {
System.out.println("find it!");
node.setLabel("var");
}
if(type.equals("literal")) {
if (label.contains("\"")) {
label = "stringliteral";
}else {
label = "intliteral";
}
node.setLabel(label);
}
}
//创建block节点,输出拼起来的总图,然后把剩下的单行输出
return subT;
}
public TreeContext buildTC(SubTree st) {
TreeContext origin = st.getTC();
TreeContext subT = new TreeContext();
ITree root = st.getRoot();
subT.importTypeLabels(origin);
subT.setRoot(root);
//创建block节点,输出拼起来的总图,然后把剩下的单行输出
return subT;
}
public void printJson(String jpath, int count, TreeContext srcT, TreeContext dstT) throws Exception {
File dir = new File(jpath);
if(!dir.exists()) {
dir.mkdirs();
}
if(srcT!=null) {
String out = jpath+"pair"+String.valueOf(count)+"_src.json";
BufferedWriter wr = new BufferedWriter(new FileWriter(new File(out)));
wr.append(TreeIoUtils.toJson(srcT).toString());
wr.flush();
wr.close();
}
if(dstT!=null) {
String out1 = jpath+"pair"+String.valueOf(count)+"_tgt.json";
BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File(out1)));
wr1.append(TreeIoUtils.toJson(dstT).toString());
wr1.flush();
wr1.close();
}
}
public ArrayList<Definition> getDef(TreeContext tc, String from) throws Exception {
ArrayList<Definition> defs = new ArrayList<>();
HashMap<ITree, ArrayList<ITree>> parBlockMap = new HashMap<>();
ArrayList<ITree> blocks = new ArrayList<>();
ITree root = tc.getRoot();
List<ITree> allNodes = root.getDescendants();
for(ITree node : allNodes) {
if(tc.getTypeLabel(node).equals("block")) {
List<ITree> pars = node.getParents();
ArrayList<ITree> parBlocks = new ArrayList<>();
for(ITree par : pars) {//search block parents
String type = tc.getTypeLabel(par);
if(type.equals("blcok")) {
parBlocks.add(par);
}
}
parBlockMap.put(node, parBlocks);
blocks.add(node);
}else if(tc.getTypeLabel(node).equals("decl")) {
// System.out.println("find def: "+node.getId());
Definition def = new Definition();
def.setRoot(node);
Boolean hasName = false;
List<ITree> children = node.getChildren();
for(ITree child : children) {
String type = tc.getTypeLabel(child);
if(type.equals("type")) {
String typeName = "";
List<ITree> typeChilds = child.getChildren();
for(ITree child1 : typeChilds) {
if(child1.isLeaf()) {//单label情况
String label = child1.getLabel();
typeName = typeName+label;
if(label==null)
throw new Exception("check ITree: "+child1.getId());
}else {
for(ITree leaf : child1.getChildren()) {
String label = leaf.getLabel();
typeName = typeName+label;
}
}
}
def.setType(typeName);
}else if(type.equals("name")) {
String label = child.getLabel();
if(label==null)
throw new Exception("check ITree: "+child.getId());
def.setVarName(label);//varName
def.setDefLabelID(child.getId());
hasName = true;
}
}
if(!hasName) {
continue;
}
List<ITree> pars = node.getParents();
List<ITree> parBlocks = new ArrayList<>();
List<ITree> parList = new ArrayList<>();
Boolean first = true;
for(ITree par : pars) {//search block parents
String type = tc.getTypeLabel(par);
if(type.equals("block")) {
if(first) {
def.setBlock(par);
first = false;
}
parBlocks.add(par);
}
parList.add(par);
}
if(parBlocks.size()==0) {
parBlocks.add(tc.getRoot());
def.setBlock(tc.getRoot());
}//全局节点没有父亲block,直接默认block为tc根节点
def.setParBlocks(parBlocks);
def.setParList(parList);
def.setTc(tc);
defs.add(def);
}
}
ArrayList<ITree> global_decls = getGlobalDefRoots(tc);
ArrayList<Definition> globalDefs = new ArrayList<>();
for(Definition def : defs) {
ITree defRoot = def.getRoot();
if(global_decls.contains(defRoot))
globalDefs.add(def);
}
if(from.equals("src")) {
blocks1 = blocks;
parBlockMap1 = parBlockMap;
defs1 = defs;
globalDefs1 = globalDefs;
}else if(from.equals("tgt")) {
blocks2 = blocks;
parBlockMap2 = parBlockMap;
defs2 = defs;
globalDefs2 = globalDefs;
}
return defs;
}
public ArrayList<ITree> getGlobalDefRoots(TreeContext tc){
ArrayList<ITree> global_decls = new ArrayList<>();
ITree root = tc.getRoot();
List<ITree> allNodes = root.getDescendants();
List<ITree> classNodes = new ArrayList<>();
for(ITree node : allNodes) {
if(tc.getTypeLabel(node).equals("class")) {
classNodes.add(node);
}
}
for(ITree node : classNodes) {
List<ITree> childs = node.getChildren();
for(ITree child : childs) {
if(tc.getTypeLabel(child).equals("block")) {
ITree blockRoot = child;
for(ITree child1 : blockRoot.getChildren()) {
if(tc.getTypeLabel(child1).equals("decl_stmt")) {
for(ITree child2 : child1.getChildren()) {
if(tc.getTypeLabel(child1).equals("decl")) {
global_decls.add(child2);
break;
}
}
}
}
break;
}
}
}
return global_decls;
}
public HashMap<ITree, ArrayList<Definition>> transferBlockMap(ArrayList<Definition> defs, TreeContext tc, String from) throws Exception {
HashMap<ITree, ArrayList<Definition>> blockMap = new HashMap<>();
ArrayList<ITree> blocks = new ArrayList<>();
if(from.equals("src")) {
blocks = blocks1;
}else if(from.equals("tgt")) {
blocks = blocks2;
}
for(ITree block : blocks) {
ITree parNode = block.getParent();
String parType = tc.getTypeLabel(parNode);
List<ITree> pars = block.getParents();
List<ITree> blockList = new ArrayList<>();
blockList.add(block);
for(ITree par : pars) {//search block parents
String type = tc.getTypeLabel(par);
if(type.equals("block")) {
blockList.add(par);
}
}
if(blockList.size()==0)
throw new Exception("check parBlock: "+block.getId());
ArrayList<Definition> defList = new ArrayList<>();
for(Definition def : defs) {
ITree parBlcok = def.getBlock();
if(!isParameter(def, tc)) {//所有非参数且block位于目标block的父亲block列表中的def放入list
if(blockList.contains(parBlcok)) {
defList.add(def);
}
}else {
ArrayList<ITree> nextBlocks = searchNextBlocks(def, tc);
if(nextBlocks.contains(block)) {
defList.add(def);
}//参数def只在所有子block中生效
}
if(parBlcok.equals(tc.getRoot())) {
if(!isParameter(def, tc)) {
defList.add(def);
}
}//发现有全局变量情况,父亲节点没有root,单独处理,放入所有defList中
}
if(parType.equals("function")) {//function parameters
for(ITree node : parNode.getChildren()) {
String type = tc.getTypeLabel(node);
if(type.equals("parameter_list")&&!node.isLeaf()) {
List<ITree> desendants = node.getDescendants();
for(ITree child : desendants) {
if(tc.getTypeLabel(child).equals("decl")) {
Definition def = searchPramDef(defs, node);
defList.add(def);
}
}
}
}
}
blockMap.put(block, defList);
}
return blockMap;
}
private static Boolean isParameter(Definition def, TreeContext tc) {
boolean isPatameter = false;
ITree root = def.getRoot();
ITree par = root.getParent();
String type = tc.getTypeLabel(par);
if(type.equals("parameter")) {
isPatameter = true;
return isPatameter;
}else {
return isPatameter;
}
}
public HashMap<String, ArrayList<Definition>> transferDefs(ArrayList<Definition> defs) {
HashMap<String, ArrayList<Definition>> defMap = new HashMap<>();
for(Definition def : defs) {
String var = def.getVarName();
if(defMap.get(var)==null) {
ArrayList<Definition> list = new ArrayList<>();
list.add(def);
defMap.put(var, list);
}else {
defMap.get(var).add(def);
}
}
return defMap;
}
public HashMap<ITree, ArrayList<Definition>> transfer2FunctionMap(ArrayList<Definition> defs, ITree root, TreeContext tc) {
HashMap<ITree, ArrayList<Definition>> def_functionMap = new HashMap<>();
for(Definition def : defs) {
List<ITree> pars = def.getParList();
for(int i=0;i<pars.size();i++) {
ITree par = pars.get(i);
String type = tc.getTypeLabel(par);
if(type.equals("function")) {
if(def_functionMap.get(par)==null) {
ArrayList<Definition> tmps = new ArrayList<>();
tmps.add(def);
def_functionMap.put(par, tmps);
}else
def_functionMap.get(par).add(def);
break;//只在最近的function内生效
}
if(i==pars.size()) {
if(def_functionMap.get(root)==null) {
ArrayList<Definition> tmps = new ArrayList<>();
tmps.add(def);
def_functionMap.put(root, tmps);
}else
def_functionMap.get(root).add(def);
}
}
}
return def_functionMap;
}
private static ArrayList<String> readIncludes(String from) throws Exception {
ArrayList<String> includes = new ArrayList<>();
String path = "tmp//includes.txt";
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String tmpline = "";
while((tmpline=br.readLine())!=null) {
String include = "";
if(from=="src") {
include = tmpline.split("\t")[0];
}else if(from=="dst") {
include = tmpline.split("\t")[1];
}
includes.add(include);
}
br.close();
return includes;
}
}
| 28,075
| 29.852747
| 173
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/DelComment.java
|
package utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* 删除Java代码中的注释
*
* @author Alive
* @build 2010-12-23
*/
public class DelComment {
public static void main(String[] args) {
clearComment("migrations_test"); //删除目录下所有java||cpp文件注释
clearInclude("migrations_test"); //删除目录下所有java||cpp文件header
//删除某个具体文件的注释
// clearComment("Absolute3DLocalizationElement2.cpp");
}
private static int count = 0;
/**
* 删除文件中的各种注释,包含//、/* * /等
* @param charset 文件编码
* @param file 文件
*/
public static void clearComment(File file, String charset) {
try {
System.out.println("-----开始处理文件:" + file.getAbsolutePath());
//递归处理文件夹
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
clearComment(f, charset); //递归调用
}
return;
} else if (!file.getName().endsWith(".cpp")&&!file.getName().endsWith(".java")) {
//非cpp or java文件直接返回
return;
}
//根据对应的编码格式读取
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
StringBuffer content = new StringBuffer();
String tmp = null;
while ((tmp = reader.readLine()) != null) {
content.append(tmp);
content.append("\n");
}
reader.close();
String target = content.toString();
//String s = target.replaceAll("\\/\\/[^\\n]*|\\/\\*([^\\*^\\/]*|[\\*^\\/*]*|[^\\**\\/]*)*\\*\\/", ""); //本段正则摘自网上,有一种情况无法满足(/* ...**/),略作修改
String s = target.replaceAll("\\/\\/[^\\n]*|\\/\\*([^\\*^\\/]*|[\\*^\\/*]*|[^\\**\\/]*)*\\*+\\/", "");
//System.out.println(s);
//使用对应的编码格式输出
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
out.write(s);
out.flush();
out.close();
count++;
System.out.println("-----文件处理完成---" + count);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
发现不一样的include会严重影响action生成,是否是没导入dependency的关系?
*/
public static void clearInclude(File file, String charset) {
try {
System.out.println("-----开始处理文件:" + file.getAbsolutePath());
//递归处理文件夹
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
clearInclude(f, charset); //递归调用
}
return;
} else if (!file.getName().endsWith(".cpp")&&!file.getName().endsWith(".java")) {
//非cpp or java文件直接返回
return;
}
//根据对应的编码格式读取
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
StringBuffer content = new StringBuffer();
String tmp = null;
while ((tmp = reader.readLine()) != null) {
// System.out.println(tmp);
if(!tmp.contains("#include")&&!tmp.contains("#define")) {
content.append(tmp);
content.append("\n");
}
}
reader.close();
String target = content.toString();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
out.write(target);
out.flush();
out.close();
count++;
System.out.println("-----文件处理完成---" + count);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clearComment(String filePath, String charset) {
clearComment(new File(filePath), charset);
}
public static void clearComment(String filePath) {
clearComment(new File(filePath), "UTF-8");
}
public static void clearComment(File file) {
clearComment(file, "UTF-8");
}
public static void clearInclude(String filePath, String charset) {
clearInclude(new File(filePath), charset);
}
public static void clearInclude(String filePath) {
clearInclude(new File(filePath), "UTF-8");
}
public static void clearInclude(File file) {
clearInclude(file, "UTF-8");
}
}
| 4,780
| 30.873333
| 152
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/FileOperation.java
|
package utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOperation {
public void copyFile(File sourcefile,File targetFile) throws IOException{
if(!targetFile.getParentFile().exists())
targetFile.getParentFile().mkdirs();
//新建文件输入流并对它进行缓冲
FileInputStream input=new FileInputStream(sourcefile);
BufferedInputStream inbuff=new BufferedInputStream(input);
//新建文件输出流并对它进行缓冲
FileOutputStream out=new FileOutputStream(targetFile);
BufferedOutputStream outbuff=new BufferedOutputStream(out);
//缓冲数组
byte[] b=new byte[1024*5];
int len=0;
while((len=inbuff.read(b))!=-1){
outbuff.write(b, 0, len);
}
outbuff.flush(); //刷新此缓冲的输出流
inbuff.close();//关闭流
outbuff.close();
out.close();
input.close();
}
public void copyDirectiory(String sourceDir,String targetDir) throws IOException{
//新建目标目录
File source = new File(sourceDir);
File target = new File(targetDir);
if(!target.exists()){
target.mkdirs();
}
//获取源文件夹当下的文件或目录
File[] file=source.listFiles();
for (File sourceFile : file) {
if(sourceFile.isFile()){
//目标文件
File targetFile=new File(new File(targetDir).getAbsolutePath()+File.separator+sourceFile.getName());
copyFile(sourceFile, targetFile);
}
if(sourceFile.isDirectory()){
//准备复制的源文件夹
String dir1=sourceDir+"\\"+sourceFile.getName();
//准备复制的目标文件夹
String dir2=targetDir+"\\"+sourceFile.getName();
copyDirectiory(dir1, dir2);
}
}
}
public void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}//删除指定文件夹下所有文件param path 文件夹完整绝对路径
public boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists() || !file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (String element : tempList) {
if (path.endsWith(File.separator)) {
temp = new File(path + element);
} else {
temp = new File(path + File.separator + element);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + element);//先删除文件夹里面的文件
delFolder(path + "/" + element);//再删除空文件夹
flag = true;
}
}
return flag;
}
}
| 2,887
| 28.469388
| 105
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/FilterFiles.java
|
package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FilterFiles {
public static void main (String args[]) throws Exception{
String dirPath1 = "tmp\\ROS1_src\\";
String dirPath2 = "tmp\\ROS2_src\\";
String outPath = "tmp\\output\\";
ArrayList<File> fileList1 = new ArrayList<>();
traverseFolder(dirPath1, fileList1);
System.out.println("size:"+fileList1.size());
ArrayList<File> fileList2 = new ArrayList<>();
traverseFolder(dirPath2, fileList2);
FileOperation fo = new FileOperation();
for(File file1 : fileList1) {
String fileName1 = file1.getName();
Boolean ifFind = false;
for(File file2 : fileList2) {
String fileName2 = file2.getName();
if(fileName1.equals(fileName2)) {
String data1 = ReadFileToString(file1);
String data2 = ReadFileToString(file2);
if(data1.equals(data2)) {
System.out.println(fileName1+" is identitcal");
ifFind = true;
}else {
String javaName1 = fileName1.substring(0, fileName1.length()-4);
String javaName2 = fileName2.substring(0, fileName2.length()-4);
String newFilePath1 = outPath+javaName1+"\\"+javaName1+"1.cpp";
String newFilePath2 = outPath+javaName2+"\\"+javaName2+"2.cpp";
File newFile1 = new File(newFilePath1);
File newFile2 = new File(newFilePath2);
fo.copyFile(file1, newFile1);
fo.copyFile(file2, newFile2);
ifFind = true;
break;
}
}
}
if(!ifFind) {
System.out.println("Cannot find "+fileName1);
}
}
}
public static String ReadFileToString(File file) throws IOException {
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader = new BufferedReader(new FileReader(file));
char[] buf = new char[10];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
public static void traverseFolder(String path, ArrayList<File> fileList) {
File dir = new File(path);
if (dir.exists()) {
File[] files = dir.listFiles();
if (files.length == 0) {
System.out.println("文件夹是空的!");
} else {
for (File file : files) {
if (file.isDirectory()) {
traverseFolder(file.getAbsolutePath(), fileList);
} else {
if(file.getName().contains(".cpp")||file.getName().contains(".CPP"))
fileList.add(file);
}
}
}
} else {
System.out.println("文件不存在!");
}
}
}
| 2,614
| 27.736264
| 78
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/Levenshtein.java
|
package utils;
public class Levenshtein {
/**
* 比较两个字符串的相识度
* 核心算法:用一个二维数组记录每个字符串是否相同,如果相同记为0,不相同记为1,每行每列相同个数累加
* 则数组最后一个数为不相同的总数,从而判断这两个字符的相识度
*
* @param str
* @param target
* @return
*/
public static void main(String[] args) {
String a= "1000";
String b = "rmw_qos_profile_default";
System.out.println("相似度:"+getSimilarityRatio(a,b));
}
private static int compare(String str, String target) {
int d[][]; // 矩阵
int n = str.length();
int m = target.length();
int i; // 遍历str的
int j; // 遍历target的
char ch1; // str的
char ch2; // target的
int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
d = new int[n + 1][m + 1];
// 初始化第一列
for (i = 0; i <= n; i++) {
d[i][0] = i;
}
// 初始化第一行
for (j = 0; j <= m; j++) {
d[0][j] = j;
}
for (i = 1; i <= n; i++) {
// 遍历str
ch1 = str.charAt(i - 1);
// 去匹配target
for (j = 1; j <= m; j++) {
ch2 = target.charAt(j - 1);
if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) {
temp = 0;
} else {
temp = 1;
}
// 左边+1,上边+1, 左上角+temp取最小
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp);
}
}
return d[n][m];
}
/**
* 获取最小的值
*/
private static int min(int one, int two, int three) {
return (one = one < two ? one : two) < three ? one : three;
}
/**
* 获取两字符串的相似度
*/
public static float getSimilarityRatio(String str, String target) {
int max = Math.max(str.length(), target.length());
return 1 - (float) compare(str, target) / max;
}
}
| 2,062
| 25.113924
| 88
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/Output.java
|
package utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.io.TreeIoUtils;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import gumtreediff.tree.TreeUtils;
import split.Split;
import structure.Definition;
import structure.Migration;
import structure.SubTree;
import structure.Transform;
public class Output {
public static void main (String args[]) throws Exception{
String path = "migrations_test";
// String path = "Absolute3DLocalizationElement.cpp";
// Output.collectTokens(sp.trans);
// Output.collectChangePairs(path, "");
// Output.collectDefUse(path, "", "");
Output.printJson(path, null);
// String path = "talker.cpp";
// Output.tokensFromInputFile(path);
}
public static void tokensFromInputFile(String path) throws Exception {
Split sp = new Split();
File output = new File("src-test.txt");
File outLine = new File("lineNum.txt");
File outFile = new File("src-var.txt");
BufferedWriter wr = new BufferedWriter(new FileWriter(output));
BufferedWriter wr1 = new BufferedWriter(new FileWriter(outLine));
BufferedWriter wr2 = new BufferedWriter(new FileWriter(outFile));
File cppFile = new File(path);
TreeContext tc = new SrcmlCppTreeGenerator().generateFromFile(cppFile);
String cppName = cppFile.getName();
System.out.println("Reading file: "+cppName);
Defuse def = new Defuse();
ArrayList<Definition> defs1 = def.getDef(tc, "src");//先计算action,再收集defs
HashMap<String, ArrayList<Definition>> defMap1 = def.transferDefs(defs1);
HashMap<ITree, ArrayList<Definition>> blockMap1 = def.transferBlockMap(defs1, tc, "src");
ArrayList<SubTree> sub1 = sp.splitSubTree(tc, cppName);//Subtree中割裂过block,注意
for(SubTree srcT : sub1) {
ITree root = srcT.getRoot();
List<ITree> candidates = root.getDescendants();
if(srcT!=null&&srcT.getTC()!=null) {
String src = subtree2src(srcT);
ArrayList<ITree> leaves1 = new ArrayList<>();
Utils.traverse2Leaf(root, leaves1);
int labelCount = 0;
for(ITree leaf : leaves1) {
String label = leaf.getLabel();
if(!label.equals(""))
labelCount++;
String type = tc.getTypeLabel(leaf);
if(type.equals("literal")) {
leaf.setLabel(Output.deleteLiteral(leaf, tc));
}
ArrayList<Definition> stringList = defMap1.get(label);
if(stringList!=null) {
ITree parBlock = def.searchBlock(leaf, tc);
ArrayList<Definition> blockList = blockMap1.get(parBlock);
for(Definition def1 : stringList) {
if(blockList!=null) {
if(blockList.contains(def1)) {
if(leaf.getId()>def1.getDefLabelID()) {
leaf.setLabel("var");
}
}
}
if(def1.getDefLabelID()==leaf.getId()) {
leaf.setLabel("var");
}
}
}
}
if(labelCount<=1)
continue;
wr.append(src);
wr.newLine();
wr.flush();
src = subtree2src(srcT);
wr2.append(src);
wr2.newLine();
wr2.flush();
candidates.add(root);
int beginLine = 0;
int beginColumn = 0;
int endLine = 0;
int endColumn = 0;
for(ITree node : candidates) {
int line = node.getLine();
int column = node.getColumn();
if(line==0)
continue;//null
int lastLine = node.getLastLine();
int lastColumn = node.getLastColumn();
if(beginLine==0&&line>beginLine) {
beginLine = line;
}else if(line<beginLine&&line!=0){
beginLine = line;
}
if(beginColumn==0&&column>beginColumn) {
beginColumn = column;
}else if(column<beginColumn&&column!=0){
beginColumn = column;
}
if(endLine==0&&lastLine>endLine) {
endLine = lastLine;
}else if(lastLine>endLine) {
endLine = lastLine;
}
if(endColumn==0&&lastColumn>endColumn) {
endColumn = lastColumn;
}else if(lastColumn>endColumn) {
endColumn = lastColumn;
}
}
wr1.append(String.valueOf(beginLine)+","+String.valueOf(beginColumn)+
"->"+String.valueOf(endLine)+","+String.valueOf(endColumn));
wr1.newLine();
wr1.flush();
}
}
wr.close();
wr1.close();
wr2.close();
}
public static void printJson(String path, String filter) throws Exception {
Split sp = new Split();
ArrayList<Migration> migrats = new ArrayList<>();
migrats = sp.readMigration(path, filter);
sp.storeTrans(migrats);
ArrayList<Transform> trans = sp.trans;
for(int i=0;i<trans.size();i++) {
Transform tf = trans.get(i);
System.out.println("Analyse:"+tf.getMiName());
SubTree srcT = tf.getSTree();
SubTree dstT = tf.getDTree();
if(srcT!=null&&dstT!=null) {
if(srcT.getTC()!=null&&dstT.getTC()!=null) {
TreeContext sub1 = new TreeContext();
TreeContext sub2 = new TreeContext();
sub1.importTypeLabels(srcT.getTC());
sub2.importTypeLabels(dstT.getTC());
sub1.setRoot(srcT.getRoot());
sub2.setRoot(dstT.getRoot());
String out = "jsons\\pair"+String.valueOf(i)+"_src.json";
BufferedWriter wr = new BufferedWriter(new FileWriter(new File(out)));
wr.append(TreeIoUtils.toJson(sub1).toString());
wr.flush();
wr.close();
String out1 = "jsons\\pair"+String.valueOf(i)+"_tgt.json";
BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File(out1)));
wr1.append(TreeIoUtils.toJson(sub2).toString());
wr1.flush();
wr1.close();
}
}
}
}
public static void printJson1(String path, String filter) throws Exception {
Split sp = new Split();
ArrayList<Migration> migrats = new ArrayList<>();
migrats = sp.readMigration(path, filter);
for(int i=0;i<migrats.size();i++) {
Migration mi = migrats.get(i);
TreeContext srcT = mi.getSrcT();
TreeContext dstT = mi.getDstT();
if(srcT!=null&&dstT!=null) {
String out = "jsons\\pair"+String.valueOf(i)+"_src.json";
BufferedWriter wr = new BufferedWriter(new FileWriter(new File(out)));
wr.append(TreeIoUtils.toJson(srcT).toString());
wr.flush();
wr.close();
String out1 = "jsons\\pair"+String.valueOf(i)+"_tgt.json";
BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File(out1)));
wr1.append(TreeIoUtils.toJson(dstT).toString());
wr1.flush();
wr1.close();
}
}
}
public static void collectChangePairs(String path, String filter) throws Exception {
Split sp = new Split();
ArrayList<Migration> migrats = new ArrayList<>();
migrats = sp.readMigration(path, filter);
sp.storeTrans(migrats);
String out = "change.txt";
String out1 = "src-train.txt";
String out2 = "tgt-train.txt";
BufferedWriter wr = new BufferedWriter(new FileWriter(new File(out)));
BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File(out1)));
BufferedWriter wr2 = new BufferedWriter(new FileWriter(new File(out2)));
for(Transform tf : sp.trans) {
System.out.println("===============================");
SubTree srcT = tf.getSTree();
SubTree dstT = tf.getDTree();
if(srcT!=null&&dstT!=null) {
if(srcT.getTC()!=null&&dstT.getTC()!=null) {
String src = subtree2src(srcT);
String dst = subtree2src(dstT);
if(!(src.contains("error situation")||dst.contains("error situation"))) {
// System.out.println(src);
wr.append(src+"\t");
wr1.append(src);
wr1.newLine();
wr1.flush();
// System.out.println(dst);
wr.append(dst);
wr.newLine();
wr.flush();
wr2.append(dst);
wr2.newLine();
wr2.flush();
}
}
}
}
wr.close();
wr1.close();
wr2.close();
}
public static void collectTokens(ArrayList<Transform> trans) throws Exception {
String out1 = "srcDiffToken.txt";
String out2 = "dstDiffToken.txt";
BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File(out1)));
BufferedWriter wr2 = new BufferedWriter(new FileWriter(new File(out2)));
for(Transform tf : trans) {
System.out.println("===============================");
SubTree srcT = tf.getSTree();
SubTree dstT = tf.getDTree();
if(srcT!=null&&dstT!=null) {
List<ITree> leaves1 = new ArrayList<>();
List<ITree> leaves2 = new ArrayList<>();
if(srcT.getTC()!=null&&dstT.getTC()!=null) {
leaves1 = Utils.traverse2Leaf(srcT.getRoot(), leaves1);
leaves2 = Utils.traverse2Leaf(dstT.getRoot(), leaves2);
for(int i=0;i<leaves1.size();i++) {
ITree leaf = leaves1.get(i);
if(leaf.getLabel()!=null) {
wr1.append(leaf.getLabel());
if(i!=leaves1.size()-1)
wr1.append(" ");
}
}
wr1.append("\t");
// wr1.newLine();
// wr1.flush();
for(int i=0;i<leaves2.size();i++) {
ITree leaf = leaves2.get(i);
if(leaf.getLabel()!=null) {
wr1.append(leaf.getLabel());
if(i!=leaves2.size()-1)
wr1.append(" ");
}
}
wr1.newLine();
wr1.flush();
// wr2.append(s2);
// wr2.newLine();
// wr2.flush();
}
}
}
wr1.close();
wr2.close();
}
public static ArrayList<Integer> locateLineNum(SubTree st, String path) throws Exception {
ArrayList<Integer> candidates = new ArrayList<>();
List<ITree> leaves = new ArrayList<>();
leaves = Utils.traverse2Leaf(st.getRoot(), leaves);
// System.out.println("tokens:"+Utils.printToken(st));
ArrayList<String> labels = new ArrayList<>();
ArrayList<String> codes = new ArrayList<>();
for(ITree tmp : leaves) {
String label = tmp.getLabel();
labels.add(label);
}
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String tmpline = "";
while((tmpline = br.readLine())!=null) {
codes.add(tmpline);
}
br.close();
float sim = Float.MIN_VALUE;
for(String code : codes) {
int count = 0;
for(String label : labels) {
if(code.contains(label)) {
count++;
}
}
float tmpsim = (float)count/(float)(labels.size());
if(tmpsim>sim) {
candidates.clear();
sim = tmpsim;
int lineNum = codes.indexOf(code)+1;
candidates.add(lineNum);
}else if(tmpsim==sim) {
int lineNum = codes.indexOf(code)+1;
candidates.add(lineNum);
}
}
return candidates;
}//search整份代码,找到包含最多tokens的行号(可能不唯一)
public static String subtree2src(SubTree st) throws Exception {
// String src = String.valueOf(st.getRoot().getId());
String src = "";
String loopEnd = "";
ITree root = st.getRoot();
TreeContext srcT = st.getTC();
String sType = srcT.getTypeLabel(root);
if(sType.equals("while")||sType.equals("for")||sType.equals("if")) {
if(sType.equals("while"))
src = src+"while ( ";
if(sType.equals("for"))
src = src+"for ( ";
if(sType.equals("if"))
src = src+"if ( ";
loopEnd = " ) ";
}else if (sType.equals("return")){
src = src+"return ";
}
List<ITree> leaves = new ArrayList<>();
leaves = Utils.traverse2Leaf(root, leaves);
// System.out.println(leaves.size());
// for(ITree leaf : leaves) {
// String type = srcT.getTypeLabel(leaf);
// String label = leaf.getLabel();
// System.out.println(type+":"+label);
// }
if(leaves.size()==0)
throw new Exception("null leaves");
else if(leaves.size()==1) {
src = src+leaves.get(0).getLabel();//先把0号叶子放入
return src;
}
src = src+leaves.get(0).getLabel();//先把0号叶子放入
// System.out.println("leafSize:"+leaves.size());
for(int i=0;i<leaves.size()-1;i++) {
// System.out.println(src);
int size = 0;
ITree leaf1 = leaves.get(i);
ITree leaf2 = leaves.get(i+1);
if(leaf1.getLabel()==""&&leaf2.getLabel()=="")
continue;
if(leaf2.getLabel().equals("")&&
!srcT.getTypeLabel(leaf2).equals("argument_list")&&
!srcT.getTypeLabel(leaf2).equals("parameter_list")) {
i++;
if(i<leaves.size()-1) {
leaf2 = leaves.get(i+1);
}else {
continue;
}
}//发现有截取block后的断点影响还原,跳过
if(leaf1.isRoot()||leaf2.isRoot())//叶子节点为总树根节点,可能么?
throw new Exception("why is root???");
ITree sharePar = Utils.findShareParent(leaf1, leaf2, srcT);
// String parType = srcT.getTypeLabel(sharePar);
List<ITree> childs = sharePar.getChildren();
if(childs.contains(leaf1)&&childs.contains(leaf2)) {//同一层的两个叶子节点,还原时候直接拼起来就行
src = src+" "+leaf2.getLabel();
}else if(childs.size()>=2){//分情况讨论不同分支下还原代码问题
ITree node1 = null;
ITree node2 = null;
for(ITree child : childs) {
if(child.isLeaf()) {
if(child.equals(leaf1))
node1 = child;
if(child.equals(leaf2))
node2 = child;
}else {
List<ITree> list = TreeUtils.preOrder(child);
if(list.contains(leaf1))
node1 = child;
if(list.contains(leaf2))
node2 = child;
// if(list.contains(leaf1)&&list.contains(leaf1))
// throw new Exception("wrong sharePar!");
}
}//找sharePar的下一个leaf1,leaf2对应父节点(或其本身)
String type1 = "";
String type2 = "";
if(node1!=null&&node2!=null) {
type1 = srcT.getTypeLabel(node1);
type2 = srcT.getTypeLabel(node2);
}else
System.out.println("why node is null?"+st.getMiName()+","+st.getRoot().getId());
if(type1.equals("name")) {
if(type2.equals("argument_list")||type2.equals("parameter_list")) {
List<ITree> arguLeaves = new ArrayList<>();
arguLeaves = Utils.traverse2Leaf(node2, arguLeaves);//找到argulist中所有叶子
src = src + recoverArguList(node2, arguLeaves, srcT);//argulist单独处理
if(src.substring(src.length()-1)==" ")
src = src.substring(0, src.length()-1);//去除空格
size = arguLeaves.size();
i=i+size-1;
}else if(type2.equals("init")) {
src = src+" = "+leaf2.getLabel();
}else if(type2.equals("operator")) {
src = src+" "+leaf2.getLabel();
}else if(type2.equals("modifier")) {
src = src+" * ";
}else if(type2.equals("index")) {
src = src+" [ "+leaf2.getLabel()+" ] ";
}else {
src = String.valueOf(st.getRoot().getId())+"error name situation";
break;
// throw new Exception("没考虑过的name情况:"+type2);
}
}else if(type1.equals("type")) {
if(type2.equals("name")) {
src = src+" "+leaf2.getLabel();
}else {
src = String.valueOf(st.getRoot().getId())+"error type situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else if(type1.equals("operator")) {
if(type2.equals("call")) {//好像有node2为call的情况
node2 = node2.getChildren().get(0);
type2 = srcT.getTypeLabel(node2);
}
if(type2.equals("name")||type2.equals("operator")) {
src = src+" "+leaf2.getLabel();
}else {
src = String.valueOf(st.getRoot().getId())+"error operator situation";
break;
// throw new Exception("没考虑过的operator情况:"+type2);
}
}else if(type1.equals("call")) {
if(type2.equals("operator")) {
src = src+" "+leaf2.getLabel();
}else if(type2.equals("call")) {
src = src+" , "+leaf2.getLabel();
}else {
src = String.valueOf(st.getRoot().getId())+ "error call situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else if(type1.equals("specifier")) {
if(type2.equals("name")){
src = src+" "+leaf2.getLabel();
}else {
src = String.valueOf(st.getRoot().getId())+"error specifier situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else if(type1.equals("parameter_list")) {
if(type2.equals("member_init_list")) {
src = src+" : "+leaf2.getLabel();
}
}else if(type1.equals("decl")) {
if(type2.equals("decl")) {
src = src+" , "+leaf2.getLabel();
}
}else if(type1.equals("init")) {
if(type2.equals("condition")) {
src = src+" ; "+leaf2.getLabel();
}
}else if(type1.equals("condition")) {
if(type2.equals("incr")) {
src = src+" ; "+leaf2.getLabel();
}
}else {
src = src+"error other situation";
break;
// throw new Exception("没考虑过的children情况");
}
}
}
src = src+loopEnd;
if(src.contains(" "))
src = src.replace(" ", " ");
src = src.trim();
return src;
}
public static String recoverArguList(ITree root, List<ITree> arguLeaves, TreeContext srcT) throws Exception {
String arguSrc = "";
String end = "";
ITree node = root.getParent();
String type = srcT.getTypeLabel(node);//找到argument_list父节点
if(type.equals("name")) {//name情况用<>
arguSrc = arguSrc+" < ";
end = " > ";
}else if(type.equals("call")||type.equals("decl")) {//call的情况下用()
arguSrc = arguSrc+" ( ";
end = " ) ";
}else if(type.equals("constructor")||type.equals("function")) {
arguSrc = arguSrc+" ( ";
end = " ) ";
}
if(arguLeaves.size()==0) {
arguSrc = arguSrc+end;
return arguSrc;
}//返回空括号
if(arguLeaves.size()==1) {
arguSrc = arguSrc + deleteLiteral(arguLeaves.get(0), srcT)+end;
return arguSrc;
}//返回单个元素+括号
arguSrc = arguSrc + deleteLiteral(arguLeaves.get(0), srcT);
for(int i=0;i<arguLeaves.size()-1;i++) {
ITree leaf1 = arguLeaves.get(i);
ITree leaf2 = arguLeaves.get(i+1);
ITree sharePar = Utils.findShareParent(leaf1, leaf2, srcT);
// String parType = srcT.getTypeLabel(sharePar);
List<ITree> childs = sharePar.getChildren();
if(childs.contains(leaf1)&&childs.contains(leaf2)) {//同一层的两个叶子节点,还原时候直接拼起来就行
arguSrc = arguSrc+" "+deleteLiteral(leaf2, srcT);
}else if(childs.size()>=2){
ITree node1 = null;
ITree node2 = null;
for(ITree child : childs) {
if(child.isLeaf()) {
if(child.equals(leaf1))
node1 = child;
if(child.equals(leaf2))
node2 = child;
}else {
List<ITree> list = TreeUtils.preOrder(child);
if(list.contains(leaf1))
node1 = child;
if(list.contains(leaf2))
node2 = child;
// if(list.contains(leaf1)&&list.contains(leaf1))
// throw new Exception("wrong sharePar!");
}
}//找sharePar的下一个leaf1,leaf2对应父节点(或其本身)
String type1 = srcT.getTypeLabel(node1);
String type2 = srcT.getTypeLabel(node2);
if(type1.equals("name")) {
if(type2.equals("argument_list")||type2.equals("parameter_list")) {
List<ITree> leaves = new ArrayList<>();
leaves = Utils.traverse2Leaf(node2, leaves);//找到argulist中所有叶子
arguSrc = arguSrc + recoverArguList(node2, leaves, srcT);
}else if(type2.equals("operator")) {
arguSrc = arguSrc+" "+deleteLiteral(leaf2, srcT);
}else if(type2.equals("modifier")) {
arguSrc = arguSrc+" * ";
}else {
arguSrc = String.valueOf(srcT.getRoot().getId())+"error nameArg situation";
break;
// throw new Exception("没考虑过的name情况:"+type2);
}
}else if(type1.equals("argument")||type1.equals("parameter")) {
if(type2.equals("argument")||type2.equals("parameter")) {
arguSrc = arguSrc+" , "+deleteLiteral(leaf2, srcT);
}else {
arguSrc = String.valueOf(srcT.getRoot().getId())+"error argumentArg situation";
break;
// throw new Exception("没考虑过的argument情况:"+type2);
}
}else if(type1.equals("type")) {
if(type2.equals("name")) {
arguSrc = arguSrc+" "+deleteLiteral(leaf2, srcT);
}else {
arguSrc = String.valueOf(srcT.getRoot().getId())+"error typeArg situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else if(type1.equals("call")) {
if(type2.equals("operator")) {
arguSrc = arguSrc+" "+deleteLiteral(leaf2, srcT);
}else {
arguSrc = String.valueOf(srcT.getRoot().getId())+"error callArg situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else if(type1.equals("operator")) {
if(type2.equals("call")) {//好像有node2为call的情况
node2 = node2.getChildren().get(0);
type2 = srcT.getTypeLabel(node2);
}
if(type2.equals("name")||type2.equals("operator")) {
arguSrc = arguSrc+" "+deleteLiteral(leaf2, srcT);
}else {
arguSrc = String.valueOf(srcT.getRoot().getId())+"error operatorArg situation";
break;
// throw new Exception("没考虑过的operator情况:"+type2);
}
}else if(type1.equals("specifier")) {
if(type2.equals("name")){
arguSrc = arguSrc+" "+deleteLiteral(leaf2, srcT);
}else {
arguSrc = String.valueOf(srcT.getRoot().getId())+"error specifierArg situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else {
arguSrc = String.valueOf(srcT.getRoot().getId())+"error otherArg situation";
break;
// throw new Exception("没考虑过的children情况");
}
}
}
arguSrc = arguSrc+end;//加上收尾
return arguSrc;
}//argulist相当于subtree中的subtree,单独还原
public static String deleteLiteral(ITree leaf, TreeContext tc) {
String label = leaf.getLabel();
String type = tc.getTypeLabel(leaf);
if(type.equals("literal")) {
// if(isNumber(label)==true) {
// if(isInteger(label)==true) {
// label = "Int";
// }else if(isDouble(label)==true){
// label = "Float";
// }
// }
if(label.contains("\""))
label = "\"\"";
}
return label;
}
public static String absVariable(String src, HashMap<String, String> varMap) {
String[] srcs = src.split(" ");
String newLine = "";
if(srcs.length==1) {
String token = srcs[0];
if(varMap.containsKey(token)) {
if(newLine.equals("")) {
newLine = varMap.get(token);
}else
newLine = newLine+" "+varMap.get(token);
}else {
if(newLine.equals("")) {
newLine = token;
}else
newLine = newLine+" "+token;
}
}else {
for(int i=0;i<srcs.length-1;i++) {
String token = srcs[i];
String nextToken = srcs[i+1];
if(varMap.containsKey(token)) {
if(newLine.equals("")) {
newLine = varMap.get(token);
}else {
if(nextToken.equals("(")) {
newLine = newLine+" "+token;
}else
newLine = newLine+" "+varMap.get(token);
}
}else {
if(newLine.equals("")) {
newLine = token;
}else
newLine = newLine+" "+token;
}
}
newLine = newLine+" "+srcs[srcs.length-1];//补上尾巴
}
return newLine;
}
private static boolean isNumber (Object obj) {
if (obj instanceof Number) {
return true;
} else if (obj instanceof String){
try{
Double.parseDouble((String)obj);
return true;
}catch (Exception e) {
return false;
}
}
return false;
}
/*
* 判断是否为整数
* @param str 传入的字符串
* @return 是整数返回true,否则返回false
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
/*
* 判断是否为浮点数,包括double和float
* @param str 传入的字符串
* @return 是浮点数返回true,否则返回false
*/
public static boolean isDouble(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
return pattern.matcher(str).matches();
}
}
| 22,996
| 30.895978
| 110
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/Printing.java
|
package utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import gumtreediff.tree.TreeUtils;
import structure.Edge;
public class Printing {
public static void main (String args[]) throws Exception{
String path1 = "talker.cpp";
File cppfile1 = new File(path1);
TreeContext tc1 = new SrcmlCppTreeGenerator().generateFromFile(cppfile1);
String path2 = "talker2.cpp";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlCppTreeGenerator().generateFromFile(cppfile2);
mergeGraph(tc1, tc2);
}
public static void mergeGraph(TreeContext tc1, TreeContext tc2) throws IOException {
Matcher m = Matchers.getInstance().getMatcher("gumtree-topdown", tc1.getRoot(), tc2.getRoot());
m.match();//只包含topdown找到的同构子树mapping
MappingStore mappings = m.getMappings();
ArrayList<ITree> mapNodes1 = new ArrayList<>();
ArrayList<ITree> mapNodes2 = new ArrayList<>();
ArrayList<Edge> edges = new ArrayList<>();
HashMap<Integer, ITree> idMap1 = new HashMap<>();
HashMap<Integer, ITree> idMap2 = new HashMap<>();
HashMap<Integer, Integer> newid_map2 = new HashMap<>();
for(Mapping map : mappings) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
System.out.println("Mapping:"+src.getId()+"->"+dst.getId());
mapNodes1.add(src);
mapNodes2.add(dst);
}
// ArrayList<ITree> subRoots1 = searchSubRoot(mapNodes1);//找同构子树根节点
ArrayList<ITree> subRoots1 = mapNodes1;//所有同构子树节点全部包括
BufferedWriter wr = new BufferedWriter(new FileWriter(new File("tokens.txt")));
BufferedWriter wr1 = new BufferedWriter(new FileWriter(new File("edges.txt")));
BufferedWriter wr2 = new BufferedWriter(new FileWriter(new File("merge_nodes.txt")));
BufferedWriter wr3 = new BufferedWriter(new FileWriter(new File("node_map.txt")));
ITree root1 = tc1.getRoot();
List<ITree> preOrder1 = TreeUtils.preOrder(root1);
int nodeNum = preOrder1.size();
for(ITree node : preOrder1) {
int id = node.getId();
idMap1.put(id, node);
}
ITree root2 = tc2.getRoot();
int nextID = nodeNum;
List<ITree> preOrder2 = TreeUtils.preOrder(root2);
for(ITree node : preOrder2) {
int id = node.getId();
idMap2.put(id, node);
}//put AST nodes into ordered map
for(Map.Entry<Integer, ITree> entry : idMap2.entrySet()) {
int id = entry.getKey();
ITree node = entry.getValue();
int oldId = id;
if(mapNodes2.contains(node)) {
id = mappings.getSrc(node).getId();//将dst的id转成src的id
System.out.println(id+" "+oldId);
wr2.append(id+" "+oldId);
wr2.newLine();
wr2.flush();
newid_map2.put(oldId, id);
}else {
id = nextID;
newid_map2.put(oldId, id);
nextID++;
}
}// traverse tc2 firstly and put oldid and newid into the map
for(Map.Entry<Integer, ITree> entry : idMap1.entrySet()) {
int id = entry.getKey();
ITree node = entry.getValue();
ITree par = node.getParent();
String type = tc1.getTypeLabel(node);
String label = "NULL";
if(node.hasLabel()) {
label = node.getLabel();
}
if(par!=null) {
Edge edge = new Edge(par.getId(), id);
if(!edges.contains(edge)) {
wr1.append(par.getId()+" "+id);
wr1.newLine();
wr1.flush();
edges.add(edge);
}
}
wr.append(String.valueOf(id)+","+type+","+label);
wr.newLine();
wr.flush();
}
for(Map.Entry<Integer, ITree> entry : idMap2.entrySet()) {
int id = entry.getKey();
ITree node = entry.getValue();
ITree par = node.getParent();
String type = tc2.getTypeLabel(node);
String label = "NULL";
if(node.hasLabel()) {
label = node.getLabel();
}
int oldId = id;
// id += nodeNum;//将TC2的id加在TC1之后
System.out.println(id+","+newid_map2.get(id));
id = newid_map2.get(id);
wr3.append(oldId+"->"+id);
wr3.newLine();
wr3.flush();
// System.out.println(id);
if(par!=null) {
int parID = par.getId();
parID = newid_map2.get(parID);
Edge edge = new Edge(parID, id);
if(!edges.contains(edge)) {
wr1.append(parID+" "+id);
wr1.newLine();
wr1.flush();
edges.add(edge);
}
}
if(!mapNodes2.contains(node)) {
wr.append(String.valueOf(id)+","+type+","+label);
wr.newLine();
wr.flush();
}
}
// int vitualID = nodeNum+preOrder2.size();
// for(ITree src : subRoots1) {
// ITree dst = mappings.getDst(src);
// int srcID = src.getId();
// int dstID = nodeNum+dst.getId();
// wr1.append(srcID+" "+vitualID);
// wr.append(vitualID+",virtualNode,NULL");
// wr.newLine();
// wr.flush();
// wr2.append(srcID+","+dstID);
// wr2.newLine();
// wr2.append(String.valueOf(vitualID));
// wr1.newLine();
// wr2.newLine();
// wr1.append(dstID+" "+vitualID);
// wr1.newLine();
// wr1.flush();
// wr2.flush();
// vitualID++;
// }
wr.close();
wr1.close();
wr2.close();
wr3.close();
}
private static ArrayList<ITree> searchSubRoot(ArrayList<ITree> mapNodes) {
ArrayList<ITree> subRoots = new ArrayList<>();
for(ITree node : mapNodes) {
boolean hasPar = false;
List<ITree> pars = node.getParents();
for(ITree node1 : mapNodes) {
if(pars.contains(node1)) {
hasPar = true;
break;
}
}
if (!hasPar) {
subRoots.add(node);
}
}
return subRoots;
}
}
| 5,850
| 28.852041
| 103
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/Similarity.java
|
package utils;
import java.util.ArrayList;
import java.util.List;
import apted.costmodel.StringUnitCostModel;
import apted.distance.APTED;
import apted.node.Node;
import apted.node.StringNodeData;
import apted.parser.BracketStringInputParser;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import structure.SubTree;
public class Similarity {
private static TreeContext tCont;
public static double getSimilarity(SubTree st1, SubTree st2) throws Exception {
float editDistance = getEditDistance(st1, st2);
ITree subRoot1 = st1.getRoot();
ITree subRoot2 = st2.getRoot();
List<ITree> nodes1 = new ArrayList<>();
nodes1 = Utils.collectNode(subRoot1, nodes1);
int nodeNum1 = nodes1.size();
List<ITree> nodes2 = new ArrayList<>();
nodes2 = Utils.collectNode(subRoot2, nodes2);
int nodeNum2 = nodes2.size();
int edgeNum1 = 0;
edgeNum1 = Utils.collectEdge(subRoot1, edgeNum1);
int edgeNum2 = 0;
edgeNum2 = Utils.collectEdge(subRoot2, edgeNum2);
double similarity = 1.0-editDistance/(nodeNum1+nodeNum2+edgeNum1+edgeNum2);
// System.out.println(similarity);
return similarity;
}
public static float getEditDistance(SubTree st1, SubTree st2) throws Exception {
String srcTree = transfer2string(st1);
String dstTree = transfer2string(st2);
// System.out.println(srcTree);
// System.out.println(dstTree);
BracketStringInputParser parser = new BracketStringInputParser();
Node<StringNodeData> t1 = parser.fromString(srcTree);
Node<StringNodeData> t2 = parser.fromString(dstTree);
// Initialise APTED.
APTED<StringUnitCostModel, StringNodeData> apted = new APTED<>(new StringUnitCostModel());
// Execute APTED.
float result = apted.computeEditDistance(t1, t2);
// System.out.println(result);
// List<int[]> editMapping = apted.computeEditMapping();
// for (int[] nodeAlignment : editMapping) {
// System.out.println(nodeAlignment[0] + "->" + nodeAlignment[1]);
// }
return result;
}
public static String transfer2string(SubTree st) throws Exception {
tCont = st.getTC();
ITree root = st.getRoot();
String bracketTree = "";
List<ITree> children = root.getChildren();
if(children.isEmpty())
throw new Exception("check the root!");
else {
bracketTree = traverse(root, bracketTree, 0);
}
return bracketTree;
}
private static String traverse(ITree node, String bracketTree, int num) throws Exception {
List<ITree> childs = node.getChildren();
String type = tCont.getTypeLabel(node);
// int size = node.getParent().getChildren().size()-1;
bracketTree = bracketTree + "{"+tCont.getTypeLabel(node);
if (node.hasLabel()&&childs.size()==0) {
if(type.equals("name")) {
if(node.isRoot())
throw new Exception("why root???");
ITree par = node.getParent();
String parType = tCont.getTypeLabel(par);
List<ITree> parChilds = par.getChildren();
if(parType.equals("decl")&&parChilds.get(1).equals(node)) {//抽象掉decl的第二个节点也就是name部分的名字
ITree firstChild = parChilds.get(0);
String firstType = tCont.getTypeLabel(firstChild);
if(firstType.equals("type")) {
if(parChilds.size()==1)
throw new Exception("unknown size");
else
bracketTree = bracketTree+"(declName)";
}else
bracketTree = bracketTree+"("+node.getLabel()+")";
}else
bracketTree = bracketTree+"("+node.getLabel()+")";
}else
bracketTree = bracketTree+"("+node.getLabel()+")";
}
for(int i=0;i<childs.size();i++) {
ITree child = childs.get(i);
bracketTree = traverse(child, bracketTree, i);
}
bracketTree = bracketTree +"}";
return bracketTree;
}//收集AST树中所有点
}
| 3,639
| 33.018692
| 92
|
java
|
SeqTrans
|
SeqTrans-master/gumtree/src/utils/Utils.java
|
package utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import gumtreediff.actions.ActionGenerator;
import gumtreediff.actions.model.Action;
import gumtreediff.actions.model.Delete;
import gumtreediff.actions.model.Insert;
import gumtreediff.actions.model.Move;
import gumtreediff.actions.model.Update;
import gumtreediff.gen.srcml.SrcmlCppTreeGenerator;
import gumtreediff.matchers.Mapping;
import gumtreediff.matchers.MappingStore;
import gumtreediff.matchers.Matcher;
import gumtreediff.matchers.Matchers;
import gumtreediff.tree.ITree;
import gumtreediff.tree.TreeContext;
import gumtreediff.tree.TreeUtils;
import nodecluster.Cluster;
import split.Split;
import structure.Boundary;
import structure.ChangeTuple;
import structure.DTree;
import structure.SubTree;
public class Utils {
public static void main (String args[]) throws Exception{
String path = "talker.cpp";
File cppfile = new File(path);
TreeContext tc1 = new SrcmlCppTreeGenerator().generateFromFile(cppfile);
String path2 = "talker2.cpp";
File cppfile2 = new File(path2);
TreeContext tc2 = new SrcmlCppTreeGenerator().generateFromFile(cppfile2);
// HashMap<String, LinkedList<Action>> actions = collectAction(tc1, tc2);
// printAllActions(tc1, tc2, actions);
String miName = path2.split("/")[path2.split("/").length-1];//标记文件名
Split sp = new Split();
ArrayList<SubTree> sts = sp.splitSubTree(tc2, miName);
System.out.println(sts.size());
for(SubTree st : sts) {
String src = subtree2src(st);
System.out.println(src);
}
}
public static String subtree2src(SubTree st) throws Exception {//old version
String src = "";
String loopEnd = "";
ITree root = st.getRoot();
TreeContext srcT = st.getTC();
String sType = srcT.getTypeLabel(root);
if(sType.equals("while")||sType.equals("for")) {
if(sType.equals("while"))
src = src+"while(";
if(sType.equals("for"))
src = src+"for(";
loopEnd = ")";
}
List<ITree> leaves = new ArrayList<>();
leaves = traverse2Leaf(root, leaves);
// System.out.println(leaves.size());
// for(ITree leaf : leaves) {
// String type = srcT.getTypeLabel(leaf);
// String label = leaf.getLabel();
// System.out.println(type+":"+label);
// }
if(leaves.size()==0)
throw new Exception("null leaves");
else if(leaves.size()==1) {
src = src+leaves.get(0).getLabel();//先把0号叶子放入
return src;
}
src = src+leaves.get(0).getLabel();//先把0号叶子放入
for(int i=0;i<leaves.size()-1;i++) {
int size = 0;
ITree leaf1 = leaves.get(i);
ITree leaf2 = leaves.get(i+1);
if(leaf1.isRoot()||leaf2.isRoot())//叶子节点为总树根节点,可能么?
throw new Exception("why is root???");
ITree sharePar = findShareParent(leaf1, leaf2, srcT);
// String parType = srcT.getTypeLabel(sharePar);
List<ITree> childs = sharePar.getChildren();
if(childs.contains(leaf1)&&childs.contains(leaf2)) {//同一层的两个叶子节点,还原时候直接拼起来就行
src = src+ leaf2.getLabel();
}else if(childs.size()>=2){//分情况讨论不同分支下还原代码问题
ITree node1 = null;
ITree node2 = null;
for(ITree child : childs) {
if(child.isLeaf()) {
if(child.equals(leaf1))
node1 = child;
if(child.equals(leaf2))
node2 = child;
}else {
List<ITree> list = TreeUtils.preOrder(child);
if(list.contains(leaf1))
node1 = child;
if(list.contains(leaf2))
node2 = child;
// if(list.contains(leaf1)&&list.contains(leaf1))
// throw new Exception("wrong sharePar!");
}
}//找sharePar的下一个leaf1,leaf2对应父节点(或其本身)
String type1 = "";
String type2 = "";
if(node1!=null&&node2!=null) {
type1 = srcT.getTypeLabel(node1);
type2 = srcT.getTypeLabel(node2);
}else
System.out.println("why node is null?"+st.getMiName()+","+st.getRoot().getId());
if(type1.equals("name")) {
if(type2.equals("argument_list")||type2.equals("parameter_list")) {
List<ITree> arguLeaves = new ArrayList<>();
arguLeaves = traverse2Leaf(node2, arguLeaves);//找到argulist中所有叶子
src = src + recoverArguList(node2, arguLeaves, srcT);//argulist单独处理
size = arguLeaves.size();
i=i+size-1;
}else if(type2.equals("init")) {
src = src+"="+leaf2.getLabel();
}else if(type2.equals("operator")) {
src = src+leaf2.getLabel();
}else {
src = "error situation";
break;
// throw new Exception("没考虑过的name情况:"+type2);
}
}else if(type1.equals("type")) {
if(type2.equals("name")) {
src = src+" "+leaf2.getLabel();
}else {
src = "error situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else if(type1.equals("operator")) {
if(type2.equals("call")) {//好像有node2为call的情况
node2 = node2.getChildren().get(0);
type2 = srcT.getTypeLabel(node2);
}
if(type2.equals("name")||type2.equals("operator")) {
src = src+leaf2.getLabel();
}else {
src = "error situation";
break;
// throw new Exception("没考虑过的operator情况:"+type2);
}
}else if(type1.equals("specifier")) {
if(type2.equals("name")){
src = src+" "+leaf2.getLabel();
}else {
src = "error situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}
}else {
src = "error situation";
break;
// throw new Exception("没考虑过的children情况");
}
}
src = src+loopEnd;
return src;
}
public static String recoverArguList(ITree root, List<ITree> arguLeaves, TreeContext srcT) throws Exception {
String arguSrc = "";
String end = "";
ITree node = root.getParent();
String type = srcT.getTypeLabel(node);//找到argument_list父节点
if(type.equals("name")) {//name情况用<>
arguSrc = arguSrc+"<";
end = ">";
}else if(type.equals("call")||type.equals("decl")) {//call的情况下用()
arguSrc = arguSrc+"(";
end = ")";
}else if(type.equals("constructor")||type.equals("function")) {
arguSrc = arguSrc+"(";
end = ")";
}
if(arguLeaves.size()==0) {
arguSrc = arguSrc+end;
return arguSrc;
}//返回空括号
if(arguLeaves.size()==1) {
arguSrc = arguSrc + arguLeaves.get(0).getLabel()+end;
return arguSrc;
}//返回单个元素+括号
arguSrc = arguSrc + arguLeaves.get(0).getLabel();
for(int i=0;i<arguLeaves.size()-1;i++) {
ITree leaf1 = arguLeaves.get(i);
ITree leaf2 = arguLeaves.get(i+1);
ITree sharePar = findShareParent(leaf1, leaf2, srcT);
// String parType = srcT.getTypeLabel(sharePar);
List<ITree> childs = sharePar.getChildren();
if(childs.contains(leaf1)&&childs.contains(leaf2)) {//同一层的两个叶子节点,还原时候直接拼起来就行
arguSrc = arguSrc+ leaf2.getLabel();
}else if(childs.size()>=2){
ITree node1 = null;
ITree node2 = null;
for(ITree child : childs) {
if(child.isLeaf()) {
if(child.equals(leaf1))
node1 = child;
if(child.equals(leaf2))
node2 = child;
}else {
List<ITree> list = TreeUtils.preOrder(child);
if(list.contains(leaf1))
node1 = child;
if(list.contains(leaf2))
node2 = child;
// if(list.contains(leaf1)&&list.contains(leaf1))
// throw new Exception("wrong sharePar!");
}
}//找sharePar的下一个leaf1,leaf2对应父节点(或其本身)
String type1 = srcT.getTypeLabel(node1);
String type2 = srcT.getTypeLabel(node2);
if(type1.equals("name")) {
if(type2.equals("argument_list")||type2.equals("parameter_list")) {
List<ITree> leaves = new ArrayList<>();
leaves = traverse2Leaf(node2, leaves);//找到argulist中所有叶子
arguSrc = arguSrc + recoverArguList(node2, leaves, srcT);
}else if(type2.equals("operator")) {
arguSrc = arguSrc+leaf2.getLabel();
}else if(type2.equals("modifier")) {
arguSrc = arguSrc+" *";
}else {
arguSrc = "error situation";
break;
// throw new Exception("没考虑过的name情况:"+type2);
}
}else if(type1.equals("argument")||type1.equals("parameter")) {
if(type2.equals("argument")||type2.equals("parameter")) {
arguSrc = arguSrc+","+leaf2.getLabel();
}else {
arguSrc = "error situation";
break;
// throw new Exception("没考虑过的argument情况:"+type2);
}
}else if(type1.equals("type")) {
if(type2.equals("name")) {
arguSrc = arguSrc+" "+leaf2.getLabel();
}else {
arguSrc = "error situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else if(type1.equals("operator")) {
if(type2.equals("call")) {//好像有node2为call的情况
node2 = node2.getChildren().get(0);
type2 = srcT.getTypeLabel(node2);
}
if(type2.equals("name")||type2.equals("operator")) {
arguSrc = arguSrc+leaf2.getLabel();
}else {
arguSrc = "error situation";
break;
// throw new Exception("没考虑过的operator情况:"+type2);
}
}else if(type1.equals("specifier")) {
if(type2.equals("name")){
arguSrc = arguSrc+" "+leaf2.getLabel();
}else {
arguSrc = "error situation";
break;
// throw new Exception("没考虑过的type情况:"+type2);
}
}else {
arguSrc = "error situation";
break;
// throw new Exception("没考虑过的children情况");
}
}
}
arguSrc = arguSrc+end;//加上收尾
return arguSrc;
}//argulist相当于subtree中的subtree,单独还原
public static ChangeTuple filterChange(DTree sDT, DTree dDT) throws Exception {
ChangeTuple ct = new ChangeTuple();
TreeContext sTC = sDT.getTreeContext();
TreeContext dTC = dDT.getTreeContext();
ITree sRoot = sDT.getRoot();
ITree dRoot = dDT.getRoot();
List<ITree> sLeaves = new ArrayList<>();
List<ITree> dLeaves = new ArrayList<>();
sLeaves = traverse2Leaf(sRoot, sLeaves);
dLeaves = traverse2Leaf(dRoot, dLeaves);
ArrayList<Integer> sameLocation = new ArrayList<>();
ArrayList<Integer> diffLocation = new ArrayList<>();
for(ITree sLeaf : sLeaves) {
String sType = sTC.getTypeLabel(sLeaf);
String sValue = sLeaf.getLabel();
int pos1 = sLeaf.positionInParent();
for(ITree dLeaf : dLeaves) {
String dType = dTC.getTypeLabel(dLeaf);
String dValue = dLeaf.getLabel();
int pos2 = dLeaf.positionInParent();
if(sType.equals(dType)&&sValue.equals(dValue)) {
if(pos1==pos2)
sameLocation.add(pos1);
}else {
if(pos1==pos2)
diffLocation.add(pos1);
}
}
}
Collections.sort(sameLocation);
Collections.sort(diffLocation);
String sString = "";
String dString = "";
ArrayList<ITree> sMoves = new ArrayList<>();
ArrayList<ITree> dMoves = new ArrayList<>();
if(diffLocation.size()!=0&&sameLocation.size()!=0) {
if(diffLocation.get(diffLocation.size()-1)<sameLocation.get(0)||
diffLocation.get(0)>sameLocation.get(sameLocation.size()-1)) {
for(int i=0;i<sameLocation.size();i++){
ITree sLeaf = sLeaves.get(sameLocation.get(i));
ITree dLeaf = dLeaves.get(sameLocation.get(i));
sMoves.add(sLeaf);
dMoves.add(dLeaf);
}
for(ITree node : sMoves) {
sLeaves.remove(node);
}
for(ITree node : dMoves) {
dLeaves.remove(node);
}
for(ITree leaf : sLeaves) {
String value = leaf.getLabel();
sString = sString + value;
}
for(ITree leaf : dLeaves) {
String value = leaf.getLabel();
dString = dString + value;
}
ct.setSrc(sString);
ct.setDst(dString);
//diff的最后一个位置编号也比same小或第一个位置编号就比same大,只保留diff部分,否则不改
}else {
sString = Utils.printLeaf(sDT);
dString = Utils.printLeaf(dDT);
ct.setSrc(sString);
ct.setDst(dString);
}
}else if(sameLocation.size()==0) {
sString = Utils.printLeaf(sDT);
dString = Utils.printLeaf(dDT);
ct.setSrc(sString);
ct.setDst(dString);
}else {
throw new Exception("error!");
}
return ct;
}//change中包含相同的不修改部分,需要过滤删除
public static ITree findShareParent(ITree leaf1, ITree leaf2, TreeContext tc) throws Exception {
if(leaf1.isRoot()||leaf2.isRoot())
throw new Exception("check the leaf!");
ITree sharePar = null;
if(leaf1.getParent().equals(leaf2.getParent()))//大概率同个父亲
sharePar = leaf1.getParent();
else {
ITree subRoot = traverSubRoot(leaf1, tc);
boolean ifSamePar = true;
while(ifSamePar) {
List<ITree> children = subRoot.getChildren();
for(ITree child : children) {
List<ITree> order = TreeUtils.preOrder(child);
if(order.contains(leaf1)&&order.contains(leaf2)) {
ifSamePar = true;
subRoot = child;
break;
}
else
ifSamePar = false;
}
}
sharePar = subRoot;
}
// System.out.println("find sharePar:"+tc.getTypeLabel(sharePar));
return sharePar;
}//找两个节点共有最低的父亲节点
public static ITree traverSubRoot(ITree node, TreeContext tc) {
ITree subRoot = null;
String typeLabel = tc.getTypeLabel(node);
while(!ifSRoot(typeLabel)) {//可能有问题,要注意循环条件
if(node.isRoot()) {//发现有修改include的情况,subroot为总树根节点
subRoot = node;
break;
}else {
node = node.getParent();
typeLabel = tc.getTypeLabel(node);
// System.out.println("typeLabel:"+typeLabel);
subRoot = node;
}
}
return subRoot;
}//往上追溯某节点在子树内的根节点
public static ITree searchBlock(SubTree sub) throws Exception {
ITree sRoot = sub.getRoot();
TreeContext tc = sub.getTC();
ITree par = sRoot.getParent();
while(par!=null&&!tc.getTypeLabel(par).equals("block")) {
par = par.getParent();
}
if(par==null) {
return null;
}else {
return par;
}
}//搜索并定位父亲节点中的第一个block节点
public static ITree searchFunction(SubTree st) {
TreeContext tc = st.getTC();
List<ITree> pars = st.getPars();
for(ITree par : pars) {
String type = tc.getTypeLabel(par);
if(type.equals("function"))
return par;
}
return null;
}
public static ArrayList<ITree> searchFunctions(TreeContext tc){
ArrayList<ITree> functions = new ArrayList<>();
ITree root = tc.getRoot();
List<ITree> des = root.getDescendants();
for(ITree node : des) {
String type = tc.getTypeLabel(node);
if(type.equals("function")) {
functions.add(node);
}
}
return functions;
}
public static Boundary searchSubtreeBoundary(SubTree st) {
ITree sRoot = st.getRoot();
TreeContext tc = st.getTC();
List<ITree> nodes1 = sRoot.getDescendants();
nodes1.add(sRoot);//srcT所有节点
int sBeginLine = 0;
int sLastLine = 0;
int sBeginCol = 0;
int sLastCol = 0;
for(ITree node : nodes1) {
int line = node.getLine();
int col = node.getColumn();
int lastLine = node.getLastLine();
int lastCol = node.getLastColumn();
String type = tc.getTypeLabel(node);
if(!type.equals("block")) {//跳过block节点,该节点会导致lastline为大括号结束位置
if(sBeginLine==0&&line!=0) {
sBeginLine = line;
}else if(line < sBeginLine&&line!=0) {
sBeginLine = line;
}//begin line
if(sBeginCol==0&&col!=0) {
sBeginCol = col;
}else if(col < sBeginCol&&col!=0) {
sBeginCol = col;
}//begin col
if(lastLine > sLastLine) {
sLastLine = lastLine;
}//last line
if(lastCol > sLastCol) {
sLastCol = lastCol;
}//last col
// if(sRoot.getId()==16329) {
// System.err.println(node.getId()+type+":"+line+","+lastLine+","+col+","+lastCol);
// }
}else if(type.equals("empty_stmt"))//特殊情况
continue;
}
Boundary boundary = new Boundary(sRoot, sBeginLine, sLastLine, sBeginCol, sLastCol);
System.out.println("FCID:"+sRoot.getId()+";"+sBeginLine+","+sLastLine+","+sBeginCol+","+sLastCol);
return boundary;
}
public static Boundary searchFunctionBoundary(ITree function, TreeContext tc) throws Exception {
String type = tc.getTypeLabel(function);
if(!type.equals("function"))
throw new Exception("not a function! "+type);
List<ITree> des = function.getDescendants();
int beginLine = 0;
int lastLine = 0;
int beginCol = 0;
int lastCol = 0;
for(ITree node : des) {
int beginLine_tmp = node.getLine();
int beginCol_tmp = node.getColumn();
int lastLine_tmp = node.getLastLine();
int lastCol_tmp = node.getLastColumn();
if(beginLine==0&&beginLine_tmp!=0) {
beginLine = beginLine_tmp;
}else if(beginLine_tmp < beginLine&&beginLine_tmp!=0) {
beginLine = beginLine_tmp;
}//begin line
if(beginCol==0&&beginCol_tmp!=0) {
beginCol = beginCol_tmp;
}else if(beginCol_tmp < beginCol&&beginCol_tmp!=0) {
beginCol = beginCol_tmp;
}//begin col
if(lastLine_tmp > lastLine) {
lastLine = lastLine_tmp;
}//last line
if(lastCol_tmp > lastCol) {
lastCol = lastCol_tmp;
}//last col
}
Boundary boundary = new Boundary(function, beginLine, lastLine, beginCol, lastCol);
System.out.println("FCID:"+function.getId()+";"+beginLine+","+lastLine+","+beginCol+","+lastCol);
return boundary;
}
public static List<ITree> collectNode(ITree node, List<ITree> nodes) throws Exception {
if(nodes.isEmpty())
nodes.add(node);
if(node.isRoot()&&node.getChildren().isEmpty())
throw new Exception("Empty root");
List<ITree> childs = node.getChildren();
nodes.addAll(node.getChildren());
for(ITree child : childs) {
if(!child.getChildren().isEmpty()) {
collectNode(child, nodes);
}else continue;
}
return nodes;
}//收集AST树中所有点
public static Integer collectEdge(ITree node, int num) {
List<ITree> childs = node.getChildren();
for(ITree child : childs) {
num = num+1;
// System.out.println(child.getParent().getId()+"->"+child.getId());
collectEdge(child, num);
}
return num;
}//收集AST树中所有边
public static ArrayList<Integer> collectSrcActNodeIds(TreeContext tc1, TreeContext tc2, MappingStore mappings, HashMap<String, LinkedList<Action>> actMap) throws Exception{
ArrayList<Integer> srcActIds = new ArrayList<>();
HashMap<String, LinkedList<Action>> actions = actMap;
LinkedList<Action> updates = actions.get("update");
LinkedList<Action> deletes = actions.get("delete");
LinkedList<Action> inserts = actions.get("insert");
LinkedList<Action> moves = actions.get("move");
Cluster cl = new Cluster(tc1, tc2, mappings);
for(Action a : updates) {
int id = a.getNode().getId();
srcActIds.add(id);
}
for(Action a : deletes) {
int id = a.getNode().getId();
srcActIds.add(id);
}
// for(Action a : inserts) {
// ITree sRoot = cl.traverseSRoot(a);//似乎不应该指定sRoot,应寻找insert的root
// if(sRoot==null) {
// System.err.println("insert err");
// continue;//碰见一次,原因未知
// }
// int id = sRoot.getId();
// srcActIds.add(id);
// }
cl.buildInsertMap(inserts);//似乎不应该指定sRoot,先建立insert node 映射关系
for(Action a : inserts) {
ITree dst = a.getNode();
ITree mapped_insert_root = cl.traverseRealParent(a);//该action根节点insert_root在src树上的映射
if(mapped_insert_root==null) {
throw new Exception("mapped_insert_root is null!"+dst.getId());
// System.err.println("mapped_insert_root is null!");
// continue;//碰见一次,原因未知
}
int id = mapped_insert_root.getId();
srcActIds.add(id);
}
for(Action a : moves) {
ITree src = a.getNode();
List<ITree> des = src.getDescendants();
des.add(src);
for(ITree child : des) {
int id = child.getId();
srcActIds.add(id);
}//all children and itself are added into the changeList
ITree sRoot = cl.findMovRoot(a);
if(sRoot==null) {
// throw new Exception("sRoot is null!"+src.getId());
// System.err.println("move err");
continue;//碰见一次,原因未知
}
int root_id = sRoot.getId();
srcActIds.add(root_id);
}
return srcActIds;
}
public static String printToken(SubTree st) throws Exception {
String tokens = "";
ITree sRoot = st.getRoot();
List<ITree> leaves = new ArrayList<>();
leaves = traverse2Leaf(sRoot, leaves);
for(int i=0;i<leaves.size();i++) {
ITree leaf = leaves.get(i);
String label = leaf.getLabel();
// if(!label.equals("")) {
// tokens = tokens+label;
// }
tokens = tokens+leaf.getId()+":"+label;
if(i!=leaves.size()-1) {
tokens = tokens+" ";
}
}
return tokens;
}
public static String printLeaf(DTree dt) throws Exception {
String values = "";
List<ITree> leaves = dt.getLeaves();
for(ITree leaf : leaves) {
values = values + leaf.getLabel();
}
return values;
}
public static String printDTree(DTree dt) {
String dString = "";
String typeName = dt.getRootType();
dString = dString+dt.getRoot().getId()+typeName+"{";
List<ITree> leaves = dt.getLeaves();
for(ITree leaf : leaves) {
dString = dString+leaf.getId()+leaf.getLabel()+",";
}
dString = dString.substring(0, dString.length()-1)+"}";
return dString;
}
public static String printParents(ITree node, TreeContext tc) {
List<ITree> pars = node.getParents();
String parString = "";
for(ITree par : pars) {
String parType = tc.getTypeLabel(par);
parString = parString+parType;
}
return parString;
}
public static List<ITree> traverse2Leaf(ITree node, List<ITree> leafList) throws Exception{//从根节点深度遍历至叶子节点,优先确定path相同的leaf mappings
List<ITree> childList = node.getChildren();
if(node.isLeaf()){
leafList.add(node);
}else{
for(ITree child : childList){
leafList = traverse2Leaf(child, leafList);
}
}
return leafList;
}
public static HashMap<String, LinkedList<Action>> collectAction(TreeContext tc1, TreeContext tc2, MappingStore mappings) {
ActionGenerator g = new ActionGenerator(tc1.getRoot(), tc2.getRoot(), mappings);
List<Action> actions = g.generate();
System.out.println("ActionSize:"+actions.size());
checkTCRoot(tc1);
checkTCRoot(tc2);
HashMap<Integer, Integer> mapping1 = new HashMap<>();
for(Mapping map : mappings) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
mapping1.put(src.getId(), dst.getId());
}
System.out.println("mapSize:"+mapping1.size());
HashMap<String, LinkedList<Action>> actionMap = new HashMap<>();
HashMap<Integer, Action> moves = new HashMap<>();
HashMap<Integer, Action> updates = new HashMap<>();
HashMap<Integer, Action> inserts = new HashMap<>();
HashMap<Integer, Action> deletes = new HashMap<>();
ArrayList<Integer> movId = new ArrayList<>();
ArrayList<Integer> uptId = new ArrayList<>();
ArrayList<Integer> addId = new ArrayList<>();
ArrayList<Integer> delId = new ArrayList<>();
LinkedList<Action> mov = new LinkedList<>();
LinkedList<Action> upt = new LinkedList<>();
LinkedList<Action> add = new LinkedList<>();
LinkedList<Action> del = new LinkedList<>();
for (Action a : actions) {
ITree src = a.getNode();
if (a instanceof Move) {
moves.put(src.getId(), a);
movId.add(src.getId());
// System.out.println(((Move)a).toString());
} else if (a instanceof Update) {
updates.put(src.getId(), a);
uptId.add(src.getId());
// System.out.println(((Update)a).toString());
} else if (a instanceof Insert) {
inserts.put(src.getId(), a);
addId.add(src.getId());
// System.out.println(((Insert)a).toString());
} else if (a instanceof Delete) {
deletes.put(src.getId(), a);
delId.add(src.getId());
// System.out.println(((Delete)a).toString());
}
}
for(int n : movId) {
Action tmp = moves.get(n);
mov.add(tmp);
}
for(int n : uptId) {
Action tmp = updates.get(n);
upt.add(tmp);
}
for(int n : addId) {
Action tmp = inserts.get(n);
add.add(tmp);
}
for(int n : delId) {
Action tmp = deletes.get(n);
del.add(tmp);
}
actionMap.put("move", mov);
actionMap.put("update", upt);
actionMap.put("insert", add);
actionMap.put("delete", del);
return actionMap;
}
public static void printAllActions(TreeContext tc1, TreeContext tc2, HashMap<String, LinkedList<Action>> actionMap) {
Matcher m = Matchers.getInstance().getMatcher(tc1.getRoot(), tc2.getRoot());
m.match();
for(Mapping map : m.getMappings()) {
ITree src = map.getFirst();
ITree dst = map.getSecond();
System.out.println("Mapping:"+src.getId()+"->"+dst.getId());
}
LinkedList<Action> moves = actionMap.get("move");
LinkedList<Action> updates = actionMap.get("update");
LinkedList<Action> inserts = actionMap.get("insert");
LinkedList<Action> deletes = actionMap.get("delete");
for (Action element : moves) {
Move act = (Move)element;
System.out.println("Mov:"+act.getNode().getId()+"->"+act.getParent().getId()+","+act.getPosition());
}
for (Action update : updates) {
Update act = (Update)update;
System.out.println("Upt:"+act.getNode().getId()+","+act.getValue());
}
for (Action act : inserts) {
ITree dst = act.getNode();
System.out.println("dstID:"+dst.getId());
// ITree src = mappings.getSrc(dst);
String label = Integer.toString(dst.getId());
if (dst.hasLabel()) label = label+","+dst.getLabel();
if (tc2.hasLabelFor(dst.getType()))
label = label+","+tc2.getTypeLabel(dst.getType());
System.out.println("Add:"+label+"->"+dst.getParent().getId()+","+dst.getParent().getChildPosition(dst));
}
for (Action delete : deletes) {
Delete act = (Delete)delete;
System.out.println("Del:"+act.getNode().getId());
}
}
public static ITree findNode(TreeContext tc, int id) throws Exception{
ITree root = tc.getRoot();
List<ITree> nodes = new ArrayList<>();
nodes = collectNode(root, nodes);
ITree target = null;
for(ITree node : nodes) {
if(node.getId()==id) {
target = node;
}
}
return target;
}
public static Boolean ifSRoot(String typeLabel) {//该方法关系到subtree划分,非常重要
if(typeLabel=="decl_stmt"||typeLabel=="expr_stmt"||typeLabel=="while"||
typeLabel=="function"||typeLabel=="function_decl"||typeLabel=="if"||
typeLabel=="else"||typeLabel=="ternary"||typeLabel=="for"||
typeLabel=="class"||typeLabel=="return"||typeLabel=="catch"||
typeLabel=="try"||typeLabel=="throw"||typeLabel=="enum"||
typeLabel=="constructor"||typeLabel=="constructor_decl"||
typeLabel=="interface"||typeLabel=="switch"||typeLabel=="then") {
return true;//include暂时不算typelabel, mapping有问题,import也不考虑
}else
return false;
}//SRoot条件可能有遗漏
public static Boolean ifChild(ITree root, ITree target) throws Exception {
Boolean findNode = null;
// if(root.getId()==target.getId())
// throw new Exception("error id! "+target.getId());
List<ITree> childs = TreeUtils.preOrder(root);
for(ITree t : childs) {
if(t.equals(target))
findNode = true;
}
if(findNode==null)
findNode = false;
return findNode;
}
public static void checkTCRoot(TreeContext tc){//发现action后有迷之根节点
ITree root = tc.getRoot();
if(root.getParent()!=null) {
System.err.println("find error root!!"+root.getParent().getId()+tc.getTypeLabel(root.getParent()));
root.setParent(null);
}
}
}
| 27,109
| 31.235434
| 173
|
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/AccountApplication.java
|
package com.piggymetrics.account;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
@SpringBootApplication
@EnableDiscoveryClient
@EnableOAuth2Client
@EnableFeignClients
@EnableCircuitBreaker
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AccountApplication {
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
}
}
| 870
| 35.291667
| 102
|
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/client/AuthServiceClient.java
|
package com.piggymetrics.account.client;
import com.piggymetrics.account.domain.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "auth-service")
public interface AuthServiceClient {
@RequestMapping(method = RequestMethod.POST, value = "/uaa/users", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(User user);
}
| 536
| 32.5625
| 117
|
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/client/StatisticsServiceClient.java
|
package com.piggymetrics.account.client;
import com.piggymetrics.account.domain.Account;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "statistics-service", fallback = StatisticsServiceClientFallback.class)
public interface StatisticsServiceClient {
@RequestMapping(method = RequestMethod.PUT, value = "/statistics/{accountName}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void updateStatistics(@PathVariable("accountName") String accountName, Account account);
}
| 737
| 42.411765
| 131
|
java
|
piggymetrics
|
piggymetrics-master/account-service/src/main/java/com/piggymetrics/account/client/StatisticsServiceClientFallback.java
|
package com.piggymetrics.account.client;
import com.piggymetrics.account.domain.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author cdov
*/
@Component
public class StatisticsServiceClientFallback implements StatisticsServiceClient {
private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsServiceClientFallback.class);
@Override
public void updateStatistics(String accountName, Account account) {
LOGGER.error("Error during update statistics for account: {}", accountName);
}
}
| 598
| 30.526316
| 104
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.