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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package Torello.JavaDoc;


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

import java.util.concurrent.locks.*;

import java.io.IOException;
import java.util.Optional;
import java.util.List;
import java.util.function.Consumer;


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

import Torello.Java.*;

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

import Torello.Java.Additional.Ret2;
import Torello.Java.Additional.Ret3;

import Torello.Java.ReadOnly.ReadOnlyList;
import Torello.Java.ReadOnly.ReadOnlyArrayList;

import Torello.JDUInternal.ParseJavaSource.PJSHelper;


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

import com.sun.source.tree.ClassTree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.Tree;


/**
 * <B STYLE='color:darkred;'>Reflection Class:</B>
 * 
 * Holds all information extracted from <CODE><B>'&#46;java'</CODE></B> Source-Files regarding
 * Nested-Types (Inner-Classes).
 * 
 * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_GET_INST_2>
 * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_NESTED>
 * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_DIAGRAM>
 */
public class NestedType extends Declaration implements Cloneable
{
    /** <EMBED CLASS='external-html' DATA-FILE-ID=SVUID> */
    protected static final long serialVersionUID = 1;

    @Override
    String codeHiLiteString() { return null; }


    // ********************************************************************************************
    // ********************************************************************************************
    // Public Fields
    // ********************************************************************************************
    // ********************************************************************************************


    /** Identifies whether this is a nested/inner Class, Interface, Enum, Annotation etc... */
    public final CIET ciet;

    /**
     * The name of the package in which the enclosing-class of this nested-type is defined.  This
     * field will be null if the package was not found, or left blank as the 'default class'.
     */
    public final String packageName;

    /**
     * The {@code name}-field ({@link Declaration#name}) of this class uses the lone
     * Java-Identifier (Just One Word) which identifies this {@code NestedClass} within the scope
     * of the enclosing class.  However, {@code nameWithContainer} is a {@code String} that also
     * includes any / all enclosing-class names, each followed-by a {@code '.'}
     * 
     * <BR /><BR /><B STYLE='color: red;'>EXAMPLE:</B> For Java {@code java.util.Map.Entry<K, V>},
     * the {@code nameWithContainer} would be {@code "Map.Entry"}.
     * 
     * <BR /><BR />Generic Type-Parameter information is <B><I>not</I></B> included in this 
     * {@code String}, and neither is the Package-Name.
     */
    public final String nameWithContainer;

    /**
     * This field is identical to {@link #nameWithContainer}, but also has the Package-Name
     * prepended to it, if the Package-Name was present in the enclosing class' {@code '.java'}
     * file.
     * 
     * <BR /><BR /><B STYLE='color: red;'>EXAMPLE:</B> For Java {@code java.util.Map.Entry<K, V>},
     * the {@code fullyQualifiedName} would be {@code "java.util.Map.Entry"}.
     */
    public final String fullyQualifiedName;

    /** The number of fields that are defined in this inner-type */
    public final int numFields;

    /** The number of methods defined in this inner-type */
    public final int numMethods;

    /** <EMBED CLASS='external-html' DATA-FILE-ID=NT_GTPARAMS> */
    public final ReadOnlyList<String> genericTypeParameters;

    /**
     * <EMBED CLASS='external-html' DATA-FILE-ID=NT_IMPL_TYPES>
     * <EMBED CLASS='external-html' DATA-FILE-ID=JPB_JOW_TITLE>
     */
    public final ReadOnlyList<String> implementedTypesJOW;

    /** <EMBED CLASS='external-html' DATA-FILE-ID=NT_EXTEND_TYPES> */
    public final ReadOnlyList<String> extendedTypesJOW;


    // ********************************************************************************************
    // ********************************************************************************************
    // Native Parser Library Hook
    // ********************************************************************************************
    // ********************************************************************************************


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


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


