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

3188
LINES

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

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

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

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

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: #1032978
Snippet name: JavaX Translator backup
Eternal ID of this version: #1032978/1
Text MD5: d11be1fd5ff0aa6abb3e2ef0f7e3cb1d
Transpilation MD5: 815341cd02ed45ded4c866a0fe5b5312
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-10-11 07:02:09
Source code size: 107145 bytes / 3188 lines
Pitched / IR pitched: No / No
Views / Downloads: 237 / 827
Referenced in: [show references]