/** Returns <code>true</code> if the rhs array type can be assigned to the lhs array type. */ private static boolean areArraysAssignable(JArrayType lhsType, JArrayType rhsType) { // areClassTypesAssignable should prevent us from getting here if the types // are referentially equal. assert (lhsType != rhsType); JType lhsComponentType = lhsType.getComponentType(); JType rhsComponentType = rhsType.getComponentType(); if (lhsComponentType.isPrimitive() != null || rhsComponentType.isPrimitive() != null) { /* * Arrays are referentially stable so there will only be one int[] no * matter how many times it is referenced in the code. So, if either * component type is a primitive then we know that we are not assignable. */ return false; } assert (lhsComponentType instanceof JClassType); assert (rhsComponentType instanceof JClassType); JClassType thisComponentClass = (JClassType) lhsComponentType; JClassType subtypeComponentClass = (JClassType) rhsComponentType; return areClassTypesAssignable(thisComponentClass, subtypeComponentClass); }
/** * Adds the given parameter to this JConstructor's list of parameters. * * @param parameter The parameter to add to the this JConstructor's list of parameters. */ public void addParameter(final JParameter parameter) { if (parameter == null) { return; } // -- check current params if (_params.get(parameter.getName()) != null) { StringBuilder err = new StringBuilder(64); err.append("A parameter already exists for the constructor, "); err.append(this._declaringClass.getName()); err.append(", with the name: "); err.append(parameter.getName()); throw new IllegalArgumentException(err.toString()); } _params.put(parameter.getName(), parameter); // -- be considerate and add the class name to the // -- declaring class's list of imports if (_declaringClass != null) { JType jType = parameter.getType(); if (!jType.isPrimitive()) { _declaringClass.addImport(jType.getName()); } } }
public void addMethod(JMethod jMethod) throws IllegalArgumentException { if (jMethod == null) { throw new IllegalArgumentException("Class methods cannot be null"); } // -- check method name and signatures *add later* // -- keep method list sorted for esthetics when printing // -- START SORT :-) boolean added = false; short modifierVal = 0; JModifiers modifiers = jMethod.getModifiers(); for (int i = 0; i < methods.size(); i++) { JMethod tmp = (JMethod) methods.elementAt(i); // -- first compare modifiers if (tmp.getModifiers().isPrivate()) { if (!modifiers.isPrivate()) { methods.insertElementAt(jMethod, i); added = true; break; } } // -- compare names if (jMethod.getName().compareTo(tmp.getName()) < 0) { methods.insertElementAt(jMethod, i); added = true; break; } } // -- END SORT if (!added) methods.addElement(jMethod); // -- check parameter packages to make sure we have them // -- in our import list String[] pkgNames = jMethod.getParameterClassNames(); for (int i = 0; i < pkgNames.length; i++) { addImport(pkgNames[i]); } // -- check return type to make sure it's included in the // -- import list JType jType = jMethod.getReturnType(); if (jType != null) { while (jType.isArray()) jType = jType.getComponentType(); if (!jType.isPrimitive()) addImport(((JClass) jType).getName()); } // -- check exceptions JClass[] exceptions = jMethod.getExceptions(); for (int i = 0; i < exceptions.length; i++) { addImport(exceptions[i].getName()); } } // -- addMethod
/** * If the type is a JSO or an array of JSOs it returns cggcc.JavaScriptObject or an array of * cggcc.JavaScriptObject respectively; otherwise returns {@code type}. */ public JType normalizeJsoType(JType type) { type = type.getUnderlyingType(); if (type instanceof JArrayType) { return getOrCreateArrayType( normalizeJsoType(((JArrayType) type).getLeafType()), ((JArrayType) type).getDims()); } if (type.isJsoType()) { return getJavaScriptObject(); } return type; }
private void emitBody(SourceWriter w) throws NotFoundException { JClassType baseClass = context_.getTypeOracle().getType("org.rstudio.core.client.js.JsObjectInjector"); JClassType c = baseType_.asParameterizationOf(baseClass.isGenericType()); JType typeToInject = c.isParameterized().getTypeArgs()[0]; w.print("public native final void injectObject("); w.print(typeToInject.getQualifiedSourceName()); w.println(" value) /*-{"); w.indent(); w.println(baseExpression_ + " = {"); w.indent(); JMethod[] methods = typeToInject.isClassOrInterface().getMethods(); for (int i = 0; i < methods.length; i++) { JMethod method = methods[i]; final JParameter[] jParameters = method.getParameters(); StringBuilder argString = new StringBuilder(); for (int j = 0; j < jParameters.length; j++) { argString.append("_").append(j); if (j < jParameters.length - 1) argString.append(", "); } w.println(method.getName() + ": function(" + argString + ") {"); w.indent(); if (!method.getReturnType().getQualifiedSourceName().equals("void")) w.print("return "); w.print("value.@"); w.print(typeToInject.getQualifiedSourceName()); w.print("::"); w.print(method.getName()); w.print("("); for (JParameter param : jParameters) w.print(param.getType().getJNISignature()); w.print(")("); w.print(argString.toString()); w.println(");"); w.outdent(); w.print("}"); w.println((i < methods.length - 1) ? "," : ""); } w.outdent(); w.println("};"); w.outdent(); w.println("}-*/;"); }
public static String getJsniSig(JMethod method, boolean addReturnType) { StringBuilder sb = new StringBuilder(); sb.append(method.getName()); sb.append("("); for (int i = 0; i < method.getOriginalParamTypes().size(); ++i) { JType type = method.getOriginalParamTypes().get(i); sb.append(type.getJsniSignatureName()); } sb.append(")"); if (addReturnType) { sb.append(method.getOriginalReturnType().getJsniSignatureName()); } return sb.toString(); }
protected String toStringExpression(JType type, String expr) { if (type.isPrimitive() != null) { return "\"\"+" + expr; } if (STRING_TYPE == type) { return expr; } if (type.isClass() != null && isOverlayArrayType(type.isClass())) { return "(new " + JSON_ARRAY_CLASS + "(" + expr + ")).toString()"; } if (type.isClass() != null && OVERLAY_VALUE_TYPE.isAssignableFrom(type.isClass())) { return "(new " + JSON_OBJECT_CLASS + "(" + expr + ")).toString()"; } return String.format("(%s != null ? %s.toString() : null)", expr, expr); }
/** * Adds the given JMethodSignature to this JClass * * @param jMethodSig the JMethodSignature to add. * @throws java.lang.IllegalArgumentException when the given JMethodSignature conflicts with an * existing method signature. */ public void addMethod(JMethodSignature jMethodSig) throws IllegalArgumentException { if (jMethodSig == null) { String err = "The JMethodSignature cannot be null."; throw new IllegalArgumentException(err); } // -- check method name and signatures *add later* // -- keep method list sorted for esthetics when printing // -- START SORT :-) boolean added = false; // short modifierVal = 0; JModifiers modifiers = jMethodSig.getModifiers(); for (int i = 0; i < methods.size(); i++) { JMethodSignature tmp = (JMethodSignature) methods.elementAt(i); // -- first compare modifiers if (tmp.getModifiers().isProtected()) { if (!modifiers.isProtected()) { methods.insertElementAt(jMethodSig, i); added = true; break; } } // -- compare names if (jMethodSig.getName().compareTo(tmp.getName()) < 0) { methods.insertElementAt(jMethodSig, i); added = true; break; } } // -- END SORT if (!added) methods.addElement(jMethodSig); // -- check return type to make sure it's included in the // -- import list JType jType = jMethodSig.getReturnType(); if (jType != null) { while (jType.isArray()) jType = jType.getComponentType(); if (!jType.isPrimitive()) addImport(jType.getName()); } // -- check exceptions JClass[] exceptions = jMethodSig.getExceptions(); for (JClass exception : exceptions) { addImport(exception.getName()); } } // -- addMethod
// Local variables // FIXME : find a better management method for local variables public JLocalVariable addNewLocalVariable(JType type, String name) { assert !frozen; JLocalVariable var = context.JLocalVariable(this, type, name, localVariableIndex); localVariableIndex += type.getSize(); localVariables.add(var); return var; }
protected String toFormStringExpression(JParameter argument, Style classStyle) throws UnableToCompleteException { JType type = argument.getType(); String expr = argument.getName(); if (type.isPrimitive() != null) { return "\"\"+" + expr; } if (STRING_TYPE == type) { return expr; } if (type.isClass() != null && isOverlayArrayType(type.isClass())) { return "(new " + JSON_ARRAY_CLASS + "(" + expr + ")).toString()"; } if (type.isClass() != null && OVERLAY_VALUE_TYPE.isAssignableFrom(type.isClass())) { return "(new " + JSON_OBJECT_CLASS + "(" + expr + ")).toString()"; } if (type.getQualifiedBinaryName().startsWith("java.lang.")) { return String.format("(%s != null ? %s.toString() : null)", expr, expr); } Json jsonAnnotation = argument.getAnnotation(Json.class); final Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle; return locator.encodeExpression(type, expr, style) + ".toString()"; }
public void addMember(JMember jMember) throws IllegalArgumentException { if (jMember == null) { throw new IllegalArgumentException("Class members cannot be null"); } if (members.get(jMember.getName()) != null) { String err = "duplicate name found: " + jMember.getName(); throw new IllegalArgumentException(err); } members.put(jMember.getName(), jMember); // if member is of a type not imported by this class // then add import JType type = jMember.getType(); while (type.isArray()) type = type.getComponentType(); if (!type.isPrimitive()) { addImport(((JClass) type).getName()); } } // -- addMember
public Collection<JType> getSubclasses(JType type) { return Collections2.transform( typeOracle.getSubTypeNames(type.getName()), new Function<String, JType>() { @Override public JType apply(String typeName) { return getFromTypeMap(typeName); } }); }
private String getGenericType(JType jType) { if (jType.erasure().name().equals("List")) { final String typeName = jType.fullName(); int start = 0; int end = typeName.length(); for (int i = 0; i < typeName.length(); ++i) { switch (typeName.charAt(i)) { case '<': start = i; break; case '>': end = i; break; } } // plus one for excluding '<' return typeName.substring(start + 1, end); } return jType.erasure().name(); }
/** * Obtains a type object from a type name. * * <p>This method handles primitive types, arrays, and existing {@link Class}es. * * @exception ClassNotFoundException If the specified type is not found. */ public JType parseType(String name) throws ClassNotFoundException { // array if (name.endsWith("[]")) return parseType(name.substring(0, name.length() - 2)).array(); // try primitive type try { return JType.parse(this, name); } catch (IllegalArgumentException e) {; } // existing class return new TypeNameParser(name).parseTypeName(); }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == JAnnotationWriter.class) { try { return method.invoke(this, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } String name = method.getName(); Object arg = null; if (args != null && args.length > 0) arg = args[0]; // check how it's defined on the annotation Method m = annotation.getDeclaredMethod(name); Class<?> rt = m.getReturnType(); // array value if (rt.isArray()) { return addArrayValue(proxy, name, rt.getComponentType(), method.getReturnType(), arg); } // sub annotation if (Annotation.class.isAssignableFrom(rt)) { Class<? extends Annotation> r = (Class<? extends Annotation>) rt; return new TypedAnnotationWriter(r, method.getReturnType(), use.annotationParam(name, r)) .createProxy(); } // scalar value if (arg instanceof JType) { JType targ = (JType) arg; checkType(Class.class, rt); if (m.getDefaultValue() != null) { // check the default if (targ.equals(targ.owner().ref((Class) m.getDefaultValue()))) return proxy; // defaulted } use.param(name, targ); return proxy; } // other Java built-in types checkType(arg.getClass(), rt); if (m.getDefaultValue() != null && m.getDefaultValue().equals(arg)) // defaulted. no need to write out. return proxy; if (arg instanceof String) { use.param(name, (String) arg); return proxy; } if (arg instanceof Boolean) { use.param(name, (Boolean) arg); return proxy; } if (arg instanceof Integer) { use.param(name, (Integer) arg); return proxy; } if (arg instanceof Class) { use.param(name, (Class) arg); return proxy; } if (arg instanceof Enum) { use.param(name, (Enum) arg); return proxy; } throw new IllegalArgumentException("Unable to handle this method call " + method.toString()); }
public JField getClassLiteralField(JType type) { return classLiteralFieldsByType.get(type.isJsoType() ? getJavaScriptObject() : type); }
private void buildMethodInterceptor( JDefinedClass definedClass, ConstructorInjectionPoint proxyConstructorInjectionPoint, JMethod constructor, JBlock constructorBody, Map<ASTMethod, Map<InjectionNode, JFieldVar>> interceptorFields, Map.Entry<ASTMethod, Set<InjectionNode>> methodInterceptorEntry) throws ClassNotFoundException { ASTMethod method = methodInterceptorEntry.getKey(); if (method.getAccessModifier().equals(ASTAccessModifier.PRIVATE)) { throw new TransfuseAnalysisException("Unable to provide AOP on private methods"); } if (!interceptorFields.containsKey(methodInterceptorEntry.getKey())) { interceptorFields.put( methodInterceptorEntry.getKey(), new HashMap<InjectionNode, JFieldVar>()); } Map<InjectionNode, JFieldVar> injectionNodeInstanceNameMap = interceptorFields.get(methodInterceptorEntry.getKey()); // setup interceptor fields for (InjectionNode interceptorInjectionNode : methodInterceptorEntry.getValue()) { String interceptorInstanceName = namer.generateName(interceptorInjectionNode); JFieldVar interceptorField = definedClass.field( JMod.PRIVATE, codeModel.ref(interceptorInjectionNode.getClassName()), interceptorInstanceName); injectionNodeInstanceNameMap.put(interceptorInjectionNode, interceptorField); JVar interceptorParam = constructor.param( codeModel.ref(interceptorInjectionNode.getClassName()), namer.generateName(interceptorInjectionNode)); constructorBody.assign(interceptorField, interceptorParam); proxyConstructorInjectionPoint.addInjectionNode(interceptorInjectionNode); } JType returnType = codeModel.parseType(method.getReturnType().getName()); JMethod methodDeclaration = definedClass.method( method.getAccessModifier().getCodeModelJMod(), returnType, method.getName()); JBlock body = methodDeclaration.body(); // define method parameter Map<ASTParameter, JVar> parameterMap = new HashMap<ASTParameter, JVar>(); for (ASTParameter parameter : method.getParameters()) { parameterMap.put( parameter, methodDeclaration.param( JMod.FINAL, codeModel.ref(parameter.getASTType().getName()), namer.generateName(parameter.getASTType()))); } // aop interceptor Map<InjectionNode, JFieldVar> interceptorNameMap = interceptorFields.get(methodInterceptorEntry.getKey()); JArray paramArray = JExpr.newArray(codeModel.ref(Object.class)); for (ASTParameter astParameter : method.getParameters()) { paramArray.add(parameterMap.get(astParameter)); } JInvocation interceptorInvocation = buildInterceptorChain( definedClass, method, parameterMap, methodInterceptorEntry.getValue(), interceptorNameMap) .invoke("invoke"); interceptorInvocation.arg(paramArray); if (method.getReturnType().equals(ASTVoidType.VOID)) { body.add(interceptorInvocation); } else { body._return(JExpr.cast(returnType.boxify(), interceptorInvocation)); } }
public boolean isJavaLangObject(JType type) { assert type != null; return type.getUnderlyingType() == typeJavaLangObject; }
@Override public String getJsniSignatureName() { return "[" + elementType.getJsniSignatureName(); }
public JType _ref(Class c) { if (c.isPrimitive()) return JType.parse(this, c.getName()); else return ref(c); }
public boolean isJavaLangString(JType type) { assert type != null; return type.getUnderlyingType() == typeString; }
public JPrimitiveType getPrimitiveType() { Class v = boxToPrimitive.get(_class); if (v != null) return JType.parse(JCodeModel.this, v.getName()); else return null; }
/** * Prints the source code for this JInterface to the given JSourceWriter * * @param jsw the JSourceWriter to print to. [May not be null] */ public void print(JSourceWriter jsw, boolean classOnly) { if (jsw == null) { throw new IllegalArgumentException("argument 'jsw' should not be null."); } StringBuilder buffer = new StringBuilder(); if (!classOnly) { printHeader(jsw); printPackageDeclaration(jsw); printImportDeclarations(jsw); } // ------------/ // - Java Doc -/ // ------------/ getJDocComment().print(jsw); JAnnotations annotations = getAnnotations(); if (annotations != null) annotations.print(jsw); // -- print class information // -- we need to add some JavaDoc API adding comments buffer.setLength(0); JModifiers modifiers = getModifiers(); if (modifiers.isPrivate()) { buffer.append("private "); } else if (modifiers.isPublic()) { buffer.append("public "); } if (modifiers.isAbstract()) { buffer.append("abstract "); } buffer.append("interface "); buffer.append(getLocalName()); jsw.writeln(buffer.toString()); buffer.setLength(0); jsw.indent(); if (getInterfaceCount() > 0) { Enumeration<String> e = getInterfaces(); buffer.append("extends "); while (e.hasMoreElements()) { buffer.append(e.nextElement()); if (e.hasMoreElements()) buffer.append(", "); } jsw.writeln(buffer.toString()); buffer.setLength(0); } jsw.unindent(); jsw.writeln('{'); jsw.indent(); // -- declare static members if (fields != null) { if (fields.size() > 0) { jsw.writeln(); jsw.writeln(" //--------------------------/"); jsw.writeln(" //- Class/Member Variables -/"); jsw.writeln("//--------------------------/"); jsw.writeln(); } for (int i = 0; i < fields.size(); i++) { JField jField = (JField) fields.get(i); // -- print Java comment JDocComment comment = jField.getComment(); if (comment != null) comment.print(jsw); // -- print member jsw.write(jField.getModifiers().toString()); jsw.write(' '); JType type = jField.getType(); String typeName = type.toString(); // -- for esthetics use short name in some cases if (typeName.equals(toString())) { typeName = type.getLocalName(); } jsw.write(typeName); jsw.write(' '); jsw.write(jField.getName()); String init = jField.getInitString(); if (init != null) { jsw.write(" = "); jsw.write(init); } jsw.writeln(';'); jsw.writeln(); } } // -- print method signatures if (methods.size() > 0) { jsw.writeln(); jsw.writeln(" //-----------/"); jsw.writeln(" //- Methods -/"); jsw.writeln("//-----------/"); jsw.writeln(); } for (int i = 0; i < methods.size(); i++) { JMethodSignature signature = (JMethodSignature) methods.elementAt(i); signature.print(jsw); jsw.writeln(';'); } for (String sourceCodeEntry : sourceCodeEntries) { jsw.writeln(sourceCodeEntry); } jsw.unindent(); jsw.writeln('}'); jsw.flush(); jsw.close(); } // -- printSource
@Override public String getJavahSignatureName() { return "_3" + elementType.getJavahSignatureName(); }
/** Resolves external references during AST stitching. */ public void resolve(List<JInterfaceType> resolvedInterfaces, List<JNode> resolvedRescues) { assert JType.replaces(resolvedInterfaces, superInterfaces); superInterfaces = Lists.normalize(resolvedInterfaces); assert JNameOf.replacesNamedElements(resolvedRescues, artificialRescues); artificialRescues = Lists.normalize(resolvedRescues); }
@Override public boolean replaces(JType originalType) { return (originalType instanceof JArrayType) && elementType.replaces(((JArrayType) originalType).getElementType()); }
public JArrayType(JType elementType) { super( elementType.getSourceInfo().makeChild(SourceOrigin.UNKNOWN), elementType.getName() + "[]"); assert !(elementType instanceof JNonNullType); this.elementType = elementType; }
/** * Prints the source code for this JClass * * @param lineSeparator the line separator to use at the end of each line. If null, then the * default line separator for the runtime platform will be used. */ public void print(String lineSeparator) { // -- open output file String name = getLocalName(); String filename = name + ".java"; if ((packageName != null) && (packageName.length() > 0)) { String path = packageName.replace('.', File.separatorChar); File pathFile = new File(path); if (!pathFile.exists()) { pathFile.mkdirs(); } filename = path + File.separator + filename; } File file = new File(filename); JSourceWriter jsw = null; try { jsw = new JSourceWriter(new FileWriter(file)); } catch (java.io.IOException ioe) { System.out.println("unable to create class file: " + filename); return; } if (lineSeparator == null) { lineSeparator = System.getProperty("line.separator"); } jsw.setLineSeparator(lineSeparator); StringBuffer buffer = new StringBuffer(); // -- write class header if (header != null) header.print(jsw); else { jsw.writeln("/*"); jsw.writeln(" * " + DEFAULT_HEADER); jsw.writeln("*/"); } jsw.writeln(); jsw.flush(); // -- print package name if ((packageName != null) && (packageName.length() > 0)) { buffer.setLength(0); buffer.append("package "); buffer.append(packageName); buffer.append(';'); jsw.writeln(buffer.toString()); jsw.writeln(); } // -- print imports jsw.writeln(" //---------------------------------/"); jsw.writeln(" //- Imported classes and packages -/"); jsw.writeln("//---------------------------------/"); jsw.writeln(); for (int i = 0; i < imports.size(); i++) { jsw.write("import "); jsw.write(imports.elementAt(i)); jsw.writeln(';'); } jsw.writeln(); // ------------/ // - Java Doc -/ // ------------/ jdc.print(jsw); // -- print class information // -- we need to add some JavaDoc API adding comments buffer.setLength(0); if (modifiers.isPrivate()) { buffer.append("private "); } else if (modifiers.isPublic()) { buffer.append("public "); } if (modifiers.isAbstract()) { buffer.append("abstract "); } buffer.append("class "); buffer.append(getLocalName()); buffer.append(' '); if (superClass != null) { buffer.append("extends "); buffer.append(superClass); buffer.append(' '); } if (interfaces.size() > 0) { int iSize = interfaces.size(); boolean endl = false; if ((iSize > 1) || (superClass != null)) { jsw.writeln(buffer.toString()); buffer.setLength(0); endl = true; } buffer.append("implements "); for (int i = 0; i < iSize; i++) { if (i > 0) buffer.append(", "); buffer.append(interfaces.elementAt(i)); } if (endl) { jsw.writeln(buffer.toString()); buffer.setLength(0); } else buffer.append(' '); } buffer.append('{'); jsw.writeln(buffer.toString()); buffer.setLength(0); jsw.writeln(); jsw.indent(); // -- declare members if (members.size() > 0) { jsw.writeln(); jsw.writeln(" //--------------------/"); jsw.writeln(" //- Member Variables -/"); jsw.writeln("//--------------------/"); jsw.writeln(); } for (int i = 0; i < members.size(); i++) { JMember jMember = (JMember) members.get(i); // -- print Java comment JDocComment comment = jMember.getComment(); if (comment != null) comment.print(jsw); // -- print member jsw.write(jMember.getModifiers().toString()); jsw.write(' '); JType type = jMember.getType(); String typeName = type.toString(); // -- for esthetics use short name in some cases if (typeName.equals(toString())) { typeName = type.getLocalName(); } jsw.write(typeName); jsw.write(' '); jsw.write(jMember.getName()); String init = jMember.getInitString(); if (init != null) { jsw.write(" = "); jsw.write(init); } jsw.writeln(';'); jsw.writeln(); } // -- print constructors if (constructors.size() > 0) { jsw.writeln(); jsw.writeln(" //----------------/"); jsw.writeln(" //- Constructors -/"); jsw.writeln("//----------------/"); jsw.writeln(); } for (int i = 0; i < constructors.size(); i++) { JConstructor jConstructor = (JConstructor) constructors.elementAt(i); jConstructor.print(jsw); jsw.writeln(); } // -- print methods if (methods.size() > 0) { jsw.writeln(); jsw.writeln(" //-----------/"); jsw.writeln(" //- Methods -/"); jsw.writeln("//-----------/"); jsw.writeln(); } for (int i = 0; i < methods.size(); i++) { JMethod jMethod = (JMethod) methods.elementAt(i); jMethod.print(jsw); jsw.writeln(); } jsw.unindent(); jsw.writeln('}'); jsw.flush(); jsw.close(); } // -- printSource
public String getClassLiteralName(JType type) { return type.getJavahSignatureName() + "_classLit"; }
@Override public boolean isFinal() { return elementType.isFinal(); }