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