1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package Torello.JavaDoc;


// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// Standard-Java Imports
// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

import java.io.IOException;
import java.util.Optional;


// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// Java-HTML Imports
// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

import Torello.Java.*;

import static Torello.Java.C.*;
import static Torello.JavaDoc.PF.*;

import Torello.Java.Additional.Ret2;

import Torello.JDUInternal.DataClasses.MainLoopData.CallableSignature;


// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// The new Source-Code Parser: com.sun.source.*
// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

import com.sun.source.tree.MethodTree;


/**
 * <B STYLE='color:darkred;'>Reflection Class:</B>
 * 
 * Holds all information extracted from <CODE>'&#46;java'</CODE> Source-Files about Method's
 * identified in that file.
 * 
 * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_GET_INST>
 * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_METHOD>
 * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_DIAGRAM>
 */
@JDHeaderBackgroundImg(EmbedTagFileID={"REFLECTION_EXTENSION"})
public class Method
    extends Callable
    implements java.io.Serializable, Comparable<Method>, Cloneable
{
    /** <EMBED CLASS='external-html' DATA-FILE-ID=SVUID> */
    public static final long serialVersionUID = 1;

    /**
     * The return type of the {@code method}, as a {@code String}.  If this is a method with a
     * {@code 'void'} return-type, this shall be "void".
     * 
     * <BR /><BR /><B>NOTE:</B> The parsed return-type will include the full-package name of the
     * returned class (or interface), if the {@code method} returns a class or interface. 
     */
    public final String returnType;

    /**
     * The return type of the {@code method}, as a {@code String}.<BR /><BR />
     * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_JOW_TITLE>
     */
    public final String returnTypeJOW;


    // ********************************************************************************************
    // ********************************************************************************************
    // Reference-Hook: com.sun.source.tree
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * <EMBED CLASS='external-html' DATA-FILE-ID=SSTB_HOOK_FIELD>
     * 
     * If a user decides to make use of the native Sun/Oracle {@code MethodTree} instance that was
     * used to build this {@code Method} instance, it may be retrieved from this {@code transient}
     * field.
     */
    public final transient MethodTree methodTree;


    // ********************************************************************************************
    // ********************************************************************************************
    // Constructor - com.sun.source.tree 
    // ********************************************************************************************
    // ********************************************************************************************

    
    /**
     * <EMBED CLASS="defs" DATA-KIND=Method DATA-ENTITY=MethodTree>
     * <EMBED CLASS='external-html' DATA-FILE-ID=RC_DESCRIPTION>
     * @param mt <EMBED CLASS='external-html' DATA-FILE-ID=RC_PARAM_TREE>
     * @param util <EMBED CLASS='external-html' DATA-FILE-ID=RC_PARAM_UTIL>
     */
    public Method(MethodTree mt, TreeUtils util)
    {
        super(mt, mt.getName().toString(), Entity.METHOD, util);

        this.returnType     = mt.getReturnType().toString();
        this.returnTypeJOW  = StrSource.typeToJavaIdentifier(this.returnType);
        this.methodTree     = mt;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Constructor: Used Internally by SignatureParse / SummaryHTMLFile
    // ********************************************************************************************
    // ********************************************************************************************


    // Ensures that the Version with longer type-information strings is used.
    // Java Doc often uses longer type strings than is available from the source-code parse
    // Remember, JavaParser Symbol-Solver doesn't work well, and the Sun/Oracle Parser doesn't have
    // a linker at all.
    //
    // Called from JDUInternal.ParseHTML.SignatureParse:
    //      This is used when the JavaDocHTMLFile is asking that a method be retrieved based on
    //      input from **BOTH** the HTML-File **AND** the Source-File

    public Method(CallableSignature cSig, Method mFromSourceParser)
    {
        // Does the same thing as the loop statement below, but for the "parameterTypes"
        super(cSig, mFromSourceParser);

        // Java Doc always produces "java.lang.String", while JP just gives "String"
        //
        // REMEMBER: JP is lazy when it comes to "Package Information" for types.
        //           Java-Doc includes it often - BUT NOT ALWAYS.  (See above comment)
        //
        // Remember, though, the rest of the JavaParser fields are filled out, Java Doc
        // leaves out all the other information that JP retrieves.

        this.returnType =
            (cSig.returnType.length() > mFromSourceParser.returnType.length())
                ? cSig.returnType
                : mFromSourceParser.returnType;

        // This should never matter.  They must be identical.
        this.returnTypeJOW = mFromSourceParser.returnTypeJOW;

        // Save the reference hook
        this.methodTree = mFromSourceParser.methodTree;
    }

    // Used for "Synthetic Methods ONLY!"  Literally, this line is the only way this particular
    // Constructor could ever be called:
    //
    // From JDUInternal.ParseHTML.SignatureParse:
    //      if (StrCmpr.equalsXOR(cSig.name, "valueOf", "values")) return new Method(cSig);

    public Method(CallableSignature cSig)
    {
        // Does the same thing as the loop statement below, but for the "parameterTypes"
        super(cSig, Entity.METHOD);

        this.returnType         = cSig.returnType;
        this.returnTypeJOW      = cSig.returnTypeJOW;
        this.methodTree         = null;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // toString()
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Generates a {@code String} of this {@code method}, with most information included.
     * 
     * <BR /><BR /><B>NOTE:</B> This will not return every piece of information contained by this
     * class. For example, both the method body, and any possible JavaDoc Comments are not
     * included.  For a more enhanced {@code toString()} version, call the one that accepts flags.
     * 
     * @return A printable {@code String} of this method.
     * 
     * @see PF
     * @see #toString(int)
     * @see StrCSV#toCSV(String[], boolean, boolean, Integer)
     */
    public String toString()
    {
        return
            "Name:            [" + name + "]\n" +
            "Signature:       [" + StrPrint.abbrevEndRDSF(signature, MAX_STR_LEN, true) + "]\n" +
            "Modifiers:       [" + StrCSV.toCSV(modifiers, true, true, null) + "]\n" +
            printedParameterNamesTS() +
            printedParameterTypesTS() +
            "Return Type:     [" + returnType + "]\n" +
            printedExceptionsTS() +

            // This will **NEVER** be null - unless 'this' instance was built from an HTML File,
            // rather than a source-code file.  Instances like that are only used temporarily, and
            // are garbage collected instantly.  Do this check anyway (just in case).

            "Location:        " + ((this.location == null)
                ? "null" 
                : ('[' + this.location.quickSummary() + ']'));
    }

    /**
     * This class expects a flags that has been masked using the constant ({@code public, static,
     * final int}) fields of class {@link PF}.  Please view this class for more information about
     * the flags available for modifying the return-value of this {@code toString()} method.
     * 
     * @param flags These are the toString flags from class PF ("Print Flags").  View available
     * flags listed in class {@link PF}.
     * 
     * @return A printable {@code String} of this method, with comment information included as well.
     * 
     * @see StrCSV#toCSV(String[], boolean, boolean, Integer)
     * @see #toString()
     * @see PF
     */
    public String toString(int flags)
    {
        boolean color = (flags & UNIX_COLORS) > 0;
        Ret2<Boolean, Boolean> jow = jowFlags(flags);

        return 
            printedName("Method", 20, color) +
            printedSignature(20, color) +
            printedModifiers(20) +
            printedParamNames() + 
            printedParamTypes(jow) +
            printedReturnType(jow, color) +
            printedExceptions() +
            printedLocation(20, color, (flags & BRIEF_LOCATION) > 0) +

            // The previous method does not add a '\n' end to the end of the returned string
            // These are both optional, they add a '\n' AT THE BEGINNING if one of them is included

            printedComments(20, color, (flags & JAVADOC_COMMENTS) > 0) +
            printedCallableBody(flags);
    }

    private String printedReturnType(Ret2<Boolean, Boolean> jow, boolean color)
    {
        String rt = null, rtJOW = null;

        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Worry about the colors first
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        if (jow.a || jow.b)
            rtJOW = color ? (BGREEN + returnTypeJOW + RESET) : returnTypeJOW;

        if (! jow.b)
            rt = color ? (BGREEN + returnType + RESET) : returnType;
        

        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Now print the string
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        if (jow.b /*onlyJOW*/) return "Return Simple-Type: [" + rtJOW + "]\n";

        else if (jow.a /*addJOW*/) return
            "Return Type:        [" + rt + "]\n" +
            "Return Simple-Type: [" + rtJOW + "]\n";

        else return "Return Type:        [" + rt + "]\n";
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // CompareTo & Equals
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Java's {@code interface Comparable<T>} requirements.  This does a very simple comparison
     * using the two method's {@code name} field. If the name comparison will not
     * suffice in making a decision, then the number of parameters, and parameter-types are used
     * to making the sort-decision.
     * 
     * @param m Any other {@code Method} to be compared to {@code 'this' Method}
     * 
     * @return An integer that fulfils Java's {@code interface Comparable<Method> public boolean
     * compareTo(Method m)} method requirements.
     */
    public int compareTo(Method m)
    {
        // Identical References
        if (this == m) return 0;

        // Sorting by ignoring case is best - usually for the looks of a list
        // NOTE: Returning '0' is bad, because a TreeSet will remove duplicate-elements.  This
        //       means two different meethods with the same name would not "fit" into a treeset.

        int ret = this.name.compareToIgnoreCase(m.name);
        if (ret != 0) return ret;

        // Try to identify a different without ignoring case.
        ret = this.name.compareTo(m.name);
        if (ret != 0) return ret;

        ret = this.numParameters() - m.numParameters();
        if (ret != 0) return ret;

        for (int i=0; i < this.parameterTypesJOW.size(); i++)
        {
            ret = this.parameterTypesJOW.get(i).compareTo(m.parameterTypesJOW.get(i));
            if (ret != 0) return ret;
        }

        return 0;
    }

    /**
     * This <I>should be called an "atypical version" of </I>the usual {@code equals(Object other)}
     * method.  This version of equals merely compares the name and parameters-list of the method.
     * The presumption here is that the definition of a 'method' only has 
     * meaning - <I>at all</I> - inside the context of a {@code class, interface, } or
     * {@code enumerated-type} where that method is defined. Since inside any {@code '.java'}
     * source-code file, there may only be one method with a given name and parameter-list, this
     * shall return {@code TRUE} whenever the method being compared has the same name and parameter
     * types as {@code 'this'} does.
     * 
     * @param other This may be any other {@code method}.  It is <I><B>strongly suggested</B></I>
     * that this be a {@code method} defined in the same {@code '.java'} source-code file as
     * {@code 'this' method}.
     * 
     * @return This method returns {@code TRUE} when {@code 'this'} instance of {@code Method} has
     * <B>both</B> the same {@code public final Sting name} <B>and</B> the same parameter-list as
     * {@code 'other'}.
     */
    public boolean equals(Method other)
    {
        // The method's must have the same name!
        if (! this.name.equals(other.name)) return false;

        // If the number of parameters in the 'other' instance of Method differ from the number
        // of parameters in 'this' Method, then return FALSE immediately.  It cannot be a match.

        if (this.numParameters() != other.numParameters()) return false;

        // If both of these have zero parameters, and their names have matched, return true
        // immediately

        if (this.numParameters() == 0) return true;

        // If any of the parameter-names are different, break immediately and return false;
        for (int i=0; i < this.parameterNames.size(); i++)
            if (! this.parameterNames.get(i).equals(other.parameterNames.get(i))) return false;

        // If the parameter-types listed by the javadoc '.html' file differ from the parameter
        // types listed in the original '.java' source-code file, then break immediately.
        //
        // NOTE: The "package-information" for the FULL CLASS OR INTERFACE NAME is not always
        //       available.

        for (int i=0; i < this.parameterTypesJOW.size(); i++)
            if (! this.parameterTypesJOW.get(i).equals(other.parameterTypesJOW.get(i)))
                return false;

        // ALL TEST PASSED
        return true;
    }
}