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