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

3193
LINES

< > BotCompany Repo | #1033035 // JavaX Translator backup

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Uses 1176K of libraries. Click here for Pure Java version (28688L/192K).

1  
!1006722
2  
3  
// TODO: deprecate (remove) the "f <id>" syntax
4  
5  
// TODO: skip ifclass blocks in findFunctionInvocations.
6  
//       after main loop completes (including standard functions+
7  
//       classes), run tok_ifclass and if any change, run main loop
8  
//       again.
9  
//       This will allow clean handling of functions like "unnull"
10  
//       which right now _always_ include Symbol (because unnull
11  
//       references emptySymbol inside an ifclass Symbol block).
12  
13  
// Note: Before editing this, transpile #7
14  
// Use 'Very fresh' (R-transpile doesn't seem to work) or Q/M if you haven't screwed yourself currently
15  
// by making your transpiler unable to transpile itself... or
16  
// something
17  
18  
// Note: Don't try hijackPrint, it doesn't seem to work in here
19  
// (because of the way it is called by e.g. transpileForServer_returnPair?)
20  
21  
/* functions to possibly edit when creating/changing JavaX constructs:
22  
  tok_pingify
23  
*/
24  
25  
// new JavaParser includes
26  
!include once #1025814
27  
!include once #1025813
28  
29  
!include once #1025802 // optimized findCodeTokens
30  
31  
set flag OurSubLists.
32  
set flag NoIllegalAccesses.
33  
34  
set flag javaTokForJFind_array_simpleCache.
35  
set flag tok_moveImportsUp_skipMostReToks.
36  
37  
set flag AllowMetaCode.
38  
set flag jreplace_performing. // record replacements
39  
40  
//set flag tok_forUnnull_debug.
41  
42  
// ifdef in cached includes? => i think cached includes still contain the ifdefs, so it's fine. tok_ifdef is not called within localStuff1
43  
44  
set flag noAI.
45  
set flag isQuoted_dirty. // should be OK, we're dealing with tokens
46  
47  
static bool autoQuine = true;
48  
static int maxQuineLength = 80;
49  
sbool assumeTriple = true;
50  
sbool quickInstanceOfEnabled; // interferes with things
51  
sbool debug_jreplace;
52  
53  
// _registerThread usually costs nothing because we need
54  
// the registerWeakHashMap mechanism anyway for ping().
55  
// Anyway - no forced functions for now :)
56  
static L<S> functionsToAlwaysInclude = ll(
57  
  //"_registerThread",
58  
  //"asRuntimeException"
59  
);
60  
61  
// classes with two type parameters that can written with just one
62  
// e.g. Pair<S> => Pair<S, S>
63  
static Set<S> pairClasses = lithashset("Pair", "Either", "Map", "AbstractMap", "HashMap", "TreeMap", "LinkedHashMap", "MultiMap", "CompactHashMap", "WrappedMap", "F1", "IF1", "AllOnAll", "AllOnAllWithUpdates", "MultiSetMap", "AutoMap", "ValueOnDemandMap", "NavigableMap", "SortedMap");
64  
65  
// classes with 3 type parameters that can written with just one
66  
// e.g. T3<S> => T3<S, S, S>
67  
static Set<S> tripleClasses = lithashset("T3", "IF2", "F2", "IVF3", "VF3");
68  
69  
sS transpilingSnippetID;
70  
//static new AtomicInteger varCount;
71  
static new ThreadLocal<AtomicInteger> varCountByThread;
72  
static Map<S, S> snippetCache = syncMap();
73  
sbool useIndexedList2 = false, useTokenIndexedList = true;
74  
sbool opt_javaTok = true;
75  
static bool cacheStdFunctions = true, cacheStdClasses = true;
76  
static new HashMap<Long, CachedInclude> cachedIncludes;
77  
static ExecutorService executor;
78  
static L lclasses;
79  
static long startTime, lastPrint;
80  
81  
// These variables have to be cleared manually for each transpilation
82  
83  
static new HashSet<Long> included;
84  
static NavigableSet<S> definitions = ciSet();
85  
static new HashMap<S> rewrites;
86  
static new HashSet<S> shouldNotIncludeFunction; // this verifies after the fact that the function was not included
87  
static new HashSet<S> shouldNotIncludeClass;
88  
static new HashSet<S> doNotIncludeFunction; // this actually prevents the function from being included
89  
static new SS functionToPackage;
90  
static new HashSet<S> doNotIncludeClass;
91  
static new HashSet<S> needLatest; // this forces a function to be included
92  
static new HashSet<S> addedFunctions;
93  
static new HashSet<S> addedClasses;
94  
static new HashSet<S> hardFunctionReferences;
95  
static new HashSet<S> mapLikeFunctions;
96  
static new HashSet<S> lambdaMapLikeFunctions;
97  
static new HashSet<S> curry1LikeFunctions;
98  
static new HashSet<S> mapMethodLikeFunctions;
99  
static new HashSet<S> nuLikeFunctions;
100  
static new HashSet<S> getLikeFunctions; // name is slightly misleading. this turns a pre-argument into a fieldLambda
101  
static new HashSet<S> lambdaMethod0LikeFunctions; // we're getting better again with the names (maybe)
102  
static new HashSet<S> lambda0LikeFunctions;
103  
static SS extraStandardFunctions;
104  
sbool quickmainDone1, quickmainDone2;
105  
static new TreeSet<S> libs;
106  
sS mainBaseClass, mainPackage, mainClassName;
107  
sbool localStuffOnly; // for transpiling a fragment
108  
sbool asInclude; // for transpiling an include (auto-close scopes, enable all standard class ifclass [todo])
109  
sbool allowMetaCode = false; // run any embedded meta code
110  
static LS metaPostBlocks, metaTransformers, localTransformers;
111  
sbool dontPrintSource;
112  
sbool dontLoadCachedIncludesFromVM; // for benchmarking
113  
static new HashSet<S> haveClasses;
114  
115  
sclass CachedInclude {
116  
  S javax;
117  
  Future<S> java;
118  
  S realJava;
119  
  long snippetID;
120  
  
121  
  *() {}
122  
  *(long *snippetID) {}
123  
  
124  
  S java() {
125  
    ret realJava != null ? realJava : getFuture(java);
126  
  }
127  
  
128  
  Future<S> javaFuture() {
129  
    ret realJava != null ? nowFuture(realJava) : java;
130  
  }
131  
  
132  
  void clean {
133  
    if (java != null) {
134  
      realJava = getFuture(java);
135  
      java = null;
136  
    }
137  
  }
138  
}
139  
140  
p {
141  
  startTime = lastPrint = sysNow();
142  
  pcall {
143  
    if (!dontLoadCachedIncludesFromVM)
144  
      vmKeepWithProgramMD5_get('cachedIncludes);
145  
  }
146  
  executor = Executors.newFixedThreadPool(numberOfCores());
147  
  transpilingSnippetID = or(getThreadLocal((ThreadLocal<S>) getOpt(javax(), 'transpilingSnippetID)), transpilingSnippetID);
148  
  //print(+transpilingSnippetID);
149  
  set transpileRaw_dontCopyFromCreator;
150  
  
151  
  fO oldPrint = or(print_byThread()!, f print_raw);
152  
  temp tempInterceptPrint(new F1<S, Bool>() {
153  
    Bool get(S s) {
154  
      long now = sysNow();
155  
      long time = now-lastPrint; // -startTime;
156  
      lastPrint = now;
157  
      callF(oldPrint, "[" + formatInt(time/1000, 2) + ":" + formatInt(time % 1000, 3) + "] " + s);
158  
      false;
159  
    }
160  
  });
161  
  
162  
  try {
163  
    _main();
164  
  } finally {
165  
    interceptPrintInThisThread(oldPrint);
166  
    if (executor != null) executor.shutdown();
167  
    executor = null;
168  
    localStuffOnly = false;
169  
    asInclude = false;
170  
  }
171  
}
172  
173  
svoid _main() ctex {
174  
  if (sameSnippetID(programID(), defaultJavaXTranslatorID())) setDefaultJavaXTranslatorID(#7);
175  
  
176  
  //reTok_modify_check = true;
177  
  //if (useIndexedList) findCodeTokens_debug = true;
178  
  javaTok_opt = opt_javaTok;
179  
  //findCodeTokens_indexed = findCodeTokens_unindexed = 0;
180  
  findCodeTokens_bails = findCodeTokens_nonbails = 0;
181  
  javaTok_n = javaTok_elements = 0;
182  
  S in = loadMainJava();
183  
  
184  
  print("759 STARTING " + identityHashCode(main.class));
185  
  // clear things
186  
  includeInMainLoaded_magicComment = null;
187  
  included.clear();
188  
  definitions.clear();
189  
  rewrites.clear();
190  
  // XXX definitions.add("SymbolAsString");
191  
  shouldNotIncludeFunction.clear();
192  
  shouldNotIncludeClass.clear();
193  
  doNotIncludeFunction.clear();
194  
  functionToPackage.clear();
195  
  needLatest.clear();
196  
  doNotIncludeClass.clear();
197  
  addedFunctions.clear();
198  
  addedClasses.clear();
199  
  hardFunctionReferences.clear();
200  
  mapLikeFunctions = cloneHashSet(tok_mapLikeFunctions());
201  
  lambdaMapLikeFunctions = new HashSet;
202  
  curry1LikeFunctions = new HashSet;
203  
  mapMethodLikeFunctions = cloneHashSet(tok_mapMethodLikeFunctions());
204  
  nuLikeFunctions.clear();
205  
  getLikeFunctions.clear();
206  
  lambdaMethod0LikeFunctions.clear();
207  
  lambda0LikeFunctions.clear();
208  
  extraStandardFunctions = new HashMap;
209  
  libs.clear();
210  
  mainBaseClass = mainPackage = mainClassName = null;
211  
  varCountByThread.set(null);
212  
  quickmainDone1 = quickmainDone2 = false;
213  
  metaPostBlocks = new L;
214  
  metaTransformers = new L;
215  
  localTransformers = new L;
216  
  dontPrintSource = false;
217  
  defaultMaxQuineLength_value = defaultMaxQuineLength_defaultValue;
218  
  debug_jreplace = false;
219  
  haveClasses.clear();
220  
  
221  
  //L ts = findTranslators(toLines(join(tok)));
222  
  //print("Translators in source at start: " + structure(ts));
223  
  
224  
  L<S> tok = jtok(in);
225  
  
226  
  try {
227  
    tok_definitions(tok);
228  
    
229  
    // add m { }
230  
    
231  
    if (!localStuffOnly && !hasCodeTokens(tok, "m", "{") && !hasCodeTokens(tok, "main", "{") && !hasCodeTokens(tok, "class", "main")) {
232  
      if (l(tok) == 1) tok = singlePlusList(first(tok), dropFirst(javaTok("m {}")));
233  
      else {
234  
        replaceTokens_reTok(tok, 1, 2, "m {\n\n" + unnull(get(tok, 1)));
235  
        replaceTokens_reTok(tok, l(tok)-2, l(tok)-1, unnull(get(tok, l(tok)-2)) + "}");
236  
      }
237  
      tok_moveImportsUp(tok);
238  
    }
239  
    
240  
    // standard translate
241  
    
242  
    //ts = findTranslators(toLines(join(tok)));
243  
    //print("Translators in source: " + structure(ts));
244  
    
245  
    if (tok_hasTranslators(tok))
246  
      tok = jtok(defaultTranslate(join(tok)));
247  
    
248  
    //print("end of default translate");
249  
    //print(join(tok));
250  
  
251  
    //tok_autoCloseBrackets(tok);    
252  
    
253  
    tok_metaTransformNow(tok);
254  
    
255  
    tok_processEarlyIncludes(tok);
256  
      
257  
    tok_earlyGeneralStuff(tok);
258  
    
259  
    tok = tok_processIncludes(tok); // before standard functions
260  
    if (processConceptsDot(tok))
261  
      tok = tok_processIncludes(tok);
262  
    tok = localStuff1(tok);
263  
    
264  
   if (!localStuffOnly) {
265  
    int safety = 0;
266  
    boolean same;
267  
    do { // BIG LOOP
268  
      ping();
269  
      LS before = cloneList(tok);
270  
      
271  
      // do the non-local stuff (flags and rewrites, things that correlate across includes like tok_selfType)
272  
      
273  
      // to allow crazy stuff like "nonStatic !include #someStaticClass"
274  
      tok_processEarlyIncludes(tok);
275  
      
276  
      jreplace(tok, "nonStatic static", "");
277  
      
278  
      tok_selfType(tok);
279  
      tok_mainClassNameAndPackage(tok);
280  
      tok_definitions(tok);
281  
      tok_ifndef(tok);
282  
      tok_ifdef(tok);
283  
      defineMapLikesEtc(tok);
284  
      if (tok_applyAllXLikeFunctions(tok)) {
285  
        functionReferences(tok);
286  
        lambdaReferences(tok);
287  
      }
288  
      
289  
      tok_dropExtraCommas(tok); // from e.g. tok_applyMapMethodLikeFunctions
290  
      tok_delegateTo(tok);
291  
      tok_replaceWith(tok);
292  
      tok_findAndClearRewrites(tok);
293  
      tok_processRewrites(tok);
294  
      
295  
      tok_multiTypeArguments_v2(tok);
296  
      
297  
      // main bla(...) => mainClassName.bla(...)
298  
      // or main ClassName => main.ClassName
299  
      //jreplace(tok, "main <id>(", mainClassName() + ".$2(");
300  
      grabImportedStaticFunctions(tok);
301  
      jreplace_dyn_allowNull(tok, "main <id>", (_tok, cIdx, end) -> {
302  
        S fname = _tok.get(cIdx+2);
303  
        bool isClass = haveClasses.contains(fname);
304  
        printVars expandMainRef(+fname, +isClass);
305  
        if (isClass || eqGet(_tok, cIdx+4, "(")) {
306  
          S pkg = functionToPackage.get(fname);
307  
          printVars expandMainRef(+pkg);
308  
          S call = "." + fname;
309  
          ret or(pkg, mainClassName()) + call;
310  
        }
311  
        null;
312  
      });
313  
      
314  
      try {
315  
        if (safety == 0) tok = quickmain(tok);
316  
      } catch e {
317  
        printSources(tok);
318  
        rethrow(e);
319  
      }
320  
      tok_collectMetaPostBlocks(tok, metaPostBlocks);
321  
      tok_collectTransformers(tok, metaTransformers);
322  
      tok_collectTransformers(tok, localTransformers, "meta-transformLocal");
323  
324  
      tok_metaTransformNow(tok);
325  
      
326  
      // Hack to allow DynModule to reimplement _registerThread
327  
      /*if (tok.contains("DynModule") && !addedClasses.contains("DynModule"))
328  
        addStandardClasses_v2(tok);*/
329  
      
330  
      defineExtraSF(tok);
331  
      tok = standardFunctions(tok);
332  
      tok = stdstuff(tok); // all the keywords, standard
333  
      S diff;
334  
      long startTime = now();
335  
      //diff = unidiff(before, join(tok));
336  
      //print("unidiff: " + (now()-startTime) + " ms");
337  
      //same = eq(diff, "");
338  
      same = eq(tok, before);
339  
      if (!same) {
340  
        print("Not same " + safety + ".");
341  
        //print(indent(2, diff));
342  
      }
343  
      if (safety++ >= 10) {
344  
        //print(unidiff(before, join(tok)));
345  
        printSources(tok);
346  
        fail("safety 10 error!");
347  
      }
348  
    } while (!same); // END OF BIG LOOP
349  
    
350  
    print("Post.");
351  
    
352  
    if (mainBaseClass != null) {
353  
      jreplace1(tok, "class main", "class main extends " + mainBaseClass);
354  
      mainBaseClass = null;
355  
    }
356  
    
357  
    print('moveImportsUp); tok_moveImportsUp(tok);
358  
    
359  
    print('Indexing); tok = indexTokenList(tok);
360  
    
361  
    // POST-PROCESSING after stdstuff loop
362  
    
363  
    if (transpilingSnippetID != null)
364  
      jreplace_dyn(tok, "class whatever", 
365  
        func(L<S> tok, int cIndex) -> S {
366  
          pcall { ret "class " + stringToLegalIdentifier(getSnippetTitle(transpilingSnippetID)); }
367  
          ret "class Whatever";
368  
        });
369  
    
370  
    //print("Type<A, A>"); // Type<A> to Type<A, A>
371  
    
372  
    print('extendClasses); tok = extendClasses(tok);
373  
    print('libs); libs(tok);
374  
    print('sourceCodeLine); sourceCodeLine(tok);
375  
    
376  
    tok_overridableFunctionDefs(tok, null);
377  
    
378  
    // escaping for lambdas
379  
    //jreplace(tok, "-=>", "->");
380  
  
381  
    // Stuff that depends on the list of inner classes (haveClasses)
382  
    haveClasses = haveClasses_actual(tok);
383  
    print('innerClassesVar); innerClassesVar(tok, haveClasses);
384  
    fillVar_transpilationDate(tok);
385  
    haveClasses_addImported(tok, haveClasses);
386  
    print('ifclass); tok_ifclass(tok, haveClasses);
387  
    
388  
    print('slashCasts); slashCasts(tok, haveClasses);
389  
    print('newWithoutNew); newWithoutNew(tok, haveClasses);
390  
    
391  
    if (!assumeTriple) {
392  
      print('Triple);
393  
      if (tok.contains("Triple") && !haveClasses.contains("Triple")) {
394  
        jreplace(tok, "Triple", "T3");
395  
        haveClasses.remove("Triple");
396  
        haveClasses.add("T3");
397  
        slashCasts(tok, lithashset("T3"));
398  
        tok_quickInstanceOf(tok, lithashset("T3"));
399  
      }
400  
    }
401  
    
402  
    if (hasDef("SymbolAsString"))
403  
      jreplace(tok, "Symbol", "String");
404  
  
405  
    // using non-lazy version now for cleanImports
406  
    print('classReferences); expandClassReferences/*_lazy*/(tok, haveClasses);
407  
    
408  
    if (metaCodeAllowed()) runMetaPostBlocks(tok);
409  
410  
    // Error-checking
411  
    print("Error-checking"); 
412  
    Set<S> functions = new HashSet(findFunctions(tok));
413  
    for (S f : hardFunctionReferences)
414  
      if (!functions.contains(f))
415  
        fail("Function " + f + " requested, but not supplied");
416  
  
417  
    print('autoImports); tok = autoImports(tok); // faster to do it at the end
418  
    
419  
    if (hasDef("cleanImports"))
420  
      tok_cleanImports(tok);
421  
    
422  
    if (includeInMainLoaded_magicComment != null) {
423  
      int i = lastIndexOfStartingWith(tok, includeInMainLoaded_magicComment);
424  
      if (i >= 0) tok.set(i, dropPrefix(includeInMainLoaded_magicComment, tok.get(i)));
425  
    }
426  
427  
    print("definitions=" + sfu(definitions));
428  
    if (containsOneOf(definitions, "allpublic", "reparse", "PublicExceptTopClass")) {
429  
      // Fire up the Java parser & pretty printer!
430  
      print(containsIC(definitions, "allpublic")? "Making all public." : "Reparsing.");
431  
      //try {
432  
        S src = join(tok);
433  
        try {
434  
          if (containsIC(definitions, "allpublic"))
435  
            src = javaParser_makeAllPublic(src);
436  
          else if (containsIC(definitions, "PublicExceptTopClass"))
437  
            src = javaParser_makeAllPublic(src, notTopLevelClassDecl := true);
438  
          else if (containsIC(definitions, "keepComments"))
439  
            src = javaParser_makeAllPublic_keepComments(src);
440  
          else {
441  
            print("javaParser_reparse_keepComments. size=" + l(src));
442  
            src = javaParser_reparse_keepComments(src);
443  
            print("size=" + l(src));
444  
          }
445  
        } catch e {
446  
          S _src = src;
447  
          S errorContext = extractAndPrintJavaParseError(_src, e);
448  
          File f = transpilerErrorSourceFile();
449  
          saveTextFileVerbose(f, src);
450  
          dontPrintSource = true;
451  
          fail("Java parsing error:" + errorContext + innerMessage(e)); // drop the long nested parser stacktraces
452  
        }
453  
        tok = jtok(src);
454  
      /*} catch e {
455  
        S src = join(tok);
456  
        if (!dontPrintSource)
457  
          print(src);
458  
        print(f2s(saveProgramTextFile("error.java", src)));
459  
        throw rethrow(e);
460  
      }*/
461  
    }
462  
    
463  
    // Do this after JavaParser (because it doesn't like package after class)
464  
    
465  
    if (mainPackage != null) {
466  
      print('mainPackage);
467  
      tokPrepend(tok, 1, "package " + mainPackage + ";\n");
468  
      reTok(tok, 1, 2);
469  
    }
470  
    
471  
    if (mainClassName != null) {
472  
      print('mainClassName);
473  
      jreplace(tok, "class main", "class " + mainClassName);
474  
      jreplace(tok, "main.class", mainClassName + ".class");
475  
      //tokPrepend(tok, 1, "class main {}\n"); // so main.class is generated and compiler sanity checks succeed. we can later skip it in the JavaXClassLoader
476  
    }
477  
    
478  
    if (nempty(libs)) {
479  
      print("Adding libs: " + libs);
480  
      tok.add(concatMap_strings(func(S s) -> S { "\n!" + s }, libs));
481  
    }
482  
   } // if (!localStuffOnly)
483  
  } catch e {
484  
    if (!dontPrintSource)
485  
      printSources(tok);
486  
    S src = join(tok);
487  
    print(f2s(saveProgramTextFile("error.java", src)));
488  
    throw rethrow(e);
489  
  }
490  
  
491  
  /*if (useIndexedList)
492  
    print("Indexed/unindexed lookups: " + findCodeTokens_indexed + "/" + findCodeTokens_unindexed + ", lists made: " + IndexedList2.instances);
493  
  print("findCodeToken bails: " + findCodeTokens_bails + "/" + findCodeTokens_nonbails);
494  
  print("javaToks: " + javaTok_n + "/" + javaTok_elements);*/
495  
  
496  
  print("Saving.");
497  
  
498  
  // for dexcompile.php
499  
  if (mainClassName != null)
500  
    tokPrepend(tok, 0, "//FILENAME: " 
501  
      + (mainPackage != null ? mainPackage.replace(".", "/") + "/" : "") + mainClassName + ".java\n");
502  
    
503  
  if (mainJava != null)
504  
    mainJava = join(tok);
505  
  else if (tok.contains("package"))
506  
    splitJavaFiles(tok);
507  
  else
508  
    saveMainJava(tok);
509  
}
510  
511  
static LS localStuff1(LS tok) {
512  
  int safety = 0, i;
513  
  boolean same;
514  
  tok = indexTokenList(tok);
515  
  
516  
  tok_scopes(tok, autoCloseScopes := true);
517  
    
518  
  do {
519  
    ping();
520  
    LS before = cloneList(tok);
521  
    
522  
    //print("localStuff loop " + safety);
523  
    
524  
    earlyStuff(tok);
525  
    
526  
    // EARLY local stuff goes here
527  
    
528  
    tok_dropMetaComments(tok);
529  
    
530  
    tok_earlyGeneralStuff(tok);
531  
    
532  
    conceptDeclarations(tok);
533  
    tok_recordDecls(tok);
534  
    
535  
    tok = multilineStrings(tok);
536  
    tok_singleQuoteIdentifiersToStringConstants(tok);
537  
    tok_inStringEvals(tok);
538  
    tok_listComprehensions(tok);
539  
    
540  
    tok_eventInterfaces(tok);
541  
    
542  
    tok_eventFunctions(tok);
543  
    
544  
    tok_for_single(tok);
545  
    
546  
    tok_for_unpair(tok); // Do this...
547  
    //tok_doubleFor_v2(tok);
548  
    tok_doubleFor_v3(tok); // ...before this
549  
    
550  
    tok_forUnnull(tok);
551  
    tok_ifCast(tok);
552  
    forPing(tok);
553  
    tok_directSnippetRefs(tok);
554  
    quicknu(tok);
555  
    //tok_juxtaposeCalls(tok);
556  
    
557  
    jreplace(tok, "LLS", "L<LS>");
558  
    jreplace(tok, "LS", "L<S>");
559  
    jreplace(tok, "ES", "Ext<S>");
560  
    jreplace(tok, "ExtS", "Ext<S>");
561  
    
562  
    jreplace(tok, "WeakRef", "WeakReference");
563  
    
564  
    jreplace(tok, "dispose <id>;", "{ cleanUp($2); $2 = null; }");
565  
  
566  
    tok_doPing(tok);
567  
      
568  
    replaceKeywordBlock(tok,
569  
      "swing",
570  
      "{ swing(r {",
571  
      "}); }");
572  
      
573  
    replaceKeywordBlock(tok,
574  
      "androidUI",
575  
      "{ androidUI(r {",
576  
      "}); }");
577  
      
578  
    replaceKeywordBlock(tok,
579  
      "withDBLock",
580  
      "{ withDBLock(r {",
581  
      "}); }");
582  
      
583  
    replaceKeywordBlock(tok, "afterwards", "temp tempAfterwards(r {", "});");
584  
      
585  
    for (S keyword : ll("tokcondition", "tokCondition"))
586  
      replaceKeywordBlock(tok,
587  
        keyword,
588  
        "new TokCondition { public bool get(final L<S> tok, final int i) {",
589  
        "}}");
590  
      
591  
    jreplace(tok, "synced <id>", "synchronized $2");
592  
    jreplace(tok, "sync <id>", "synchronized $2");
593  
    
594  
    jreplace(tok, "synchronized {", "synchronized(this) {");
595  
    
596  
    replaceKeywordBlock(tok, "answer",
597  
      "static S answer(S s) {\nfinal new Matches m;\n",
598  
      "\nret null;\n}");
599  
      
600  
    replaceKeywordBlock(tok, "static-pcall",
601  
      "static { pcall {",
602  
      "}}");
603  
      
604  
    replaceKeywordBlock(tok, "loading",
605  
      "{ temp tempShowLoadingAnimation(); ",
606  
      "}");
607  
  
608  
    replaceKeywordPlusQuotedBlock(tok, "loading",
609  
      new O { S[] get(L<S> tok, int i) {
610  
        S text = tok.get(i+2);
611  
        ret new S[] {
612  
          "{ temp tempShowLoadingAnimation(" + text + "); ",
613  
          "}" };
614  
      }});
615  
      
616  
    while ((i = jfind(tok, "visualize as")) >= 0) {
617  
      int j = tok_findEndOfStatement(tok, i); // expression, rather
618  
      tok.set(i+2, "{ ret");
619  
      tok.set(j-1, "; }");
620  
      reTok(tok, i, j);
621  
    }
622  
      
623  
    for (S pat : ll("visual {", "visualize {"))
624  
      jreplace(tok, pat, "public JComponent visualize() {", tokCondition_beginningOfMethodDeclaration());
625  
  
626  
    jreplace(tok, "visualize2 {", "JComponent visualize2() {", tokCondition_beginningOfMethodDeclaration());
627  
    
628  
    replaceKeywordBlock(tok, "start-thread-printDone", "start-thread {", "printDone(); }");
629  
630  
    replaceKeywordBlock(tok, "start-thread", [[start { thread "Start" { temp enter(); pcall {]], "}}}");
631  
    
632  
    jreplace(tok, "start {", "void start() ctex { super.start();", tokCondition_beginningOfMethodDeclaration());
633  
    
634  
    var notVoidMethod = tokcondition {
635  
      ret neqGet(tok, i-1, "void");
636  
    };
637  
    
638  
    // run { ... } => public void run() { ... }
639  
    // same with close
640  
    // These need to be ctex as AutoCloseable and Runnable don't allow explicit exceptions
641  
    jreplace(tok, "run {", "public void run() ctex {", notVoidMethod);
642  
    jreplace(tok, "close {", "public void close() ctex {", notVoidMethod);
643  
    
644  
    replaceKeywordBlock(tok, "html",
645  
      "static O html(S uri, fMap<S, S> params) ctex " + "{\n", "}");
646  
    
647  
    replaceKeywordBlock(tok, "afterVisualize",
648  
      "visualize { JComponent _c = super.visualize();",
649  
      "ret _c; }");
650  
    
651  
    replaceKeywordBlock(tok, "enhanceFrame",
652  
      "void enhanceFrame(Container f) { super.enhanceFrame(f);",
653  
      "}");
654  
    
655  
    if (assumeTriple)
656  
      jreplace(tok, "Triple", "T3");
657  
658  
    tok_shortFinals(tok);
659  
    
660  
    tok_moduleClassDecls(tok);
661  
662  
    jreplace(tok, "static sync", "static synchronized");
663  
    jreplace(tok, "sclass", "static class");
664  
    jreplace(tok, "fclass", "final class");
665  
    jreplace(tok, "fsclass", "final static class");
666  
    jreplace(tok, "srecord", "static record");
667  
    jreplace(tok, "strecord", "static transformable record");
668  
    jreplace(tok, "record noeq", "noeq record");
669  
    jreplace(tok, "asclass", "abstract static class");
670  
    jreplace(tok, "sinterface", "static interface");
671  
    jreplace(tok, "ssynchronized", "static synchronized");
672  
  
673  
    jreplace(tok, "ssvoid", "static synchronized void");
674  
    jreplace(tok, "sbool", "static bool");
675  
    jreplace(tok, "fbool", "final bool");
676  
    jreplace(tok, "sint", "static int");
677  
    jreplace(tok, "snew", "static new");
678  
    jreplace(tok, "sv <id>", "static void $2");
679  
    jreplace(tok, "pvoid", "public void");
680  
  
681  
    // "sS" => static S
682  
    jreplace(tok, "sS", "static S");
683  
  
684  
    // "sO" => static O
685  
    jreplace(tok, "sO", "static O");
686  
  
687  
    // "sL" => static L
688  
    jreplace(tok, "sL", "static L");
689  
  
690  
    // "toString {" => "public S toString() {"
691  
    jreplace(tok, "toString {", "public S toString() {");
692  
    
693  
    jreplace(tok, "Int", "Integer");
694  
    jreplace(tok, "Bool", "Boolean");
695  
    jreplace(tok, "BigInt", "BigInteger");
696  
    jreplace(tok, "Char", "Character");
697  
    
698  
    jreplace(tok, "Sym", "Symbol");
699  
    jreplace(tok, "SymSym", "SymbolSymbol");
700  
    
701  
    jreplace(tok, "SS", "Map<S>");
702  
    jreplace(tok, "SymbolSymbol", "Map<Symbol>");
703  
    
704  
    jreplace(tok, "CISet", "Set<S>");
705  
    
706  
    jreplace(tok, "MapSO", "Map<S, O>");
707  
    
708  
    jreplace(tok, "ByName<", "IF1<S, ");
709  
    
710  
    jreplace(tok, "ITransform<<id>>", "IF1<$3>");
711  
    jreplace(tok, "ITransform", "IF1");
712  
    
713  
    jreplace(tok, "PairS", "Pair<S>");
714  
    jreplace(tok, "LPairS", "L<Pair<S>>");
715  
    
716  
    jreplace(tok, "T3S", "T3<S>");
717  
    jreplace(tok, "F1S", "F1<S>");
718  
    
719  
    jreplace(tok, "ItIt", "IterableIterator");
720  
    jreplace(tok, "CloseableItIt", "CloseableIterableIterator");
721  
722  
    jreplace(tok, "class <id> > <id>", "class $2 extends $4", tokCondition {
723  
      S t = _get(tok, i+1+4*2);
724  
      ret eq(t, "{") || isIdentifier(t);
725  
    });
726  
    jreplace(tok, "class <id> > <id><<id>> {", "class $2 extends $4  $5 $6 $7 {");
727  
    
728  
    jreplace(tok, "ISegmenter", "IF1<BufferedImage, L<Rect>>");
729  
    
730  
    // IPred<A, B> => IF2<A, B, Bool>
731  
    jreplace(tok, "IPred<<id>, <id>>", "IF2<$3, $5, Bool>");
732  
    
733  
    // IPred<A> => IF1<A, Bool>
734  
    jreplace(tok, "IPred<<id>>", "IF1<$3, Bool>");
735  
    jreplace(tok, "IPred<<id>[]>", "IF1<$3[], Bool>");
736  
    
737  
    // Proposition => WithReasoning<S> (should we really define this?)
738  
    jreplace("Proposition", "WithReasoning<S>");
739  
    
740  
    replaceKeywordBlock(tok, "print exceptions",
741  
      "{ try {",
742  
      "} on fail __e { printStackTrace(__e); } }");
743  
    
744  
    // "on fail {" => "catch (Throwable _e) { ... rethrow(_e); }"
745  
    replaceKeywordBlock(tok, "on fail",
746  
      "catch (Throwable _e) {",
747  
      "\nthrow rethrow(_e); }");
748  
  
749  
    // "on fail e {" => "catch (Throwable e) { ... rethrow(e); }"
750  
    replaceKeywordBlock_dyn2_legacy(tok, "on fail <id>", new O {
751  
      S[] get(LS tok, int iOpening, int iClosing) {
752  
        S var = tok.get(iOpening-2);
753  
        ret new S[] {
754  
          "catch (Throwable " + var + ") {",
755  
          "\nthrow rethrow(" + var + "); }"
756  
        };
757  
      }
758  
    });
759  
760  
    // "on fail Type e {" => "catch (Type e) { ... rethrow(e); }"
761  
    replaceKeywordBlock_dyn2_legacy(tok, "on fail <id> <id>", new O {
762  
      S[] get(LS tok, int iOpening, int iClosing) {
763  
        S type = tok.get(iOpening-4);
764  
        S var = tok.get(iOpening-2);
765  
        ret new S[] {
766  
          "catch (" + type + " " + var + ") {",
767  
          "\nthrow " + var + "; }"
768  
        };
769  
      }
770  
    });
771  
772  
    // "catch {" => "catch (Throwable _e) {"
773  
    jreplace(tok, "catch {", "catch (Throwable _e) {");
774  
  
775  
    jreplace_dyn(tok, "catch print {", -> {
776  
      S var = makeVar();
777  
      ret "catch \*var*/ { printStackTrace(\*var*/);";
778  
    });
779  
  
780  
    // "catch print e {" => "catch e { printStackTrace(e); "
781  
    jreplace(tok, "catch print <id> {", "catch $3 { printStackTrace($3);");
782  
  
783  
    // "catch print short e {" => "catch e { printExceptionShort(e); "
784  
    jreplace(tok, "catch print short <id> {", "catch $4 { printExceptionShort($4);");
785  
    
786  
    // "catch X e {" => "catch (X e) {"
787  
    jreplace(tok, "catch <id> <id> {", "catch ($2 $3) {");
788  
  
789  
    // "catch e {" => "catch (Throwable e) {" (if e is lowercase)
790  
    jreplace(tok, "catch <id> {", "catch (Throwable $2) {", tokcondition {
791  
      S word = tok.get(i+3);
792  
      ret startsWithLowerCaseOrUnderscore(word);
793  
    });
794  
    
795  
    jreplace(tok, "+ +", "+", tokcondition {
796  
      //printStructure("++: ", subList(tok, i-1, i+6));
797  
      if (empty(_get(tok, i+2))) ret false; // no space between the pluses
798  
      if (empty(_get(tok, i)) && eq("+", _get(tok, i-1))) ret false;  // an actual "++" at the left
799  
      if (empty(_get(tok, i+4)) && eq("+", _get(tok, i+5))) ret false;  // an actual "++" at the right
800  
      //print("doing it");
801  
      ret true;
802  
    });
803  
  
804  
    // single underscore (not allowed in Java anymore) to double underscore
805  
    jreplace(tok, "_", "__");
806  
    
807  
    // [stdEq] -> implementation of equals() and hashCode()
808  
    jreplace(tok, "[stdEq]",
809  
      "public bool equals(O o) { ret stdEq2(this, o); }\n" +
810  
      "public int hashCode() { ret stdHash2(this); }");
811  
    
812  
    // [stdToString] -> toString { ret stdToString(this); }
813  
    jreplace(tok, "[stdToString]",
814  
      "toString { ret stdToString(this); }");
815  
    
816  
    // [concepts] "concept.field!" for dereferencing references
817  
    
818  
    // "<id>!", "?!" etc.
819  
    jreplace(tok, "*!", "$1.get()", tokcondition {
820  
      S l = tok.get(i+1);
821  
      if (!(isIdentifier(l) || eqOneOf(l, ")", "?"))) false;
822  
      if (tok.get(i+2).contains("\n")) false; // no line break between <id> and !
823  
      if (nempty(tok.get(i+4))) true; // space after = ok
824  
      S t = _get(tok, i+5);
825  
      if (t == null) ret false;
826  
      if (isIdentifier(t) || eqOneOf(t, "=", "(")) false;
827  
      true;
828  
    });
829  
    
830  
    jreplace(tok, "for (<id> :", "for (var $3 :");
831  
    
832  
    jreplace(tok, "for (<id> <id>)", "for ($3 $4 : list($3))");
833  
    jreplace(tok, "for (final <id> <id>)", "for (final $4 $5 : list($4))");
834  
835  
    jreplace(tok, "ret", "return", tokCondition {
836  
      if (eqGetOneOf(tok, i-1, "int", "return")) false;
837  
      S next = _get(tok, i+3);
838  
      if (eq(next, ".")) ret isInteger(_get(tok, i+5)); // e.g. "ret .1", but not "ret.bla"
839  
      ret !eqOneOf(next, "=", ")");
840  
    });
841  
    
842  
    // "continue unless", "break unless"
843  
    
844  
    for (S phrase : ll("continue unless", "break unless"))
845  
      while ((i = jfind(tok, phrase)) >= 0) {
846  
        S keyword = tok.get(i);
847  
        int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
848  
        replaceTokens(tok, i, i+4, "{ if (!(");
849  
        tok.set(j, ")) " + keyword + "; }");
850  
        reTok(tok, i, j+1);
851  
      }
852  
    
853  
    // S s = bla(), return if null; => S s = bla(); if (s == null) return;
854  
    // same with continue, break
855  
    while ((i = jfind(tok, ", <id> if null;", tokCondition {
856  
      ret eqOneOf(tok.get(i+3), "return", "ret", "continue", "break");
857  
    })) >= 0) {
858  
      S cmd = tok.get(i+2);
859  
      int j = tok_findBeginningOfStatement(tok, i);
860  
      print("Found statement " + j + "/" + i + " - " + joinSubList(tok, j-1, i+5*2-1));
861  
      S var = getVarDeclarationName(subList(tok, j-1, i));
862  
      replaceTokens_reTok(tok, i, i+5*2-1, "; if (" + var + " == null) " + cmd + ";");
863  
    }
864  
    
865  
    // S s = bla(), return false if null; => S s = bla(); if (s == null) return false;
866  
    // (with false being any identifier)
867  
    while ((i = jfind(tok, ", return <id> if null;")) >= 0) {
868  
      S returnValue = tok.get(i+4);
869  
      int j = tok_findBeginningOfStatement(tok, i);
870  
      S var = getVarDeclarationName(subList(tok, j-1, i));
871  
      replaceTokens_reTok(tok, i, i+6*2-1, "; if (" + var + " == null) return " + returnValue + ";");
872  
    }
873  
    
874  
    // "continue if", "break if"
875  
    
876  
    for (S phrase : ll("continue if", "break if"))
877  
      while ((i = jfind(tok, phrase)) >= 0) {
878  
        S keyword = tok.get(i);
879  
        int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
880  
        replaceTokens(tok, i, i+4, "{ if (");
881  
        tok.set(j, ") " + keyword + "; }");
882  
        reTok(tok, i, j+1);
883  
      }
884  
    
885  
    // return unless set <var>; => { if (var) return; set var; }
886  
    jreplace(tok, "return unless set <id>;", "{ if ($4) return; set $4; }");
887  
888  
    // set x; => x = true;
889  
    // yeah it doesn't save many characters, but I like it
890  
    jreplace(tok, "set <id>;", "$2 = true;", tokCondition {
891  
      ret !eqGet(tok, i-1, "unless");
892  
    });
893  
    
894  
    // set !x; => x = false; (did this one day and thought yes it makes sense in a way)
895  
    jreplace(tok, "set !<id>;", "$3 = false;");
896  
    
897  
    // unset x; => x = false;
898  
    jreplace(tok, "unset <id>;", "$2 = false;");
899  
    
900  
    // "return if"
901  
    
902  
    while ((i = jfind(tok, "return if")) >= 0) {
903  
      int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
904  
      replaceTokens(tok, i, i+4, "{ if (");
905  
      tok.set(j, ") return; }");
906  
      reTok(tok, i, j+1);
907  
    }
908  
    
909  
    // "return unless"
910  
    
911  
    while ((i = jfind(tok, "return unless")) >= 0) {
912  
      int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
913  
      replaceTokens(tok, i, i+4, "{ if (!(");
914  
      tok.set(j, ")) return; }");
915  
      reTok(tok, i, j+1);
916  
    }
917  
    
918  
    tok_ifNullAssign(tok);
919  
920  
    // "return <id> if"
921  
    
922  
    // "return with <statement>" / "continue with <statement>" / "break with <statement>"
923  
    
924  
    while ((i = jfind(tok, "<id> with", tokcondition { ret eqOneOf(tok.get(i+1), "return", "continue", "break"); })) >= 0) {
925  
      // XXX int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
926  
      int j = tok_findEndOfStatement(tok, i+4)-1;
927  
      //print("Found statement: " + joinSubList(tok, i+4, j+1));
928  
      tok.set(j, "; " + tok.get(i) + "; }");
929  
      replaceTokens(tok, i, i+3, "{");
930  
      reTok(tok, i, j+1);
931  
    }
932  
    
933  
    while ((i = jfind(tok, "return <id> if")) >= 0) {
934  
      int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
935  
      tok.set(j, ") return " + tok.get(i+2) + "; }");
936  
      replaceTokens(tok, i, i+6, "{ if (");
937  
      reTok(tok, i, j+1);
938  
    }
939  
    
940  
    // return "bla" with <statement>
941  
    
942  
    while ((i = jfindOneOf(tok,
943  
      "return <quoted> with", "return <id> with")) >= 0) {
944  
      S result = tok.get(i+2);
945  
      int j = scanOverExpression(tok, getBracketMap(tok), i+6, ";");
946  
      replaceTokens(tok, i, i+5, "{");
947  
      tok.set(j, "; return " + result + "; }");
948  
      reTok(tok, i, j+1);
949  
    }
950  
    
951  
    tok_debugStatements(tok);
952  
953  
    // while not null (...) / if not null (...)
954  
    
955  
    while ((i = jfind_check not(tok, "<id> not null (", tokcondition {
956  
      ret eqOneOf(_get(tok, i+1), "if", "while");
957  
    })) >= 0) {
958  
      int closingBracket = findEndOfBracketPart(tok, i+6)-1;
959  
      replaceTokens(tok, i+2, i+6, "(");
960  
      tok.set(closingBracket, ") != null)");
961  
      reTok(tok, i, closingBracket+1);
962  
    }
963  
    
964  
    // while null (...) / if null (...)
965  
    
966  
    while ((i = jfind_check null(tok, "<id> null (", tokcondition {
967  
      ret eqOneOf(_get(tok, i+1), "if", "while");
968  
    })) >= 0) {
969  
      int closingBracket = findEndOfBracketPart(tok, i+4)-1;
970  
      replaceTokens(tok, i+2, i+4, "(");
971  
      tok.set(closingBracket, ") == null)");
972  
      reTok(tok, i, closingBracket+1);
973  
    }
974  
    
975  
    // Replace $1 with m.unq(0) etc. - caveat: this blocks identifiers $1, $2, ...
976  
    for (i = 1; i < l(tok); i += 2) {
977  
      S s = tok.get(i);
978  
      if (s.startsWith("$")) {
979  
        s = substring(s, 1);
980  
        if (isInteger(s)) {
981  
          tok.set(i, "m.unq(" + (parseInt(s)-1) + ")");
982  
          reTok(tok, i);
983  
        }
984  
      }
985  
    }
986  
  
987  
    // instanceof trickery
988  
    
989  
    jreplace(tok, "is a <id>", "instanceof $3");
990  
    jreplace(tok, "!<id> instanceof <id>.<id>", "!($2 instanceof $4.$6)");
991  
    jreplace(tok, "!<id> instanceof <id>", "!($2 instanceof $4)");
992  
    jreplace(tok, "<id> !instanceof <id>", "!($1 instanceof $4)");
993  
    
994  
    // map func1 func2 func3(...) => mapFGH(f func1, f func2, f func3, ...)
995  
    jreplace(tok, "map <id> <id> <id>(", "mapFGH(f $2, f $3, f $4,");
996  
997  
    // map func1 func2(...) => mapFG(f func1, f func2, ...)
998  
    jreplace(tok, "map <id> <id>(", "mapFG(f $2, f $3,");
999  
1000  
    // "ref->bla" for dereferencing Concept.Ref or ThreadLocal or other
1001  
    // For lambdas, use SPACES on the left or right of the arrow!
1002  
    //jreplace(tok, "<id> ->", "$1.get().");
1003  
    jreplace(tok, "->", ".get().", tokcondition {
1004  
      ret empty(tok.get(i)) // no space on left of arrow
1005  
        && empty(tok.get(i+2)) // no space inside of arrow
1006  
        && empty(tok.get(i+4)) // no space on right of arrow
1007  
        && !eq(_get(tok, i-1), "-"); // i-->0;
1008  
    });
1009  
    
1010  
    // shortened subconcept declaration (before star constructors!)
1011  
    shortenedSubconcepts(tok);
1012  
    
1013  
    tok_beaConceptDecls(tok);
1014  
    
1015  
    // "case" as a variable name ( => _case)
1016  
    
1017  
    caseAsVariableName(tok);
1018  
    
1019  
    // "do" as a function name ( => dO)
1020  
    
1021  
    tok_doAsMethodName(tok);
1022  
    
1023  
    // "continue" as a function name ( => _continue)
1024  
    continueAsFunctionName(tok);
1025  
    
1026  
    tok_extend(tok);
1027  
    
1028  
    jreplace(tok, "pn {", "p-noconsole {");
1029  
      
1030  
    // Do these BEFORE awt replacement! ("p-awt" contains "awt" token)
1031  
    replaceKeywordBlock(tok, "r-awt", "r { awt {", "}}");
1032  
    if (hasCodeTokens(tok, "p", "-")) tok_p_old(tok);
1033  
1034  
    replaceKeywordBlock(tok, "awt-messagebox", "awt { pcall-messagebox {", "}}");
1035  
    replaceKeywordBlock(tok, "awt", "swingLater(r {", "});");
1036  
  
1037  
    jreplace(tok, "p-android {", "set flag Android. p {");
1038  
      
1039  
    unswing(tok);
1040  
    lockBlocks(tok);
1041  
    tok_switchTo(tok);
1042  
    
1043  
    // trim x;
1044  
    
1045  
    jreplace(tok, "trim <id>;", "$2 = trim($2);");
1046  
  
1047  
    // iterate with index
1048  
  
1049  
    jreplace (tok, "for <id> over <id>:", "for (int $2 = 0; $2 < l($4); $2++)");
1050  
    jreplace (tok, "for <id> backwards over <id>:", "for (int $2 = l($5)-1; $2 >= 0; $2--)");
1051  
    jreplace (tok, "for <id>, <id> <id> over <id>: {", "for (int $2 = 0; $2 < l($7); $2++) { $4 $5 = $7.get($2);");
1052  
    jreplace (tok, "for <id>, <id> <id> backwards over <id>: {", "for (int $2 = l($8)-1; $2 >= 0; $2--) { $4 $5 = $8.get($2);");
1053  
    jreplace (tok, "for <id> to <id>:", "for (int $2 = 0; $2 < $4; $2++)");
1054  
    jreplace (tok, "for <id> to <int>:", "for (int $2 = 0; $2 < $4; $2++)");
1055  
    
1056  
    tok = expandShortTypes(tok);
1057  
      
1058  
    tok_equalsCast(tok);
1059  
    tok_equalsOptCast(tok);
1060  
1061  
    replaceKeywordBlock(tok, "r-thread-messagebox", "r-thread { pcall-messagebox {", "}}");
1062  
    
1063  
    replaceKeywordBlock(tok, "thread-messagebox", "thread { pcall-messagebox {", "}}");
1064  
    
1065  
    jreplace(tok, "rThread {", "r-thread {");
1066  
    jreplace(tok, "rEnterThread {", "rThreadEnter {");
1067  
    jreplace(tok, "rThreadEnter {", "r-thread { temp enter(); ");
1068  
  
1069  
    replaceKeywordBlock(tok, "r-thread", "runnableThread(r {", "})");
1070  
    rNamedThread(tok);
1071  
    
1072  
    // only works in the scope of a DynModule
1073  
    jreplace(tok, "rEnter {", "r { temp enter(); ");
1074  
  
1075  
    replaceKeywordBlock(tok, "r-pcall", "r { pcall {", "}}");
1076  
  
1077  
    replaceKeywordBlock(tok, "r-messagebox", "r { pcall-messagebox {", "}}");
1078  
    
1079  
    jreplace(tok, "r <id> + r <id>", "r { $2(); $5(); }");
1080  
    
1081  
    // runnable and r - now also with automatic toString if enabled
1082  
    for (S keyword : ll("runnable", "r")) {
1083  
      while ((i = jfind(tok, keyword + " {")) >= 0) {
1084  
        int idx = findCodeTokens(tok, i, false, "{");
1085  
        int j = findEndOfBracketPart(tok, idx);
1086  
        L<S> contents = subList(tok, idx+1, j-1);
1087  
        replaceTokens(tok, i, j+1, "new Runnable {"
1088  
          + "  public void run() ctex { " + tok_addSemicolon(contents) + "\n}"
1089  
          + (autoQuine ? tok_autoQuineFunc(contents) : "")
1090  
          + "}");
1091  
        reTok(tok, i, j+1);
1092  
      }
1093  
      
1094  
      while ((i = jfind(tok, keyword + " <quoted> {")) >= 0) {
1095  
        int idx = findCodeTokens(tok, i, false, "{");
1096  
        int j = findEndOfBracketPart(tok, idx);
1097  
        L<S> contents = subList(tok, idx+1, j-1);
1098  
        replaceTokens(tok, i, j+1, "new Runnable {"
1099  
          + "  public void run() ctex { " + tok_addSemicolon(contents) + "\n}"
1100  
          + "  toString { ret " + tok.get(i+2) + "; }"
1101  
          + (autoQuine ? tok_autoQuineFunc(contents, '_shortenedSourceCode) : "")
1102  
          + "}");
1103  
        reTok(tok, i, j+1);
1104  
      }
1105  
    }
1106  
    
1107  
    replaceKeywordBlock(tok,
1108  
      "expectException",
1109  
      "{ bool __ok = false; try {",
1110  
      "} catch { __ok = true; } assertTrue(\"expected exception\", __ok); }");
1111  
      
1112  
    while ((i = tok.indexOf("tex")) >= 0) {
1113  
      tok.set(i, "throws Exception");
1114  
      tok = jtok(tok);
1115  
    }
1116  
    
1117  
    // shorter & smarter whiles
1118  
    
1119  
    jreplace(tok, "while true", "while (true)");
1120  
    jreplace(tok, "while licensed", "while (licensed())");
1121  
    jreplace(tok, "repeat {", "while (licensed()) {");
1122  
    tok_repeatWithSleep(tok);
1123  
    
1124  
    // null; => return null; etc.
1125  
  
1126  
    O cond = tokcondition {
1127  
      ret tok_tokenBeforeLonelyReturnValue(tok, i-1);
1128  
    };
1129  
    jreplace(tok, "null;", "return null;", cond);
1130  
    jreplace(tok, "false;", "return false;", cond);
1131  
    jreplace(tok, "true;", "return true;", cond);
1132  
    jreplace(tok, "this;", "return this;", cond);
1133  
    
1134  
    // ok <cmd> => ret "OK" with <cmd>
1135  
    jreplace(tok, "ok <id>", "return \"OK\" with $2");
1136  
    replaceKeywordBlock(tok, "ok", "{", " return \"OK\"; }",
1137  
      func(LS _tok, int nIdx) -> bool { !eqGetOneOf(_tok, nIdx-1, "void", "svoid") });
1138  
  
1139  
    // "myFunction;" instead of "myFunction();" - quite rough
1140  
    // (isolated identifier as function call)
1141  
    cond = new TokCondition {
1142  
      public bool get(L<S> tok, int i) {
1143  
        S word = tok.get(i+3);
1144  
        //print("single word: " + word);
1145  
        ret !eqOneOf(word, "break", "continue", "return", "else", "endifdef", "endif");
1146  
      }
1147  
    };
1148  
    for (S pre : litlist("}", ";"))
1149  
      jreplace(tok, pre + " <id>;", "$1 $2();", cond);
1150  
  
1151  
    // shorter match syntax for answer methods
1152  
    
1153  
    tok_expandIfQuoted(tok);
1154  
    
1155  
    jreplace(tok, "if <id> eq <quoted>", "if (eq($2, $4))");
1156  
  
1157  
    tok_dropExtraCommas(tok);
1158  
    
1159  
    // additional translations (if necessary)
1160  
    
1161  
    jreplace(tok, "pcall ping {", "pcall { ping();");
1162  
    
1163  
    replaceKeywordBlock(tok, ") pcall",
1164  
      ") { pcall {",
1165  
      "}}");
1166  
    
1167  
    //jreplace(tok, "void <id> pcall {", "$1 $2() pcall {");
1168  
    
1169  
    replaceKeywordBlock(tok,
1170  
      "pcall",
1171  
      "try {",
1172  
      "} catch (Throwable __e) { printStackTrace(__e); }");
1173  
  
1174  
    replaceKeywordBlock(tok,
1175  
      "pcall-print",
1176  
      "try {",
1177  
      "} catch (Throwable __e) { printStackTrace(__e); }");
1178  
  
1179  
    replaceKeywordBlock(tok,
1180  
      "pcall-short",
1181  
      "try {",
1182  
      "} catch (Throwable __e) { print(exceptionToStringShort(__e)); }");
1183  
  
1184  
    replaceKeywordBlock(tok,
1185  
      "pcall-silent",
1186  
      "try {",
1187  
      "} catch (Throwable __e) { silentException(__e); }");
1188  
  
1189  
    replaceKeywordBlock(tok,
1190  
      "pcall-messagebox",
1191  
      "try {",
1192  
      "} catch __e { messageBox(__e); }");
1193  
  
1194  
    replaceKeywordBlock(tok,
1195  
      "pcall-infobox",
1196  
      "try {",
1197  
      "} catch __e { infoBox(__e); }");
1198  
  
1199  
    tok = dialogHandler(tok);
1200  
    
1201  
    replaceKeywordBlock(tok, "exceptionToUser",
1202  
      "try {",
1203  
      "} catch (Throwable __e) { ret exceptionToUser(__e); }"); 
1204  
  
1205  
    if (hasCodeTokens(tok, "twice", "{"))
1206  
      replaceKeywordBlock(tok, "twice",
1207  
        "for (int __twice = 0; __twice < 2; __twice++) {",
1208  
        "}"); 
1209  
  
1210  
    while ((i = findCodeTokens(tok, "bench", "*", "{")) >= 0) {
1211  
      int j = findEndOfBracketPart(tok, i+4)-1;
1212  
      S time = makeVar("time");
1213  
      S v = makeVar("bench");
1214  
      S n = tok.get(i+2);
1215  
      tok.set(i, "{ long " + time + " = sysNow(); for (int " + v + " = 0; " + v + " < " + n + "; " + v + "++)");
1216  
      tok.set(i+2, "");
1217  
      tok.set(j, "} printBenchResult(sysNow()-" + time + ", " + n + "); }");
1218  
      reTok(tok, i, j+1);
1219  
    }
1220  
  
1221  
    replaceKeywordBlockDyn(tok,
1222  
      "time",
1223  
      new O { S[] get() {
1224  
        S var = makeVar("startTime");
1225  
        ret new S[] {
1226  
          "{ long " + var + " = sysNow(); try { ",
1227  
          "} finally { " + var + " = sysNow()-" + var + "; saveTiming(" + var + "); } }"};
1228  
      }});
1229  
    
1230  
    // version without { }
1231  
    replaceKeywordBlockDyn(tok,
1232  
      "time2",
1233  
      new O { S[] get() {
1234  
        S var = makeVar("startTime");
1235  
        ret new S[] {
1236  
          "long " + var + " = sysNow(); ",
1237  
          " " + var + " = sysNow()-" + var + "; saveTiming(" + var + "); "};
1238  
      }});
1239  
    
1240  
    // time "bla" {
1241  
    // time msg {
1242  
    replaceKeywordPlusQuotedOrIDBlock(tok,
1243  
      "time",
1244  
      new O { S[] get(L<S> tok, int i) {
1245  
        S var = makeVar("startTime");
1246  
        ret new S[] {
1247  
          "long " + var + " = sysNow(); ",
1248  
          " done2_always(" + tok.get(i+2) + ", " + var + "); "};
1249  
      }});
1250  
    
1251  
    if (hasCodeTokens(tok, "assertFail", "{")) {
1252  
      S var = makeVar("oops");
1253  
      
1254  
      replaceKeywordBlock(tok,
1255  
        "assertFail",
1256  
        "boolean " + var + " = false; try {",
1257  
        "\n" + var + " = true; } catch (Exception e) { /* ok */ } assertFalse(" + var + ");"); 
1258  
    }
1259  
    
1260  
    replaceKeywordBlock(tok,
1261  
      "yo",
1262  
      "try {",
1263  
      "} catch (Exception " + makeVar("e") + ") { ret false; }",
1264  
      tokcondition {
1265  
        ret neqOneOf(_get(tok, i-1), "svoid", "void");
1266  
      });
1267  
  
1268  
    replaceKeywordBlock(tok,
1269  
      "awtIfNecessary",
1270  
      "swingNowOrLater(r " + "{",
1271  
      "});");
1272  
      
1273  
    ctex(tok);
1274  
      
1275  
    replaceKeywordBlock(tok,
1276  
      "actionListener",
1277  
      "new java.awt.event.ActionListener() { " +
1278  
        "public void actionPerformed(java.awt.event.ActionEvent _evt) { pcall-messagebox {",
1279  
      "}}}");
1280  
      
1281  
    for (S keyword : ll("autocloseable", "autoCloseable"))
1282  
      /*replaceKeywordBlock(tok,
1283  
        keyword,
1284  
        "new AutoCloseable() { public void close() throws Exception {",
1285  
        "}}");*/
1286  
        replaceKeywordBlock_dyn2_legacy(tok, keyword, new O {
1287  
          S[] get(LS tok, int iOpening, int iClosing) {
1288  
            LS contents = subList(tok, iOpening+1, iClosing);
1289  
            ret new S[] {
1290  
              "new AutoCloseable() { toString { ret " + quote(shorten(defaultMaxQuineLength(), trimJoin(contents))) + "; } public void close() throws Exception {",
1291  
              "}}"
1292  
            };
1293  
          }
1294  
        });
1295  
      
1296  
    // try answer (string, test with nempty)
1297  
    while ((i = findCodeTokens(tok, "try", "answer")) >= 0) {
1298  
      int j = findEndOfStatement(tok, i);
1299  
      S v = makeVar();
1300  
      bool needCurly = !eqGet(tok, i-2, "{");
1301  
      tok.set(i, (needCurly ? "{" : "") + " S " + v);
1302  
      tok.set(i+2, "=");
1303  
      tok.set(j-1, "; if (!empty(" + v + ")) ret " + v + "; " + (needCurly ? "}" : ""));
1304  
      reTok(tok, i, j);
1305  
    }
1306  
  
1307  
    // try bool[ean] (try answer with Bool type)
1308  
    while ((i = findCodeTokens(tok, "try", "boolean")) >= 0) {
1309  
      int j = findEndOfStatement(tok, i);
1310  
      S v = makeVar();
1311  
      tok.set(i, "{ Bool " + v);
1312  
      tok.set(i+2, "=");
1313  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1314  
      reTok(tok, i, j);
1315  
    }
1316  
    
1317  
    // <statement>, print "..."; => { <statement>; print("..."); }
1318  
    while ((i = jfind(tok, ", print <quoted>;")) >= 0) {
1319  
      int j = tok_findBeginningOfStatement(tok, i);
1320  
      replaceTokens_reTok(tok, i, i+4*2-1, "; print(" + tok.get(i+4) + "); }");
1321  
      tokPrepend_reTok(tok, j, "{ ");
1322  
    }
1323  
    
1324  
    // return if null <expression> => if (<expression> == null) return;
1325  
    while ((i = jfind(tok, "return if null")) >= 0) {
1326  
      int j = findEndOfStatement(tok, i);
1327  
      clearTokens(tok, i, i+2);
1328  
      tok.set(i+4, "((");
1329  
      tok.set(j-1, ") == null) ret;");
1330  
      reTok(tok, i, j);
1331  
    }
1332  
    
1333  
    // return optional (return if not null)
1334  
    while ((i = jfind_check optional(tok, "return optional <id> =")) >= 0) {
1335  
      int j = findEndOfStatement(tok, i);
1336  
      S v = tok.get(i+4);
1337  
      clearTokens(tok, i+2, i+4);
1338  
      tok.set(i, "{");
1339  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1340  
      reTok(tok, i, j);
1341  
    }
1342  
    
1343  
    // try object (return if not null)
1344  
    
1345  
    jreplace_dyn(tok, "try object (<id>)", (_tok, cIdx) -> {
1346  
      S type = _tok.get(cIdx+6);
1347  
      ret "try object " + type + " " + makeVar() + " = (" + type + ")";
1348  
    });
1349  
    
1350  
    while ((i = jfind_check object(tok, "try object")) >= 0) {
1351  
      int j = findEndOfStatement(tok, i);
1352  
      clearTokens(tok, i, i+3);
1353  
      bool isDecl = isIdentifier(get(tok, i+4)) && isIdentifier(get(tok, i+6)) && eqGet(tok, i+8, "=");
1354  
      if (isDecl) {
1355  
        S v = get(tok, i+6);
1356  
        tok.set(i, "{");
1357  
        tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1358  
      } else {
1359  
        S v = makeVar();
1360  
        tok.set(i, "{ O " + v + "=");
1361  
        tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1362  
      }
1363  
      reTok(tok, i, j);
1364  
    }
1365  
    
1366  
    // try Int i = ...; (return if not null, shorter version of "try object")
1367  
    /*while ((i = jfind(tok, "try <id> <id> =")) >= 0) {
1368  
      int j = findEndOfStatement(tok, i);
1369  
      S type = tok.get(i+2), v = tok.get(i+4);
1370  
      tok.set(i, "{");
1371  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1372  
      reTok(tok, i, j);
1373  
    }*/
1374  
    while ((i = jfind(tok, "try <id>")) >= 0) {
1375  
      int iType = i+2, iVar = tok_findEndOfType(tok, iType);
1376  
      S v = tok.get(iVar);
1377  
      assertEquals("try object", "=", get(tok, iVar+2));
1378  
      int j = findEndOfStatement(tok, iVar);
1379  
      tok.set(i, "{");
1380  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1381  
      reTok(tok, i, j);
1382  
    }
1383  
    
1384  
    // debug print ...; => if (debug) print(...);
1385  
    while ((i = jfind(tok, "debug print")) >= 0) {
1386  
      int j = findEndOfStatement(tok, i);
1387  
      replaceTokens(tok, i, i+4, "if (debug) print(");
1388  
      tok.set(j-1, ");");
1389  
      reTok(tok, i, j);
1390  
    }
1391  
    
1392  
    functionReferences(tok);
1393  
    tok_expandLPair(tok);
1394  
    tok_expandPairL(tok);
1395  
    tok_expandLT3(tok);
1396  
    tok_quicknew2(tok);
1397  
    
1398  
    // before temp blocks
1399  
    tok_varNamedLikeFunction(tok);
1400  
    
1401  
    tok_onCleanExit(tok);
1402  
    
1403  
    tempBlocks(tok); // after quicknew2 for stuff like "temp new X x;"
1404  
1405  
    // X x = nu(+...)  =>  X x = nu X(+...)
1406  
    jreplace(tok, "<id> <id> = nu(+", "$1 $2 = nu $1(+");
1407  
    // X x = nu(a := ...)  =>  X x = nu X(a := ...)
1408  
    jreplace(tok, "<id> <id> = nu(<id> :=", "$1 $2 = nu $1($6 :=");
1409  
    
1410  
    tok_expandVarCopies(tok); // AFTER the lines just above
1411  
    tok_replaceColonEqualsSyntax(tok); // ditto
1412  
1413  
    tok_unpair(tok);
1414  
    tok_cachedFunctions(tok);
1415  
    tok_simplyCachedFunctions(tok);
1416  
    tok_timedCachedFunctions(tok);
1417  
    
1418  
    tok_optPar(tok);
1419  
    
1420  
    throwFailEtc(tok);
1421  
    tok_typeAA(tok, pairClasses);
1422  
    tok_typeAAA(tok, tripleClasses);
1423  
    tok_typeAO(tok, litset("WithTrail"));
1424  
1425  
    // before star constructors so we can define star constructors in a macro
1426  
    tok_localMacro(tok);
1427  
1428  
    // do this after expanding sclass etc.
1429  
    tok = tok_expandStarConstructors(tok);
1430  
    
1431  
    tok_kiloConstants(tok);
1432  
    //tok_colonMessages(tok);
1433  
    
1434  
    while ((i = jfind(tok, "shit:")) >= 0) {
1435  
      int j = tok_findEndOfStatement(tok, i);
1436  
      tok.set(i+2, "(");
1437  
      tok.set(j-1, ");");
1438  
      reTok(tok, i, j);
1439  
    }
1440  
      
1441  
    jreplace("shit(", "ret with print(");
1442  
    
1443  
    tok_virtualTypes(tok);
1444  
    tok_autoLongConstants(tok);
1445  
    
1446  
    // common misordering of type arguments
1447  
    jreplace("boolean <A>", "<A> boolean");
1448  
    
1449  
    tok_unimplementedMethods(tok);
1450  
    tok_switchableFields(tok);
1451  
    tok_autoDisposeFields(tok);
1452  
    tok_shortVisualize(tok);
1453  
    tok_whileGreaterThan(tok);
1454  
    tok_ifThenEnd(tok);
1455  
    
1456  
    tok_autoInitVars(tok);
1457  
    
1458  
    tok_fixBadTypeParameterOrder(tok);
1459  
    
1460  
    // shortened method declarations BEFORE standardFunctions
1461  
    tok_svoidEtc(tok);
1462  
    jreplace(tok, "void <id> {", "$1 $2() {");
1463  
    jreplace(tok, "void <id> thread {", "$1 $2() thread {");
1464  
    jreplace(tok, "String <id> {", "$1 $2() {");
1465  
    jreplace(tok, "Object <id> {", "$1 $2() {");
1466  
    jreplace(tok, "List <id> {", "$1 $2() {");
1467  
1468  
    namedThreads(tok);
1469  
    threads(tok);
1470  
    
1471  
    //tok_maxEquals(tok);
1472  
    
1473  
    tok_questionDot(tok);
1474  
    
1475  
    jreplace(tok, "if (<id>?!)", "if ($3 != null && $3!)");
1476  
    
1477  
    tok_embeddedFunctions(tok);
1478  
    
1479  
    // quicknew for arrays
1480  
    
1481  
    jreplace("<id>[] <id> = new[", "$1[] $4 = new $1[");
1482  
    jreplace("<id>[] <id> = new {", "$1[] $4 = {");
1483  
    jreplace("<id><<id>>[] <id> = new[", "$1 $2 $3 $4[] $7 = new $1[");
1484  
    
1485  
    jreplace("<id> ifNull =", "if ($1 == null) $1 =");
1486  
    
1487  
    jreplace("class <id> extends <id><.<id>>", "class $2 extends $4<$2.$7>");
1488  
    
1489  
    tok_once(tok); // must come before next line so you can combine them
1490  
    tok_ifRecordMatch(tok);
1491  
    
1492  
    jreplace(tok, "<id> ||=", "$1 = $1 ||");
1493  
    
1494  
    // magicValue followed by a numerical constant
1495  
    jreplace("magicValue", "", (_tok, _i) -> {
1496  
      S t = _get(_tok, _i+3);
1497  
      ret eqOneOf(t, ".", "-") || isInteger(t);
1498  
    });
1499  
    
1500  
    lambdaReferences(tok);
1501  
    
1502  
    tok_returnSelf(tok);
1503  
    
1504  
    // Lua-like print statement
1505  
    jreplace(tok, "print <quoted>", "print($2);");
1506  
    
1507  
    tok_tildeCalls(tok);
1508  
    
1509  
    tok_svoidEtc(tok);
1510  
    tok_swappableFunctions(tok);
1511  
    
1512  
    tok_optParLambda(tok);
1513  
    
1514  
    tok_runnableClasses(tok);
1515  
    
1516  
    tok_swapStatement(tok);
1517  
    
1518  
    //defineMapLikesEtc(tok);
1519  
    
1520  
    tok_defaultArguments_debug = isDef("tok_defaultArguments_debug"); 
1521  
    tok_defaultArguments(tok);
1522  
    
1523  
    tok_akaFunctionNames(tok);
1524  
    
1525  
    tok_persistableClasses(tok);
1526  
    
1527  
    tok_transientClasses(tok);
1528  
    
1529  
    tok_shortMethodReferences(tok);
1530  
    
1531  
    jreplace(tok, "== null ?:", "== null ? null :");
1532  
    jreplace(tok, "?:", "== null ? null :");
1533  
    
1534  
    tok_orCase(tok);
1535  
    
1536  
    tok_beforeMethods(tok);
1537  
    tok_afterMethods(tok);
1538  
    
1539  
    tok_returnAsFunctionName(tok);
1540  
    
1541  
    tok_transpileGetSet(tok);
1542  
    
1543  
    tok_pcallPrefix(tok);
1544  
    
1545  
    tok_numberFunctionNames(tok);
1546  
    
1547  
    tok_castToStatements(tok);
1548  
    
1549  
    tok_optionalFields(tok);
1550  
    
1551  
    tok_getFromMap(tok);
1552  
    
1553  
    jreplace(tok, "for <id> : <id> {", "for (var $2 : $4) {");
1554  
    
1555  
    tok_shortLambdas(tok);
1556  
    
1557  
    if (metaCodeAllowed()) runTransformers(tok, localTransformers);
1558  
    
1559  
    tok_andVarMixIn(tok);
1560  
    
1561  
    tok_stages(tok);
1562  
    
1563  
    tok_beginPeriod(tok);
1564  
    
1565  
    tok_enterStatement(tok);
1566  
    
1567  
    tok_gettableFields(tok);
1568  
    
1569  
    // end of local stuff
1570  
    
1571  
    tok_processMetaBlocks(tok, metaCodeAllowed());
1572  
    if (metaCodeAllowed()) runTransformers(tok, metaTransformers);
1573  
1574  
    same = eq(tok, before);
1575  
    /*if (!same)
1576  
      print("local not same " + safety + " (" + l(tok) + " tokens)");*/
1577  
    if (safety++ >= 10) {
1578  
      printSources(tok);
1579  
      fail("safety 10 error!");
1580  
    }
1581  
  } while (!same);
1582  
  
1583  
  ret tok;
1584  
}
1585  
1586  
static L<S> reTok_include(L<S> tok, int i, int j) {
1587  
  ret reTok_modify(tok, i, j, f localStuff1);
1588  
}
1589  
1590  
static L<S> includeInMainLoaded_reTok(L<S> tok, int i, int j) {
1591  
  ret reTok_include(tok, i, j);
1592  
}
1593  
1594  
static L<S> stdstuff(L<S> tok) {
1595  
  //if (++level >= 10) fail("woot? 10");
1596  
  
1597  
  print("stdstuff!");
1598  
  int i;
1599  
  
1600  
  new L<S> ts;
1601  
  tok_findTranslators(tok, ts);
1602  
  if (nempty(ts))
1603  
    print("DROPPING TRANSLATORS: " + structure(ts));
1604  
1605  
  print('quickmain); tok = quickmain(tok);
1606  
  print('includes); tok = tok_processIncludes(tok);
1607  
  print('conceptsDot); if (processConceptsDot(tok))
1608  
  tok = tok_processIncludes(tok);
1609  
  
1610  
  LS dontImports = tok_processDontImports(tok, definitions);
1611  
  for (S s : dontImports)
1612  
    doNotIncludeFunction.remove(afterLastDot(s));
1613  
  
1614  
  //print('starConstructors); tok = tok_expandStarConstructors(tok);
1615  
    
1616  
  // drop Java 8 annotations since we're compiling for Java 7
1617  
  jreplace(tok, "@Nullable", "");
1618  
1619  
  // STANDARD CLASSES & INTERFACES
1620  
  
1621  
  print("standard classes");
1622  
  haveClasses = addStandardClasses_v2(tok);
1623  
  
1624  
  tok_quickInstanceOf(tok, haveClasses);
1625  
1626  
  // concept-related stuff
1627  
  
1628  
  // auto-import concepts
1629  
  /*bool _a = tok_hasClassRef2(tok, "Concept") || tok_hasClassRef2(tok, "Concepts"), _b = !haveClasses.contains("Concept");
1630  
  //print("auto-import: " + _a + ", " + _b);
1631  
  if (_a && _b) {
1632  
    print("Auto-including concepts.");
1633  
    if (shouldNotIncludeClass.contains("Concepts")) {
1634  
      print(join(tok));
1635  
      fail("Unwanted concepts import");
1636  
    }
1637  
    printStruct(haveClasses);
1638  
    tok = includeInMainLoaded(tok, "concepts.");
1639  
    reTok(tok, l(tok)-1, l(tok));
1640  
    //processConceptsDot(tok);
1641  
  }*/
1642  
  
1643  
  ret tok;
1644  
} // end of stdStuff!
1645  
1646  
static L<S> multilineStrings(L<S> tok) {
1647  
  for (int i = 1; i < tok.size(); i += 2) {
1648  
    S t = tok.get(i);
1649  
    if (isQuoted(t))
1650  
      if (t.startsWith("[") || t.contains("\r") || t.contains("\n"))
1651  
        tok.set(i, quote(unquote(t)));
1652  
  }
1653  
  ret tok;
1654  
}
1655  
1656  
static L<S> quickmain(L<S> tok) {
1657  
  if (quickmainDone1 && quickmainDone2) ret tok;
1658  
1659  
  int i = findCodeTokens(tok, "main", "{");
1660  
  if (i < 0) i = findCodeTokens(tok, "m", "{");
1661  
  if (i >= 0 && !(i-2 > 0 && tok.get(i-2).equals("class"))) {
1662  
    tokSet_reTok(tok, i, (definitions.contains("mainClassPublic") ? "public " : "") + "class main");
1663  
    quickmainDone1 = true;
1664  
  }
1665  
    
1666  
  i = findCodeTokens(tok, "psvm", "{");
1667  
  if (i < 0) i = findCodeTokens(tok, "p", "{");
1668  
  if (i >= 0) {
1669  
    int idx = i+2;
1670  
    int j = findEndOfBracketPart(tok, idx)-1;
1671  
    L<S> contents = subList(tok, idx+1, j);
1672  
    //print("contents: " + sfu(contents));
1673  
    tok.set(i, "public static void main(final String[] args) throws Exception");
1674  
    replaceTokens(tok, idx+1, j, tok_addSemicolon(contents));
1675  
    reTok(tok, i, j);
1676  
    quickmainDone2 = true;
1677  
  }
1678  
    
1679  
  ret tok;
1680  
}
1681  
1682  
sS makeVar(S name) {
1683  
  AtomicInteger counter = varCountByThread!;
1684  
  if (counter == null)
1685  
    varCountByThread.set(counter = new AtomicInteger);
1686  
  ret "_" + name + "_" + getAndInc(counter);
1687  
}
1688  
1689  
static S makeVar() { ret makeVar(""); }
1690  
1691  
static L<S> rtq(L<S> tok, S id) {
1692  
  ret runTranslatorQuick(tok, id);
1693  
}
1694  
1695  
static L<S> expandShortTypes(L<S> tok) {
1696  
  // replace <int> with <Integer>
1697  
  for (int i = 1; i+4 < tok.size(); i += 2)
1698  
    if (tok.get(i).equals("<")
1699  
      && litlist(">", ",").contains(tok.get(i+4))) {
1700  
      String type = tok.get(i+2);
1701  
      if (type.equals("int")) type = "Integer";
1702  
      else if (type.equals("long")) type = "Long";
1703  
      tok.set(i+2, type);
1704  
    }
1705  
    
1706  
  jreplace(tok, "O", "Object");
1707  
  jreplace(tok, "S", "String");
1708  
  jreplace(tok, "L", "List");
1709  
  jreplace(tok, "Cl", "Collection");
1710  
  
1711  
  // bool -> boolean if it's not a function name
1712  
  jreplace(tok, "bool", "boolean", tokCondition {
1713  
    ret neqGetOneOf(tok, i+3, "(", null);
1714  
  });
1715  
  
1716  
  jreplace(tok, "AtomicBool", "AtomicBoolean");
1717  
  jreplace(tok, "AtomicInt", "AtomicInteger");
1718  
1719  
  jreplace(tok, "LL< <id> >", "L<L<$3>>");
1720  
  jreplace(tok, "LL< <id><<id>> >", "L<L<$3<$5>>>");
1721  
  jreplace(tok, "LL<?>", "L<L<?>>");
1722  
  jreplace(tok, "LL", "L<L>");
1723  
  jreplace(tok, "LPt", "L<Pt>");
1724  
  
1725  
  jreplace(tok, "Clusters< <id> >", "Map<$3, Collection<$3>>");
1726  
  
1727  
  ret tok;
1728  
}
1729  
1730  
static L<S> autoImports(L<S> tok) {
1731  
  HashSet<S> imports = new HashSet(tok_findImports(tok));
1732  
  new StringBuilder buf;
1733  
  for (S c : standardImports())
1734  
    if (!(imports.contains(c)))
1735  
      buf.append("import " + c + ";\n");
1736  
  if (buf.length() == 0) ret tok;
1737  
  tok.set(0, buf+tok.get(0));
1738  
  ret reTok(tok, 0, 1);
1739  
}
1740  
1741  
static L<S> tok_processIncludes(L<S> tok) {
1742  
  int safety = 0;
1743  
  while (hasCodeTokens(tok, "!", "include") && ++safety < 100)
1744  
    tok = tok_processIncludesSingle(tok);
1745  
  
1746  
  //tok_autoCloseBrackets(tok);
1747  
  ret tok;
1748  
}
1749  
1750  
svoid tok_processEarlyIncludes(L<S> tok) {
1751  
  int i;
1752  
  while ((i = jfind_check include(tok, "!include early #<int>")) >= 0) {
1753  
    S id = tok.get(i+8);
1754  
    included.add(parseLong(id));
1755  
    replaceTokens_reTok(tok, i, i+10, "\n" + cacheGet(id) + "\n");
1756  
  }
1757  
}
1758  
1759  
static L<S> tok_processIncludesSingle(L<S> tok) {
1760  
  int i;
1761  
  while ((i = jfind_check include(tok, "!include #<int>")) >= 0) {
1762  
    S id = tok.get(i+6);
1763  
    included.add(parseLong(id));
1764  
    replaceTokens(tok, i, i+8, "\n" + cacheGet(id) + "\n");
1765  
    reTok_include(tok, i, i+8);
1766  
  }
1767  
  while ((i = jfind_check include(tok, "!include once #<int>")) >= 0) {
1768  
    S id = tok.get(i+8);
1769  
    bool isNew = included.add(parseLong(id));
1770  
    replaceTokens(tok, i, i+10, 
1771  
      isNew ? "\n" + cacheGet(id) + "\n" : "");
1772  
    reTok_include(tok, i, i+10);
1773  
  }
1774  
  ret tok;
1775  
}
1776  
1777  
// ctex and various other error-related keyword blocks
1778  
static void ctex(L<S> tok) {
1779  
  replaceKeywordBlock(tok, "ctex",
1780  
    "{ try {",
1781  
    "} catch (Exception __e) { throw rethrow(__e); } }");
1782  
  for (S keyword : ll("null on exception", "null on error"))
1783  
    replaceKeywordBlock(tok, keyword,
1784  
      "{ try {",
1785  
      "} catch (Throwable __e) { return null; } }");
1786  
  replaceKeywordBlock(tok, "false on exception",
1787  
    "{ try {",
1788  
    "} catch (Throwable __e) { return false; } }");
1789  
  replaceKeywordBlock(tok, "try-OrError",
1790  
    "{ try {",
1791  
    "} catch (Throwable __e) { return OrError.error(__e); } }");
1792  
}
1793  
  
1794  
static L<S> dialogHandler(L<S> tok) {
1795  
  ret replaceKeywordBlock(tok,
1796  
    "dialogHandler",
1797  
    "new DialogHandler() {\n" +
1798  
      "public void run(final DialogIO io) {",
1799  
    "}}");
1800  
}
1801  
1802  
static L<S> extendClasses(L<S> tok) {
1803  
  int i;
1804  
  while ((i = jfind(tok, "extend <id> {")) >= 0) {
1805  
    S className = tok.get(i+2);
1806  
    int idx = findCodeTokens(tok, i, false, "{");
1807  
    int j = findEndOfBracketPart(tok, idx+2);
1808  
    S content = joinSubList(tok, idx+1, j-1);
1809  
    L<S> c = findInnerClassOfMain(tok, className);
1810  
    print("Extending class " + className);
1811  
    clearTokens(subList(tok, i, j+1));
1812  
    if (c == null) {
1813  
      print("Warning: Can't extend class " + className + ", not found");
1814  
      continue;
1815  
    }
1816  
    int startOfClass = indexOfSubList(tok, c);
1817  
    int endOfClass = startOfClass + l(c)-1;
1818  
    //print("Extending class " + className + " ==> " + join(subList(tok, startOfClass, endOfClass)));
1819  
    while (neq(tok.get(endOfClass), "}")) --endOfClass;
1820  
    //print("Extending class " + className + " ==> " + join(subList(tok, startOfClass, endOfClass)));
1821  
    tok.set(endOfClass, content + "\n" + tok.get(endOfClass));
1822  
    
1823  
    doubleReTok(tok, i, j+1, endOfClass, endOfClass+1);
1824  
  }
1825  
  ret tok;
1826  
}
1827  
1828  
// for ping / while ping
1829  
static void forPing(L<S> tok) {
1830  
  int i;
1831  
  for (S keyword : ll("for", "fOr", "while"))
1832  
    while ((i = jfind(tok, keyword + " ping (")) >= 0) {
1833  
      int bracketEnd = findEndOfBracketPart(tok, i+4)-1;
1834  
      int iStatement = bracketEnd+2;
1835  
      int iEnd = findEndOfStatement(tok, iStatement);
1836  
      tok.set(i+2, "");
1837  
      
1838  
      // turn into block
1839  
      if (!eq(get(tok, iStatement), "{")) {
1840  
        tok.set(iStatement, "{ " + tok.get(iStatement));
1841  
        tok.set(iEnd-1, tok.get(iEnd-1) + " }");
1842  
      }
1843  
        
1844  
      // add ping
1845  
      tok.set(iStatement, "{ ping(); " + dropPrefixTrim("{", tok.get(iStatement)));
1846  
      reTok(tok, i+2, iEnd);
1847  
    }
1848  
}
1849  
1850  
// lib 123 => !123
1851  
static void libs(L<S> tok) {
1852  
  int i;
1853  
  while ((i = jfind(tok, "lib <int>")) >= 0) {
1854  
    S id = tok.get(i+2);
1855  
    print("lib " + id);
1856  
    if (!libs.contains(id)) {
1857  
      libs.add(id);
1858  
      clearAllTokens(tok, i, i+3);
1859  
      /*tok.set(i, "!");
1860  
      tok.set(i+1, "");*/
1861  
    } else {
1862  
      print("...ignoring (duplicate)");
1863  
      clearAllTokens(tok, i, i+3);
1864  
      reTok(tok, i, i+3);
1865  
    }
1866  
  }
1867  
  print("libs found: " + libs);
1868  
}
1869  
1870  
// sourceCodeLine() => 1234
1871  
static void sourceCodeLine(L<S> tok) {
1872  
  int i ;
1873  
  while ((i = jfind(tok, "sourceCodeLine()")) >= 0) {
1874  
    replaceTokens(tok, i, i+5, str(countChar(joinSubList(tok, 0, i), '\n')+1));
1875  
    reTok(tok, i, i+5);
1876  
  }
1877  
}
1878  
1879  
// done before any other processing
1880  
svoid earlyStuff(LS tok) {
1881  
  int i;
1882  
  
1883  
  tok_processEarlyIncludes(tok);
1884  
      
1885  
  tok_scopes(tok, autoCloseScopes := asInclude);
1886  
  tok_autosemi(tok);
1887  
  tok_autoCloseBrackets(tok);
1888  
  jreplace(tok, "°", "()");
1889  
  
1890  
  // Note: this makes the word "quine" a special operator
1891  
  // (unusable as a function name)
1892  
  
1893  
  while ((i = jfind(tok, "quine(")) >= 0) {
1894  
    int idx = findCodeTokens(tok, i, false, "(");
1895  
    int j = findEndOfBracketPart(tok, idx+2);
1896  
    tok.set(i, "new Quine");
1897  
    tok.set(idx, "(" + quote(joinSubList(tok, idx+1, j-1)) + ", ");
1898  
    reTok(tok, i, idx+1);
1899  
  }
1900  
  
1901  
  jreplace_check after(tok, "void <id> after super {", "void $2 { super.$2();");
1902  
  
1903  
  replaceKeywordBlock(tok, "r-enter", "r { enter {", "}}");
1904  
    
1905  
  // do this before func & voidfunc because otherwise they swallow it
1906  
  jreplace(tok, "enter {", "{ temp enter();");
1907  
  
1908  
  tok_mutatorMethods(tok);
1909  
  
1910  
  // func keyword for lambdas - now automatically quines toString() if enabled
1911  
  
1912  
  replaceKeywordBlock(tok,
1913  
    "null",
1914  
    "{",
1915  
    "null; }");
1916  
    
1917  
  // do func & voidfunc early to preserve original code as toString
1918  
  
1919  
  while ((i = jfind(tok, "func(")) >= 0) {
1920  
    int argsFrom = i+4, argsTo = findCodeTokens(tok, i, false, ")");
1921  
    int idx = findCodeTokens(tok, argsTo, false, "{");
1922  
    int j = findEndOfBracketPart(tok, idx);
1923  
    L<S> contents = subList(tok, idx+1, j-1);
1924  
    
1925  
    S returnType = "O";
1926  
    if (eq(tok.get(argsTo+2), "-") && eq(tok.get(argsTo+4), ">"))
1927  
      returnType = tok_toNonPrimitiveTypes(joinSubList(tok, argsTo+6, idx-1));
1928  
      
1929  
    S toString = autoQuine ? "  public S toString() { ret " + quote(shorten(defaultMaxQuineLength(), trimJoin(contents))) + "; }" : "";
1930  
    
1931  
    L<S> args = cloneSubList(tok, argsFrom-1, argsTo);
1932  
    tok_shortFinals(args);
1933  
    tok_toNonPrimitiveTypes(args);
1934  
    
1935  
    L<S> types = tok_typesOfParams(args);
1936  
    O type = "O";
1937  
    if (l(types) <= 3)
1938  
      type = "F" + l(types) + "<" + joinWithComma(types) + ", " + returnType + ">";
1939  
    S body = tok_addReturn(contents);
1940  
    
1941  
    replaceTokens_reTok(tok, i, j,
1942  
      "new " + type + "() { public "
1943  
        + returnType + " get(" + trimJoin(args) + ") ctex { "
1944  
          + body
1945  
        + " }\n" +
1946  
       + toString + "}");
1947  
  }
1948  
  
1949  
  while ((i = jfind(tok, "voidfunc(")) >= 0) {
1950  
    int argsFrom = i+4, argsTo = findCodeTokens(tok, i, false, ")");
1951  
    int idx = findCodeTokens(tok, argsTo, false, "{");
1952  
    int j = findEndOfBracketPart(tok, idx);
1953  
    L<S> contents = subList(tok, idx+1, j-1);
1954  
    
1955  
    if (jcontains(subList(tok, argsTo+1, idx), "->"))
1956  
      fail("voidfunc with return type: " + joinSubList(tok, i, j+1));
1957  
    
1958  
    L<S> args = cloneSubList(tok, argsFrom-1, argsTo);
1959  
    tok_shortFinals(args);
1960  
    tok_toNonPrimitiveTypes(args);
1961  
    
1962  
    L<S> types = tok_typesOfParams(args);
1963  
    O type = "O";
1964  
    if (l(types) <= 4)
1965  
      type = "VF" + l(types) + "<" + joinWithComma(types) + ">";
1966  
1967  
    replaceTokens(tok, i, j, "new " + type + "() { public void get(" + trimJoin(args) + ") ctex { " + tok_addSemicolon(contents) + " }\n" +
1968  
    (autoQuine ? "  public S toString() { ret " + quote(shorten(defaultMaxQuineLength(), trim(join(contents)))) + "; }" : "") + "}");
1969  
    reTok(tok, i, j);
1970  
  }
1971  
  
1972  
  jreplace(tok, "func {", "func -> O {");
1973  
  jreplace(tok, "f {", "f -> O {");
1974  
  
1975  
  // swing -> S { ... } => swing(func -> S { ... })
1976  
  while ((i = jfind(tok, "swing ->")) >= 0) {
1977  
    int bracket = findCodeTokens(tok, i, false, "{");
1978  
    int j = findEndOfBracketPart(tok, bracket);
1979  
    tok.set(i, "swing(func");
1980  
    tok.set(j-1, "})");
1981  
    reTok(tok, i, j);
1982  
  }
1983  
  
1984  
  tok_qFunctions(tok);
1985  
  
1986  
  jreplace(tok, "func fullToString {", "func -> O fullToString {");
1987  
  
1988  
  for (S keyword : ll(/*"f",*/ "func")) {
1989  
    while ((i = jfind(tok, keyword + " ->", tokcondition {
1990  
      ret isIdentifier(_get(tok, i+7)); // avoid lambda declaration like: f -> { ... }
1991  
    })) >= 0) {
1992  
      // I think there is a bug here for something like func -> x { new x { } }
1993  
      int idx = findCodeTokens(tok, i, false, "{");
1994  
      int j = findEndOfBracketPart(tok, idx);
1995  
      S returnType = tok_toNonPrimitiveTypes(joinSubList(tok, i+6, idx-1));
1996  
      int quineLength = defaultMaxQuineLength();
1997  
      if (eq(lastJavaToken(returnType), "fullToString")) {
1998  
        quineLength = Int.MAX_VALUE;
1999  
        returnType = dropLastJavaTokenAndSpacing(returnType);
2000  
      }
2001  
      L<S> contents = subList(tok, idx+1, j-1);
2002  
      replaceTokens(tok, i, j, "new F0<" + returnType + ">() { public " + returnType + " get() ctex { " + tok_addReturn(contents) + " }\n" +
2003  
        (autoQuine ? "  public S toString() { ret " + quote(shorten(quineLength, trimJoin(contents))) + "; }" : "") + "}");
2004  
      reTok(tok, i, j);
2005  
    }
2006  
  }
2007  
    
2008  
  while ((i = jfind(tok, "time repeat * {")) >= 0) {
2009  
    int j = findEndOfBlock(tok, i+6)-1;
2010  
    tok.set(i, "time {");
2011  
    tok.set(j, "}}");
2012  
    reTok(tok, i, j+1);
2013  
  }
2014  
2015  
  // do this before "m {" stuff because "repeat m" [doesn't seem to work yet though)
2016  
  while ((i = findCodeTokens(tok, "repeat", "*", "{")) >= 0) {
2017  
    S v = makeVar("repeat");
2018  
    tok.set(i, "for (int " + v + " = 0; " + v + " < " + tok.get(i+2) + "; " + v + "++)");
2019  
    tok.set(i+2, "");
2020  
    reTok(tok, i, i+3);
2021  
  }
2022  
}
2023  
2024  
static void throwFailEtc(L<S> tok) {
2025  
  bool anyChange = false;
2026  
  for (int i = 1; i+4 < l(tok); i += 2)
2027  
    if (eqOneOf(get(tok, i+2), "fail", "todo")
2028  
      && eq(get(tok, i+4), "(")
2029  
      && !eqOneOf(get(tok, i), "throw", "RuntimeException", "return", "f", "function", ".", "void", "main", "Throwable")) {
2030  
      tok.set(i+2, "throw " + tok.get(i+2));
2031  
      anyChange = true;
2032  
    }
2033  
  if (anyChange)
2034  
    reTok(tok);
2035  
}
2036  
2037  
static void namedThreads(L<S> tok) {
2038  
  for (int i = 0; i < 100; i++) {
2039  
    int idx = findCodeTokens(tok, "thread", "<quoted>", "{");
2040  
    if (idx < 0) idx = findCodeTokens(tok, "thread", "<id>", "{");
2041  
    if (idx < 0)
2042  
      break;
2043  
    int j = findEndOfBracketPart(tok, idx+4);
2044  
    S tName = tok.get(idx+2);
2045  
    
2046  
    S pre = "startThread(" + tName + ", r { ";
2047  
    S post = "})";
2048  
    if (!tok_tokenLeftOfExpression(tok, idx-2)) post += ";";
2049  
2050  
    tok.set(idx, pre);
2051  
    tok.set(idx+2, "");
2052  
    tok.set(idx+4, "");
2053  
    tok.set(j-1, post);
2054  
    //print(join(subList(tok, idx, j)));
2055  
    reTok(tok, idx, j);
2056  
  }
2057  
}
2058  
2059  
static void rNamedThread(L<S> tok) {
2060  
  for (int i = 0; i < 100; i++) {
2061  
    int idx = findCodeTokens(tok, "r", "-", "thread", "<quoted>", "{");
2062  
    if (idx < 0) idx = findCodeTokens(tok, "r", "-", "thread", "<id>", "{");
2063  
    if (idx < 0)
2064  
      break;
2065  
    int j = findEndOfBracketPart(tok, idx+8);
2066  
    S tName = tok.get(idx+6);
2067  
    
2068  
    S pre = "r { thread " + tName + " {";
2069  
    S post = "}}";
2070  
2071  
    replaceTokens(tok, idx, idx+9, pre);
2072  
    tok.set(j-1, post);
2073  
    reTok(tok, idx, j);
2074  
  }
2075  
}
2076  
2077  
static void threads(L<S> tok) {
2078  
  replaceKeywordBlock(tok, "daemon", "startDaemonThread(r {", "});");
2079  
  //replaceKeywordBlock(tok, "thread", "startThread(r {", "});");
2080  
  
2081  
  // now enclose in { } to allow using like "void bla() thread { ... }" - if it's not used as an expression
2082  
  
2083  
  replaceKeywordBlock_dyn2_legacy(tok, "thread", new O { // don't use func here, it can't be transpiled
2084  
    S[] get (LS tok, int iOpening, int iClosing) {
2085  
      // is the thread clause used as an expression?
2086  
      bool isExpression = tok_tokenLeftOfExpression(tok, iOpening-4);
2087  
      ret new S[] {
2088  
        (isExpression ? "" : "{ ") + "startThread(r {",
2089  
        "})" +
2090  
        (isExpression ? "" : "; }")
2091  
      };
2092  
    }
2093  
  });
2094  
}
2095  
2096  
static SS sf; // standard standard functions (haha)
2097  
static Bool _761ok;
2098  
2099  
static LS standardFunctions(LS tok) {
2100  
  if (sf == null) {
2101  
    S _761 = cacheGet("#761");
2102  
    if (_761ok == null)
2103  
      _761ok = isBracketHygienic(_761);
2104  
    assertTrue("Whoa! #761 truncated?", _761ok);
2105  
    L<S> standardFunctions = concatLists(
2106  
      (L) loadVariableDefinition(_761, "standardFunctions"),
2107  
      (L) loadVariableDefinition(cacheGet("#1006654"), "standardFunctions"));
2108  
2109  
    sf = new HashMap;
2110  
    for (S x : standardFunctions) {
2111  
      S[] f = x.split("/");
2112  
      sf.put(f[1], f[0]);
2113  
    }
2114  
  }
2115  
  
2116  
  SS sfMap = combinedMap(extraStandardFunctions, sf);
2117  
    
2118  
  for (int i = 0; ; i++) {
2119  
    print("Looking for required functions");
2120  
    Set<S> defd = new HashSet(findFunctions(tok));
2121  
    
2122  
    int j;
2123  
    while ((j = jfind(tok, "should not include function *.")) >= 0) {
2124  
      S fname = tok.get(j+8);
2125  
      shouldNotIncludeFunction.add(fname);
2126  
      clearAllTokens(subList(tok, j, j+12));
2127  
    }
2128  
2129  
    while ((j = jfind(tok, "do not include function *.")) >= 0) {
2130  
      S fname = tok.get(j+8);
2131  
      doNotIncludeFunction.add(fname);
2132  
      clearAllTokens(subList(tok, j, j+12));
2133  
    }
2134  
    
2135  
    while ((j = jfind(tok, "need latest <id>.")) >= 0) {
2136  
      S t = tok.get(j+4);
2137  
      needLatest.add(t);
2138  
      doNotIncludeClass.remove(t);
2139  
      clearAllTokens(subList(tok, j, j+8));
2140  
    }
2141  
    
2142  
    grabImportedStaticFunctions(tok);
2143  
    doNotIncludeFunction.removeAll(needLatest);
2144  
    
2145  
    // changes tok
2146  
    Set<String> invocations = findFunctionInvocations(tok, sfMap, hardFunctionReferences, defd, true, mainClassName());
2147  
    /*if (invocations.contains("str"))
2148  
      print("==STR==" + join(tok) + "==STR==");*/
2149  
    if (!cic(definitions, "leanMode"))
2150  
      invocations.addAll(functionsToAlwaysInclude);
2151  
2152  
    //print("Functions invoked: " + structure(invocations));
2153  
    List<String> needed = diff(invocations, defd);
2154  
    for (S f : doNotIncludeFunction) needed.remove(f);
2155  
    if (needed.isEmpty())
2156  
      break;
2157  
    print("Adding functions: " + join(" " , needed));
2158  
    
2159  
    HashSet neededSet = new HashSet(needed);
2160  
    Collection<S> bad = setIntersection(neededSet, shouldNotIncludeFunction);
2161  
    if (nempty(bad)) {
2162  
      S msg = "INCLUDING BAD FUNCTIONS: " + sfu(bad);
2163  
      print(msg);
2164  
      print(join(tok));
2165  
      fail(msg);
2166  
    }
2167  
      
2168  
    new L<S> added;
2169  
    new L<Future<S>> parts;
2170  
    new L<S> preload;
2171  
    
2172  
    for (S x : needed)
2173  
      if (sfMap.containsKey(x))
2174  
        preload.add(sfMap.get(x));
2175  
    print("Preloading: " + preload);
2176  
    cachePreload(preload);
2177  
    
2178  
    for (String x : cloneList(needed)) {
2179  
      if (defd.contains(x)) continue;
2180  
      
2181  
      String id = sfMap.get(x);
2182  
      if (id == null) {
2183  
        print("Standard function " + x + " not found.");
2184  
        needed.remove(x);
2185  
        continue;
2186  
      }
2187  
      //print("Adding function: " + x + " (" + id + ")");
2188  
       
2189  
      S function = cacheGet(id) + "\n";
2190  
      //if (("\n" + function).contains("\n!")) print("Warning: " + id + " contains translators.");
2191  
      
2192  
      if (cacheStdFunctions) {
2193  
        long _id = psI(id);
2194  
        CachedInclude ci = cachedIncludes.get(_id);
2195  
        if (ci == null) {
2196  
          cachedIncludes.put(_id, ci = new CachedInclude(_id));
2197  
          //println("Caching include " + _id + ", l=" + l(cachedIncludes));
2198  
        }
2199  
        function += "\n";
2200  
        fS _function = function;
2201  
        if (neq(ci.javax, function)) {
2202  
          print("Compiling function: " + x);
2203  
          ci.javax = function;
2204  
          ci.java = executor.submit(new Callable<S>() {
2205  
            public S call() {
2206  
              // We assume that variables made with makeVar() will always be local to some block
2207  
              varCountByThread.set(null);
2208  
              ret join(localStuff1(jtok(_function)));
2209  
            }
2210  
          });
2211  
          ci.realJava = null;
2212  
        }
2213  
        parts.add(ci.javaFuture());
2214  
      } else
2215  
        parts.add(nowFuture(function));
2216  
        
2217  
      added.add(x);
2218  
      Collection<S> newFunctions = new HashSet(findFunctionDefs(javaTok(function)));
2219  
      defd.addAll(newFunctions);
2220  
      for (S f : newFunctions)
2221  
        if (!addedFunctions.add(f)) {
2222  
          printSources(tok);
2223  
          fail("Trying to add function " + f + " again - main class syntax broken!");
2224  
        }
2225  
    }
2226  
    
2227  
    print("Getting " + nParts(parts));
2228  
    S text = lines(getAllFutures(parts));
2229  
    print("Including " + nParts(parts));
2230  
    tok = includeInMainLoaded(tok, text);
2231  
      
2232  
    // defd = new HashSet(findFunctions(tok));
2233  
    //print("Functions added: " + joinWithSpace(added));
2234  
    
2235  
    for (String x : needed)
2236  
      if (!defd.contains(x)) {
2237  
        print(join(tok));
2238  
        fail("Function not defined properly: " + x);
2239  
      }
2240  
    //print("Iteration " + (i+2));
2241  
    
2242  
    print("Processing definitions");
2243  
    
2244  
    dontPrint('definitions); tok_definitions(tok);
2245  
    dontPrint('ifndef); tok_ifndef(tok);
2246  
    dontPrint('ifdef); tok_ifdef(tok);
2247  
    
2248  
    if (i >= 1000) fail("Too many iterations");
2249  
  }
2250  
  
2251  
  ret tok;
2252  
}
2253  
2254  
// TODO: skip functions defined in inner classes!
2255  
static LS findFunctions(L<S> tok) {
2256  
  //ret findFunctionDefinitions(join(findMainClass(tok)));
2257  
  ret findFunctionDefs(findMainClass(tok));
2258  
}
2259  
2260  
static S cacheGet(S snippetID) {
2261  
  snippetID = formatSnippetID(snippetID);
2262  
  S text = snippetCache.get(snippetID);
2263  
  if (text == null) {
2264  
    text = loadSnippet(snippetID);
2265  
    // very early processing/checks for includes
2266  
    
2267  
    if (hasUnclosedStringLiterals(text))
2268  
      fail("Unclosed string literals in " + snippetID);
2269  
      
2270  
    if (regexpContains("\\bscope\\b", text)) {
2271  
      LS tok = javaTok(text);
2272  
      tok_scopes(tok, autoCloseScopes := true);
2273  
      text = join(tok);
2274  
    }
2275  
    
2276  
    snippetCache.put(snippetID, text);
2277  
  }
2278  
  ret text;
2279  
}
2280  
2281  
static void cachePreload(Collection<S> ids) {
2282  
  new L<S> needed;
2283  
  for (S id : ids)
2284  
    if (!snippetCache.containsKey(formatSnippetID(id)))
2285  
      needed.add(formatSnippetID(id));
2286  
  if (l(needed) > 1) {
2287  
    L<S> texts = loadSnippets(needed);
2288  
    for (int i = 0; i < l(needed); i++)
2289  
      if (texts.get(i) != null)
2290  
        snippetCache.put(needed.get(i), texts.get(i));
2291  
  }
2292  
}
2293  
2294  
static L<S> jtok(L<S> tok) {
2295  
  ret jtok(join(tok));
2296  
}
2297  
2298  
static L<S> jtok(S s) {
2299  
  ret indexTokenList(javaTok(s));
2300  
}
2301  
2302  
static HashSet<S> haveClasses_actual(L<S> tok) {
2303  
  new HashSet<S> have;
2304  
  for (L<S> c : innerClassesOfMain(tok))
2305  
    have.add(getClassDeclarationName(c));
2306  
  ret have;
2307  
}
2308  
2309  
static HashSet<S> haveClasses_addImported(LS tok, HashSet<S> have, bool mainLevel default true) {
2310  
  have.addAll(tok_importedClassNames(tok, mainLevel ? lambda2 onImportFound : null));
2311  
  have.addAll(usualJavaClassNames()); // for S => S.class
2312  
  ret have;
2313  
}
2314  
2315  
// works on Java level (no "sclass" etc)
2316  
// returns list of classes we have (useful for other processing)
2317  
static HashSet<S> addStandardClasses_v2(L<S> tok) {
2318  
  if (lclasses == null) {
2319  
    S sc = cacheGet(#1003674);
2320  
    lclasses = new L;
2321  
    for (S line : tlft_j(sc)) {
2322  
      int idx = line.indexOf('/');
2323  
      lclasses.addAll(ll(line.substring(0, idx), line.substring(idx+1)));
2324  
    }
2325  
  }
2326  
  L<S> definitions = lclasses;
2327  
2328  
  for (int safety = 0; safety < 10; safety++) {
2329  
    HashSet<S> have = haveClasses_actual(tok);
2330  
    haveClasses_addImported(tok, have);
2331  
    have.addAll(keys(rewrites));
2332  
2333  
    int j;
2334  
    while ((j = jfind(tok, "should not include class *.")) >= 0) {
2335  
      S cname = tok.get(j+8);
2336  
      shouldNotIncludeClass.add(cname);
2337  
      clearAllTokens(subList(tok, j, j+12));
2338  
    }
2339  
    
2340  
    while ((j = jfind(tok, "do not include class *.")) >= 0) {
2341  
      S name = tok.get(j+8);
2342  
      if (!needLatest.contains(name)) doNotIncludeClass.add(name);
2343  
      clearAllTokens(subList(tok, j, j+12));
2344  
    }
2345  
    
2346  
    new SS need;
2347  
    new Set<S> snippets;
2348  
    Set<S> idx = tokenIndexWithoutIfclass_forStdClasses(tok);
2349  
    
2350  
    while ((j = jfind(tok, "please include class *.")) >= 0) {
2351  
      S cname = tok.get(j+6);
2352  
      idx.add(cname);
2353  
      clearAllTokens(subList(tok, j, j+10));
2354  
    }
2355  
2356  
    for (int i = 0; i+1 < l(definitions); i += 2) {
2357  
      S className = definitions.get(i);
2358  
      S snippetID = fsI(definitions.get(i+1));
2359  
      if (idx.contains(className) && !have.contains(className) && snippets.add(snippetID))
2360  
        need.put(className, snippetID);
2361  
    }
2362  
    if (hasDef("SymbolAsString")) {
2363  
      print("Have SymbolAsString.");
2364  
      if (need.containsKey("Symbol")) {
2365  
        print("Have Symbol.");
2366  
        need.remove("Symbol");
2367  
      }
2368  
    } else
2369  
      print("No SymbolAsString.");
2370  
      
2371  
    removeAll(need, doNotIncludeClass);
2372  
    if (empty(need)) ret have;
2373  
  
2374  
    for (S className : keys(need))
2375  
      if (shouldNotIncludeClass.contains(className)) {
2376  
        S msg = "INCLUDING BAD CLASS: " + className;
2377  
        print(msg);
2378  
        print(join(tok));
2379  
        fail(msg);
2380  
      }
2381  
      
2382  
    cachePreload(values(need));
2383  
    
2384  
    new LPair<S, CachedInclude> parts; // class name, Java code
2385  
    
2386  
    print("Adding classes: " + joinWithSpace(keys(need)));
2387  
    for (S className : keys(need)) {
2388  
      if (have.contains(className)) continue; // intermittent add
2389  
      S snippetID = need.get(className);
2390  
      //print("Adding class " + className + " / " + snippetID);
2391  
      snippetID = fsI(snippetID);
2392  
      S text = cacheGet(snippetID) + "\n";
2393  
      
2394  
      assertTrue(cacheStdClasses);
2395  
      long _id = psI(snippetID);
2396  
      CachedInclude ci = cachedIncludes.get(_id);
2397  
      if (ci == null) cachedIncludes.put(_id, ci = new CachedInclude(_id));
2398  
      if (neq(ci.javax, text)) {
2399  
        print("Compiling class: " + className);
2400  
        ci.javax = text;
2401  
        ci.java = executor.submit(new Callable<S>() {
2402  
          public S call() {
2403  
            // We assume that variables made with makeVar() will always be local to some block
2404  
            varCountByThread.set(null);
2405  
            ret join(localStuff1(jtok(text)));
2406  
          }
2407  
        });
2408  
        ci.realJava = null;
2409  
      }
2410  
      parts.add(pair(className, ci));
2411  
    }
2412  
    
2413  
    new StringBuilder buf;
2414  
    for (Pair<S, CachedInclude> p : parts) {
2415  
      S className = p.a;
2416  
      LS ct = javaTok(p.b.java());
2417  
      new SS rewritten;
2418  
      tok_findAndClearRewrites(ct, rewritten);
2419  
      if (rewritten.containsKey(className))
2420  
        have.add(className);
2421  
      for (LS c : allClasses(ct)) {
2422  
        S name = getClassDeclarationName(c);
2423  
        have.add(name);
2424  
      }
2425  
      
2426  
      haveClasses_addImported(ct, have, false);
2427  
      
2428  
      if (!have.contains(className))
2429  
        fail("Wrongly defined class: " + className + " / " + p.b.snippetID + "\n\n" + p.b.java());
2430  
      if (!addedClasses.add(className)) {
2431  
        printSources(tok);
2432  
        fail("Trying to add class " + className + " again - main class syntax broken!");
2433  
      }
2434  
      buf.append(p.b.java());
2435  
    } // for part
2436  
    
2437  
    tok = includeInMainLoaded(tok, str(buf));
2438  
  }
2439  
  fail("safety 10");
2440  
}
2441  
2442  
static Set<S> expandableClassNames = lithashset("BigInteger");
2443  
2444  
// no reTok - leaves tok dirty
2445  
// magically append ".class" to class name references
2446  
svoid expandClassReferences_lazy(L<S> tok, Set<S> classNames, L<IntRange> reToks default null) {
2447  
  for (int i = 3; i+2 < l(tok); i += 2) {
2448  
    S t = tok.get(i);
2449  
    
2450  
    // skip implements/extends/throws lists
2451  
    if (eqOneOf(t, "implements", "extends", "throws")) {
2452  
      i = tok_endOfImplementsList(tok, i);
2453  
      continue;
2454  
    }
2455  
    
2456  
    if (classNames.contains(t) || expandableClassNames.contains(t)) {
2457  
      S s = tok.get(i-2); t = tok.get(i+2);
2458  
      // Now s is token before class name, t is token after class name
2459  
      // TODO: This whole logic ain't very good
2460  
      // (Hard to distinguish between "Int.class" as an argument
2461  
      // and "Int" as a type parameter.)
2462  
      if (eqOneOf(s, "instanceof", "new", ".", "<", ">", "/", "nu")) continue;
2463  
      if (eq(t, ":")) continue; // e.g. String::concat
2464  
      if (isInteger(s)) continue;
2465  
      if (isIdentifier(s) && !eqOneOf(s, "ret", "return")) continue;
2466  
        
2467  
      if (eq(t, ",") && isIdentifier(get(tok, i+4)) && eqGet(tok, i+6, ">")) continue; // e.g. T3<L<S>, S, S>
2468  
      if (eq(s, ",") && isIdentifier(get(tok, i-4)) &&
2469  
        (eqGet(tok, i-6, "<") || eqGet(tok, i-6, ",")
2470  
        && isIdentifier(get(tok, i-8)) && eqGet(tok, i-10, "<"))) continue; // e.g. T3<S, S, S> or IF3<S, S, S, S>
2471  
      if (eq(s, ",") && eqOneOf(_get(tok, i-6), "implements", "throws")) continue;
2472  
      
2473  
      // check for cast
2474  
      if (eq(s, "(") && eq(t, ")") && i >= 5) {
2475  
        if (!eqOneOf(get(tok, i+4), "{", ";")) {
2476  
          S x = tok.get(i-4);
2477  
          if (!isIdentifier(x)) continue;
2478  
          if (eqOneOf(x, "ret", "return")) continue;
2479  
        }
2480  
      }
2481  
      
2482  
      // check following token
2483  
      if (eqOneOf(t, ",", ")", ";", ":", "|")) {
2484  
        tok.set(i, tok.get(i) + ".class");
2485  
        reToks?.add(intRange(i, i+1));
2486  
      }
2487  
    }
2488  
  }
2489  
}
2490  
2491  
svoid expandClassReferences(L<S> tok, Set<S> classNames) {
2492  
  new L<IntRange> reToks;
2493  
  expandClassReferences_lazy(tok, classNames, reToks);
2494  
  reTok_multi(tok, reToks);
2495  
}
2496  
2497  
// "<id>/<ClassName>" => "((ClassName) <id>)"
2498  
static void slashCasts(L<S> tok, final Set<S> classNames) {
2499  
  /*jreplace(tok, "<id>/<id>", "(($3) $1)", tokcondition {
2500  
    ret classNames.contains(tok.get(i+5));
2501  
  });*/
2502  
  int n = l(tok)-4;
2503  
  for (int i = 1; i < n; i += 2)
2504  
    if (tok.get(i+2).equals("/") && isIdentifier(tok.get(i))
2505  
      && classNames.contains(tok.get(i+4)))
2506  
      replaceTokens_reTok(tok, i, i+5, "((" + tok.get(i+4) + ") " + tok.get(i) + ")");
2507  
}
2508  
2509  
// "<ClassName>(...)" => "new <ClassName>(...)"
2510  
// doesn't work at beginning of statement as we can't easily
2511  
// distinguish it from a constructor declaration.
2512  
static void newWithoutNew(L<S> tok, final Set<S> classNames) {
2513  
  TokCondition cond = newWithoutNew_condition(classNames);
2514  
  jreplace(tok, "<id>(", "new $1(", cond);
2515  
  // just two cases with type args for now
2516  
  jreplace(tok, "<id><<id>>(", "new $1<$3>(", cond);
2517  
  jreplace(tok, "<id><>(", "new $1<>(", cond);
2518  
}
2519  
2520  
static TokCondition newWithoutNew_condition(final Set<S> classNames) {
2521  
  ret tokcondition {
2522  
    if (!classNames.contains(tok.get(i+1))) false;
2523  
    S prev = _get(tok, i-1);
2524  
    bool ok = //!(eqGet(tok, i-3, "ifclass") && isIdentifier(prev))
2525  
      nempty(prev) // discarded ifclass
2526  
      && (eq(prev, ">") ? eqGet(tok, i-3, "-")
2527  
      : neqOneOf(prev, "new", ";", "}", "{", "public", "protected", "private", "."));
2528  
    //print("newWithoutNew: checking " + struct(subList(tok, i-3, i+2)) + " => " + ok);
2529  
    ret ok;
2530  
  };
2531  
}
2532  
2533  
static bool processConceptsDot(L<S> tok) {
2534  
  bool anyChange = false, change;
2535  
  do {
2536  
    change = false;
2537  
    for (int i : jfindAll(tok, "concepts."))
2538  
      if (contains(get(tok, i+3), "\n")) {
2539  
        replaceTokens(tok, i, i+3, "!" + "include once #1004863 // Dynamic Concepts");
2540  
        reTok(tok, i, i+3);
2541  
        change = anyChange = true;
2542  
        break;
2543  
      }
2544  
  } while (change);
2545  
  ret anyChange;
2546  
}
2547  
2548  
svoid caseAsVariableName(L<S> tok) {
2549  
  if (!tok.contains("case")) ret;
2550  
  for (int i = 1; i+2 < l(tok); i += 2) {
2551  
    S t = tok.get(i+2);
2552  
    if (tok.get(i).equals("case")
2553  
      && !(t.startsWith("'") || isInteger(t) || isIdentifier(t) || isQuoted(t)
2554  
        || eq(t, "-") && eqGet(tok, i+3, "") && isInteger(get(tok, i+4))))
2555  
      tok.set(i, "_case");
2556  
  }
2557  
}
2558  
2559  
static void continueAsFunctionName(L<S> tok) {
2560  
  jreplace(tok, "continue(", "_continue(");
2561  
}
2562  
2563  
// f bla => "bla" - and "please include function bla."
2564  
static void functionReferences(L<S> tok) {
2565  
  int i;
2566  
  
2567  
  jreplace_dyn(tok, "f-thread <id>", func(L<S> tok, int cIdx) {
2568  
    "dynamicCallableMC_thread(" + quote(tok.get(cIdx+6)) + ")"
2569  
  });
2570  
  
2571  
  S keyword = "f";
2572  
  while ((i = jfind(tok, keyword + " <id>", tokcondition {
2573  
    ret !eqOneOf(tok.get(i+3), "instanceof", "default");
2574  
  })) >= 0) {
2575  
    S f = tok.get(i+2);
2576  
    clearTokens(tok, i, i+2);
2577  
    tok.set(i+2, quote(f));
2578  
    reTok(tok, i, i+2);
2579  
    tok.set(l(tok)-1, last(tok) + "\nplease include function " + f + ".");
2580  
    reTok(tok, l(tok)-1, l(tok));
2581  
  }
2582  
  
2583  
  // r|rThread|rEnter|rThreadEnter|rEnterThread fname => r|rThread|... { fname() }
2584  
  while ((i = jfindOneOf_cond(tok, tokcondition {
2585  
    ret !eq(tok.get(i+3), "instanceof")
2586  
      && !eq(_get(tok, i-1), "cast");
2587  
  }, "r <id>", "rThread <id>", "rEnter <id>", "rThreadEnter <id>",
2588  
    "rEnterThread <id>")) >= 0) {
2589  
    S f = tok.get(i+2);
2590  
    replaceTokens(tok, i, i+3, tok.get(i) + " { " + f + "(); }");
2591  
    reTok(tok, i, i+3);
2592  
  }
2593  
  
2594  
  // dm_q fname => r_dm_q(r fname)
2595  
  jreplace(tok, "dm_q <id>", "r_dm_q(r $2)");
2596  
  
2597  
  // vf<S> fname => voidfunc(S s) { fname(s) }
2598  
  jreplace(tok, "vf<<id>> <id>", "voidfunc($3 a) { $5(a) }");
2599  
  
2600  
  // vf<L<S>> fname => voidfunc(L<S> a) { fname(a) }
2601  
  jreplace(tok, "vf<<id><<id>>> <id>", "voidfunc($3<$5> a) { $8(a) }");
2602  
  
2603  
  // construct<S> Entry => func(S s) -> Entry { new Entry(s) }
2604  
  jreplace(tok, "construct<<id>> <id>", "func($3 a) -> $5 { new $5(a) }");
2605  
  
2606  
  // f<S> fname => func -> S { fname() }
2607  
  jreplace(tok, "f<<id>> <id>", "func -> $3 { $5() }");
2608  
  
2609  
  // f<S, S> fname => func(S x) -> S { fname(x) }
2610  
  jreplace(tok, "f<<id>, <id>> <id>", "func($3 x) -> $5 { $7(x) }");
2611  
  
2612  
  // f<S, L<S>> fname => func(S x) -> L<S> { fname(x) }
2613  
  jreplace(tok, "f<<id>, <id><<id>>> <id>", "func($3 x) -> $5 $6 $7 $8 { $10(x) }");
2614  
  
2615  
  // f<L<S>, S> fname => func(L<S> x) -> S { fname(x) }
2616  
  jreplace(tok, "f<<id><<id>>, <id>> <id>", "func($3 $4 $5 $6 x) -> $8 { $10(x) }");
2617  
  
2618  
  // f<S, L<S>, S> fname => func(S x, L<S> y) -> S { fname(x, y) }
2619  
  jreplace(tok, "f<<id>, <id><<id>>, <id>> <id>", "func($3 x, $5 $6 $7 $8 y) -> $10 { $12(x, y) }");
2620  
  
2621  
  // if1 fname => a -> fname(a)
2622  
  // ivf1 fname => a -> fname(a)
2623  
  for (S _keyword : ll("if1", "ivf1"))
2624  
    jreplace_dyn(tok, _keyword + " <id>", func(LS tok, int i) -> S {
2625  
      S var = makeVar();
2626  
      ret var + " -> " + tok.get(i+2) + "(" + var + ")";
2627  
    });
2628  
}
2629  
2630  
static void quicknu(L<S> tok) {
2631  
  jreplace(tok, "nu <id>(", "nu($2.class, "); // not needed anymore
2632  
  jreplace(tok, "nu <id>", "new $2");
2633  
}
2634  
2635  
// fill variable innerClasses_list
2636  
static void innerClassesVar(L<S> tok, Set<S> have) {
2637  
  int i = jfind_check myInnerClasses_list(tok, ">myInnerClasses_list;");
2638  
  if (i < 0) ret;
2639  
  tok.set(i+4, "=litlist(\n" + joinQuoted(", ", have) + ");");
2640  
  reTok(tok, i+4, i+5);
2641  
}
2642  
2643  
// fill variable innerClasses_list
2644  
static void fillVar_transpilationDate(L<S> tok) {
2645  
  int i = jfind_check myTranspilationDate_value(tok, "long myTranspilationDate_value;");
2646  
  if (i < 0) ret;
2647  
  tok.set(i+4, " = " + now() + "L;");
2648  
  reTok(tok, i+4, i+5);
2649  
}
2650  
2651  
sbool ifclass_reTokImmediately = false;
2652  
sbool ifclass_noReTok = true;
2653  
2654  
// process ifclass x ... endif blocks
2655  
static void tok_ifclass(LS tok, Set<S> have) {
2656  
  tok_conditionals(tok, "ifclass", "endif", id -> contains(have, id), ifclass_reTokImmediately, ifclass_noReTok);
2657  
}
2658  
2659  
// returns number of changes
2660  
static int tok_conditionals(LS tok, S keyword, S keywordEnd, IPred<S> pred, bool reTokImmediately, bool noReTok) {
2661  
  int changes = 0;
2662  
  if (tok instanceof IContentsIndexedList) {
2663  
    int[] l = tok/IContentsIndexedList.indicesOf(keyword);
2664  
    for (int j = l(l)-1; j >= 0; j--) {
2665  
      int i = l[j];
2666  
      if (isIdentifier(get(tok, i+2))) {
2667  
        processConditional(tok, i, keyword, keywordEnd, pred, reTokImmediately && !noReTok);
2668  
        ++changes;
2669  
      }
2670  
    }
2671  
  } else {
2672  
    if (!tok.contains(keyword)) ret changes;
2673  
    int i = l(tok);
2674  
    while ((i = rjfind(tok, 1, i-1, keyword + " <id>")) >= 0) {
2675  
      ++changes;
2676  
      processConditional(tok, i, keyword, keywordEnd, pred, reTokImmediately && !noReTok);
2677  
    }
2678  
  }
2679  
  if (changes != 0 && !reTokImmediately && !noReTok) reTok(tok);
2680  
  //print(keyword + ": " + nChanges(changes));
2681  
  ret changes;
2682  
}
2683  
2684  
svoid processConditional(LS tok, int i, S keyword, S keywordEnd, IPred<S> pred, bool reTokImmediately) {
2685  
  int j = jfind(tok, i+4, keywordEnd);
2686  
  if (j < 0) j = l(tok)-1;
2687  
  S name = tok.get(i+2);
2688  
  bool has = pred.get(name);
2689  
  //print(keyword + " " + name + " => " + has);
2690  
  if (has) {
2691  
    clearTokens_maybeReTok(tok, j, j+1, reTokImmediately);
2692  
    clearTokens_maybeReTok(tok, i, i+3, reTokImmediately);
2693  
  } else
2694  
    clearTokens_maybeReTok(tok, i, j+1, reTokImmediately); // safer than before
2695  
}
2696  
2697  
// set flag *.
2698  
static void tok_definitions(L<S> tok) {
2699  
  int i;
2700  
  while ((i = jfind_check flag(tok, "set flag <id>.")) >= 0) {
2701  
    S fname = tok.get(i+4);
2702  
    print("Setting flag " + fname);
2703  
    definitions.add(fname);
2704  
    if (eqic(fname, "debug_jreplace")) set debug_jreplace;
2705  
    clearAllTokens(subList(tok, i, i+8));
2706  
  }
2707  
  
2708  
  while ((i = jfind_check flag(tok, "unset flag <id>.")) >= 0) {
2709  
    S fname = tok.get(i+4);
2710  
    print("Unsetting flag " + fname);
2711  
    definitions.remove(fname);
2712  
    clearAllTokens(subList(tok, i, i+8));
2713  
  }
2714  
}
2715  
2716  
// rewrite <id> [=|with|to] <definition>
2717  
// - a global version of "replace <id> with"
2718  
// new version - may not work yet
2719  
/*svoid tok_findAndClearRewrites(LS tok, SS newlyDefined default null) {
2720  
  tok_findRewrites(tok, newlyDefined, f -> {
2721  
    print("Have rewrite: " + f.token + " => " + f.replacement());
2722  
    clearTokens(f.tok, f.startCIdx(), f.endNIdx());
2723  
  });
2724  
}*/
2725  
2726  
2727  
// rewrite <id> [=|with|to] <definition>
2728  
// - a global version of "replace <id> with"
2729  
// old version (works)
2730  
svoid tok_findAndClearRewrites(LS tok, SS newlyDefined default null) {
2731  
  int i;
2732  
  while ((i = jfind(tok, "rewrite <id>", (_tok, nIdx) ->
2733  
    eqGetOneOf(_tok, nIdx+5, "with", "=", "to"))) >= 0) {
2734  
    S token = tok.get(i+2);
2735  
    int repStart = i+6;
2736  
    int repEnd = smartIndexOf(tok, repStart, ".");
2737  
    S replacement = joinSubList(tok, repStart, repEnd-1);
2738  
    clearTokens(tok, i, repEnd+1);
2739  
    mapPut(newlyDefined, token, replacement);
2740  
    rewrites.put(token, replacement);
2741  
    print("Have rewrite: " + token + " => " + replacement);
2742  
  }
2743  
}
2744  
2745  
static void tok_processRewrites(L<S> tok) {
2746  
  for (S token : keys(rewrites))
2747  
    jreplace(tok, token, rewrites.get(token));
2748  
}
2749  
2750  
// extend *. (set base class of main class)
2751  
static void tok_extend(L<S> tok) {
2752  
  int i;
2753  
  while ((i = jfind(tok, "extend <id>.")) >= 0) {
2754  
    mainBaseClass = tok.get(i+2);
2755  
    clearAllTokens(tok, i, i+7);
2756  
  }
2757  
}
2758  
2759  
// process ifndef x ... endifndef blocks
2760  
static void tok_ifndef(LS tok) {
2761  
  tok_conditionals(tok, "ifndef", "endifndef", id -> !definitions.contains(id), true, false);
2762  
}
2763  
  
2764  
// process ifdef x ... endifdef blocks
2765  
static void tok_ifdef(LS tok) {
2766  
  tok_conditionals(tok, "ifdef", "endifdef", id -> definitions.contains(id), true, false);
2767  
}
2768  
  
2769  
svoid conceptDeclarations(L<S> tok) {
2770  
  for (S kw : ll("concept", "sconcept")) {
2771  
    O cond = tokcondition { tok_addFieldOrder(tok, i+1); true; };
2772  
    bool re = false;
2773  
    if (jreplace(tok, kw + " <id> {", "static class $2 extends Concept {", cond)) re = true;
2774  
    if (jreplace(tok, kw + " <id> implements", "static class $2 extends Concept implements", cond)) re = true;
2775  
    if (jreplace(tok, kw + " <id>", "static class $2", cond)) re = true;
2776  
    if (re) reTok(tok);
2777  
  }
2778  
}
2779  
2780  
svoid shortenedSubconcepts(L<S> tok) {
2781  
  jreplace(tok, "<id> > <id> {", "concept $3 extends $1 {", tokcondition {
2782  
    bool b = (i == 0 || tok.get(i).contains("\n")) || eq(_get(tok, i-1), "abstract"); // only at beginning of line or after "abstract"
2783  
    //print("subconcept " + b + ": " + structure(subList(tok, i-1, i+5)));
2784  
    ret b;
2785  
  });
2786  
}
2787  
2788  
// -slightly experimental
2789  
// -do calculation in another thread, then return to AWT thread
2790  
// -must be placed in a block
2791  
// -transforms rest of block 
2792  
svoid unswing(L<S> tok) {
2793  
  int i;
2794  
  while ((i = jfind(tok, "unswing {")) >= 0) {
2795  
    int idx = i+2;
2796  
    int closingBracket = findEndOfBracketPart(tok, idx)-1;
2797  
    int endOfOuterBlock = findEndOfBracketPart(tok, closingBracket)-1;
2798  
    tok.set(i, "thread");
2799  
    tok.set(closingBracket, " awt {");
2800  
    tok.set(endOfOuterBlock, "}}}");
2801  
    reTok(tok, closingBracket-1, endOfOuterBlock+1);
2802  
  }
2803  
}
2804  
2805  
// -Syntax: lock theLock;
2806  
// -lock a lock, unlock at end of current block with finally
2807  
svoid lockBlocks(L<S> tok) {
2808  
  int i;
2809  
  while ((i = jfind(tok, "lock <id>", tokcondition { ret neq(tok.get(i+3), "instanceof"); })) >= 0) {
2810  
    int semicolon = findEndOfStatement(tok, i)-1;
2811  
    S var = makeVar();
2812  
    int endOfOuterBlock = findEndOfBracketPart(tok, semicolon)-1;
2813  
    replaceTokens(tok, i, semicolon+1,
2814  
      "Lock " + var + " = " + joinSubList(tok, i+2, semicolon-1) + "; lock(" + var + "); try {");
2815  
    tok.set(endOfOuterBlock, "} finally { unlock(" + var + "); } }");
2816  
    reTok(tok, i, endOfOuterBlock+1);
2817  
  }
2818  
}
2819  
2820  
// -Syntax: temp Bla bla = bla();
2821  
// -expands to try(Bla bla = bla()) { ... } with rest of block inside
2822  
svoid tempBlocks(L<S> tok) {
2823  
  int i;
2824  
  jreplace_dyn(tok, "temp (<id>) <id>", (_tok, cIdx) -> {
2825  
    S var = makeVar(), type = tok.get(cIdx+4), firstTokenOfExpr = tok.get(cIdx+8);
2826  
    ret "temp \*type*/ \*var*/ = cast \*firstTokenOfExpr*/";
2827  
  });
2828  
  
2829  
  jreplace(tok, "temp <id> =", "temp var $2 =");
2830  
  
2831  
  while ((i = jfind(tok, "temp <id>")) >= 0) {
2832  
    int semicolon = findEndOfStatement(tok, i)-1;
2833  
    int endOfOuterBlock = findEndOfBracketPart(tok, semicolon)-1;
2834  
    L<S> sub = subList(tok, i-1, semicolon);
2835  
    int eq = subList(sub, 0, smartIndexOfOneOf(sub, "{", "(")).indexOf("=");
2836  
    S var;
2837  
    if (eq >= 0)
2838  
      var = sub.get(eq-2);
2839  
    else {
2840  
      // no var name, e.g. temp newThoughtSpace();
2841  
      var = makeVar();
2842  
      tok.set(i+2, "AutoCloseable " + var + " = " + tok.get(i+2));
2843  
    }
2844  
      
2845  
    //tok.set(i, "try (");
2846  
    //tok.set(semicolon, ") {";
2847  
    //tok.set(endOfOuterBlock, "}}");
2848  
    
2849  
    tok.set(i, "");
2850  
    tok.set(semicolon, "; try {");
2851  
    tok.set(endOfOuterBlock, "} finally { _close(" + var + "); }}");
2852  
    
2853  
    reTok(tok, i, endOfOuterBlock+1);
2854  
  }
2855  
}
2856  
2857  
svoid forgetCachedIncludes {
2858  
  cachedIncludes.clear();
2859  
}
2860  
2861  
// TODO: when to do this / merge contents if there are multiple transpilers?
2862  
svoid cleanMeUp {
2863  
  for (CachedInclude ci : values(cachedIncludes))
2864  
    ci.clean();
2865  
  vmKeepWithProgramMD5_save('cachedIncludes);
2866  
}
2867  
2868  
svoid printSources(L<S> tok) {
2869  
  S src = join(tok);
2870  
  print("----");
2871  
  print(src);
2872  
  print("----");
2873  
  print("Bracket hygiene: " + testBracketHygiene2(src));
2874  
}
2875  
2876  
svoid tok_quickInstanceOf(L<S> tok, final Set<S> haveClasses) {
2877  
  if (!quickInstanceOfEnabled) ret;
2878  
  // "x << X" or "x >> X" => "x instanceof X"
2879  
  for (S op : ll("<<", ">>"))
2880  
    jreplace(tok, "<id> " + op + " <id>", "$1 instanceof $4", tokcondition {
2881  
      ret haveClasses.contains(tok.get(i+7))
2882  
        && !eqOneOf(tok.get(i-1), "<", "extends", "implements");
2883  
    });
2884  
}
2885  
2886  
sbool hasDef aka isDef(S s) {
2887  
  ret definitions.contains(s);
2888  
}
2889  
2890  
svoid tok_shortFinals(L<S> tok) {
2891  
  jreplace(tok, "fS", "final S");
2892  
  jreplace(tok, "fO", "final O");
2893  
  jreplace(tok, "fL", "final L");
2894  
  jreplace(tok, "fMap", "final Map");
2895  
  jreplace(tok, "fRunnable", "final Runnable");
2896  
  jreplace(tok, "f int", "final int");
2897  
}
2898  
2899  
svoid tok_mainClassNameAndPackage(LS tok) {
2900  
  int i;
2901  
  if ((i = jfind(tok, "mainClassName <id>")) >= 0) {
2902  
    mainClassName = tok.get(i+2);
2903  
    if (eqGet(tok, i+4, ".") && isIdentifier(get(tok, i+6))) {
2904  
      mainPackage = mainClassName;
2905  
      mainClassName = tok.get(i+6);
2906  
      clearTokensAndReTok(tok, i, i+7);
2907  
    } else
2908  
      clearTokensAndReTok(tok, i, i+3);
2909  
  }
2910  
  
2911  
  if ((i = jfind(tok, "mainPackage <id>")) >= 0) {
2912  
    int j = i+2;
2913  
    while (subListEquals(tok, j+1, "", ".", "") && isIdentifier(get(tok, j+4)))
2914  
      j += 4;
2915  
    mainPackage = joinSubList(tok, i+2, j+1);
2916  
    clearTokens_reTok(tok, i, j+1);
2917  
  }
2918  
}
2919  
2920  
svoid defineMapLikesEtc(LS tok) {
2921  
  defineMapLikes(tok);
2922  
  defineLambdaMapLikes(tok);
2923  
  defineCurry1Likes(tok);
2924  
  defineMapMethodLikes(tok);
2925  
  defineNuLikes(tok);
2926  
  defineXLikes(tok, "getLike", getLikeFunctions);
2927  
  defineXLikes(tok, "lambdaMethod0Like", lambdaMethod0LikeFunctions);
2928  
  defineXLikes(tok, "lambda0Like", lambda0LikeFunctions);
2929  
}
2930  
2931  
svoid defineMapLikes(LS tok) {
2932  
  int i;
2933  
  while ((i = jfind(tok, "mapLike <id>")) >= 0) {
2934  
    mapLikeFunctions.add(printIf(printMapLikes(), "mapLike", tok.get(i+2)));
2935  
    clearTokens_reTok(tok, i, i+2);
2936  
  }
2937  
}
2938  
2939  
svoid defineLambdaMapLikes(LS tok) {
2940  
  int i;
2941  
  while ((i = jfind(tok, "lambdaMapLike <id>")) >= 0) {
2942  
    lambdaMapLikeFunctions.add(printIf(printMapLikes(), "lambdaMapLike", tok.get(i+2)));
2943  
    clearTokens_reTok(tok, i, i+2);
2944  
  }
2945  
}
2946  
2947  
svoid defineCurry1Likes(LS tok) {
2948  
  int i;
2949  
  while ((i = jfind(tok, "curry1Like <id>")) >= 0) {
2950  
    curry1LikeFunctions.add(printIf(printMapLikes(), "curry1Like", tok.get(i+2)));
2951  
    clearTokens_reTok(tok, i, i+2);
2952  
  }
2953  
}
2954  
2955  
svoid defineMapMethodLikes(LS tok) {
2956  
  int i;
2957  
  while ((i = jfind(tok, "mapMethodLike <id>")) >= 0) {
2958  
    mapMethodLikeFunctions.add(printIf(printMapLikes(), "mapMethodLike", tok.get(i+2)));
2959  
    clearTokens_reTok(tok, i, i+2);
2960  
  }
2961  
}
2962  
2963  
// functions that work like "nu" syntactically (accept a class as "super-first" parameter [left of the bracket])
2964  
svoid defineNuLikes(LS tok) {
2965  
  int i;
2966  
  while ((i = jfind(tok, "nuLike <id>")) >= 0) {
2967  
    nuLikeFunctions.add(printIf(printMapLikes(), "nuLike", tok.get(i+2)));
2968  
    clearTokens_reTok(tok, i, i+2);
2969  
  }
2970  
}
2971  
2972  
svoid defineXLikes(LS tok, S keyword, Set<S> xLikeFunctions) {
2973  
  int i;
2974  
  while ((i = jfind(tok, keyword + " <id>")) >= 0) {
2975  
    xLikeFunctions.add(printIf(printMapLikes(), keyword, tok.get(i+2)));
2976  
    clearTokens_reTok(tok, i, i+2);
2977  
  }
2978  
}
2979  
2980  
svoid defineExtraSF(LS tok) {
2981  
  int i;
2982  
  IntRange reTok = null;
2983  
  while ((i = jfind(tok, "function <id> is in *.")) >= 0) {
2984  
    extraStandardFunctions.put(tok.get(i+2), fsI(unquote(tok.get(i+8))));
2985  
    clearTokens(tok, i, i+12);
2986  
    reTok = combineIntRanges(reTok, intRange(i, i+12));
2987  
  }
2988  
  reTok(tok, reTok);
2989  
}
2990  
2991  
sbool tok_applyAllXLikeFunctions(LS tok) {
2992  
  new L<IntRange> reToks;
2993  
  for (int i : jfindAll(tok, "<id> <id> (")) {
2994  
    S f = tok.get(i), arg = tok.get(i+2), replacement = null;
2995  
    if (contains(mapLikeFunctions, f))
2996  
      replacement = "\*f*/(f \*arg*/,";
2997  
    else if (contains(lambdaMapLikeFunctions, f))
2998  
      replacement = "\*f*/(lambda1 \*arg*/,";
2999  
    else if (contains(curry1LikeFunctions, f))
3000  
      replacement = "\*f*/(lambda2 \*arg*/,";
3001  
    else if (contains(mapMethodLikeFunctions, f))
3002  
      replacement = "\*f*/(\*quote(arg)*/,";
3003  
    else if (contains(nuLikeFunctions, f))
3004  
      replacement = "\*f*/(\*arg*/.class,";
3005  
    else if (contains(getLikeFunctions, f))
3006  
      replacement = "\*f*/(lambdaField \*arg*/,";
3007  
    else if (contains(lambdaMethod0LikeFunctions, f))
3008  
      replacement = "\*f*/(methodLambda0 \*arg*/,";
3009  
    else if (contains(lambda0LikeFunctions, f))
3010  
      replacement = "\*f*/(lambda0 \*arg*/,";
3011  
    
3012  
    if (replacement != null)
3013  
      replaceTokens_reTokLater(tok, reToks, i, i+5, replacement + " ");
3014  
  }
3015  
  reTok_multi(tok, reToks);
3016  
  ret nempty(reToks);
3017  
}
3018  
3019  
/*sbool tok_applyMapLikeFunctions(LS tok, final Set<S> mapLikeFunctions) {
3020  
  // map funcname(...) => map(f funcname, ...)
3021  
  // filter funcname(...) => filter(f funcname, ...)
3022  
  // ...
3023  
  ret jreplace(tok, "<id> <id>(", "$1(f $2,", func(L<S> tok, int i) -> bool {
3024  
    contains(mapLikeFunctions, tok.get(i+1))
3025  
  });
3026  
}*/
3027  
3028  
/*sbool tok_applyLambdaMapLikeFunctions(LS tok, final Set<S> lambdaMapLikeFunctions) {
3029  
  // mapNonNulls funcname(...) => mapNonNulls(lambda1 funcname, ...)
3030  
  // mapKeysAndValues funcname(...) => mapKeysAndValues(lambda1 funcname, ...)
3031  
  // ...
3032  
  ret jreplace(tok, "<id> <id>(", "$1(lambda1 $2,", func(L<S> tok, int i) -> bool {
3033  
    contains(lambdaMapLikeFunctions, tok.get(i+1))
3034  
  });
3035  
}*/
3036  
3037  
/*sbool tok_applyCurry1LikeFunctions(LS tok, final Set<S> curry1LikeFunctions) {
3038  
  // curry1 funcname(...) => curry1(lambda2 funcname, ...)
3039  
  ret jreplace(tok, "<id> <id>(", "$1(lambda2 $2,", func(L<S> tok, int i) -> bool {
3040  
    contains(curry1LikeFunctions, tok.get(i+1))
3041  
  });
3042  
}*/
3043  
3044  
/*sbool tok_applyMapMethodLikeFunctions(LS tok, final Set<S> mapMethodLikeFunctions) {
3045  
  // mapMethod funcname(...) => mapMethod('funcname, ...)
3046  
  // collect funcname(...) => collect('funcname, ...)
3047  
  // ...
3048  
  ret jreplace_dyn(tok, "<id> <id>(",
3049  
    func(L<S> tok, int cIdx) -> S { tok.get(cIdx) + "(" + quote(tok.get(cIdx+2)) + "," },
3050  
    func(L<S> tok, int i) -> bool {
3051  
      contains(mapMethodLikeFunctions, tok.get(i+1))
3052  
    });
3053  
}*/
3054  
3055  
svoid runMetaPostBlocks(LS tok) {
3056  
  for ping (S code : unnull(metaPostBlocks)) {
3057  
    S snippetID = standardFunctionSnippet(assertIdentifier(code));
3058  
    if (empty(snippetID))
3059  
      fail("meta-post function not found: " + code);
3060  
    call(hotwireCached(snippetID), code, tok);
3061  
    //callF(codeToFunctionOnArbitraryType(code, "LS", L, "tok"), tok);
3062  
  }
3063  
}
3064  
3065  
svoid runTransformers(LS tok, LS transformers) {
3066  
  fOr ping (S code : transformers)
3067  
    tok_runMetaTransformer(tok, code);
3068  
}
3069  
3070  
/*sbool tok_applyNuLikeFunctions(LS tok, final Set<S> nuLikeFunctions) {
3071  
  // nu ClassName(...) => nu(ClassName, ...)
3072  
  // ...
3073  
  ret jreplace_dyn(tok, "<id> <id>(",
3074  
    func(L<S> tok, int cIdx) -> S { tok.get(cIdx) + "(" + tok.get(cIdx+2) + ".class," },
3075  
    func(L<S> tok, int i) -> bool {
3076  
      contains(nuLikeFunctions, tok.get(i+1))
3077  
    });
3078  
}*/
3079  
3080  
/*sbool tok_applyGetLikeFunctions(LS tok, Set<S> getLikeFunctions) {
3081  
  // get fieldName(...) => get(fieldLambda fieldName, ...)
3082  
  // ...
3083  
  ret jreplace_dyn(tok, "<id> <id>(",
3084  
    func(L<S> tok, int cIdx) -> S { tok.get(cIdx) + "(lambdaField " + tok.get(cIdx+2) + "," },
3085  
    func(L<S> tok, int i) -> bool {
3086  
      contains(getLikeFunctions, tok.get(i+1))
3087  
    });
3088  
}*/
3089  
3090  
sbool metaCodeAllowed() {
3091  
  ret allowMetaCode || containsIC(definitions, "allowMetaCode");
3092  
}
3093  
3094  
static LS indexTokenList(LS tok) {
3095  
  if (useIndexedList2) ret indexedList2(tok);
3096  
  if (useTokenIndexedList) ret tokenIndexedList3(tok);
3097  
  ret tok;
3098  
}
3099  
3100  
svoid tok_earlyGeneralStuff(LS tok) {
3101  
  // self-compile construct (TODO)
3102  
  /*jreplace(tok, "self-compile", (tok, iOpening, iClosing) -> S[] {
3103  
  
3104  
    selfCompiling
3105  
  });*/
3106  
  
3107  
  tok_standardBot1(tok);
3108  
  tok_processSimplified(tok);
3109  
  tok_compactModules(tok);
3110  
  
3111  
  tok_metaFor(tok);
3112  
  
3113  
  // is, short for "implements"
3114  
  jreplace(tok, "is <id>", "implements $2", tokCondition {
3115  
    ret !eqGetOneOf(tok, i+3, "a", "in"); // "is a", "is in" are defined as something else
3116  
  });
3117  
}
3118  
3119  
svoid lambdaReferences(LS tok) {
3120  
  // lambda0 myFunction => () -> myFunction()
3121  
  jreplace(tok, "lambda0 <id>", "() -> $2()");
3122  
  
3123  
  // lambda1 myFunction => var123 -> myFunction(var123)
3124  
  jreplace_dyn(tok, "lambda1 <id>", func(L<S> tok, int cIdx) {
3125  
    S var = makeVar();
3126  
    S s = var + " -> " + tok.get(cIdx+2) + "(" + var + ")";
3127  
    ret eqGet(tok, cIdx-2, ")") ? roundBracket(s) : s;
3128  
  });
3129  
  
3130  
  // lambda2 myFunction => (a, b) -> myFunction(a, b)
3131  
  jreplace_dyn(tok, "lambda2 <id>", func(LS tok, int cIdx) {
3132  
    S a = makeVar();
3133  
    S b = makeVar();
3134  
    S s = "(\*a*/, \*b*/) -> \*tok.get(cIdx+2)*/(\*a*/, \*b*/)";
3135  
    ret eqGet(tok, cIdx-2, ")") ? roundBracket(s) : s;
3136  
  });
3137  
  
3138  
  // methodLambda0 methodName => var123 -> var123.methodName()
3139  
  jreplace_dyn(tok, "methodLambda0 <id>", func(LS tok, int cIdx) {
3140  
    S var = makeVar();
3141  
    ret var + " -> " + var + "." + tok.get(cIdx+2) + "()";
3142  
  });
3143  
  
3144  
  // fieldLambda fieldName => var123 -> var123.fieldName
3145  
  jreplace_dyn(tok, "fieldLambda <id>", func(LS tok, int cIdx) {
3146  
    S var = makeVar();
3147  
    ret var + " -> " + var + "." + tok.get(cIdx+2);
3148  
  });
3149  
}
3150  
3151  
svoid clearSnippetCache {
3152  
  snippetCache.clear();
3153  
  sf = null;
3154  
  lclasses = null;
3155  
}
3156  
3157  
svoid mediumRefresh {
3158  
  clearSnippetCache();
3159  
  print("Medium-refreshed transpiler " + mc());
3160  
}
3161  
3162  
svoid jreplace_performing(LS tok, int i, int end, S expansion) {
3163  
  if (debug_jreplace)
3164  
    print("jreplace: " + quote(joinSubList(tok, i, end)) + " => " + quote(expansion));
3165  
}
3166  
3167  
sS mainClassName() {
3168  
  ret or(mainClassName, "main");
3169  
}
3170  
3171  
svoid grabImportedStaticFunctions(LS tok) {
3172  
  for (S name : tok_importedStaticFunctionNamesWithPackages(tok)) {
3173  
    int idx = lastIndexOf(name, '.');
3174  
    S pkg = takeFirst(idx, name);
3175  
    S functionName = dropFirst(idx+1, name);
3176  
    //print(functionName + " => " + pkg);
3177  
    doNotIncludeFunction.add(functionName);
3178  
    functionToPackage.put(functionName, pkg);
3179  
  }
3180  
}
3181  
3182  
sbool printMapLikes() {
3183  
  ret contains(definitions, "printMapLikesEtc");
3184  
}
3185  
3186  
// delete import if marked as "need latest"
3187  
svoid onImportFound(LS tok, IntRange r) {
3188  
  S id = get(tok, r.end-3);
3189  
  if (needLatest.contains(id)) {
3190  
    print("Purging import: " + joinSubList(tok, r));
3191  
    clearTokens(tok, r);
3192  
  }
3193  
}

Author comment

Began life as a copy of #759

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): bhatertpkbcr, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1033035
Snippet name: JavaX Translator backup
Eternal ID of this version: #1033035/1
Text MD5: 298e03438f2b4c1406228fddd7a69416
Transpilation MD5: 428eaa76953ca1230355118c80dd8188
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-10-11 14:43:01
Source code size: 107308 bytes / 3193 lines
Pitched / IR pitched: No / No
Views / Downloads: 247 / 806
Referenced in: [show references]