fix string literal quotes + test

This commit is contained in:
Renaud Pawlak 2020-06-04 14:56:17 +02:00
parent e84a1b0bae
commit fafa808f79
7 changed files with 56 additions and 47 deletions

2
transpiler/.nvmrc Normal file
View File

@ -0,0 +1,2 @@
12

View File

@ -632,8 +632,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
if (fullImport) { if (fullImport) {
if (context.useRequireForModules) { if (context.useRequireForModules) {
context.addHeader("import." + targetName, context.addHeader("import." + targetName,
"import " + targetName + " = require(" + getAdapter().getStringLiteralQuote() "import " + targetName + " = require(" + getStringLiteralQuote()
+ moduleName + getAdapter().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");
@ -1899,22 +1899,22 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
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("[" + getAdapter().getStringLiteralQuote() + CLASS_NAME_IN_CONSTRUCTOR .print("[" + getStringLiteralQuote() + CLASS_NAME_IN_CONSTRUCTOR
+ getAdapter().getStringLiteralQuote() + "] = ") + getStringLiteralQuote() + "] = ")
.print(getAdapter().getStringLiteralQuote() + classdecl.sym.getQualifiedName().toString() .print(getStringLiteralQuote() + classdecl.sym.getQualifiedName().toString()
+ getAdapter().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("[" + getAdapter().getStringLiteralQuote() + INTERFACES_FIELD_NAME .print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME
+ getAdapter().getStringLiteralQuote() + "] = "); + getStringLiteralQuote() + "] = ");
print("["); print("[");
for (String itf : interfaces) { for (String itf : interfaces) {
print(getAdapter().getStringLiteralQuote()).print(itf) print(getStringLiteralQuote()).print(itf)
.print(getAdapter().getStringLiteralQuote() + ","); .print(getStringLiteralQuote() + ",");
} }
removeLastChar(); removeLastChar();
print("];").println(); print("];").println();
@ -2029,8 +2029,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
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("[" + getAdapter().getStringLiteralQuote() + ENUM_WRAPPER_CLASS_WRAPPERS .print("[" + getStringLiteralQuote() + ENUM_WRAPPER_CLASS_WRAPPERS
+ getAdapter().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 +2052,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
.print("("); .print("(");
} }
print("" + (index++) + ", "); print("" + (index++) + ", ");
print(getAdapter().getStringLiteralQuote() + varDecl.sym.name.toString() print(getStringLiteralQuote() + varDecl.sym.name.toString()
+ getAdapter().getStringLiteralQuote()); + getStringLiteralQuote());
if (!newClass.args.isEmpty()) { if (!newClass.args.isEmpty()) {
print(", "); print(", ");
} }
@ -3416,10 +3416,10 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
} else { } else {
if (context.hasAnnotationType(varDecl.vartype.type.tsym, ANNOTATION_STRING_TYPE) if (context.hasAnnotationType(varDecl.vartype.type.tsym, ANNOTATION_STRING_TYPE)
&& !varDecl.vartype.type.tsym.isEnum()) { && !varDecl.vartype.type.tsym.isEnum()) {
print(getAdapter().getStringLiteralQuote()); print(getStringLiteralQuote());
print(context.getAnnotationValue(varDecl.vartype.type.tsym, ANNOTATION_STRING_TYPE, print(context.getAnnotationValue(varDecl.vartype.type.tsym, ANNOTATION_STRING_TYPE,
String.class, varDecl.vartype.type.tsym.name.toString()).toString()); String.class, varDecl.vartype.type.tsym.name.toString()).toString());
print(getAdapter().getStringLiteralQuote()); print(getStringLiteralQuote());
} else { } else {
substituteAndPrintType(varDecl.vartype); substituteAndPrintType(varDecl.vartype);
} }
@ -3638,9 +3638,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(getAdapter().getStringLiteralQuote()).print(context print(getStringLiteralQuote()).print(context
.getRootRelativeJavaName(((Type.ClassType) fieldAccess.type).typarams_field.head.tsym)) .getRootRelativeJavaName(((Type.ClassType) fieldAccess.type).typarams_field.head.tsym))
.print(getAdapter().getStringLiteralQuote()); .print(getStringLiteralQuote());
} else { } else {
String name = fieldAccess.selected.type.tsym.toString(); String name = fieldAccess.selected.type.tsym.toString();
if (context.isMappedType(name)) { if (context.isMappedType(name)) {
@ -3648,10 +3648,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(getAdapter().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(getAdapter().getStringLiteralQuote()); .print(getStringLiteralQuote());
} }
} else { } else {
if (CONSTRUCTOR_TYPE_MAPPING.containsKey(name)) { if (CONSTRUCTOR_TYPE_MAPPING.containsKey(name)) {
@ -4515,8 +4515,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
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(getAdapter().getStringLiteralQuote()).print(i) print(getStringLiteralQuote()).print(i)
.print(getAdapter().getStringLiteralQuote() + ","); .print(getStringLiteralQuote() + ",");
} }
removeLastChar(); removeLastChar();
print("]"); print("]");
@ -4737,7 +4737,7 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
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);
} }
@ -5359,7 +5359,7 @@ 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(getAdapter().getStringLiteralQuote() + value + getAdapter().getStringLiteralQuote() print(getStringLiteralQuote() + value + getStringLiteralQuote()
+ " /* " + caseStatement.pat + " */"); + " /* " + caseStatement.pat + " */");
} else { } else {
print("" + value + " /* " + caseStatement.pat + " */"); print("" + value + " /* " + caseStatement.pat + " */");
@ -5798,13 +5798,13 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print("[" + getAdapter().getStringLiteralQuote() + INTERFACES_FIELD_NAME print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME
+ getAdapter().getStringLiteralQuote() + "]").print(" != null && "); + getStringLiteralQuote() + "]").print(" != null && ");
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print("[" + getAdapter().getStringLiteralQuote() + INTERFACES_FIELD_NAME print("[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME
+ getAdapter().getStringLiteralQuote() + "].indexOf(\"") + getStringLiteralQuote() + "].indexOf(\"")
.print(type.tsym.getQualifiedName().toString()).print("\") >= 0"); .print(type.tsym.getQualifiedName().toString()).print("\") >= 0");
print(" || "); print(" || ");
print(exprStr, expr); print(exprStr, expr);
@ -5814,21 +5814,21 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print(".constructor[" + getAdapter().getStringLiteralQuote() + INTERFACES_FIELD_NAME print(".constructor[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME
+ getAdapter().getStringLiteralQuote() + "]").print(" != null && "); + getStringLiteralQuote() + "]").print(" != null && ");
print(exprStr, expr); print(exprStr, expr);
if (checkFirstArrayElement) if (checkFirstArrayElement)
print("[0]"); print("[0]");
print(".constructor[" + getAdapter().getStringLiteralQuote() + INTERFACES_FIELD_NAME print(".constructor[" + getStringLiteralQuote() + INTERFACES_FIELD_NAME
+ getAdapter().getStringLiteralQuote() + "].indexOf(\"") + getStringLiteralQuote() + "].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(" === " + getAdapter().getStringLiteralQuote() + "string" print(" === " + getStringLiteralQuote() + "string"
+ getAdapter().getStringLiteralQuote()); + getStringLiteralQuote());
} }
print(")"); print(")");
} else { } else {
@ -5964,9 +5964,9 @@ 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(relTarget)
.print("[" + getAdapter().getStringLiteralQuote() .print("[" + getStringLiteralQuote()
+ Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_WRAPPERS + Java2TypeScriptTranslator.ENUM_WRAPPER_CLASS_WRAPPERS
+ getAdapter().getStringLiteralQuote() + "], ") + getStringLiteralQuote() + "], ")
.print(expression).print(")"); .print(expression).print(")");
return true; return true;
} }

