2727import com .sun .tools .javac .parser .Tokens .TokenKind ;
2828import com .sun .tools .javac .parser .UnicodeReader ;
2929import com .sun .tools .javac .util .Context ;
30+ import java .util .Comparator ;
3031import java .util .Set ;
3132
3233/** A wrapper around javac's lexer. */
@@ -71,22 +72,40 @@ public String stringVal() {
7172 }
7273 }
7374
74- /** Lex the input and return a list of {@link RawTok}s. */
75- public static ImmutableList <RawTok > getTokens (
76- String source , Context context , Set <TokenKind > stopTokens ) {
75+ private static ImmutableList <Token > readAllToken (String source , Context context ) {
7776 if (source == null ) {
7877 return ImmutableList .of ();
7978 }
8079 ScannerFactory fac = ScannerFactory .instance (context );
8180 char [] buffer = (source + EOF_COMMENT ).toCharArray ();
8281 Scanner scanner =
8382 new AccessibleScanner (fac , new CommentSavingTokenizer (fac , buffer , buffer .length ));
83+ ImmutableList .Builder <Token > tokens = ImmutableList .builder ();
84+ do {
85+ scanner .nextToken ();
86+ tokens .add (scanner .token ());
87+ } while (scanner .token ().kind != TokenKind .EOF );
88+ if (Runtime .version ().feature () < 21 ) {
89+ return tokens .build ();
90+ } else {
91+ return ImmutableList .sortedCopyOf (Comparator .comparingInt (t -> t .pos ), tokens .build ());
92+ }
93+ }
94+
95+ /** Lex the input and return a list of {@link RawTok}s. */
96+ public static ImmutableList <RawTok > getTokens (
97+ String source , Context context , Set <TokenKind > stopTokens ) {
98+ if (source == null ) {
99+ return ImmutableList .of ();
100+ }
101+ ImmutableList <Token > javacTokens = readAllToken (source , context );
102+
103+ var javacTokenIt = javacTokens .iterator ();
84104 ImmutableList .Builder <RawTok > tokens = ImmutableList .builder ();
85105 int end = source .length ();
86106 int last = 0 ;
87107 do {
88- scanner .nextToken ();
89- Token t = scanner .token ();
108+ Token t = javacTokenIt .next ();
90109 if (t .comments != null ) {
91110 for (Comment c : Lists .reverse (t .comments )) {
92111 if (last < c .getSourcePos (0 )) {
@@ -104,6 +123,8 @@ public static ImmutableList<RawTok> getTokens(
104123 break ;
105124 }
106125 if (last < t .pos ) {
126+ /* If the current token is not immediately following the previous one,
127+ treat the gap as a token */
107128 tokens .add (new RawTok (null , null , last , t .pos ));
108129 }
109130 tokens .add (
@@ -113,7 +134,7 @@ public static ImmutableList<RawTok> getTokens(
113134 t .pos ,
114135 t .endPos ));
115136 last = t .endPos ;
116- } while (scanner . token (). kind != TokenKind . EOF );
137+ } while (javacTokenIt . hasNext () );
117138 if (last < end ) {
118139 tokens .add (new RawTok (null , null , last , end ));
119140 }
0 commit comments