    /**
     * <EMBED CLASS="defs" DATA-KIND=NestedType DATA-ENTITY=ClassTree>
     * <EMBED CLASS='external-html' DATA-FILE-ID=RC_DESCRIPTION>
     * @param ct <EMBED CLASS='external-html' DATA-FILE-ID=RC_PARAM_TREE>
     * @param util <EMBED CLASS='external-html' DATA-FILE-ID=RC_PARAM_UTIL>
     */
    public NestedType(ClassTree ct, TreeUtils util)
    {
        super(
            util,                           // TreeUtils
            ct,                             // com.sun.source.Tree.ClassTree instance
            ct.getModifiers(),              // Annotations **AND** public, static, final
            ct.getSimpleName().toString(),  // Name of the class    - NEED TO DEBUG THIS !!!
            Entity.INNER_CLASS,
            null                            // BODY SHOULDN'T BE NULL, BUT IT IS FOR NOW!!!
        );


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Generic Type Parametes
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // List<? extends TypeParameterTree> genericTypeParams = ct.getTypeParameters();
        @SuppressWarnings("unchecked")
        List<TypeParameterTree> genericTypeParams =
            (List<TypeParameterTree>) ct.getTypeParameters();

        if ((genericTypeParams == null) || (genericTypeParams.size() > 0))
            this.genericTypeParameters = EMPTY_READONLY_LIST;

        else this.genericTypeParameters = new ReadOnlyArrayList<String>(
            genericTypeParams,
            (TypeParameterTree tpt) -> tpt.toString().trim(),
            genericTypeParams.size()
        );


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Implements Clause
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // List<? extends Tree> implementedTypes = ct.getImplementsClause();
        @SuppressWarnings("unchecked")
        List<Tree> implementedTypes = (List<Tree>) ct.getImplementsClause();

        if ((implementedTypes == null) || (implementedTypes.size() == 0))
            this.implementedTypesJOW = EMPTY_READONLY_LIST;

        else this.implementedTypesJOW = new ReadOnlyArrayList<String>(
            implementedTypes,
            (Tree t) -> StrSource.typeToJavaIdentifier(t.toString().trim()).trim(),
            implementedTypes.size()
        );


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Extends Clause
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // this.extendedTypesJOW = PJSHelper.getExtendedTypes(ct);
        Tree t = ct.getExtendsClause();

        this.extendedTypesJOW = (t == null)
            ? EMPTY_READONLY_LIST
            : ReadOnlyList.of(t.toString());


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Other Stuff
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // Reference Hook: This was built using the com.sun.source.tree.ClassTree class, so
        // there simply isn't a com.github.javaparser.ast.body.TypeDeclaration (so it is
        // set to null)

        this.classTree = ct;

        // This is the kind of this inner-class / nested-type.  This CIET is computed using the
        // internal-helper method because it is just a big switch-statement.  I suspect it is going
        // to be reused elsewhere, but I am not 100% on that yet.

        // this.ciet = PJSHelper.getCIET(ct);
        switch (ct.getKind())
        {
            case CLASS:             this.ciet = CIET.CLASS;         break;
            case INTERFACE:         this.ciet = CIET.INTERFACE;     break;
            case ENUM:              this.ciet = CIET.ENUM;          break;
            case ANNOTATION_TYPE:   this.ciet =  CIET.ANNOTATION;   break;

            default: throw new UnreachableError();
        }

        /*
        if (this.ciet == null)
            Messager.assertFailJavaParser("Unknown Type Declaration: ", this.signature);
        */

        // This Helper Computes all three of these fields.
        Ret3<String, String, String> names = PJSHelper.getInnerTypeNames(ct, util);

        // return new Ret3<>(packageName, nameWithContainer, fullyQualifiedName);
        this.packageName        = names.a;
        this.nameWithContainer  = names.b;
        this.fullyQualifiedName = names.c;

        // This Helper counts the number of methods and fields in a TypeDeclaration
        Ret2<Integer, Integer> counts = PJSHelper.countMethodsFields(ct, this.ciet);

        // return new Ret<>(numMethods, numFields);
        this.numMethods = counts.a;
        this.numFields  = counts.b;
    }


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


