01: package org.incava.java;
02:
03: import java.util.*;
04: import net.sourceforge.pmd.ast.*;
05:
06: /**
07: * Miscellaneous routines for fields.
08: */
09: public class FieldUtil extends SimpleNodeUtil {
10: public static Token getName(ASTVariableDeclarator vd) {
11: ASTVariableDeclaratorId vid = (ASTVariableDeclaratorId) findChild(
12: vd, ASTVariableDeclaratorId.class);
13: Token nameTk = vid.getFirstToken();
14: return nameTk;
15: }
16:
17: public static ASTVariableDeclarator[] getVariableDeclarators(
18: ASTFieldDeclaration fld) {
19: return (ASTVariableDeclarator[]) findChildren(fld,
20: ASTVariableDeclarator.class);
21: }
22:
23: /**
24: * Returns a string in the form "a, b, c", for the variables declared in
25: * this field.
26: */
27: public static String getNames(ASTFieldDeclaration fld) {
28: ASTVariableDeclarator[] avds = getVariableDeclarators(fld);
29: StringBuffer buf = new StringBuffer();
30: for (int ai = 0; ai < avds.length; ++ai) {
31: ASTVariableDeclarator avd = avds[ai];
32: if (ai > 0) {
33: buf.append(", ");
34: }
35: buf.append(VariableUtil.getName(avd).image);
36: }
37: return buf.toString();
38: }
39:
40: public static double getMatchScore(ASTFieldDeclaration a,
41: ASTFieldDeclaration b) {
42: ASTVariableDeclarator[] avds = getVariableDeclarators(a);
43: ASTVariableDeclarator[] bvds = getVariableDeclarators(b);
44:
45: Token[] aNames = VariableUtil.getVariableNames(avds);
46: Token[] bNames = VariableUtil.getVariableNames(bvds);
47:
48: int matched = 0;
49: int i = 0;
50: while (i < aNames.length && i < bNames.length) {
51: if (aNames[i].image.equals(bNames[i].image)) {
52: ++matched;
53: }
54: ++i;
55: }
56:
57: int count = Math.max(aNames.length, bNames.length);
58:
59: double score = 0.5 * matched / count;
60:
61: ASTType aType = (ASTType) findChild(a, ASTType.class);
62: ASTType bType = (ASTType) findChild(b, ASTType.class);
63:
64: if (toString(aType).equals(toString(bType))) {
65: score += 0.5;
66: }
67:
68: return score;
69: }
70:
71: }
|