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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package Torello.JavaDoc;

import Torello.Java.Additional.Ret3;

import static Torello.Java.C.*;

import Torello.JDUInternal.Messager.Messager;
import Torello.JDUInternal.Messager.Where.JDUUserAPI;
import Torello.JDUInternal.Messager.Where.Where_Am_I;

import java.util.*;
import com.sun.source.util.*;
import com.sun.source.tree.*;
import com.sun.source.doctree.*;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import javax.tools.StandardJavaFileManager;
import javax.tools.JavaFileObject;

/**
 * This is a helpful interface to retrieve and extract the utilities provided by the Java-Compiler
 * interface provided by the JDK.  This class utilizes the Tree-Classes defined in the Java Package
 * {@code com.sun.source.tree.*} (and also {@code com.sun.source.util.*}.  These AST (Tree's) work
 * and function as an alternative to the {@code JavaParser} AST Generator.
 */
public class TreeUtils
{
    private static final Where_Am_I WHERE_AM_I = JDUUserAPI.TreeUtils;


    // ********************************************************************************************
    // ********************************************************************************************
    // Static-Instances & Static-Constants
    // ********************************************************************************************
    // ********************************************************************************************


    // javac options we pass to the compiler.  We enable preview so that all preview features can
    // be parsed.

    private static final List<String> OPTIONS = 
        List.of("--enable-preview", "--release=" + getJavaMajorVersion());

    // major version of JDK such as 16, 17, 18 etc.
    private static int getJavaMajorVersion() { return Runtime.version().feature(); }

    // Standard JDK Stuff - no fancy library imports here
    // javax.tools.JavaCompiler, javax.tools.ToolProvider

    private static final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    // javax.tools.StandardJavaFileManager
    private static final StandardJavaFileManager fileManager =
        compiler.getStandardFileManager(null, null, null);


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


    /** <EMBED CLASS='external-html' DATA-FILE-ID=TU_SOURCE_POS> */
    public final SourcePositions sourcePositions;

    /**
     * Java's Sun/Oracle Abstract Syntax Tree engine provides AST's for Java-Doc Comments, in
     * addition to trees for the actual source-code.  This reference here is merely an instance of
     * the utility class containing tools for traversing Java-Doc Comment Syntax Trees.
     * 
     * <BR /><BR />More information about these trees is available in the documentation for the
     * Java package {@code com.sun.source.util.DocTrees}.
     */
    public final DocTrees docTrees;

    /** <EMBED CLASS='external-html' DATA-FILE-ID=TU_DOC_SOURCE_POS> */
    public final DocSourcePositions docSourcePositions;

    /**
     * This instance is generated by the Java-Compiler when it is asked to perform an AST (Abstract
     * Syntax Tree) parse of a Java Source-Code File (a {@code '.java'} File).  A
     * {@code CompilationUnitTree} is essentially the root node (the 'top' of the tree) of a
     * Source-Code AST.
     * 
     * <BR /><BR />Please review the Sun/Oracle Documentation Page for a fuller explanation of this
     * class' features.
     */
    public final CompilationUnitTree compilationUnitTree;

    /** <EMBED CLASS='external-html' DATA-FILE-ID=TU_LINE_MAP> */
    public final LineMap lineMap;

    /**
     * This is nothing more than a copy of the constructor-parameter by the same name.  This shall
     * contain the file-name for the source-code file that has been parsed to create an instance
     * of this class, {@code TreeUtils}.
     */
    public final String srcFileName;

    /**
     * This is also a copy of a constructor-parameter, reserved for any needed use by a reference
     * in this class.  It holds a {@code '.java'} source-code file, loaded into memory and saved as
     * a {@code java.lang.String}.
     */
    public final String srcFileAsStr;


