use crate::ast::Program;
pub const THROWABLES: &[(&str, &str)] = &[
("Throwable", ""),
("Error", "Throwable"),
("Exception", "Throwable"),
("RuntimeException", "Exception"),
("IllegalArgumentException", "RuntimeException"),
("NumberFormatException", "IllegalArgumentException"),
("IllegalStateException", "RuntimeException"),
("ArithmeticException", "RuntimeException"),
("NullPointerException", "RuntimeException"),
("ClassCastException", "RuntimeException"),
("UnsupportedOperationException", "RuntimeException"),
("NegativeArraySizeException", "RuntimeException"),
("IndexOutOfBoundsException", "RuntimeException"),
(
"ArrayIndexOutOfBoundsException",
"IndexOutOfBoundsException",
),
(
"StringIndexOutOfBoundsException",
"IndexOutOfBoundsException",
),
("PatternSyntaxException", "IllegalArgumentException"),
("ConcurrentModificationException", "RuntimeException"),
("NoSuchElementException", "RuntimeException"),
("IllegalFormatException", "IllegalArgumentException"),
("IllegalFormatConversionException", "IllegalFormatException"),
("IllegalFormatWidthException", "IllegalFormatException"),
("IllegalFormatPrecisionException", "IllegalFormatException"),
("MissingFormatArgumentException", "IllegalFormatException"),
("UnknownFormatConversionException", "IllegalFormatException"),
(
"FormatFlagsConversionMismatchException",
"IllegalFormatException",
),
("IllegalFormatFlagsException", "IllegalFormatException"),
("MissingFormatWidthException", "IllegalFormatException"),
];
pub fn is_throwable(name: &str) -> bool {
THROWABLES.iter().any(|(n, _)| *n == name)
}
pub fn qualified_throwable(name: &str) -> Option<String> {
if !is_throwable(name) {
return None;
}
Some(match name {
"PatternSyntaxException" => format!("java.util.regex.{name}"),
"ConcurrentModificationException"
| "NoSuchElementException"
| "IllegalFormatException"
| "IllegalFormatConversionException"
| "IllegalFormatWidthException"
| "IllegalFormatPrecisionException"
| "MissingFormatArgumentException"
| "UnknownFormatConversionException"
| "FormatFlagsConversionMismatchException"
| "IllegalFormatFlagsException"
| "MissingFormatWidthException" => format!("java.util.{name}"),
_ => format!("java.lang.{name}"),
})
}
pub fn qualified_class(name: &str) -> Option<String> {
if matches!(name, "Object" | "StringBuilder" | "StringBuffer") {
return Some(format!("java.lang.{name}"));
}
qualified_throwable(name)
}
pub const FUNCTIONAL: &[(&str, &str, &str)] = &[
("Runnable", "void run()", ""),
("Callable", "Object call()", ""),
("Supplier", "Object get()", ""),
(
"Consumer",
"void accept(Object t)",
"default Consumer andThen(Consumer after) { return t -> { this.accept(t); after.accept(t); }; }",
),
(
"BiConsumer",
"void accept(Object t, Object u)",
"default BiConsumer andThen(BiConsumer after) { return (t, u) -> { this.accept(t, u); after.accept(t, u); }; }",
),
(
"Function",
"Object apply(Object t)",
"default Function andThen(Function after) { return t -> after.apply(this.apply(t)); } \
default Function compose(Function before) { return v -> this.apply(before.apply(v)); } \
static Function identity() { return t -> t; }",
),
(
"BiFunction",
"Object apply(Object t, Object u)",
"default BiFunction andThen(Function after) { return (t, u) -> after.apply(this.apply(t, u)); }",
),
(
"UnaryOperator",
"Object apply(Object t)",
"static UnaryOperator identity() { return t -> t; }",
),
(
"BinaryOperator",
"Object apply(Object t, Object u)",
"static BinaryOperator minBy(Comparator comparator) { return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; } \
static BinaryOperator maxBy(Comparator comparator) { return (a, b) -> comparator.compare(a, b) >= 0 ? a : b; }",
),
(
"Predicate",
"boolean test(Object t)",
"default Predicate and(Predicate other) { return t -> this.test(t) && other.test(t); } \
default Predicate negate() { return t -> !this.test(t); } \
default Predicate or(Predicate other) { return t -> this.test(t) || other.test(t); } \
static Predicate not(Predicate target) { return target.negate(); }",
),
(
"BiPredicate",
"boolean test(Object t, Object u)",
"default BiPredicate and(BiPredicate other) { return (t, u) -> this.test(t, u) && other.test(t, u); } \
default BiPredicate negate() { return (t, u) -> !this.test(t, u); } \
default BiPredicate or(BiPredicate other) { return (t, u) -> this.test(t, u) || other.test(t, u); }",
),
(
"Comparator",
"int compare(Object a, Object b)",
"default Comparator reversed() { return (a, b) -> this.compare(b, a); } \
default Comparator thenComparing(Object other) { Comparator c = Comparator.asComparator(other); return (a, b) -> { int r = this.compare(a, b); if (r != 0) { return r; } return c.compare(a, b); }; } \
default Comparator thenComparingInt(Function key) { return this.thenComparing(key); } \
default Comparator thenComparingLong(Function key) { return this.thenComparing(key); } \
default Comparator thenComparingDouble(Function key) { return this.thenComparing(key); } \
static Comparator asComparator(Object x) { if (Comparator.isKeyExtractor(x)) { Function k = (Function) x; return (a, b) -> k.apply(a).compareTo(k.apply(b)); } return (Comparator) x; } \
static Comparator naturalOrder() { return (a, b) -> a.compareTo(b); } \
static Comparator reverseOrder() { return (a, b) -> b.compareTo(a); } \
static Comparator comparing(Function key) { return (a, b) -> key.apply(a).compareTo(key.apply(b)); } \
static Comparator comparingInt(Function key) { return Comparator.comparing(key); } \
static Comparator comparingLong(Function key) { return Comparator.comparing(key); } \
static Comparator comparingDouble(Function key) { return Comparator.comparing(key); }",
),
("IntSupplier", "int getAsInt()", ""),
(
"IntPredicate",
"boolean test(int value)",
"default IntPredicate and(IntPredicate other) { return value -> this.test(value) && other.test(value); } \
default IntPredicate negate() { return value -> !this.test(value); } \
default IntPredicate or(IntPredicate other) { return value -> this.test(value) || other.test(value); }",
),
(
"IntConsumer",
"void accept(int value)",
"default IntConsumer andThen(IntConsumer after) { return value -> { this.accept(value); after.accept(value); }; }",
),
(
"IntUnaryOperator",
"int applyAsInt(int operand)",
"default IntUnaryOperator compose(IntUnaryOperator before) { return v -> this.applyAsInt(before.applyAsInt(v)); } \
default IntUnaryOperator andThen(IntUnaryOperator after) { return v -> after.applyAsInt(this.applyAsInt(v)); } \
static IntUnaryOperator identity() { return v -> v; }",
),
("IntBinaryOperator", "int applyAsInt(int left, int right)", ""),
("ToIntFunction", "int applyAsInt(Object value)", ""),
("ToDoubleFunction", "double applyAsDouble(Object value)", ""),
];
pub fn is_functional(name: &str) -> bool {
FUNCTIONAL.iter().any(|(n, _, _)| *n == name)
}
fn prelude_source(declared: &[String]) -> String {
let mut src =
String::from("public class __JavaLang { public static void main(String[] a) { } }\n");
for (name, sup) in THROWABLES {
if declared.iter().any(|d| d == name) {
continue;
}
let extends = if sup.is_empty() {
String::new()
} else {
format!(" extends {sup}")
};
src.push_str(&format!("class {name}{extends} {{\n"));
if sup.is_empty() {
src.push_str(" String detailMessage;\n");
src.push_str(&format!(" {name}() {{ }}\n"));
src.push_str(&format!(" {name}(String m) {{ detailMessage = m; }}\n"));
src.push_str(" String getMessage() { return detailMessage; }\n");
src.push_str(" String getLocalizedMessage() { return getMessage(); }\n");
src.push_str(
" String toString() { String n = this.getClass().getName(); \
if (detailMessage == null) { return n; } return n + \": \" + detailMessage; }\n",
);
} else {
src.push_str(&format!(" {name}() {{ }}\n"));
src.push_str(&format!(" {name}(String m) {{ super(m); }}\n"));
}
src.push_str("}\n");
}
src
}
pub fn inject(prog: &mut Program) -> Result<(), String> {
if prog.uses_exceptions {
let src = prelude_source(&declared_names(prog));
merge(prog, &src)?;
}
if prog.uses_functional {
let src = functional_source(&declared_names(prog));
merge(prog, &src)?;
}
Ok(())
}
fn declared_names(prog: &Program) -> Vec<String> {
prog.classes.iter().map(|c| c.name.clone()).collect()
}
fn merge(prog: &mut Program, src: &str) -> Result<(), String> {
let parsed = crate::parser::parse(src)?;
prog.classes.extend(
parsed
.classes
.into_iter()
.filter(|c| !c.name.starts_with("__")),
);
prog.methods.extend(
parsed
.methods
.into_iter()
.filter(|m| !m.owner.starts_with("__")),
);
Ok(())
}
fn functional_source(declared: &[String]) -> String {
let mut src = String::from(
"public class __JavaUtilFunction { public static void main(String[] a) { } }\n",
);
for (name, sam, members) in FUNCTIONAL {
if declared.iter().any(|d| d == name) {
continue;
}
src.push_str(&format!("interface {name} {{ {sam}; {members} }}\n"));
}
src
}