import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
public class main {
static boolean autoQuine = true;
static class Matches {
String[] m;
String get(int i) { return i < m.length ? m[i] : null; }
String unq(int i) { return unquote(get(i)); }
String fsi(int i) { return formatSnippetID(unq(i)); }
String fsi() { return fsi(0); }
String tlc(int i) { return unq(i).toLowerCase(); }
boolean bool(int i) { return "true".equals(unq(i)); }
String rest() { return m[m.length-1]; } // for matchStart
int psi(int i) { return Integer.parseInt(unq(i)); }
}
/**
* A class to compare vectors of objects. The result of comparison
* is a list of change
objects which form an
* edit script. The objects compared are traditionally lines
* of text from two files. Comparison options such as "ignore
* whitespace" are implemented by modifying the equals
* and hashcode
methods for the objects compared.
*
* The basic algorithm is described in:
* "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
* Algorithmica Vol. 1 No. 2, 1986, p 251.
*
* This class outputs different results from GNU diff 1.15 on some
* inputs. Our results are actually better (smaller change list, smaller
* total size of changes), but it would be nice to know why. Perhaps
* there is a memory overwrite bug in GNU diff 1.15.
*
* @author Stuart D. Gathman, translated from GNU diff 1.15
* Copyright (C) 2000 Business Management Systems, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the
* GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
static class EGDiff {
/**
* Prepare to find differences between two arrays. Each element of
* the arrays is translated to an "equivalence number" based on
* the result of equals
. The original Object arrays
* are no longer needed for computing the differences. They will
* be needed again later to print the results of the comparison as
* an edit script, if desired.
*/
public EGDiff(Object[] a, Object[] b) {
Hashtable h = new Hashtable(a.length + b.length);
filevec[0] = new file_data(a, h);
filevec[1] = new file_data(b, h);
}
/**
* 1 more than the maximum equivalence value used for this or its
* sibling file.
*/
private int equiv_max = 1;
/**
* When set to true, the comparison uses a heuristic to speed it up.
* With this heuristic, for files with a constant small density
* of changes, the algorithm is linear in the file size.
*/
public boolean heuristic = false;
/**
* When set to true, the algorithm returns a guarranteed minimal
* set of changes. This makes things slower, sometimes much slower.
*/
public boolean no_discards = false;
private int[] xvec, yvec; /* Vectors being compared. */
private int[] fdiag; /* Vector, indexed by diagonal, containing
the X coordinate of the point furthest
along the given diagonal in the forward
search of the edit matrix. */
private int[] bdiag; /* Vector, indexed by diagonal, containing
the X coordinate of the point furthest
along the given diagonal in the backward
search of the edit matrix. */
private int fdiagoff, bdiagoff;
private final file_data[] filevec = new file_data[2];
private int cost;
/**
* Find the midpoint of the shortest edit script for a specified
* portion of the two files.
*
* We scan from the beginnings of the files, and simultaneously from the ends,
* doing a breadth-first search through the space of edit-sequence.
* When the two searches meet, we have found the midpoint of the shortest
* edit sequence.
*
* The value returned is the number of the diagonal on which the midpoint lies.
* The diagonal number equals the number of inserted lines minus the number
* of deleted lines (counting only lines before the midpoint).
* The edit cost is stored into COST; this is the total number of
* lines inserted or deleted (counting only lines before the midpoint).
*
* This function assumes that the first lines of the specified portions
* of the two files do not match, and likewise that the last lines do not
* match. The caller must trim matching lines from the beginning and end
* of the portions it is going to specify.
*
* Note that if we return the "wrong" diagonal value, or if
* the value of bdiag at that diagonal is "wrong",
* the worst this can do is cause suboptimal diff output.
* It cannot cause incorrect diff output.
*/
private int diag(int xoff, int xlim, int yoff, int ylim) {
final int[] fd = fdiag; // Give the compiler a chance.
final int[] bd = bdiag; // Additional help for the compiler.
final int[] xv = xvec; // Still more help for the compiler.
final int[] yv = yvec; // And more and more . . .
final int dmin = xoff - ylim; // Minimum valid diagonal.
final int dmax = xlim - yoff; // Maximum valid diagonal.
final int fmid = xoff - yoff; // Center diagonal of top-down search.
final int bmid = xlim - ylim; // Center diagonal of bottom-up search.
int fmin = fmid, fmax = fmid; // Limits of top-down search.
int bmin = bmid, bmax = bmid; // Limits of bottom-up search.
/* True if southeast corner is on an odd
diagonal with respect to the northwest. */
final boolean odd = (fmid - bmid & 1) != 0;
fd[fdiagoff + fmid] = xoff;
bd[bdiagoff + bmid] = xlim;
for (int c = 1; ; ++c) {
int d; /* Active diagonal. */
boolean big_snake = false;
/* Extend the top-down search by an edit step in each diagonal. */
if (fmin > dmin)
fd[fdiagoff + --fmin - 1] = -1;
else
++fmin;
if (fmax < dmax)
fd[fdiagoff + ++fmax + 1] = -1;
else
--fmax;
for (d = fmax; d >= fmin; d -= 2) {
int x, y, oldx, tlo = fd[fdiagoff + d - 1], thi = fd[fdiagoff + d + 1];
if (tlo >= thi)
x = tlo + 1;
else
x = thi;
oldx = x;
y = x - d;
while (x < xlim && y < ylim && xv[x] == yv[y]) {
++x;
++y;
}
if (x - oldx > 20)
big_snake = true;
fd[fdiagoff + d] = x;
if (odd && bmin <= d && d <= bmax && bd[bdiagoff + d] <= fd[fdiagoff + d]) {
cost = 2 * c - 1;
return d;
}
}
/* Similar extend the bottom-up search. */
if (bmin > dmin)
bd[bdiagoff + --bmin - 1] = Integer.MAX_VALUE;
else
++bmin;
if (bmax < dmax)
bd[bdiagoff + ++bmax + 1] = Integer.MAX_VALUE;
else
--bmax;
for (d = bmax; d >= bmin; d -= 2) {
int x, y, oldx, tlo = bd[bdiagoff + d - 1], thi = bd[bdiagoff + d + 1];
if (tlo < thi)
x = tlo;
else
x = thi - 1;
oldx = x;
y = x - d;
while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1]) {
--x;
--y;
}
if (oldx - x > 20)
big_snake = true;
bd[bdiagoff + d] = x;
if (!odd && fmin <= d && d <= fmax && bd[bdiagoff + d] <= fd[fdiagoff + d]) {
cost = 2 * c;
return d;
}
}
/* Heuristic: check occasionally for a diagonal that has made
lots of progress compared with the edit distance.
If we have any such, find the one that has made the most
progress and return it as if it had succeeded.
With this heuristic, for files with a constant small density
of changes, the algorithm is linear in the file size. */
if (c > 200 && big_snake && heuristic) {
int best = 0;
int bestpos = -1;
for (d = fmax; d >= fmin; d -= 2) {
int dd = d - fmid;
if ((fd[fdiagoff + d] - xoff) * 2 - dd > 12 * (c + (dd > 0 ? dd : -dd))) {
if (fd[fdiagoff + d] * 2 - dd > best
&& fd[fdiagoff + d] - xoff > 20
&& fd[fdiagoff + d] - d - yoff > 20) {
int k;
int x = fd[fdiagoff + d];
/* We have a good enough best diagonal;
now insist that it end with a significant snake. */
for (k = 1; k <= 20; k++)
if (xvec[x - k] != yvec[x - d - k])
break;
if (k == 21) {
best = fd[fdiagoff + d] * 2 - dd;
bestpos = d;
}
}
}
}
if (best > 0) {
cost = 2 * c - 1;
return bestpos;
}
best = 0;
for (d = bmax; d >= bmin; d -= 2) {
int dd = d - bmid;
if ((xlim - bd[bdiagoff + d]) * 2 + dd > 12 * (c + (dd > 0 ? dd : -dd))) {
if ((xlim - bd[bdiagoff + d]) * 2 + dd > best
&& xlim - bd[bdiagoff + d] > 20
&& ylim - (bd[bdiagoff + d] - d) > 20) {
/* We have a good enough best diagonal;
now insist that it end with a significant snake. */
int k;
int x = bd[bdiagoff + d];
for (k = 0; k < 20; k++)
if (xvec[x + k] != yvec[x - d + k])
break;
if (k == 20) {
best = (xlim - bd[bdiagoff + d]) * 2 + dd;
bestpos = d;
}
}
}
}
if (best > 0) {
cost = 2 * c - 1;
return bestpos;
}
}
}
}
/**
* Compare in detail contiguous subsequences of the two files
* which are known, as a whole, to match each other.
*
* The results are recorded in the vectors filevec[N].changed_flag, by
* storing a 1 in the element for each line that is an insertion or deletion.
*
* The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
*
* Note that XLIM, YLIM are exclusive bounds.
* All line numbers are origin-0 and discarded lines are not counted.
*/
private void compareseq(int xoff, int xlim, int yoff, int ylim) {
/* Slide down the bottom initial diagonal. */
while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff]) {
++xoff;
++yoff;
}
/* Slide up the top initial diagonal. */
while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1]) {
--xlim;
--ylim;
}
/* Handle simple cases. */
if (xoff == xlim)
while (yoff < ylim)
filevec[1].changed_flag[1 + filevec[1].realindexes[yoff++]] = true;
else if (yoff == ylim)
while (xoff < xlim)
filevec[0].changed_flag[1 + filevec[0].realindexes[xoff++]] = true;
else {
/* Find a point of correspondence in the middle of the files. */
int d = diag(xoff, xlim, yoff, ylim);
int c = cost;
int b = bdiag[bdiagoff + d];
if (c == 1) {
/* This should be impossible, because it implies that
one of the two subsequences is empty,
and that case was handled above without calling `diag'.
Let's verify that this is true. */
throw new IllegalArgumentException("Empty subsequence");
} else {
/* Use that point to split this problem into two subproblems. */
compareseq(xoff, b, yoff, b - d);
/* This used to use f instead of b,
but that is incorrect!
It is not necessarily the case that diagonal d
has a snake from b to f. */
compareseq(b, xlim, b - d, ylim);
}
}
}
/**
* Discard lines from one file that have no matches in the other file.
*/
private void discard_confusing_lines() {
filevec[0].discard_confusing_lines(filevec[1]);
filevec[1].discard_confusing_lines(filevec[0]);
}
private boolean inhibit = false;
/**
* Adjust inserts/deletes of blank lines to join changes
* as much as possible.
*/
private void shift_boundaries() {
if (inhibit)
return;
filevec[0].shift_boundaries(filevec[1]);
filevec[1].shift_boundaries(filevec[0]);
}
public interface ScriptBuilder {
/**
* Scan the tables of which lines are inserted and deleted,
* producing an edit script.
*
* @param changed0 true for lines in first file which do not match 2nd
* @param len0 number of lines in first file
* @param changed1 true for lines in 2nd file which do not match 1st
* @param len1 number of lines in 2nd file
* @return a linked list of changes - or null
*/
public change build_script(boolean[] changed0, int len0,
boolean[] changed1, int len1);
}
/**
* Scan the tables of which lines are inserted and deleted,
* producing an edit script in reverse order.
*/
static class ReverseScript implements ScriptBuilder {
public change build_script(final boolean[] changed0, int len0,
final boolean[] changed1, int len1) {
change script = null;
int i0 = 0, i1 = 0;
while (i0 < len0 || i1 < len1) {
if (changed0[1 + i0] || changed1[1 + i1]) {
int line0 = i0, line1 = i1;
/* Find # lines changed here in each file. */
while (changed0[1 + i0]) ++i0;
while (changed1[1 + i1]) ++i1;
/* Record this change. */
script = new change(line0, line1, i0 - line0, i1 - line1, script);
}
/* We have reached lines in the two files that match each other. */
i0++;
i1++;
}
return script;
}
}
static class ForwardScript implements ScriptBuilder {
/**
* Scan the tables of which lines are inserted and deleted,
* producing an edit script in forward order.
*/
public change build_script(final boolean[] changed0, int len0,
final boolean[] changed1, int len1) {
change script = null;
int i0 = len0, i1 = len1;
while (i0 >= 0 || i1 >= 0) {
if (changed0[i0] || changed1[i1]) {
int line0 = i0, line1 = i1;
/* Find # lines changed here in each file. */
while (changed0[i0]) --i0;
while (changed1[i1]) --i1;
/* Record this change. */
script = new change(i0, i1, line0 - i0, line1 - i1, script);
}
/* We have reached lines in the two files that match each other. */
i0--;
i1--;
}
return script;
}
}
/**
* Standard ScriptBuilders.
*/
public final static ScriptBuilder
forwardScript = new ForwardScript(),
reverseScript = new ReverseScript();
/* Report the differences of two files. DEPTH is the current directory
depth. */
public final change diff_2(final boolean reverse) {
return diff(reverse ? reverseScript : forwardScript);
}
/**
* Get the results of comparison as an edit script. The script
* is described by a list of changes. The standard ScriptBuilder
* implementations provide for forward and reverse edit scripts.
* Alternate implementations could, for instance, list common elements
* instead of differences.
*
* @param bld an object to build the script from change flags
* @return the head of a list of changes
*/
public change diff(final ScriptBuilder bld) {
/* Some lines are obviously insertions or deletions
because they don't match anything. Detect them now,
and avoid even thinking about them in the main comparison algorithm. */
discard_confusing_lines();
/* Now do the main comparison algorithm, considering just the
undiscarded lines. */
xvec = filevec[0].undiscarded;
yvec = filevec[1].undiscarded;
int diags =
filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3;
fdiag = new int[diags];
fdiagoff = filevec[1].nondiscarded_lines + 1;
bdiag = new int[diags];
bdiagoff = filevec[1].nondiscarded_lines + 1;
compareseq(0, filevec[0].nondiscarded_lines,
0, filevec[1].nondiscarded_lines);
fdiag = null;
bdiag = null;
/* Modify the results slightly to make them prettier
in cases where that can validly be done. */
shift_boundaries();
/* Get the results of comparison in the form of a chain
of `struct change's -- an edit script. */
return bld.build_script(filevec[0].changed_flag,
filevec[0].buffered_lines,
filevec[1].changed_flag,
filevec[1].buffered_lines);
}
/**
* The result of comparison is an "edit script": a chain of change objects.
* Each change represents one place where some lines are deleted
* and some are inserted.
*
* LINE0 and LINE1 are the first affected lines in the two files (origin 0).
* DELETED is the number of lines deleted here from file 0.
* INSERTED is the number of lines inserted here in file 1.
*
* If DELETED is 0 then LINE0 is the number of the line before
* which the insertion was done; vice versa for INSERTED and LINE1.
*/
public static class change {
/**
* Previous or next edit command.
*/
public change link;
/**
* # lines of file 1 changed here.
*/
public final int inserted;
/**
* # lines of file 0 changed here.
*/
public final int deleted;
/**
* Line number of 1st deleted line.
*/
public final int line0;
/**
* Line number of 1st inserted line.
*/
public final int line1;
/**
* Cons an additional entry onto the front of an edit script OLD.
* LINE0 and LINE1 are the first affected lines in the two files (origin 0).
* DELETED is the number of lines deleted here from file 0.
* INSERTED is the number of lines inserted here in file 1.
*
* If DELETED is 0 then LINE0 is the number of the line before
* which the insertion was done; vice versa for INSERTED and LINE1.
*/
public change(int line0, int line1, int deleted, int inserted, change old) {
this.line0 = line0;
this.line1 = line1;
this.inserted = inserted;
this.deleted = deleted;
this.link = old;
//System.err.println(line0+","+line1+","+inserted+","+deleted);
}
}
/**
* Data on one input file being compared.
*/
class file_data {
/**
* Allocate changed array for the results of comparison.
*/
void clear() {
/* Allocate a flag for each line of each file, saying whether that line
is an insertion or deletion.
Allocate an extra element, always zero, at each end of each vector.
*/
changed_flag = new boolean[buffered_lines + 2];
}
/**
* Return equiv_count[I] as the number of lines in this file
* that fall in equivalence class I.
*
* @return the array of equivalence class counts.
*/
int[] equivCount() {
int[] equiv_count = new int[equiv_max];
for (int i = 0; i < buffered_lines; ++i)
++equiv_count[equivs[i]];
return equiv_count;
}
/**
* Discard lines that have no matches in another file.
*
* A line which is discarded will not be considered by the actual
* comparison algorithm; it will be as if that line were not in the file.
* The file's `realindexes' table maps virtual line numbers
* (which don't count the discarded lines) into real line numbers;
* this is how the actual comparison algorithm produces results
* that are comprehensible when the discarded lines are counted.
*
* When we discard a line, we also mark it as a deletion or insertion
* so that it will be printed in the output.
*
* @param f the other file
*/
void discard_confusing_lines(file_data f) {
clear();
/* Set up table of which lines are going to be discarded. */
final byte[] discarded = discardable(f.equivCount());
/* Don't really discard the provisional lines except when they occur
in a run of discardables, with nonprovisionals at the beginning
and end. */
filterDiscards(discarded);
/* Actually discard the lines. */
discard(discarded);
}
/**
* Mark to be discarded each line that matches no line of another file.
* If a line matches many lines, mark it as provisionally discardable.
*
* @param counts The count of each equivalence number for the other file.
* @return 0=nondiscardable, 1=discardable or 2=provisionally discardable
* for each line
*/
private byte[] discardable(final int[] counts) {
final int end = buffered_lines;
final byte[] discards = new byte[end];
final int[] equivs = this.equivs;
int many = 5;
int tem = end / 64;
/* Multiply MANY by approximate square root of number of lines.
That is the threshold for provisionally discardable lines. */
while ((tem = tem >> 2) > 0)
many *= 2;
for (int i = 0; i < end; i++) {
int nmatch;
if (equivs[i] == 0)
continue;
nmatch = counts[equivs[i]];
if (nmatch == 0)
discards[i] = 1;
else if (nmatch > many)
discards[i] = 2;
}
return discards;
}
/**
* Don't really discard the provisional lines except when they occur
* in a run of discardables, with nonprovisionals at the beginning
* and end.
*/
private void filterDiscards(final byte[] discards) {
final int end = buffered_lines;
for (int i = 0; i < end; i++) {
/* Cancel provisional discards not in middle of run of discards. */
if (discards[i] == 2)
discards[i] = 0;
else if (discards[i] != 0) {
/* We have found a nonprovisional discard. */
int j;
int length;
int provisional = 0;
/* Find end of this run of discardable lines.
Count how many are provisionally discardable. */
for (j = i; j < end; j++) {
if (discards[j] == 0)
break;
if (discards[j] == 2)
++provisional;
}
/* Cancel provisional discards at end, and shrink the run. */
while (j > i && discards[j - 1] == 2) {
discards[--j] = 0;
--provisional;
}
/* Now we have the length of a run of discardable lines
whose first and last are not provisional. */
length = j - i;
/* If 1/4 of the lines in the run are provisional,
cancel discarding of all provisional lines in the run. */
if (provisional * 4 > length) {
while (j > i)
if (discards[--j] == 2)
discards[j] = 0;
} else {
int consec;
int minimum = 1;
int tem = length / 4;
/* MINIMUM is approximate square root of LENGTH/4.
A subrun of two or more provisionals can stand
when LENGTH is at least 16.
A subrun of 4 or more can stand when LENGTH >= 64. */
while ((tem = tem >> 2) > 0)
minimum *= 2;
minimum++;
/* Cancel any subrun of MINIMUM or more provisionals
within the larger run. */
for (j = 0, consec = 0; j < length; j++)
if (discards[i + j] != 2)
consec = 0;
else if (minimum == ++consec)
/* Back up to start of subrun, to cancel it all. */
j -= consec;
else if (minimum < consec)
discards[i + j] = 0;
/* Scan from beginning of run
until we find 3 or more nonprovisionals in a row
or until the first nonprovisional at least 8 lines in.
Until that point, cancel any provisionals. */
for (j = 0, consec = 0; j < length; j++) {
if (j >= 8 && discards[i + j] == 1)
break;
if (discards[i + j] == 2) {
consec = 0;
discards[i + j] = 0;
} else if (discards[i + j] == 0)
consec = 0;
else
consec++;
if (consec == 3)
break;
}
/* I advances to the last line of the run. */
i += length - 1;
/* Same thing, from end. */
for (j = 0, consec = 0; j < length; j++) {
if (j >= 8 && discards[i - j] == 1)
break;
if (discards[i - j] == 2) {
consec = 0;
discards[i - j] = 0;
} else if (discards[i - j] == 0)
consec = 0;
else
consec++;
if (consec == 3)
break;
}
}
}
}
}
/**
* Actually discard the lines.
*
* @param discards flags lines to be discarded
*/
private void discard(final byte[] discards) {
final int end = buffered_lines;
int j = 0;
for (int i = 0; i < end; ++i)
if (no_discards || discards[i] == 0) {
undiscarded[j] = equivs[i];
realindexes[j++] = i;
} else
changed_flag[1 + i] = true;
nondiscarded_lines = j;
}
file_data(Object[] data, Hashtable h) {
buffered_lines = data.length;
equivs = new int[buffered_lines];
undiscarded = new int[buffered_lines];
realindexes = new int[buffered_lines];
for (int i = 0; i < data.length; ++i) {
Integer ir = (Integer) h.get(data[i]);
if (ir == null)
h.put(data[i], new Integer(equivs[i] = equiv_max++));
else
equivs[i] = ir.intValue();
}
}
/**
* Adjust inserts/deletes of blank lines to join changes
* as much as possible.
*
* We do something when a run of changed lines include a blank
* line at one end and have an excluded blank line at the other.
* We are free to choose which blank line is included.
* `compareseq' always chooses the one at the beginning,
* but usually it is cleaner to consider the following blank line
* to be the "change". The only exception is if the preceding blank line
* would join this change to other changes.
*
* @param f the file being compared against
*/
void shift_boundaries(file_data f) {
final boolean[] changed = changed_flag;
final boolean[] other_changed = f.changed_flag;
int i = 0;
int j = 0;
int i_end = buffered_lines;
int preceding = -1;
int other_preceding = -1;
for (; ;) {
int start, end, other_start;
/* Scan forwards to find beginning of another run of changes.
Also keep track of the corresponding point in the other file. */
while (i < i_end && !changed[1 + i]) {
while (other_changed[1 + j++])
/* Non-corresponding lines in the other file
will count as the preceding batch of changes. */
other_preceding = j;
i++;
}
if (i == i_end)
break;
start = i;
other_start = j;
for (; ;) {
/* Now find the end of this run of changes. */
while (i < i_end && changed[1 + i]) i++;
end = i;
/* If the first changed line matches the following unchanged one,
and this run does not follow right after a previous run,
and there are no lines deleted from the other file here,
then classify the first changed line as unchanged
and the following line as changed in its place. */
/* You might ask, how could this run follow right after another?
Only because the previous run was shifted here. */
if (end != i_end
&& equivs[start] == equivs[end]
&& !other_changed[1 + j]
&& end != i_end
&& !((preceding >= 0 && start == preceding)
|| (other_preceding >= 0
&& other_start == other_preceding))) {
changed[1 + end] = true;
changed[1 + start++] = false;
++i;
/* Since one line-that-matches is now before this run
instead of after, we must advance in the other file
to keep in synch. */
++j;
} else
break;
}
preceding = i;
other_preceding = j;
}
}
/**
* Number of elements (lines) in this file.
*/
final int buffered_lines;
/**
* Vector, indexed by line number, containing an equivalence code for
* each line. It is this vector that is actually compared with that
* of another file to generate differences.
*/
private final int[] equivs;
/**
* Vector, like the previous one except that
* the elements for discarded lines have been squeezed out.
*/
final int[] undiscarded;
/**
* Vector mapping virtual line numbers (not counting discarded lines)
* to real ones (counting those lines). Both are origin-0.
*/
final int[] realindexes;
/**
* Total number of nondiscarded lines.
*/
int nondiscarded_lines;
/**
* Array, indexed by real origin-1 line number,
* containing true for a line that is an insertion or a deletion.
* The results of comparison are stored here.
*/
boolean[] changed_flag;
}
}
static class BlockDiff {
public CopyBlock asCopyBlock() { return null; }
public NewBlock asNewBlock () { return null; }
}
static class CopyBlock extends BlockDiff {
int firstLine, lines;
CopyBlock(int firstLine, int lines) {
this.firstLine = firstLine;
this.lines = lines;
}
public CopyBlock asCopyBlock() { return this; }
public int getFirstLine() { return firstLine; }
public int getLines() { return lines; }
}
static class NewBlock extends BlockDiff {
int originalStart;
List contents;
NewBlock(int originalStart, List contents) {
this.originalStart = originalStart;
this.contents = contents;
}
public NewBlock asNewBlock () { return this; }
public int getOriginalStart() {
return originalStart;
}
public List getContents() {
return contents;
}
}
static class ExplodedLine {
int type;
String left, right;
int leftIndex, rightIndex;
ExplodedLine(int type, String left, String right, int leftIndex, int rightIndex) {
this.type = type;
this.left = left;
this.right = right;
this.leftIndex = leftIndex;
this.rightIndex = rightIndex;
}
public int getType() {
return type;
}
public String getLeft() {
return left;
}
public String getRight() {
return right;
}
public int getLeftIndex() {
return leftIndex;
}
public int getRightIndex() {
return rightIndex;
}
}
static class BlockDiffer {
public static final int IDENTICAL = 0;
public static final int DIFFERENT = 1;
public static final int LEFT_ONLY = 2;
public static final int RIGHT_ONLY = 3;
private static void printChange(EGDiff.change change) {
if (change != null) {
System.out.println("line0="+change.line0+", line1="+change.line1
+", inserted="+change.inserted+", deleted="+change.deleted);
printChange(change.link);
}
}
/** Generates the text content of a Unified-format context diff between 2 files
* (NB the 'files-changed' header must be added separately).
*/
public static List generateUniDiff(List fileA, List fileB, int contextSize) {
EGDiff diff = new EGDiff(fileA.toArray(), fileB.toArray());
EGDiff.change change = diff.diff_2(false);
if (change != null) {
int inserted, deleted;
List hunkLines = new ArrayList();
int cumulExtraLinesBwrtA = 0;
// Each hunk is generated with a header
do {
int line0 = change.line0, line1 = change.line1;
int changeStart = ((line1 < line0) ? line1 : line0);
int contextStart = ((changeStart > contextSize) ? changeStart - contextSize : 0);
int headerPosn = hunkLines.size();
// Provide the first lines of context
for (int i = contextStart; i < changeStart; i++)
//System.out.println(" " + fileA.get(i));
hunkLines.add(" " + fileA.get(i));
boolean hunkFinish = false;
// Step through each change giving the change lines and following context
do {
inserted = change.inserted;
deleted = change.deleted;
line0 = change.line0;
line1 = change.line1;
if (line1 < line0) // An insert comes earlier
while (inserted-- > 0)
hunkLines.add("+" + fileB.get(line1++));
while (deleted-- > 0)
hunkLines.add("-" + fileA.get(line0++));
while (inserted-- > 0)
hunkLines.add("+" + fileB.get(line1++));
// Lines following are trailing context, identical in fileA and fileB
// The next change may overlap the context, so check and if so, form one hunk
EGDiff.change nextChange = change.link;
int nextChangeStart = fileA.size();
if (nextChange != null)
nextChangeStart = ((nextChange.line1 < nextChange.line0) ? nextChange.line1 : nextChange.line0);
if (nextChangeStart - line0 > contextSize * 2) { // A separate hunk
nextChangeStart = line0 + contextSize;
hunkFinish = true;
}
if (nextChangeStart > fileA.size())
nextChangeStart = fileA.size(); // Limit to file size
while (line0 < nextChangeStart) {
hunkLines.add(" " + fileA.get(line0++));
line1++; // Keep in sync with trailing context
}
change = change.link;
} while (!hunkFinish && change != null);
int hunkStartB = contextStart + cumulExtraLinesBwrtA;
int hunkTotA = line0 - contextStart;
int hunkTotB = line1 - hunkStartB;
hunkLines.add(headerPosn, "@@ -" + (contextStart + 1) + ',' + hunkTotA +
" +" + (hunkStartB + 1) + ',' + hunkTotB + " @@");
cumulExtraLinesBwrtA += hunkTotB - hunkTotA;
} while (change != null);
return hunkLines;
}
return null;
}
/* For testing:
private static void printUniDiff(List fileA, List fileB, int contextSize) {
List uniDiff = generateUniDiff(fileA, fileB, contextSize);
if (uniDiff != null)
for (int j = 0; j < uniDiff.size(); j++)
System.out.println(uniDiff.get(j));
}
*/
public static List diffLines(List lines, List reference) {
List diffs = new ArrayList();
EGDiff diff = new EGDiff(reference.toArray(), lines.toArray());
EGDiff.change change = diff.diff_2(false);
//printChange(change);
//printUniDiff(reference, lines, 3);
int l0 = 0, l1 = 0;
while (change != null) {
if (change.line0 > l0 && change.line1 > l1)
diffs.add(new CopyBlock(l0, change.line0-l0));
if (change.inserted != 0)
diffs.add(new NewBlock(change.line1, lines.subList(change.line1, change.line1+change.inserted)));
l0 = change.line0 + change.deleted;
l1 = change.line1 + change.inserted;
change = change.link;
}
if (l0 < reference.size())
diffs.add(new CopyBlock(l0, reference.size()-l0));
return diffs;
}
/** fills files with empty lines to align matching blocks
*
* @param file1 first file
* @param file2 second file
* @return an array with two lists
*/
public static List explode(List file1, List file2) {
List lines = new ArrayList();
List diffs = BlockDiffer.diffLines(file2, file1);
int lastLineCopied = 0, rightOnlyStart = -1, rightPosition = 0;
for (int i = 0; i < diffs.size(); i++) {
BlockDiff diff = diffs.get(i);
if (diff instanceof CopyBlock) {
CopyBlock copyBlock = (CopyBlock) diff;
if (lastLineCopied < copyBlock.getFirstLine()) {
if (rightOnlyStart >= 0) {
int overlap = Math.min(lines.size()-rightOnlyStart, copyBlock.getFirstLine()-lastLineCopied);
//lines.subList(rightOnlyStart, rightOnlyStart+overlap).clear();
convertRightOnlyToDifferent(lines, rightOnlyStart, overlap, file1, lastLineCopied);
lastLineCopied += overlap;
}
addBlock(lines, LEFT_ONLY, file1, lastLineCopied, copyBlock.getFirstLine(), lastLineCopied, -1);
}
addBlock(lines, IDENTICAL, file1, copyBlock.getFirstLine(), copyBlock.getFirstLine()+copyBlock.getLines(),
copyBlock.getFirstLine(), rightPosition);
rightPosition += copyBlock.getLines();
lastLineCopied = copyBlock.getFirstLine()+copyBlock.getLines();
rightOnlyStart = -1;
} else if (diff instanceof NewBlock) {
NewBlock newBlock = (NewBlock) diff;
/*if (nextDiff instanceof BlockDiffer.CopyBlock) {
BlockDiffer.CopyBlock copyBlock = (BlockDiffer.CopyBlock) nextDiff;
copyBlock.getFirstLine()-lastLineCopied*/
rightOnlyStart = lines.size();
addBlock(lines, RIGHT_ONLY, newBlock.getContents(), 0, newBlock.getContents().size(), -1, rightPosition);
rightPosition += newBlock.getContents().size();
}
}
if (rightOnlyStart >= 0) {
int overlap = Math.min(lines.size()-rightOnlyStart, file1.size()-lastLineCopied);
//lines.subList(rightOnlyStart, rightOnlyStart+overlap).clear();
convertRightOnlyToDifferent(lines, rightOnlyStart, overlap, file1, lastLineCopied);
lastLineCopied += overlap;
}
addBlock(lines, LEFT_ONLY, file1, lastLineCopied, file1.size(), lastLineCopied, -1);
return lines;
}
private static void convertRightOnlyToDifferent(List lines, int start, int numLines,
List leftLines, int leftStart) {
for (int i = 0; i < numLines; i++) {
ExplodedLine line = lines.get(start+i);
lines.set(start+i,
new ExplodedLine(DIFFERENT, leftLines.get(i+leftStart), line.getRight(), i+leftStart, line.getRightIndex()));
}
}
private static void addBlock(List lines, int type, List srcLines, int start, int end,
int leftStart, int rightStart) {
for (int i = start; i < end; i++)
lines.add(new ExplodedLine(type, type == RIGHT_ONLY ? "" : srcLines.get(i),
type == LEFT_ONLY ? "" : srcLines.get(i),
type == RIGHT_ONLY ? -1 : i - start + leftStart,
type == LEFT_ONLY ? -1 : i - start + rightStart));
}
public static List condense(List lines) {
List result = new ArrayList();
for (Iterator i = lines.iterator(); i.hasNext();) {
ExplodedLine line = i.next();
if (line.getType() == IDENTICAL) {
if (result.isEmpty() || result.get(result.size()-1).getType() != IDENTICAL)
result.add(new ExplodedLine(IDENTICAL, "[...]", "[...]", -1, -1));
} else
result.add(line);
}
return result;
}
}
static abstract class DialogIO {
String line;
boolean eos, loud, noClose;
abstract String readLineImpl();
abstract boolean isStillConnected();
abstract void sendLine(String line);
abstract boolean isLocalConnection();
abstract Socket getSocket();
abstract void close();
int getPort() { return getSocket().getPort(); }
boolean helloRead;
int shortenOutputTo = 500;
String readLineNoBlock() {
String l = line;
line = null;
return l;
}
boolean waitForLine() { try {
if (line != null) return true;
//print("Readline");
line = readLineImpl();
//print("Readline done: " + line);
if (line == null) eos = true;
return line != null;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
String readLine() {
waitForLine();
helloRead = true;
return readLineNoBlock();
}
String ask(String s, Object... args) {
if (loud) return askLoudly(s, args);
if (!helloRead) readLine();
if (args.length != 0) s = format3(s, args);
sendLine(s);
return readLine();
}
String askLoudly(String s, Object... args) {
if (!helloRead) readLine();
if (args.length != 0) s = format3(s, args);
print("> " + shorten(s, shortenOutputTo));
sendLine(s);
String answer = readLine();
print("< " + shorten(answer, shortenOutputTo));
return answer;
}
void pushback(String l) {
if (line != null)
throw fail();
line = l;
helloRead = false;
}
}
static abstract class DialogHandler {
abstract void run(DialogIO io);
}
static class IndexedList2 extends AbstractList {
ArrayList l = new ArrayList();
MultiSet index = new MultiSet(false); // HashMap
static boolean debug;
static int instances;
IndexedList2() {
++instances;
}
IndexedList2(List x) {
this();
l.ensureCapacity(l(x));
addAll(x);
}
// required immutable list methods
@Override
public A get(int i) {
return l.get(i);
}
@Override
public int size() {
return l.size();
}
// required mutable list methods
@Override
public A set(int i, A a) {
A prev = l.get(i);
if (prev != a) {
index.remove(prev);
index.add(a);
}
l.set(i, a);
return prev;
}
@Override
public void add(int i, A a) {
index.add(a);
l.add(i, a);
}
@Override
public A remove(int i) {
A a = l.get(i);
index.remove(a);
l.remove(i);
return a;
}
// speed up methods
@Override
protected void removeRange(int fromIndex, int toIndex) {
for (int i = fromIndex; i < toIndex; i++)
unindex(i);
l.subList(fromIndex, toIndex).clear();
}
@Override
public int indexOf(Object a) {
if (!contains(a)) return -1;
return l.indexOf(a);
}
@Override
public boolean contains(Object a) {
boolean b = index.contains((A) a);
if (debug) print("IndexedList2.contains " + a + " => " + b);
return b;
}
@Override
public void clear() {
index.clear();
l.clear();
}
@Override
public boolean addAll(int i, Collection extends A> c) {
index.addAll((Collection) c);
return l.addAll(i, c);
}
// indexing methods
void unindex(int i) {
index.remove(l.get(i));
}
void index(int i) {
index.add(l.get(i));
}
// static methods
static IndexedList2 ensureIndexed(List l) {
return l instanceof IndexedList2 ? (IndexedList2) l : new IndexedList2(l);
}
}
// uses HashMap by default
static class MultiSet {
Map map = new HashMap();
public MultiSet(boolean useTreeMap) {
if (useTreeMap)
map = new TreeMap();
}
public MultiSet() {
}
public MultiSet(Collection c) {
addAll(c);
}
public void add(A key) {
add(key, 1);
}
public void addAll(Collection c) {
if (c != null) for (A a : c)
add(a);
}
public void add(A key, int count) {
if (map.containsKey(key))
map.put(key, map.get(key)+count);
else
map.put(key, count);
}
public int get(A key) {
return key != null && map.containsKey(key) ? map.get(key) : 0;
}
public boolean contains(A key) {
return map.containsKey(key);
}
public void remove(A key) {
Integer i = map.get(key);
if (i != null && i > 1)
map.put(key, i - 1);
else
map.remove(key);
}
public List getTopTen() {
return getTopTen(10);
}
public List getTopTen(int maxSize) {
List list = getSortedListDescending();
return list.size() > maxSize ? list.subList(0, maxSize) : list;
}
List highestFirst() {
return getSortedListDescending();
}
List lowestFirst() {
return reversedList(getSortedListDescending());
}
public List getSortedListDescending() {
List list = new ArrayList(map.keySet());
Collections.sort(list, new Comparator() {
public int compare(A a, A b) {
return map.get(b).compareTo(map.get(a));
}
});
return list;
}
public int getNumberOfUniqueElements() {
return map.size();
}
int uniqueSize() {
return map.size();
}
public Set asSet() {
return map.keySet();
}
Set keySet() { // synonym for idiots
return map.keySet();
}
public A getMostPopularEntry() {
int max = 0;
A a = null;
for (Map.Entry entry : map.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
a = entry.getKey();
}
}
return a;
}
public void removeAll(A key) {
map.remove(key);
}
public int size() {
int size = 0;
for (int i : map.values())
size += i;
return size;
}
public MultiSet mergeWith(MultiSet set) {
MultiSet result = new MultiSet();
for (A a : set.asSet()) {
result.add(a, set.get(a));
}
return result;
}
public boolean isEmpty() {
return map.isEmpty();
}
public String toString() {
return structure(this);
}
public void clear() {
map.clear();
}
Map asMap() {
return cloneMap(map);
}
}
static ThreadLocal DynamicObject_loading = new ThreadLocal();
static class DynamicObject {
String className; // just the name, without the "main$"
Map fieldValues = new HashMap();
DynamicObject() {}
// className = just the name, without the "main$"
DynamicObject(String className) {
this.className = className;}
}
static class CompilerBot {
static boolean verbose;
// returns jar path
static File compileSnippet(String snippetID) {
String transpiledSrc = getServerTranspiled2(snippetID);
int i = transpiledSrc.indexOf('\n');
String libs = transpiledSrc.substring(0, Math.max(0, i));
if (verbose)
print("Compiling snippet: " + snippetID + ". Libs: " + libs);
transpiledSrc = transpiledSrc.substring(i+1);
return compile(transpiledSrc, libs);
}
static File compile(String src) {
return compile(src, "");
}
static File compile(String src, String libs) {
return compile(src, libs, null);
}
static File compile(String src, String dehlibs, String javaTarget) {
if (verbose)
print("Compiling " + l(src) + " chars");
String md5 = md5(dehlibs + "\n" + src);
File jar = getJarFile(md5);
if (jar == null || jar.length() <= 22) {
// have to compile
javaCompileToJar(src, dehlibs, jar);
} else {
if (verbose)
print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)");
touchFile(jar); // so we can find the unused ones easier
}
return jar;
}
static File getJarFile(String md5) {
assertTrue(isMD5(md5));
return new File(getCacheProgramDir("#1002203"), md5 + ".jar");
}
}
// hmm, this shouldn't call functions really. That was just
// for coroutines.
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
return ((Boolean) callF(o)).booleanValue();
}
static boolean isTrue(Object pred, Object arg) {
return booleanValue(callF(pred, arg));
}
static int varCount;
static Map snippetCache = new HashMap();
static boolean useIndexedList = true, opt_javaTok = true;
public static void main(final String[] args) throws Exception {
if (useIndexedList) findCodeTokens_debug = true;
javaTok_opt = opt_javaTok;
findCodeTokens_indexed = findCodeTokens_unindexed = 0;
findCodeTokens_bails = findCodeTokens_nonbails = 0;
javaTok_n = javaTok_elements = 0;
print("759 STARTING " + identityHashCode(main.class));
varCount = 0;
List tok = jtok(loadMainJava());
List ts = findTranslators(toLines(join(tok)));
//print("Translators in source at start: " + structure(ts));
// "duplicate" statement
List lines = toLines(join(tok));
call(getJavaX(), "findTranslators", lines);
Matches m = new Matches();
if (match("duplicate *", fromLines(lines), m)) {
// actual copying - unused
// tok = jtok(loadSnippet(m.get(0)));
// reference by include()
tok = jtok("m { p { callMain(include(" + quote(m.get(0)) + ")); } }");
}
// add m { }
if (!hasCodeTokens(tok, "m", "{") && !hasCodeTokens(tok, "main", "{") && !hasCodeTokens(tok, "class", "main"))
tok = jtok(moveImportsUp("m {\n" + join(tok) + "\n}"));
// standard translate
ts = findTranslators(toLines(join(tok)));
//print("Translators in source: " + structure(ts));
tok = jtok(defaultTranslate(join(tok)));
//print("end of default translate");
//print(join(tok));
tok_autoCloseBrackets(tok);
tok = processIncludes(tok); // before standard functions
processConceptsDot(tok);
tok = processIncludes(tok);
earlyStuff(tok);
int safety = 0;
boolean same;
do {
String before = join(tok);
tok = standardFunctions(tok);
tok = stdstuff(tok); // standard functions and all the keywords
String diff;
long startTime = now();
//diff = unidiff(before, join(tok));
//print("unidiff: " + (now()-startTime) + " ms");
//same = eq(diff, "");
same = eq(before, join(tok)); // << could be sped up
if (!same) {
print("Not same " + safety + ".");
//print(indent(2, diff));
}
if (safety++ >= 10) {
//print(unidiff(before, join(tok)));
print("----");
print(join(tok));
print("----");
throw fail("safety 10 error!");
}
} while (!same);
// POST-PROCESSING after stdstuff loop
quicknew2(tok);
//tok = jtok(quicknew(join(tok)));
tok = extendClasses(tok);
libs(tok);
sourceCodeLine(tok);
throwFail(tok);
innerClassesVar(tok);
tok = autoImports(tok); // faster to do it at the end
if (useIndexedList)
print("Indexed/unindexed lookups: " + findCodeTokens_indexed + "/" + findCodeTokens_unindexed + ", lists made: " + IndexedList2.instances);
print("findCodeToken bails: " + findCodeTokens_bails + "/" + findCodeTokens_nonbails);
print("javaToks: " + javaTok_n + "/" + javaTok_elements);
if (tok.contains("package"))
splitJavaFiles(tok);
else
saveMainJava(tok);
}
static List stdstuff(List tok) {
//if (++level >= 10) fail("woot? 10");
print("stdstuff!");
int i;
if (jfind(tok, "!") >= 0) {
List lines = toLines(join(tok));
List ts = findTranslators(lines);
tok = jtok(fromLines(lines));
print("DROPPING TRANSLATORS: " + structure(ts));
}
tok = quickmain(tok);
tok = processIncludes(tok);
processConceptsDot(tok);
tok = processIncludes(tok);
earlyStuff(tok);
tok = multilineStrings(tok);
inStringEvals(tok);
listComprehensions(tok);
directSnippetRefs(tok);
quicknu(tok);
jreplace(tok, "synced ", "synchronized $2");
tok = replaceKeywordBlock(tok, "answer",
"static S answer(S s) {\nfinal new Matches m;\n",
"\nret null;\n}");
tok = replaceKeywordBlock(tok, "loading",
"{ JWindow _loading_window = showLoadingAnimation(); try { /* loading try */ ",
"/* loading try */ } finally { disposeWindow(_loading_window); }\n /* loading end */ } /* after loading */ \n");
tok = replaceKeywordBlock(tok, "html",
"static O html(S uri, fMap params) ctex " + "{\n", "}");
// "static sync" => static synchronized
jreplace(tok, "static sync", "static synchronized");
// "sclass" => static class
jreplace(tok, "sclass", "static class");
// "asclass" => abstract static class
jreplace(tok, "asclass", "abstract static class");
// "sinterface" => static interface
jreplace(tok, "sinterface", "static interface");
// "ssynchronized" => static synchronized
jreplace(tok, "ssynchronized", "static synchronized");
jreplace(tok, "ssvoid", "static synchronized void");
jreplace(tok, "svoid", "static void");
jreplace(tok, "sbool", "static bool");
jreplace(tok, "sint", "static int");
jreplace(tok, "snew", "static new");
jreplace(tok, "sv ", "static void $2");
jreplace(tok, "pvoid", "public void");
// "sS" => static S
jreplace(tok, "sS", "static S");
// "sO" => static O
jreplace(tok, "sO", "static O");
// "sL" => static L
jreplace(tok, "sL", "static L");
// "toString {" => "public S toString() {"
jreplace(tok, "toString {", "public S toString() {");
jreplace(tok, "Int", "Integer");
jreplace(tok, "Bool", "Boolean");
jreplace(tok, "Char", "Character");
// I REALLY wanted to avoid this, but eh...
jreplace(tok, "SS", "Map");
// "catch {" => "catch (Throwable _e) {"
jreplace(tok, "catch {", "catch (Throwable _e) {");
// "catch X e {" => "catch (X e) {"
jreplace(tok, "catch {", "catch ($2 $3) {");
// "catch e {" => "catch (Throwable e) {" (if e is lowercase)
jreplace(tok, "catch {", "catch (Throwable $2) {", new Object() {
boolean get(List tok, int i) {
String word = tok.get(i+3);
return startsWithLowerCase(word);
}
});
jreplace(tok, "+ +", "+", new Object() {
boolean get(List tok, int i) {
//printStructure("++: ", subList(tok, i-1, i+6));
if (empty(_get(tok, i+2))) return false; // no space between the pluses
if (empty(_get(tok, i)) && eq("+", _get(tok, i-1))) return false; // an actual "++" at the left
if (empty(_get(tok, i+4)) && eq("+", _get(tok, i+5))) return false; // an actual "++" at the right
//print("doing it");
return true;
}
});
// some crazy fancy syntax
jreplace(tok, "set ;", "$2 = true;");
// [stdEq] -> implementation of equals()
jreplace(tok, "[stdEq]",
"public bool equals(O o) { ret stdEq2(this, o); }\n" +
"public int hashCode() { ret stdHash2(this); }");
// [concepts] "concept.field -> bla" for dereferencing references
jreplace(tok, " ->", "$1.get().");
// [concepts] "concept.field!" for dereferencing references
jreplace(tok, "!", "$1.get()", new Object() { boolean get(List tok, int i) {
if (tok.get(i+2).contains("\n")) return false; // no line break between and !
String t = _get(tok, i+5);
if (t == null) return false;
if (isIdentifier(t) || eqOneOf(t, "=", "(")) return false;
return true;
}});
// [concepts] "field := value" for defining fields e.g. in "uniq"
while ((i = jfind(tok, " :=")) >= 0) {
tok.set(i, quote(tok.get(i)));
tok.set(i+2, ",");
tok.set(i+4, "");
reTok(tok, i, i+5);
}
// "quoted" := value
while ((i = jfind(tok, " :=")) >= 0) {
tok.set(i, tok.get(i));
tok.set(i+2, ",");
tok.set(i+4, "");
reTok(tok, i, i+5);
}
// more shortening
jreplace(tok, "fS", "final S");
jreplace(tok, "fO", "final O");
jreplace(tok, "fL", "final L");
jreplace(tok, "fMap", "final Map");
jreplace(tok, "fRunnable", "final Runnable");
jreplace(tok, "f int", "final int");
// "continue unless"
while ((i = jfind(tok, "continue unless")) >= 0) {
int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
replaceTokens(tok, i, i+4, "{ if (!(");
tok.set(j, ")) continue; }");
reTok(tok, i, j+1);
}
// "continue if"
while ((i = jfind(tok, "continue if")) >= 0) {
int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
replaceTokens(tok, i, i+4, "{ if (");
tok.set(j, ") continue; }");
reTok(tok, i, j+1);
}
// "return if"
while ((i = jfind(tok, "return if")) >= 0) {
int j = scanOverExpression(tok, getBracketMap(tok), i+4, ";");
replaceTokens(tok, i, i+4, "{ if (");
tok.set(j, ") return; }");
reTok(tok, i, j+1);
}
// Replace $1 with m.unq(0) etc. - caveat: this blocks identifiers $1, $2, ...
for (i = 1; i < l(tok); i += 2) {
String s = tok.get(i);
if (s.startsWith("$")) {
s = substring(s, 1);
if (isInteger(s)) {
tok.set(i, "m.unq(" + (parseInt(s)-1) + ")");
reTok(tok, i);
}
}
}
// shortened method declarations - hopefully that works
jreplace(tok, "void {", "$1 $2() {");
jreplace(tok, "String {", "$1 $2() {");
jreplace(tok, "Object {", "$1 $2() {");
jreplace(tok, "List {", "$1 $2() {");
// instanceof trickery
jreplace(tok, "is a ", "instanceof $3");
jreplace(tok, "! instanceof .", "!($2 instanceof $4.$6)");
jreplace(tok, "! instanceof ", "!($2 instanceof $4)");
jreplace(tok, " !instanceof ", "!($1 instanceof $4)");
// func keyword for lambdas - now automatically quines toString() if enabled
while ((i = jfind(tok, "func(")) >= 0) {
int argsFrom = i+4, argsTo = findCodeTokens(tok, i, false, ")");
int idx = findCodeTokens(tok, argsTo, false, "{");
int j = findEndOfBracketPart(tok, idx);
List contents = subList(tok, idx+1, j-1);
replaceTokens(tok, i, j, "new O { O get(" + join(subList(tok, argsFrom, argsTo-1)) + ") ct" + "ex { " + tok_addReturn(contents) + " }\n" +
(autoQuine ? " public S toString() { ret " + quote(trim(join(contents))) + "; }" : "") + "}");
reTok(tok, i, j);
}
while ((i = jfind(tok, "voidfunc(")) >= 0) {
int argsFrom = i+4, argsTo = findCodeTokens(tok, i, false, ")");
int idx = findCodeTokens(tok, argsTo, false, "{");
int j = findEndOfBracketPart(tok, idx);
List contents = subList(tok, idx+1, j-1);
replaceTokens(tok, i, j, "new O { void get(" + join(subList(tok, argsFrom, argsTo-1)) + ") ct" + "ex { " + tok_addSemicolon(contents) + " }\n" +
(autoQuine ? " public S toString() { ret " + quote(trim(join(contents))) + "; }" : "") + "}");
reTok(tok, i, j);
}
while ((i = jfind(tok, "func {")) >= 0) {
int idx = findCodeTokens(tok, i, false, "{");
int j = findEndOfBracketPart(tok, idx+2);
List contents = subList(tok, idx+1, j-1);
replaceTokens(tok, i, j, "new O { O get() ct" + "ex { " + tok_addReturn(contents) + " }\n" +
(autoQuine ? " public S toString() { ret " + quote(trim(join(contents))) + "; }" : "") + "}");
reTok(tok, i, j);
}
/*tok = replaceKeywordBlock(tok, "func",
"new O { O get() { ret",
";}}");*/
// shortened subconcept declaration (before star constructors!)
jreplace(tok, " > {", "concept $3 extends $1 {", new Object() { Object get(List tok, int i) {
//print("subconcept: " + quote(tok.get(i)));
return tok.get(i).contains("\n"); // only at beginning of line
}});
// concept declarations
for (String kw : ll("concept", "sconcept")) {
Object cond = new Object() {
Object get(List tok, int i) {
addFieldOrder(tok, i+1);
return true;
}
};
boolean re = false;
if (jreplace(tok, kw + " {", "static class $2 extends Concept {", cond)) re = true;
if (jreplace(tok, kw + " implements", "static class $2 extends Concept implements", cond)) re = true;
if (jreplace(tok, kw + " ", "static class $2", cond)) re = true;
if (re) reTok(tok);
}
// "case" as a variable name ( => _case)
caseAsVariableName(tok);
// "continue" as a function name ( => _continue)
continueAsFunctionName(tok);
// * constructors
if (hasCodeTokens(tok, "\\*", "("))
tok = expandStarConstructors(tok);
// Do this BEFORE awt replacement! ("p-awt" contains "awt" token)
tok = replaceKeywordBlock(tok, "p-substance-thread", "p { substance();", "}");
tok = replaceKeywordBlock(tok, "p-substance", "p-awt { substance();", "}");
jreplace(tok, "p-type {", "p-typewriter {");
tok = replaceKeywordBlock(tok, "p-awt", "p { swing {", "}}");
tok = replaceKeywordBlock(tok, "p-typewriter", "p { typeWriterConsole();", "}");
tok = replaceKeywordBlock(tok, "p-lowprio", "p { lowPriorityThread(r " + "{", "}); }");
tok_p_repeatWithSleep(tok);
tok = replaceKeywordBlock(tok,
"awt",
"swingLater(r " + "{", // for #711
"});");
tok = replaceKeywordBlock(tok,
"swing",
"{ swingAndWait(r " + "{", // for #711
"}); }");
// crazy stuff
jreplace (tok, "for over :", "for (int $2 = 0; $2 < l($4); $2++)");
jreplace (tok, "for to :", "for (int $2 = 0; $2 < $4; $2++)");
jreplace (tok, "for to :", "for (int $2 = 0; $2 < $4; $2++)");
// STANDARD CLASSES & INTERFACES
String sc = cacheGet("#1003674");
List lclasses = new ArrayList();
for (String line : toLinesFullTrim(sc)) {
line = javaDropComments(line).trim();
int idx = line.indexOf('/');
lclasses.addAll(ll(line.substring(0, idx), line.substring(idx+1)));
}
final Set haveClasses = addLibraryClasses(tok, toStringArray(lclasses));
haveClasses.add("String");
// Stuff that depends on the list of inner classes (haveClasses)
expandClassReferences(tok, haveClasses);
slashCasts(tok, haveClasses);
// "x << X" => "x instanceof X"
jreplace(tok, " << ", "$1 instanceof $4", new Object() {
Object get(List tok, int i) {
return haveClasses.contains(tok.get(i+7));
}
});
expandVarCopies(tok);
// concept-related stuff
// auto-import concepts
boolean _a = hasCodeTokens(tok, /*"extends",*/ "Concept"), _b = !haveClasses.contains("Concept");
print("auto-import: " + _a + ", " + _b);
if (_a && _b) {
printStruct(haveClasses);
tok = includeInMainLoaded(tok, "concepts.");
reTok(tok, l(tok)-1, l(tok));
//processConceptsDot(tok);
}
jreplace(tok, "for ( )", "for ($3 $4 : list($3))");
// the infamous missing functions (usually caused by class Matches)
// maybe not needed anymore?
if (!hasCodeTokens(tok, "String", "unquote") && containsToken(tok, "unquote")) {
print("Adding unquote");
tok = includeInMain(tok, "#1001735");
}
if (!hasCodeTokens(tok, "String", "formatSnippetID") && containsToken(tok, "formatSnippetID")) {
print("Adding formatSnippetID");
tok = includeInMain(tok, "#1000709");
}
tok = expandShortTypes(tok);
if (containsToken(tok, "cast")) {
String s = join(tok);
s = s.replaceAll("(\\w+<[\\w\\s,\\[\\]]+>|\\w+|\\w+\\[\\]|\\w+\\[\\]\\[\\])\\s+(\\w+)\\s*=\\s*cast(\\W[^;]*);", "$1 $2 = ($1) ($3);");
tok = jtok(s);
}
tok = replaceKeywordBlock(tok, "r-thread", "runnableThread(r " + "{", "})");
// runnable and r - now also with automatic toString if enabled
for (String keyword : ll("runnable", "r"))
while ((i = jfind(tok, keyword + " {")) >= 0) {
int idx = findCodeTokens(tok, i, false, "{");
int j = findEndOfBracketPart(tok, idx);
List contents = subList(tok, idx+1, j-1);
//print("r contents: " + structure(contents));
replaceTokens(tok, i, j+1, "new Runnable() { public void run() { try { " + tok_addSemicolon(contents) +
"\n} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } }" +
(autoQuine ? " public S toString() { return " + quote(trim(join(contents))) + "; }" : "") +
"}");
reTok(tok, i, j+1);
}
tok = replaceKeywordBlock(tok,
"expectException",
"{ bool __ok = false; try {",
"} catch { __ok = true; } assertTrue(\"expected exception\", __ok); }");
while ((i = tok.indexOf("tex")) >= 0) {
tok.set(i, "throws Exception");
tok = jtok(tok);
}
// shorter & smarter whiles
jreplace(tok, "while true", "while (true)");
jreplace(tok, "while licensed", "while (licensed())");
jreplace(tok, "repeat {", "while (licensed()) {");
tok_repeatWithSleep(tok);
// null; => return null; etc.
Object cond = new Object() {
boolean get(List tok, int i) {
String t = _get(tok, i-1);
return l(t) == 1 && "{};)".contains(t) || eq(t, "else");
}
};
jreplace(tok, "null;", "return null;", cond);
jreplace(tok, "false;", "return false;", cond);
jreplace(tok, "true;", "return true;", cond);
jreplace(tok, "this;", "return this;", cond);
// "myFunction;" instead of "myFunction();" - quite rough
cond = new Object() {
boolean get(List tok, int i) {
String word = tok.get(i+3);
//print("single word: " + word);
return !litlist("break", "continue", "return").contains(word);
}
};
for (String pre : litlist("}", ";"))
jreplace(tok, pre + " ;", "$1 $2();", cond);
// shorter match syntax for answer methods
jreplace(tok, "if || ",
"if (matchOneOf(s, m, $2, $5))");
jreplace(tok, "if ", "if (matchStartX($2, s, m))",
new Object() { boolean get(List tok, int i) {
return unquote(tok.get(i+3)).endsWith("...");
}});
jreplace(tok, "if ", "if (match($2, s, m))");
jreplace(tok, "if match ", "if (match($3, s, m))");
// extra commas ("litlist(1, 2,)")
jreplace(tok, ",)", ")");
// additional translations (if necessary)
tok = replaceKeywordBlock(tok,
"pcall",
"try { /* pcall 1*/ ",
"/* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }");
tok = dialogHandler(tok);
tok = replaceKeywordBlock(tok, "exceptionToUser",
"try {",
"} catch (Throwable __e) { ret exceptionToUser(__e); }");
if (hasCodeTokens(tok, "twice", "{"))
tok = replaceKeywordBlock(tok, "twice",
"for (int __twice = 0; __twice < 2; __twice++) {",
"}");
while ((i = findCodeTokens(tok, "repeat", "*", "{")) >= 0) {
String v = makeVar("repeat");
tok.set(i, "for (int " + v + " = 0; " + v + " < " + tok.get(i+2) + "; " + v + "++)");
tok.set(i+2, "");
tok = jtok(tok);
}
tok = replaceKeywordBlockDyn(tok,
"time",
new Object() { String[] get() {
String var = makeVar("startTime");
return new String[] {
"{ long " + var + " = now(); try { ",
"} finally { " + var + " = now()-" + var + "; saveTiming(" + var + "); } }"};
}});
if (hasCodeTokens(tok, "assertFail", "{")) {
String var = makeVar("oops");
tok = replaceKeywordBlock(tok,
"assertFail",
"boolean " + var + " = false; try {",
"\n" + var + " = true; } catch (Exception e) { /* ok */ } assertFalse(" + var + ");");
}
tok = replaceKeywordBlock(tok,
"yo",
"try {",
"} catch (Exception " + makeVar("e") + ") { ret false; }");
tok = replaceKeywordBlock(tok,
"awtIfNecessary",
"swingNowOrLater(r " + "{",
"});");
if (hasCodeTokens(tok, "ctex"))
tok = ctex(tok);
tok = replaceKeywordBlock(tok,
"actionListener",
"new java.awt.event.ActionListener() { " +
"public void actionPerformed(java.awt.event.ActionEvent _evt) {",
"}}");
namedThreads(tok);
threads(tok);
// try answer
while ((i = findCodeTokens(tok, "try", "answer")) >= 0) {
int j = findEndOfStatement(tok, i);
String v = makeVar("a");
tok.set(i, "{ S " + v);
tok.set(i+2, "=");
tok.set(j-1, "; if (!empty(" + v + ")) ret " + v + "; }");
tok = jtok(tok);
}
// return optional (return if not null)
while ((i = jfind(tok, "return optional =")) >= 0) {
int j = findEndOfStatement(tok, i);
String v = tok.get(i+4);
clearTokens(tok, i+2, i+4);
tok.set(i, "{");
tok.set(j-1, "; if (" + v + " != null) ret " + v + "; }");
tok = jtok(tok);
}
functionReferences(tok);
// TODO: optimize
String moved = moveImportsUp2(join(tok));
if (moved != null)
tok = jtok(moved);
return tok;
} // end of stdStuff!
static List multilineStrings(List tok) {
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (isQuoted(t))
if (t.startsWith("[") || t.contains("\r") || t.contains("\n"))
tok.set(i, quote(unquote(t)));
}
return tok;
}
static void inStringEvals(List tok) {
boolean change = false;
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (!isQuoted(t)) continue;
if (t.contains("\\*") && !t.contains("\\\\")) { // << rough
tok.set(i, inStringEval(t));
change = true;
}
}
if (change) reTok(tok);
}
static String inStringEval(String t) {
t = dropPrefix("\"", dropSuffix("\"", t));
List l = new ArrayList();
int idx;
while ((idx = t.indexOf("\\*")) >= 0) {
int j = indexOf(t, idx, "*/");
if (j < 0) break;
if (idx > 0)
l.add("\"" + substring(t, 0, idx) + "\"");
l.add("(" + trim(substring(t, idx+2, j)) + ")");
t = substring(t, j+2);
}
if (nempty(t))
l.add("\"" + t + "\"");
return "(" + join(" + ", l) + ")";
}
static List quickmain(List tok) {
int i = findCodeTokens(tok, "main", "{");
if (i < 0) i = findCodeTokens(tok, "m", "{");
if (i >= 0 && !(i-2 > 0 && tok.get(i-2).equals("class")))
tok.set(i, "public class main");
i = findCodeTokens(tok, "psvm", "{");
if (i < 0) i = findCodeTokens(tok, "p", "{");
if (i >= 0)
tok.set(i, "public static void main(final String[] args) throws Exception");
return jtok(tok);
}
static String makeVar(String name) {
return "_" + name + "_" + varCount++;
}
static String makeVar() { return makeVar(""); }
/*static L standardFunctions(L tok) {
ret rtq(tok, "#1002474");
}*/
static List rtq(List tok, String id) {
return runTranslatorQuick(tok, id);
}
static List expandShortTypes(List tok) {
// replace with
for (int i = 1; i+4 < tok.size(); i += 2)
if (tok.get(i).equals("<")
&& litlist(">", ",").contains(tok.get(i+4))) {
String type = tok.get(i+2);
if (type.equals("int")) type = "Integer";
else if (type.equals("long")) type = "Long";
tok.set(i+2, type);
}
// O = Object, S = String, ret = return
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.equals("O")) t = "Object";
if (t.equals("S")) t = "String";
else if (t.equals("L")) t = "List";
//else if (t.equals("F")) t = "Function";
else if (t.equals("ret")) t = "return";
else if (t.equals("bool") && i+2 < tok.size() && neq(tok.get(i+2), "(")) t = "boolean"; // bool -> boolean if it's not a function name
tok.set(i, t);
}
return tok;
}
static List autoImports(List tok) {
String s = join(tok);
List imports = findImports(s);
StringBuilder buf = new StringBuilder();
for (String c : standardImports)
if (!(imports.contains(c)))
buf.append("import " + c + ";\n");
if (buf.length() == 0) return tok;
return jtok(buf+s);
}
static String[] standardImports = {
"java.util.*",
"java.util.zip.*",
"java.util.List",
"java.util.regex.*",
"java.util.concurrent.*",
"java.util.concurrent.atomic.*",
"java.util.concurrent.locks.*",
"javax.swing.*",
"javax.swing.event.*",
"javax.swing.text.*",
"javax.swing.table.*",
"java.io.*",
"java.net.*",
"java.lang.reflect.*",
"java.lang.ref.*",
"java.lang.management.*",
"java.security.*",
"java.security.spec.*",
"java.awt.*",
"java.awt.event.*",
"java.awt.image.*",
"javax.imageio.*",
"java.math.*"
};
static List expandStarConstructors(List tok) {
mainLoop: for (int i = 3; i+6 < tok.size(); i += 2) {
String t = tok.get(i), l = tok.get(i-2);
if (!t.equals("*"))
continue;
if (!tok.get(i+2).equals("("))
continue;
if (!eqOneOf(l, "}", "public", "private", "protected", ";", "{")) // is this correct...??
continue;
// ok, it seems like a constructor declaration.
// Now find class name by going backwards.
int j = i, level = 1;
while (j > 0 && level > 0) {
t = tok.get(j);
if (t.equals("}")) ++level;
if (t.equals("{")) --level;
j -= 2;
}
while (j > 0) {
t = tok.get(j);
if (t.equals("class")) {
String className = tok.get(j+2);
tok.set(i, className); // exchange constructor name!
// now for the parameters.
// Syntax: *(Learner *learner) {
// We will surely add type inference here in time... :)
j = i+2;
while (!tok.get(j).equals("{"))
j += 2;
int block = j+1;
for (int k = i+2; k < block-1; k += 2)
if (tok.get(k).equals("*")) {
tok.remove(k);
tok.remove(k);
block -= 2;
String name = tok.get(k);
tok.addAll(block, Arrays.asList(new String[] {
"\n ", "this", "", ".", "", name, " ", "=", " ", name, "", ";" }));
}
continue mainLoop;
}
j -= 2;
}
}
return tok;
}
static List processIncludes(List tok) {
int safety = 0;
while (hasCodeTokens(tok, "!", "include") && ++safety < 100)
tok = processIncludesSingle_2(tok);
tok_autoCloseBrackets(tok);
return tok;
}
static List processIncludesSingle(List tok) {
String s = join(tok);
Matcher m = Pattern.compile("\n\\s*!include (#\\d+)").matcher(s);
if (!m.find()) return tok;
StringBuffer buf = new StringBuffer();
do {
String includedSrc = loadSnippet(m.group(1));
m.appendReplacement(buf, m.quoteReplacement("\n" + includedSrc));
} while (m.find());
m.appendTail(buf);
return jtok(str(buf));
}
static List processIncludesSingle_2(List tok) {
int i;
while ((i = jfind(tok, "!include #")) >= 0) {
String id = tok.get(i+6);
String includedSrc = loadSnippet(id);
clearTokens(tok, i, i+8);
tok.set(i, "\n" + includedSrc + "\n");
reTok(tok, i, i+8);
}
return tok;
}
static List ctex(List tok) {
String s = join(tok);
Pattern regex = Pattern.compile("\\s+(no\\s+exceptions|ctex|null on exception)\\s*\\{");
for (int i = 0; i < 100; i++) {
Matcher matcher = regex.matcher(s);
if (!matcher.find())
break;
String kind = matcher.group(1);
//print("Iteration " + (i+1));
int start = matcher.start(), end = matcher.end();
int endOfBlock = ctex_findEndOfBlock(s, end);
String catchBlock, catchWhat;
if (kind.startsWith("null")) {
catchBlock = "return null;";
catchWhat = "Throwable";
} else {
catchBlock = "throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e);";
catchWhat = "Throwable";
}
String tryBlock = " { try {\n " +
s.substring(end, endOfBlock) + "\n} catch (" + catchWhat + " __e) { " + catchBlock + " }";
s = s.substring(0, start) + tryBlock + s.substring(endOfBlock);
}
return jtok(s);
}
// start is the index AFTER the opening bracket
// returns index OF closing bracket
static int ctex_findEndOfBlock(String s, int start) {
int level = 1;
for (int i = start; i < s.length(); i++) {
if (s.charAt(i) == '{') ++level;
else if (s.charAt(i) == '}') --level;
if (level == 0)
return i;
}
return s.length();
}
static List dialogHandler(List tok) {
return replaceKeywordBlock(tok,
"dialogHandler",
"new DialogHandler() {\n" +
"public void run(final DialogIO io) {",
"}}");
}
static void quicknew2(List tok) {
jreplace(tok, "new ;", "$2 $3 = new $2;");
jreplace(tok, "new <> ;", "$2<$4> $6 = new $2;");
jreplace(tok, "new <,> ;", "$2<$4,$6> $8 = new $2;");
jreplace(tok, "new <<>> ;", "$2 $3 $4 $5 $6 $7 $8 $9 = new $2;");
jreplace(tok, "for args " + "{", "for (int i = 0; i < args.length; i++) { final String arg = args[i];");
// Constructor calls without parentheses
// So you can say something like: predictors.add(new P1);
jreplace1(tok, "new ", "new $2()", new Object() {
boolean get(List tok, int i) {
return eqOneOf(_get(tok, i+5), "{", ",", ")", ";", ":");
}
});
jreplace(tok, "new " + "List(", "new ArrayList(");
jreplace(tok, "new " + "Map(", "new HashMap(");
jreplace(tok, "\\*[] ;", "$2[] $6 = new $2[$4];");
}
// OLD
static String quicknew(String s) {
s = s.replaceAll("new\\s+L<([\\w\\[\\]<>,\\s]+)>\\s+(\\w+);", "List<$1> $2 = new ArrayList<$1>();");
s = s.replaceAll("new\\s+List<([\\w\\[\\]<>,\\s]+)>\\s+(\\w+);", "List<$1> $2 = new ArrayList<$1>();");
s = s.replaceAll("new\\s+\\(Hash\\)Set<(\\w+)>\\s+(\\w+);", "Set<$1> $2 = new HashSet<$1>();");
s = s.replaceAll("new\\s+\\(Tree\\)Set<(\\w+)>\\s+(\\w+);", "Set<$1> $2 = new TreeSet<$1>();");
s = s.replaceAll("new\\s+Set<(\\w+)>\\s+(\\w+);", "Set<$1> $2 = new TreeSet<$1>();"); // TreeSet now default - pay attention to explicitly say HashSet if you need it.
s = s.replaceAll("new\\s+\\(Hash\\)Map<([\\w\\s,]+)>\\s+(\\w+);", "Map<$1> $2 = new HashMap<$1>();");
s = s.replaceAll("new\\s+\\(Tree\\)Map<([\\w\\s,]+)>\\s+(\\w+);", "Map<$1> $2 = new TreeMap<$1>();");
// TreeMap when string as key
s = s.replaceAll("new\\s+Map<(S,[\\w\\s,]+)>\\s+(\\w+);", "Map<$1> $2 = new TreeMap<$1>();");
s = s.replaceAll("new\\s+Map<(String,[\\w\\s,]+)>\\s+(\\w+);", "Map<$1> $2 = new TreeMap<$1>();");
// HashMap is default for everything else
s = s.replaceAll("new\\s+Map<([\\w\\s,]+)>\\s+(\\w+);", "Map<$1> $2 = new HashMap<$1>();");
s = s.replaceAll("new\\s+(\\w+<[\\w\\s,]+>)\\s+(\\w+);", "$1 $2 = new $1();");
return s;
}
static List extendClasses(List tok) {
int i;
while ((i = jfind(tok, "extend {")) >= 0) {
String className = tok.get(i+2);
int idx = findCodeTokens(tok, i, false, "{");
int j = findEndOfBracketPart(tok, idx+2);
String content = join(subList(tok, idx+1, j-1));
List c = findInnerClassOfMain(tok, className);
print("Extending class " + className + " ==> " + join(c));
clearTokens(tok.subList(i, j+1));
if (c == null) {
print("Warning: Can't extend class " + className + ", not found");
continue;
}
int startOfClass = indexOfSubList(tok, c); // magicIndexOfSubList is broken
int endOfClass = startOfClass + l(c)-1;
print("Extending class " + className + " ==> " + join(subList(tok, startOfClass, endOfClass)));
while (neq(tok.get(endOfClass), "}")) --endOfClass;
print("Extending class " + className + " ==> " + join(subList(tok, startOfClass, endOfClass)));
tok.set(endOfClass, content + "\n" + tok.get(endOfClass));
reTok(tok); // changed in 2 places, let's retok it all
}
return tok;
}
static void listComprehensions(List tok) {
int i;
for (String op : ll(":", "in"))
while ((i = jfind(tok, "[ " + op)) >= 0) {
Map bracketMap = getBracketMap(tok);
String type = tok.get(i+2), id = tok.get(i+4);
int j = scanOverExpression(tok, bracketMap, i+8, "|");
String exp = join(tok.subList(i+8, j));
j += 2;
int k = scanOverExpression(tok, bracketMap, j, "]");
String where = join(tok.subList(j, k));
++k;
String code = "filter(" + exp + ", func(" + type + " " + id + ") { " + where + " })";
replaceTokens(tok, i, k, code);
reTok(tok, i, k);
}
}
// lib 123 => !123
static void libs(List tok) {
TreeSet libs = new TreeSet();
int i;
while ((i = jfind(tok, "lib ")) >= 0) {
String id = tok.get(i+2);
print("lib " + id);
if (!libs.contains(id)) {
libs.add(id);
tok.set(i, "!");
tok.set(i+1, "");
} else {
print("...ignoring (duplicate)");
clearAllTokens(tok, i, i+3);
reTok(tok, i, i+3);
}
}
}
// sourceCodeLine() => 1234
static void sourceCodeLine(List tok) {
int i ;
while ((i = jfind(tok, "sourceCodeLine()")) >= 0) {
replaceTokens(tok, i, i+5, str(countChar(join(subList(tok, 0, i)), '\n')+1));
reTok(tok, i, i+5);
}
}
// done before any other processing
static void earlyStuff(List tok) {
int i;
// Note: this makes the word "quine" a special operator
// (unusable as a function name)
while ((i = jfind(tok, "quine(")) >= 0) {
int idx = findCodeTokens(tok, i, false, "(");
int j = findEndOfBracketPart(tok, idx+2);
tok.set(i, "new Quine");
tok.set(idx, "(" + quote(join(subList(tok, idx+1, j-1))) + ", ");
reTok(tok, i, idx+1);
}
}
static void throwFail(List tok) {
boolean anyChange = false;
for (int i = 1; i+2 < l(tok); i += 2)
if (eq(get(tok, i+2), "fail") && !eqOneOf(get(tok, i), "throw", "RuntimeException", "return")) {
tok.set(i+2, "throw fail");
anyChange = true;
}
if (anyChange)
reTok(tok);
}
static void namedThreads(List tok) {
for (int i = 0; i < 100; i++) {
int idx = findCodeTokens(tok, "thread", "", "{");
if (idx < 0) idx = findCodeTokens(tok, "thread", "", "{");
if (idx < 0)
break;
int j = findEndOfBracketPart(tok, idx+4);
String tName = tok.get(idx+2);
String var = "_t_" + i;
String pre = "{ /*nt*/ Thread " + var + " = new Thread(" + tName + ") {\n" +
"public void run() { /* in run */ pcall { /* in thread */ \n";
String post = "/* in thread */ } /* in run */ }\n};\n" +
var + ".start(); }";
tok.set(idx, pre);
tok.set(idx+2, "");
tok.set(idx+4, "");
tok.set(j-1, post);
//print(join(subList(tok, idx, j)));
reTok(tok, idx, j);
}
}
static void threads(List tok) {
for (boolean daemon : litlist(false, true))
for (int i = 0; i < 100; i++) {
int idx = findCodeTokens(tok, daemon ? "daemon" : "thread", "{");
if (idx < 0)
break;
int j = findEndOfBracketPart(tok, idx+2);
String var = "_t_" + i;
String pre = "{ Thread " + var + " = new Thread() {\n" +
"public void run() { pcall\n";
String post = "} }\n};\n" +
(daemon ? var + ".setDaemon(true);\n" : "") +
var + ".start(); }";
tok.set(idx, pre);
tok.set(j-1, post);
reTok(tok, idx, j);
}
}
static Map sf;
static List standardFunctions(List tok) {
if (sf == null) {
List standardFunctions = concatLists(
(List) loadVariableDefinition(cacheGet("#761"), "standardFunctions"),
(List) loadVariableDefinition(cacheGet("#1006654"), "standardFunctions"));
sf = new HashMap();
for (String x : standardFunctions) {
String[] f = x.split("/");
sf.put(f[1], f[0]);
}
}
for (int i = 0; ; i++) {
Set defd = new HashSet(findFunctions(tok));
// changes tok
Set invocations = findFunctionInvocations(tok, sf);
//print("Functions invoked: " + structure(invocations));
List needed = diff(invocations, defd);
if (needed.isEmpty())
break;
print("Adding functions: " + join(" " , needed));
List added = new ArrayList();
StringBuilder buf = new StringBuilder();
List preload = new ArrayList();
for (String x : needed)
if (sf.containsKey(x))
preload.add(sf.get(x));
cachePreload(preload);
for (String x : cloneList(needed)) {
if (defd.contains(x)) continue;
String id = sf.get(x);
if (id == null) {
print("Standard function " + x + " not found.");
needed.remove(x);
continue;
}
//print("Adding function: " + x + " (" + id + ")");
String function = cacheGet(id);
if (("\n" + function).contains("\n!")) print("Warning: " + id + " contains translators.");
buf.append(function).append("\n");
added.add(x);
defd.addAll(findFunctionDefs(javaTok(function)));
}
tok = includeInMainLoaded(tok, str(buf));
// defd = new HashSet(findFunctions(tok));
//print("Functions added: " + structure(added));
for (String x : needed)
if (!defd.contains(x)) {
print(join(tok));
throw fail("Function not defined properly: " + x);
}
//print("Iteration " + (i+2));
if (i >= 1000) throw fail("Too many iterations");
}
return tok;
}
static List findFunctions(List tok) {
//ret findFunctionDefinitions(join(findMainClass(tok)));
return findFunctionDefs(findMainClass(tok));
}
static String cacheGet(String snippetID) {
snippetID = formatSnippetID(snippetID);
String text = snippetCache.get(snippetID);
if (text == null)
snippetCache.put(snippetID, text = loadSnippet(snippetID));
return text;
}
static void cachePreload(List ids) {
List needed = new ArrayList();
for (String id : ids)
if (!snippetCache.containsKey(formatSnippetID(id)))
needed.add(formatSnippetID(id));
if (l(needed) > 1) {
List texts = loadSnippets(needed);
for (int i = 0; i < l(needed); i++)
if (texts.get(i) != null)
snippetCache.put(needed.get(i), texts.get(i));
}
}
static List jtok(List tok) {
return jtok(join(tok));
}
static List jtok(String s) {
List l = javaTok(s);
return useIndexedList ? new IndexedList2(l) : l;
}
// works on Java level (no "sclass" etc)
// returns list of classes we have (useful for other processing)
static Set addLibraryClasses(List tok, String... data) {
HashSet have = new HashSet();
for (List c : innerClassesOfMain(tok))
have.add(getClassDeclarationName(c));
have.addAll(tok_importedClassNames(tok));
List idx = IndexedList2.ensureIndexed(tok);
for (int i = 0; i+1 < l(data); i++) {
String className = data[i], snippetID = data[i+1];
if (idx.contains(className)
&& !have.contains(className)) {
print("Adding class " + className + " / " + snippetID);
snippetID = formatSnippetID(snippetID);
String text = cacheGet(snippetID);
includeInMainLoaded(tok, text);
List ct = javaTok(text);
jreplace (ct, "sclass", "static class");
jreplace (ct, "sinterface", "static interface");
tok_autoCloseBrackets(ct);
for (List c : allClasses(ct))
have.add(getClassDeclarationName(c));
if (!have.contains(className))
throw fail("Wrongly defined class: " + className + " / " + snippetID);
}
}
return have;
}
// magically append ".class" to class name references
static void expandClassReferences(List tok, Set classNames) {
boolean change = false;
for (int i = 3; i+2 < l(tok); i += 2)
if (classNames.contains(tok.get(i))) {
String s = tok.get(i-2), t = tok.get(i+2);
if (eqOneOf(s, "instanceof", "new", ".", "<", "implements", "throws", "extends", "/", "nu")) continue;
if (isIdentifier(s)) continue; // XXX?
if (eq(s, ",") && eqOneOf(_get(tok, i-6), "implements", "throws")) continue;
// TODO: longer lists
// check for cast
if (eq(s, "(") && eq(t, ")")
&& i >= 5) {
if (neq(get(tok, i+4), "{")) {
String x = tok.get(i-4);
if (!isIdentifier(x)) continue;
if (eqOneOf(x, "ret", "return")) continue;
}
}
if (eqOneOf(t, ",", ")", ";", ":")) {
tok.set(i, tok.get(i) + ".class");
change = true;
}
}
if (change) reTok(tok);
}
// "/" => "((ClassName) )"
static void slashCasts(List tok, final Set classNames) {
jreplace(tok, "/", "(($3) $1)", new Object() {
Object get(List tok, int i) {
return classNames.contains(tok.get(i+5));
}
});
}
// +var => "var", +var
static void expandVarCopies(List tok) {
boolean change = false;
for (int i = 3; i+2 < l(tok); i += 2) {
if (!eq(tok.get(i), "+")) continue;
if (!eqOneOf(tok.get(i-2), "(", ",")) continue;
String s = tok.get(i+2);
if (!isIdentifier(s)) continue;
tok.set(i, quote(s) + ", ");
change = true;
}
if (change) reTok(tok);
}
static void processConceptsDot(List tok) {
boolean change;
do {
change = false;
for (int i : jfindAll(tok, "concepts."))
if (contains(get(tok, i+3), "\n")) {
replaceTokens(tok, i, i+3, "!" + "include #1004863 // Dynamic Concepts");
reTok(tok, i, i+3);
change = true;
break;
}
} while (change);
}
static void addFieldOrder(List tok, int i) {
int idx = findCodeTokens(tok, i, false, "{");
if (idx < 0) return;
int j = findEndOfBracketPart(tok, idx+2);
List vars = allVarNames(subList(tok, idx+1, j-1));
print("addFieldOrder " + struct(vars));
if (!vars.contains("_fieldOrder")
&& !isSortedList(vars)) {
print("Adding field order");
tok.set(idx+2, "static String _fieldOrder = " + quote(join(" ", vars)) + ";\n " + tok.get(idx+2));
// reTok has to be done by caller
}
}
static void caseAsVariableName(List tok) {
if (!tok.contains("case")) return;
for (int i = 1; i+2 < l(tok); i += 2) {
String t = tok.get(i+2);
if (tok.get(i).equals("case")
&& !(t.startsWith("'") || isInteger(t) || isIdentifier(t)))
tok.set(i, "_case");
}
}
static void continueAsFunctionName(List tok) {
jreplace(tok, "continue(", "_continue(");
}
// func bla => "bla" - and "please include function bla."
static void functionReferences(List tok) {
int i;
for (String keyword : ll("f", "func"))
while ((i = jfind(tok, keyword + " ", new Object() {
Object get(List tok, int i) {
return !eq(tok.get(i+3), "instanceof");
}
})) >= 0) {
String f = tok.get(i+2);
clearTokens(tok, i, i+2);
tok.set(i+2, quote(f));
reTok(tok, i, i+2);
tok.set(l(tok)-1, last(tok) + "\nplease include function " + f + ".");
reTok(tok, l(tok)-1, l(tok));
}
}
// # 123 => "#123"
static void directSnippetRefs(List tok) {
int i;
while ((i = jfind(tok, "#", new Object() {
boolean get(List tok, int i) {
return neq(_get(tok, i-1), "include");
}
})) >= 0) {
String id = tok.get(i+2);
clearTokens(tok, i+1, i+3);
tok.set(i, quote("#" + id));
reTok(tok, i, i+3);
}
}
static void quicknu(List tok) {
jreplace(tok, "nu (", "nu($2.class, ");
jreplace(tok, "nu ", "new $2");
}
// fill variable innerClasses_list
static void innerClassesVar(List tok) {
if (!tok.contains("myInnerClasses_list")) return;
List have = new ArrayList();
for (List c : innerClassesOfMain(tok))
have.add(getClassDeclarationName(c));
int i = jfind(tok, ">myInnerClasses_list;");
if (i < 0) return;
tok.set(i+4, "=litlist(\n" + joinQuoted(", ", have) + ");");
reTok(tok, i+4, i+5);
}
static String struct(Object o) {
return structure(o);
}
static Map getBracketMap(List tok) {
Map map = new HashMap();
List stack = new ArrayList();
for (int i = 1; i < l(tok); i+= 2) {
if (litlist("{", "(").contains(tok.get(i)))
stack.add(i);
else if (litlist("}", ")").contains(tok.get(i))) {
if (!empty(stack))
map.put(liftLast(stack), i);
}
}
return map;
}
static Object callF(Object f, Object... args) {
return callFunction(f, args);
}
static List> innerClassesOfMain(List tok) {
return innerClasses(findMainClass(tok));
}
static String joinQuoted(String sep, Collection c) {
List l = new ArrayList();
for (String s : c) l.add(quote(s));
return join(sep, l);
}
static String shorten(String s, int max) {
if (s == null) return "";
if (max < 0) return s;
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static int identityHashCode(Object o) {
return System.identityHashCode(o);
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder();
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else
out.append(c);
}
out.append('"');
}
static List includeInMain(List tok, String snippetID) {
return includeInMainLoaded(tok, loadSnippet(snippetID));
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
public static String join(String glue, Iterable strings) {
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String[] strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String dropPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static List jfindAll(List tok, String pat) {
List tokin = javaTok(pat);
jfind_preprocess(tokin);
String[] toks = toStringArray(codeTokensOnly(tokin));
int i = -1;
List l = new ArrayList();
while ((i = findCodeTokens(tok, i+1, false, toks)) >= 0)
l.add(i);
return l;
}
static List findInnerClassOfMain(List tok, String className) {
for (List c : innerClassesOfMain(tok)) {
String name = getClassDeclarationName(c);
if (eq(name, className))
return c;
}
return null;
}
static String getClassDeclarationName(List c) {
if (c != null)
for (int i = 1; i+2 < c.size(); i += 2)
if (eqOneOf(c.get(i), "class", "interface", "enum"))
return c.get(i+2);
return null;
}
static List tok_importedClassNames(List tok) {
List names = new ArrayList();
for (int i = 1; i < l(tok); i += 2)
if (eq(tok.get(i), "import")) {
int j = findEndOfStatement(tok, i); // index of ;+1
String s = get(tok, j-3);
if (isIdentifier (s))
names.add(s);
i = j-1;
}
return names;
}
static int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static int jfind(List tok, int startIdx, String in, Object condition) {
List tokin = javaTok(in);
jfind_preprocess(tokin);
return jfind(tok, startIdx, tokin, condition);
}
// assumes you preprocessed tokin
static int jfind(List tok, List