List of usage examples for javax.lang.model.type TypeKind ARRAY
TypeKind ARRAY
To view the source code for javax.lang.model.type TypeKind ARRAY.
Click Source Link
From source file:auto.parse.processor.AutoParseProcessor.java
private static boolean containsArrayType(Set<TypeMirror> types) { for (TypeMirror type : types) { if (type.getKind() == TypeKind.ARRAY) { return true; }/*from w ww .ja v a 2 s. c o m*/ } return false; }
From source file:auto.parse.processor.AutoParseProcessor.java
private static boolean isReferenceArrayType(TypeMirror type) { return type.getKind() == TypeKind.ARRAY && (((ArrayType) type).getComponentType().getKind() != TypeKind.BYTE); }
From source file:org.jsweet.transpiler.typescript.Java2TypeScriptTranslator.java
@Override public void visitApply(JCMethodInvocation inv) { if (!getAdapter().substituteMethodInvocation(inv)) { String meth = inv.meth.toString(); String methName = meth.substring(meth.lastIndexOf('.') + 1); if (methName.equals("super") && getScope().removedSuperclass) { return; }/*from w w w . jav a2 s. co m*/ boolean applyVarargs = true; if (JSweetConfig.NEW_FUNCTION_NAME.equals(methName)) { print("new "); applyVarargs = false; } boolean anonymous = JSweetConfig.ANONYMOUS_FUNCTION_NAME.equals(methName) || JSweetConfig.ANONYMOUS_STATIC_FUNCTION_NAME.equals(methName) || JSweetConfig.NEW_FUNCTION_NAME.equals(methName); boolean targetIsThisOrStaticImported = meth.equals(methName) || meth.equals("this." + methName); MethodType type = inv.meth.type instanceof MethodType ? (MethodType) inv.meth.type : null; MethodSymbol methSym = null; String methodName = null; boolean keywordHandled = false; if (targetIsThisOrStaticImported) { JCImport staticImport = getStaticGlobalImport(methName); if (staticImport == null) { JCClassDecl p = getParent(JCClassDecl.class); methSym = p == null ? null : Util.findMethodDeclarationInType(context.types, p.sym, methName, type); if (methSym != null) { typeChecker.checkApply(inv, methSym); if (!methSym.isStatic()) { if (!meth.startsWith("this.")) { print("this"); if (!anonymous) { print("."); } } } else { if (meth.startsWith("this.") && methSym.isStatic()) { report(inv, JSweetProblem.CANNOT_ACCESS_STATIC_MEMBER_ON_THIS, methSym.getSimpleName()); } if (!JSweetConfig.GLOBALS_CLASS_NAME.equals(methSym.owner.getSimpleName().toString())) { print("" + methSym.owner.getSimpleName()); if (methSym.owner.isEnum()) { print(ENUM_WRAPPER_CLASS_SUFFIX); } if (!anonymous) { print("."); } } } } else { if (getScope().defaultMethodScope) { TypeSymbol target = Util.getStaticImportTarget( getContext().getDefaultMethodCompilationUnit(getParent(JCMethodDecl.class)), methName); if (target != null) { print(getRootRelativeName(target) + "."); } } else { TypeSymbol target = Util.getStaticImportTarget(compilationUnit, methName); if (target != null) { print(getRootRelativeName(target) + "."); } } if (getScope().innerClass) { JCClassDecl parent = getParent(JCClassDecl.class); int level = 0; MethodSymbol method = null; if (parent != null) { while (getScope(level++).innerClass) { parent = getParent(JCClassDecl.class, parent); if ((method = Util.findMethodDeclarationInType(context.types, parent.sym, methName, type)) != null) { break; } } } if (method != null) { if (method.isStatic()) { print(method.getEnclosingElement().getSimpleName().toString() + "."); } else { print("this."); for (int i = 0; i < level; i++) { print(PARENT_CLASS_FIELD_NAME + "."); } if (anonymous) { removeLastChar(); } } } } } } else { JCFieldAccess staticFieldAccess = (JCFieldAccess) staticImport.qualid; methSym = Util.findMethodDeclarationInType(context.types, staticFieldAccess.selected.type.tsym, methName, type); if (methSym != null) { Map<String, VarSymbol> vars = new HashMap<>(); Util.fillAllVariablesInScope(vars, getStack(), inv, getParent(JCMethodDecl.class)); if (vars.containsKey(methSym.getSimpleName().toString())) { report(inv, JSweetProblem.HIDDEN_INVOCATION, methSym.getSimpleName()); } if (context.bundleMode && methSym.owner.getSimpleName().toString().equals(GLOBALS_CLASS_NAME) && methSym.owner.owner != null && !methSym.owner.owner.getSimpleName().toString().equals(GLOBALS_PACKAGE_NAME)) { String prefix = getRootRelativeName(methSym.owner.owner); if (!StringUtils.isEmpty(prefix)) { print(getRootRelativeName(methSym.owner.owner) + "."); } } } if (JSweetConfig.TS_STRICT_MODE_KEYWORDS.contains(context.getActualName(methSym))) { String targetClass = getStaticContainerFullName(staticImport); if (!isBlank(targetClass)) { print(targetClass); print("."); keywordHandled = true; } if (JSweetConfig.isLibPath(methSym.getEnclosingElement().getQualifiedName().toString())) { methodName = methName.toLowerCase(); } } } } else { if (inv.meth instanceof JCFieldAccess) { JCExpression selected = ((JCFieldAccess) inv.meth).selected; if (context.hasAnnotationType(selected.type.tsym, FunctionalInterface.class.getName())) { anonymous = true; } methSym = Util.findMethodDeclarationInType(context.types, selected.type.tsym, methName, type); if (methSym != null) { typeChecker.checkApply(inv, methSym); } } } boolean isStatic = methSym == null || methSym.isStatic(); if (!Util.hasVarargs(methSym) // || !inv.args.isEmpty() && (inv.args.last().type.getKind() != TypeKind.ARRAY // we dont use apply if var args type differ || !context.types.erasure(((ArrayType) inv.args.last().type).elemtype) .equals(context.types.erasure( ((ArrayType) methSym.getParameters().last().type).elemtype)))) { applyVarargs = false; } String targetVarName = null; if (anonymous) { if (inv.meth instanceof JCFieldAccess) { JCExpression selected = ((JCFieldAccess) inv.meth).selected; print(selected); } } else { if (inv.meth instanceof JCFieldAccess && applyVarargs && !targetIsThisOrStaticImported && !isStatic) { targetVarName = "this['__jswref_" + (applyTargetRefCounter++) + "']"; print("("); print(targetVarName + " = "); print(((JCFieldAccess) inv.meth).selected); print(")."); if (keywordHandled) { print(((JCFieldAccess) inv.meth).name.toString()); } else { if (methSym == null) { methSym = (MethodSymbol) ((JCFieldAccess) inv.meth).sym; } if (methSym != null) { print(context.getActualName(methSym)); } else { print(((JCFieldAccess) inv.meth).name.toString()); } } } else if (methodName != null) { print(methodName); } else { if (keywordHandled) { print(inv.meth); } else { if (methSym == null && inv.meth instanceof JCFieldAccess && ((JCFieldAccess) inv.meth).sym instanceof MethodSymbol) { methSym = (MethodSymbol) ((JCFieldAccess) inv.meth).sym; } if (methSym != null && inv.meth instanceof JCFieldAccess) { JCExpression selected = ((JCFieldAccess) inv.meth).selected; print(selected).print("."); } if (methSym != null) { print(context.getActualName(methSym)); } else { print(inv.meth); } } } } if (applyVarargs) { print(".apply"); } else { if (inv.typeargs != null && !inv.typeargs.isEmpty()) { print("<"); for (JCExpression argument : inv.typeargs) { getAdapter().substituteAndPrintType(argument).print(","); } removeLastChar(); print(">"); } else { // force type arguments to any because they are inferred to // {}by default if (methSym != null && !methSym.getTypeParameters().isEmpty()) { ClassSymbol target = (ClassSymbol) methSym.getEnclosingElement(); if (!target.getQualifiedName().toString().startsWith(JSweetConfig.LIBS_PACKAGE + ".")) { // invalid overload type parameters are erased Overload overload = context.getOverload(target, methSym); boolean inOverload = overload != null && overload.methods.size() > 1; if (!(inOverload && !overload.isValid)) { printAnyTypeArguments(methSym.getTypeParameters().size()); } } } } } print("("); if (applyVarargs) { String contextVar = "null"; if (targetIsThisOrStaticImported) { contextVar = "this"; } else if (targetVarName != null) { contextVar = targetVarName; } print(contextVar + ", "); if (inv.args.size() > 1) { print("["); } } int argsLength = applyVarargs ? inv.args.size() - 1 : inv.args.size(); if (getScope().innerClassNotStatic && "super".equals(methName)) { TypeSymbol s = getParent(JCClassDecl.class).extending.type.tsym; if (s.getEnclosingElement() instanceof ClassSymbol && !s.isStatic()) { print(PARENT_CLASS_FIELD_NAME); if (argsLength > 0) { print(", "); } } } if (getScope().enumWrapperClassScope && isAnonymousClass() && "super".equals(methName)) { print(ENUM_WRAPPER_CLASS_ORDINAL + ", " + ENUM_WRAPPER_CLASS_NAME); if (argsLength > 0) { print(", "); } } for (int i = 0; i < argsLength; i++) { JCExpression arg = inv.args.get(i); if (inv.meth.type != null) { List<Type> argTypes = ((MethodType) inv.meth.type).argtypes; Type paramType = i < argTypes.size() ? argTypes.get(i) : argTypes.get(argTypes.size() - 1); if (!getAdapter().substituteAssignedExpression(paramType, arg)) { print(arg); } } if (i < argsLength - 1) { print(", "); } } if (applyVarargs) { if (inv.args.size() > 1) { // we cast array to any[] to avoid concat error on // different // types print("].concat(<any[]>"); } print(inv.args.last()); if (inv.args.size() > 1) { print(")"); } } print(")"); } }
From source file:org.jsweet.transpiler.typescript.Java2TypeScriptTranslator.java
@Override public void visitNewClass(JCNewClass newClass) { ClassSymbol clazz = ((ClassSymbol) newClass.clazz.type.tsym); if (clazz.name.toString().endsWith(JSweetConfig.GLOBALS_CLASS_NAME)) { report(newClass, JSweetProblem.GLOBAL_CANNOT_BE_INSTANTIATED); return;//from www. j a v a 2 s .com } if (getScope().localClasses.stream().map(c -> c.type).anyMatch(t -> t.equals(newClass.type))) { print("new ").print(getScope().name + ".").print(newClass.clazz.toString()); print("(").printConstructorArgList(newClass, true).print(")"); return; } boolean isInterface = context.isInterface(clazz); if (newClass.def != null || isInterface) { if (context.isAnonymousClass(newClass)) { int anonymousClassIndex = initAnonymousClass(newClass); print("new ") .print(getScope().name + "." + getScope().name + ANONYMOUS_PREFIX + anonymousClassIndex); if (newClass.def.getModifiers().getFlags().contains(Modifier.STATIC)) { printAnonymousClassTypeArgs(newClass); } print("(").printConstructorArgList(newClass, false).print(")"); return; } if (isInterface || context.hasAnnotationType(newClass.clazz.type.tsym, JSweetConfig.ANNOTATION_OBJECT_TYPE)) { if (isInterface) { print("<any>"); } Set<String> interfaces = new HashSet<>(); if (getContext().options.isInterfaceTracking()) { context.grabSupportedInterfaceNames(interfaces, clazz); if (!interfaces.isEmpty()) { print("Object.defineProperty("); } } print("{").println().startIndent(); boolean statementPrinted = false; boolean initializationBlockFound = false; if (newClass.def != null) { for (JCTree m : newClass.def.getMembers()) { if (m instanceof JCBlock) { initializationBlockFound = true; List<VarSymbol> initializedVars = new ArrayList<>(); for (JCTree s : ((JCBlock) m).stats) { boolean currentStatementPrinted = false; if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCAssign) { JCAssign assignment = (JCAssign) ((JCExpressionStatement) s).expr; VarSymbol var = null; if (assignment.lhs instanceof JCFieldAccess) { var = Util.findFieldDeclaration(clazz, ((JCFieldAccess) assignment.lhs).name); printIndent().print(var.getSimpleName().toString()); } else if (assignment.lhs instanceof JCIdent) { var = Util.findFieldDeclaration(clazz, ((JCIdent) assignment.lhs).name); printIndent().print(assignment.lhs.toString()); } else { continue; } initializedVars.add(var); print(": ").print(assignment.rhs).print(",").println(); currentStatementPrinted = true; statementPrinted = true; } else if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCMethodInvocation) { JCMethodInvocation invocation = (JCMethodInvocation) ((JCExpressionStatement) s).expr; String meth = invocation.meth.toString(); if (meth.equals(JSweetConfig.INDEXED_SET_FUCTION_NAME) || meth.equals(JSweetConfig.UTIL_CLASSNAME + "." + JSweetConfig.INDEXED_SET_FUCTION_NAME)) { if (invocation.getArguments().size() == 3) { if ("this".equals(invocation.getArguments().get(0).toString())) { printIndent().print(invocation.args.tail.head).print(": ") .print(invocation.args.tail.tail.head).print(",").println(); } currentStatementPrinted = true; statementPrinted = true; } else { printIndent().print(invocation.args.head).print(": ") .print(invocation.args.tail.head).print(",").println(); currentStatementPrinted = true; statementPrinted = true; } } } if (!currentStatementPrinted) { report(s, JSweetProblem.INVALID_INITIALIZER_STATEMENT); } } for (Symbol s : clazz.getEnclosedElements()) { if (s instanceof VarSymbol) { if (!initializedVars.contains(s)) { if (!context.hasAnnotationType(s, JSweetConfig.ANNOTATION_OPTIONAL)) { report(m, JSweetProblem.UNINITIALIZED_FIELD, s); } } } } if (statementPrinted) { removeLastChars(2); } } } } if (!statementPrinted && !initializationBlockFound) { for (Symbol s : clazz.getEnclosedElements()) { if (s instanceof VarSymbol) { if (!context.hasAnnotationType(s, JSweetConfig.ANNOTATION_OPTIONAL)) { report(newClass, JSweetProblem.UNINITIALIZED_FIELD, s); } } } } println().endIndent().printIndent().print("}"); if (getContext().options.isInterfaceTracking()) { if (!interfaces.isEmpty()) { print(", '" + INTERFACES_FIELD_NAME + "', { configurable: true, value: "); print("["); for (String i : interfaces) { print("\"").print(i).print("\","); } removeLastChar(); print("]"); print(" })"); } } } else { // ((target : DataStruct3) => { // target['i'] = 1; // target['s2'] = ""; // return target // })(new DataStruct3()); print("((target:").print(newClass.clazz).print(") => {").println().startIndent(); for (JCTree m : newClass.def.getMembers()) { if (m instanceof JCBlock) { for (JCTree s : ((JCBlock) m).stats) { boolean currentStatementPrinted = false; if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCAssign) { JCAssign assignment = (JCAssign) ((JCExpressionStatement) s).expr; VarSymbol var = null; if (assignment.lhs instanceof JCFieldAccess) { var = Util.findFieldDeclaration(clazz, ((JCFieldAccess) assignment.lhs).name); printIndent().print("target['").print(var.getSimpleName().toString()) .print("']"); } else if (assignment.lhs instanceof JCIdent) { printIndent().print("target['").print(assignment.lhs.toString()).print("']"); } else { continue; } print(" = ").print(assignment.rhs).print(";").println(); currentStatementPrinted = true; } else if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCMethodInvocation) { JCMethodInvocation invocation = (JCMethodInvocation) ((JCExpressionStatement) s).expr; String meth = invocation.meth.toString(); if (meth.equals(JSweetConfig.INDEXED_SET_FUCTION_NAME) || meth.equals(JSweetConfig.UTIL_CLASSNAME + "." + JSweetConfig.INDEXED_SET_FUCTION_NAME)) { if (invocation.getArguments().size() == 3) { if ("this".equals(invocation.getArguments().get(0).toString())) { printIndent().print("target[").print(invocation.args.tail.head) .print("]").print(" = ").print(invocation.args.tail.tail.head) .print(";").println(); } currentStatementPrinted = true; } else { printIndent().print("target[").print(invocation.args.head).print("]") .print(" = ").print(invocation.args.tail.head).print(";").println(); currentStatementPrinted = true; } } } if (!currentStatementPrinted) { report(s, JSweetProblem.INVALID_INITIALIZER_STATEMENT); } } } } printIndent().print("return target;").println(); println().endIndent().printIndent().print("})("); print("new ").print(newClass.clazz).print("(").printArgList(newClass.args).print("))"); } } else { if (context.hasAnnotationType(newClass.clazz.type.tsym, JSweetConfig.ANNOTATION_ERASED)) { if (newClass.args.length() != 1) { report(newClass, JSweetProblem.ERASED_CLASS_CONSTRUCTOR); } print("(").print(newClass.args.head).print(")"); } else if (context.hasAnnotationType(newClass.clazz.type.tsym, JSweetConfig.ANNOTATION_OBJECT_TYPE)) { print("{}"); } else { if (!getAdapter().substituteNewClass(newClass)) { if (typeChecker.checkType(newClass, null, newClass.clazz)) { boolean applyVarargs = true; MethodSymbol methSym = (MethodSymbol) newClass.constructor; if (newClass.args.size() == 0 || !Util.hasVarargs(methSym) // || newClass.args.last().type.getKind() != TypeKind.ARRAY // we dont use apply if var args type differ || !context.types.erasure(((ArrayType) newClass.args.last().type).elemtype) .equals(context.types.erasure( ((ArrayType) methSym.getParameters().last().type).elemtype))) { applyVarargs = false; } if (applyVarargs) { // this is necessary in case the user defines a // Function class that hides the global Function // class context.addGlobalsMapping("Function", "__Function"); print("<any>new (__Function.prototype.bind.apply(").print(newClass.clazz) .print(", [null"); for (int i = 0; i < newClass.args.length() - 1; i++) { print(", ").print(newClass.args.get(i)); } print("].concat(<any[]>").print(newClass.args.last()).print(")))"); } else { if (newClass.clazz instanceof JCTypeApply) { JCTypeApply typeApply = (JCTypeApply) newClass.clazz; print("new ").print(typeApply.clazz); if (!typeApply.arguments.isEmpty()) { print("<").printTypeArgList(typeApply.arguments).print(">"); } else { // erase types since the diamond (<>) // operator // does not exists in TypeScript printAnyTypeArguments( ((ClassSymbol) newClass.clazz.type.tsym).getTypeParameters().length()); } print("(").printConstructorArgList(newClass, false).print(")"); } else { print("new ").print(newClass.clazz).print("(") .printConstructorArgList(newClass, false).print(")"); } } } } } } }
From source file:org.jsweet.transpiler.Java2TypeScriptTranslator.java
@Override public void visitApply(JCMethodInvocation inv) { boolean debugMode = false; if (context.options.isDebugMode()) { if (Util.getSymbol(inv.meth) instanceof MethodSymbol) { MethodSymbol methodSymbol = (MethodSymbol) Util.getSymbol(inv.meth); if (!methodSymbol.isConstructor() && Util.isSourceElement(methodSymbol)) { debugMode = true;/*from ww w. j a v a 2 s .c om*/ } } } if (debugMode) { print("__debug_result(yield "); } if (!getAdapter().substituteMethodInvocation(new MethodInvocationElementSupport(inv))) { String meth = inv.meth.toString(); String methName = meth.substring(meth.lastIndexOf('.') + 1); if (methName.equals("super") && getScope().removedSuperclass) { return; } boolean applyVarargs = true; if (JSweetConfig.NEW_FUNCTION_NAME.equals(methName)) { print("new "); applyVarargs = false; } boolean anonymous = JSweetConfig.ANONYMOUS_FUNCTION_NAME.equals(methName) || JSweetConfig.ANONYMOUS_STATIC_FUNCTION_NAME.equals(methName) || JSweetConfig.NEW_FUNCTION_NAME.equals(methName); boolean targetIsThisOrStaticImported = meth.equals(methName) || meth.equals("this." + methName); MethodType type = inv.meth.type instanceof MethodType ? (MethodType) inv.meth.type : null; MethodSymbol methSym = null; String methodName = null; boolean keywordHandled = false; if (targetIsThisOrStaticImported) { JCImport staticImport = getStaticGlobalImport(methName); if (staticImport == null) { JCClassDecl p = getParent(JCClassDecl.class); methSym = p == null ? null : Util.findMethodDeclarationInType(context.types, p.sym, methName, type); if (methSym != null) { typeChecker.checkApply(inv, methSym); if (!methSym.isStatic()) { if (!meth.startsWith("this.")) { print("this"); if (!anonymous) { print("."); } } } else { if (meth.startsWith("this.") && methSym.isStatic()) { report(inv, JSweetProblem.CANNOT_ACCESS_STATIC_MEMBER_ON_THIS, methSym.getSimpleName()); } if (!JSweetConfig.GLOBALS_CLASS_NAME.equals(methSym.owner.getSimpleName().toString())) { print("" + methSym.owner.getSimpleName()); if (methSym.owner.isEnum()) { print(ENUM_WRAPPER_CLASS_SUFFIX); } if (!anonymous) { print("."); } } } } else { if (getScope().defaultMethodScope) { TypeSymbol target = Util.getStaticImportTarget( getContext().getDefaultMethodCompilationUnit(getParent(JCMethodDecl.class)), methName); if (target != null) { print(getRootRelativeName(target) + "."); } } else { TypeSymbol target = Util.getStaticImportTarget(compilationUnit, methName); if (target != null) { print(getRootRelativeName(target) + "."); } } if (getScope().innerClass) { JCClassDecl parent = getParent(JCClassDecl.class); int level = 0; MethodSymbol method = null; if (parent != null) { while (getScope(level++).innerClass) { parent = getParent(JCClassDecl.class, parent); if ((method = Util.findMethodDeclarationInType(context.types, parent.sym, methName, type)) != null) { break; } } } if (method != null) { if (method.isStatic()) { print(method.getEnclosingElement().getSimpleName().toString() + "."); } else { print("this."); for (int i = 0; i < level; i++) { print(PARENT_CLASS_FIELD_NAME + "."); } if (anonymous) { removeLastChar(); } } } } } } else { JCFieldAccess staticFieldAccess = (JCFieldAccess) staticImport.qualid; methSym = Util.findMethodDeclarationInType(context.types, staticFieldAccess.selected.type.tsym, methName, type); if (methSym != null) { Map<String, VarSymbol> vars = new HashMap<>(); Util.fillAllVariablesInScope(vars, getStack(), inv, getParent(JCMethodDecl.class)); if (vars.containsKey(methSym.getSimpleName().toString())) { report(inv, JSweetProblem.HIDDEN_INVOCATION, methSym.getSimpleName()); } if (context.bundleMode && methSym.owner.getSimpleName().toString().equals(GLOBALS_CLASS_NAME) && methSym.owner.owner != null && !methSym.owner.owner.getSimpleName().toString().equals(GLOBALS_PACKAGE_NAME)) { String prefix = getRootRelativeName(methSym.owner.owner); if (!StringUtils.isEmpty(prefix)) { print(getRootRelativeName(methSym.owner.owner) + "."); } } } if (JSweetConfig.TS_STRICT_MODE_KEYWORDS.contains(context.getActualName(methSym))) { String targetClass = getStaticContainerFullName(staticImport); if (!isBlank(targetClass)) { print(targetClass); print("."); keywordHandled = true; } if (JSweetConfig.isLibPath(methSym.getEnclosingElement().getQualifiedName().toString())) { methodName = methName.toLowerCase(); } } } } else { if (inv.meth instanceof JCFieldAccess) { JCExpression selected = ((JCFieldAccess) inv.meth).selected; if (context.isFunctionalType(selected.type.tsym)) { anonymous = true; } methSym = Util.findMethodDeclarationInType(context.types, selected.type.tsym, methName, type); if (methSym != null) { typeChecker.checkApply(inv, methSym); } } } boolean isStatic = methSym == null || methSym.isStatic(); if (!Util.hasVarargs(methSym) // || !inv.args.isEmpty() && (inv.args.last().type.getKind() != TypeKind.ARRAY // we dont use apply if var args type differ || !context.types.erasure(((ArrayType) inv.args.last().type).elemtype) .equals(context.types.erasure( ((ArrayType) methSym.getParameters().last().type).elemtype)))) { applyVarargs = false; } String targetVarName = null; if (anonymous) { if (inv.meth instanceof JCFieldAccess) { JCExpression selected = ((JCFieldAccess) inv.meth).selected; print(selected); } } else { // method with name if (inv.meth instanceof JCFieldAccess && applyVarargs && !targetIsThisOrStaticImported && !isStatic) { targetVarName = "this['__jswref_" + (applyTargetRefCounter++) + "']"; print("("); print(targetVarName + " = "); print(((JCFieldAccess) inv.meth).selected); print(")"); String accessedMemberName; if (keywordHandled) { accessedMemberName = ((JCFieldAccess) inv.meth).name.toString(); } else { if (methSym == null) { methSym = (MethodSymbol) ((JCFieldAccess) inv.meth).sym; } if (methSym != null) { accessedMemberName = context.getActualName(methSym); } else { accessedMemberName = ((JCFieldAccess) inv.meth).name.toString(); } } print(getTSMemberAccess(accessedMemberName, true)); } else if (methodName != null) { print(getTSMemberAccess(methodName, removeLastChar('.'))); } else { if (keywordHandled) { print(inv.meth); } else { if (methSym == null && inv.meth instanceof JCFieldAccess && ((JCFieldAccess) inv.meth).sym instanceof MethodSymbol) { methSym = (MethodSymbol) ((JCFieldAccess) inv.meth).sym; } if (methSym != null && inv.meth instanceof JCFieldAccess) { JCExpression selected = ((JCFieldAccess) inv.meth).selected; if (!GLOBALS_CLASS_NAME.equals(selected.type.tsym.getSimpleName().toString())) { print(selected).print("."); } else { if (context.useModules) { if (!((ClassSymbol) selected.type.tsym).sourcefile.getName() .equals(getCompilationUnit().sourcefile.getName())) { // TODO: when using several qualified // Globals classes, we // need to disambiguate (use qualified // name with // underscores) print(GLOBALS_CLASS_NAME).print("."); } } Map<String, VarSymbol> vars = new HashMap<>(); Util.fillAllVariablesInScope(vars, getStack(), inv, getParent(JCMethodDecl.class)); if (vars.containsKey(methName)) { report(inv, JSweetProblem.HIDDEN_INVOCATION, methName); } } } if (methSym != null) { if (context.isInvalidOverload(methSym) && !methSym.getParameters().isEmpty() && !Util.hasTypeParameters(methSym) && !Util.hasVarargs(methSym) && getParent(JCMethodDecl.class) != null && !getParent(JCMethodDecl.class).sym.isDefault()) { if (methSym.getEnclosingElement().isInterface()) { removeLastChar('.'); print("['" + getOverloadMethodName(methSym) + "']"); } else { print(getOverloadMethodName(methSym)); } } else { print(getTSMemberAccess(context.getActualName(methSym), removeLastChar('.'))); } } else { print(inv.meth); } } } } if (applyVarargs) { print(".apply"); } else { if (inv.typeargs != null && !inv.typeargs.isEmpty()) { print("<"); for (JCExpression argument : inv.typeargs) { substituteAndPrintType(argument).print(","); } removeLastChar(); print(">"); } else { // force type arguments to any because they are inferred to // {}by default if (methSym != null && !methSym.getTypeParameters().isEmpty()) { ClassSymbol target = (ClassSymbol) methSym.getEnclosingElement(); if (!target.getQualifiedName().toString().startsWith(JSweetConfig.LIBS_PACKAGE + ".")) { // invalid overload type parameters are erased Overload overload = context.getOverload(target, methSym); boolean inOverload = overload != null && overload.methods.size() > 1; if (!(inOverload && !overload.isValid)) { printAnyTypeArguments(methSym.getTypeParameters().size()); } } } } } print("("); if (applyVarargs) { String contextVar = "null"; if (targetIsThisOrStaticImported) { contextVar = "this"; } else if (targetVarName != null) { contextVar = targetVarName; } print(contextVar + ", "); if (inv.args.size() > 1) { print("["); } } int argsLength = applyVarargs ? inv.args.size() - 1 : inv.args.size(); if (getScope().innerClassNotStatic && "super".equals(methName)) { TypeSymbol s = getParent(JCClassDecl.class).extending.type.tsym; if (s.getEnclosingElement() instanceof ClassSymbol && !s.isStatic()) { print(PARENT_CLASS_FIELD_NAME); if (argsLength > 0) { print(", "); } } } if (getScope().enumWrapperClassScope && isAnonymousClass() && "super".equals(methName)) { print(ENUM_WRAPPER_CLASS_ORDINAL + ", " + ENUM_WRAPPER_CLASS_NAME); if (argsLength > 0) { print(", "); } } for (int i = 0; i < argsLength; i++) { JCExpression arg = inv.args.get(i); if (inv.meth.type != null) { List<Type> argTypes = ((MethodType) inv.meth.type).argtypes; Type paramType = i < argTypes.size() ? argTypes.get(i) : argTypes.get(argTypes.size() - 1); if (!substituteAssignedExpression(paramType, arg)) { print(arg); } } else { // this should never happen but we fall back just in case print(arg); } if (i < argsLength - 1) { print(", "); } } if (applyVarargs) { if (inv.args.size() > 1) { // we cast array to any[] to avoid concat error on // different // types print("].concat(<any[]>"); } print(inv.args.last()); if (inv.args.size() > 1) { print(")"); } } print(")"); } if (debugMode) { print(")"); } }
From source file:org.jsweet.transpiler.Java2TypeScriptTranslator.java
@Override public void visitNewClass(JCNewClass newClass) { ClassSymbol clazz = ((ClassSymbol) newClass.clazz.type.tsym); if (clazz.getSimpleName().toString().equals(JSweetConfig.GLOBALS_CLASS_NAME)) { report(newClass, JSweetProblem.GLOBAL_CANNOT_BE_INSTANTIATED); return;/* www. ja v a 2s . c o m*/ } if (getScope().localClasses.stream().map(c -> c.type).anyMatch(t -> t.equals(newClass.type))) { print("new ").print(getScope().name + ".").print(newClass.clazz.toString()); print("(").printConstructorArgList(newClass, true).print(")"); return; } boolean isInterface = context.isInterface(clazz); if (newClass.def != null || isInterface) { if (context.isAnonymousClass(newClass)) { int anonymousClassIndex = initAnonymousClass(newClass); print("new ") .print(getScope().name + "." + getScope().name + ANONYMOUS_PREFIX + anonymousClassIndex); if (newClass.def.getModifiers().getFlags().contains(Modifier.STATIC)) { printAnonymousClassTypeArgs(newClass); } print("(").printConstructorArgList(newClass, false).print(")"); return; } if (isInterface || context.hasAnnotationType(newClass.clazz.type.tsym, JSweetConfig.ANNOTATION_OBJECT_TYPE)) { if (isInterface) { print("<any>"); } Set<String> interfaces = new HashSet<>(); if (getContext().options.isInterfaceTracking()) { context.grabSupportedInterfaceNames(interfaces, clazz); if (!interfaces.isEmpty()) { print("Object.defineProperty("); } } print("{").println().startIndent(); boolean statementPrinted = false; boolean initializationBlockFound = false; if (newClass.def != null) { for (JCTree m : newClass.def.getMembers()) { if (m instanceof JCBlock) { initializationBlockFound = true; List<VarSymbol> initializedVars = new ArrayList<>(); for (JCTree s : ((JCBlock) m).stats) { boolean currentStatementPrinted = false; if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCAssign) { JCAssign assignment = (JCAssign) ((JCExpressionStatement) s).expr; VarSymbol var = null; if (assignment.lhs instanceof JCFieldAccess) { var = Util.findFieldDeclaration(clazz, ((JCFieldAccess) assignment.lhs).name); printIndent().print(var.getSimpleName().toString()); } else if (assignment.lhs instanceof JCIdent) { var = Util.findFieldDeclaration(clazz, ((JCIdent) assignment.lhs).name); printIndent().print(assignment.lhs.toString()); } else { continue; } initializedVars.add(var); print(": ").print(assignment.rhs).print(",").println(); currentStatementPrinted = true; statementPrinted = true; } else if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCMethodInvocation) { JCMethodInvocation invocation = (JCMethodInvocation) ((JCExpressionStatement) s).expr; String meth = invocation.meth.toString(); if (meth.equals(JSweetConfig.INDEXED_SET_FUCTION_NAME) || (meth .equals(JSweetConfig.UTIL_CLASSNAME + "." + JSweetConfig.INDEXED_SET_FUCTION_NAME) || meth.equals(JSweetConfig.DEPRECATED_UTIL_CLASSNAME + "." + JSweetConfig.INDEXED_SET_FUCTION_NAME))) { if (invocation.getArguments().size() == 3) { if ("this".equals(invocation.getArguments().get(0).toString())) { printIndent().print(invocation.args.tail.head).print(": ") .print(invocation.args.tail.tail.head).print(",").println(); } currentStatementPrinted = true; statementPrinted = true; } else { printIndent().print(invocation.args.head).print(": ") .print(invocation.args.tail.head).print(",").println(); currentStatementPrinted = true; statementPrinted = true; } } } if (!currentStatementPrinted) { report(s, JSweetProblem.INVALID_INITIALIZER_STATEMENT); } } for (Symbol s : clazz.getEnclosedElements()) { if (s instanceof VarSymbol) { if (!initializedVars.contains(s)) { if (!context.hasAnnotationType(s, JSweetConfig.ANNOTATION_OPTIONAL)) { report(m, JSweetProblem.UNINITIALIZED_FIELD, s); } } } } if (statementPrinted) { removeLastChars(2); } } } } if (!statementPrinted && !initializationBlockFound) { for (Symbol s : clazz.getEnclosedElements()) { if (s instanceof VarSymbol) { if (!context.hasAnnotationType(s, JSweetConfig.ANNOTATION_OPTIONAL)) { report(newClass, JSweetProblem.UNINITIALIZED_FIELD, s); } } } } println().endIndent().printIndent().print("}"); if (getContext().options.isInterfaceTracking()) { if (!interfaces.isEmpty()) { print(", '" + INTERFACES_FIELD_NAME + "', { configurable: true, value: "); print("["); for (String i : interfaces) { print("\"").print(i).print("\","); } removeLastChar(); print("]"); print(" })"); } } } else { // ((target : DataStruct3) => { // target['i'] = 1; // target['s2'] = ""; // return target // })(new DataStruct3()); print("((target:").print(newClass.clazz).print(") => {").println().startIndent(); for (JCTree m : newClass.def.getMembers()) { if (m instanceof JCBlock) { for (JCTree s : ((JCBlock) m).stats) { boolean currentStatementPrinted = false; if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCAssign) { JCAssign assignment = (JCAssign) ((JCExpressionStatement) s).expr; VarSymbol var = null; if (assignment.lhs instanceof JCFieldAccess) { var = Util.findFieldDeclaration(clazz, ((JCFieldAccess) assignment.lhs).name); printIndent().print("target['").print(var.getSimpleName().toString()) .print("']"); } else if (assignment.lhs instanceof JCIdent) { printIndent().print("target['").print(assignment.lhs.toString()).print("']"); } else { continue; } print(" = ").print(assignment.rhs).print(";").println(); currentStatementPrinted = true; } else if (s instanceof JCExpressionStatement && ((JCExpressionStatement) s).expr instanceof JCMethodInvocation) { JCMethodInvocation invocation = (JCMethodInvocation) ((JCExpressionStatement) s).expr; String meth = invocation.meth.toString(); if (meth.equals(JSweetConfig.INDEXED_SET_FUCTION_NAME) || (meth.equals( JSweetConfig.UTIL_CLASSNAME + "." + JSweetConfig.INDEXED_SET_FUCTION_NAME) || meth.equals(JSweetConfig.DEPRECATED_UTIL_CLASSNAME + "." + JSweetConfig.INDEXED_SET_FUCTION_NAME))) { if (invocation.getArguments().size() == 3) { if ("this".equals(invocation.getArguments().get(0).toString())) { printIndent().print("target[").print(invocation.args.tail.head) .print("]").print(" = ").print(invocation.args.tail.tail.head) .print(";").println(); } currentStatementPrinted = true; } else { printIndent().print("target[").print(invocation.args.head).print("]") .print(" = ").print(invocation.args.tail.head).print(";").println(); currentStatementPrinted = true; } } } if (!currentStatementPrinted) { report(s, JSweetProblem.INVALID_INITIALIZER_STATEMENT); } } } } printIndent().print("return target;").println(); println().endIndent().printIndent().print("})("); print("new ").print(newClass.clazz).print("(").printArgList(null, newClass.args).print("))"); } } else { if (context.hasAnnotationType(newClass.clazz.type.tsym, JSweetConfig.ANNOTATION_OBJECT_TYPE)) { print("{}"); } else { if (!getAdapter().substituteNewClass(new NewClassElementSupport(newClass))) { String mappedType = context.getTypeMappingTarget(newClass.clazz.type.toString()); if (typeChecker.checkType(newClass, null, newClass.clazz)) { boolean applyVarargs = true; MethodSymbol methSym = (MethodSymbol) newClass.constructor; if (newClass.args.size() == 0 || !Util.hasVarargs(methSym) // || newClass.args.last().type.getKind() != TypeKind.ARRAY // we dont use apply if var args type differ || !context.types.erasure(((ArrayType) newClass.args.last().type).elemtype) .equals(context.types.erasure( ((ArrayType) methSym.getParameters().last().type).elemtype))) { applyVarargs = false; } if (applyVarargs) { // this is necessary in case the user defines a // Function class that hides the global Function // class context.addGlobalsMapping("Function", "__Function"); print("<any>new (__Function.prototype.bind.apply("); if (mappedType != null) { print(mapConstructorType(mappedType)); } else { print(newClass.clazz); } print(", [null"); for (int i = 0; i < newClass.args.length() - 1; i++) { print(", ").print(newClass.args.get(i)); } print("].concat(<any[]>").print(newClass.args.last()).print(")))"); } else { if (newClass.clazz instanceof JCTypeApply) { JCTypeApply typeApply = (JCTypeApply) newClass.clazz; mappedType = context.getTypeMappingTarget(typeApply.clazz.type.toString()); print("new "); if (mappedType != null) { print(mapConstructorType(mappedType)); } else { print(typeApply.clazz); } if (!typeApply.arguments.isEmpty()) { print("<").printTypeArgList(typeApply.arguments).print(">"); } else { // erase types since the diamond (<>) // operator // does not exists in TypeScript printAnyTypeArguments( ((ClassSymbol) newClass.clazz.type.tsym).getTypeParameters().length()); } print("(").printConstructorArgList(newClass, false).print(")"); } else { print("new "); if (mappedType != null) { print(mapConstructorType(mappedType)); } else { print(newClass.clazz); } print("(").printConstructorArgList(newClass, false).print(")"); } } } } } } }