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

3181
LINES

< > BotCompany Repo | #1033089 // Transpiler dev.

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

Download Jar. Uses 1176K of libraries. Compilation Failed (28709L/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  
    jreplace(tok, "for (<id> :", "for (var $3 :");
817  
    
818  
    jreplace(tok, "for (<id> <id>)", "for ($3 $4 : list($3))");
819  
    jreplace(tok, "for (final <id> <id>)", "for (final $4 $5 : list($4))");
820  
821  
    jreplace(tok, "ret", "return", tokCondition {
822  
      if (eqGetOneOf(tok, i-1, "int", "return")) false;
823  
      S next = _get(tok, i+3);
824  
      if (eq(next, ".")) ret isInteger(_get(tok, i+5)); // e.g. "ret .1", but not "ret.bla"
825  
      ret !eqOneOf(next, "=", ")");
826  
    });
827  
    
828  
    // "continue unless", "break unless"
829  
    
830  
    for (S phrase : ll("continue unless", "break unless"))
831  
      while ((i = jfind(tok, phrase)) >= 0) {
832  
        S keyword = tok.get(i);
833  
        int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
834  
        replaceTokens(tok, i, i+4, "{ if (!(");
835  
        tok.set(j, ")) " + keyword + "; }");
836  
        reTok(tok, i, j+1);
837  
      }
838  
    
839  
    // S s = bla(), return if null; => S s = bla(); if (s == null) return;
840  
    // same with continue, break
841  
    while ((i = jfind(tok, ", <id> if null;", tokCondition {
842  
      ret eqOneOf(tok.get(i+3), "return", "ret", "continue", "break");
843  
    })) >= 0) {
844  
      S cmd = tok.get(i+2);
845  
      int j = tok_findBeginningOfStatement(tok, i);
846  
      print("Found statement " + j + "/" + i + " - " + joinSubList(tok, j-1, i+5*2-1));
847  
      S var = getVarDeclarationName(subList(tok, j-1, i));
848  
      replaceTokens_reTok(tok, i, i+5*2-1, "; if (" + var + " == null) " + cmd + ";");
849  
    }
850  
    
851  
    // S s = bla(), return false if null; => S s = bla(); if (s == null) return false;
852  
    // (with false being any identifier)
853  
    while ((i = jfind(tok, ", return <id> if null;")) >= 0) {
854  
      S returnValue = tok.get(i+4);
855  
      int j = tok_findBeginningOfStatement(tok, i);
856  
      S var = getVarDeclarationName(subList(tok, j-1, i));
857  
      replaceTokens_reTok(tok, i, i+6*2-1, "; if (" + var + " == null) return " + returnValue + ";");
858  
    }
859  
    
860  
    // "continue if", "break if"
861  
    
862  
    for (S phrase : ll("continue if", "break if"))
863  
      while ((i = jfind(tok, phrase)) >= 0) {
864  
        S keyword = tok.get(i);
865  
        int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
866  
        replaceTokens(tok, i, i+4, "{ if (");
867  
        tok.set(j, ") " + keyword + "; }");
868  
        reTok(tok, i, j+1);
869  
      }
870  
    
871  
    // return unless set <var>; => { if (var) return; set var; }
872  
    jreplace(tok, "return unless set <id>;", "{ if ($4) return; set $4; }");
873  
874  
    // set x; => x = true;
875  
    // yeah it doesn't save many characters, but I like it
876  
    jreplace(tok, "set <id>;", "$2 = true;", tokCondition {
877  
      ret !eqGet(tok, i-1, "unless");
878  
    });
879  
    
880  
    // set !x; => x = false; (did this one day and thought yes it makes sense in a way)
881  
    jreplace(tok, "set !<id>;", "$3 = false;");
882  
    
883  
    // unset x; => x = false;
884  
    jreplace(tok, "unset <id>;", "$2 = false;");
885  
    
886  
    // "return if"
887  
    
888  
    while ((i = jfind(tok, "return if")) >= 0) {
889  
      int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
890  
      replaceTokens(tok, i, i+4, "{ if (");
891  
      tok.set(j, ") return; }");
892  
      reTok(tok, i, j+1);
893  
    }
894  
    
895  
    // "return unless"
896  
    
897  
    while ((i = jfind(tok, "return unless")) >= 0) {
898  
      int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
899  
      replaceTokens(tok, i, i+4, "{ if (!(");
900  
      tok.set(j, ")) return; }");
901  
      reTok(tok, i, j+1);
902  
    }
903  
    
904  
    tok_ifNullAssign(tok);
905  
906  
    // "return <id> if"
907  
    
908  
    // "return with <statement>" / "continue with <statement>" / "break with <statement>"
909  
    
910  
    while ((i = jfind(tok, "<id> with", tokcondition { ret eqOneOf(tok.get(i+1), "return", "continue", "break"); })) >= 0) {
911  
      // XXX int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
912  
      int j = tok_findEndOfStatement(tok, i+4)-1;
913  
      //print("Found statement: " + joinSubList(tok, i+4, j+1));
914  
      tok.set(j, "; " + tok.get(i) + "; }");
915  
      replaceTokens(tok, i, i+3, "{");
916  
      reTok(tok, i, j+1);
917  
    }
918  
    
919  
    while ((i = jfind(tok, "return <id> if")) >= 0) {
920  
      int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
921  
      tok.set(j, ") return " + tok.get(i+2) + "; }");
922  
      replaceTokens(tok, i, i+6, "{ if (");
923  
      reTok(tok, i, j+1);
924  
    }
925  
    
926  
    // return "bla" with <statement>
927  
    
928  
    while ((i = jfindOneOf(tok,
929  
      "return <quoted> with", "return <id> with")) >= 0) {
930  
      S result = tok.get(i+2);
931  
      int j = scanOverExpression(tok, getBracketMap(tok), i+6, ";");
932  
      replaceTokens(tok, i, i+5, "{");
933  
      tok.set(j, "; return " + result + "; }");
934  
      reTok(tok, i, j+1);
935  
    }
936  
    
937  
    tok_debugStatements(tok);
938  
939  
    // while not null (...) / if not null (...)
940  
    
941  
    while ((i = jfind_check not(tok, "<id> not null (", tokcondition {
942  
      ret eqOneOf(_get(tok, i+1), "if", "while");
943  
    })) >= 0) {
944  
      int closingBracket = findEndOfBracketPart(tok, i+6)-1;
945  
      replaceTokens(tok, i+2, i+6, "(");
946  
      tok.set(closingBracket, ") != null)");
947  
      reTok(tok, i, closingBracket+1);
948  
    }
949  
    
950  
    // while null (...) / if null (...)
951  
    
952  
    while ((i = jfind_check null(tok, "<id> null (", tokcondition {
953  
      ret eqOneOf(_get(tok, i+1), "if", "while");
954  
    })) >= 0) {
955  
      int closingBracket = findEndOfBracketPart(tok, i+4)-1;
956  
      replaceTokens(tok, i+2, i+4, "(");
957  
      tok.set(closingBracket, ") == null)");
958  
      reTok(tok, i, closingBracket+1);
959  
    }
960  
    
961  
    // Replace $1 with m.unq(0) etc. - caveat: this blocks identifiers $1, $2, ...
962  
    for (i = 1; i < l(tok); i += 2) {
963  
      S s = tok.get(i);
964  
      if (s.startsWith("$")) {
965  
        s = substring(s, 1);
966  
        if (isInteger(s)) {
967  
          tok.set(i, "m.unq(" + (parseInt(s)-1) + ")");
968  
          reTok(tok, i);
969  
        }
970  
      }
971  
    }
972  
  
973  
    // instanceof trickery
974  
    
975  
    jreplace(tok, "is a <id>", "instanceof $3");
976  
    jreplace(tok, "!<id> instanceof <id>.<id>", "!($2 instanceof $4.$6)");
977  
    jreplace(tok, "!<id> instanceof <id>", "!($2 instanceof $4)");
978  
    jreplace(tok, "<id> !instanceof <id>", "!($1 instanceof $4)");
979  
    
980  
    // map func1 func2 func3(...) => mapFGH(f func1, f func2, f func3, ...)
981  
    jreplace(tok, "map <id> <id> <id>(", "mapFGH(f $2, f $3, f $4,");
982  
983  
    // map func1 func2(...) => mapFG(f func1, f func2, ...)
984  
    jreplace(tok, "map <id> <id>(", "mapFG(f $2, f $3,");
985  
986  
    // "ref->bla" for dereferencing Concept.Ref or ThreadLocal or other
987  
    // For lambdas, use SPACES on the left or right of the arrow!
988  
    //jreplace(tok, "<id> ->", "$1.get().");
989  
    jreplace(tok, "->", ".get().", tokcondition {
990  
      ret empty(tok.get(i)) // no space on left of arrow
991  
        && empty(tok.get(i+2)) // no space inside of arrow
992  
        && empty(tok.get(i+4)) // no space on right of arrow
993  
        && !eq(_get(tok, i-1), "-"); // i-->0;
994  
    });
995  
    
996  
    // shortened subconcept declaration (before star constructors!)
997  
    shortenedSubconcepts(tok);
998  
    
999  
    tok_beaConceptDecls(tok);
1000  
    
1001  
    // "case" as a variable name ( => _case)
1002  
    
1003  
    caseAsVariableName(tok);
1004  
    
1005  
    // "do" as a function name ( => dO)
1006  
    
1007  
    tok_doAsMethodName(tok);
1008  
    
1009  
    // "continue" as a function name ( => _continue)
1010  
    continueAsFunctionName(tok);
1011  
    
1012  
    tok_extend(tok);
1013  
    
1014  
    jreplace(tok, "pn {", "p-noconsole {");
1015  
      
1016  
    // Do these BEFORE awt replacement! ("p-awt" contains "awt" token)
1017  
    replaceKeywordBlock(tok, "r-awt", "r { awt {", "}}");
1018  
    if (hasCodeTokens(tok, "p", "-")) tok_p_old(tok);
1019  
1020  
    replaceKeywordBlock(tok, "awt-messagebox", "awt { pcall-messagebox {", "}}");
1021  
    replaceKeywordBlock(tok, "awt", "swingLater(r {", "});");
1022  
  
1023  
    jreplace(tok, "p-android {", "set flag Android. p {");
1024  
      
1025  
    unswing(tok);
1026  
    lockBlocks(tok);
1027  
    tok_switchTo(tok);
1028  
    
1029  
    // trim x;
1030  
    
1031  
    jreplace(tok, "trim <id>;", "$2 = trim($2);");
1032  
  
1033  
    // iterate with index
1034  
  
1035  
    jreplace (tok, "for <id> over <id>:", "for (int $2 = 0; $2 < l($4); $2++)");
1036  
    jreplace (tok, "for <id> backwards over <id>:", "for (int $2 = l($5)-1; $2 >= 0; $2--)");
1037  
    jreplace (tok, "for <id>, <id> <id> over <id>: {", "for (int $2 = 0; $2 < l($7); $2++) { $4 $5 = $7.get($2);");
1038  
    jreplace (tok, "for <id>, <id> <id> backwards over <id>: {", "for (int $2 = l($8)-1; $2 >= 0; $2--) { $4 $5 = $8.get($2);");
1039  
    jreplace (tok, "for <id> to <id>:", "for (int $2 = 0; $2 < $4; $2++)");
1040  
    jreplace (tok, "for <id> to <int>:", "for (int $2 = 0; $2 < $4; $2++)");
1041  
    
1042  
    tok = expandShortTypes(tok);
1043  
      
1044  
    tok_equalsCast(tok);
1045  
    tok_equalsOptCast(tok);
1046  
1047  
    replaceKeywordBlock(tok, "r-thread-messagebox", "r-thread { pcall-messagebox {", "}}");
1048  
    
1049  
    replaceKeywordBlock(tok, "thread-messagebox", "thread { pcall-messagebox {", "}}");
1050  
    
1051  
    jreplace(tok, "rThread {", "r-thread {");
1052  
    jreplace(tok, "rEnterThread {", "rThreadEnter {");
1053  
    jreplace(tok, "rThreadEnter {", "r-thread { temp enter(); ");
1054  
  
1055  
    replaceKeywordBlock(tok, "r-thread", "runnableThread(r {", "})");
1056  
    rNamedThread(tok);
1057  
    
1058  
    // only works in the scope of a DynModule
1059  
    jreplace(tok, "rEnter {", "r { temp enter(); ");
1060  
  
1061  
    replaceKeywordBlock(tok, "r-pcall", "r { pcall {", "}}");
1062  
  
1063  
    replaceKeywordBlock(tok, "r-messagebox", "r { pcall-messagebox {", "}}");
1064  
    
1065  
    jreplace(tok, "r <id> + r <id>", "r { $2(); $5(); }");
1066  
    
1067  
    // runnable and r - now also with automatic toString if enabled
1068  
    for (S keyword : ll("runnable", "r")) {
1069  
      while ((i = jfind(tok, keyword + " {")) >= 0) {
1070  
        int idx = findCodeTokens(tok, i, false, "{");
1071  
        int j = findEndOfBracketPart(tok, idx);
1072  
        L<S> contents = subList(tok, idx+1, j-1);
1073  
        replaceTokens(tok, i, j+1, "new Runnable {"
1074  
          + "  public void run() ctex { " + tok_addSemicolon(contents) + "\n}"
1075  
          + (autoQuine ? tok_autoQuineFunc(contents) : "")
1076  
          + "}");
1077  
        reTok(tok, i, j+1);
1078  
      }
1079  
      
1080  
      while ((i = jfind(tok, keyword + " <quoted> {")) >= 0) {
1081  
        int idx = findCodeTokens(tok, i, false, "{");
1082  
        int j = findEndOfBracketPart(tok, idx);
1083  
        L<S> contents = subList(tok, idx+1, j-1);
1084  
        replaceTokens(tok, i, j+1, "new Runnable {"
1085  
          + "  public void run() ctex { " + tok_addSemicolon(contents) + "\n}"
1086  
          + "  toString { ret " + tok.get(i+2) + "; }"
1087  
          + (autoQuine ? tok_autoQuineFunc(contents, '_shortenedSourceCode) : "")
1088  
          + "}");
1089  
        reTok(tok, i, j+1);
1090  
      }
1091  
    }
1092  
    
1093  
    replaceKeywordBlock(tok,
1094  
      "expectException",
1095  
      "{ bool __ok = false; try {",
1096  
      "} catch { __ok = true; } assertTrue(\"expected exception\", __ok); }");
1097  
      
1098  
    while ((i = tok.indexOf("tex")) >= 0) {
1099  
      tok.set(i, "throws Exception");
1100  
      tok = jtok(tok);
1101  
    }
1102  
    
1103  
    // shorter & smarter whiles
1104  
    
1105  
    jreplace(tok, "while true", "while (true)");
1106  
    jreplace(tok, "while licensed", "while (licensed())");
1107  
    jreplace(tok, "repeat {", "while (licensed()) {");
1108  
    tok_repeatWithSleep(tok);
1109  
    
1110  
    // null; => return null; etc.
1111  
  
1112  
    O cond = tokcondition {
1113  
      ret tok_tokenBeforeLonelyReturnValue(tok, i-1);
1114  
    };
1115  
    jreplace(tok, "null;", "return null;", cond);
1116  
    jreplace(tok, "false;", "return false;", cond);
1117  
    jreplace(tok, "true;", "return true;", cond);
1118  
    jreplace(tok, "this;", "return this;", cond);
1119  
    
1120  
    // ok <cmd> => ret "OK" with <cmd>
1121  
    jreplace(tok, "ok <id>", "return \"OK\" with $2");
1122  
    replaceKeywordBlock(tok, "ok", "{", " return \"OK\"; }",
1123  
      func(LS _tok, int nIdx) -> bool { !eqGetOneOf(_tok, nIdx-1, "void", "svoid") });
1124  
  
1125  
    // "myFunction;" instead of "myFunction();" - quite rough
1126  
    // (isolated identifier as function call)
1127  
    cond = new TokCondition {
1128  
      public bool get(L<S> tok, int i) {
1129  
        S word = tok.get(i+3);
1130  
        //print("single word: " + word);
1131  
        ret !eqOneOf(word, "break", "continue", "return", "else", "endifdef", "endif");
1132  
      }
1133  
    };
1134  
    for (S pre : litlist("}", ";"))
1135  
      jreplace(tok, pre + " <id>;", "$1 $2();", cond);
1136  
  
1137  
    // shorter match syntax for answer methods
1138  
    
1139  
    tok_expandIfQuoted(tok);
1140  
    
1141  
    jreplace(tok, "if <id> eq <quoted>", "if (eq($2, $4))");
1142  
  
1143  
    tok_dropExtraCommas(tok);
1144  
    
1145  
    // additional translations (if necessary)
1146  
    
1147  
    jreplace(tok, "pcall ping {", "pcall { ping();");
1148  
    
1149  
    replaceKeywordBlock(tok, ") pcall",
1150  
      ") { pcall {",
1151  
      "}}");
1152  
    
1153  
    //jreplace(tok, "void <id> pcall {", "$1 $2() pcall {");
1154  
    
1155  
    replaceKeywordBlock(tok,
1156  
      "pcall",
1157  
      "try {",
1158  
      "} catch (Throwable __e) { printStackTrace(__e); }");
1159  
  
1160  
    replaceKeywordBlock(tok,
1161  
      "pcall-print",
1162  
      "try {",
1163  
      "} catch (Throwable __e) { printStackTrace(__e); }");
1164  
  
1165  
    replaceKeywordBlock(tok,
1166  
      "pcall-short",
1167  
      "try {",
1168  
      "} catch (Throwable __e) { print(exceptionToStringShort(__e)); }");
1169  
  
1170  
    replaceKeywordBlock(tok,
1171  
      "pcall-silent",
1172  
      "try {",
1173  
      "} catch (Throwable __e) { silentException(__e); }");
1174  
  
1175  
    replaceKeywordBlock(tok,
1176  
      "pcall-messagebox",
1177  
      "try {",
1178  
      "} catch __e { messageBox(__e); }");
1179  
  
1180  
    replaceKeywordBlock(tok,
1181  
      "pcall-infobox",
1182  
      "try {",
1183  
      "} catch __e { infoBox(__e); }");
1184  
  
1185  
    tok = dialogHandler(tok);
1186  
    
1187  
    replaceKeywordBlock(tok, "exceptionToUser",
1188  
      "try {",
1189  
      "} catch (Throwable __e) { ret exceptionToUser(__e); }"); 
1190  
  
1191  
    if (hasCodeTokens(tok, "twice", "{"))
1192  
      replaceKeywordBlock(tok, "twice",
1193  
        "for (int __twice = 0; __twice < 2; __twice++) {",
1194  
        "}"); 
1195  
  
1196  
    while ((i = findCodeTokens(tok, "bench", "*", "{")) >= 0) {
1197  
      int j = findEndOfBracketPart(tok, i+4)-1;
1198  
      S time = makeVar("time");
1199  
      S v = makeVar("bench");
1200  
      S n = tok.get(i+2);
1201  
      tok.set(i, "{ long " + time + " = sysNow(); for (int " + v + " = 0; " + v + " < " + n + "; " + v + "++)");
1202  
      tok.set(i+2, "");
1203  
      tok.set(j, "} printBenchResult(sysNow()-" + time + ", " + n + "); }");
1204  
      reTok(tok, i, j+1);
1205  
    }
1206  
  
1207  
    replaceKeywordBlockDyn(tok,
1208  
      "time",
1209  
      new O { S[] get() {
1210  
        S var = makeVar("startTime");
1211  
        ret new S[] {
1212  
          "{ long " + var + " = sysNow(); try { ",
1213  
          "} finally { " + var + " = sysNow()-" + var + "; saveTiming(" + var + "); } }"};
1214  
      }});
1215  
    
1216  
    // version without { }
1217  
    replaceKeywordBlockDyn(tok,
1218  
      "time2",
1219  
      new O { S[] get() {
1220  
        S var = makeVar("startTime");
1221  
        ret new S[] {
1222  
          "long " + var + " = sysNow(); ",
1223  
          " " + var + " = sysNow()-" + var + "; saveTiming(" + var + "); "};
1224  
      }});
1225  
    
1226  
    // time "bla" {
1227  
    // time msg {
1228  
    replaceKeywordPlusQuotedOrIDBlock(tok,
1229  
      "time",
1230  
      new O { S[] get(L<S> tok, int i) {
1231  
        S var = makeVar("startTime");
1232  
        ret new S[] {
1233  
          "long " + var + " = sysNow(); ",
1234  
          " done2_always(" + tok.get(i+2) + ", " + var + "); "};
1235  
      }});
1236  
    
1237  
    if (hasCodeTokens(tok, "assertFail", "{")) {
1238  
      S var = makeVar("oops");
1239  
      
1240  
      replaceKeywordBlock(tok,
1241  
        "assertFail",
1242  
        "boolean " + var + " = false; try {",
1243  
        "\n" + var + " = true; } catch (Exception e) { /* ok */ } assertFalse(" + var + ");"); 
1244  
    }
1245  
    
1246  
    replaceKeywordBlock(tok,
1247  
      "yo",
1248  
      "try {",
1249  
      "} catch (Exception " + makeVar("e") + ") { ret false; }",
1250  
      tokcondition {
1251  
        ret neqOneOf(_get(tok, i-1), "svoid", "void");
1252  
      });
1253  
  
1254  
    replaceKeywordBlock(tok,
1255  
      "awtIfNecessary",
1256  
      "swingNowOrLater(r " + "{",
1257  
      "});");
1258  
      
1259  
    ctex(tok);
1260  
      
1261  
    replaceKeywordBlock(tok,
1262  
      "actionListener",
1263  
      "new java.awt.event.ActionListener() { " +
1264  
        "public void actionPerformed(java.awt.event.ActionEvent _evt) { pcall-messagebox {",
1265  
      "}}}");
1266  
      
1267  
    for (S keyword : ll("autocloseable", "autoCloseable"))
1268  
      /*replaceKeywordBlock(tok,
1269  
        keyword,
1270  
        "new AutoCloseable() { public void close() throws Exception {",
1271  
        "}}");*/
1272  
        replaceKeywordBlock_dyn2_legacy(tok, keyword, new O {
1273  
          S[] get(LS tok, int iOpening, int iClosing) {
1274  
            LS contents = subList(tok, iOpening+1, iClosing);
1275  
            ret new S[] {
1276  
              "new AutoCloseable() { toString { ret " + quote(shorten(defaultMaxQuineLength(), trimJoin(contents))) + "; } public void close() throws Exception {",
1277  
              "}}"
1278  
            };
1279  
          }
1280  
        });
1281  
      
1282  
    // try answer (string, test with nempty)
1283  
    while ((i = findCodeTokens(tok, "try", "answer")) >= 0) {
1284  
      int j = findEndOfStatement(tok, i);
1285  
      S v = makeVar();
1286  
      bool needCurly = !eqGet(tok, i-2, "{");
1287  
      tok.set(i, (needCurly ? "{" : "") + " S " + v);
1288  
      tok.set(i+2, "=");
1289  
      tok.set(j-1, "; if (!empty(" + v + ")) ret " + v + "; " + (needCurly ? "}" : ""));
1290  
      reTok(tok, i, j);
1291  
    }
1292  
  
1293  
    // try bool[ean] (try answer with Bool type)
1294  
    while ((i = findCodeTokens(tok, "try", "boolean")) >= 0) {
1295  
      int j = findEndOfStatement(tok, i);
1296  
      S v = makeVar();
1297  
      tok.set(i, "{ Bool " + v);
1298  
      tok.set(i+2, "=");
1299  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1300  
      reTok(tok, i, j);
1301  
    }
1302  
    
1303  
    // <statement>, print "..."; => { <statement>; print("..."); }
1304  
    while ((i = jfind(tok, ", print <quoted>;")) >= 0) {
1305  
      int j = tok_findBeginningOfStatement(tok, i);
1306  
      replaceTokens_reTok(tok, i, i+4*2-1, "; print(" + tok.get(i+4) + "); }");
1307  
      tokPrepend_reTok(tok, j, "{ ");
1308  
    }
1309  
    
1310  
    // return if null <expression> => if (<expression> == null) return;
1311  
    while ((i = jfind(tok, "return if null")) >= 0) {
1312  
      int j = findEndOfStatement(tok, i);
1313  
      clearTokens(tok, i, i+2);
1314  
      tok.set(i+4, "((");
1315  
      tok.set(j-1, ") == null) ret;");
1316  
      reTok(tok, i, j);
1317  
    }
1318  
    
1319  
    // return optional (return if not null)
1320  
    while ((i = jfind_check optional(tok, "return optional <id> =")) >= 0) {
1321  
      int j = findEndOfStatement(tok, i);
1322  
      S v = tok.get(i+4);
1323  
      clearTokens(tok, i+2, i+4);
1324  
      tok.set(i, "{");
1325  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1326  
      reTok(tok, i, j);
1327  
    }
1328  
    
1329  
    // try object (return if not null)
1330  
    
1331  
    jreplace_dyn(tok, "try object (<id>)", (_tok, cIdx) -> {
1332  
      S type = _tok.get(cIdx+6);
1333  
      ret "try object " + type + " " + makeVar() + " = (" + type + ")";
1334  
    });
1335  
    
1336  
    while ((i = jfind_check object(tok, "try object")) >= 0) {
1337  
      int j = findEndOfStatement(tok, i);
1338  
      clearTokens(tok, i, i+3);
1339  
      bool isDecl = isIdentifier(get(tok, i+4)) && isIdentifier(get(tok, i+6)) && eqGet(tok, i+8, "=");
1340  
      if (isDecl) {
1341  
        S v = get(tok, i+6);
1342  
        tok.set(i, "{");
1343  
        tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1344  
      } else {
1345  
        S v = makeVar();
1346  
        tok.set(i, "{ O " + v + "=");
1347  
        tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1348  
      }
1349  
      reTok(tok, i, j);
1350  
    }
1351  
    
1352  
    // try Int i = ...; (return if not null, shorter version of "try object")
1353  
    /*while ((i = jfind(tok, "try <id> <id> =")) >= 0) {
1354  
      int j = findEndOfStatement(tok, i);
1355  
      S type = tok.get(i+2), v = tok.get(i+4);
1356  
      tok.set(i, "{");
1357  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1358  
      reTok(tok, i, j);
1359  
    }*/
1360  
    while ((i = jfind(tok, "try <id>")) >= 0) {
1361  
      int iType = i+2, iVar = tok_findEndOfType(tok, iType);
1362  
      S v = tok.get(iVar);
1363  
      assertEquals("try object", "=", get(tok, iVar+2));
1364  
      int j = findEndOfStatement(tok, iVar);
1365  
      tok.set(i, "{");
1366  
      tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
1367  
      reTok(tok, i, j);
1368  
    }
1369  
    
1370  
    // debug print ...; => if (debug) print(...);
1371  
    while ((i = jfind(tok, "debug print")) >= 0) {
1372  
      int j = findEndOfStatement(tok, i);
1373  
      replaceTokens(tok, i, i+4, "if (debug) print(");
1374  
      tok.set(j-1, ");");
1375  
      reTok(tok, i, j);
1376  
    }
1377  
    
1378  
    functionReferences(tok);
1379  
    tok_expandLPair(tok);
1380  
    tok_expandPairL(tok);
1381  
    tok_expandLT3(tok);
1382  
    tok_quicknew2(tok);
1383  
    
1384  
    tok_exclamPostfix(tok);
1385  
    
1386  
    // before temp blocks
1387  
    tok_varNamedLikeFunction(tok);
1388  
    
1389  
    tok_onCleanExit(tok);
1390  
    
1391  
    tempBlocks(tok); // after quicknew2 for stuff like "temp new X x;"
1392  
1393  
    // X x = nu(+...)  =>  X x = nu X(+...)
1394  
    jreplace(tok, "<id> <id> = nu(+", "$1 $2 = nu $1(+");
1395  
    // X x = nu(a := ...)  =>  X x = nu X(a := ...)
1396  
    jreplace(tok, "<id> <id> = nu(<id> :=", "$1 $2 = nu $1($6 :=");
1397  
    
1398  
    tok_expandVarCopies(tok); // AFTER the lines just above
1399  
    tok_replaceColonEqualsSyntax(tok); // ditto
1400  
1401  
    tok_unpair(tok);
1402  
    tok_cachedFunctions(tok);
1403  
    tok_simplyCachedFunctions(tok);
1404  
    tok_timedCachedFunctions(tok);
1405  
    
1406  
    tok_optPar(tok);
1407  
    
1408  
    throwFailEtc(tok);
1409  
    tok_typeAA(tok, pairClasses);
1410  
    tok_typeAAA(tok, tripleClasses);
1411  
    tok_typeAO(tok, litset("WithTrail"));
1412  
1413  
    // before star constructors so we can define star constructors in a macro
1414  
    tok_localMacro(tok);
1415  
1416  
    // do this after expanding sclass etc.
1417  
    tok = tok_expandStarConstructors(tok);
1418  
    
1419  
    tok_kiloConstants(tok);
1420  
    //tok_colonMessages(tok);
1421  
    
1422  
    while ((i = jfind(tok, "shit:")) >= 0) {
1423  
      int j = tok_findEndOfStatement(tok, i);
1424  
      tok.set(i+2, "(");
1425  
      tok.set(j-1, ");");
1426  
      reTok(tok, i, j);
1427  
    }
1428  
      
1429  
    jreplace("shit(", "ret with print(");
1430  
    
1431  
    tok_virtualTypes(tok);
1432  
    tok_autoLongConstants(tok);
1433  
    
1434  
    // common misordering of type arguments
1435  
    jreplace("boolean <A>", "<A> boolean");
1436  
    
1437  
    tok_unimplementedMethods(tok);
1438  
    tok_switchableFields(tok);
1439  
    tok_autoDisposeFields(tok);
1440  
    tok_shortVisualize(tok);
1441  
    tok_whileGreaterThan(tok);
1442  
    tok_ifThenEnd(tok);
1443  
    
1444  
    tok_autoInitVars(tok);
1445  
    
1446  
    tok_fixBadTypeParameterOrder(tok);
1447  
    
1448  
    // shortened method declarations BEFORE standardFunctions
1449  
    tok_svoidEtc(tok);
1450  
    jreplace(tok, "void <id> {", "$1 $2() {");
1451  
    jreplace(tok, "void <id> thread {", "$1 $2() thread {");
1452  
    jreplace(tok, "String <id> {", "$1 $2() {");
1453  
    jreplace(tok, "Object <id> {", "$1 $2() {");
1454  
    jreplace(tok, "List <id> {", "$1 $2() {");
1455  
1456  
    namedThreads(tok);
1457  
    threads(tok);
1458  
    
1459  
    //tok_maxEquals(tok);
1460  
    
1461  
    tok_questionDot(tok);
1462  
    
1463  
    jreplace(tok, "if (<id>?!)", "if ($3 != null && $3!)");
1464  
    
1465  
    tok_embeddedFunctions(tok);
1466  
    
1467  
    // quicknew for arrays
1468  
    
1469  
    jreplace("<id>[] <id> = new[", "$1[] $4 = new $1[");
1470  
    jreplace("<id>[] <id> = new {", "$1[] $4 = {");
1471  
    jreplace("<id><<id>>[] <id> = new[", "$1 $2 $3 $4[] $7 = new $1[");
1472  
    
1473  
    jreplace("<id> ifNull =", "if ($1 == null) $1 =");
1474  
    
1475  
    jreplace("class <id> extends <id><.<id>>", "class $2 extends $4<$2.$7>");
1476  
    
1477  
    tok_once(tok); // must come before next line so you can combine them
1478  
    tok_ifRecordMatch(tok);
1479  
    
1480  
    jreplace(tok, "<id> ||=", "$1 = $1 ||");
1481  
    
1482  
    // magicValue followed by a numerical constant
1483  
    jreplace("magicValue", "", (_tok, _i) -> {
1484  
      S t = _get(_tok, _i+3);
1485  
      ret eqOneOf(t, ".", "-") || isInteger(t);
1486  
    });
1487  
    
1488  
    lambdaReferences(tok);
1489  
    
1490  
    tok_returnSelf(tok);
1491  
    
1492  
    // Lua-like print statement
1493  
    jreplace(tok, "print <quoted>", "print($2);");
1494  
    
1495  
    tok_tildeCalls(tok);
1496  
    
1497  
    tok_svoidEtc(tok);
1498  
    tok_swappableFunctions(tok);
1499  
    
1500  
    tok_optParLambda(tok);
1501  
    
1502  
    tok_runnableClasses(tok);
1503  
    
1504  
    tok_swapStatement(tok);
1505  
    
1506  
    //defineMapLikesEtc(tok);
1507  
    
1508  
    tok_defaultArguments_debug = isDef("tok_defaultArguments_debug"); 
1509  
    tok_defaultArguments(tok);
1510  
    
1511  
    tok_akaFunctionNames(tok);
1512  
    
1513  
    tok_persistableClasses(tok);
1514  
    
1515  
    tok_transientClasses(tok);
1516  
    
1517  
    tok_shortMethodReferences(tok);
1518  
    
1519  
    jreplace(tok, "== null ?:", "== null ? null :");
1520  
    jreplace(tok, "?:", "== null ? null :");
1521  
    
1522  
    tok_orCase(tok);
1523  
    
1524  
    tok_beforeMethods(tok);
1525  
    tok_afterMethods(tok);
1526  
    
1527  
    tok_returnAsFunctionName(tok);
1528  
    
1529  
    tok_transpileGetSet(tok);
1530  
    
1531  
    tok_pcallPrefix(tok);
1532  
    
1533  
    tok_numberFunctionNames(tok);
1534  
    
1535  
    tok_castToStatements(tok);
1536  
    
1537  
    tok_optionalFields(tok);
1538  
    
1539  
    tok_getFromMap(tok);
1540  
    
1541  
    jreplace(tok, "for <id> : <id> {", "for (var $2 : $4) {");
1542  
    
1543  
    tok_shortLambdas(tok);
1544  
    
1545  
    if (metaCodeAllowed()) runTransformers(tok, localTransformers);
1546  
    
1547  
    tok_andVarMixIn(tok);
1548  
    
1549  
    tok_stages(tok);
1550  
    
1551  
    tok_beginPeriod(tok);
1552  
    
1553  
    tok_enterStatement(tok);
1554  
    
1555  
    tok_settableFields(tok);
1556  
    
1557  
    // end of local stuff
1558  
    
1559  
    tok_processMetaBlocks(tok, metaCodeAllowed());
1560  
    if (metaCodeAllowed()) runTransformers(tok, metaTransformers);
1561  
1562  
    same = eq(tok, before);
1563  
    /*if (!same)
1564  
      print("local not same " + safety + " (" + l(tok) + " tokens)");*/
1565  
    if (safety++ >= 10) {
1566  
      printSources(tok);
1567  
      fail("safety 10 error!");
1568  
    }
1569  
  } while (!same);
1570  
  
1571  
  ret tok;
1572  
}
1573  
1574  
static L<S> reTok_include(L<S> tok, int i, int j) {
1575  
  ret reTok_modify(tok, i, j, f localStuff1);
1576  
}
1577  
1578  
static L<S> includeInMainLoaded_reTok(L<S> tok, int i, int j) {
1579  
  ret reTok_include(tok, i, j);
1580  
}
1581  
1582  
static L<S> stdstuff(L<S> tok) {
1583  
  //if (++level >= 10) fail("woot? 10");
1584  
  
1585  
  print("stdstuff!");
1586  
  int i;
1587  
  
1588  
  new L<S> ts;
1589  
  tok_findTranslators(tok, ts);
1590  
  if (nempty(ts))
1591  
    print("DROPPING TRANSLATORS: " + structure(ts));
1592  
1593  
  print('quickmain); tok = quickmain(tok);
1594  
  print('includes); tok = tok_processIncludes(tok);
1595  
  print('conceptsDot); if (processConceptsDot(tok))
1596  
  tok = tok_processIncludes(tok);
1597  
  
1598  
  LS dontImports = tok_processDontImports(tok, definitions);
1599  
  for (S s : dontImports)
1600  
    doNotIncludeFunction.remove(afterLastDot(s));
1601  
  
1602  
  //print('starConstructors); tok = tok_expandStarConstructors(tok);
1603  
    
1604  
  // drop Java 8 annotations since we're compiling for Java 7
1605  
  jreplace(tok, "@Nullable", "");
1606  
1607  
  // STANDARD CLASSES & INTERFACES
1608  
  
1609  
  print("standard classes");
1610  
  haveClasses = addStandardClasses_v2(tok);
1611  
  
1612  
  tok_quickInstanceOf(tok, haveClasses);
1613  
1614  
  // concept-related stuff
1615  
  
1616  
  // auto-import concepts
1617  
  /*bool _a = tok_hasClassRef2(tok, "Concept") || tok_hasClassRef2(tok, "Concepts"), _b = !haveClasses.contains("Concept");
1618  
  //print("auto-import: " + _a + ", " + _b);
1619  
  if (_a && _b) {
1620  
    print("Auto-including concepts.");
1621  
    if (shouldNotIncludeClass.contains("Concepts")) {
1622  
      print(join(tok));
1623  
      fail("Unwanted concepts import");
1624  
    }
1625  
    printStruct(haveClasses);
1626  
    tok = includeInMainLoaded(tok, "concepts.");
1627  
    reTok(tok, l(tok)-1, l(tok));
1628  
    //processConceptsDot(tok);
1629  
  }*/
1630  
  
1631  
  ret tok;
1632  
} // end of stdStuff!
1633  
1634  
static L<S> multilineStrings(L<S> tok) {
1635  
  for (int i = 1; i < tok.size(); i += 2) {
1636  
    S t = tok.get(i);
1637  
    if (isQuoted(t))
1638  
      if (t.startsWith("[") || t.contains("\r") || t.contains("\n"))
1639  
        tok.set(i, quote(unquote(t)));
1640  
  }
1641  
  ret tok;
1642  
}
1643  
1644  
static L<S> quickmain(L<S> tok) {
1645  
  if (quickmainDone1 && quickmainDone2) ret tok;
1646  
1647  
  int i = findCodeTokens(tok, "main", "{");
1648  
  if (i < 0) i = findCodeTokens(tok, "m", "{");
1649  
  if (i >= 0 && !(i-2 > 0 && tok.get(i-2).equals("class"))) {
1650  
    tokSet_reTok(tok, i, (definitions.contains("mainClassPublic") ? "public " : "") + "class main");
1651  
    quickmainDone1 = true;
1652  
  }
1653  
    
1654  
  i = findCodeTokens(tok, "psvm", "{");
1655  
  if (i < 0) i = findCodeTokens(tok, "p", "{");
1656  
  if (i >= 0) {
1657  
    int idx = i+2;
1658  
    int j = findEndOfBracketPart(tok, idx)-1;
1659  
    L<S> contents = subList(tok, idx+1, j);
1660  
    //print("contents: " + sfu(contents));
1661  
    tok.set(i, "public static void main(final String[] args) throws Exception");
1662  
    replaceTokens(tok, idx+1, j, tok_addSemicolon(contents));
1663  
    reTok(tok, i, j);
1664  
    quickmainDone2 = true;
1665  
  }
1666  
    
1667  
  ret tok;
1668  
}
1669  
1670  
sS makeVar(S name) {
1671  
  AtomicInteger counter = varCountByThread!;
1672  
  if (counter == null)
1673  
    varCountByThread.set(counter = new AtomicInteger);
1674  
  ret "_" + name + "_" + getAndInc(counter);
1675  
}
1676  
1677  
static S makeVar() { ret makeVar(""); }
1678  
1679  
static L<S> rtq(L<S> tok, S id) {
1680  
  ret runTranslatorQuick(tok, id);
1681  
}
1682  
1683  
static L<S> expandShortTypes(L<S> tok) {
1684  
  // replace <int> with <Integer>
1685  
  for (int i = 1; i+4 < tok.size(); i += 2)
1686  
    if (tok.get(i).equals("<")
1687  
      && litlist(">", ",").contains(tok.get(i+4))) {
1688  
      String type = tok.get(i+2);
1689  
      if (type.equals("int")) type = "Integer";
1690  
      else if (type.equals("long")) type = "Long";
1691  
      tok.set(i+2, type);
1692  
    }
1693  
    
1694  
  jreplace(tok, "O", "Object");
1695  
  jreplace(tok, "S", "String");
1696  
  jreplace(tok, "L", "List");
1697  
  jreplace(tok, "Cl", "Collection");
1698  
  
1699  
  // bool -> boolean if it's not a function name
1700  
  jreplace(tok, "bool", "boolean", tokCondition {
1701  
    ret neqGetOneOf(tok, i+3, "(", null);
1702  
  });
1703  
  
1704  
  jreplace(tok, "AtomicBool", "AtomicBoolean");
1705  
  jreplace(tok, "AtomicInt", "AtomicInteger");
1706  
1707  
  jreplace(tok, "LL< <id> >", "L<L<$3>>");
1708  
  jreplace(tok, "LL< <id><<id>> >", "L<L<$3<$5>>>");
1709  
  jreplace(tok, "LL<?>", "L<L<?>>");
1710  
  jreplace(tok, "LL", "L<L>");
1711  
  jreplace(tok, "LPt", "L<Pt>");
1712  
  
1713  
  jreplace(tok, "Clusters< <id> >", "Map<$3, Collection<$3>>");
1714  
  
1715  
  ret tok;
1716  
}
1717  
1718  
static L<S> autoImports(L<S> tok) {
1719  
  HashSet<S> imports = new HashSet(tok_findImports(tok));
1720  
  new StringBuilder buf;
1721  
  for (S c : standardImports())
1722  
    if (!(imports.contains(c)))
1723  
      buf.append("import " + c + ";\n");
1724  
  if (buf.length() == 0) ret tok;
1725  
  tok.set(0, buf+tok.get(0));
1726  
  ret reTok(tok, 0, 1);
1727  
}
1728  
1729  
static L<S> tok_processIncludes(L<S> tok) {
1730  
  int safety = 0;
1731  
  while (hasCodeTokens(tok, "!", "include") && ++safety < 100)
1732  
    tok = tok_processIncludesSingle(tok);
1733  
  
1734  
  //tok_autoCloseBrackets(tok);
1735  
  ret tok;
1736  
}
1737  
1738  
svoid tok_processEarlyIncludes(L<S> tok) {
1739  
  int i;
1740  
  while ((i = jfind_check include(tok, "!include early #<int>")) >= 0) {
1741  
    S id = tok.get(i+8);
1742  
    included.add(parseLong(id));
1743  
    replaceTokens_reTok(tok, i, i+10, "\n" + cacheGet(id) + "\n");
1744  
  }
1745  
}
1746  
1747  
static L<S> tok_processIncludesSingle(L<S> tok) {
1748  
  int i;
1749  
  while ((i = jfind_check include(tok, "!include #<int>")) >= 0) {
1750  
    S id = tok.get(i+6);
1751  
    included.add(parseLong(id));
1752  
    replaceTokens(tok, i, i+8, "\n" + cacheGet(id) + "\n");
1753  
    reTok_include(tok, i, i+8);
1754  
  }
1755  
  while ((i = jfind_check include(tok, "!include once #<int>")) >= 0) {
1756  
    S id = tok.get(i+8);
1757  
    bool isNew = included.add(parseLong(id));
1758  
    replaceTokens(tok, i, i+10, 
1759  
      isNew ? "\n" + cacheGet(id) + "\n" : "");
1760  
    reTok_include(tok, i, i+10);
1761  
  }
1762  
  ret tok;
1763  
}
1764  
1765  
// ctex and various other error-related keyword blocks
1766  
static void ctex(L<S> tok) {
1767  
  replaceKeywordBlock(tok, "ctex",
1768  
    "{ try {",
1769  
    "} catch (Exception __e) { throw rethrow(__e); } }");
1770  
  for (S keyword : ll("null on exception", "null on error"))
1771  
    replaceKeywordBlock(tok, keyword,
1772  
      "{ try {",
1773  
      "} catch (Throwable __e) { return null; } }");
1774  
  replaceKeywordBlock(tok, "false on exception",
1775  
    "{ try {",
1776  
    "} catch (Throwable __e) { return false; } }");
1777  
  replaceKeywordBlock(tok, "try-OrError",
1778  
    "{ try {",
1779  
    "} catch (Throwable __e) { return OrError.error(__e); } }");
1780  
}
1781  
  
1782  
static L<S> dialogHandler(L<S> tok) {
1783  
  ret replaceKeywordBlock(tok,
1784  
    "dialogHandler",
1785  
    "new DialogHandler() {\n" +
1786  
      "public void run(final DialogIO io) {",
1787  
    "}}");
1788  
}
1789  
1790  
static L<S> extendClasses(L<S> tok) {
1791  
  int i;
1792  
  while ((i = jfind(tok, "extend <id> {")) >= 0) {
1793  
    S className = tok.get(i+2);
1794  
    int idx = findCodeTokens(tok, i, false, "{");
1795  
    int j = findEndOfBracketPart(tok, idx+2);
1796  
    S content = joinSubList(tok, idx+1, j-1);
1797  
    L<S> c = findInnerClassOfMain(tok, className);
1798  
    print("Extending class " + className);
1799  
    clearTokens(subList(tok, i, j+1));
1800  
    if (c == null) {
1801  
      print("Warning: Can't extend class " + className + ", not found");
1802  
      continue;
1803  
    }
1804  
    int startOfClass = indexOfSubList(tok, c);
1805  
    int endOfClass = startOfClass + l(c)-1;
1806  
    //print("Extending class " + className + " ==> " + join(subList(tok, startOfClass, endOfClass)));
1807  
    while (neq(tok.get(endOfClass), "}")) --endOfClass;
1808  
    //print("Extending class " + className + " ==> " + join(subList(tok, startOfClass, endOfClass)));
1809  
    tok.set(endOfClass, content + "\n" + tok.get(endOfClass));
1810  
    
1811  
    doubleReTok(tok, i, j+1, endOfClass, endOfClass+1);
1812  
  }
1813  
  ret tok;
1814  
}
1815  
1816  
// for ping / while ping
1817  
static void forPing(L<S> tok) {
1818  
  int i;
1819  
  for (S keyword : ll("for", "fOr", "while"))
1820  
    while ((i = jfind(tok, keyword + " ping (")) >= 0) {
1821  
      int bracketEnd = findEndOfBracketPart(tok, i+4)-1;
1822  
      int iStatement = bracketEnd+2;
1823  
      int iEnd = findEndOfStatement(tok, iStatement);
1824  
      tok.set(i+2, "");
1825  
      
1826  
      // turn into block
1827  
      if (!eq(get(tok, iStatement), "{")) {
1828  
        tok.set(iStatement, "{ " + tok.get(iStatement));
1829  
        tok.set(iEnd-1, tok.get(iEnd-1) + " }");
1830  
      }
1831  
        
1832  
      // add ping
1833  
      tok.set(iStatement, "{ ping(); " + dropPrefixTrim("{", tok.get(iStatement)));
1834  
      reTok(tok, i+2, iEnd);
1835  
    }
1836  
}
1837  
1838  
// lib 123 => !123
1839  
static void libs(L<S> tok) {
1840  
  int i;
1841  
  while ((i = jfind(tok, "lib <int>")) >= 0) {
1842  
    S id = tok.get(i+2);
1843  
    print("lib " + id);
1844  
    if (!libs.contains(id)) {
1845  
      libs.add(id);
1846  
      clearAllTokens(tok, i, i+3);
1847  
      /*tok.set(i, "!");
1848  
      tok.set(i+1, "");*/
1849  
    } else {
1850  
      print("...ignoring (duplicate)");
1851  
      clearAllTokens(tok, i, i+3);
1852  
      reTok(tok, i, i+3);
1853  
    }
1854  
  }
1855  
  print("libs found: " + libs);
1856  
}
1857  
1858  
// sourceCodeLine() => 1234
1859  
static void sourceCodeLine(L<S> tok) {
1860  
  int i ;
1861  
  while ((i = jfind(tok, "sourceCodeLine()")) >= 0) {
1862  
    replaceTokens(tok, i, i+5, str(countChar(joinSubList(tok, 0, i), '\n')+1));
1863  
    reTok(tok, i, i+5);
1864  
  }
1865  
}
1866  
1867  
// done before any other processing
1868  
svoid earlyStuff(LS tok) {
1869  
  int i;
1870  
  
1871  
  tok_processEarlyIncludes(tok);
1872  
      
1873  
  tok_scopes(tok, autoCloseScopes := asInclude);
1874  
  tok_autosemi(tok);
1875  
  tok_autoCloseBrackets(tok);
1876  
  jreplace(tok, "°", "()");
1877  
  
1878  
  // Note: this makes the word "quine" a special operator
1879  
  // (unusable as a function name)
1880  
  
1881  
  while ((i = jfind(tok, "quine(")) >= 0) {
1882  
    int idx = findCodeTokens(tok, i, false, "(");
1883  
    int j = findEndOfBracketPart(tok, idx+2);
1884  
    tok.set(i, "new Quine");
1885  
    tok.set(idx, "(" + quote(joinSubList(tok, idx+1, j-1)) + ", ");
1886  
    reTok(tok, i, idx+1);
1887  
  }
1888  
  
1889  
  jreplace_check after(tok, "void <id> after super {", "void $2 { super.$2();");
1890  
  
1891  
  replaceKeywordBlock(tok, "r-enter", "r { enter {", "}}");
1892  
    
1893  
  // do this before func & voidfunc because otherwise they swallow it
1894  
  jreplace(tok, "enter {", "{ temp enter();");
1895  
  
1896  
  tok_mutatorMethods(tok);
1897  
  
1898  
  // func keyword for lambdas - now automatically quines toString() if enabled
1899  
  
1900  
  replaceKeywordBlock(tok,
1901  
    "null",
1902  
    "{",
1903  
    "null; }");
1904  
    
1905  
  // do func & voidfunc early to preserve original code as toString
1906  
  
1907  
  while ((i = jfind(tok, "func(")) >= 0) {
1908  
    int argsFrom = i+4, argsTo = findCodeTokens(tok, i, false, ")");
1909  
    int idx = findCodeTokens(tok, argsTo, false, "{");
1910  
    int j = findEndOfBracketPart(tok, idx);
1911  
    L<S> contents = subList(tok, idx+1, j-1);
1912  
    
1913  
    S returnType = "O";
1914  
    if (eq(tok.get(argsTo+2), "-") && eq(tok.get(argsTo+4), ">"))
1915  
      returnType = tok_toNonPrimitiveTypes(joinSubList(tok, argsTo+6, idx-1));
1916  
      
1917  
    S toString = autoQuine ? "  public S toString() { ret " + quote(shorten(defaultMaxQuineLength(), trimJoin(contents))) + "; }" : "";
1918  
    
1919  
    L<S> args = cloneSubList(tok, argsFrom-1, argsTo);
1920  
    tok_shortFinals(args);
1921  
    tok_toNonPrimitiveTypes(args);
1922  
    
1923  
    L<S> types = tok_typesOfParams(args);
1924  
    O type = "O";
1925  
    if (l(types) <= 3)
1926  
      type = "F" + l(types) + "<" + joinWithComma(types) + ", " + returnType + ">";
1927  
    S body = tok_addReturn(contents);
1928  
    
1929  
    replaceTokens_reTok(tok, i, j,
1930  
      "new " + type + "() { public "
1931  
        + returnType + " get(" + trimJoin(args) + ") ctex { "
1932  
          + body
1933  
        + " }\n" +
1934  
       + toString + "}");
1935  
  }
1936  
  
1937  
  while ((i = jfind(tok, "voidfunc(")) >= 0) {
1938  
    int argsFrom = i+4, argsTo = findCodeTokens(tok, i, false, ")");
1939  
    int idx = findCodeTokens(tok, argsTo, false, "{");
1940  
    int j = findEndOfBracketPart(tok, idx);
1941  
    L<S> contents = subList(tok, idx+1, j-1);
1942  
    
1943  
    if (jcontains(subList(tok, argsTo+1, idx), "->"))
1944  
      fail("voidfunc with return type: " + joinSubList(tok, i, j+1));
1945  
    
1946  
    L<S> args = cloneSubList(tok, argsFrom-1, argsTo);
1947  
    tok_shortFinals(args);
1948  
    tok_toNonPrimitiveTypes(args);
1949  
    
1950  
    L<S> types = tok_typesOfParams(args);
1951  
    O type = "O";
1952  
    if (l(types) <= 4)
1953  
      type = "VF" + l(types) + "<" + joinWithComma(types) + ">";
1954  
1955  
    replaceTokens(tok, i, j, "new " + type + "() { public void get(" + trimJoin(args) + ") ctex { " + tok_addSemicolon(contents) + " }\n" +
1956  
    (autoQuine ? "  public S toString() { ret " + quote(shorten(defaultMaxQuineLength(), trim(join(contents)))) + "; }" : "") + "}");
1957  
    reTok(tok, i, j);
1958  
  }
1959  
  
1960  
  jreplace(tok, "func {", "func -> O {");
1961  
  jreplace(tok, "f {", "f -> O {");
1962  
  
1963  
  // swing -> S { ... } => swing(func -> S { ... })
1964  
  while ((i = jfind(tok, "swing ->")) >= 0) {
1965  
    int bracket = findCodeTokens(tok, i, false, "{");
1966  
    int j = findEndOfBracketPart(tok, bracket);
1967  
    tok.set(i, "swing(func");
1968  
    tok.set(j-1, "})");
1969  
    reTok(tok, i, j);
1970  
  }
1971  
  
1972  
  tok_qFunctions(tok);
1973  
  
1974  
  jreplace(tok, "func fullToString {", "func -> O fullToString {");
1975  
  
1976  
  for (S keyword : ll(/*"f",*/ "func")) {
1977  
    while ((i = jfind(tok, keyword + " ->", tokcondition {
1978  
      ret isIdentifier(_get(tok, i+7)); // avoid lambda declaration like: f -> { ... }
1979  
    })) >= 0) {
1980  
      // I think there is a bug here for something like func -> x { new x { } }
1981  
      int idx = findCodeTokens(tok, i, false, "{");
1982  
      int j = findEndOfBracketPart(tok, idx);
1983  
      S returnType = tok_toNonPrimitiveTypes(joinSubList(tok, i+6, idx-1));
1984  
      int quineLength = defaultMaxQuineLength();
1985  
      if (eq(lastJavaToken(returnType), "fullToString")) {
1986  
        quineLength = Int.MAX_VALUE;
1987  
        returnType = dropLastJavaTokenAndSpacing(returnType);
1988  
      }
1989  
      L<S> contents = subList(tok, idx+1, j-1);
1990  
      replaceTokens(tok, i, j, "new F0<" + returnType + ">() { public " + returnType + " get() ctex { " + tok_addReturn(contents) + " }\n" +
1991  
        (autoQuine ? "  public S toString() { ret " + quote(shorten(quineLength, trimJoin(contents))) + "; }" : "") + "}");
1992  
      reTok(tok, i, j);
1993  
    }
1994  
  }
1995  
    
1996  
  while ((i = jfind(tok, "time repeat * {")) >= 0) {
1997  
    int j = findEndOfBlock(tok, i+6)-1;
1998  
    tok.set(i, "time {");
1999  
    tok.set(j, "}}");
2000  
    reTok(tok, i, j+1);
2001  
  }
2002  
2003  
  // do this before "m {" stuff because "repeat m" [doesn't seem to work yet though)
2004  
  while ((i = findCodeTokens(tok, "repeat", "*", "{")) >= 0) {
2005  
    S v = makeVar("repeat");
2006  
    tok.set(i, "for (int " + v + " = 0; " + v + " < " + tok.get(i+2) + "; " + v + "++)");
2007  
    tok.set(i+2, "");
2008  
    reTok(tok, i, i+3);
2009  
  }
2010  
}
2011  
2012  
static void throwFailEtc(L<S> tok) {
2013  
  bool anyChange = false;
2014  
  for (int i = 1; i+4 < l(tok); i += 2)
2015  
    if (eqOneOf(get(tok, i+2), "fail", "todo")
2016  
      && eq(get(tok, i+4), "(")
2017  
      && !eqOneOf(get(tok, i), "throw", "RuntimeException", "return", "f", "function", ".", "void", "main", "Throwable")) {
2018  
      tok.set(i+2, "throw " + tok.get(i+2));
2019  
      anyChange = true;
2020  
    }
2021  
  if (anyChange)
2022  
    reTok(tok);
2023  
}
2024  
2025  
static void namedThreads(L<S> tok) {
2026  
  for (int i = 0; i < 100; i++) {
2027  
    int idx = findCodeTokens(tok, "thread", "<quoted>", "{");
2028  
    if (idx < 0) idx = findCodeTokens(tok, "thread", "<id>", "{");
2029  
    if (idx < 0)
2030  
      break;
2031  
    int j = findEndOfBracketPart(tok, idx+4);
2032  
    S tName = tok.get(idx+2);
2033  
    
2034  
    S pre = "startThread(" + tName + ", r { ";
2035  
    S post = "})";
2036  
    if (!tok_tokenLeftOfExpression(tok, idx-2)) post += ";";
2037  
2038  
    tok.set(idx, pre);
2039  
    tok.set(idx+2, "");
2040  
    tok.set(idx+4, "");
2041  
    tok.set(j-1, post);
2042  
    //print(join(subList(tok, idx, j)));
2043  
    reTok(tok, idx, j);
2044  
  }
2045  
}
2046  
2047  
static void rNamedThread(L<S> tok) {
2048  
  for (int i = 0; i < 100; i++) {
2049  
    int idx = findCodeTokens(tok, "r", "-", "thread", "<quoted>", "{");
2050  
    if (idx < 0) idx = findCodeTokens(tok, "r", "-", "thread", "<id>", "{");
2051  
    if (idx < 0)
2052  
      break;
2053  
    int j = findEndOfBracketPart(tok, idx+8);
2054  
    S tName = tok.get(idx+6);
2055  
    
2056  
    S pre = "r { thread " + tName + " {";
2057  
    S post = "}}";
2058  
2059  
    replaceTokens(tok, idx, idx+9, pre);
2060  
    tok.set(j-1, post);
2061  
    reTok(tok, idx, j);
2062  
  }
2063  
}
2064  
2065  
static void threads(L<S> tok) {
2066  
  replaceKeywordBlock(tok, "daemon", "startDaemonThread(r {", "});");
2067  
  //replaceKeywordBlock(tok, "thread", "startThread(r {", "});");
2068  
  
2069  
  // now enclose in { } to allow using like "void bla() thread { ... }" - if it's not used as an expression
2070  
  
2071  
  replaceKeywordBlock_dyn2_legacy(tok, "thread", new O { // don't use func here, it can't be transpiled
2072  
    S[] get (LS tok, int iOpening, int iClosing) {
2073  
      // is the thread clause used as an expression?
2074  
      bool isExpression = tok_tokenLeftOfExpression(tok, iOpening-4);
2075  
      ret new S[] {
2076  
        (isExpression ? "" : "{ ") + "startThread(r {",
2077  
        "})" +
2078  
        (isExpression ? "" : "; }")
2079  
      };
2080  
    }
2081  
  });
2082  
}
2083  
2084  
static SS sf; // standard standard functions (haha)
2085  
static Bool _761ok;
2086  
2087  
static LS standardFunctions(LS tok) {
2088  
  if (sf == null) {
2089  
    S _761 = cacheGet("#761");
2090  
    if (_761ok == null)
2091  
      _761ok = isBracketHygienic(_761);
2092  
    assertTrue("Whoa! #761 truncated?", _761ok);
2093  
    L<S> standardFunctions = concatLists(
2094  
      (L) loadVariableDefinition(_761, "standardFunctions"),
2095  
      (L) loadVariableDefinition(cacheGet("#1006654"), "standardFunctions"));
2096  
2097  
    sf = new HashMap;
2098  
    for (S x : standardFunctions) {
2099  
      S[] f = x.split("/");
2100  
      sf.put(f[1], f[0]);
2101  
    }
2102  
  }
2103  
  
2104  
  SS sfMap = combinedMap(extraStandardFunctions, sf);
2105  
    
2106  
  for (int i = 0; ; i++) {
2107  
    print("Looking for required functions");
2108  
    Set<S> defd = new HashSet(findFunctions(tok));
2109  
    
2110  
    int j;
2111  
    while ((j = jfind(tok, "should not include function *.")) >= 0) {
2112  
      S fname = tok.get(j+8);
2113  
      shouldNotIncludeFunction.add(fname);
2114  
      clearAllTokens(subList(tok, j, j+12));
2115  
    }
2116  
2117  
    while ((j = jfind(tok, "do not include function *.")) >= 0) {
2118  
      S fname = tok.get(j+8);
2119  
      doNotIncludeFunction.add(fname);
2120  
      clearAllTokens(subList(tok, j, j+12));
2121  
    }
2122  
    
2123  
    while ((j = jfind(tok, "need latest <id>.")) >= 0) {
2124  
      S t = tok.get(j+4);
2125  
      needLatest.add(t);
2126  
      doNotIncludeClass.remove(t);
2127  
      clearAllTokens(subList(tok, j, j+8));
2128  
    }
2129  
    
2130  
    grabImportedStaticFunctions(tok);
2131  
    doNotIncludeFunction.removeAll(needLatest);
2132  
    
2133  
    // changes tok
2134  
    Set<String> invocations = findFunctionInvocations(tok, sfMap, hardFunctionReferences, defd, true, mainClassName());
2135  
    /*if (invocations.contains("str"))
2136  
      print("==STR==" + join(tok) + "==STR==");*/
2137  
    if (!cic(definitions, "leanMode"))
2138  
      invocations.addAll(functionsToAlwaysInclude);
2139  
2140  
    //print("Functions invoked: " + structure(invocations));
2141  
    List<String> needed = diff(invocations, defd);
2142  
    for (S f : doNotIncludeFunction) needed.remove(f);
2143  
    if (needed.isEmpty())
2144  
      break;
2145  
    print("Adding functions: " + join(" " , needed));
2146  
    
2147  
    HashSet neededSet = new HashSet(needed);
2148  
    Collection<S> bad = setIntersection(neededSet, shouldNotIncludeFunction);
2149  
    if (nempty(bad)) {
2150  
      S msg = "INCLUDING BAD FUNCTIONS: " + sfu(bad);
2151  
      print(msg);
2152  
      print(join(tok));
2153  
      fail(msg);
2154  
    }
2155  
      
2156  
    new L<S> added;
2157  
    new L<Future<S>> parts;
2158  
    new L<S> preload;
2159  
    
2160  
    for (S x : needed)
2161  
      if (sfMap.containsKey(x))
2162  
        preload.add(sfMap.get(x));
2163  
    print("Preloading: " + preload);
2164  
    cachePreload(preload);
2165  
    
2166  
    for (String x : cloneList(needed)) {
2167  
      if (defd.contains(x)) continue;
2168  
      
2169  
      String id = sfMap.get(x);
2170  
      if (id == null) {
2171  
        print("Standard function " + x + " not found.");
2172  
        needed.remove(x);
2173  
        continue;
2174  
      }
2175  
      //print("Adding function: " + x + " (" + id + ")");
2176  
       
2177  
      S function = cacheGet(id) + "\n";
2178  
      //if (("\n" + function).contains("\n!")) print("Warning: " + id + " contains translators.");
2179  
      
2180  
      if (cacheStdFunctions) {
2181  
        long _id = psI(id);
2182  
        CachedInclude ci = cachedIncludes.get(_id);
2183  
        if (ci == null) {
2184  
          cachedIncludes.put(_id, ci = new CachedInclude(_id));
2185  
          //println("Caching include " + _id + ", l=" + l(cachedIncludes));
2186  
        }
2187  
        function += "\n";
2188  
        fS _function = function;
2189  
        if (neq(ci.javax, function)) {
2190  
          print("Compiling function: " + x);
2191  
          ci.javax = function;
2192  
          ci.java = executor.submit(new Callable<S>() {
2193  
            public S call() {
2194  
              // We assume that variables made with makeVar() will always be local to some block
2195  
              varCountByThread.set(null);
2196  
              ret join(localStuff1(jtok(_function)));
2197  
            }
2198  
          });
2199  
          ci.realJava = null;
2200  
        }
2201  
        parts.add(ci.javaFuture());
2202  
      } else
2203  
        parts.add(nowFuture(function));
2204  
        
2205  
      added.add(x);
2206  
      Collection<S> newFunctions = new HashSet(findFunctionDefs(javaTok(function)));
2207  
      defd.addAll(newFunctions);
2208  
      for (S f : newFunctions)
2209  
        if (!addedFunctions.add(f)) {
2210  
          printSources(tok);
2211  
          fail("Trying to add function " + f + " again - main class syntax broken!");
2212  
        }
2213  
    }
2214  
    
2215  
    print("Getting " + nParts(parts));
2216  
    S text = lines(getAllFutures(parts));
2217  
    print("Including " + nParts(parts));
2218  
    tok = includeInMainLoaded(tok, text);
2219  
      
2220  
    // defd = new HashSet(findFunctions(tok));
2221  
    //print("Functions added: " + joinWithSpace(added));
2222  
    
2223  
    for (String x : needed)
2224  
      if (!defd.contains(x)) {
2225  
        print(join(tok));
2226  
        fail("Function not defined properly: " + x);
2227  
      }
2228  
    //print("Iteration " + (i+2));
2229  
    
2230  
    print("Processing definitions");
2231  
    
2232  
    dontPrint('definitions); tok_definitions(tok);
2233  
    dontPrint('ifndef); tok_ifndef(tok);
2234  
    dontPrint('ifdef); tok_ifdef(tok);
2235  
    
2236  
    if (i >= 1000) fail("Too many iterations");
2237  
  }
2238  
  
2239  
  ret tok;
2240  
}
2241  
2242  
// TODO: skip functions defined in inner classes!
2243  
static LS findFunctions(L<S> tok) {
2244  
  //ret findFunctionDefinitions(join(findMainClass(tok)));
2245  
  ret findFunctionDefs(findMainClass(tok));
2246  
}
2247  
2248  
static S cacheGet(S snippetID) {
2249  
  snippetID = formatSnippetID(snippetID);
2250  
  S text = snippetCache.get(snippetID);
2251  
  if (text == null) {
2252  
    text = loadSnippet(snippetID);
2253  
    // very early processing/checks for includes
2254  
    
2255  
    if (hasUnclosedStringLiterals(text))
2256  
      fail("Unclosed string literals in " + snippetID);
2257  
      
2258  
    if (regexpContains("\\bscope\\b", text)) {
2259  
      LS tok = javaTok(text);
2260  
      tok_scopes(tok, autoCloseScopes := true);
2261  
      text = join(tok);
2262  
    }
2263  
    
2264  
    snippetCache.put(snippetID, text);
2265  
  }
2266  
  ret text;
2267  
}
2268  
2269  
static void cachePreload(Collection<S> ids) {
2270  
  new L<S> needed;
2271  
  for (S id : ids)
2272  
    if (!snippetCache.containsKey(formatSnippetID(id)))
2273  
      needed.add(formatSnippetID(id));
2274  
  if (l(needed) > 1) {
2275  
    L<S> texts = loadSnippets(needed);
2276  
    for (int i = 0; i < l(needed); i++)
2277  
      if (texts.get(i) != null)
2278  
        snippetCache.put(needed.get(i), texts.get(i));
2279  
  }
2280  
}
2281  
2282  
static L<S> jtok(L<S> tok) {
2283  
  ret jtok(join(tok));
2284  
}
2285  
2286  
static L<S> jtok(S s) {
2287  
  ret indexTokenList(javaTok(s));
2288  
}
2289  
2290  
static HashSet<S> haveClasses_actual(L<S> tok) {
2291  
  new HashSet<S> have;
2292  
  for (L<S> c : innerClassesOfMain(tok))
2293  
    have.add(getClassDeclarationName(c));
2294  
  ret have;
2295  
}
2296  
2297  
static HashSet<S> haveClasses_addImported(LS tok, HashSet<S> have, bool mainLevel default true) {
2298  
  have.addAll(tok_importedClassNames(tok, mainLevel ? lambda2 onImportFound : null));
2299  
  have.addAll(usualJavaClassNames()); // for S => S.class
2300  
  ret have;
2301  
}
2302  
2303  
// works on Java level (no "sclass" etc)
2304  
// returns list of classes we have (useful for other processing)
2305  
static HashSet<S> addStandardClasses_v2(L<S> tok) {
2306  
  if (lclasses == null) {
2307  
    S sc = cacheGet(#1003674);
2308  
    lclasses = new L;
2309  
    for (S line : tlft_j(sc)) {
2310  
      int idx = line.indexOf('/');
2311  
      lclasses.addAll(ll(line.substring(0, idx), line.substring(idx+1)));
2312  
    }
2313  
  }
2314  
  L<S> definitions = lclasses;
2315  
2316  
  for (int safety = 0; safety < 10; safety++) {
2317  
    HashSet<S> have = haveClasses_actual(tok);
2318  
    haveClasses_addImported(tok, have);
2319  
    have.addAll(keys(rewrites));
2320  
2321  
    int j;
2322  
    while ((j = jfind(tok, "should not include class *.")) >= 0) {
2323  
      S cname = tok.get(j+8);
2324  
      shouldNotIncludeClass.add(cname);
2325  
      clearAllTokens(subList(tok, j, j+12));
2326  
    }
2327  
    
2328  
    while ((j = jfind(tok, "do not include class *.")) >= 0) {
2329  
      S name = tok.get(j+8);
2330  
      if (!needLatest.contains(name)) doNotIncludeClass.add(name);
2331  
      clearAllTokens(subList(tok, j, j+12));
2332  
    }
2333  
    
2334  
    new SS need;
2335  
    new Set<S> snippets;
2336  
    Set<S> idx = tokenIndexWithoutIfclass_forStdClasses(tok);
2337  
    
2338  
    while ((j = jfind(tok, "please include class *.")) >= 0) {
2339  
      S cname = tok.get(j+6);
2340  
      idx.add(cname);
2341  
      clearAllTokens(subList(tok, j, j+10));
2342  
    }
2343  
2344  
    for (int i = 0; i+1 < l(definitions); i += 2) {
2345  
      S className = definitions.get(i);
2346  
      S snippetID = fsI(definitions.get(i+1));
2347  
      if (idx.contains(className) && !have.contains(className) && snippets.add(snippetID))
2348  
        need.put(className, snippetID);
2349  
    }
2350  
    if (hasDef("SymbolAsString")) {
2351  
      print("Have SymbolAsString.");
2352  
      if (need.containsKey("Symbol")) {
2353  
        print("Have Symbol.");
2354  
        need.remove("Symbol");
2355  
      }
2356  
    } else
2357  
      print("No SymbolAsString.");
2358  
      
2359  
    removeAll(need, doNotIncludeClass);
2360  
    if (empty(need)) ret have;
2361  
  
2362  
    for (S className : keys(need))
2363  
      if (shouldNotIncludeClass.contains(className)) {
2364  
        S msg = "INCLUDING BAD CLASS: " + className;
2365  
        print(msg);
2366  
        print(join(tok));
2367  
        fail(msg);
2368  
      }
2369  
      
2370  
    cachePreload(values(need));
2371  
    
2372  
    new LPair<S, CachedInclude> parts; // class name, Java code
2373  
    
2374  
    print("Adding classes: " + joinWithSpace(keys(need)));
2375  
    for (S className : keys(need)) {
2376  
      if (have.contains(className)) continue; // intermittent add
2377  
      S snippetID = need.get(className);
2378  
      //print("Adding class " + className + " / " + snippetID);
2379  
      snippetID = fsI(snippetID);
2380  
      S text = cacheGet(snippetID) + "\n";
2381  
      
2382  
      assertTrue(cacheStdClasses);
2383  
      long _id = psI(snippetID);
2384  
      CachedInclude ci = cachedIncludes.get(_id);
2385  
      if (ci == null) cachedIncludes.put(_id, ci = new CachedInclude(_id));
2386  
      if (neq(ci.javax, text)) {
2387  
        print("Compiling class: " + className);
2388  
        ci.javax = text;
2389  
        ci.java = executor.submit(new Callable<S>() {
2390  
          public S call() {
2391  
            // We assume that variables made with makeVar() will always be local to some block
2392  
            varCountByThread.set(null);
2393  
            ret join(localStuff1(jtok(text)));
2394  
          }
2395  
        });
2396  
        ci.realJava = null;
2397  
      }
2398  
      parts.add(pair(className, ci));
2399  
    }
2400  
    
2401  
    new StringBuilder buf;
2402  
    for (Pair<S, CachedInclude> p : parts) {
2403  
      S className = p.a;
2404  
      LS ct = javaTok(p.b.java());
2405  
      new SS rewritten;
2406  
      tok_findAndClearRewrites(ct, rewritten);
2407  
      if (rewritten.containsKey(className))
2408  
        have.add(className);
2409  
      for (LS c : allClasses(ct)) {
2410  
        S name = getClassDeclarationName(c);
2411  
        have.add(name);
2412  
      }
2413  
      
2414  
      haveClasses_addImported(ct, have, false);
2415  
      
2416  
      if (!have.contains(className))
2417  
        fail("Wrongly defined class: " + className + " / " + p.b.snippetID + "\n\n" + p.b.java());
2418  
      if (!addedClasses.add(className)) {
2419  
        printSources(tok);
2420  
        fail("Trying to add class " + className + " again - main class syntax broken!");
2421  
      }
2422  
      buf.append(p.b.java());
2423  
    } // for part
2424  
    
2425  
    tok = includeInMainLoaded(tok, str(buf));
2426  
  }
2427  
  fail("safety 10");
2428  
}
2429  
2430  
static Set<S> expandableClassNames = lithashset("BigInteger");
2431  
2432  
// no reTok - leaves tok dirty
2433  
// magically append ".class" to class name references
2434  
svoid expandClassReferences_lazy(L<S> tok, Set<S> classNames, L<IntRange> reToks default null) {
2435  
  for (int i = 3; i+2 < l(tok); i += 2) {
2436  
    S t = tok.get(i);
2437  
    
2438  
    // skip implements/extends/throws lists
2439  
    if (eqOneOf(t, "implements", "extends", "throws")) {
2440  
      i = tok_endOfImplementsList(tok, i);
2441  
      continue;
2442  
    }
2443  
    
2444  
    if (classNames.contains(t) || expandableClassNames.contains(t)) {
2445  
      S s = tok.get(i-2); t = tok.get(i+2);
2446  
      // Now s is token before class name, t is token after class name
2447  
      // TODO: This whole logic ain't very good
2448  
      // (Hard to distinguish between "Int.class" as an argument
2449  
      // and "Int" as a type parameter.)
2450  
      if (eqOneOf(s, "instanceof", "new", ".", "<", ">", "/", "nu")) continue;
2451  
      if (eq(t, ":")) continue; // e.g. String::concat
2452  
      if (isInteger(s)) continue;
2453  
      if (isIdentifier(s) && !eqOneOf(s, "ret", "return")) continue;
2454  
        
2455  
      if (eq(t, ",") && isIdentifier(get(tok, i+4)) && eqGet(tok, i+6, ">")) continue; // e.g. T3<L<S>, S, S>
2456  
      if (eq(s, ",") && isIdentifier(get(tok, i-4)) &&
2457  
        (eqGet(tok, i-6, "<") || eqGet(tok, i-6, ",")
2458  
        && isIdentifier(get(tok, i-8)) && eqGet(tok, i-10, "<"))) continue; // e.g. T3<S, S, S> or IF3<S, S, S, S>
2459  
      if (eq(s, ",") && eqOneOf(_get(tok, i-6), "implements", "throws")) continue;
2460  
      
2461  
      // check for cast
2462  
      if (eq(s, "(") && eq(t, ")") && i >= 5) {
2463  
        if (!eqOneOf(get(tok, i+4), "{", ";")) {
2464  
          S x = tok.get(i-4);
2465  
          if (!isIdentifier(x)) continue;
2466  
          if (eqOneOf(x, "ret", "return")) continue;
2467  
        }
2468  
      }
2469  
      
2470  
      // check following token
2471  
      if (eqOneOf(t, ",", ")", ";", ":", "|")) {
2472  
        tok.set(i, tok.get(i) + ".class");
2473  
        reToks?.add(intRange(i, i+1));
2474  
      }
2475  
    }
2476  
  }
2477  
}
2478  
2479  
svoid expandClassReferences(L<S> tok, Set<S> classNames) {
2480  
  new L<IntRange> reToks;
2481  
  expandClassReferences_lazy(tok, classNames, reToks);
2482  
  reTok_multi(tok, reToks);
2483  
}
2484  
2485  
// "<id>/<ClassName>" => "((ClassName) <id>)"
2486  
static void slashCasts(L<S> tok, final Set<S> classNames) {
2487  
  /*jreplace(tok, "<id>/<id>", "(($3) $1)", tokcondition {
2488  
    ret classNames.contains(tok.get(i+5));
2489  
  });*/
2490  
  int n = l(tok)-4;
2491  
  for (int i = 1; i < n; i += 2)
2492  
    if (tok.get(i+2).equals("/") && isIdentifier(tok.get(i))
2493  
      && classNames.contains(tok.get(i+4)))
2494  
      replaceTokens_reTok(tok, i, i+5, "((" + tok.get(i+4) + ") " + tok.get(i) + ")");
2495  
}
2496  
2497  
// "<ClassName>(...)" => "new <ClassName>(...)"
2498  
// doesn't work at beginning of statement as we can't easily
2499  
// distinguish it from a constructor declaration.
2500  
static void newWithoutNew(L<S> tok, final Set<S> classNames) {
2501  
  TokCondition cond = newWithoutNew_condition(classNames);
2502  
  jreplace(tok, "<id>(", "new $1(", cond);
2503  
  // just two cases with type args for now
2504  
  jreplace(tok, "<id><<id>>(", "new $1<$3>(", cond);
2505  
  jreplace(tok, "<id><>(", "new $1<>(", cond);
2506  
}
2507  
2508  
static TokCondition newWithoutNew_condition(final Set<S> classNames) {
2509  
  ret tokcondition {
2510  
    if (!classNames.contains(tok.get(i+1))) false;
2511  
    S prev = _get(tok, i-1);
2512  
    bool ok = //!(eqGet(tok, i-3, "ifclass") && isIdentifier(prev))
2513  
      nempty(prev) // discarded ifclass
2514  
      && (eq(prev, ">") ? eqGet(tok, i-3, "-")
2515  
      : neqOneOf(prev, "new", ";", "}", "{", "public", "protected", "private", "."));
2516  
    //print("newWithoutNew: checking " + struct(subList(tok, i-3, i+2)) + " => " + ok);
2517  
    ret ok;
2518  
  };
2519  
}
2520  
2521  
static bool processConceptsDot(L<S> tok) {
2522  
  bool anyChange = false, change;
2523  
  do {
2524  
    change = false;
2525  
    for (int i : jfindAll(tok, "concepts."))
2526  
      if (contains(get(tok, i+3), "\n")) {
2527  
        replaceTokens(tok, i, i+3, "!" + "include once #1004863 // Dynamic Concepts");
2528  
        reTok(tok, i, i+3);
2529  
        change = anyChange = true;
2530  
        break;
2531  
      }
2532  
  } while (change);
2533  
  ret anyChange;
2534  
}
2535  
2536  
svoid caseAsVariableName(L<S> tok) {
2537  
  if (!tok.contains("case")) ret;
2538  
  for (int i = 1; i+2 < l(tok); i += 2) {
2539  
    S t = tok.get(i+2);
2540  
    if (tok.get(i).equals("case")
2541  
      && !(t.startsWith("'") || isInteger(t) || isIdentifier(t) || isQuoted(t)
2542  
        || eq(t, "-") && eqGet(tok, i+3, "") && isInteger(get(tok, i+4))))
2543  
      tok.set(i, "_case");
2544  
  }
2545  
}
2546  
2547  
static void continueAsFunctionName(L<S> tok) {
2548  
  jreplace(tok, "continue(", "_continue(");
2549  
}
2550  
2551  
// f bla => "bla" - and "please include function bla."
2552  
static void functionReferences(L<S> tok) {
2553  
  int i;
2554  
  
2555  
  jreplace_dyn(tok, "f-thread <id>", func(L<S> tok, int cIdx) {
2556  
    "dynamicCallableMC_thread(" + quote(tok.get(cIdx+6)) + ")"
2557  
  });
2558  
  
2559  
  S keyword = "f";
2560  
  while ((i = jfind(tok, keyword + " <id>", tokcondition {
2561  
    ret !eqOneOf(tok.get(i+3), "instanceof", "default");
2562  
  })) >= 0) {
2563  
    S f = tok.get(i+2);
2564  
    clearTokens(tok, i, i+2);
2565  
    tok.set(i+2, quote(f));
2566  
    reTok(tok, i, i+2);
2567  
    tok.set(l(tok)-1, last(tok) + "\nplease include function " + f + ".");
2568  
    reTok(tok, l(tok)-1, l(tok));
2569  
  }
2570  
  
2571  
  // r|rThread|rEnter|rThreadEnter|rEnterThread fname => r|rThread|... { fname() }
2572  
  while ((i = jfindOneOf_cond(tok, tokcondition {
2573  
    ret !eq(tok.get(i+3), "instanceof")
2574  
      && !eq(_get(tok, i-1), "cast");
2575  
  }, "r <id>", "rThread <id>", "rEnter <id>", "rThreadEnter <id>",
2576  
    "rEnterThread <id>")) >= 0) {
2577  
    S f = tok.get(i+2);
2578  
    replaceTokens(tok, i, i+3, tok.get(i) + " { " + f + "(); }");
2579  
    reTok(tok, i, i+3);
2580  
  }
2581  
  
2582  
  // dm_q fname => r_dm_q(r fname)
2583  
  jreplace(tok, "dm_q <id>", "r_dm_q(r $2)");
2584  
  
2585  
  // vf<S> fname => voidfunc(S s) { fname(s) }
2586  
  jreplace(tok, "vf<<id>> <id>", "voidfunc($3 a) { $5(a) }");
2587  
  
2588  
  // vf<L<S>> fname => voidfunc(L<S> a) { fname(a) }
2589  
  jreplace(tok, "vf<<id><<id>>> <id>", "voidfunc($3<$5> a) { $8(a) }");
2590  
  
2591  
  // construct<S> Entry => func(S s) -> Entry { new Entry(s) }
2592  
  jreplace(tok, "construct<<id>> <id>", "func($3 a) -> $5 { new $5(a) }");
2593  
  
2594  
  // f<S> fname => func -> S { fname() }
2595  
  jreplace(tok, "f<<id>> <id>", "func -> $3 { $5() }");
2596  
  
2597  
  // f<S, S> fname => func(S x) -> S { fname(x) }
2598  
  jreplace(tok, "f<<id>, <id>> <id>", "func($3 x) -> $5 { $7(x) }");
2599  
  
2600  
  // f<S, L<S>> fname => func(S x) -> L<S> { fname(x) }
2601  
  jreplace(tok, "f<<id>, <id><<id>>> <id>", "func($3 x) -> $5 $6 $7 $8 { $10(x) }");
2602  
  
2603  
  // f<L<S>, S> fname => func(L<S> x) -> S { fname(x) }
2604  
  jreplace(tok, "f<<id><<id>>, <id>> <id>", "func($3 $4 $5 $6 x) -> $8 { $10(x) }");
2605  
  
2606  
  // f<S, L<S>, S> fname => func(S x, L<S> y) -> S { fname(x, y) }
2607  
  jreplace(tok, "f<<id>, <id><<id>>, <id>> <id>", "func($3 x, $5 $6 $7 $8 y) -> $10 { $12(x, y) }");
2608  
  
2609  
  // if1 fname => a -> fname(a)
2610  
  // ivf1 fname => a -> fname(a)
2611  
  for (S _keyword : ll("if1", "ivf1"))
2612  
    jreplace_dyn(tok, _keyword + " <id>", func(LS tok, int i) -> S {
2613  
      S var = makeVar();
2614  
      ret var + " -> " + tok.get(i+2) + "(" + var + ")";
2615  
    });
2616  
}
2617  
2618  
static void quicknu(L<S> tok) {
2619  
  jreplace(tok, "nu <id>(", "nu($2.class, "); // not needed anymore
2620  
  jreplace(tok, "nu <id>", "new $2");
2621  
}
2622  
2623  
// fill variable innerClasses_list
2624  
static void innerClassesVar(L<S> tok, Set<S> have) {
2625  
  int i = jfind_check myInnerClasses_list(tok, ">myInnerClasses_list;");
2626  
  if (i < 0) ret;
2627  
  tok.set(i+4, "=litlist(\n" + joinQuoted(", ", have) + ");");
2628  
  reTok(tok, i+4, i+5);
2629  
}
2630  
2631  
// fill variable innerClasses_list
2632  
static void fillVar_transpilationDate(L<S> tok) {
2633  
  int i = jfind_check myTranspilationDate_value(tok, "long myTranspilationDate_value;");
2634  
  if (i < 0) ret;
2635  
  tok.set(i+4, " = " + now() + "L;");
2636  
  reTok(tok, i+4, i+5);
2637  
}
2638  
2639  
sbool ifclass_reTokImmediately = false;
2640  
sbool ifclass_noReTok = true;
2641  
2642  
// process ifclass x ... endif blocks
2643  
static void tok_ifclass(LS tok, Set<S> have) {
2644  
  tok_conditionals(tok, "ifclass", "endif", id -> contains(have, id), ifclass_reTokImmediately, ifclass_noReTok);
2645  
}
2646  
2647  
// returns number of changes
2648  
static int tok_conditionals(LS tok, S keyword, S keywordEnd, IPred<S> pred, bool reTokImmediately, bool noReTok) {
2649  
  int changes = 0;
2650  
  if (tok instanceof IContentsIndexedList) {
2651  
    int[] l = tok/IContentsIndexedList.indicesOf(keyword);
2652  
    for (int j = l(l)-1; j >= 0; j--) {
2653  
      int i = l[j];
2654  
      if (isIdentifier(get(tok, i+2))) {
2655  
        processConditional(tok, i, keyword, keywordEnd, pred, reTokImmediately && !noReTok);
2656  
        ++changes;
2657  
      }
2658  
    }
2659  
  } else {
2660  
    if (!tok.contains(keyword)) ret changes;
2661  
    int i = l(tok);
2662  
    while ((i = rjfind(tok, 1, i-1, keyword + " <id>")) >= 0) {
2663  
      ++changes;
2664  
      processConditional(tok, i, keyword, keywordEnd, pred, reTokImmediately && !noReTok);
2665  
    }
2666  
  }
2667  
  if (changes != 0 && !reTokImmediately && !noReTok) reTok(tok);
2668  
  //print(keyword + ": " + nChanges(changes));
2669  
  ret changes;
2670  
}
2671  
2672  
svoid processConditional(LS tok, int i, S keyword, S keywordEnd, IPred<S> pred, bool reTokImmediately) {
2673  
  int j = jfind(tok, i+4, keywordEnd);
2674  
  if (j < 0) j = l(tok)-1;
2675  
  S name = tok.get(i+2);
2676  
  bool has = pred.get(name);
2677  
  //print(keyword + " " + name + " => " + has);
2678  
  if (has) {
2679  
    clearTokens_maybeReTok(tok, j, j+1, reTokImmediately);
2680  
    clearTokens_maybeReTok(tok, i, i+3, reTokImmediately);
2681  
  } else
2682  
    clearTokens_maybeReTok(tok, i, j+1, reTokImmediately); // safer than before
2683  
}
2684  
2685  
// set flag *.
2686  
static void tok_definitions(L<S> tok) {
2687  
  int i;
2688  
  while ((i = jfind_check flag(tok, "set flag <id>.")) >= 0) {
2689  
    S fname = tok.get(i+4);
2690  
    print("Setting flag " + fname);
2691  
    definitions.add(fname);
2692  
    if (eqic(fname, "debug_jreplace")) set debug_jreplace;
2693  
    clearAllTokens(subList(tok, i, i+8));
2694  
  }
2695  
  
2696  
  while ((i = jfind_check flag(tok, "unset flag <id>.")) >= 0) {
2697  
    S fname = tok.get(i+4);
2698  
    print("Unsetting flag " + fname);
2699  
    definitions.remove(fname);
2700  
    clearAllTokens(subList(tok, i, i+8));
2701  
  }
2702  
}
2703  
2704  
// rewrite <id> [=|with|to] <definition>
2705  
// - a global version of "replace <id> with"
2706  
// new version - may not work yet
2707  
/*svoid tok_findAndClearRewrites(LS tok, SS newlyDefined default null) {
2708  
  tok_findRewrites(tok, newlyDefined, f -> {
2709  
    print("Have rewrite: " + f.token + " => " + f.replacement());
2710  
    clearTokens(f.tok, f.startCIdx(), f.endNIdx());
2711  
  });
2712  
}*/
2713  
2714  
2715  
// rewrite <id> [=|with|to] <definition>
2716  
// - a global version of "replace <id> with"
2717  
// old version (works)
2718  
svoid tok_findAndClearRewrites(LS tok, SS newlyDefined default null) {
2719  
  int i;
2720  
  while ((i = jfind(tok, "rewrite <id>", (_tok, nIdx) ->
2721  
    eqGetOneOf(_tok, nIdx+5, "with", "=", "to"))) >= 0) {
2722  
    S token = tok.get(i+2);
2723  
    int repStart = i+6;
2724  
    int repEnd = smartIndexOf(tok, repStart, ".");
2725  
    S replacement = joinSubList(tok, repStart, repEnd-1);
2726  
    clearTokens(tok, i, repEnd+1);
2727  
    mapPut(newlyDefined, token, replacement);
2728  
    rewrites.put(token, replacement);
2729  
    print("Have rewrite: " + token + " => " + replacement);
2730  
  }
2731  
}
2732  
2733  
static void tok_processRewrites(L<S> tok) {
2734  
  for (S token : keys(rewrites))
2735  
    jreplace(tok, token, rewrites.get(token));
2736  
}
2737  
2738  
// extend *. (set base class of main class)
2739  
static void tok_extend(L<S> tok) {
2740  
  int i;
2741  
  while ((i = jfind(tok, "extend <id>.")) >= 0) {
2742  
    mainBaseClass = tok.get(i+2);
2743  
    clearAllTokens(tok, i, i+7);
2744  
  }
2745  
}
2746  
2747  
// process ifndef x ... endifndef blocks
2748  
static void tok_ifndef(LS tok) {
2749  
  tok_conditionals(tok, "ifndef", "endifndef", id -> !definitions.contains(id), true, false);
2750  
}
2751  
  
2752  
// process ifdef x ... endifdef blocks
2753  
static void tok_ifdef(LS tok) {
2754  
  tok_conditionals(tok, "ifdef", "endifdef", id -> definitions.contains(id), true, false);
2755  
}
2756  
  
2757  
svoid conceptDeclarations(L<S> tok) {
2758  
  for (S kw : ll("concept", "sconcept")) {
2759  
    O cond = tokcondition { tok_addFieldOrder(tok, i+1); true; };
2760  
    bool re = false;
2761  
    if (jreplace(tok, kw + " <id> {", "static class $2 extends Concept {", cond)) re = true;
2762  
    if (jreplace(tok, kw + " <id> implements", "static class $2 extends Concept implements", cond)) re = true;
2763  
    if (jreplace(tok, kw + " <id>", "static class $2", cond)) re = true;
2764  
    if (re) reTok(tok);
2765  
  }
2766  
}
2767  
2768  
svoid shortenedSubconcepts(L<S> tok) {
2769  
  jreplace(tok, "<id> > <id> {", "concept $3 extends $1 {", tokcondition {
2770  
    bool b = (i == 0 || tok.get(i).contains("\n")) || eq(_get(tok, i-1), "abstract"); // only at beginning of line or after "abstract"
2771  
    //print("subconcept " + b + ": " + structure(subList(tok, i-1, i+5)));
2772  
    ret b;
2773  
  });
2774  
}
2775  
2776  
// -slightly experimental
2777  
// -do calculation in another thread, then return to AWT thread
2778  
// -must be placed in a block
2779  
// -transforms rest of block 
2780  
svoid unswing(L<S> tok) {
2781  
  int i;
2782  
  while ((i = jfind(tok, "unswing {")) >= 0) {
2783  
    int idx = i+2;
2784  
    int closingBracket = findEndOfBracketPart(tok, idx)-1;
2785  
    int endOfOuterBlock = findEndOfBracketPart(tok, closingBracket)-1;
2786  
    tok.set(i, "thread");
2787  
    tok.set(closingBracket, " awt {");
2788  
    tok.set(endOfOuterBlock, "}}}");
2789  
    reTok(tok, closingBracket-1, endOfOuterBlock+1);
2790  
  }
2791  
}
2792  
2793  
// -Syntax: lock theLock;
2794  
// -lock a lock, unlock at end of current block with finally
2795  
svoid lockBlocks(L<S> tok) {
2796  
  int i;
2797  
  while ((i = jfind(tok, "lock <id>", tokcondition { ret neq(tok.get(i+3), "instanceof"); })) >= 0) {
2798  
    int semicolon = findEndOfStatement(tok, i)-1;
2799  
    S var = makeVar();
2800  
    int endOfOuterBlock = findEndOfBracketPart(tok, semicolon)-1;
2801  
    replaceTokens(tok, i, semicolon+1,
2802  
      "Lock " + var + " = " + joinSubList(tok, i+2, semicolon-1) + "; lock(" + var + "); try {");
2803  
    tok.set(endOfOuterBlock, "} finally { unlock(" + var + "); } }");
2804  
    reTok(tok, i, endOfOuterBlock+1);
2805  
  }
2806  
}
2807  
2808  
// -Syntax: temp Bla bla = bla();
2809  
// -expands to try(Bla bla = bla()) { ... } with rest of block inside
2810  
svoid tempBlocks(L<S> tok) {
2811  
  int i;
2812  
  jreplace_dyn(tok, "temp (<id>) <id>", (_tok, cIdx) -> {
2813  
    S var = makeVar(), type = tok.get(cIdx+4), firstTokenOfExpr = tok.get(cIdx+8);
2814  
    ret "temp \*type*/ \*var*/ = cast \*firstTokenOfExpr*/";
2815  
  });
2816  
  
2817  
  jreplace(tok, "temp <id> =", "temp var $2 =");
2818  
  
2819  
  while ((i = jfind(tok, "temp <id>")) >= 0) {
2820  
    int semicolon = findEndOfStatement(tok, i)-1;
2821  
    int endOfOuterBlock = findEndOfBracketPart(tok, semicolon)-1;
2822  
    L<S> sub = subList(tok, i-1, semicolon);
2823  
    int eq = subList(sub, 0, smartIndexOfOneOf(sub, "{", "(")).indexOf("=");
2824  
    S var;
2825  
    if (eq >= 0)
2826  
      var = sub.get(eq-2);
2827  
    else {
2828  
      // no var name, e.g. temp newThoughtSpace();
2829  
      var = makeVar();
2830  
      tok.set(i+2, "AutoCloseable " + var + " = " + tok.get(i+2));
2831  
    }
2832  
      
2833  
    //tok.set(i, "try (");
2834  
    //tok.set(semicolon, ") {";
2835  
    //tok.set(endOfOuterBlock, "}}");
2836  
    
2837  
    tok.set(i, "");
2838  
    tok.set(semicolon, "; try {");
2839  
    tok.set(endOfOuterBlock, "} finally { _close(" + var + "); }}");
2840  
    
2841  
    reTok(tok, i, endOfOuterBlock+1);
2842  
  }
2843  
}
2844  
2845  
svoid forgetCachedIncludes {
2846  
  cachedIncludes.clear();
2847  
}
2848  
2849  
// TODO: when to do this / merge contents if there are multiple transpilers?
2850  
svoid cleanMeUp {
2851  
  for (CachedInclude ci : values(cachedIncludes))
2852  
    ci.clean();
2853  
  vmKeepWithProgramMD5_save('cachedIncludes);
2854  
}
2855  
2856  
svoid printSources(L<S> tok) {
2857  
  S src = join(tok);
2858  
  print("----");
2859  
  print(src);
2860  
  print("----");
2861  
  print("Bracket hygiene: " + testBracketHygiene2(src));
2862  
}
2863  
2864  
svoid tok_quickInstanceOf(L<S> tok, final Set<S> haveClasses) {
2865  
  if (!quickInstanceOfEnabled) ret;
2866  
  // "x << X" or "x >> X" => "x instanceof X"
2867  
  for (S op : ll("<<", ">>"))
2868  
    jreplace(tok, "<id> " + op + " <id>", "$1 instanceof $4", tokcondition {
2869  
      ret haveClasses.contains(tok.get(i+7))
2870  
        && !eqOneOf(tok.get(i-1), "<", "extends", "implements");
2871  
    });
2872  
}
2873  
2874  
sbool hasDef aka isDef(S s) {
2875  
  ret definitions.contains(s);
2876  
}
2877  
2878  
svoid tok_shortFinals(L<S> tok) {
2879  
  jreplace(tok, "fS", "final S");
2880  
  jreplace(tok, "fO", "final O");
2881  
  jreplace(tok, "fL", "final L");
2882  
  jreplace(tok, "fMap", "final Map");
2883  
  jreplace(tok, "fRunnable", "final Runnable");
2884  
  jreplace(tok, "f int", "final int");
2885  
}
2886  
2887  
svoid tok_mainClassNameAndPackage(LS tok) {
2888  
  int i;
2889  
  if ((i = jfind(tok, "mainClassName <id>")) >= 0) {
2890  
    mainClassName = tok.get(i+2);
2891  
    if (eqGet(tok, i+4, ".") && isIdentifier(get(tok, i+6))) {
2892  
      mainPackage = mainClassName;
2893  
      mainClassName = tok.get(i+6);
2894  
      clearTokensAndReTok(tok, i, i+7);
2895  
    } else
2896  
      clearTokensAndReTok(tok, i, i+3);
2897  
  }
2898  
  
2899  
  if ((i = jfind(tok, "mainPackage <id>")) >= 0) {
2900  
    int j = i+2;
2901  
    while (subListEquals(tok, j+1, "", ".", "") && isIdentifier(get(tok, j+4)))
2902  
      j += 4;
2903  
    mainPackage = joinSubList(tok, i+2, j+1);
2904  
    clearTokens_reTok(tok, i, j+1);
2905  
  }
2906  
}
2907  
2908  
svoid defineMapLikesEtc(LS tok) {
2909  
  defineMapLikes(tok);
2910  
  defineLambdaMapLikes(tok);
2911  
  defineCurry1Likes(tok);
2912  
  defineMapMethodLikes(tok);
2913  
  defineNuLikes(tok);
2914  
  defineXLikes(tok, "getLike", getLikeFunctions);
2915  
  defineXLikes(tok, "lambdaMethod0Like", lambdaMethod0LikeFunctions);
2916  
  defineXLikes(tok, "lambda0Like", lambda0LikeFunctions);
2917  
}
2918  
2919  
svoid defineMapLikes(LS tok) {
2920  
  int i;
2921  
  while ((i = jfind(tok, "mapLike <id>")) >= 0) {
2922  
    mapLikeFunctions.add(printIf(printMapLikes(), "mapLike", tok.get(i+2)));
2923  
    clearTokens_reTok(tok, i, i+2);
2924  
  }
2925  
}
2926  
2927  
svoid defineLambdaMapLikes(LS tok) {
2928  
  int i;
2929  
  while ((i = jfind(tok, "lambdaMapLike <id>")) >= 0) {
2930  
    lambdaMapLikeFunctions.add(printIf(printMapLikes(), "lambdaMapLike", tok.get(i+2)));
2931  
    clearTokens_reTok(tok, i, i+2);
2932  
  }
2933  
}
2934  
2935  
svoid defineCurry1Likes(LS tok) {
2936  
  int i;
2937  
  while ((i = jfind(tok, "curry1Like <id>")) >= 0) {
2938  
    curry1LikeFunctions.add(printIf(printMapLikes(), "curry1Like", tok.get(i+2)));
2939  
    clearTokens_reTok(tok, i, i+2);
2940  
  }
2941  
}
2942  
2943  
svoid defineMapMethodLikes(LS tok) {
2944  
  int i;
2945  
  while ((i = jfind(tok, "mapMethodLike <id>")) >= 0) {
2946  
    mapMethodLikeFunctions.add(printIf(printMapLikes(), "mapMethodLike", tok.get(i+2)));
2947  
    clearTokens_reTok(tok, i, i+2);
2948  
  }
2949  
}
2950  
2951  
// functions that work like "nu" syntactically (accept a class as "super-first" parameter [left of the bracket])
2952  
svoid defineNuLikes(LS tok) {
2953  
  int i;
2954  
  while ((i = jfind(tok, "nuLike <id>")) >= 0) {
2955  
    nuLikeFunctions.add(printIf(printMapLikes(), "nuLike", tok.get(i+2)));
2956  
    clearTokens_reTok(tok, i, i+2);
2957  
  }
2958  
}
2959  
2960  
svoid defineXLikes(LS tok, S keyword, Set<S> xLikeFunctions) {
2961  
  int i;
2962  
  while ((i = jfind(tok, keyword + " <id>")) >= 0) {
2963  
    xLikeFunctions.add(printIf(printMapLikes(), keyword, tok.get(i+2)));
2964  
    clearTokens_reTok(tok, i, i+2);
2965  
  }
2966  
}
2967  
2968  
svoid defineExtraSF(LS tok) {
2969  
  int i;
2970  
  IntRange reTok = null;
2971  
  while ((i = jfind(tok, "function <id> is in *.")) >= 0) {
2972  
    extraStandardFunctions.put(tok.get(i+2), fsI(unquote(tok.get(i+8))));
2973  
    clearTokens(tok, i, i+12);
2974  
    reTok = combineIntRanges(reTok, intRange(i, i+12));
2975  
  }
2976  
  reTok(tok, reTok);
2977  
}
2978  
2979  
sbool tok_applyAllXLikeFunctions(LS tok) {
2980  
  new L<IntRange> reToks;
2981  
  for (int i : jfindAll(tok, "<id> <id> (")) {
2982  
    S f = tok.get(i), arg = tok.get(i+2), replacement = null;
2983  
    if (contains(mapLikeFunctions, f))
2984  
      replacement = "\*f*/(f \*arg*/,";
2985  
    else if (contains(lambdaMapLikeFunctions, f))
2986  
      replacement = "\*f*/(lambda1 \*arg*/,";
2987  
    else if (contains(curry1LikeFunctions, f))
2988  
      replacement = "\*f*/(lambda2 \*arg*/,";
2989  
    else if (contains(mapMethodLikeFunctions, f))
2990  
      replacement = "\*f*/(\*quote(arg)*/,";
2991  
    else if (contains(nuLikeFunctions, f))
2992  
      replacement = "\*f*/(\*arg*/.class,";
2993  
    else if (contains(getLikeFunctions, f))
2994  
      replacement = "\*f*/(lambdaField \*arg*/,";
2995  
    else if (contains(lambdaMethod0LikeFunctions, f))
2996  
      replacement = "\*f*/(methodLambda0 \*arg*/,";
2997  
    else if (contains(lambda0LikeFunctions, f))
2998  
      replacement = "\*f*/(lambda0 \*arg*/,";
2999  
    
3000  
    if (replacement != null)
3001  
      replaceTokens_reTokLater(tok, reToks, i, i+5, replacement + " ");
3002  
  }
3003  
  reTok_multi(tok, reToks);
3004  
  ret nempty(reToks);
3005  
}
3006  
3007  
/*sbool tok_applyMapLikeFunctions(LS tok, final Set<S> mapLikeFunctions) {
3008  
  // map funcname(...) => map(f funcname, ...)
3009  
  // filter funcname(...) => filter(f funcname, ...)
3010  
  // ...
3011  
  ret jreplace(tok, "<id> <id>(", "$1(f $2,", func(L<S> tok, int i) -> bool {
3012  
    contains(mapLikeFunctions, tok.get(i+1))
3013  
  });
3014  
}*/
3015  
3016  
/*sbool tok_applyLambdaMapLikeFunctions(LS tok, final Set<S> lambdaMapLikeFunctions) {
3017  
  // mapNonNulls funcname(...) => mapNonNulls(lambda1 funcname, ...)
3018  
  // mapKeysAndValues funcname(...) => mapKeysAndValues(lambda1 funcname, ...)
3019  
  // ...
3020  
  ret jreplace(tok, "<id> <id>(", "$1(lambda1 $2,", func(L<S> tok, int i) -> bool {
3021  
    contains(lambdaMapLikeFunctions, tok.get(i+1))
3022  
  });
3023  
}*/
3024  
3025  
/*sbool tok_applyCurry1LikeFunctions(LS tok, final Set<S> curry1LikeFunctions) {
3026  
  // curry1 funcname(...) => curry1(lambda2 funcname, ...)
3027  
  ret jreplace(tok, "<id> <id>(", "$1(lambda2 $2,", func(L<S> tok, int i) -> bool {
3028  
    contains(curry1LikeFunctions, tok.get(i+1))
3029  
  });
3030  
}*/
3031  
3032  
/*sbool tok_applyMapMethodLikeFunctions(LS tok, final Set<S> mapMethodLikeFunctions) {
3033  
  // mapMethod funcname(...) => mapMethod('funcname, ...)
3034  
  // collect funcname(...) => collect('funcname, ...)
3035  
  // ...
3036  
  ret jreplace_dyn(tok, "<id> <id>(",
3037  
    func(L<S> tok, int cIdx) -> S { tok.get(cIdx) + "(" + quote(tok.get(cIdx+2)) + "," },
3038  
    func(L<S> tok, int i) -> bool {
3039  
      contains(mapMethodLikeFunctions, tok.get(i+1))
3040  
    });
3041  
}*/
3042  
3043  
svoid runMetaPostBlocks(LS tok) {
3044  
  for ping (S code : unnull(metaPostBlocks)) {
3045  
    S snippetID = standardFunctionSnippet(assertIdentifier(code));
3046  
    if (empty(snippetID))
3047  
      fail("meta-post function not found: " + code);
3048  
    call(hotwireCached(snippetID), code, tok);
3049  
    //callF(codeToFunctionOnArbitraryType(code, "LS", L, "tok"), tok);
3050  
  }
3051  
}
3052  
3053  
svoid runTransformers(LS tok, LS transformers) {
3054  
  fOr ping (S code : transformers)
3055  
    tok_runMetaTransformer(tok, code);
3056  
}
3057  
3058  
/*sbool tok_applyNuLikeFunctions(LS tok, final Set<S> nuLikeFunctions) {
3059  
  // nu ClassName(...) => nu(ClassName, ...)
3060  
  // ...
3061  
  ret jreplace_dyn(tok, "<id> <id>(",
3062  
    func(L<S> tok, int cIdx) -> S { tok.get(cIdx) + "(" + tok.get(cIdx+2) + ".class," },
3063  
    func(L<S> tok, int i) -> bool {
3064  
      contains(nuLikeFunctions, tok.get(i+1))
3065  
    });
3066  
}*/
3067  
3068  
/*sbool tok_applyGetLikeFunctions(LS tok, Set<S> getLikeFunctions) {
3069  
  // get fieldName(...) => get(fieldLambda fieldName, ...)
3070  
  // ...
3071  
  ret jreplace_dyn(tok, "<id> <id>(",
3072  
    func(L<S> tok, int cIdx) -> S { tok.get(cIdx) + "(lambdaField " + tok.get(cIdx+2) + "," },
3073  
    func(L<S> tok, int i) -> bool {
3074  
      contains(getLikeFunctions, tok.get(i+1))
3075  
    });
3076  
}*/
3077  
3078  
sbool metaCodeAllowed() {
3079  
  ret allowMetaCode || containsIC(definitions, "allowMetaCode");
3080  
}
3081  
3082  
static LS indexTokenList(LS tok) {
3083  
  if (useIndexedList2) ret indexedList2(tok);
3084  
  if (useTokenIndexedList) ret tokenIndexedList3(tok);
3085  
  ret tok;
3086  
}
3087  
3088  
svoid tok_earlyGeneralStuff(LS tok) {
3089  
  // self-compile construct (TODO)
3090  
  /*jreplace(tok, "self-compile", (tok, iOpening, iClosing) -> S[] {
3091  
  
3092  
    selfCompiling
3093  
  });*/
3094  
  
3095  
  tok_standardBot1(tok);
3096  
  tok_processSimplified(tok);
3097  
  tok_compactModules(tok);
3098  
  
3099  
  tok_metaFor(tok);
3100  
  
3101  
  // is, short for "implements"
3102  
  jreplace(tok, "is <id>", "implements $2", tokCondition {
3103  
    ret !eqGetOneOf(tok, i+3, "a", "in"); // "is a", "is in" are defined as something else
3104  
  });
3105  
}
3106  
3107  
svoid lambdaReferences(LS tok) {
3108  
  // lambda0 myFunction => () -> myFunction()
3109  
  jreplace(tok, "lambda0 <id>", "() -> $2()");
3110  
  
3111  
  // lambda1 myFunction => var123 -> myFunction(var123)
3112  
  jreplace_dyn(tok, "lambda1 <id>", func(L<S> tok, int cIdx) {
3113  
    S var = makeVar();
3114  
    S s = var + " -> " + tok.get(cIdx+2) + "(" + var + ")";
3115  
    ret eqGet(tok, cIdx-2, ")") ? roundBracket(s) : s;
3116  
  });
3117  
  
3118  
  // lambda2 myFunction => (a, b) -> myFunction(a, b)
3119  
  jreplace_dyn(tok, "lambda2 <id>", func(LS tok, int cIdx) {
3120  
    S a = makeVar();
3121  
    S b = makeVar();
3122  
    S s = "(\*a*/, \*b*/) -> \*tok.get(cIdx+2)*/(\*a*/, \*b*/)";
3123  
    ret eqGet(tok, cIdx-2, ")") ? roundBracket(s) : s;
3124  
  });
3125  
  
3126  
  // methodLambda0 methodName => var123 -> var123.methodName()
3127  
  jreplace_dyn(tok, "methodLambda0 <id>", func(LS tok, int cIdx) {
3128  
    S var = makeVar();
3129  
    ret var + " -> " + var + "." + tok.get(cIdx+2) + "()";
3130  
  });
3131  
  
3132  
  // fieldLambda fieldName => var123 -> var123.fieldName
3133  
  jreplace_dyn(tok, "fieldLambda <id>", func(LS tok, int cIdx) {
3134  
    S var = makeVar();
3135  
    ret var + " -> " + var + "." + tok.get(cIdx+2);
3136  
  });
3137  
}
3138  
3139  
svoid clearSnippetCache {
3140  
  snippetCache.clear();
3141  
  sf = null;
3142  
  lclasses = null;
3143  
}
3144  
3145  
svoid mediumRefresh {
3146  
  clearSnippetCache();
3147  
  print("Medium-refreshed transpiler " + mc());
3148  
}
3149  
3150  
svoid jreplace_performing(LS tok, int i, int end, S expansion) {
3151  
  if (debug_jreplace)
3152  
    print("jreplace: " + quote(joinSubList(tok, i, end)) + " => " + quote(expansion));
3153  
}
3154  
3155  
sS mainClassName() {
3156  
  ret or(mainClassName, "main");
3157  
}
3158  
3159  
svoid grabImportedStaticFunctions(LS tok) {
3160  
  for (S name : tok_importedStaticFunctionNamesWithPackages(tok)) {
3161  
    int idx = lastIndexOf(name, '.');
3162  
    S pkg = takeFirst(idx, name);
3163  
    S functionName = dropFirst(idx+1, name);
3164  
    //print(functionName + " => " + pkg);
3165  
    doNotIncludeFunction.add(functionName);
3166  
    functionToPackage.put(functionName, pkg);
3167  
  }
3168  
}
3169  
3170  
sbool printMapLikes() {
3171  
  ret contains(definitions, "printMapLikesEtc");
3172  
}
3173  
3174  
// delete import if marked as "need latest"
3175  
svoid onImportFound(LS tok, IntRange r) {
3176  
  S id = get(tok, r.end-3);
3177  
  if (needLatest.contains(id)) {
3178  
    print("Purging import: " + joinSubList(tok, r));
3179  
    clearTokens(tok, r);
3180  
  }
3181  
}

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: #1033089
Snippet name: Transpiler dev.
Eternal ID of this version: #1033089/1
Text MD5: 7541c1e312bd7de3dc8a4b09288887fa
Transpilation MD5: 1f31918ce5b78ebef43ecf3817567630
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-10-14 03:55:29
Source code size: 106813 bytes / 3181 lines
Pitched / IR pitched: No / No
Views / Downloads: 75 / 325
Referenced in: [show references]