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 org.objectweb.asm.AnnotationVisitor;
32 import org.objectweb.asm.ClassReader;
33 import org.objectweb.asm.ClassVisitor;
34 import org.objectweb.asm.ClassWriter;
35 import org.objectweb.asm.Label;
36 import org.objectweb.asm.MethodVisitor;
37 import org.objectweb.asm.Opcodes;
38 import org.objectweb.asm.Type;
39 import org.objectweb.asm.signature.SignatureReader;
40 import org.objectweb.asm.signature.SignatureVisitor;
41 import org.objectweb.asm.signature.SignatureWriter;
45 * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
47 abstract class JsClassLoader extends ClassLoader {
48 JsClassLoader(ClassLoader parent) {
50 setDefaultAssertionStatus(JsClassLoader.class.desiredAssertionStatus());
54 protected abstract URL findResource(String name);
57 protected abstract Enumeration<URL> findResources(String name);
60 protected Class<?> findClass(String name) throws ClassNotFoundException {
61 if (name.startsWith("javafx")) {
62 return Class.forName(name);
64 if (name.startsWith("netscape")) {
65 return Class.forName(name);
67 if (name.startsWith("com.sun")) {
68 return Class.forName(name);
70 if (name.equals(JsClassLoader.class.getName())) {
71 return JsClassLoader.class;
73 if (name.equals(Fn.class.getName())) {
76 if (name.equals(FnUtils.class.getName())) {
79 URL u = findResource(name.replace('.', '/') + ".class");
81 InputStream is = null;
84 byte[] arr = new byte[is.available()];
86 while (len < arr.length) {
87 int read = is.read(arr, len, arr.length - len);
89 throw new IOException("Can't read " + u);
95 ClassReader cr = new ClassReader(arr);
96 FindInClass tst = new FindInClass(null);
99 ClassWriter w = new ClassWriterEx(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
100 FindInClass fic = new FindInClass(w);
102 arr = w.toByteArray();
105 return defineClass(name, arr, 0, arr.length);
107 } catch (IOException ex) {
108 throw new ClassNotFoundException("Can't load " + name, ex);
111 if (is != null) is.close();
112 } catch (IOException ex) {
113 throw new ClassNotFoundException(null, ex);
118 name.equals("org.apidesign.html.boot.spi.Fn") ||
119 name.equals("org.apidesign.html.boot.impl.FnUtils")
121 return Class.forName(name);
124 return super.findClass(name);
127 protected abstract Fn defineFn(String code, String... names);
128 protected abstract void loadScript(Reader code) throws Exception;
130 private final class FindInClass extends ClassVisitor {
134 public FindInClass(ClassVisitor cv) {
135 super(Opcodes.ASM4, cv);
139 public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
141 super.visit(version, access, name, signature, superName, interfaces);
145 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
146 if ("Lnet/java/html/js/JavaScriptResource;".equals(desc)) {
147 return new LoadResource();
149 return super.visitAnnotation(desc, visible);
154 public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
155 return new FindInMethod(access, name, desc,
156 super.visitMethod(access & (~Opcodes.ACC_NATIVE), name, desc, signature, exceptions)
160 private final class FindInMethod extends MethodVisitor {
161 private final String name;
162 private final String desc;
163 private final int access;
164 private List<String> args;
166 private boolean bodyGenerated;
168 public FindInMethod(int access, String name, String desc, MethodVisitor mv) {
169 super(Opcodes.ASM4, mv);
170 this.access = access;
176 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
178 "Lnet/java/html/js/JavaScriptBody;".equals(desc) // NOI18N
179 || "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;".equals(desc) // NOI18N
182 return new FindInAnno();
184 return super.visitAnnotation(desc, visible);
187 private void generateJSBody(List<String> args, String body) {
193 public void visitCode() {
200 private boolean generateBody() {
204 bodyGenerated = true;
206 super.visitFieldInsn(
207 Opcodes.GETSTATIC, FindInClass.this.name,
208 "$$fn$$" + name + "_" + found,
209 "Lorg/apidesign/html/boot/spi/Fn;"
211 super.visitInsn(Opcodes.DUP);
212 Label ifNotNull = new Label();
213 super.visitJumpInsn(Opcodes.IFNONNULL, ifNotNull);
216 super.visitInsn(Opcodes.POP);
217 super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
218 super.visitLdcInsn(body);
219 super.visitIntInsn(Opcodes.SIPUSH, args.size());
220 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
221 boolean needsVM = false;
222 for (int i = 0; i < args.size(); i++) {
224 String argName = args.get(i);
225 needsVM = "vm".equals(argName);
226 super.visitInsn(Opcodes.DUP);
227 super.visitIntInsn(Opcodes.BIPUSH, i);
228 super.visitLdcInsn(argName);
229 super.visitInsn(Opcodes.AASTORE);
231 super.visitMethodInsn(Opcodes.INVOKESTATIC,
232 "org/apidesign/html/boot/impl/FnUtils", "define",
233 "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
235 super.visitInsn(Opcodes.DUP);
236 super.visitFieldInsn(
237 Opcodes.PUTSTATIC, FindInClass.this.name,
238 "$$fn$$" + name + "_" + found,
239 "Lorg/apidesign/html/boot/spi/Fn;"
243 super.visitLabel(ifNotNull);
246 if ((access & Opcodes.ACC_STATIC) == 0) {
248 super.visitIntInsn(Opcodes.ALOAD, 0);
251 super.visitInsn(Opcodes.ACONST_NULL);
254 super.visitIntInsn(Opcodes.SIPUSH, args.size());
255 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
257 class SV extends SignatureVisitor {
258 private boolean nowReturn;
259 private Type returnType;
261 private int loadIndex = offset;
268 public void visitBaseType(char descriptor) {
269 final Type t = Type.getType("" + descriptor);
274 FindInMethod.super.visitInsn(Opcodes.DUP);
275 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
276 FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), loadIndex++);
278 switch (descriptor) {
279 case 'I': factory = "java/lang/Integer"; break;
280 case 'J': factory = "java/lang/Long"; loadIndex++; break;
281 case 'S': factory = "java/lang/Short"; break;
282 case 'F': factory = "java/lang/Float"; break;
283 case 'D': factory = "java/lang/Double"; loadIndex++; break;
284 case 'Z': factory = "java/lang/Boolean"; break;
285 case 'C': factory = "java/lang/Character"; break;
286 case 'B': factory = "java/lang/Byte"; break;
287 default: throw new IllegalStateException(t.toString());
289 FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
290 factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
292 FindInMethod.super.visitInsn(Opcodes.AASTORE);
296 public SignatureVisitor visitArrayType() {
298 throw new IllegalStateException("Not supported yet");
301 return new SignatureWriter();
305 public void visitClassType(String name) {
307 returnType = Type.getObjectType(name);
314 public SignatureVisitor visitReturnType() {
319 private void loadObject() {
320 FindInMethod.super.visitInsn(Opcodes.DUP);
321 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
322 FindInMethod.super.visitVarInsn(Opcodes.ALOAD, loadIndex++);
323 FindInMethod.super.visitInsn(Opcodes.AASTORE);
328 SignatureReader sr = new SignatureReader(desc);
332 FindInMethod.super.visitInsn(Opcodes.DUP);
333 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, sv.index);
334 int lastSlash = FindInClass.this.name.lastIndexOf('/');
335 String jsCallbacks = FindInClass.this.name.substring(0, lastSlash + 1) + "$JsCallbacks$";
336 FindInMethod.super.visitFieldInsn(Opcodes.GETSTATIC, jsCallbacks, "VM", "L" + jsCallbacks + ";");
337 FindInMethod.super.visitInsn(Opcodes.AASTORE);
340 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
341 "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
343 switch (sv.returnType.getSort()) {
345 super.visitInsn(Opcodes.RETURN);
349 super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
350 super.visitInsn(Opcodes.ARETURN);
353 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean");
354 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
355 "java/lang/Boolean", "booleanValue", "()Z"
357 super.visitInsn(Opcodes.IRETURN);
360 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
361 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
362 "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
364 super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
370 public void visitEnd() {
373 if (generateBody()) {
375 super.visitMaxs(1, 0);
377 FindInClass.this.visitField(
378 Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
379 "$$fn$$" + name + "_" + found,
380 "Lorg/apidesign/html/boot/spi/Fn;",
390 private final class FindInAnno extends AnnotationVisitor {
391 private List<String> args = new ArrayList<String>();
393 private boolean javacall = false;
395 public FindInAnno() {
400 public void visit(String name, Object value) {
402 args.add((String) value);
405 if (name.equals("javacall")) { // NOI18N
406 javacall = (Boolean)value;
409 assert name.equals("body");
410 body = (String) value;
414 public AnnotationVisitor visitArray(String name) {
419 public void visitEnd() {
422 body = FnUtils.callback(body);
425 generateJSBody(args, body);
431 private final class LoadResource extends AnnotationVisitor {
432 public LoadResource() {
437 public void visit(String attrName, Object value) {
438 String relPath = (String) value;
439 if (relPath.startsWith("/")) {
440 FnUtils.loadScript(JsClassLoader.this, relPath);
442 int last = name.lastIndexOf('/');
443 String fullPath = name.substring(0, last + 1) + relPath;
444 FnUtils.loadScript(JsClassLoader.this, fullPath);
450 private class ClassWriterEx extends ClassWriter {
452 public ClassWriterEx(ClassReader classReader, int flags) {
453 super(classReader, flags);
457 protected String getCommonSuperClass(final String type1, final String type2) {
459 ClassLoader classLoader = JsClassLoader.this;
461 c = Class.forName(type1.replace('/', '.'), false, classLoader);
462 d = Class.forName(type2.replace('/', '.'), false, classLoader);
463 } catch (Exception e) {
464 throw new RuntimeException(e.toString());
466 if (c.isAssignableFrom(d)) {
469 if (d.isAssignableFrom(c)) {
472 if (c.isInterface() || d.isInterface()) {
473 return "java/lang/Object";
476 c = c.getSuperclass();
477 } while (!c.isAssignableFrom(d));
478 return c.getName().replace('.', '/');