View File

@ -98,7 +98,6 @@ import org.jsweet.transpiler.model.support.IdentifierElementSupport;
import org.jsweet.transpiler.model.support.ImportElementSupport; import org.jsweet.transpiler.model.support.ImportElementSupport;
import org.jsweet.transpiler.model.support.MethodInvocationElementSupport; import org.jsweet.transpiler.model.support.MethodInvocationElementSupport;
import org.jsweet.transpiler.model.support.NewClassElementSupport; import org.jsweet.transpiler.model.support.NewClassElementSupport;
import org.jsweet.transpiler.model.support.UtilSupport;
import org.jsweet.transpiler.model.support.VariableAccessElementSupport; import org.jsweet.transpiler.model.support.VariableAccessElementSupport;
import org.jsweet.transpiler.util.Util; import org.jsweet.transpiler.util.Util;

View File

@ -94,14 +94,6 @@ public class PrinterAdapter {
this.parentAdapter = null; this.parentAdapter = null;
} }
/**
* Returns a quote string (single or double quote depending on the
* <code>useSingleQuotesForStringLiterals</code> option).
*/
public String getStringLiteralQuote() {
return getContext().options.isUseSingleQuotesForStringLiterals() ? "'" : "\"";
}
/** /**
* Returns the current compilation unit. * Returns the current compilation unit.
*/ */

