Libraryless. Click here for Pure Java version (5853L/39K/113K).
1 | !636 |
2 | !quickmain |
3 | !auto-import |
4 | !standard functions |
5 | !quicknew |
6 | !1000346 // use "case" as a variable name |
7 | !688 // buf.isEmpty |
8 | !class JavaTok |
9 | !1000381 // L<S> |
10 | !697 // "*()" constructor syntax, v2 |
11 | !ctex |
12 | !719 // fill innerClasses |
13 | |
14 | import java.lang.reflect.*; |
15 | import java.math.*; // BigInteger |
16 | import java.text.DecimalFormat; |
17 | import java.lang.management.*; // for time measurement |
18 | |
19 | !include #1000451 // class _x18 modified for Android |
20 | |
21 | interface Function { |
22 | public Object process(Object in); |
23 | public void toJava_process(Code code); |
24 | } |
25 | |
26 | interface ReversibleFunction extends Function { |
27 | public Object unprocess(Object in); |
28 | public void toJava_unprocess(Code code); |
29 | } |
30 | |
31 | // generic learner (works on objects) |
32 | interface Learner { |
33 | public void processInOut(Object in, Object out); |
34 | public Object processIn(Object in); |
35 | public void toJava(Code code); |
36 | public void tryAgain(); |
37 | } |
38 | |
39 | abstract class Base { |
40 | void printVars() { |
41 | new StringBuilder buf; |
42 | Field[] fields = getClass().getDeclaredFields(); |
43 | for (Field field : fields) { |
44 | if ((field.getModifiers() & Modifier.STATIC) != 0) |
45 | continue; |
46 | Object value; |
47 | try { |
48 | value = field.get(this); |
49 | } catch (Exception e) { |
50 | value = "?"; |
51 | } |
52 | |
53 | if (!buf.isEmpty()) buf.append(", "); |
54 | buf.append(field.getName() + "=" + value); |
55 | } |
56 | System.out.println(buf.toString()); |
57 | } |
58 | } |
59 | |
60 | abstract class LearnerImpl extends Base implements Learner { |
61 | public void tryAgain() { |
62 | throw new RuntimeException("No try again"); |
63 | } |
64 | |
65 | public void toJava(Code code) { |
66 | main.todo(); |
67 | } |
68 | } |
69 | |
70 | class Code { |
71 | new StringBuilder buf; |
72 | String var = "in"; |
73 | String indent = ""; |
74 | new List<String> translators; |
75 | new List<String> varStack; |
76 | int varCounter; |
77 | |
78 | *() { |
79 | translators.add("!636"); |
80 | } |
81 | |
82 | void line(String line) { |
83 | buf.append(indent).append(line).append('\n'); |
84 | } |
85 | |
86 | void indent() { |
87 | indent += " "; |
88 | } |
89 | |
90 | void unindent() { |
91 | indent = indent.substring(0, indent.length()-2); |
92 | } |
93 | |
94 | void translators(String... ids) { |
95 | for (String id : ids) |
96 | if (! translators.contains(id)) // space is needed otherwise translator 636 is fooled :) |
97 | translators.add(id); |
98 | } |
99 | |
100 | String getTranslators() { |
101 | // TODO: We should really fix the "standard functions" translator |
102 | // to properly find the main class. |
103 | // |
104 | // As a hack, we move it upwards (before classes adding) |
105 | int i = translators.indexOf("!standard functions"); |
106 | if (i >= 0) { |
107 | translators.remove(i); |
108 | translators.add(0, "!standard functions"); |
109 | } |
110 | |
111 | return main.fromLines(translators); |
112 | } |
113 | |
114 | String s() { |
115 | return "((String) " + var + ")"; |
116 | } |
117 | |
118 | String list() { |
119 | return "((List) " + var + ")"; |
120 | } |
121 | |
122 | void assign(String exp) { |
123 | line(var + " = " + exp + ";"); |
124 | } |
125 | |
126 | void newVar() { |
127 | varStack.add(var); |
128 | var = "_v" + (++varCounter); |
129 | line("Object " + var + ";"); |
130 | } |
131 | |
132 | void oldVar() { |
133 | var = varStack.get(varStack.size()-1); |
134 | varStack.remove(varStack.size()-1); |
135 | } |
136 | } |
137 | |
138 | main { |
139 | static Object androidContext; |
140 | |
141 | static final String ALL = "#681"; |
142 | |
143 | static new List<Case> cases; |
144 | static new HashMap<String, Case> casesByID; |
145 | static boolean testJava = false, showFails, execTasks = false; |
146 | static boolean collectClosest = false; // saves time |
147 | static new (Hash)Set<String> parseErrors; |
148 | static int caseIdx; |
149 | static new (Hash)Set<Class> debuggedClasses; |
150 | static String strategy = "#1000464"; |
151 | static String[] innerClasses; |
152 | static new List<Throwable> strategyParseErrors; |
153 | |
154 | psvm { |
155 | _x18.androidContext = androidContext; |
156 | long startTime = System.currentTimeMillis(); |
157 | |
158 | new List<String> snippetIDs; |
159 | new List<String> inputs; |
160 | |
161 | for (int i = 0; i < args.length; i++) { |
162 | String arg = args[i]; |
163 | if (arg.equals("debug")) |
164 | debugOn(args[++i]); |
165 | else if (arg.equals("in")) { |
166 | String in = args[++i]; |
167 | System.out.println("in=" + quote(in)); |
168 | String quoteUnquote = unquote("\"" + in + "\""); |
169 | System.out.println("now in=" + quote(quoteUnquote)); |
170 | inputs.add(quoteUnquote); |
171 | } else if (arg.equals("-notestjava")) |
172 | testJava = false; |
173 | else if (arg.equals("-testjava")) |
174 | testJava = true; |
175 | else if (arg.equals("-withexec")) |
176 | execTasks = true; |
177 | else if (arg.equals("-showfails")) |
178 | showFails = true; |
179 | else if (arg.equals("strategy")) |
180 | strategy = args[++i]; |
181 | else if (arg.equals("all")) |
182 | snippetIDs.add(ALL); |
183 | else if (isSnippetID(arg)) |
184 | snippetIDs.add(arg); |
185 | else |
186 | System.err.println("Unknown argument: " + arg + ", ignoring"); |
187 | } |
188 | |
189 | if (snippetIDs.isEmpty()) |
190 | if (parse(null) == null) |
191 | parse(ALL); |
192 | |
193 | for (String snippetID : snippetIDs) |
194 | try { |
195 | Case case = parse(snippetID); |
196 | case.halfExamples.addAll(inputs); |
197 | } catch (Throwable e) { |
198 | e.printStackTrace(); |
199 | parseErrors.add(snippetID); |
200 | } |
201 | |
202 | int solved = 0, n = cases.size(), goodJava = 0; |
203 | for (caseIdx = 0; caseIdx < n; caseIdx++) { |
204 | Case case = cases.get(caseIdx); |
205 | try { |
206 | calculate(case); |
207 | } catch (Throwable e) { |
208 | e.printStackTrace(); |
209 | } |
210 | if (case.winner != null) |
211 | ++solved; |
212 | if (case.goodJava) |
213 | ++goodJava; |
214 | if (caseIdx+1 == solved) |
215 | System.out.println((caseIdx+1) + " case(s) processed & solved."); |
216 | else |
217 | System.out.println((caseIdx+1) + " case(s) processed, " + solved + " solved."); |
218 | if (testJava && goodJava < solved) |
219 | System.out.println((solved-goodJava) + " case(s) with BAD JAVA."); |
220 | } |
221 | |
222 | print "" |
223 | print "----" |
224 | |
225 | List<Case> sorted = casesSortedByID(); |
226 | boolean allSolved = solved == n; |
227 | if (solved != 0) { |
228 | System.out.println(); |
229 | System.out.print("Solved: "); |
230 | for (Case case : sorted) |
231 | if (case.winner != null) |
232 | System.out.print(case.id + " "); |
233 | System.out.println(); |
234 | } |
235 | if (testJava && solved > goodJava) { |
236 | System.out.println(); |
237 | System.out.print("Bad Java: "); |
238 | for (Case case : sorted) |
239 | if (case.winner != null && !case.goodJava) |
240 | System.out.print(case.id + " "); |
241 | System.out.println(); |
242 | } |
243 | if (!allSolved) { |
244 | System.out.println(); |
245 | System.out.print("Unsolved: "); |
246 | for (Case case : sorted) |
247 | if (case.winner == null) |
248 | System.out.print(case.id + " "); |
249 | System.out.println(); |
250 | } |
251 | if (!parseErrors.isEmpty()) { |
252 | System.out.print("\nParse errors: "); |
253 | for (String id : parseErrors) |
254 | System.out.print(id + " "); |
255 | System.out.println(); |
256 | } |
257 | if (!strategyParseErrors.isEmpty()) |
258 | System.out.println("Strategy parse errors!"); |
259 | System.out.println(); |
260 | if (allSolved && testJava && goodJava < solved) |
261 | System.out.println("ALL SOLVED (" + solved + "), but some BAD JAVA."); |
262 | else { |
263 | System.out.println(allSolved ? "ALL SOLVED (" + solved + ")" : "Solved " + solved + " out of " + n + "."); |
264 | if (testJava) |
265 | if (goodJava == solved) |
266 | System.out.println("All Java code OK" + (allSolved ? "" : " (for solved cases)") + "."); |
267 | else |
268 | System.out.println("Some bad Java."); |
269 | else |
270 | System.out.println("Java not tested."); |
271 | } |
272 | print "" |
273 | |
274 | /*long time = getUserTime(); |
275 | if (time >= 0) |
276 | System.out.println("User time: " + formatDouble(time/1e9, 3) + "s");*/ |
277 | |
278 | long time = System.currentTimeMillis()-startTime; |
279 | System.out.println("Real time: " + formatDouble(time/1e3, 3) + "s"); |
280 | } |
281 | |
282 | public static String formatDouble(double d, int digits) { |
283 | String format = "0."; |
284 | for (int i = 0; i < digits; i++) format += "#"; |
285 | String s = new DecimalFormat(format).format(d); |
286 | return s.replace(',', '.'); // hack german -> english |
287 | } |
288 | |
289 | /** Get user time in nanoseconds. */ |
290 | public static long getUserTime( ) { |
291 | ThreadMXBean bean = ManagementFactory.getThreadMXBean(); |
292 | return bean.isCurrentThreadCpuTimeSupported() ? |
293 | bean.getCurrentThreadUserTime() : -1L; |
294 | } |
295 | |
296 | static class Case { |
297 | String id; |
298 | new List<String[]> fullExamples; |
299 | new List<String> halfExamples; |
300 | List<String[]> examples1, examples2; |
301 | Learner winner; |
302 | RunnersUp runnersUp = collectClosest ? new RunnersUp() : null; |
303 | boolean goodJava; |
304 | List<Case> combined; |
305 | int splitPoint = -1; |
306 | |
307 | // stats |
308 | int learnersTried, retries; |
309 | |
310 | void split() { |
311 | if (examples1 != null) |
312 | return; // already done |
313 | if (fullExamples.size() < 2) |
314 | throw new RuntimeException("Too few examples (" + fullExamples.size() + ")"); |
315 | if (splitPoint < 0) |
316 | splitPoint = fullExamples.size()-1; |
317 | System.out.println("Full examples: " + fullExamples.size() + ", splitPoint: " + splitPoint + ", half examples: " + halfExamples.size()); |
318 | examples1 = fullExamples.subList(0, splitPoint); |
319 | examples2 = fullExamples.subList(splitPoint, fullExamples.size()); |
320 | } |
321 | |
322 | void add(Case case) { |
323 | combined.add(case); |
324 | fullExamples.addAll(case.fullExamples); |
325 | halfExamples.addAll(case.halfExamples); |
326 | } |
327 | |
328 | Object processIn(Object in) { |
329 | return winner.processIn(in); |
330 | } |
331 | } |
332 | |
333 | static Case parse(String arg) tex { |
334 | try { |
335 | new Case case; |
336 | String text; |
337 | if (arg != null) { |
338 | if (casesByID.containsKey(arg)) |
339 | return casesByID.get(arg); |
340 | |
341 | if (arg.startsWith("Combine")) { |
342 | case.id = "Combine"; |
343 | case.combined = new ArrayList<Case>(); |
344 | List<String> tok = JavaTok.split(arg); |
345 | new List<String> ids; |
346 | for (int i = 5; i < tok.size(); i += 6) { // skip # and "and" |
347 | Case case2 = parse("#" + tok.get(i)); |
348 | case.id += " #" + tok.get(i); |
349 | cases.remove(case2); |
350 | case.add(case2); |
351 | } |
352 | addCase(case); |
353 | return case; |
354 | } else if (isSnippetID(arg)) { |
355 | case.id = arg; |
356 | text = loadSnippet(arg); |
357 | } else { |
358 | case.id = "direct"; |
359 | text = arg; |
360 | } |
361 | } else { |
362 | case.id = "input.txt"; |
363 | text = loadTextFile("input/input.txt", null); |
364 | if (text == null) return null; |
365 | } |
366 | |
367 | // it's a collection of cases! |
368 | if (text.trim().startsWith("#") || text.trim().startsWith("Combine")) { |
369 | for (String line : toLines(text)) |
370 | parse(line); |
371 | return null; |
372 | } |
373 | |
374 | // it's a "Continue:" task - transform to I/O format |
375 | if (text.trim().startsWith("Continue:")) { |
376 | List<String> lines = toLines(text); |
377 | new StringBuilder buf; |
378 | for (int i = 1; i < lines.size(); i++) { |
379 | buf.append("In: " + quote("" + i) + "\n"); |
380 | buf.append("Out: " + quote(lines.get(i)) + "\n"); |
381 | } |
382 | int numAsking = 3; |
383 | for (int i = lines.size(); i < lines.size()+numAsking; i++) |
384 | buf.append("In: " + quote("" + i) + "\n"); |
385 | text = buf.toString(); |
386 | } |
387 | |
388 | // it's an "Execute." task - run Java(X) and transform to I/O format |
389 | if (text.trim().startsWith("Execute.")) { |
390 | if (!execTasks) return null; |
391 | List<String> tok = JavaTok.split(text); |
392 | new StringBuilder buf; |
393 | for (int i = 5; i < tok.size(); i += 2) { |
394 | if (tok.get(i).equals("-") && tok.get(i+2).equals("-")) { |
395 | i += 2; |
396 | buf.append("--\n"); |
397 | } else { |
398 | String code = unquote_fixSpaces(tok.get(i)); |
399 | String result = execute("!636\n" + code); |
400 | buf.append("In: " + quote(code) + "\n"); |
401 | buf.append("Out: " + quote(result) + "\n"); |
402 | } |
403 | } |
404 | text = buf.toString(); |
405 | } |
406 | |
407 | if (text.trim().startsWith("Marking.")) { |
408 | |
409 | List<String> tok = JavaTok.split(text); |
410 | new StringBuilder buf; |
411 | for (int i = 5; i < tok.size(); i += 2) { |
412 | if (tok.get(i).equals("-") && tok.get(i+2).equals("-")) { |
413 | i += 2; |
414 | buf.append("--\n"); |
415 | } else { |
416 | String out = unquote_fixSpaces(tok.get(i)); |
417 | String in = out.replace("[[", "").replace("]]", ""); |
418 | buf.append("In: " + quote(in) + "\n"); |
419 | buf.append("Out: " + quote(out) + "\n"); |
420 | } |
421 | } |
422 | text = buf.toString(); |
423 | } |
424 | |
425 | System.out.println(text); |
426 | String in = null, out = null; |
427 | |
428 | List<String> tok = JavaTok.split(text); |
429 | for (int i = 1; i < tok.size(); i += 2) { |
430 | String t = tok.get(i), t2 = i+2 < tok.size() ? tok.get(i+2) : ""; |
431 | if (t.equals("-") && t2.equals("-")) { |
432 | i += 2; |
433 | case.splitPoint = case.fullExamples.size(); |
434 | //System.out.println("t=" + t + ", t2= " + t2); |
435 | } else if (t.toUpperCase().startsWith("I") && t2.equals("-") && tok.get(i+4).toUpperCase().equals("DOC") && tok.get(i+6).equals(":")) { // "In-Doc:" |
436 | if (in != null) |
437 | case.halfExamples.add(in); |
438 | i += 8; |
439 | int j = findNextLine(tok, i); |
440 | String inID = unquote_fixSpaces(JavaTok.join(tok.subList(i, j-1))); |
441 | in = loadSnippet(inID); |
442 | i = j-2; |
443 | out = null; |
444 | } else if (t.toUpperCase().startsWith("I") && t2.equals(":")) { // "In:" or "I:" |
445 | if (in != null) |
446 | case.halfExamples.add(in); |
447 | i += 4; |
448 | int j = findNextLine(tok, i); |
449 | in = unquote_fixSpaces(JavaTok.join(tok.subList(i, j-1))); |
450 | i = j-2; |
451 | out = null; |
452 | } else if (t.toUpperCase().startsWith("O") && t2.equals(":")) { // "Out: " or "O: " |
453 | i += 4; |
454 | int j = findNextLine(tok, i); |
455 | out = unquote_fixSpaces(JavaTok.join(tok.subList(i, j-1))); |
456 | i = j-2; |
457 | if ((in + out).indexOf('\t') >= 0) |
458 | System.err.println("WARNING: Tab character used!"); |
459 | System.out.println(quote(in) + " => " + quote(out)); |
460 | case.fullExamples.add(new String[] {in, out}); |
461 | in = out = null; |
462 | } else { |
463 | int j = findNextLine(tok, i); |
464 | String line = JavaTok.join(tok.subList(i, j-1)); |
465 | i = j-2; |
466 | System.out.println("-- Ignoring line: " + line); |
467 | } |
468 | } |
469 | |
470 | if (in != null) |
471 | case.halfExamples.add(in); |
472 | addCase(case); |
473 | return case; |
474 | } catch (Throwable e) { |
475 | parseErrors.add(arg); |
476 | e.printStackTrace(); |
477 | return null; |
478 | } |
479 | } |
480 | |
481 | static String unquote_fixSpaces(String s) { |
482 | String _ = unquote(s); |
483 | if (s.startsWith("[[")) |
484 | _ = fixSpaces(_); |
485 | return _; |
486 | } |
487 | |
488 | // remove invisible spaces at end of line - this will otherwise confuse the engine(s) greatly... |
489 | static String fixSpaces(String s) { |
490 | System.out.println(quote(s)); |
491 | s = s.replaceAll("[\t ]+(\r?\n)", "$1"); |
492 | s = s.replaceAll("[\t ]+$", ""); |
493 | //System.out.println("_fixSpaces => " + quote(s)); |
494 | return s; |
495 | } |
496 | |
497 | // i is a code-token (odd index) |
498 | // return value is also a code token, or end of list |
499 | static int findNextLine(List<String> tok, int i) { |
500 | while (i < tok.size() && tok.get(i-1).indexOf('\n') < 0) |
501 | i += 2; |
502 | return i; |
503 | } |
504 | |
505 | static void addCase(Case case) { |
506 | cases.add(case); |
507 | casesByID.put(case.id, case); |
508 | } |
509 | |
510 | static void calculate(Case case) tex { |
511 | System.out.println("\n== CASE " + case.id + " =="); |
512 | |
513 | case.split(); |
514 | Learner learner = findOKLearner(case); |
515 | if (learner == null) { |
516 | String stat = ""; |
517 | if (case.retries != 0) stat = " + " + case.retries + " retries"; |
518 | System.out.println("\nProblem not solved (" + case.learnersTried + " learners tried" + stat + ")"); |
519 | RunnersUp ru = case.runnersUp; |
520 | if (ru != null && ru.winner != null) |
521 | System.out.println("Closest result: " + quote(ru.bestResult) + " instead of " + quote(ru.expected) + " (score " + ru.bestScore + ") by " + structure(ru.winner)); |
522 | } else { |
523 | print "\nSolved!" |
524 | print(" " + structure(learner) + "\n"); |
525 | case.winner = learner; |
526 | new Code code; |
527 | if (testJava) try { |
528 | learner.toJava(code); |
529 | |
530 | if (testJava) |
531 | testJava(case, code); // prints "GOOD JAVA" or "BAD JAVA" |
532 | else |
533 | print "Java:" |
534 | |
535 | System.out.println(indent(" ", code.getTranslators())); |
536 | System.out.println(indent(" ", code.buf.toString())); |
537 | } catch (Throwable e) { |
538 | print "BAD JAVA" |
539 | } |
540 | |
541 | for (String in : case.halfExamples) { |
542 | Object out = learner.processIn(in); |
543 | System.out.println(quote(in) + " =>! " + quote((String) out)); |
544 | } |
545 | } |
546 | } |
547 | |
548 | static void choice_orderList(List l) { |
549 | } |
550 | |
551 | static Learner findOKLearner(Case case) tex { |
552 | List<Learner> list = makeLearners(); |
553 | choice_orderList(list); |
554 | for (Learner learner : list) try { |
555 | if (learnerOK(learner, case)) |
556 | return learner; |
557 | } catch (Throwable e) { |
558 | if (showFails) |
559 | e.printStackTrace(); |
560 | } |
561 | |
562 | if (case.combined != null) { |
563 | Case switchCase = makeSwitchCase(case); |
564 | calculate(switchCase); |
565 | Learner learner = switchCase.winner; |
566 | if (learner != null) |
567 | return new LSwitch(case, learner); |
568 | } |
569 | |
570 | return null; |
571 | } |
572 | |
573 | static Case makeSwitchCase(Case case) { |
574 | int i = 0; |
575 | Case s = new Case(); |
576 | s.id = "Switch " + case.id; |
577 | s.examples1 = new ArrayList<String[]>(); |
578 | s.examples2 = new ArrayList<String[]>(); |
579 | for (Case c : case.combined) { |
580 | ++i; |
581 | for (String[] e : c.examples1) |
582 | s.examples1.add(new String[] {e[0], String.valueOf(i)}); |
583 | for (String[] e : c.examples2) |
584 | s.examples2.add(new String[] {e[0], String.valueOf(i)}); |
585 | for (String[] e : c.fullExamples) |
586 | s.fullExamples.add(new String[] {e[0], String.valueOf(i)}); |
587 | } |
588 | return s; |
589 | } |
590 | |
591 | static boolean learnerOK(Learner learner, Case case) { |
592 | String[] _e = null; |
593 | try { |
594 | if (case.examples1 == null) |
595 | fail("Case not calculated: " + case.id); |
596 | |
597 | ++case.learnersTried; |
598 | for (String[] e : case.examples1) { |
599 | _e = e; |
600 | learner.processInOut(e[0], e[1]); |
601 | } |
602 | |
603 | // full validation against all examples - but starting with the unknown ones to make coding easier for learners |
604 | int retry = 0; |
605 | retryLoop: while (true) { |
606 | int n = case.fullExamples.size(); |
607 | for (int i = 0; i < n; i++) { |
608 | String[] e = case.fullExamples.get((i+case.examples1.size()) % n); |
609 | _e = e; |
610 | String out = (String) learner.processIn(e[0]); |
611 | if (!e[1].equals(out)) { |
612 | |
613 | if (case.runnersUp != null) |
614 | case.runnersUp.add(e[1], out, leven(out, e[1]), learner); |
615 | |
616 | if (showFails) |
617 | System.out.println("[fail] " + structure(learner) + " on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1])); |
618 | ++retry; |
619 | ++case.retries; |
620 | if (retry % 1000 == 0) |
621 | System.err.println("Retry " + retry); |
622 | learner.tryAgain(); |
623 | continue retryLoop; |
624 | } |
625 | } |
626 | return true; // all test examples passed |
627 | } |
628 | } catch (Throwable e) { |
629 | if (debuggedClasses.contains(learner.getClass()) || showFails) { |
630 | e.printStackTrace(); |
631 | System.err.println("[fail] " + structure(learner) + " on " + (_e == null ? "?" : quote(_e[0])) + " - " + e); |
632 | } |
633 | return false; |
634 | } |
635 | } |
636 | |
637 | static boolean validate(String[] example, Learner learner) { |
638 | try { |
639 | String out = (String) learner.processIn(example[0]); |
640 | if (!example[1].equals(out)) { |
641 | //System.out.println("[fail] " + learner + " on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1])); |
642 | return false; |
643 | } |
644 | return true; |
645 | } catch (Throwable e) { |
646 | silentException(e); |
647 | return false; |
648 | } |
649 | } |
650 | |
651 | static void silentException(Throwable e) { |
652 | } |
653 | |
654 | static List<Learner> makeLearners() ctex { |
655 | return parseStrategy(loadSnippet(strategy)); |
656 | } |
657 | |
658 | /* XXX - important part */ |
659 | static List<Learner> parseStrategy(String strategyText) ctex { |
660 | List <String> lines = toLines(strategyText); |
661 | new List<Learner> list; |
662 | for (String s : lines) try { |
663 | s = s.trim(); |
664 | String[] parts = s.split(" +"); |
665 | if (parts.length == 0) continue; |
666 | |
667 | new Stack<Object> stack; |
668 | for (int i = parts.length-1; i >= 0; i--) { |
669 | String p = parts[i]; |
670 | Class c = findClassFlex(p); |
671 | if (c == null) |
672 | fail("Strategy element " + p + " not known"); |
673 | |
674 | Constructor ctr = c.getDeclaredConstructors()[0]; |
675 | Class[] types = ctr.getParameterTypes(); |
676 | if (types.length == 0) |
677 | stack.add(ctr.newInstance()); |
678 | else if (types.length == 1) |
679 | stack.add(ctr.newInstance(stack.pop())); |
680 | else |
681 | fail("bla"); |
682 | |
683 | /*if (isSubclass(c, ReversibleFunction.class)) { |
684 | l = new LWrap((ReversibleFunction) newInstance(c), l); |
685 | continue; |
686 | }*/ |
687 | } |
688 | |
689 | list.add((Learner) stack.peek()); |
690 | } catch (Throwable e) { |
691 | System.err.println("Strategy parse error."); |
692 | e.printStackTrace(); |
693 | strategyParseErrors.add(e); |
694 | } |
695 | return list; |
696 | } |
697 | |
698 | static List<Learner> makeLearnersX() { |
699 | new List<Learner> list; |
700 | list.addAll(level1()); |
701 | list.add(new LBox(new LMulti(level1()))); |
702 | list.add(new LBox2(new LMulti(level1()))); |
703 | |
704 | list.add(new LChange(new FCommonPrefix(), new LOutPattern())); |
705 | list.add(new LChange(new FCommonSuffix(), new LOutPattern())); |
706 | |
707 | list.add(new LEmptyBox(new LMulti(level1()))); |
708 | |
709 | list.add(new LChange(new RFToLines(), new LFixedFunction(new FLength()))); |
710 | |
711 | // for #1000455 |
712 | list.add(new LFindOutInIn(new LFixedSubstring())); |
713 | |
714 | for (int I = 1; I <= 2; I++) |
715 | // for #1000457 |
716 | list.add(new LChange(new FDropFirstLines(I), new LMulti( |
717 | new LFixWhitespace(l1()), level1()))); |
718 | |
719 | // for #1000458 |
720 | list.add(new LFixWhitespace(l1())); |
721 | |
722 | return list; |
723 | } |
724 | |
725 | static Learner l1() { |
726 | return new LMulti(level1()); |
727 | } |
728 | |
729 | static List<Learner> level1() { |
730 | new List<Learner> list; |
731 | list.add(new LId()); // always good to have as included learner |
732 | list.add(new LPrefixSuffix()); |
733 | list.add(new LSplitInput(new LOutPattern())); |
734 | list.add(new LInputPattern()); |
735 | list.add(new LFixed()); |
736 | list.add(new LWrap(new RFJavaTok(), new LEach(new LFixedFunction(new EscapeCase())))); |
737 | list.add(new LCharShift()); |
738 | list.add(new LOutSuffix(new LFirst(new LCharShift()))); |
739 | |
740 | list.add(new LChange(new RFJavaTok(), new LMulti( |
741 | new LChange(new FStringsOnly(), new LGetListElement()), |
742 | new LChange(new FNumbersOnly(), new LMath())) |
743 | )); |
744 | |
745 | // TODO - for #1000378 |
746 | list.add(new LChange(new RFJavaTok(), new LDistinguishList(new FIsString()))); |
747 | |
748 | list.add(new LFixedSubstring()); |
749 | |
750 | // of no use now it seems |
751 | // list.add(new LTryPrevious()); |
752 | |
753 | return list; |
754 | } |
755 | |
756 | public static String unquote(String s) { |
757 | if (s.startsWith("[[") && s.endsWith("]]")) |
758 | return s.substring(2, s.length()-2); |
759 | else if (s.startsWith("\"") && s.endsWith("\"") && s.length() > 1) |
760 | //return s.substring(1, s.length()-1).replace("\\\"", "\"").replace("\\\\", "\\"); |
761 | return unescapeJavaString(s.substring(1, s.length()-1)); |
762 | else |
763 | return s; // return original |
764 | } |
765 | |
766 | /** from: http://stackoverflow.com/questions/3537706/howto-unescape-a-java-string-literal-in-java, |
767 | or: https://gist.github.com/uklimaschewski/6741769 |
768 | |
769 | Thanks! |
770 | */ |
771 | public static String unescapeJavaString(String st) { |
772 | StringBuilder sb = new StringBuilder(st.length()); |
773 | |
774 | for (int i = 0; i < st.length(); i++) { |
775 | char ch = st.charAt(i); |
776 | if (ch == '\\') { |
777 | char nextChar = (i == st.length() - 1) ? '\\' : st |
778 | .charAt(i + 1); |
779 | // Octal escape? |
780 | if (nextChar >= '0' && nextChar <= '7') { |
781 | String code = "" + nextChar; |
782 | i++; |
783 | if ((i < st.length() - 1) && st.charAt(i + 1) >= '0' |
784 | && st.charAt(i + 1) <= '7') { |
785 | code += st.charAt(i + 1); |
786 | i++; |
787 | if ((i < st.length() - 1) && st.charAt(i + 1) >= '0' |
788 | && st.charAt(i + 1) <= '7') { |
789 | code += st.charAt(i + 1); |
790 | i++; |
791 | } |
792 | } |
793 | sb.append((char) Integer.parseInt(code, 8)); |
794 | continue; |
795 | } |
796 | switch (nextChar) { |
797 | case '\\': |
798 | ch = '\\'; |
799 | break; |
800 | case 'b': |
801 | ch = '\b'; |
802 | break; |
803 | case 'f': |
804 | ch = '\f'; |
805 | break; |
806 | case 'n': |
807 | ch = '\n'; |
808 | break; |
809 | case 'r': |
810 | ch = '\r'; |
811 | break; |
812 | case 't': |
813 | ch = '\t'; |
814 | break; |
815 | case '\"': |
816 | ch = '\"'; |
817 | break; |
818 | case '\'': |
819 | ch = '\''; |
820 | break; |
821 | // Hex Unicode: u???? |
822 | case 'u': |
823 | if (i >= st.length() - 5) { |
824 | ch = 'u'; |
825 | break; |
826 | } |
827 | int code = Integer.parseInt( |
828 | "" + st.charAt(i + 2) + st.charAt(i + 3) |
829 | + st.charAt(i + 4) + st.charAt(i + 5), 16); |
830 | sb.append(Character.toChars(code)); |
831 | i += 5; |
832 | continue; |
833 | } |
834 | i++; |
835 | } |
836 | sb.append(ch); |
837 | } |
838 | return sb.toString(); |
839 | } |
840 | |
841 | static String indent(String indent, String s) { |
842 | return indent + s.replace("\n", "\n" + indent); |
843 | } |
844 | |
845 | static Class<?> getClass(String name) { |
846 | try { |
847 | return Class.forName(name); |
848 | } catch (ClassNotFoundException e) { |
849 | return null; |
850 | } |
851 | } |
852 | |
853 | static void debugOn(String name) { |
854 | try { |
855 | Class c = findClassFlex(name); |
856 | debuggedClasses.add(c); |
857 | Field field; |
858 | while (true) |
859 | try { |
860 | field = c.getDeclaredField("debug"); |
861 | break; |
862 | } catch (NoSuchFieldException e) { |
863 | c = c.getSuperclass(); |
864 | } |
865 | field.setBoolean(null, true); |
866 | } catch (Exception e) { |
867 | e.printStackTrace(); |
868 | System.err.println("Cannot debug class " + name); |
869 | } |
870 | } |
871 | |
872 | static int choice(String text, int i) { |
873 | return i; |
874 | } |
875 | |
876 | // splits the input at some point, takes only one part |
877 | static class LSplitInput extends LearnerImpl { |
878 | int splitIdx = 1; // split after first character |
879 | Learner baseLearner; |
880 | |
881 | LSplitInput(Learner baseLearner) { |
882 | this.baseLearner = baseLearner; |
883 | splitIdx = choice("LSplitInput.i", splitIdx); |
884 | } |
885 | |
886 | public void processInOut(Object _in, Object _out) { |
887 | String in = (String) _in, out = (String) _out; |
888 | in = in.substring(splitIdx); |
889 | baseLearner.processInOut(in, out); |
890 | } |
891 | |
892 | public Object processIn(Object _in) { |
893 | String in = (String) _in; |
894 | in = in.substring(splitIdx); |
895 | return baseLearner.processIn(in); |
896 | } |
897 | |
898 | public void toJava(Code code) { |
899 | if (splitIdx != 0) |
900 | code.line(code.var + " = ((String) " + code.var + ").substring(" + splitIdx + ");"); |
901 | baseLearner.toJava(code); |
902 | } |
903 | } |
904 | |
905 | static class FDropFirstLines implements Function { |
906 | int n; |
907 | *(int *n) {} |
908 | |
909 | public Object process(Object _in) { |
910 | String in = (String)_in; |
911 | for (int I=0; I < n; I++) |
912 | in = in.substring(in.indexOf('\n')+1); |
913 | return in; |
914 | } |
915 | |
916 | public void toJava_process(Code code) { |
917 | todo(); |
918 | } |
919 | } |
920 | |
921 | // removes common suffix from out, delegates to base learner |
922 | static class LOutSuffix extends LearnerImpl { |
923 | String suffixOut = ""; |
924 | Learner baseLearner; |
925 | |
926 | LOutSuffix(Learner baseLearner) { |
927 | this.baseLearner = baseLearner; |
928 | } |
929 | |
930 | public void processInOut(Object _in, Object _out) { |
931 | String in = (String) _in, out = (String) _out; |
932 | if (out.endsWith("!")) |
933 | suffixOut = "!"; |
934 | if (out.endsWith(suffixOut)) |
935 | out = out.substring(0, out.length()-suffixOut.length()); |
936 | |
937 | baseLearner.processInOut(in, out); |
938 | } |
939 | |
940 | public Object processIn(Object _in) { |
941 | String in = (String) _in; |
942 | return baseLearner.processIn(in) + suffixOut; |
943 | } |
944 | |
945 | public void toJava(Code code) { |
946 | baseLearner.toJava(code); |
947 | if (suffixOut.length() != 0) |
948 | code.line(code.var + " = " + code.s() + "+" + quote(suffixOut) + ";"); |
949 | } |
950 | } |
951 | |
952 | // if input appears in output in fixed pattern |
953 | static class LOutPattern extends LearnerImpl { |
954 | static boolean debug; |
955 | String pattern = "%!%"; |
956 | |
957 | public void processInOut(Object _in, Object _out) { |
958 | String in = (String) _in, out = (String) _out; |
959 | pattern = out.replace(in, "%!%"); |
960 | if (debug) |
961 | System.out.println("LOutPattern: in=" + quote(in) + ", out=" + quote(out) + ", pattern=" + quote(pattern)); |
962 | } |
963 | |
964 | public String processIn(Object _in) { |
965 | String in = (String) _in; |
966 | return pattern.replace("%!%", in); |
967 | } |
968 | |
969 | public void toJava(Code code) { |
970 | code.line(code.var + " = " + quote(pattern) + ".replace(" + quote("%!%") + ", (String) " + code.var + ");"); |
971 | } |
972 | } |
973 | |
974 | // simplets learner - only knows the "id" function |
975 | static class LId extends LearnerImpl { |
976 | public void processInOut(Object in, Object out) { |
977 | } |
978 | |
979 | public Object processIn(Object in) { |
980 | return in; |
981 | } |
982 | |
983 | public void toJava(Code code) { |
984 | } |
985 | } |
986 | |
987 | // learns to exchange common prefixes and suffixes |
988 | static class LPrefixSuffix extends LearnerImpl { |
989 | static boolean debug; |
990 | String prefixIn, suffixIn, prefixOut, suffixOut; |
991 | |
992 | public void processInOut(Object _in, Object _out) { |
993 | String in = (String) _in, out = (String) _out; |
994 | updateIn(in); |
995 | prefixOut = prefixOut == null ? out : commonPrefix(prefixOut, out); |
996 | suffixOut = suffixOut == null ? out : commonSuffix(suffixOut, out); |
997 | if (debug) |
998 | printState("processInOut(" + quote(in) + ", " + quote(out) + ")"); |
999 | } |
1000 | |
1001 | void updateIn(String in) { |
1002 | prefixIn = prefixIn == null ? in : commonPrefix(prefixIn, in); |
1003 | suffixIn = suffixIn == null ? in : commonSuffix(suffixIn, in); |
1004 | if (debug) |
1005 | printState("updateIn(" + quote(in) + ")"); |
1006 | } |
1007 | |
1008 | public String processIn(Object _in) { |
1009 | String in = (String) _in; |
1010 | //System.out.println("[before last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut)); |
1011 | //System.out.println("[last info] " + quote(in)); |
1012 | |
1013 | // use latest information |
1014 | String p = prefixIn, s = suffixIn; |
1015 | updateIn(in); |
1016 | prefixOut = prefixOut.substring(0, prefixOut.length()-(p.length()-prefixIn.length())); |
1017 | suffixOut = suffixOut.substring(s.length()-suffixIn.length()); |
1018 | |
1019 | //System.out.println("[after last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut)); |
1020 | String core = in.substring(prefixIn.length(), in.length()-suffixIn.length()); |
1021 | return prefixOut + core + suffixOut; |
1022 | } |
1023 | |
1024 | public void toJava(Code code) { |
1025 | if (prefixIn.length() != 0 || suffixIn.length() != 0) |
1026 | code.line(code.var + " = ((String) " + code.var + ").substring(" + prefixIn.length() + ", " + code.s() + ".length()-" + suffixIn.length() + ");"); |
1027 | if (prefixOut.length() != 0 || suffixOut.length() != 0) |
1028 | code.line(code.var + " = " + quote(prefixOut) + " + " + code.var + " + " + quote(suffixOut) + ";"); |
1029 | } |
1030 | |
1031 | void printState(String text) { |
1032 | System.out.println(text); |
1033 | printVars(); |
1034 | } |
1035 | } |
1036 | |
1037 | // for "find" tasks (e.g. "abcde" to "[[abc]]de") |
1038 | static class LInputPattern extends LearnerImpl { |
1039 | String regexp = "", findMarker1 = "[[", findMarker2 = "]]"; |
1040 | |
1041 | public void processInOut(Object _in, Object _out) { |
1042 | String in = (String) _in, out = (String) _out; |
1043 | int i = out.indexOf(findMarker1), j = out.indexOf(findMarker2, i+1); |
1044 | if (j < 0) return; |
1045 | String s = out.substring(i+2, j); |
1046 | regexp = s.replaceAll("\\d+", Matcher.quoteReplacement("\\d+")); |
1047 | System.out.println("regexp: " + regexp); |
1048 | } |
1049 | |
1050 | public String processIn(Object _in) { |
1051 | String in = (String) _in; |
1052 | if (regexp.length() == 0) |
1053 | return in; |
1054 | else |
1055 | return in.replaceAll("(" + regexp + ")", findMarker1 + "$1" + findMarker2); |
1056 | } |
1057 | |
1058 | public void toJava(Code code) { |
1059 | code.line(code.var + " = ((String) " + code.var + ").replaceAll(" + quote("(" + regexp + ")") + ", \"[[$1]]\");"); |
1060 | } |
1061 | } |
1062 | |
1063 | static class LFixed extends LearnerImpl { |
1064 | static boolean debug; |
1065 | Object value; |
1066 | |
1067 | public void processInOut(Object in, Object out) { |
1068 | value = out; |
1069 | if (debug) |
1070 | printVars(); |
1071 | } |
1072 | |
1073 | public Object processIn(Object in) { |
1074 | return value; |
1075 | } |
1076 | |
1077 | public void toJava(Code code) { |
1078 | code.line(code.var + " = " + quote((String) value) + ";"); |
1079 | } |
1080 | } |
1081 | |
1082 | static void fail() { |
1083 | throw new RuntimeException("fail"); |
1084 | } |
1085 | |
1086 | static void fail(String msg) { |
1087 | throw new RuntimeException(msg); |
1088 | } |
1089 | |
1090 | static void assertSameSize(List a, List b) { |
1091 | if (a.size() != b.size()) |
1092 | fail("wrong list sizes"); |
1093 | } |
1094 | |
1095 | // process lists in parallel |
1096 | // (in and out must be a list of same length) |
1097 | static class LEach extends LearnerImpl { |
1098 | static boolean debug; |
1099 | Learner base; |
1100 | |
1101 | LEach(Learner base) { |
1102 | this.base = base; |
1103 | } |
1104 | |
1105 | public void processInOut(Object _in, Object _out) { |
1106 | List in = (List) _in, out = (List) _out; |
1107 | assertSameSize(in, out); |
1108 | for (int i = 0; i < in.size(); i++) |
1109 | base.processInOut(in.get(i), out.get(i)); |
1110 | if (debug) |
1111 | printVars(); |
1112 | } |
1113 | |
1114 | public Object processIn(Object _in) { |
1115 | List in = (List) _in; |
1116 | List out = new ArrayList(); |
1117 | for (Object x : in) |
1118 | out.add(base.processIn(x)); |
1119 | return out; |
1120 | } |
1121 | |
1122 | public void toJava(Code code) { |
1123 | code.line("List out = new ArrayList();"); |
1124 | code.line("for (Object x : (List) in) {"); |
1125 | code.indent(); |
1126 | code.line("in = x;"); |
1127 | base.toJava(code); |
1128 | code.line("out.add(in);"); |
1129 | code.unindent(); |
1130 | code.line("}"); |
1131 | code.line("in = out;"); |
1132 | } |
1133 | } |
1134 | |
1135 | static class LChange extends LearnerImpl { |
1136 | Function f; |
1137 | Learner base; |
1138 | |
1139 | LChange(Function f, Learner base) { |
1140 | this.f = f; |
1141 | this.base = base; |
1142 | } |
1143 | |
1144 | public void processInOut(Object in, Object out) { |
1145 | in = f.process(in); |
1146 | base.processInOut(in, out); |
1147 | } |
1148 | |
1149 | public Object processIn(Object in) { |
1150 | in = f.process(in); |
1151 | return base.processIn(in); |
1152 | } |
1153 | |
1154 | public void toJava(Code code) { |
1155 | f.toJava_process(code); |
1156 | base.toJava(code); |
1157 | } |
1158 | } |
1159 | |
1160 | static class LFindOutInIn extends LearnerImpl { |
1161 | static boolean debug; |
1162 | Learner base; |
1163 | String findMarker1 = "{{", findMarker2 = "}}"; |
1164 | |
1165 | *(Learner *base) {} |
1166 | |
1167 | public void processInOut(Object _in, Object _out) { |
1168 | String in = (String) _in, out = (String) _out; |
1169 | if (out.length() == 0) |
1170 | out = in; |
1171 | else { |
1172 | int i = in.indexOf(out); |
1173 | if (i < 0) throw new RuntimeException("error"); |
1174 | int j = i+out.length(); |
1175 | out = in.substring(0, i) + findMarker1 + in.substring(i, j) + findMarker2 + in.substring(j); |
1176 | if (debug) |
1177 | System.out.println("LFindOutInIn: index=" + i); |
1178 | } |
1179 | |
1180 | base.processInOut(in, out); |
1181 | |
1182 | if (debug) |
1183 | System.out.println("LFindOutInIn: Base learned. " + base); |
1184 | } |
1185 | |
1186 | public Object processIn(Object _in) { |
1187 | if (debug) |
1188 | System.out.println("LFindOutInIn: processIn"); |
1189 | String in = (String) _in; |
1190 | String out = (String) base.processIn(in); |
1191 | int i = out.indexOf(findMarker1), j = out.indexOf(findMarker2, i)-2; |
1192 | String result = i < 0 ? "" : in.substring(i, j); |
1193 | if (debug) |
1194 | System.out.println("LFindOutInIn: processIn " + i + " " + j + " " + quote(result)); |
1195 | return result; |
1196 | } |
1197 | |
1198 | public void tryAgain() { |
1199 | base.tryAgain(); |
1200 | } |
1201 | } |
1202 | |
1203 | static class LWrap extends LearnerImpl { |
1204 | ReversibleFunction f; |
1205 | Learner base; |
1206 | |
1207 | LWrap(ReversibleFunction f, Learner base) { |
1208 | this.f = f; |
1209 | this.base = base; |
1210 | } |
1211 | |
1212 | public void processInOut(Object in, Object out) { |
1213 | in = f.process(in); |
1214 | out = f.process(out); |
1215 | base.processInOut(in, out); |
1216 | } |
1217 | |
1218 | public Object processIn(Object in) { |
1219 | in = f.process(in); |
1220 | in = base.processIn(in); |
1221 | in = f.unprocess(in); |
1222 | return in; |
1223 | } |
1224 | |
1225 | public void toJava(Code code) { |
1226 | f.toJava_process(code); |
1227 | base.toJava(code); |
1228 | f.toJava_unprocess(code); |
1229 | } |
1230 | } |
1231 | |
1232 | static class RFJavaTok implements ReversibleFunction { |
1233 | public Object process(Object in) { |
1234 | return JavaTok.split((String) in); |
1235 | } |
1236 | |
1237 | public Object unprocess(Object in) { |
1238 | return JavaTok.join((List) in); |
1239 | } |
1240 | |
1241 | public void toJava_process(Code code) { |
1242 | code.translators("!636", "!class JavaTok"); |
1243 | code.line(code.var + " = JavaTok.split((String) " + code.var + ");"); |
1244 | } |
1245 | |
1246 | public void toJava_unprocess(Code code) { |
1247 | code.translators("!636", "!class JavaTok"); |
1248 | code.line(code.var + " = JavaTok.join((List) " + code.var + ");"); |
1249 | } |
1250 | } |
1251 | |
1252 | static class RFToLines implements ReversibleFunction { |
1253 | public Object process(Object in) { |
1254 | return toLines((String) in); |
1255 | } |
1256 | |
1257 | public Object unprocess(Object in) { |
1258 | return fromLines((List) in); |
1259 | } |
1260 | |
1261 | public void toJava_process(Code code) { |
1262 | code.translators("!636", "!standard functions"); |
1263 | code.assign("toLines(" + code.s() + ");"); |
1264 | } |
1265 | |
1266 | public void toJava_unprocess(Code code) { |
1267 | code.translators("!636", "!standard functions"); |
1268 | code.assign("fromLines(" + code.list() + ");"); |
1269 | } |
1270 | } |
1271 | |
1272 | // works on a token list - makes a list of only the string constants (unquoted) |
1273 | static class FStringsOnly implements Function { |
1274 | static boolean debug; |
1275 | |
1276 | public Object process(Object _in) { |
1277 | new List<String> tok; |
1278 | for (String s : (List<String>) _in) { |
1279 | boolean isString = s.startsWith("\"") || s.startsWith("[["); |
1280 | if (isString) |
1281 | tok.add(unquote(s)); |
1282 | if (debug) |
1283 | System.out.println("FStringsOnly - isString: " + isString + " - " + s); |
1284 | } |
1285 | return tok; |
1286 | } |
1287 | |
1288 | public void toJava_process(Code code) { |
1289 | code.translators("!standard functions"); |
1290 | code.line("List<String> tok = new ArrayList<String>();"); |
1291 | code.line("for (String s : (List<String>) " + code.var + ")"); |
1292 | code.line(" if (s.startsWith(\"\\\"\") || s.startsWith(\"[[\")) tok.add(unquote(s));"); |
1293 | code.assign("tok"); |
1294 | } |
1295 | } |
1296 | |
1297 | // works on a token list - makes a list of only the number constants |
1298 | static class FNumbersOnly implements Function { |
1299 | static boolean debug; |
1300 | |
1301 | public Object process(Object _in) { |
1302 | new List<String> tok; |
1303 | for (String s : (List<String>) _in) { |
1304 | boolean isNumber = s.length() != 0 && (Character.isDigit(s.charAt(0)) || (s.charAt(0) == '-' && s.length() > 1)); |
1305 | if (isNumber) |
1306 | tok.add(s); |
1307 | if (debug) |
1308 | System.out.println("FNumbersOnly - isNumber: " + isNumber + " - " + s); |
1309 | } |
1310 | return tok; |
1311 | } |
1312 | |
1313 | public void toJava_process(Code code) { |
1314 | code.line("List<String> tok = new ArrayList<String>();"); |
1315 | code.line("for (String s : (List<String>) " + code.var + ")"); |
1316 | code.line(" if (s.length() != 0 && (Character.isDigit(s.charAt(0)) || (s.charAt(0) == '-' && s.length() > 1))) tok.add(s);"); |
1317 | code.assign("tok"); |
1318 | } |
1319 | } |
1320 | |
1321 | static class FLength implements Function { |
1322 | static boolean debug; |
1323 | |
1324 | public Object process(Object in) { |
1325 | Object result = String.valueOf(in instanceof List ? ((List) in).size() : ((String) in).length()); |
1326 | if (debug) |
1327 | System.out.println("FLength: " + result); |
1328 | return result; |
1329 | } |
1330 | |
1331 | public void toJava_process(Code code) { |
1332 | code.assign("String.valueOf(" + code.var + " instanceof List ? " + code.list() + ".size() : " + code.s() + ".length())"); |
1333 | } |
1334 | } |
1335 | |
1336 | static class LFixedFunction extends LearnerImpl { |
1337 | Function f; |
1338 | |
1339 | LFixedFunction(Function f) { |
1340 | this.f = f; |
1341 | } |
1342 | |
1343 | public void processInOut(Object in, Object out) { |
1344 | } |
1345 | |
1346 | public Object processIn(Object in) { |
1347 | return f.process(in); |
1348 | } |
1349 | |
1350 | public void toJava(Code code) { |
1351 | f.toJava_process(code); |
1352 | } |
1353 | } |
1354 | |
1355 | // trivial stuff like taking the one element out of a 1-element list |
1356 | static class LTrivial extends LearnerImpl { |
1357 | public void processInOut(Object in, Object out) { |
1358 | } |
1359 | |
1360 | public Object processIn(Object in) { |
1361 | return ((List) in).get(0); |
1362 | } |
1363 | |
1364 | public void toJava(Code code) { |
1365 | code.assign(code.list() + ".get(0)"); |
1366 | } |
1367 | } |
1368 | |
1369 | // get element of a list at fixed index |
1370 | static class LGetListElement extends LearnerImpl { |
1371 | static boolean debug; |
1372 | int i; |
1373 | |
1374 | public void processInOut(Object _in, Object out) { |
1375 | List in = (List) _in; |
1376 | i = in.indexOf(out); |
1377 | if (debug) |
1378 | System.out.println("LGetListElement: " + i + " " + out); |
1379 | } |
1380 | |
1381 | public Object processIn(Object in) { |
1382 | return ((List) in).get(i); |
1383 | } |
1384 | |
1385 | public void toJava(Code code) { |
1386 | code.assign(code.list() + ".get(" + i + ")"); |
1387 | } |
1388 | } |
1389 | |
1390 | // math operations |
1391 | static class LMath extends LearnerImpl { |
1392 | static boolean debug; |
1393 | String allOperations = "+ - * /"; |
1394 | new (Tree)Set<String> possibleOperations; |
1395 | |
1396 | LMath() { |
1397 | possibleOperations.addAll(Arrays.asList(allOperations.split(" +"))); |
1398 | } |
1399 | |
1400 | public void processInOut(Object _in, Object _out) { |
1401 | List in = (List) _in; |
1402 | String out = (String) _out; |
1403 | BigInteger[] inNumbers = getNumbers(in); |
1404 | BigInteger[] outNumbers = new BigInteger[] {getNumber(out)}; |
1405 | findOperation(inNumbers, outNumbers); |
1406 | if (debug) |
1407 | System.out.println("Operations: " + possibleOperations); |
1408 | } |
1409 | |
1410 | public void findOperation(BigInteger[] in, BigInteger[] out) { |
1411 | filterOperations(in, out); |
1412 | if (possibleOperations.isEmpty()) |
1413 | fail("tilt"); |
1414 | } |
1415 | |
1416 | public void filterOperations(BigInteger[] in, BigInteger[] out) { |
1417 | for (Iterator<String> i = possibleOperations.iterator(); i.hasNext(); ) { |
1418 | String op = i.next(); |
1419 | BigInteger[] out2 = doOperation(op, in); |
1420 | if (out2 == null || !arraysEqual(out, out2)) |
1421 | i.remove(); // keep only matching operations |
1422 | } |
1423 | } |
1424 | |
1425 | public BigInteger[] doOperation(String op, BigInteger[] in) { |
1426 | op = op.intern(); |
1427 | try { |
1428 | if (in.length == 2) { |
1429 | BigInteger a = in[0], b = in[1], x = null; |
1430 | if (op == "+") |
1431 | x = a.add(b); |
1432 | else if (op == "-") |
1433 | x = a.subtract(b); |
1434 | else if (op == "*") |
1435 | x = a.multiply(b); |
1436 | else if (op == "/") |
1437 | x = a.divide(b); |
1438 | return x != null ? new BigInteger[] {x} : null; |
1439 | } |
1440 | return null; |
1441 | } catch (Throwable e) { |
1442 | return null; |
1443 | } |
1444 | } |
1445 | |
1446 | public String processIn(Object _in) { |
1447 | List<String> in = (List<String>) _in; |
1448 | String op = possibleOperations.iterator().next(); |
1449 | if (debug) |
1450 | System.out.println("op: " + op); |
1451 | BigInteger[] inNumbers = getNumbers(in); |
1452 | BigInteger[] outNumbers = doOperation(op, inNumbers); |
1453 | return outNumbers[0].toString(); |
1454 | } |
1455 | |
1456 | String BI = BigInteger.class.getName(); |
1457 | |
1458 | public void toJava(Code code) { |
1459 | String op = possibleOperations.iterator().next(); |
1460 | String a = "new " + BI + "((String) " + code.list() + ".get(0))"; |
1461 | String b = "new " + BI + "((String) " + code.list() + ".get(1))"; |
1462 | if (op.equals("+")) |
1463 | code.assign(a + ".add(" + b + ").toString()"); |
1464 | else |
1465 | todo(); |
1466 | } |
1467 | |
1468 | static BigInteger[] getNumbers(List<String> in) { |
1469 | BigInteger[] big = new BigInteger[in.size()]; |
1470 | for (int i = 0; i < in.size(); i++) |
1471 | big[i] = new BigInteger(in.get(i)); |
1472 | return big; |
1473 | } |
1474 | |
1475 | static BigInteger getNumber(String s) { |
1476 | return new BigInteger(s); |
1477 | } |
1478 | |
1479 | static boolean arraysEqual(BigInteger[] a, BigInteger[] b) { |
1480 | if (a.length != b.length) return false; |
1481 | for (int i = 0; i < a.length; i++) |
1482 | if (!a[i].equals(b[i])) return false; |
1483 | return true; |
1484 | } |
1485 | } |
1486 | |
1487 | static class EscapeCase implements Function { |
1488 | static boolean debug; |
1489 | |
1490 | public Object process(Object _in) { |
1491 | if (debug) |
1492 | System.out.println("EscapeCase: " + _in); |
1493 | String in = (String) _in; |
1494 | return in.equals("case") ? "_case" : in; |
1495 | } |
1496 | |
1497 | public void toJava_process(Code code) { |
1498 | code.line("if (\"case\".equals(" + code.var + ")) " + code.var + " = " + quote("_case") + ";"); |
1499 | } |
1500 | } |
1501 | |
1502 | static class LCharShift extends LearnerImpl { |
1503 | int shift; |
1504 | |
1505 | public void processInOut(Object _in, Object _out) { |
1506 | String in = (String) _in, out = (String) _out; |
1507 | shift = (int) out.charAt(0) - (int) in.charAt(0); |
1508 | } |
1509 | |
1510 | public Object processIn(Object _in) { |
1511 | String in = (String) _in; |
1512 | char[] c = new char[in.length()]; |
1513 | for (int i = 0; i < c.length; i++) |
1514 | c[i] = (char) ((int) in.charAt(i) + shift); |
1515 | return new String(c); |
1516 | } |
1517 | |
1518 | public void toJava(Code code) { |
1519 | code.line("char[] c = new char[((String) " + code.var + ").length()];"); |
1520 | code.line("for (int i = 0; i < c.length; i++)"); |
1521 | code.line(" c[i] = (char) ((int) ((String) " + code.var + ").charAt(i)" + (shift < 0 ? "" + shift : "+" + shift) + ");"); |
1522 | code.line(code.var + " = new String(c);"); |
1523 | } |
1524 | } |
1525 | |
1526 | // applies base learner to first char of string |
1527 | // (or first element of list, TODO) |
1528 | static class LFirst extends LearnerImpl { |
1529 | Learner baseLearner; |
1530 | |
1531 | *(Learner baseLearner) { |
1532 | this.baseLearner = baseLearner; |
1533 | } |
1534 | |
1535 | public void processInOut(Object _in, Object _out) { |
1536 | String in = (String) _in, out = (String) _out; |
1537 | if (in.length() == 0) |
1538 | return; |
1539 | String firstIn = in.substring(0, 1), firstOut = out.substring(0, 1); |
1540 | baseLearner.processInOut(firstIn, firstOut); |
1541 | } |
1542 | |
1543 | public Object processIn(Object _in) { |
1544 | String in = (String) _in; |
1545 | if (in.length() == 0) |
1546 | return in; |
1547 | String firstIn = in.substring(0, 1); |
1548 | return baseLearner.processIn(firstIn) + in.substring(1); |
1549 | } |
1550 | |
1551 | public void toJava(Code code) { |
1552 | code.line("if (" + code.s() + ".length() != 0) {"); |
1553 | code.indent(); |
1554 | code.line("String rest = " + code.s() + ".substring(1);"); |
1555 | code.line(code.var + " = " + code.s() + ".substring(0, 1);"); |
1556 | baseLearner.toJava(code); |
1557 | code.line(code.var + " = " + code.s() + "+rest;"); |
1558 | code.unindent(); |
1559 | code.line("}"); |
1560 | } |
1561 | } |
1562 | |
1563 | static Method findMainMethod(Class<?> theClass) { |
1564 | for (Method method : theClass.getMethods()) |
1565 | if (method.getName().equals("main") && method.getParameterTypes().length == 1) |
1566 | return method; |
1567 | throw new RuntimeException("Method 'main' with 1 parameter not found in " + theClass.getName()); |
1568 | } |
1569 | |
1570 | // compile JavaX source and load main class |
1571 | static Class<?> compileAndLoadMainClass(String src) tex { |
1572 | File srcDir = _x18.TempDirMaker_make(); |
1573 | File classesDir = _x18.TempDirMaker_make(); |
1574 | _x18.saveTextFile(new File(srcDir, "main.java").getPath(), src); |
1575 | new List<File> libraries; |
1576 | File transpiledDir = _x18.topLevelTranslate(srcDir, libraries); |
1577 | String javacOutput = _x18.compileJava(transpiledDir, libraries, classesDir); |
1578 | System.out.println(javacOutput); |
1579 | URL[] urls = {classesDir.toURI().toURL()}; |
1580 | |
1581 | // make class loader |
1582 | URLClassLoader classLoader = new URLClassLoader(urls); |
1583 | |
1584 | // load main class |
1585 | Class<?> mainClass = classLoader.loadClass("main"); |
1586 | return mainClass; |
1587 | } |
1588 | |
1589 | static Method compileJavaInToOut(Code code) { |
1590 | try { |
1591 | String java = code.buf.toString(); |
1592 | String prelude = /*"import java.util.*;\n\n" +*/ |
1593 | "public class main { public static Object main(Object in) throws Exception {\n"; |
1594 | String postlude = "\nreturn in;\n}}"; |
1595 | String src = code.getTranslators() + "\n" + prelude + java + postlude; |
1596 | Class<?> mainClass = compileAndLoadMainClass(src); |
1597 | return findMainMethod(mainClass); |
1598 | } catch (Exception e) { |
1599 | throw new RuntimeException(e); |
1600 | } |
1601 | } |
1602 | |
1603 | static Method findCalcMethod(Class<?> theClass) { |
1604 | for (Method method : theClass.getMethods()) |
1605 | if (method.getName().equals("calc")) |
1606 | return method; |
1607 | throw new RuntimeException("Method 'calc' not found in " + theClass.getName()); |
1608 | } |
1609 | |
1610 | // for simplejava stuff (execute tasks) |
1611 | static String execute(String src) { |
1612 | try { |
1613 | Class<?> mainClass = compileAndLoadMainClass(src); |
1614 | Method m = findCalcMethod(mainClass); |
1615 | return String.valueOf(m.invoke(null)); |
1616 | } catch (Exception e) { |
1617 | throw new RuntimeException(e); |
1618 | } |
1619 | } |
1620 | |
1621 | static void testJava(Case case, Code code) { |
1622 | try { |
1623 | Method m = compileJavaInToOut(code); |
1624 | |
1625 | for (String[] e : case.fullExamples) { |
1626 | String out = (String) m.invoke(null, e[0]); |
1627 | |
1628 | if (!e[1].equals(out)) { |
1629 | throw new RuntimeException("[fail] Java code on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1])); |
1630 | } |
1631 | } |
1632 | |
1633 | System.out.println("\nGOOD JAVA."); |
1634 | case.goodJava = true; |
1635 | } catch (Throwable e) { |
1636 | if (showFails) |
1637 | e.printStackTrace(); |
1638 | System.out.println("\nBAD JAVA."); |
1639 | } |
1640 | } |
1641 | |
1642 | static void todo() { |
1643 | fail("todo"); |
1644 | } |
1645 | |
1646 | static class LSwitch extends LearnerImpl { |
1647 | Case case; |
1648 | Learner switcher; |
1649 | |
1650 | *(Case case, Learner switcher) { |
1651 | this.case = case; |
1652 | this.switcher = switcher; |
1653 | } |
1654 | |
1655 | public void processInOut(Object in, Object out) { |
1656 | } |
1657 | |
1658 | public Object processIn(Object in) { |
1659 | int i = Integer.parseInt((String) switcher.processIn(in)); |
1660 | return case.combined.get(i-1).winner.processIn(in); |
1661 | } |
1662 | |
1663 | public void toJava(Code code) { |
1664 | todo(); |
1665 | } |
1666 | } |
1667 | |
1668 | static class LTryPrevious extends LearnerImpl { |
1669 | new List<Case> candidates; |
1670 | |
1671 | *() { |
1672 | for (int i = caseIdx-1; i >= 0; i--) |
1673 | candidates.add(cases.get(i)); |
1674 | } |
1675 | |
1676 | public void processInOut(Object _in, Object _out) { |
1677 | String in = (String) _in, out = (String) _out; |
1678 | for (ListIterator<Case> i = candidates.listIterator(); i.hasNext(); ) { |
1679 | Case case = i.next(); |
1680 | if (case.winner == null || !validate(new String[] {in, out}, case.winner)) |
1681 | i.remove(); |
1682 | } |
1683 | if (candidates.isEmpty()) |
1684 | fail("no previous solution found"); |
1685 | } |
1686 | |
1687 | public Object processIn(Object in) { |
1688 | return candidates.get(0).winner.processIn(in); |
1689 | } |
1690 | |
1691 | public void toJava(Code code) { |
1692 | candidates.get(0).winner.toJava(code); |
1693 | } |
1694 | } |
1695 | |
1696 | static class LMulti extends LearnerImpl { |
1697 | static boolean debug; |
1698 | new List<Learner> candidates; |
1699 | |
1700 | *(Learner... learners) { |
1701 | for (Learner l : learners) |
1702 | candidates.add(l); |
1703 | } |
1704 | |
1705 | *(L<Learner> learners) { |
1706 | for (Learner l : learners) |
1707 | candidates.add(l); |
1708 | } |
1709 | |
1710 | *(Learner l, L<Learner> ll) { |
1711 | candidates.add(l); |
1712 | candidates.addAll(ll); |
1713 | } |
1714 | |
1715 | public void processInOut(Object in, Object out) { |
1716 | if (debug) |
1717 | System.err.println("LMulti candidates: " + candidates.size()); |
1718 | for (ListIterator<Learner> i = candidates.listIterator(); i.hasNext(); ) { |
1719 | Learner l = i.next(); |
1720 | try { |
1721 | l.processInOut(in, out); |
1722 | } catch (Throwable e) { |
1723 | if (debug) { |
1724 | e.printStackTrace(); |
1725 | System.err.println("Removing candidate: " + structure(l)); |
1726 | } |
1727 | silentException(e); |
1728 | i.remove(); |
1729 | } |
1730 | } |
1731 | if (debug) |
1732 | System.err.println("LMulti candidates now: " + candidates.size()); |
1733 | if (candidates.isEmpty()) |
1734 | fail("no candidates left"); |
1735 | } |
1736 | |
1737 | public Object processIn(Object in) { |
1738 | while (true) { // fails or returns eventually |
1739 | Learner l = candidates.get(0); |
1740 | if (debug) |
1741 | System.err.println("Using candidate: " + structure(l) + ", " + candidates.size() + " left"); |
1742 | try { |
1743 | return l.processIn(in); |
1744 | } catch (Throwable e) { |
1745 | if (debug) { |
1746 | e.printStackTrace(); |
1747 | System.err.println("Removing candidate: " + structure(l)); |
1748 | } |
1749 | silentException(e); |
1750 | candidates.remove(0); |
1751 | } |
1752 | } |
1753 | } |
1754 | |
1755 | public void tryAgain() { |
1756 | candidates.remove(0); |
1757 | } |
1758 | |
1759 | public void toJava(Code code) { |
1760 | candidates.get(0).toJava(code); |
1761 | } |
1762 | } |
1763 | |
1764 | static String structure(Object o) { |
1765 | if (o == null) return "null"; |
1766 | String name = o.getClass().getName(); |
1767 | |
1768 | new StringBuilder buf; |
1769 | |
1770 | if (o instanceof Collection) { |
1771 | for (Object x : (Collection) o) { |
1772 | if (!buf.isEmpty()) buf.append(", "); |
1773 | buf.append(structure(x)); |
1774 | } |
1775 | return "{" + buf + "}"; |
1776 | } |
1777 | |
1778 | if (o instanceof String) |
1779 | return quote((String) o); |
1780 | |
1781 | // Need more cases? This should cover all library classes... |
1782 | if (name.startsWith("java.") || name.startsWith("javax.")) |
1783 | return String.valueOf(o); |
1784 | |
1785 | String shortName = o.getClass().getName().replaceAll("^main\\$", ""); |
1786 | |
1787 | // TODO: go to superclasses too |
1788 | Field[] fields = o.getClass().getDeclaredFields(); |
1789 | for (Field field : fields) { |
1790 | if ((field.getModifiers() & Modifier.STATIC) != 0) |
1791 | continue; |
1792 | Object value; |
1793 | try { |
1794 | value = field.get(o); |
1795 | } catch (Exception e) { |
1796 | value = "?"; |
1797 | } |
1798 | |
1799 | String fieldName = field.getName(); |
1800 | |
1801 | // special case for LMulti - show only first (current) candidate |
1802 | if (shortName.equals("LMulti") && field.getName().equals("candidates")) { |
1803 | fieldName = "candidate"; |
1804 | value = ((List) value).isEmpty() ? value : ((List) value).get(0); |
1805 | } |
1806 | |
1807 | if (value != null) { |
1808 | if (!buf.isEmpty()) buf.append(", "); |
1809 | buf.append(fieldName + "=" + structure(value)); |
1810 | } |
1811 | } |
1812 | String s = shortName; |
1813 | if (!buf.isEmpty()) |
1814 | s += "(" + buf + ")"; |
1815 | return s; |
1816 | } |
1817 | |
1818 | static class FIsString implements Function { |
1819 | static boolean debug; |
1820 | |
1821 | public Object process(Object _in) { |
1822 | String in = (String) _in; |
1823 | return in.startsWith("\"") || in.startsWith("[[") ? "1" : "0"; |
1824 | } |
1825 | |
1826 | public void toJava_process(Code code) { |
1827 | code.assign(code.s() + ".startsWith(\"\\\"\") || " + code.s() + ".startsWith(\"[[\") ? \"1\" : \"0\""); |
1828 | } |
1829 | } |
1830 | |
1831 | static class FCommonPrefix implements Function { |
1832 | static boolean debug; |
1833 | |
1834 | public Object process(Object _in) { |
1835 | String in = (String) _in, prefix = null; |
1836 | for (String line : toLines(in)) |
1837 | if (line.length() != 0) { |
1838 | prefix = prefix == null ? line : commonPrefix(prefix, line); |
1839 | if (debug) |
1840 | System.out.println("FCommonPrefix: line=" + quote(line) + ", prefix=" + quote(prefix)); |
1841 | } |
1842 | return prefix; |
1843 | } |
1844 | |
1845 | public void toJava_process(Code code) { |
1846 | todo(); |
1847 | } |
1848 | } |
1849 | |
1850 | static class FCommonSuffix implements Function { |
1851 | static boolean debug; |
1852 | |
1853 | public Object process(Object _in) { |
1854 | String in = (String) _in, suffix = null; |
1855 | for (String line : toLines(in)) |
1856 | if (line.length() != 0) { |
1857 | suffix = suffix == null ? line : commonSuffix(suffix, line); |
1858 | if (debug) |
1859 | System.out.println("FCommonSuffix: line=" + quote(line) + ", suffix=" + quote(suffix)); |
1860 | } |
1861 | return suffix; |
1862 | } |
1863 | |
1864 | public void toJava_process(Code code) { |
1865 | todo(); |
1866 | } |
1867 | } |
1868 | |
1869 | /*static class Pair { |
1870 | Object a, b; |
1871 | |
1872 | public boolean equals(Object o) { |
1873 | return o instanceof Pair && a.equals(((Pair) o).a) && b.equals((Pair) o).b); |
1874 | } |
1875 | |
1876 | public int hashCode() { |
1877 | return a.hashCode()+b.hashCode()*2; |
1878 | } |
1879 | }*/ |
1880 | |
1881 | static class Matrix { |
1882 | new HashMap<Object, Map> dataByCol; |
1883 | |
1884 | void put(Object col, Object row, Object value) { |
1885 | //data.put(new Pair(col, row), value); |
1886 | getCol(col).put(row, value); |
1887 | } |
1888 | |
1889 | Map getCol(Object col) { |
1890 | Map map = dataByCol.get(col); |
1891 | if (map == null) |
1892 | dataByCol.put(col, map = new HashMap()); |
1893 | return map; |
1894 | } |
1895 | |
1896 | Object get(Object col, Object row) { |
1897 | //return data.get(new Pair(col, row)); |
1898 | return getCol(col).get(row); |
1899 | } |
1900 | |
1901 | Set cols() { |
1902 | return dataByCol.keySet(); |
1903 | } |
1904 | |
1905 | Set rowsFor(Object col) { |
1906 | return getCol(col).keySet(); |
1907 | } |
1908 | } |
1909 | |
1910 | static class LDistinguishList extends LearnerImpl { |
1911 | static boolean debug; |
1912 | Function helper; |
1913 | int idx; |
1914 | new Matrix matrix; |
1915 | |
1916 | *(Function helper) { |
1917 | this.helper = helper; |
1918 | } |
1919 | |
1920 | public void processInOut(Object _in, Object out) { |
1921 | List in = (List) _in; |
1922 | for (int i = 0; i < in.size(); i++) { |
1923 | Object y = helper.process(in.get(i)); |
1924 | matrix.put(i, y, out); |
1925 | } |
1926 | } |
1927 | |
1928 | public Object processIn(Object _in) { |
1929 | // find idx |
1930 | |
1931 | for (Object i : matrix.cols()) { |
1932 | Collection ys = matrix.rowsFor(i); |
1933 | if (ys.size() > 1) { |
1934 | idx = (Integer) i; |
1935 | break; |
1936 | } |
1937 | } |
1938 | |
1939 | List in = (List) _in; |
1940 | Object y = helper.process(in.get(idx)); |
1941 | return matrix.get(idx, y); |
1942 | } |
1943 | |
1944 | public void toJava(Code code) { |
1945 | List ys = new ArrayList(matrix.rowsFor(idx)); |
1946 | //String v = code.var; |
1947 | //code.newVar(); |
1948 | //String vy = code.var; |
1949 | //code.oldVar(); |
1950 | code.assign(code.list() + ".get(" + idx + ")"); |
1951 | helper.toJava_process(code); |
1952 | |
1953 | for (int i = 0; i < ys.size(); i++) { |
1954 | Object y = ys.get(i); |
1955 | if (i < ys.size()) |
1956 | code.line((i == 0 ? "" : "else ") + "if (" + quote((String) y) + ".equals(" + code.var + "))"); |
1957 | else |
1958 | code.line("else"); |
1959 | code.line(" " + code.var + " = " + quote((String) matrix.get(idx, y)) + ";"); |
1960 | } |
1961 | } |
1962 | } |
1963 | |
1964 | static class RunnersUp { |
1965 | String expected; |
1966 | int bestScore = -1; |
1967 | String bestResult; |
1968 | Learner winner; |
1969 | |
1970 | void add(String expected, String result, int score, Learner learner) { |
1971 | if (!expected.equals(this.expected) || bestScore == -1 || score < bestScore) { |
1972 | bestScore = score; |
1973 | bestResult = result; |
1974 | winner = learner; |
1975 | } |
1976 | this.expected = expected; |
1977 | } |
1978 | } |
1979 | |
1980 | static List<Case> casesSortedByID() { |
1981 | new (Tree)Map<Long, Case> map; |
1982 | new List<Case> rest; |
1983 | for (Case c : cases) |
1984 | if (isSnippetID(c.id)) |
1985 | map.put(parseSnippetID(c.id), c); |
1986 | else |
1987 | rest.add(c); |
1988 | List<Case> list = new ArrayList<Case>(map.values()); |
1989 | list.addAll(rest); |
1990 | return list; |
1991 | } |
1992 | |
1993 | !include #1000388 // leven (Levenshtein distance function) |
1994 | |
1995 | !include #1000382 // Box learners |
1996 | !include #1000387 // Empty box learner |
1997 | |
1998 | // for "find" tasks (e.g. "abcde" to "[[abc]]de") |
1999 | static class LFixedSubstring extends LearnerImpl { |
2000 | static boolean debug; |
2001 | String findMarker1 = "{{", findMarker2 = "}}"; |
2002 | int i, j; |
2003 | |
2004 | public void processInOut(Object _in, Object _out) { |
2005 | String in = (String) _in, out = (String) _out; |
2006 | i = out.indexOf(findMarker1); |
2007 | j = out.indexOf(findMarker2, i)-2; |
2008 | if (debug && j >= 0) { |
2009 | boolean correct = in.substring(i, j).equals(out.substring(i+2, j+2)); |
2010 | System.out.println("LFixedSubstring: i, j = " + i + ", " + j + " " + correct + " " + quote(in.substring(i, j))); |
2011 | } |
2012 | } |
2013 | |
2014 | public String processIn(Object _in) { |
2015 | String in = (String) _in; |
2016 | return in.substring(0, i) + findMarker1 + in.substring(i, j) + findMarker2 + in.substring(j); |
2017 | } |
2018 | } |
2019 | |
2020 | static void print(Object o) { |
2021 | System.out.println(o); |
2022 | } |
2023 | |
2024 | !include #1000459 // LFixWhiteSpace |
2025 | |
2026 | static Object newInstance(Class c, Object... args) ctex { |
2027 | Constructor m = findConstructor(c, args); |
2028 | m.setAccessible(true); |
2029 | return m.newInstance(args); |
2030 | } |
2031 | |
2032 | static Constructor findConstructor(Class c, Object[] args) { |
2033 | for (Constructor m : c.getDeclaredConstructors()) { |
2034 | if (!checkArgs(m.getParameterTypes(), args, false)) |
2035 | continue; |
2036 | return m; |
2037 | } |
2038 | throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName()); |
2039 | } |
2040 | |
2041 | static Class findClass(String name) ctex { |
2042 | for (String c : innerClasses) |
2043 | if (c.equalsIgnoreCase(name)) |
2044 | return Class.forName("main$" + c); |
2045 | return null; |
2046 | } |
2047 | |
2048 | static boolean isSubclass(Class a, Class b) { |
2049 | return b.isAssignableFrom(a); |
2050 | } |
2051 | |
2052 | static boolean checkArgs(Class[] types, Object[] args, boolean debug) { |
2053 | if (types.length != args.length) { |
2054 | if (debug) |
2055 | System.out.println("Bad parameter length: " + args.length + " vs " + types.length); |
2056 | return false; |
2057 | } |
2058 | for (int i = 0; i < types.length; i++) |
2059 | if (!(args[i] == null || types[i].isInstance(args[i]))) { |
2060 | if (debug) |
2061 | System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); |
2062 | return false; |
2063 | } |
2064 | return true; |
2065 | } |
2066 | |
2067 | !include #1000465 // LCertainElement |
2068 | |
2069 | static Class findClassFlex(String p) { |
2070 | Class c = findClass(p); |
2071 | if (c == null) c = findClass("L" + p); |
2072 | if (c == null) c = findClass("F" + p); |
2073 | if (c == null) c = findClass("RF" + p); |
2074 | return c; |
2075 | } |
2076 | |
2077 | !include #1000468 // LOneWordChanged |
2078 | !include #1000470 // LBla |
2079 | } |
Began life as a copy of #716
download show line numbers debug dex old transpilations
Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, jtubtzbbkimh, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
ID | Author/Program | Comment | Date |
---|---|---|---|
381 | #1000610 (pitcher) | 2015-08-18 00:07:07 | |
380 | #1000604 (pitcher) | 2015-08-18 00:07:22 |
Snippet ID: | #717 |
Snippet name: | IOIOI Processor (v13) |
Eternal ID of this version: | #717/1 |
Text MD5: | 1c9c6ededea99cfd3420cd46e9f21688 |
Transpilation MD5: | 38bc22bc44a2cc6aa7be51b7c7c4fb0c |
Author: | stefan |
Category: | |
Type: | JavaX source code |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2015-08-08 19:36:14 |
Source code size: | 63827 bytes / 2079 lines |
Pitched / IR pitched: | No / Yes |
Views / Downloads: | 1093 / 1186 |
Referenced in: | [show references] |