javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 19 Feb 2013 15:54:36 +0100
branchmodel
changeset 767 2b1cf4f012f2
parent 765 1bc37d5f30d8
child 768 e320d8156140
permissions -rw-r--r--
When computing VM method name use erasured type
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     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.
     8  *
     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.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.htmlpage;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.io.OutputStreamWriter;
    23 import java.io.Writer;
    24 import java.util.ArrayList;
    25 import java.util.Collection;
    26 import java.util.Collections;
    27 import java.util.HashMap;
    28 import java.util.LinkedHashSet;
    29 import java.util.List;
    30 import java.util.Locale;
    31 import java.util.Map;
    32 import java.util.Set;
    33 import javax.annotation.processing.AbstractProcessor;
    34 import javax.annotation.processing.Completion;
    35 import javax.annotation.processing.Completions;
    36 import javax.annotation.processing.Processor;
    37 import javax.annotation.processing.RoundEnvironment;
    38 import javax.annotation.processing.SupportedAnnotationTypes;
    39 import javax.lang.model.element.AnnotationMirror;
    40 import javax.lang.model.element.Element;
    41 import javax.lang.model.element.ElementKind;
    42 import javax.lang.model.element.ExecutableElement;
    43 import javax.lang.model.element.Modifier;
    44 import javax.lang.model.element.PackageElement;
    45 import javax.lang.model.element.TypeElement;
    46 import javax.lang.model.element.VariableElement;
    47 import javax.lang.model.type.MirroredTypeException;
    48 import javax.lang.model.type.TypeMirror;
    49 import javax.tools.Diagnostic;
    50 import javax.tools.FileObject;
    51 import javax.tools.StandardLocation;
    52 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
    53 import org.apidesign.bck2brwsr.htmlpage.api.On;
    54 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    55 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    56 import org.openide.util.lookup.ServiceProvider;
    57 
    58 /** Annotation processor to process an XHTML page and generate appropriate 
    59  * "id" file.
    60  *
    61  * @author Jaroslav Tulach <jtulach@netbeans.org>
    62  */
    63 @ServiceProvider(service=Processor.class)
    64 @SupportedAnnotationTypes({
    65     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    66     "org.apidesign.bck2brwsr.htmlpage.api.On"
    67 })
    68 public final class PageProcessor extends AbstractProcessor {
    69     @Override
    70     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    71         boolean ok = true;
    72         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    73             Page p = e.getAnnotation(Page.class);
    74             if (p == null) {
    75                 continue;
    76             }
    77             PackageElement pe = (PackageElement)e.getEnclosingElement();
    78             String pkg = pe.getQualifiedName().toString();
    79             
    80             ProcessPage pp;
    81             try {
    82                 InputStream is = openStream(pkg, p.xhtml());
    83                 pp = ProcessPage.readPage(is);
    84                 is.close();
    85             } catch (IOException iOException) {
    86                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
    87                 ok = false;
    88                 pp = null;
    89             }
    90             Writer w;
    91             String className = p.className();
    92             if (className.isEmpty()) {
    93                 int indx = p.xhtml().indexOf('.');
    94                 className = p.xhtml().substring(0, indx);
    95             }
    96             try {
    97                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
    98                 w = new OutputStreamWriter(java.openOutputStream());
    99                 try {
   100                     w.append("package " + pkg + ";\n");
   101                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   102                     w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   103                     w.append("final class ").append(className).append(" {\n");
   104                     w.append("  private boolean locked;\n");
   105                     if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   106                         ok = false;
   107                     } else {
   108                         for (String id : pp.ids()) {
   109                             String tag = pp.tagNameForId(id);
   110                             String type = type(tag);
   111                             w.append("  ").append("public final ").
   112                                 append(type).append(' ').append(cnstnt(id)).append(" = new ").
   113                                 append(type).append("(\"").append(id).append("\");\n");
   114                         }
   115                     }
   116                     List<String> propsGetSet = new ArrayList<String>();
   117                     Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
   118                     if (!generateComputedProperties(w, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
   119                         ok = false;
   120                     }
   121                     generateProperties(w, p.properties(), propsGetSet, propsDeps);
   122                     w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   123                     if (!propsGetSet.isEmpty()) {
   124                         w.write("public " + className + " applyBindings() {\n");
   125                         w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   126                         w.write(className + ".class, this, ");
   127                         w.write("new String[] {\n");
   128                         String sep = "";
   129                         for (String n : propsGetSet) {
   130                             w.write(sep);
   131                             if (n == null) {
   132                                 w.write("    null");
   133                             } else {
   134                                 w.write("    \"" + n + "\"");
   135                             }
   136                             sep = ",\n";
   137                         }
   138                         w.write("\n  });\n  return this;\n}\n");
   139                         
   140                         w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
   141                         w.write("  org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
   142                         w.write("}\n");
   143                     }
   144                     w.append("}\n");
   145                 } finally {
   146                     w.close();
   147                 }
   148             } catch (IOException ex) {
   149                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   150                 return false;
   151             }
   152         }
   153         return ok;
   154     }
   155 
   156     private InputStream openStream(String pkg, String name) throws IOException {
   157         try {
   158             FileObject fo = processingEnv.getFiler().getResource(
   159                 StandardLocation.SOURCE_PATH, pkg, name);
   160             return fo.openInputStream();
   161         } catch (IOException ex) {
   162             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   163         }
   164     }
   165 
   166     private static String type(String tag) {
   167         if (tag.equals("title")) {
   168             return "Title";
   169         }
   170         if (tag.equals("button")) {
   171             return "Button";
   172         }
   173         if (tag.equals("input")) {
   174             return "Input";
   175         }
   176         if (tag.equals("canvas")) {
   177             return "Canvas";
   178         }
   179         if (tag.equals("img")) {
   180             return "Image";
   181         }
   182         return "Element";
   183     }
   184 
   185     private static String cnstnt(String id) {
   186         return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
   187     }
   188 
   189     private boolean initializeOnClick(
   190         String className, TypeElement type, Writer w, ProcessPage pp
   191     ) throws IOException {
   192         boolean ok = true;
   193         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   194         { //for (Element clazz : pe.getEnclosedElements()) {
   195           //  if (clazz.getKind() != ElementKind.CLASS) {
   196             //    continue;
   197            // }
   198             w.append("  public ").append(className).append("() {\n");
   199             StringBuilder dispatch = new StringBuilder();
   200             int dispatchCnt = 0;
   201             for (Element method : type.getEnclosedElements()) {
   202                 On oc = method.getAnnotation(On.class);
   203                 if (oc != null) {
   204                     for (String id : oc.id()) {
   205                         if (pp == null) {
   206                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
   207                             ok = false;
   208                             continue;
   209                         }
   210                         if (pp.tagNameForId(id) == null) {
   211                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   212                             ok = false;
   213                             continue;
   214                         }
   215                         ExecutableElement ee = (ExecutableElement)method;
   216                         StringBuilder params = new StringBuilder();
   217                         {
   218                             boolean first = true;
   219                             for (VariableElement ve : ee.getParameters()) {
   220                                 if (!first) {
   221                                     params.append(", ");
   222                                 }
   223                                 first = false;
   224                                 if (ve.asType() == stringType) {
   225                                     params.append('"').append(id).append('"');
   226                                     continue;
   227                                 }
   228                                 String rn = ve.asType().toString();
   229                                 int last = rn.lastIndexOf('.');
   230                                 if (last >= 0) {
   231                                     rn = rn.substring(last + 1);
   232                                 }
   233                                 if (rn.equals(className)) {
   234                                     params.append(className).append(".this");
   235                                     continue;
   236                                 }
   237                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   238                                     "@On method can only accept String or " + className + " arguments",
   239                                     ee
   240                                 );
   241                                 return false;
   242                             }
   243                         }
   244                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   245                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   246                             ok = false;
   247                             continue;
   248                         }
   249                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   250                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   251                             ok = false;
   252                             continue;
   253                         }
   254                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   255                             append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
   256 
   257                         dispatch.
   258                             append("      case ").append(dispatchCnt).append(": ").
   259                             append(type.getSimpleName().toString()).
   260                             append('.').append(ee.getSimpleName()).append("(").
   261                             append(params).
   262                             append("); break;\n");
   263                         
   264                         dispatchCnt++;
   265                     }
   266                 }
   267             }
   268             w.append("  }\n");
   269             if (dispatchCnt > 0) {
   270                 w.append("class OnDispatch implements Runnable {\n");
   271                 w.append("  private final int dispatch;\n");
   272                 w.append("  OnDispatch(int d) { dispatch = d; }\n");
   273                 w.append("  public void run() {\n");
   274                 w.append("    switch (dispatch) {\n");
   275                 w.append(dispatch);
   276                 w.append("    }\n");
   277                 w.append("  }\n");
   278                 w.append("}\n");
   279             }
   280             
   281 
   282         }
   283         return ok;
   284     }
   285 
   286     @Override
   287     public Iterable<? extends Completion> getCompletions(
   288         Element element, AnnotationMirror annotation, 
   289         ExecutableElement member, String userText
   290     ) {
   291         if (!userText.startsWith("\"")) {
   292             return Collections.emptyList();
   293         }
   294         
   295         Element cls = findClass(element);
   296         Page p = cls.getAnnotation(Page.class);
   297         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   298         String pkg = pe.getQualifiedName().toString();
   299         ProcessPage pp;
   300         try {
   301             InputStream is = openStream(pkg, p.xhtml());
   302             pp = ProcessPage.readPage(is);
   303             is.close();
   304         } catch (IOException iOException) {
   305             return Collections.emptyList();
   306         }
   307         
   308         List<Completion> cc = new ArrayList<Completion>();
   309         userText = userText.substring(1);
   310         for (String id : pp.ids()) {
   311             if (id.startsWith(userText)) {
   312                 cc.add(Completions.of("\"" + id + "\"", id));
   313             }
   314         }
   315         return cc;
   316     }
   317     
   318     private static Element findClass(Element e) {
   319         if (e == null) {
   320             return null;
   321         }
   322         Page p = e.getAnnotation(Page.class);
   323         if (p != null) {
   324             return e;
   325         }
   326         return e.getEnclosingElement();
   327     }
   328 
   329     private void generateProperties(
   330         Writer w, Property[] properties, Collection<String> props,
   331         Map<String,Collection<String>> deps
   332     ) throws IOException {
   333         for (Property p : properties) {
   334             final String tn = typeName(p);
   335             String[] gs = toGetSet(p.name(), tn, p.array());
   336 
   337             if (p.array()) {
   338                 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
   339                     + p.name() + "\"");
   340                 final Collection<String> dependants = deps.get(p.name());
   341                 if (dependants != null) {
   342                     for (String depProp : dependants) {
   343                         w.write(", ");
   344                         w.write('\"');
   345                         w.write(depProp);
   346                         w.write('\"');
   347                     }
   348                 }
   349                 w.write(");\n");
   350                 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
   351                 w.write("  if (locked) throw new IllegalStateException();\n");
   352                 w.write("  prop_" + p.name() + ".assign(ko);\n");
   353                 w.write("  return prop_" + p.name() + ";\n");
   354                 w.write("}\n");
   355                 w.write("private Object[] " + gs[0] + "ToArray() {\n");
   356                 w.write("  return " + gs[0] + "().toArray(new Object[0]);\n");
   357                 w.write("}\n");
   358             } else {
   359                 w.write("private " + tn + " prop_" + p.name() + ";\n");
   360                 w.write("public " + tn + " " + gs[0] + "() {\n");
   361                 w.write("  if (locked) throw new IllegalStateException();\n");
   362                 w.write("  return prop_" + p.name() + ";\n");
   363                 w.write("}\n");
   364                 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
   365                 w.write("  if (locked) throw new IllegalStateException();\n");
   366                 w.write("  prop_" + p.name() + " = v;\n");
   367                 w.write("  if (ko != null) {\n");
   368                 w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   369                 final Collection<String> dependants = deps.get(p.name());
   370                 if (dependants != null) {
   371                     for (String depProp : dependants) {
   372                         w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   373                     }
   374                 }
   375                 w.write("  }\n");
   376                 w.write("}\n");
   377             }
   378             
   379             props.add(p.name());
   380             props.add(gs[2]);
   381             props.add(gs[3]);
   382             props.add(gs[0]);
   383         }
   384     }
   385 
   386     private boolean generateComputedProperties(
   387         Writer w, Property[] fixedProps,
   388         Collection<? extends Element> arr, Collection<String> props,
   389         Map<String,Collection<String>> deps
   390     ) throws IOException {
   391         boolean ok = true;
   392         for (Element e : arr) {
   393             if (e.getKind() != ElementKind.METHOD) {
   394                 continue;
   395             }
   396             if (e.getAnnotation(ComputedProperty.class) == null) {
   397                 continue;
   398             }
   399             ExecutableElement ee = (ExecutableElement)e;
   400             final TypeMirror rt = ee.getReturnType();
   401             TypeMirror ert = processingEnv.getTypeUtils().erasure(rt);
   402             final String tn = ert.toString();
   403             final String sn = ee.getSimpleName().toString();
   404             String[] gs = toGetSet(sn, tn, false);
   405             
   406             w.write("public " + tn + " " + gs[0] + "() {\n");
   407             w.write("  if (locked) throw new IllegalStateException();\n");
   408             int arg = 0;
   409             for (VariableElement pe : ee.getParameters()) {
   410                 final String dn = pe.getSimpleName().toString();
   411                 
   412                 if (!verifyPropName(pe, dn, fixedProps)) {
   413                     ok = false;
   414                 }
   415                 
   416                 final String dt = pe.asType().toString();
   417                 String[] call = toGetSet(dn, dt, false);
   418                 w.write("  " + dt + " arg" + (++arg) + " = ");
   419                 w.write(call[0] + "();\n");
   420                 
   421                 Collection<String> depends = deps.get(dn);
   422                 if (depends == null) {
   423                     depends = new LinkedHashSet<String>();
   424                     deps.put(dn, depends);
   425                 }
   426                 depends.add(sn);
   427             }
   428             w.write("  try {\n");
   429             w.write("    locked = true;\n");
   430             w.write("    return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   431             String sep = "";
   432             for (int i = 1; i <= arg; i++) {
   433                 w.write(sep);
   434                 w.write("arg" + i);
   435                 sep = ", ";
   436             }
   437             w.write(");\n");
   438             w.write("  } finally {\n");
   439             w.write("    locked = false;\n");
   440             w.write("  }\n");
   441             w.write("}\n");
   442             
   443             props.add(e.getSimpleName().toString());
   444             props.add(gs[2]);
   445             props.add(null);
   446             props.add(gs[0]);
   447         }
   448         
   449         return ok;
   450     }
   451 
   452     private static String[] toGetSet(String name, String type, boolean array) {
   453         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   454         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   455         if ("int".equals(type)) {
   456             bck2brwsrType = "I";
   457         }
   458         if ("double".equals(type)) {
   459             bck2brwsrType = "D";
   460         }
   461         String pref = "get";
   462         if ("boolean".equals(type)) {
   463             pref = "is";
   464             bck2brwsrType = "Z";
   465         }
   466         final String nu = n.replace('.', '_');
   467         if (array) {
   468             return new String[] { 
   469                 "get" + n,
   470                 null,
   471                 "get" + nu + "ToArray___3Ljava_lang_Object_2",
   472                 null
   473             };
   474         }
   475         return new String[]{
   476             pref + n, 
   477             "set" + n, 
   478             pref + nu + "__" + bck2brwsrType,
   479             "set" + nu + "__V" + bck2brwsrType
   480         };
   481     }
   482 
   483     private String typeName(Property p) {
   484         String ret;
   485         try {
   486             ret = p.type().getName();
   487         } catch (MirroredTypeException ex) {
   488             TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
   489             ret = tm.toString();
   490         }
   491         if (p.array()) {
   492             if (ret.equals("byte")) {
   493                 return Byte.class.getName();
   494             }
   495             if (ret.equals("short")) {
   496                 return Short.class.getName();
   497             }
   498             if (ret.equals("char")) {
   499                 return Character.class.getName();
   500             }
   501             if (ret.equals("int")) {
   502                 return Integer.class.getName();
   503             }
   504             if (ret.equals("long")) {
   505                 return Long.class.getName();
   506             }
   507             if (ret.equals("float")) {
   508                 return Float.class.getName();
   509             }
   510             if (ret.equals("double")) {
   511                 return Double.class.getName();
   512             }
   513         }
   514         return ret;
   515     }
   516 
   517     private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
   518         StringBuilder sb = new StringBuilder();
   519         String sep = "";
   520         for (Property property : existingProps) {
   521             if (property.name().equals(propName)) {
   522                 return true;
   523             }
   524             sb.append(sep);
   525             sb.append('"');
   526             sb.append(property.name());
   527             sb.append('"');
   528             sep = ", ";
   529         }
   530         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
   531             propName + " is not one of known properties: " + sb
   532             , e
   533         );
   534         return false;
   535     }
   536 }