View File

@ -137,6 +137,14 @@ public abstract class AbstractTreePrinter extends AbstractTreeScanner {
this.fillSourceMap = fillSourceMap; this.fillSourceMap = fillSourceMap;
} }
/**
* Returns a quote string (single or double quote depending on the
* <code>useSingleQuotesForStringLiterals</code> option).
*/
protected String getStringLiteralQuote() {
return this.context.options.isUseSingleQuotesForStringLiterals() ? "'" : "\"";
}
/** /**
* Gets this output of this printer. * Gets this output of this printer.
*/ */

View File

@ -211,10 +211,16 @@ public class NativeStructuresTests extends AbstractTest {
@Test @Test
public void testStrings() { public void testStrings() {
eval((logHandler, result) -> { eval(ModuleKind.none, (logHandler, result) -> {
Assert.assertEquals("There should be no errors", 0, logHandler.reportedProblems.size()); Assert.assertEquals("There should be no errors", 0, logHandler.reportedProblems.size());
assertEquals(">,0,ABC,abc,abcd,AB,b", result.get("trace")); assertEquals(">,0,ABC,abc,abcd,AB,b,Hello, I'm \"Renaud\",Hello, \"Renaud\"", result.get("trace"));
}, getSourceFile(Strings.class)); }, getSourceFile(Strings.class));
transpilerTest().getTranspiler().setUseSingleQuotesForStringLiterals(true);
eval(ModuleKind.none, (logHandler, result) -> {
Assert.assertEquals("There should be no errors", 0, logHandler.reportedProblems.size());
assertEquals(">,0,ABC,abc,abcd,AB,b,Hello, I'm \"Renaud\",Hello, \"Renaud\"", result.get("trace"));
}, getSourceFile(Strings.class));
transpilerTest().getTranspiler().setUseSingleQuotesForStringLiterals(false);
} }
@Ignore @Ignore

View File

@ -20,6 +20,8 @@ public class Strings {
trace.push(new String(sb)); trace.push(new String(sb));
trace.push(new String(bytes, 0, 2)); trace.push(new String(bytes, 0, 2));
trace.push(new String(chars, 1, 1)); trace.push(new String(chars, 1, 1));
trace.push("Hello, I'm \"Renaud\"");
trace.push("Hello, \"Renaud\"");
$export("trace", trace.join(",")); $export("trace", trace.join(","));
assert "" == new String(); assert "" == new String();
byte[] bytes2 = { 'a', 'b', 'c' }; byte[] bytes2 = { 'a', 'b', 'c' };