    /**
     * Generates a {@code String} of this {@code nested-type}, with most information included.
     * 
     * @return A printable {@code String} of this {@code nested-type}.
     * 
     * @see PF
     * @see #toString(int)
     * @see StrCSV#toCSV(String[], boolean, boolean, Integer)
     */
    public String toString()
    {
        return
            "Name:            [" + name + "]\n" +
            "With Container:  [" + nameWithContainer + "]\n" +
            "Kind:            [" + ciet.toString() + "]\n" +
            "Signature:       [" +
                StrPrint.abbrevEndRDSF(signature, MAX_STR_LEN, true) + "]\n" +

            // "Type Parameters:".length() ==>  16  (17=16+1)
            printedTypeParameters(17) +

            "Modifiers:       [" +
                StrCSV.toCSV(modifiers, true, true, null) + "]\n" +

                // 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;
        String nameTitle = "Nested " + ciet.toString();

        // 7 ==> " Name: ".length()
        int LEN = nameTitle.length() + 7;

        return 
            printedName(nameTitle, LEN, color) +
            StringParse.rightSpacePad("Fully Qualified:", LEN) + '[' + fullyQualifiedName + "]\n" +
            StringParse.rightSpacePad("With Container:", LEN) + '[' + nameWithContainer + "]\n" +
            printedSignature(LEN, color) +
            printedTypeParameters(LEN) +
            printedModifiers(LEN) +
            printedExtendsImplements(LEN) +
            printedMethodField(LEN, color) + 
            printedLocation(LEN, color, (flags & BRIEF_LOCATION) > 0) +

            // The previous method does not add a '\n' end to the end of the returned string
            // This is optional, it adds a '\n' AT THE BEGINNING if it is included

            printedComments(LEN, color, (flags & JAVADOC_COMMENTS) > 0);
    }

    private String printedMethodField(int numSpaces, boolean color)
    {
        return
            StringParse.rightSpacePad("Num Methods:", numSpaces) +
                '[' + (color ? BGREEN : "") + numMethods + (color ? RESET : "") + "]\n" +
            StringParse.rightSpacePad("Num Fields:", numSpaces) +
                '[' + (color ? BGREEN : "") + numFields + (color ? RESET : "") + "]\n";
    }

    private String printedExtendsImplements(int LEN)
    {
        return
            (((this.extendedTypesJOW != null) && (this.extendedTypesJOW.size() > 0))
                ? (StringParse.rightSpacePad("Extends:", LEN) + '[' +
                    StrCSV.toCSV(extendedTypesJOW, true, false, null) + "]\n")
                : "") +
            (((this.implementedTypesJOW != null) && (this.implementedTypesJOW.size() > 0))
                ? (StringParse.rightSpacePad("Implements:", LEN) + '[' +
                    StrCSV.toCSV(implementedTypesJOW, true, false, null) + "]\n")
                : "");
    }

    private String printedTypeParameters(int numSpaces)
    {
        if ((this.genericTypeParameters == null) || (this.genericTypeParameters.size() == 0))
            return "";

        return
            StringParse.rightSpacePad("Type-Parameters:", numSpaces) +
            '[' + StrCSV.toCSV(genericTypeParameters, true, true, MAX_STR_LEN) + "]\n";
    }


    // *************************************************************************************
    // *************************************************************************************
    // Clone, CompareTo & Equals Stuff
    // *************************************************************************************
    // *************************************************************************************


    /**
     * Java's {@code interface Comparable<T>} requirements.  This does a very simple comparison
     * using the two nested-types's {@code 'name'} field.
     * 
     * @param nt Any other {@code Nested-Type} to be compared to {@code 'this'}
     * 
     * @return An integer that fulfills Java's
     * {@code interface Comparable<NestedType>, public boolean compareTo(NestedType nt)} method
     * requirements.
     */
    public int compareTo(NestedType nt)
    { return (this == nt) ? 0 : this.name.compareTo(nt.name); }

    /**
     * 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 of the field defined.  The
     * presumption here is that the definition of a 'field' only has meaning - <I>at all</I> -
     * inside the context of a {@code class, interface, } or {@code enumerated-type} where that
     * field is defined.  Since inside any {@code '.java'} source-code file, there may only be one
     * field with a given name, this method shall return {@code TRUE} whenever the field being
     * compared also has the same name.
     * 
     * @param other This may be any other field.  It is <I><B>strongly suggested</B></I> that
     * {@code 'other'} be a field defined in the same {@code '.java'} source-code file as
     * {@code 'this'} field.
     * 
     * @return This method returns {@code TRUE} when {@code 'this'} instance of {@code Field} has
     * the same {@code 'name'} as the name-field of input-parameter {@code 'other'}
     */
    public boolean equals(NestedType other)
    { return this.name.equals(other.name); }
}