ability to substitute a method's body in adapter

This commit is contained in:
Louis Grignon 2020-07-19 16:06:04 +02:00
parent 659e715b1b
commit cfaac45185
2 changed files with 136 additions and 127 deletions

View File

@ -631,9 +631,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
boolean fullImport = require || GLOBALS_CLASS_NAME.equals(targetName); boolean fullImport = require || GLOBALS_CLASS_NAME.equals(targetName);
if (fullImport) { if (fullImport) {
if (context.useRequireForModules) { if (context.useRequireForModules) {
context.addHeader("import." + targetName, context.addHeader("import." + targetName, "import " + targetName + " = require("
"import " + targetName + " = require(" + getStringLiteralQuote() + getStringLiteralQuote() + moduleName + getStringLiteralQuote() + ");\n");
+ moduleName + getStringLiteralQuote() + ");\n");
} else { } else {
context.addHeader("import." + targetName, context.addHeader("import." + targetName,
"import * as " + targetName + " from '" + moduleName + "';\n"); "import * as " + targetName + " from '" + moduleName + "';\n");
@ -1897,27 +1896,26 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
if (!getScope().interfaceScope && !getScope().declareClassScope && !getScope().enumScope if (!getScope().interfaceScope && !getScope().declareClassScope && !getScope().enumScope
&& !(getScope().enumWrapperClassScope && classdecl.sym.isAnonymous())) { && !(getScope().enumWrapperClassScope && classdecl.sym.isAnonymous())) {
if (!classdecl.sym.isAnonymous()) { if (!classdecl.sym.isAnonymous()) {
println().printIndent() println().printIndent()
.print(getScope().enumWrapperClassScope ? classdecl.sym.getSimpleName().toString() : name) .print(getScope().enumWrapperClassScope ? classdecl.sym.getSimpleName().toString() : name)
.print("[" + getStringLiteralQuote() + CLASS_NAME_IN_CONSTRUCTOR .print("[" + getStringLiteralQuote() + CLASS_NAME_IN_CONSTRUCTOR + getStringLiteralQuote()
+ getStringLiteralQuote() + "] = ") + "] = ")
.print(getStringLiteralQuote() + classdecl.sym.getQualifiedName().toString() .print(getStringLiteralQuote() + classdecl.sym.getQualifiedName().toString()
+ getStringLiteralQuote() + ";"); + getStringLiteralQuote() + ";");
} }
Set<String> interfaces = new HashSet<>(); Set<String> interfaces = new HashSet<>();
context.grabSupportedInterfaceNames(interfaces, classdecl.sym); context.grabSupportedInterfaceNames(interfaces, classdecl.sym);
if (!interfaces.isEmpty()) { if (!interfaces.isEmpty()) {
println().printIndent() println().printIndent()
.print(getScope().enumWrapperClassScope ? classdecl.sym.getSimpleName().toString() : name) .print(getScope().enumWrapperClassScope ? classdecl.sym.getSimpleName().toString() : name)
.print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME .print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME + getStringLiteralQuote()
+ getStringLiteralQuote() + "] = "); + "] = ");
print("["); print("[");
for (String itf : interfaces) { for (String itf : interfaces) {
print(getStringLiteralQuote()).print(itf) print(getStringLiteralQuote()).print(itf).print(getStringLiteralQuote() + ",");
.print(getStringLiteralQuote() + ","); }
} removeLastChar();
removeLastChar(); print("];").println();
print("];").println();
} }
if (!getScope().enumWrapperClassScope) { if (!getScope().enumWrapperClassScope) {
println(); println();
@ -2028,9 +2026,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
// end of namespace ================================================= // end of namespace =================================================
if (getScope().enumScope && getScope().isComplexEnum && !getScope().anonymousClasses.contains(classdecl)) { if (getScope().enumScope && getScope().isComplexEnum && !getScope().anonymousClasses.contains(classdecl)) {
println().printIndent().print(classdecl.sym.getSimpleName().toString()) println().printIndent().print(classdecl.sym.getSimpleName().toString()).print(
.print("[" + getStringLiteralQuote() + ENUM_WRAPPER_CLASS_WRAPPERS "[" + getStringLiteralQuote() + ENUM_WRAPPER_CLASS_WRAPPERS + getStringLiteralQuote() + "] = [");
+ getStringLiteralQuote() + "] = [");
int index = 0; int index = 0;
for (JCTree tree : classdecl.defs) { for (JCTree tree : classdecl.defs) {
if (tree instanceof JCVariableDecl if (tree instanceof JCVariableDecl
@ -2052,8 +2049,7 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
.print("("); .print("(");
} }
print("" + (index++) + ", "); print("" + (index++) + ", ");
print(getStringLiteralQuote() + varDecl.sym.name.toString() print(getStringLiteralQuote() + varDecl.sym.name.toString() + getStringLiteralQuote());
+ getStringLiteralQuote());
if (!newClass.args.isEmpty()) { if (!newClass.args.isEmpty()) {
print(", "); print(", ");
} }
@ -2119,11 +2115,11 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
case JSweetConfig.NEW_FUNCTION_NAME: case JSweetConfig.NEW_FUNCTION_NAME:
return "new"; return "new";
default: default:
if(context.hasMethodNameMapping(methodDecl.sym)) { if (context.hasMethodNameMapping(methodDecl.sym)) {
return context.getMethodNameMapping(methodDecl.sym); return context.getMethodNameMapping(methodDecl.sym);
} else { } else {
return name; return name;
} }
} }
} }
@ -2485,62 +2481,67 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
} else { } else {
print(" ").print("{").println().startIndent(); print(" ").print("{").println().startIndent();
String replacedBody = null; if (!getAdapter().substituteMethodBody(parent.sym, methodDecl.sym)) {
if (context.hasAnnotationType(methodDecl.sym, JSweetConfig.ANNOTATION_REPLACE)) {
replacedBody = (String) context.getAnnotationValue(methodDecl.sym,
JSweetConfig.ANNOTATION_REPLACE, String.class, null);
}
boolean fieldsInitPrinted = false; String replacedBody = null;
int position = getCurrentPosition(); if (context.hasAnnotationType(methodDecl.sym, JSweetConfig.ANNOTATION_REPLACE)) {
if (replacedBody == null || BODY_MARKER.matcher(replacedBody).find()) { replacedBody = (String) context.getAnnotationValue(methodDecl.sym,
enter(methodDecl.getBody()); JSweetConfig.ANNOTATION_REPLACE, String.class, null);
if (!methodDecl.getBody().stats.isEmpty()
&& methodDecl.getBody().stats.head.toString().startsWith("super(")) {
printBlockStatement(methodDecl.getBody().stats.head);
if (parent != null) {
printInstanceInitialization(parent, methodDecl.sym);
fieldsInitPrinted = true;
}
printBlockStatements(methodDecl.getBody().stats.tail);
} else {
if (parent != null) {
printInstanceInitialization(parent, methodDecl.sym);
fieldsInitPrinted = true;
}
printBlockStatements(methodDecl.getBody().stats);
} }
exit();
boolean fieldsInitPrinted = false;
int position = getCurrentPosition();
if (replacedBody == null || BODY_MARKER.matcher(replacedBody).find()) {
enter(methodDecl.getBody());
if (!methodDecl.getBody().stats.isEmpty()
&& methodDecl.getBody().stats.head.toString().startsWith("super(")) {
printBlockStatement(methodDecl.getBody().stats.head);
if (parent != null) {
printInstanceInitialization(parent, methodDecl.sym);
fieldsInitPrinted = true;
}
printBlockStatements(methodDecl.getBody().stats.tail);
} else {
if (parent != null) {
printInstanceInitialization(parent, methodDecl.sym);
fieldsInitPrinted = true;
}
printBlockStatements(methodDecl.getBody().stats);
}
exit();
if (replacedBody != null) {
String orgBody = getOutput().substring(position);
removeLastChars(getCurrentPosition() - position);
replacedBody = BODY_MARKER.matcher(replacedBody).replaceAll(orgBody);
replacedBody = BASE_INDENT_MARKER.matcher(replacedBody).replaceAll(getIndentString());
replacedBody = INDENT_MARKER.matcher(replacedBody).replaceAll(INDENT);
replacedBody = METHOD_NAME_MARKER.matcher(replacedBody)
.replaceAll(methodDecl.getName().toString());
replacedBody = CLASS_NAME_MARKER.matcher(replacedBody)
.replaceAll(parent.sym.getQualifiedName().toString());
}
}
if (replacedBody != null && replacedBody.trim().startsWith("super(")) {
String superCall = replacedBody.substring(0, replacedBody.indexOf(';') + 1);
replacedBody = replacedBody.substring(replacedBody.indexOf(';') + 1);
println(superCall);
}
if (!fieldsInitPrinted && parent != null) {
printInstanceInitialization(parent, methodDecl.sym);
fieldsInitPrinted = true;
}
if (replacedBody != null) { if (replacedBody != null) {
String orgBody = getOutput().substring(position); if (methodDecl.sym.isConstructor()) {
removeLastChars(getCurrentPosition() - position); getScope().hasDeclaredConstructor = true;
replacedBody = BODY_MARKER.matcher(replacedBody).replaceAll(orgBody); }
replacedBody = BASE_INDENT_MARKER.matcher(replacedBody).replaceAll(getIndentString()); printIndent().print(replacedBody).println();
replacedBody = INDENT_MARKER.matcher(replacedBody).replaceAll(INDENT);
replacedBody = METHOD_NAME_MARKER.matcher(replacedBody)
.replaceAll(methodDecl.getName().toString());
replacedBody = CLASS_NAME_MARKER.matcher(replacedBody)
.replaceAll(parent.sym.getQualifiedName().toString());
} }
} }
if (replacedBody != null && replacedBody.trim().startsWith("super(")) {
String superCall = replacedBody.substring(0, replacedBody.indexOf(';') + 1);
replacedBody = replacedBody.substring(replacedBody.indexOf(';') + 1);
println(superCall);
}
if (!fieldsInitPrinted && parent != null) {
printInstanceInitialization(parent, methodDecl.sym);
fieldsInitPrinted = true;
}
if (replacedBody != null) {
if (methodDecl.sym.isConstructor()) {
getScope().hasDeclaredConstructor = true;
}
printIndent().print(replacedBody).println();
}
endIndent().printIndent().print("}"); endIndent().printIndent().print("}");
} }
} }
@ -2585,9 +2586,9 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
print(" throw new Error('cannot invoke abstract overloaded method... check your argument(s) type(s)'); "); print(" throw new Error('cannot invoke abstract overloaded method... check your argument(s) type(s)'); ");
} else { } else {
String tsMethodAccess = getTSMemberAccess(getTSMethodName(methodDecl), true); String tsMethodAccess = getTSMemberAccess(getTSMethodName(methodDecl), true);
if (!"void".equals(methodDecl.restype.type.toString())) { if (!"void".equals(methodDecl.restype.type.toString())) {
print("return "); print("return ");
} }
print("super" + tsMethodAccess); print("super" + tsMethodAccess);
print("("); print("(");
for (int j = 0; j < method.getParameters().size(); j++) { for (int j = 0; j < method.getParameters().size(); j++) {
@ -3234,7 +3235,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
} }
private boolean isLazyInitialized(VarSymbol var) { private boolean isLazyInitialized(VarSymbol var) {
return context.options.isLazyInitializedStatics() && var.isStatic() && context.lazyInitializedStatics.contains(var) return context.options.isLazyInitializedStatics() && var.isStatic()
&& context.lazyInitializedStatics.contains(var)
&& /* enum fields are not lazy initialized */ !(var.isEnum() && /* enum fields are not lazy initialized */ !(var.isEnum()
&& var.getEnclosingElement().equals(var.type.tsym)); && var.getEnclosingElement().equals(var.type.tsym));
} }
@ -3642,8 +3644,9 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
if ("class".equals(fieldAccess.name.toString())) { if ("class".equals(fieldAccess.name.toString())) {
if (fieldAccess.type instanceof Type.ClassType if (fieldAccess.type instanceof Type.ClassType
&& context.isInterface(((Type.ClassType) fieldAccess.type).typarams_field.head.tsym)) { && context.isInterface(((Type.ClassType) fieldAccess.type).typarams_field.head.tsym)) {
print(getStringLiteralQuote()).print(context print(getStringLiteralQuote())
.getRootRelativeJavaName(((Type.ClassType) fieldAccess.type).typarams_field.head.tsym)) .print(context.getRootRelativeJavaName(
((Type.ClassType) fieldAccess.type).typarams_field.head.tsym))
.print(getStringLiteralQuote()); .print(getStringLiteralQuote());
} else { } else {
String name = fieldAccess.selected.type.tsym.toString(); String name = fieldAccess.selected.type.tsym.toString();
@ -3652,10 +3655,10 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
if (CONSTRUCTOR_TYPE_MAPPING.containsKey(target)) { if (CONSTRUCTOR_TYPE_MAPPING.containsKey(target)) {
print(mapConstructorType(target)); print(mapConstructorType(target));
} else { } else {
print(getStringLiteralQuote()) print(getStringLiteralQuote())
.print(context.getRootRelativeJavaName( .print(context.getRootRelativeJavaName(
((Type.ClassType) fieldAccess.type).typarams_field.head.tsym)) ((Type.ClassType) fieldAccess.type).typarams_field.head.tsym))
.print(getStringLiteralQuote()); .print(getStringLiteralQuote());
} }
} else { } else {
if (CONSTRUCTOR_TYPE_MAPPING.containsKey(name)) { if (CONSTRUCTOR_TYPE_MAPPING.containsKey(name)) {
@ -4518,10 +4521,9 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
if (!interfaces.isEmpty()) { if (!interfaces.isEmpty()) {
print(", '" + INTERFACES_FIELD_NAME + "', { configurable: true, value: "); print(", '" + INTERFACES_FIELD_NAME + "', { configurable: true, value: ");
print("["); print("[");
for (String i : interfaces) { for (String i : interfaces) {
print(getStringLiteralQuote()).print(i) print(getStringLiteralQuote()).print(i).print(getStringLiteralQuote() + ",");
.print(getStringLiteralQuote() + ","); }
}
removeLastChar(); removeLastChar();
print("]"); print("]");
print(" })"); print(" })");
@ -4740,9 +4742,9 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
break; break;
default: default:
} }
if (s.startsWith("\"") && context.options.isUseSingleQuotesForStringLiterals()) { if (s.startsWith("\"") && context.options.isUseSingleQuotesForStringLiterals()) {
s = "'" + s.substring(1, s.length() - 1).replace("'", "\'") + "'"; s = "'" + s.substring(1, s.length() - 1).replace("'", "\'") + "'";
} }
print(s); print(s);
} }
@ -4781,8 +4783,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
print("for(" + VAR_DECL_KEYWORD + " " + indexVarName + "=0; " + indexVarName + " < ") print("for(" + VAR_DECL_KEYWORD + " " + indexVarName + "=0; " + indexVarName + " < ")
.print(foreachLoop.expr).print("." + "length" + "; " + indexVarName + "++) {").println() .print(foreachLoop.expr).print("." + "length" + "; " + indexVarName + "++) {").println()
.startIndent().printIndent(); .startIndent().printIndent();
print(VAR_DECL_KEYWORD + " " + avoidJSKeyword(foreachLoop.var.name.toString()) + " = ").print(foreachLoop.expr) print(VAR_DECL_KEYWORD + " " + avoidJSKeyword(foreachLoop.var.name.toString()) + " = ")
.print("[" + indexVarName + "];").println(); .print(foreachLoop.expr).print("[" + indexVarName + "];").println();
} else { } else {
String arrayVarName = "array" + Util.getId(); String arrayVarName = "array" + Util.getId();
print("{").println().startIndent().printIndent(); print("{").println().startIndent().printIndent();
@ -4953,12 +4955,12 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
} }
protected void printBinaryRightOperand(JCBinary binary) { protected void printBinaryRightOperand(JCBinary binary) {
addInlinedExpression(binary.rhs); addInlinedExpression(binary.rhs);
print(binary.rhs); print(binary.rhs);
} }
protected void printBinaryLeftOperand(JCBinary binary) { protected void printBinaryLeftOperand(JCBinary binary) {
addInlinedExpression(binary.lhs); addInlinedExpression(binary.lhs);
print(binary.lhs); print(binary.lhs);
} }
@ -5278,7 +5280,7 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
@Override @Override
public void visitUnary(JCUnary unary) { public void visitUnary(JCUnary unary) {
if (!getAdapter().substituteUnaryOperator(new UnaryOperatorElementSupport(unary))) { if (!getAdapter().substituteUnaryOperator(new UnaryOperatorElementSupport(unary))) {
addInlinedExpression(unary.arg); addInlinedExpression(unary.arg);
if (!inRollback) { if (!inRollback) {
JCStatement statement = null; JCStatement statement = null;
VarSymbol[] staticInitializedField = { null }; VarSymbol[] staticInitializedField = { null };
@ -5363,8 +5365,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
if (caseStatement.pat instanceof JCIdent) { if (caseStatement.pat instanceof JCIdent) {
Object value = ((VarSymbol) ((JCIdent) caseStatement.pat).sym).getConstValue(); Object value = ((VarSymbol) ((JCIdent) caseStatement.pat).sym).getConstValue();
if (context.types.isSameType(context.symtab.stringType, caseStatement.pat.type)) { if (context.types.isSameType(context.symtab.stringType, caseStatement.pat.type)) {
print(getStringLiteralQuote() + value + getStringLiteralQuote() print(getStringLiteralQuote() + value + getStringLiteralQuote() + " /* " + caseStatement.pat
+ " /* " + caseStatement.pat + " */"); + " */");
} else { } else {
print("" + value + " /* " + caseStatement.pat + " */"); print("" + value + " /* " + caseStatement.pat + " */");
} }
@ -5802,14 +5804,13 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME + getStringLiteralQuote() + "]")
+ getStringLiteralQuote() + "]").print(" != null && "); .print(" != null && ");
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME + getStringLiteralQuote()
+ getStringLiteralQuote() + "].indexOf(\"") + "].indexOf(\"").print(type.tsym.getQualifiedName().toString()).print("\") >= 0");
.print(type.tsym.getQualifiedName().toString()).print("\") >= 0");
print(" || "); print(" || ");
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
@ -5818,21 +5819,19 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print(".constructor[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME print(".constructor[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME + getStringLiteralQuote()
+ getStringLiteralQuote() + "]").print(" != null && "); + "]").print(" != null && ");
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print(".constructor[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME print(".constructor[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME + getStringLiteralQuote()
+ getStringLiteralQuote() + "].indexOf(\"") + "].indexOf(\"").print(type.tsym.getQualifiedName().toString()).print("\") >= 0");
.print(type.tsym.getQualifiedName().toString()).print("\") >= 0");
if (CharSequence.class.getName().equals(type.tsym.getQualifiedName().toString())) { if (CharSequence.class.getName().equals(type.tsym.getQualifiedName().toString())) {
print(" || typeof "); print(" || typeof ");
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print(" === " + getStringLiteralQuote() + "string" print(" === " + getStringLiteralQuote() + "string" + getStringLiteralQuote());
+ getStringLiteralQuote());
} }
print(")"); print(")");
} else { } else {
@ -5967,11 +5966,10 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
} }
if (assignedType.isInterface() && expression.type.tsym.isEnum()) { if (assignedType.isInterface() && expression.type.tsym.isEnum()) {
String relTarget = getRootRelativeName((Symbol) expression.type.tsym); String relTarget = getRootRelativeName((Symbol) expression.type.tsym);
print("((wrappers, value) => wrappers===undefined?value:wrappers[value])(").print(relTarget) print("((wrappers, value) => wrappers===undefined?value:wrappers[value])(")
.print("[" + getStringLiteralQuote() .print(relTarget).print("[" + getStringLiteralQuote()
+ Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_WRAPPERS + Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_WRAPPERS + getStringLiteralQuote() + "], ")
+ getStringLiteralQuote() + "], ") .print(expression).print(")");
.print(expression).print(")");
return true; return true;
} }
if (expression instanceof JCConditional) { if (expression instanceof JCConditional) {

View File

@ -772,7 +772,18 @@ public class PrinterAdapter {
* @return true if substituted * @return true if substituted
*/ */
public boolean substituteOverloadMethodBody(TypeElement parentTypeElement, Overload overload) { public boolean substituteOverloadMethodBody(TypeElement parentTypeElement, Overload overload) {
return false; return parentAdapter == null ? false : parentAdapter.substituteOverloadMethodBody(parentTypeElement, overload);
}
/**
* Substitutes method's body
*
* @param parentTypeElement parent class
* @param method method's symbol
* @return true if substituted
*/
public boolean substituteMethodBody(TypeElement parentTypeElement, ExecutableElement method) {
return parentAdapter == null ? false : parentAdapter.substituteMethodBody(parentTypeElement, method);
} }
/** /**