Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

52
LINES

< > BotCompany Repo | #1012025 // tok_moveImportsUp using reTok_multi (LIVE)

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (5299L/30K).

1  
sS tok_moveImportsUp(S src) {
2  
  ret join(tok_moveImportsUp(javaTok(src)));
3  
}
4  
5  
static LS tok_moveImportsUp(L<S> tok) {
6  
  new StringBuilder buf;
7  
  
8  
  //print("tok_moveImportsUp n=" + l(tok));
9  
  //print("Source begins: " + quote(shorten(join(tok), 200)));
10  
  
11  
  // scan imports on top
12  
  int i;
13  
  new Set<S> have;
14  
  for (i = 1; i < l(tok); i += 2)
15  
    if (eq(tok.get(i), 'import)) {
16  
      int j = indexOf(tok, i+2, ";");
17  
      if (j < 0) break;
18  
      S s = joinSubList(tok, i, j+1);
19  
      have.add(s);
20  
      i = j;
21  
    } else break;
22  
  
23  
  //print("tok_moveImportsUp have " + l(have) + " after " + i);
24  
  
25  
  new L<IntRange> reToks;
26  
  
27  
  // scan imports in text
28  
  for (; i < l(tok); i += 2)
29  
    if (eq(tok.get(i), 'import)) {
30  
      int j = indexOf(tok, i+2, ";");
31  
      if (j < 0) continue; // huh?
32  
      S s = joinSubList(tok, i, j+1);
33  
      //print("Found import at " + i + ": " + s);
34  
      if (!have.contains(s)) {
35  
        buf.append(s).append("\n");
36  
        have.add(s);
37  
      }
38  
      replaceTokens(tok, i, j+1, "");
39  
      ifndef tok_moveImportsUp_skipMostReToks
40  
        reToks.add(intRange(i, j+1));
41  
      endifndef
42  
      i -= 2;
43  
    }
44  
    
45  
  if (nempty(buf)) {
46  
    if (l(tok) == 1) addAll(tok, "", "");
47  
    tok.set(1, str(buf)+"\n"+tok.get(1));
48  
    reToks.add(intRange(1, 2));
49  
  }
50  
    
51  
  ret reTok_multi(tok, reToks);
52  
}

Author comment

Began life as a copy of #1009579

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1012025
Snippet name: tok_moveImportsUp using reTok_multi (LIVE)
Eternal ID of this version: #1012025/14
Text MD5: 06845d2c5c3b8c51cad797db8d5a1189
Transpilation MD5: 319c4dc39748b19798559ebbc98746d5
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-01-20 15:29:14
Source code size: 1367 bytes / 52 lines
Pitched / IR pitched: No / No
Views / Downloads: 508 / 665
Version history: 13 change(s)
Referenced in: [show references]