    // ********************************************************************************************
    // ********************************************************************************************
    // Constructor
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Constructs an instance of this class.  Accepts a Java Source-Code File-Name, and that file
     * alredy fully-loaded into memory - as a {@code java.lang.String}.  This constructs invokes
     * the internal instance of the Java Compiler, and then fills in all of the public fields for
     * this class.
     * 
     * @param srcFileName The name of a Java Source-Code File
     * 
     * @param srcFileAsStr The textual-content of that Source-File, loaded into a
     * {@code java.lang.String}
     * 
     * @see #srcFileName
     * @see #srcFileAsStr
     */
    public TreeUtils(String srcFileName, String srcFileAsStr)
    {
        this.srcFileName    = srcFileName;
        this.srcFileAsStr   = srcFileAsStr;


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // javax.tools.JavaFileObject
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        Iterable<? extends JavaFileObject> fileObjects =
            fileManager.getJavaFileObjects(srcFileName);

        Iterator<? extends JavaFileObject> iterFileObjects = fileObjects.iterator();

        if (! iterFileObjects.hasNext()) Messager.assertFailOracleParser(
            "The JavaFileManager instance seems to have returned an empty JavaFileObject-List",
            null,
            WHERE_AM_I
        );

        // The Java-Compiler actually expects the Iterator, not the single-instance.  We can throw
        // the return object of the iterator away, it isn't used at all.  This is just more error
        // checking since some of this is quite new.

        iterFileObjects.next();

        if (iterFileObjects.hasNext()) Messager.assertFailOracleParser(
            "The JavaFileManager instance has returned a JavaFileObject-List with more than one " +
            "element",
            null,
            WHERE_AM_I
        );


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Running the Compiler to get a "JavacTask"
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // com.sun.source.util.JavacTask
        JavacTask task = (JavacTask) compiler.getTask
            (null, null, null, OPTIONS, null, fileObjects);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // The Helper Utilities: SourcePositions, DocTrees, DocSourcePositions
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        // com.sun.source.util.SourcePositions
        this.sourcePositions = Trees.instance(task).getSourcePositions();

        // com.sun.source.util.DocTrees
        this.docTrees = DocTrees.instance(task);

        // com.sun.source.util.DocSourcePositions
        this.docSourcePositions = docTrees.getSourcePositions();


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // com.sun.source.tree.CompilationUnitTree
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        Iterable<? extends CompilationUnitTree> cutList = null;

        try 
            { cutList = task.parse(); }

        catch (Exception e)
        {
            Messager.assertFailOracleParser(
                e,
                "Exception thrown while parsing Source-Code File:\n" +
                "    [" + BYELLOW + srcFileName + RESET + ']',
                null,
                WHERE_AM_I
            );
        }

        Iterator<? extends CompilationUnitTree> iter = cutList.iterator();

        if (! iter.hasNext()) Messager.assertFailOracleParser(
            "The JavacTask instance seems to have returned an empty CompilationUnitTree List",
            null,
            WHERE_AM_I
        );

        // com.sun.source.tree.CompilationUnitTree
        this.compilationUnitTree = iter.next();

        if (iter.hasNext()) Messager.assertFailOracleParser(
            "The JavacTask instance has returned a CompilationUnitTree List with more than one " +
            "element",
            null,
            WHERE_AM_I
        );


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Last, but not least: com.sun.source.tree.LineMap
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        this.lineMap = this.compilationUnitTree.getLineMap();
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Methods
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Returns the starting position within the text of the relevant Java Source-Code File for the
     * sub-tree specified by parameter {@code 'tree'}.
     * 
     * @param tree This may be any AST branch or leaf, but it must be sub-node that falls within
     * the root-node {@link #compilationUnitTree}.
     * 
     * @see #sourcePositions
     * @see #compilationUnitTree
     */
    public int startPos(Tree tree)
    { return (int) this.sourcePositions.getStartPosition(this.compilationUnitTree, tree); }

    /**
     * Returns the ending position within the text of the relevant Java Source-Code File for the
     * sub-tree specified by parameter {@code 'tree'}.
     * 
     * @param tree This may be any AST branch or leaf, but it must be sub-node that falls within
     * the root-node {@link #compilationUnitTree}.
     * 
     * @see #sourcePositions
     * @see #compilationUnitTree
     */
    public int endPos(Tree tree)
    { return (int) this.sourcePositions.getEndPosition(this.compilationUnitTree, tree); }

    /**
     * Returns the line-number within the text of the relevant Java Source-Code File for the
     * <B>first line of code</B> of the element specified by parameter {@code 'tree'}.
     * 
     * @param tree This may be any AST branch or leaf, but it must be sub-node that falls within
     * the root-node {@link #compilationUnitTree}.
     * 
     * @see #lineMap
     * @see #sourcePositions
     * @see #compilationUnitTree
     */
    public int startLineNum(Tree tree)
    {
        return (int) this.lineMap.getLineNumber
            (this.sourcePositions.getStartPosition(this.compilationUnitTree, tree));
    }

    /**
     * Returns the line-number within the text of the relevant Java Source-Code File for the
     * <B>last line of code</B> of the element specified by parameter {@code 'tree'}.
     * 
     * @param tree This may be any AST branch or leaf, but it must be sub-node that falls within
     * the root-node {@link #compilationUnitTree}.
     * 
     * @see #lineMap
     * @see #sourcePositions
     * @see #compilationUnitTree
     */
    public int endLineNum(Tree tree)
    {
        return (int) this.lineMap.getLineNumber
            (this.sourcePositions.getEndPosition(this.compilationUnitTree, tree));
    }

    /**
     * Performs a standard Java {@code 'substring'} operation on the Source-Code File, which has
     * been saved as a {@code String} into internal &amp; public field {@link #srcFileAsStr}.
     * 
     * @param sPos The first character-postion within the text-file
     * @param ePos The last character-postion within the text-file
     * @return The extracted sub-string.
     */
    public String substring(int sPos, int ePos)
    { return this.srcFileAsStr.substring(sPos, ePos); }

    /**
     * Extracts the <I>exact text / character-data</I> from the original {@code '.java'} Source
     * Code File for any node in the AST 'Parse-Tree' that was produced from that Source-File.
     * 
     * @param tree Any node in the AST that was produced from the Source-File saved inside 
     * {@code 'this'} instance of {@code TreeUtils}
     * 
     * @return The original Java-Source, as a {@code java.lang.String}
     */
    public String substring(Tree tree)
    { return this.srcFileAsStr.substring(startPos(tree), endPos(tree)); }

    /**
     * An instance of {@code TreePath} is a class which stores node / branch references for a node
     * in an AST extending back to the top-level node in the Compilation-Unit.
     * 
     * <BR /><BR />The Parse-Trees produced by the <CODE>com.sun.source.tree</CODE> classes do not
     * provide very much in the way of parent or ancestor node pointers.  This makes finding where
     * a particular branch in an Abstract Syntax Tree a little more difficult.  An instance of
     * {@code 'TreePath'} simplifies the process.
     * 
     * @param tree This should be a node that exists within the AST that is associated / stored
     * inside {@code 'this'} reference of {@code TreeUtils}.
     * 
     * @return A {@code TreePath} instance that contains the straight-line path to the root node
     * in the Abstract Syntax Tree.
     */
    public TreePath getTreePath(Tree tree)
    { return TreePath.getPath(this.compilationUnitTree, tree); }

    /**
     * Retrieve  Java-Doc Comment information (if present / if provided) for any of the entities /
     * members of a CIET / Type.
     * 
     * @param tree The {@link Entity} for which a Java-Doc Comment is sought.
     * 
     * @return An instance of {@link Ret3} as follows:
     * <BR /><BR /><UL CLASS=JDUL>
     * 
     * <LI> {@code Ret3.a: Integer}
     *      <BR />The <B STYLE='color: red'>starting</B> character-position of the Java-Doc Comment
     *      in the original Source-Code File.
     *      <BR /><BR /></LI>
     * 
     * <LI> {@code Ret3.b: Integer}
     *      <BR />The <B STYLE='color: red'>ending</B> character-position of the Java-Doc Comment
     *      in the original Source-Code File.
     *      <BR /><BR /></LI>
     * 
     * <LI> {@code Ret3.b: DocCommentTree}
     *      <BR />The Parse-Tree for the Java-Doc Comment.
     *      <BR /><BR /></LI>
     * </UL>
     * 
     * <BR /><B STYLE='color: red;'>NOTE:</B> If the {@link Entity} / Member of the {@code 'tree'}
     * that was passed as input to this method does not have a Java-Doc Comment written, then this
     * method will return null instead.
     * 
     * @see #docTrees
     * @see #compilationUnitTree
     * @see #docSourcePositions
     * @see #srcFileAsStr
     */
    public Ret3<Integer, Integer, DocCommentTree> getJavaDocInfoPos(Tree tree)
    {
        TreePath treePath = TreePath.getPath(this.compilationUnitTree, tree);

        DocCommentTree dct = (treePath != null)
            ? this.docTrees.getDocCommentTree(treePath)
            : null;

        if (dct == null) return new Ret3<>(-1, -1, null);

        int sPos = (int) this.docSourcePositions.getStartPosition
            (this.compilationUnitTree, dct, dct);

        int ePos = (int) this.docSourcePositions.getEndPosition
            (this.compilationUnitTree, dct, dct);

        // This is a case where there is an "empty comment".  I'm not sure at the moment if there
        // is a "more appropriate" way to be handling this.  However, while writing code, an empty
        // comment did, indeed, generate a **NON-NULL** 'dct' - but sPos and ePos were both -1
        // 
        // For now, I guess, we are going to pretend that a PERFECTLy-EMPTY JavaDoc-Comment (such
        // as /**    */), is identical to have NO-COMMENT at all.

        if ((sPos == -1) && (ePos == -1)) return new Ret3<>(-1, -1, null);

        while (sPos >= 2)
            if (this.srcFileAsStr.charAt(sPos--) == '*')
                if (this.srcFileAsStr.regionMatches(sPos - 1, "/**", 0, 3))
                { sPos--; break; }

        /*
        System.out.println(
            "this.srcFileName: " + this.srcFileName + '\n' +
            "sPos: " + sPos + ", ePos: " + ePos + '\n' +
            "this.srcFileAsStr.substring(sPos, sPos+50): " +
            this.srcFileAsStr.substring(sPos, sPos+50)
        );

        try { System.out.println("str: " + this.srcFileAsStr.substring(sPos, ePos)); }
        catch (Exception e) { System.out.println("e.getMessage(): " + e.getMessage()); }
        */

        // Note that today is the "BIG DAY", I am trying to run my build on OCI rather than GCP.  
        // It is April 29th, 2024.  I have just run into an issue (which never happened on whatever
        // version of `javadoc` is running on GCP).  Here, the first package to have shown the 
        // issue was in Apache.CLI.DefaultParser - which has an internal-static inner-class simply
        // named "Builder".  For "Builder" the ePos is returning '-1'
        // 
        // Thinking about how "TreeUtils" works is not something I've been doing lately, but I 
        // just reviewed all of the sordid details of "com.sun.source.util.DocSourcePositions".
        // 
        // These Methods:
        // getStartPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree)
        // getEndPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree)
        // 
        // Look for the Position in the source file's "comment" for the specific item inside that
        // comment, specifically item "tree".  For static-inner classes, this new version of 
        // javadoc that is running on OCI (rather than GCP) is returning "-1".
        // 
        // Fortunately, for me, there is an answer, but I think this solution could fail if the
        // user included a "*/" Sub-String somwhere inside their comments.
        // 
        // THIS HACK IS TO JUST SET ePos to sPos if "getEndPosition" failed and returned -1
        // 
        // NOTE: I **THINK** - but I'm not 100% that I should switch this "hacky" like line to 
        // one that iterates through the elements in the List<DocTree> returned by this method
        // from class DocCommentTree.  I used to have a method that did just that, but I deleted it
        // last year because iterating the character-data itself was much more efficient.  However,
        // apparently for static-inner classes, newer versions of javadoc are just failing.
        // 
        // default List<? extends DocTree> getFullBody()
        // Returns the entire body of a documentation comment, appearing before any block tags,
        // including the first sentence.

        if (ePos < 0) ePos = sPos;  // "The Hack"

        // And then this stuff below is the original code written in 2023...
        int MAX = this.srcFileAsStr.length() - 2;
        while (ePos < MAX)
            if (this.srcFileAsStr.charAt(ePos++) == '*')
                if (this.srcFileAsStr.regionMatches(ePos - 1, "*/", 0, 2))
                { ePos++; break; }

        return new Ret3<>(sPos, ePos, dct);
    }

    /**
     * Retrieve Java-Doc Comment information (if present / if provided) for any of the entities /
     * members of a CIET / Type.
     * 
     * @param tree The {@link Entity} for which a Java-Doc Comment is sought.
     * 
     * @return An instance of {@link Ret3} as follows:
     * <BR /><BR /><UL CLASS=JDUL>
     * 
     * <LI> {@code Ret3.a: Integer}
     *      <BR />The <B STYLE='color: red'>starting</B> line-number of the Java-Doc Comment in the
     *      original Source-Code File.
     *      <BR /><BR /></LI>
     * 
     * <LI> {@code Ret3.b: Integer}
     *      <BR />The <B STYLE='color: red'>ending</B> line-number of the Java-Doc Comment in the
     *      original Source-Code File.
     *      <BR /><BR /></LI>
     * 
     * <LI> {@code Ret3.b: DocCommentTree}
     *      <BR />The Parse-Tree for the Java-Doc Comment.
     *      <BR /><BR /></LI>
     * </UL>
     * 
     * <BR /><B STYLE='color: red;'>NOTE:</B> If the {@link Entity} / Member of the {@code 'tree'}
     * that was passed as input to this method does not have a Java-Doc Comment written, then this
     * method will return null instead.
     * 
     * @see #docTrees
     * @see #compilationUnitTree
     * @see #srcFileAsStr
     * @see #docSourcePositions
     * @see #lineMap
     */
    public Ret3<Integer, Integer, DocCommentTree> getJavaDocInfoLine(Tree tree)
    {
        TreePath treePath = TreePath.getPath(this.compilationUnitTree, tree);

        DocCommentTree dct = (treePath != null)
            ? this.docTrees.getDocCommentTree(treePath)
            : null;

        if (dct == null) return new Ret3<>(-1, -1, null);

        int sPos = (int) this.docSourcePositions.getStartPosition
            (this.compilationUnitTree, dct, dct);

        int ePos = (int) this.docSourcePositions.getEndPosition
            (this.compilationUnitTree, dct, dct);

        while (sPos >= 2)
            if (this.srcFileAsStr.charAt(sPos--) == '*')
                if (this.srcFileAsStr.regionMatches(sPos - 1, "/**", 0, 3))
                { sPos--; break; }

        int MAX = this.srcFileAsStr.length() - 2;
        while (ePos < MAX)
            if (this.srcFileAsStr.charAt(ePos++) == '*')
                if (this.srcFileAsStr.regionMatches(ePos - 1, "*/", 0, 2))
                { ePos++; break; }

        return new Ret3<>(
            (int) this.lineMap.getLineNumber(sPos),
            (int) this.lineMap.getLineNumber(ePos),
            dct
        );
    }

    /**
     * Retrieves just the Java-Doc Comment Parse-Tree, and does not include Line-Number or
     * Character-Position information.
     * 
     * @param tree The {@link Entity} / Member of the Type for which the Java-Doc Comment is being
     * sought.
     * 
     * @return The Java-Doc Comment Parse-Tree
     * 
     * @see #compilationUnitTree
     * @see #docTrees
     */
    public DocCommentTree getJavaDocCommentTree(Tree tree)
    {
        TreePath treePath = TreePath.getPath(this.compilationUnitTree, tree);

        if (treePath == null) return null;

        return this.docTrees.getDocCommentTree(treePath);
    }
}