2 * HTML via Java(tm) Language Bindings
3 * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. apidesign.org
13 * designates this particular file as subject to the
14 * "Classpath" exception as provided by apidesign.org
15 * in the License file that accompanied this code.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. Look for COPYING file in the top folder.
19 * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
21 package org.apidesign.html.boot.impl;
23 import org.apidesign.html.boot.spi.Fn;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.Reader;
28 import java.util.ArrayList;
29 import java.util.Enumeration;
30 import java.util.List;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33 import org.objectweb.asm.AnnotationVisitor;
34 import org.objectweb.asm.ClassReader;
35 import org.objectweb.asm.ClassVisitor;
36 import org.objectweb.asm.ClassWriter;
37 import org.objectweb.asm.Label;
38 import org.objectweb.asm.MethodVisitor;
39 import org.objectweb.asm.Opcodes;
40 import org.objectweb.asm.Type;
41 import org.objectweb.asm.signature.SignatureReader;
42 import org.objectweb.asm.signature.SignatureVisitor;
43 import org.objectweb.asm.signature.SignatureWriter;
47 * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
49 abstract class JsClassLoader extends ClassLoader {
50 JsClassLoader(ClassLoader parent) {
52 setDefaultAssertionStatus(JsClassLoader.class.desiredAssertionStatus());
56 protected abstract URL findResource(String name);
59 protected abstract Enumeration<URL> findResources(String name);
62 protected Class<?> findClass(String name) throws ClassNotFoundException {
63 if (name.startsWith("javafx")) {
64 return Class.forName(name);
66 if (name.startsWith("netscape")) {
67 return Class.forName(name);
69 if (name.startsWith("com.sun")) {
70 return Class.forName(name);
72 if (name.equals(JsClassLoader.class.getName())) {
73 return JsClassLoader.class;
75 if (name.equals(Fn.class.getName())) {
78 if (name.equals(FnUtils.class.getName())) {
81 URL u = findResource(name.replace('.', '/') + ".class");
83 InputStream is = null;
86 byte[] arr = new byte[is.available()];
88 while (len < arr.length) {
89 int read = is.read(arr, len, arr.length - len);
91 throw new IOException("Can't read " + u);
97 ClassReader cr = new ClassReader(arr);
98 FindInClass tst = new FindInClass(null);
101 ClassWriter w = new ClassWriterEx(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
102 FindInClass fic = new FindInClass(w);
104 arr = w.toByteArray();
107 return defineClass(name, arr, 0, arr.length);
109 } catch (IOException ex) {
110 throw new ClassNotFoundException("Can't load " + name, ex);
113 if (is != null) is.close();
114 } catch (IOException ex) {
115 throw new ClassNotFoundException(null, ex);
120 name.equals("org.apidesign.html.boot.spi.Fn") ||
121 name.equals("org.apidesign.html.boot.impl.FnUtils")
123 return Class.forName(name);
126 return super.findClass(name);
129 protected abstract Fn defineFn(String code, String... names);
130 protected abstract void loadScript(Reader code) throws Exception;
132 private final class FindInClass extends ClassVisitor {
136 public FindInClass(ClassVisitor cv) {
137 super(Opcodes.ASM4, cv);
141 public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
143 super.visit(version, access, name, signature, superName, interfaces);
147 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
148 if ("Lnet/java/html/js/JavaScriptResource;".equals(desc)) {
149 return new LoadResource();
151 return super.visitAnnotation(desc, visible);
156 public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
157 return new FindInMethod(access, name, desc,
158 super.visitMethod(access & (~Opcodes.ACC_NATIVE), name, desc, signature, exceptions)
162 private final class FindInMethod extends MethodVisitor {
163 private final String name;
164 private final String desc;
165 private final int access;
166 private List<String> args;
168 private boolean bodyGenerated;
170 public FindInMethod(int access, String name, String desc, MethodVisitor mv) {
171 super(Opcodes.ASM4, mv);
172 this.access = access;
178 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
180 "Lnet/java/html/js/JavaScriptBody;".equals(desc) // NOI18N
181 || "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;".equals(desc) // NOI18N
184 return new FindInAnno();
186 return super.visitAnnotation(desc, visible);
189 private void generateJSBody(List<String> args, String body) {
195 public void visitCode() {
202 private boolean generateBody() {
206 bodyGenerated = true;
208 super.visitFieldInsn(
209 Opcodes.GETSTATIC, FindInClass.this.name,
210 "$$fn$$" + name + "_" + found,
211 "Lorg/apidesign/html/boot/spi/Fn;"
213 super.visitInsn(Opcodes.DUP);
214 Label ifNotNull = new Label();
215 super.visitJumpInsn(Opcodes.IFNONNULL, ifNotNull);
218 super.visitInsn(Opcodes.POP);
219 super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
220 super.visitLdcInsn(body);
221 super.visitIntInsn(Opcodes.SIPUSH, args.size());
222 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
223 for (int i = 0; i < args.size(); i++) {
224 String name = args.get(i);
225 super.visitInsn(Opcodes.DUP);
226 super.visitIntInsn(Opcodes.BIPUSH, i);
227 super.visitLdcInsn(name);
228 super.visitInsn(Opcodes.AASTORE);
230 super.visitMethodInsn(Opcodes.INVOKESTATIC,
231 "org/apidesign/html/boot/impl/FnUtils", "define",
232 "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
236 super.visitLabel(ifNotNull);
239 if ((access & Opcodes.ACC_STATIC) == 0) {
241 super.visitIntInsn(Opcodes.ALOAD, 0);
244 super.visitInsn(Opcodes.ACONST_NULL);
247 super.visitIntInsn(Opcodes.SIPUSH, args.size());
248 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
250 class SV extends SignatureVisitor {
251 private boolean nowReturn;
252 private Type returnType;
260 public void visitBaseType(char descriptor) {
261 final Type t = Type.getType("" + descriptor);
266 FindInMethod.super.visitInsn(Opcodes.DUP);
267 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
268 FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), index + offset);
270 switch (descriptor) {
271 case 'I': factory = "java/lang/Integer"; break;
272 case 'J': factory = "java/lang/Long"; break;
273 case 'S': factory = "java/lang/Short"; break;
274 case 'F': factory = "java/lang/Float"; break;
275 case 'D': factory = "java/lang/Double"; break;
276 case 'Z': factory = "java/lang/Boolean"; break;
277 case 'C': factory = "java/lang/Character"; break;
278 case 'B': factory = "java/lang/Byte"; break;
279 default: throw new IllegalStateException(t.toString());
281 FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
282 factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
284 FindInMethod.super.visitInsn(Opcodes.AASTORE);
289 public SignatureVisitor visitArrayType() {
291 throw new IllegalStateException("Not supported yet");
294 return new SignatureWriter();
298 public void visitClassType(String name) {
300 returnType = Type.getObjectType(name);
307 public SignatureVisitor visitReturnType() {
312 private void loadObject() {
313 FindInMethod.super.visitInsn(Opcodes.DUP);
314 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
315 FindInMethod.super.visitVarInsn(Opcodes.ALOAD, index + offset);
316 FindInMethod.super.visitInsn(Opcodes.AASTORE);
322 SignatureReader sr = new SignatureReader(desc);
325 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
326 "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
328 switch (sv.returnType.getSort()) {
330 super.visitInsn(Opcodes.RETURN);
334 super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
335 super.visitInsn(Opcodes.ARETURN);
338 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean");
339 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
340 "java/lang/Boolean", "booleanValue", "()Z"
342 super.visitInsn(Opcodes.IRETURN);
345 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
346 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
347 "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
349 super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
355 public void visitEnd() {
358 if (generateBody()) {
360 super.visitMaxs(1, 0);
362 FindInClass.this.visitField(
363 Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
364 "$$fn$$" + name + "_" + found,
365 "Lorg/apidesign/html/boot/spi/Fn;",
375 private final class FindInAnno extends AnnotationVisitor {
376 private List<String> args = new ArrayList<String>();
378 private boolean javacall = false;
380 public FindInAnno() {
385 public void visit(String name, Object value) {
387 args.add((String) value);
390 if (name.equals("javacall")) { // NOI18N
391 javacall = (Boolean)value;
394 assert name.equals("body");
395 body = (String) value;
399 public AnnotationVisitor visitArray(String name) {
404 public void visitEnd() {
406 generateJSBody(args, javacall ?
407 FnUtils.callback(body, JsClassLoader.this) :
415 private final class LoadResource extends AnnotationVisitor {
416 public LoadResource() {
421 public void visit(String attrName, Object value) {
422 String relPath = (String) value;
423 if (relPath.startsWith("/")) {
424 FnUtils.loadScript(JsClassLoader.this, relPath);
426 int last = name.lastIndexOf('/');
427 String fullPath = name.substring(0, last + 1) + relPath;
428 FnUtils.loadScript(JsClassLoader.this, fullPath);
434 private class ClassWriterEx extends ClassWriter {
436 public ClassWriterEx(ClassReader classReader, int flags) {
437 super(classReader, flags);
441 protected String getCommonSuperClass(final String type1, final String type2) {
443 ClassLoader classLoader = JsClassLoader.this;
445 c = Class.forName(type1.replace('/', '.'), false, classLoader);
446 d = Class.forName(type2.replace('/', '.'), false, classLoader);
447 } catch (Exception e) {
448 throw new RuntimeException(e.toString());
450 if (c.isAssignableFrom(d)) {
453 if (d.isAssignableFrom(c)) {
456 if (c.isInterface() || d.isInterface()) {
457 return "java/lang/Object";
460 c = c.getSuperclass();
461 } while (!c.isAssignableFrom(d));
462 return c.getName().replace('.', '/');