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

2732
LINES

< > BotCompany Repo | #1025806 // "Super-Edgy" JavaX Translator (Extension of #7) before concurrent class compilation

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

Download Jar. Uses 2039K of libraries. Click here for Pure Java version (18570L/138K).

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

Author comment

Began life as a copy of #759

download  show line numbers  debug dex  old transpilations   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1025806
Snippet name: "Super-Edgy" JavaX Translator (Extension of #7) before concurrent class compilation
Eternal ID of this version: #1025806/1
Text MD5: 3e42828570f14d8bfabd2154d7747664
Transpilation MD5: abd20cefd4b00a95a0daafa7d1e75fba
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-10-21 19:50:05
Source code size: 91414 bytes / 2732 lines
Pitched / IR pitched: No / No
Views / Downloads: 139 / 533
Referenced in: [show references]