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;"
237 super.visitLabel(ifNotNull);
240 if ((access & Opcodes.ACC_STATIC) == 0) {
242 super.visitIntInsn(Opcodes.ALOAD, 0);
245 super.visitInsn(Opcodes.ACONST_NULL);
248 super.visitIntInsn(Opcodes.SIPUSH, args.size());
249 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
251 class SV extends SignatureVisitor {
252 private boolean nowReturn;
253 private Type returnType;
261 public void visitBaseType(char descriptor) {
262 final Type t = Type.getType("" + descriptor);
267 FindInMethod.super.visitInsn(Opcodes.DUP);
268 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
269 FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), index + offset);
271 switch (descriptor) {
272 case 'I': factory = "java/lang/Integer"; break;
273 case 'J': factory = "java/lang/Long"; break;
274 case 'S': factory = "java/lang/Short"; break;
275 case 'F': factory = "java/lang/Float"; break;
276 case 'D': factory = "java/lang/Double"; break;
277 case 'Z': factory = "java/lang/Boolean"; break;
278 case 'C': factory = "java/lang/Character"; break;
279 case 'B': factory = "java/lang/Byte"; break;
280 default: throw new IllegalStateException(t.toString());
282 FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
283 factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
285 FindInMethod.super.visitInsn(Opcodes.AASTORE);
290 public SignatureVisitor visitArrayType() {
292 throw new IllegalStateException("Not supported yet");
295 return new SignatureWriter();
299 public void visitClassType(String name) {
301 returnType = Type.getObjectType(name);
308 public SignatureVisitor visitReturnType() {
313 private void loadObject() {
314 FindInMethod.super.visitInsn(Opcodes.DUP);
315 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index);
316 FindInMethod.super.visitVarInsn(Opcodes.ALOAD, index + offset);
317 FindInMethod.super.visitInsn(Opcodes.AASTORE);
323 SignatureReader sr = new SignatureReader(desc);
327 FindInMethod.super.visitInsn(Opcodes.DUP);
328 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, sv.index);
329 int lastSlash = FindInClass.this.name.lastIndexOf('/');
330 String jsCallbacks = FindInClass.this.name.substring(0, lastSlash + 1) + "$JsCallbacks$";
331 FindInMethod.super.visitFieldInsn(Opcodes.GETSTATIC, jsCallbacks, "VM", "L" + jsCallbacks + ";");
332 FindInMethod.super.visitInsn(Opcodes.AASTORE);
335 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
336 "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
338 switch (sv.returnType.getSort()) {
340 super.visitInsn(Opcodes.RETURN);
344 super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
345 super.visitInsn(Opcodes.ARETURN);
348 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean");
349 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
350 "java/lang/Boolean", "booleanValue", "()Z"
352 super.visitInsn(Opcodes.IRETURN);
355 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
356 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
357 "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
359 super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
365 public void visitEnd() {
368 if (generateBody()) {
370 super.visitMaxs(1, 0);
372 FindInClass.this.visitField(
373 Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
374 "$$fn$$" + name + "_" + found,
375 "Lorg/apidesign/html/boot/spi/Fn;",
385 private final class FindInAnno extends AnnotationVisitor {
386 private List<String> args = new ArrayList<String>();
388 private boolean javacall = false;
390 public FindInAnno() {
395 public void visit(String name, Object value) {
397 args.add((String) value);
400 if (name.equals("javacall")) { // NOI18N
401 javacall = (Boolean)value;
404 assert name.equals("body");
405 body = (String) value;
409 public AnnotationVisitor visitArray(String name) {
414 public void visitEnd() {
417 body = FnUtils.callback(body);
420 generateJSBody(args, body);
426 private final class LoadResource extends AnnotationVisitor {
427 public LoadResource() {
432 public void visit(String attrName, Object value) {
433 String relPath = (String) value;
434 if (relPath.startsWith("/")) {
435 FnUtils.loadScript(JsClassLoader.this, relPath);
437 int last = name.lastIndexOf('/');
438 String fullPath = name.substring(0, last + 1) + relPath;
439 FnUtils.loadScript(JsClassLoader.this, fullPath);
445 private class ClassWriterEx extends ClassWriter {
447 public ClassWriterEx(ClassReader classReader, int flags) {
448 super(classReader, flags);
452 protected String getCommonSuperClass(final String type1, final String type2) {
454 ClassLoader classLoader = JsClassLoader.this;
456 c = Class.forName(type1.replace('/', '.'), false, classLoader);
457 d = Class.forName(type2.replace('/', '.'), false, classLoader);
458 } catch (Exception e) {
459 throw new RuntimeException(e.toString());
461 if (c.isAssignableFrom(d)) {
464 if (d.isAssignableFrom(c)) {
467 if (c.isInterface() || d.isInterface()) {
468 return "java/lang/Object";
471 c = c.getSuperclass();
472 } while (!c.isAssignableFrom(d));
473 return c.getName().replace('.', '/');