javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 02 May 2013 10:08:35 +0200
branchelements
changeset 1073 9321b4016d5c
parent 1010 e2d1dc505c24
child 1078 fc4fc1633445
permissions -rw-r--r--
Hopefully resuscitating the original code from rev. 146ae7b52b64 by manual merge
     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.StringWriter;
    24 import java.io.Writer;
    25 import java.lang.annotation.AnnotationTypeMismatchException;
    26 import java.lang.annotation.IncompleteAnnotationException;
    27 import java.lang.reflect.Method;
    28 import java.util.ArrayList;
    29 import java.util.Collection;
    30 import java.util.Collections;
    31 import java.util.HashMap;
    32 import java.util.HashSet;
    33 import java.util.LinkedHashSet;
    34 import java.util.List;
    35 import java.util.Map;
    36 import java.util.Set;
    37 import java.util.WeakHashMap;
    38 import javax.annotation.processing.AbstractProcessor;
    39 import javax.annotation.processing.Completion;
    40 import javax.annotation.processing.Completions;
    41 import javax.annotation.processing.ProcessingEnvironment;
    42 import javax.annotation.processing.Processor;
    43 import javax.annotation.processing.RoundEnvironment;
    44 import javax.annotation.processing.SupportedAnnotationTypes;
    45 import javax.lang.model.element.AnnotationMirror;
    46 import javax.lang.model.element.AnnotationValue;
    47 import javax.lang.model.element.Element;
    48 import javax.lang.model.element.ElementKind;
    49 import javax.lang.model.element.ExecutableElement;
    50 import javax.lang.model.element.Modifier;
    51 import javax.lang.model.element.PackageElement;
    52 import javax.lang.model.element.TypeElement;
    53 import javax.lang.model.element.VariableElement;
    54 import javax.lang.model.type.ArrayType;
    55 import javax.lang.model.type.MirroredTypeException;
    56 import javax.lang.model.type.TypeKind;
    57 import javax.lang.model.type.TypeMirror;
    58 import javax.lang.model.util.Elements;
    59 import javax.lang.model.util.Types;
    60 import javax.tools.Diagnostic;
    61 import javax.tools.FileObject;
    62 import javax.tools.StandardLocation;
    63 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
    64 import org.apidesign.bck2brwsr.htmlpage.api.Model;
    65 import org.apidesign.bck2brwsr.htmlpage.api.On;
    66 import org.apidesign.bck2brwsr.htmlpage.api.OnFunction;
    67 import org.apidesign.bck2brwsr.htmlpage.api.OnPropertyChange;
    68 import org.apidesign.bck2brwsr.htmlpage.api.OnReceive;
    69 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    70 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    71 import org.openide.util.lookup.ServiceProvider;
    72 
    73 /** Annotation processor to process an XHTML page and generate appropriate 
    74  * "id" file.
    75  *
    76  * @author Jaroslav Tulach <jtulach@netbeans.org>
    77  */
    78 @ServiceProvider(service=Processor.class)
    79 @SupportedAnnotationTypes({
    80     "org.apidesign.bck2brwsr.htmlpage.api.Model",
    81     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    82     "org.apidesign.bck2brwsr.htmlpage.api.OnFunction",
    83     "org.apidesign.bck2brwsr.htmlpage.api.OnReceive",
    84     "org.apidesign.bck2brwsr.htmlpage.api.OnPropertyChange",
    85     "org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty",
    86     "org.apidesign.bck2brwsr.htmlpage.api.On"
    87 })
    88 public final class PageProcessor extends AbstractProcessor {
    89     private final Map<Element,String> models = new WeakHashMap<>();
    90     private final Map<Element,Prprt[]> verify = new WeakHashMap<>();
    91     @Override
    92     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    93         boolean ok = true;
    94         for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
    95             if (!processModel(e)) {
    96                 ok = false;
    97             }
    98         }
    99         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
   100             if (!processPage(e)) {
   101                 ok = false;
   102             }
   103         }
   104         if (roundEnv.processingOver()) {
   105             models.clear();
   106             for (Map.Entry<Element, Prprt[]> entry : verify.entrySet()) {
   107                 TypeElement te = (TypeElement)entry.getKey();
   108                 String fqn = processingEnv.getElementUtils().getBinaryName(te).toString();
   109                 Element finalElem = processingEnv.getElementUtils().getTypeElement(fqn);
   110                 if (finalElem == null) {
   111                     continue;
   112                 }
   113                 Prprt[] props;
   114                 Model m = finalElem.getAnnotation(Model.class);
   115                 if (m != null) {
   116                     props = Prprt.wrap(processingEnv, finalElem, m.properties());
   117                 } else {
   118                     Page p = finalElem.getAnnotation(Page.class);
   119                     props = Prprt.wrap(processingEnv, finalElem, p.properties());
   120                 }
   121                 for (Prprt p : props) {
   122                     boolean[] isModel = { false };
   123                     boolean[] isEnum = { false };
   124                     boolean[] isPrimitive = { false };
   125                     String t = checkType(p, isModel, isEnum, isPrimitive);
   126                     if (isEnum[0]) {
   127                         continue;
   128                     }
   129                     if (isPrimitive[0]) {
   130                         continue;
   131                     }
   132                     if (isModel[0]) {
   133                         continue;
   134                     }
   135                     if ("java.lang.String".equals(t)) {
   136                         continue;
   137                     }
   138                     error("The type " + t + " should be defined by @Model annotation", entry.getKey());
   139                 }
   140             }
   141             verify.clear();
   142         }
   143         return ok;
   144     }
   145 
   146     private InputStream openStream(String pkg, String name) throws IOException {
   147         try {
   148             FileObject fo = processingEnv.getFiler().getResource(
   149                 StandardLocation.SOURCE_PATH, pkg, name);
   150             return fo.openInputStream();
   151         } catch (IOException ex) {
   152             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   153         }
   154     }
   155 
   156     private void error(String msg, Element e) {
   157         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e);
   158     }
   159     
   160     private boolean processModel(Element e) {
   161         boolean ok = true;
   162         Model m = e.getAnnotation(Model.class);
   163         if (m == null) {
   164             return true;
   165         }
   166         String pkg = findPkgName(e);
   167         Writer w;
   168         String className = m.className();
   169         models.put(e, className);
   170         try {
   171             StringWriter body = new StringWriter();
   172             List<String> propsGetSet = new ArrayList<>();
   173             List<String> functions = new ArrayList<>();
   174             Map<String, Collection<String>> propsDeps = new HashMap<>();
   175             Map<String, Collection<String>> functionDeps = new HashMap<>();
   176             Prprt[] props = createProps(e, m.properties());
   177             
   178             if (!generateComputedProperties(body, props, e.getEnclosedElements(), propsGetSet, propsDeps)) {
   179                 ok = false;
   180             }
   181             if (!generateOnChange(e, propsDeps, props, className, functionDeps)) {
   182                 ok = false;
   183             }
   184             if (!generateProperties(e, body, props, propsGetSet, propsDeps, functionDeps)) {
   185                 ok = false;
   186             }
   187             if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
   188                 ok = false;
   189             }
   190             FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   191             w = new OutputStreamWriter(java.openOutputStream());
   192             try {
   193                 w.append("package " + pkg + ";\n");
   194                 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   195                 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   196                 w.append("import org.apidesign.bck2brwsr.core.JavaScriptOnly;\n");
   197                 w.append("final class ").append(className).append(" implements Cloneable {\n");
   198                 w.append("  private boolean locked;\n");
   199                 w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   200                 w.append(body.toString());
   201                 w.append("  private static Class<" + inPckName(e) + "> modelFor() { return null; }\n");
   202                 w.append("  public ").append(className).append("() {\n");
   203                 w.append("    intKnckt();\n");
   204                 w.append("  };\n");
   205                 w.append("  private void intKnckt() {\n");
   206                 w.append("    ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(this, ");
   207                 writeStringArray(propsGetSet, w);
   208                 w.append(", ");
   209                 writeStringArray(functions, w);
   210                 w.append("    );\n");
   211                 w.append("  };\n");
   212                 w.append("  ").append(className).append("(Object json) {\n");
   213                 int values = 0;
   214                 for (int i = 0; i < propsGetSet.size(); i += 4) {
   215                     Prprt p = findPrprt(props, propsGetSet.get(i));
   216                     if (p == null) {
   217                         continue;
   218                     }
   219                     values++;
   220                 }
   221                 w.append("    Object[] ret = new Object[" + values + "];\n");
   222                 w.append("    org.apidesign.bck2brwsr.htmlpage.ConvertTypes.extractJSON(json, new String[] {\n");
   223                 for (int i = 0; i < propsGetSet.size(); i += 4) {
   224                     Prprt p = findPrprt(props, propsGetSet.get(i));
   225                     if (p == null) {
   226                         continue;
   227                     }
   228                     w.append("      \"").append(propsGetSet.get(i)).append("\",\n");
   229                 }
   230                 w.append("    }, ret);\n");
   231                 for (int i = 0, cnt = 0, prop = 0; i < propsGetSet.size(); i += 4) {
   232                     final String pn = propsGetSet.get(i);
   233                     Prprt p = findPrprt(props, pn);
   234                     if (p == null) {
   235                         continue;
   236                     }
   237                     boolean[] isModel = { false };
   238                     boolean[] isEnum = { false };
   239                     boolean isPrimitive[] = { false };
   240                     String type = checkType(props[prop++], isModel, isEnum, isPrimitive);
   241                     if (p.array()) {
   242                         w.append("if (ret[" + cnt + "] instanceof Object[]) {\n");
   243                         w.append("  for (Object e : ((Object[])ret[" + cnt + "])) {\n");
   244                         if (isModel[0]) {
   245                             w.append("    this.prop_").append(pn).append(".add(new ");
   246                             w.append(type).append("(e));\n");
   247                         } else if (isEnum[0]) {
   248                             w.append("    this.prop_").append(pn);
   249                             w.append(".add(e == null ? null : ");
   250                             w.append(type).append(".valueOf((String)e));\n");
   251                         } else {
   252                             if (isPrimitive(type)) {
   253                                 w.append("    this.prop_").append(pn).append(".add(((Number)e).");
   254                                 w.append(type).append("Value());\n");
   255                             } else {
   256                                 w.append("    this.prop_").append(pn).append(".add((");
   257                                 w.append(type).append(")e);\n");
   258                             }
   259                         }
   260                         w.append("  }\n");
   261                         w.append("}\n");
   262                     } else {
   263                         if (isEnum[0]) {
   264                             w.append("    this.prop_").append(pn);
   265                             w.append(" = ret[" + cnt + "] == null ? null : ");
   266                             w.append(type).append(".valueOf((String)ret[" + cnt + "]);\n");
   267                         } else if (isPrimitive(type)) {
   268                             w.append("    this.prop_").append(pn);
   269                             w.append(" = ((Number)").append("ret[" + cnt + "]).");
   270                             w.append(type).append("Value();\n");
   271                         } else {
   272                             w.append("    this.prop_").append(pn);
   273                             w.append(" = (").append(type).append(')');
   274                             w.append("ret[" + cnt + "];\n");
   275                         }
   276                     }
   277                     cnt++;
   278                 }
   279                 w.append("    intKnckt();\n");
   280                 w.append("  };\n");
   281                 writeToString(props, w);
   282                 writeClone(className, props, w);
   283                 w.append("}\n");
   284             } finally {
   285                 w.close();
   286             }
   287         } catch (IOException ex) {
   288             error("Can't create " + className + ".java", e);
   289             return false;
   290         }
   291         return ok;
   292     }
   293     
   294     private boolean processPage(Element e) {
   295         boolean ok = true;
   296         Page p = e.getAnnotation(Page.class);
   297         if (p == null) {
   298             return true;
   299         }
   300         String pkg = findPkgName(e);
   301 
   302             ProcessPage pp;
   303             ElementGenerator eGen = new ElementGenerator(processingEnv);
   304             try {
   305                 InputStream is = openStream(pkg, p.xhtml());
   306                 pp = ProcessPage.readPage(is);
   307                 is.close();
   308             } catch (IOException iOException) {
   309                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
   310                 return false;
   311             }
   312             Writer w;
   313             String className = p.className();
   314             if (className.isEmpty()) {
   315                 int indx = p.xhtml().indexOf('.');
   316                 className = p.xhtml().substring(0, indx);
   317             }
   318             try {
   319                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   320                 w = new OutputStreamWriter(java.openOutputStream());
   321                 try {
   322                     w.append("package " + pkg + ";\n");
   323                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   324                     w.append("final class ").append(className).append(" {\n");
   325                     w.append("  private boolean locked;\n");
   326                     if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   327                         return false;
   328                     }
   329                     for (String id : pp.ids()) {
   330                         String tag = pp.tagNameForId(id);
   331                         String type = eGen.getType(pkg, tag, e);
   332                         w.append("  ").append("public final ").
   333                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   334                             append(type).append("(\"").append(id).append("\");\n");
   335                     }
   336                     List<String> propsGetSet = new ArrayList<String>();
   337                     Map<String, Collection<String>> functionDeps = new HashMap<>();
   338                     Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
   339                     List<String> functions = new ArrayList<>();
   340                     Prprt[] props = createProps(e, p.properties());
   341                     if (!generateComputedProperties(w, props, e.getEnclosedElements(), propsGetSet, propsDeps)) {
   342                         ok = false;
   343                     }
   344                     if (!generateOnChange(e, propsDeps, props, className, functionDeps)) {
   345                         ok = false;
   346                     }
   347                     if (!generateProperties(e, w, props, propsGetSet, propsDeps, functionDeps)) {
   348                         ok = false;
   349                     }
   350                     if (!generateFunctions(e, w, className, e.getEnclosedElements(), functions)) {
   351                         ok = false;
   352                     }
   353                     if (!generateReceive(e, w, className, e.getEnclosedElements(), functions)) {
   354                         ok = false;
   355                     }                    
   356                     w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   357                     if (!propsGetSet.isEmpty()) {
   358                         w.write("public " + className + " applyBindings() {\n");
   359                         w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   360                         w.write(className + ".class, this, ");
   361                         writeStringArray(propsGetSet, w);
   362                         w.append(", ");
   363                         writeStringArray(functions, w);
   364                         w.write(");\n  return this;\n}\n");
   365 
   366                         w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
   367                         w.write("  org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
   368                         w.write("}\n");
   369                     }
   370                     w.append("}\n");
   371                 } finally {
   372                     w.close();
   373                 }
   374             } catch (IOException ex) {
   375                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   376                 return false;
   377             }
   378         return ok;
   379     }
   380 
   381     private static String cnstnt(String id) {
   382         return id.replace('.', '_').replace('-', '_');
   383     }
   384 
   385     private boolean initializeOnClick(
   386         String className, TypeElement type, Writer w, ProcessPage pp
   387     ) throws IOException {
   388         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   389         { //for (Element clazz : pe.getEnclosedElements()) {
   390           //  if (clazz.getKind() != ElementKind.CLASS) {
   391             //    continue;
   392            // }
   393             w.append("  public ").append(className).append("() {\n");
   394             StringBuilder dispatch = new StringBuilder();
   395             int dispatchCnt = 0;
   396             for (Element method : type.getEnclosedElements()) {
   397                 On oc = method.getAnnotation(On.class);
   398                 if (oc != null) {
   399                     for (String id : oc.id()) {
   400                         if (pp.tagNameForId(id) == null) {
   401                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   402                             return false;
   403                         }
   404                         ExecutableElement ee = (ExecutableElement)method;
   405                         StringBuilder params = new StringBuilder();
   406                         {
   407                             boolean first = true;
   408                             for (VariableElement ve : ee.getParameters()) {
   409                                 if (!first) {
   410                                     params.append(", ");
   411                                 }
   412                                 first = false;
   413                                 if (ve.asType() == stringType) {
   414                                     if (ve.getSimpleName().contentEquals("id")) {
   415                                         params.append('"').append(id).append('"');
   416                                         continue;
   417                                     }
   418                                     params.append("org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(ev, \"");
   419                                     params.append(ve.getSimpleName().toString());
   420                                     params.append("\")");
   421                                     continue;
   422                                 }
   423                                 if (processingEnv.getTypeUtils().getPrimitiveType(TypeKind.DOUBLE) == ve.asType()) {
   424                                     params.append("org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(ev, \"");
   425                                     params.append(ve.getSimpleName().toString());
   426                                     params.append("\")");
   427                                     continue;
   428                                 }
   429                                 String rn = ve.asType().toString();
   430                                 int last = rn.lastIndexOf('.');
   431                                 if (last >= 0) {
   432                                     rn = rn.substring(last + 1);
   433                                 }
   434                                 if (rn.equals(className)) {
   435                                     params.append(className).append(".this");
   436                                     continue;
   437                                 }
   438                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   439                                     "@On method can only accept String named 'id' or " + className + " arguments",
   440                                     ee
   441                                 );
   442                                 return false;
   443                             }
   444                         }
   445                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   446                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   447                             return false;
   448                         }
   449                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   450                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   451                             return false;
   452                         }
   453                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   454                             append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
   455 
   456                         dispatch.
   457                             append("      case ").append(dispatchCnt).append(": ").
   458                             append(type.getSimpleName().toString()).
   459                             append('.').append(ee.getSimpleName()).append("(").
   460                             append(params).
   461                             append("); break;\n");
   462                         
   463                         dispatchCnt++;
   464                     }
   465                 }
   466             }
   467             w.append("  }\n");
   468             if (dispatchCnt > 0) {
   469                 w.append("class OnDispatch implements OnHandler {\n");
   470                 w.append("  private final int dispatch;\n");
   471                 w.append("  OnDispatch(int d) { dispatch = d; }\n");
   472                 w.append("  public void onEvent(Object ev) {\n");
   473                 w.append("    switch (dispatch) {\n");
   474                 w.append(dispatch);
   475                 w.append("    }\n");
   476                 w.append("  }\n");
   477                 w.append("}\n");
   478             }
   479             
   480 
   481         }
   482         return true;
   483     }
   484 
   485     @Override
   486     public Iterable<? extends Completion> getCompletions(
   487         Element element, AnnotationMirror annotation, 
   488         ExecutableElement member, String userText
   489     ) {
   490         if (!userText.startsWith("\"")) {
   491             return Collections.emptyList();
   492         }
   493         
   494         Element cls = findClass(element);
   495         Page p = cls.getAnnotation(Page.class);
   496         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   497         String pkg = pe.getQualifiedName().toString();
   498         ProcessPage pp;
   499         try {
   500             InputStream is = openStream(pkg, p.xhtml());
   501             pp = ProcessPage.readPage(is);
   502             is.close();
   503         } catch (IOException iOException) {
   504             return Collections.emptyList();
   505         }
   506         
   507         List<Completion> cc = new ArrayList<Completion>();
   508         userText = userText.substring(1);
   509         for (String id : pp.ids()) {
   510             if (id.startsWith(userText)) {
   511                 cc.add(Completions.of("\"" + id + "\"", id));
   512             }
   513         }
   514         return cc;
   515     }
   516     
   517     private static Element findClass(Element e) {
   518         if (e == null) {
   519             return null;
   520         }
   521         Page p = e.getAnnotation(Page.class);
   522         if (p != null) {
   523             return e;
   524         }
   525         return e.getEnclosingElement();
   526     }
   527 
   528     private boolean generateProperties(
   529         Element where,
   530         Writer w, Prprt[] properties,
   531         Collection<String> props, 
   532         Map<String,Collection<String>> deps,
   533         Map<String,Collection<String>> functionDeps
   534     ) throws IOException {
   535         boolean ok = true;
   536         for (Prprt p : properties) {
   537             final String tn;
   538             tn = typeName(where, p);
   539             String[] gs = toGetSet(p.name(), tn, p.array());
   540 
   541             if (p.array()) {
   542                 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
   543                     + p.name() + "\"");
   544                 Collection<String> dependants = deps.get(p.name());
   545                 if (dependants != null) {
   546                     for (String depProp : dependants) {
   547                         w.write(", ");
   548                         w.write('\"');
   549                         w.write(depProp);
   550                         w.write('\"');
   551                     }
   552                 }
   553                 w.write(")");
   554                 
   555                 dependants = functionDeps.get(p.name());
   556                 if (dependants != null) {
   557                     w.write(".onChange(new Runnable() { public void run() {\n");
   558                     for (String call : dependants) {
   559                         w.append(call);
   560                     }
   561                     w.write("}})");
   562                 }
   563                 w.write(";\n");
   564                 
   565                 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
   566                 w.write("  if (locked) throw new IllegalStateException();\n");
   567                 w.write("  prop_" + p.name() + ".assign(ko);\n");
   568                 w.write("  return prop_" + p.name() + ";\n");
   569                 w.write("}\n");
   570             } else {
   571                 w.write("private " + tn + " prop_" + p.name() + ";\n");
   572                 w.write("public " + tn + " " + gs[0] + "() {\n");
   573                 w.write("  if (locked) throw new IllegalStateException();\n");
   574                 w.write("  return prop_" + p.name() + ";\n");
   575                 w.write("}\n");
   576                 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
   577                 w.write("  if (locked) throw new IllegalStateException();\n");
   578                 w.write("  prop_" + p.name() + " = v;\n");
   579                 w.write("  if (ko != null) {\n");
   580                 w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   581                 Collection<String> dependants = deps.get(p.name());
   582                 if (dependants != null) {
   583                     for (String depProp : dependants) {
   584                         w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   585                     }
   586                 }
   587                 w.write("  }\n");
   588                 dependants = functionDeps.get(p.name());
   589                 if (dependants != null) {
   590                     for (String call : dependants) {
   591                         w.append(call);
   592                     }
   593                 }
   594                 w.write("}\n");
   595             }
   596             
   597             props.add(p.name());
   598             props.add(gs[2]);
   599             props.add(gs[3]);
   600             props.add(gs[0]);
   601         }
   602         return ok;
   603     }
   604 
   605     private boolean generateComputedProperties(
   606         Writer w, Prprt[] fixedProps,
   607         Collection<? extends Element> arr, Collection<String> props,
   608         Map<String,Collection<String>> deps
   609     ) throws IOException {
   610         boolean ok = true;
   611         for (Element e : arr) {
   612             if (e.getKind() != ElementKind.METHOD) {
   613                 continue;
   614             }
   615             if (e.getAnnotation(ComputedProperty.class) == null) {
   616                 continue;
   617             }
   618             ExecutableElement ee = (ExecutableElement)e;
   619             final TypeMirror rt = ee.getReturnType();
   620             final Types tu = processingEnv.getTypeUtils();
   621             TypeMirror ert = tu.erasure(rt);
   622             String tn = fqn(ert, ee);
   623             boolean array = false;
   624             if (tn.equals("java.util.List")) {
   625                 array = true;
   626             }
   627             
   628             final String sn = ee.getSimpleName().toString();
   629             String[] gs = toGetSet(sn, tn, array);
   630             
   631             w.write("public " + tn + " " + gs[0] + "() {\n");
   632             w.write("  if (locked) throw new IllegalStateException();\n");
   633             int arg = 0;
   634             for (VariableElement pe : ee.getParameters()) {
   635                 final String dn = pe.getSimpleName().toString();
   636                 
   637                 if (!verifyPropName(pe, dn, fixedProps)) {
   638                     ok = false;
   639                 }
   640                 
   641                 final String dt = fqn(pe.asType(), ee);
   642                 String[] call = toGetSet(dn, dt, false);
   643                 w.write("  " + dt + " arg" + (++arg) + " = ");
   644                 w.write(call[0] + "();\n");
   645                 
   646                 Collection<String> depends = deps.get(dn);
   647                 if (depends == null) {
   648                     depends = new LinkedHashSet<>();
   649                     deps.put(dn, depends);
   650                 }
   651                 depends.add(sn);
   652             }
   653             w.write("  try {\n");
   654             w.write("    locked = true;\n");
   655             w.write("    return " + fqn(ee.getEnclosingElement().asType(), ee) + '.' + e.getSimpleName() + "(");
   656             String sep = "";
   657             for (int i = 1; i <= arg; i++) {
   658                 w.write(sep);
   659                 w.write("arg" + i);
   660                 sep = ", ";
   661             }
   662             w.write(");\n");
   663             w.write("  } finally {\n");
   664             w.write("    locked = false;\n");
   665             w.write("  }\n");
   666             w.write("}\n");
   667 
   668             props.add(e.getSimpleName().toString());
   669             props.add(gs[2]);
   670             props.add(null);
   671             props.add(gs[0]);
   672         }
   673         
   674         return ok;
   675     }
   676 
   677     private static String[] toGetSet(String name, String type, boolean array) {
   678         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   679         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   680         if ("int".equals(type)) {
   681             bck2brwsrType = "I";
   682         }
   683         if ("double".equals(type)) {
   684             bck2brwsrType = "D";
   685         }
   686         String pref = "get";
   687         if ("boolean".equals(type)) {
   688             pref = "is";
   689             bck2brwsrType = "Z";
   690         }
   691         final String nu = n.replace('.', '_');
   692         if (array) {
   693             return new String[] { 
   694                 "get" + n,
   695                 null,
   696                 "get" + nu + "__Ljava_util_List_2",
   697                 null
   698             };
   699         }
   700         return new String[]{
   701             pref + n, 
   702             "set" + n, 
   703             pref + nu + "__" + bck2brwsrType,
   704             "set" + nu + "__V" + bck2brwsrType
   705         };
   706     }
   707 
   708     private String typeName(Element where, Prprt p) {
   709         String ret;
   710         boolean[] isModel = { false };
   711         boolean[] isEnum = { false };
   712         boolean isPrimitive[] = { false };
   713         ret = checkType(p, isModel, isEnum, isPrimitive);
   714         if (p.array()) {
   715             String bt = findBoxedType(ret);
   716             if (bt != null) {
   717                 return bt;
   718             }
   719         }
   720         return ret;
   721     }
   722     
   723     private static String findBoxedType(String ret) {
   724         if (ret.equals("boolean")) {
   725             return Boolean.class.getName();
   726         }
   727         if (ret.equals("byte")) {
   728             return Byte.class.getName();
   729         }
   730         if (ret.equals("short")) {
   731             return Short.class.getName();
   732         }
   733         if (ret.equals("char")) {
   734             return Character.class.getName();
   735         }
   736         if (ret.equals("int")) {
   737             return Integer.class.getName();
   738         }
   739         if (ret.equals("long")) {
   740             return Long.class.getName();
   741         }
   742         if (ret.equals("float")) {
   743             return Float.class.getName();
   744         }
   745         if (ret.equals("double")) {
   746             return Double.class.getName();
   747         }
   748         return null;
   749     }
   750 
   751     private boolean verifyPropName(Element e, String propName, Prprt[] existingProps) {
   752         StringBuilder sb = new StringBuilder();
   753         String sep = "";
   754         for (Prprt Prprt : existingProps) {
   755             if (Prprt.name().equals(propName)) {
   756                 return true;
   757             }
   758             sb.append(sep);
   759             sb.append('"');
   760             sb.append(Prprt.name());
   761             sb.append('"');
   762             sep = ", ";
   763         }
   764         error(
   765             propName + " is not one of known properties: " + sb
   766             , e
   767         );
   768         return false;
   769     }
   770 
   771     private static String findPkgName(Element e) {
   772         for (;;) {
   773             if (e.getKind() == ElementKind.PACKAGE) {
   774                 return ((PackageElement)e).getQualifiedName().toString();
   775             }
   776             e = e.getEnclosingElement();
   777         }
   778     }
   779 
   780     private boolean generateFunctions(
   781         Element clazz, Writer body, String className, 
   782         List<? extends Element> enclosedElements, List<String> functions
   783     ) throws IOException {
   784         for (Element m : enclosedElements) {
   785             if (m.getKind() != ElementKind.METHOD) {
   786                 continue;
   787             }
   788             ExecutableElement e = (ExecutableElement)m;
   789             OnFunction onF = e.getAnnotation(OnFunction.class);
   790             if (onF == null) {
   791                 continue;
   792             }
   793             if (!e.getModifiers().contains(Modifier.STATIC)) {
   794                 error("@OnFunction method needs to be static", e);
   795                 return false;
   796             }
   797             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   798                 error("@OnFunction method cannot be private", e);
   799                 return false;
   800             }
   801             if (e.getReturnType().getKind() != TypeKind.VOID) {
   802                 error("@OnFunction method should return void", e);
   803                 return false;
   804             }
   805             String n = e.getSimpleName().toString();
   806             body.append("private void ").append(n).append("(Object data, Object ev) {\n");
   807             body.append("  ").append(clazz.getSimpleName()).append(".").append(n).append("(");
   808             body.append(wrapParams(e, null, className, "ev", "data"));
   809             body.append(");\n");
   810             body.append("}\n");
   811             
   812             functions.add(n);
   813             functions.add(n + "__VLjava_lang_Object_2Ljava_lang_Object_2");
   814         }
   815         return true;
   816     }
   817 
   818     private boolean generateOnChange(Element clazz, Map<String,Collection<String>> propDeps,
   819         Prprt[] properties, String className, 
   820         Map<String, Collection<String>> functionDeps
   821     ) {
   822         for (Element m : clazz.getEnclosedElements()) {
   823             if (m.getKind() != ElementKind.METHOD) {
   824                 continue;
   825             }
   826             ExecutableElement e = (ExecutableElement) m;
   827             OnPropertyChange onPC = e.getAnnotation(OnPropertyChange.class);
   828             if (onPC == null) {
   829                 continue;
   830             }
   831             for (String pn : onPC.value()) {
   832                 if (findPrprt(properties, pn) == null && findDerivedFrom(propDeps, pn).isEmpty()) {
   833                     error("No Prprt named '" + pn + "' in the model", clazz);
   834                     return false;
   835                 }
   836             }
   837             if (!e.getModifiers().contains(Modifier.STATIC)) {
   838                 error("@OnPrprtChange method needs to be static", e);
   839                 return false;
   840             }
   841             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   842                 error("@OnPrprtChange method cannot be private", e);
   843                 return false;
   844             }
   845             if (e.getReturnType().getKind() != TypeKind.VOID) {
   846                 error("@OnPrprtChange method should return void", e);
   847                 return false;
   848             }
   849             String n = e.getSimpleName().toString();
   850             
   851             
   852             for (String pn : onPC.value()) {
   853                 StringBuilder call = new StringBuilder();
   854                 call.append("  ").append(clazz.getSimpleName()).append(".").append(n).append("(");
   855                 call.append(wrapPropName(e, className, "name", pn));
   856                 call.append(");\n");
   857                 
   858                 Collection<String> change = functionDeps.get(pn);
   859                 if (change == null) {
   860                     change = new ArrayList<>();
   861                     functionDeps.put(pn, change);
   862                 }
   863                 change.add(call.toString());
   864                 for (String dpn : findDerivedFrom(propDeps, pn)) {
   865                     change = functionDeps.get(dpn);
   866                     if (change == null) {
   867                         change = new ArrayList<>();
   868                         functionDeps.put(dpn, change);
   869                     }
   870                     change.add(call.toString());
   871                 }
   872             }
   873         }
   874         return true;
   875     }
   876     
   877     private boolean generateReceive(
   878         Element clazz, Writer body, String className, 
   879         List<? extends Element> enclosedElements, List<String> functions
   880     ) throws IOException {
   881         for (Element m : enclosedElements) {
   882             if (m.getKind() != ElementKind.METHOD) {
   883                 continue;
   884             }
   885             ExecutableElement e = (ExecutableElement)m;
   886             OnReceive onR = e.getAnnotation(OnReceive.class);
   887             if (onR == null) {
   888                 continue;
   889             }
   890             if (!e.getModifiers().contains(Modifier.STATIC)) {
   891                 error("@OnReceive method needs to be static", e);
   892                 return false;
   893             }
   894             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   895                 error("@OnReceive method cannot be private", e);
   896                 return false;
   897             }
   898             if (e.getReturnType().getKind() != TypeKind.VOID) {
   899                 error("@OnReceive method should return void", e);
   900                 return false;
   901             }
   902             String modelClass = null;
   903             boolean expectsList = false;
   904             List<String> args = new ArrayList<>();
   905             {
   906                 for (VariableElement ve : e.getParameters()) {
   907                     TypeMirror modelType = null;
   908                     if (ve.asType().toString().equals(className)) {
   909                         args.add(className + ".this");
   910                     } else if (isModel(ve.asType())) {
   911                         modelType = ve.asType();
   912                     } else if (ve.asType().getKind() == TypeKind.ARRAY) {
   913                         modelType = ((ArrayType)ve.asType()).getComponentType();
   914                         expectsList = true;
   915                     }
   916                     if (modelType != null) {
   917                         if (modelClass != null) {
   918                             error("There can be only one model class among arguments", e);
   919                         } else {
   920                             modelClass = modelType.toString();
   921                             if (expectsList) {
   922                                 args.add("arr");
   923                             } else {
   924                                 args.add("arr[0]");
   925                             }
   926                         }
   927                     }
   928                 }
   929             }
   930             if (modelClass == null) {
   931                 error("The method needs to have one @Model class as parameter", e);
   932             }
   933             String n = e.getSimpleName().toString();
   934             body.append("public void ").append(n).append("(");
   935             StringBuilder assembleURL = new StringBuilder();
   936             String jsonpVarName = null;
   937             {
   938                 String sep = "";
   939                 boolean skipJSONP = onR.jsonp().isEmpty();
   940                 for (String p : findParamNames(e, onR.url(), assembleURL)) {
   941                     if (!skipJSONP && p.equals(onR.jsonp())) {
   942                         skipJSONP = true;
   943                         jsonpVarName = p;
   944                         continue;
   945                     }
   946                     body.append(sep);
   947                     body.append("String ").append(p);
   948                     sep = ", ";
   949                 }
   950                 if (!skipJSONP) {
   951                     error(
   952                         "Name of jsonp attribute ('" + onR.jsonp() + 
   953                         "') is not used in url attribute '" + onR.url() + "'", e
   954                     );
   955                 }
   956             }
   957             body.append(") {\n");
   958             body.append("  final Object[] result = { null };\n");
   959             body.append(
   960                 "  class ProcessResult implements Runnable {\n" +
   961                 "    @Override\n" +
   962                 "    public void run() {\n" +
   963                 "      Object value = result[0];\n");
   964             body.append(
   965                 "      " + modelClass + "[] arr;\n");
   966             body.append(
   967                 "      if (value instanceof Object[]) {\n" +
   968                 "        Object[] data = ((Object[])value);\n" +
   969                 "        arr = new " + modelClass + "[data.length];\n" +
   970                 "        for (int i = 0; i < data.length; i++) {\n" +
   971                 "          arr[i] = new " + modelClass + "(data[i]);\n" +
   972                 "        }\n" +
   973                 "      } else {\n" +
   974                 "        arr = new " + modelClass + "[1];\n" +
   975                 "        arr[0] = new " + modelClass + "(value);\n" +
   976                 "      }\n"
   977             );
   978             {
   979                 body.append(clazz.getSimpleName()).append(".").append(n).append("(");
   980                 String sep = "";
   981                 for (String arg : args) {
   982                     body.append(sep);
   983                     body.append(arg);
   984                     sep = ", ";
   985                 }
   986                 body.append(");\n");
   987             }
   988             body.append(
   989                 "    }\n" +
   990                 "  }\n"
   991             );
   992             body.append("  ProcessResult pr = new ProcessResult();\n");
   993             if (jsonpVarName != null) {
   994                 body.append("  String ").append(jsonpVarName).
   995                     append(" = org.apidesign.bck2brwsr.htmlpage.ConvertTypes.createJSONP(result, pr);\n");
   996             }
   997             body.append("  org.apidesign.bck2brwsr.htmlpage.ConvertTypes.loadJSON(\n      ");
   998             body.append(assembleURL);
   999             body.append(", result, pr, ").append(jsonpVarName).append("\n  );\n");
  1000 //            body.append("  ").append(clazz.getSimpleName()).append(".").append(n).append("(");
  1001 //            body.append(wrapParams(e, null, className, "ev", "data"));
  1002 //            body.append(");\n");
  1003             body.append("}\n");
  1004         }
  1005         return true;
  1006     }
  1007 
  1008     private CharSequence wrapParams(
  1009         ExecutableElement ee, String id, String className, String evName, String dataName
  1010     ) {
  1011         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
  1012         StringBuilder params = new StringBuilder();
  1013         boolean first = true;
  1014         for (VariableElement ve : ee.getParameters()) {
  1015             if (!first) {
  1016                 params.append(", ");
  1017             }
  1018             first = false;
  1019             String toCall = null;
  1020             if (ve.asType() == stringType) {
  1021                 if (ve.getSimpleName().contentEquals("id")) {
  1022                     params.append('"').append(id).append('"');
  1023                     continue;
  1024                 }
  1025                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
  1026             }
  1027             if (ve.asType().getKind() == TypeKind.DOUBLE) {
  1028                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
  1029             }
  1030             if (ve.asType().getKind() == TypeKind.INT) {
  1031                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
  1032             }
  1033             if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
  1034                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
  1035             }
  1036 
  1037             if (toCall != null) {
  1038                 params.append(toCall);
  1039                 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
  1040                     params.append(dataName);
  1041                     params.append(", null");
  1042                 } else {
  1043                     if (evName == null) {
  1044                         final StringBuilder sb = new StringBuilder();
  1045                         sb.append("Unexpected string parameter name.");
  1046                         if (dataName != null) {
  1047                             sb.append(" Try \"").append(dataName).append("\"");
  1048                         }
  1049                         error(sb.toString(), ee);
  1050                     }
  1051                     params.append(evName);
  1052                     params.append(", \"");
  1053                     params.append(ve.getSimpleName().toString());
  1054                     params.append("\"");
  1055                 }
  1056                 params.append(")");
  1057                 continue;
  1058             }
  1059             String rn = fqn(ve.asType(), ee);
  1060             int last = rn.lastIndexOf('.');
  1061             if (last >= 0) {
  1062                 rn = rn.substring(last + 1);
  1063             }
  1064             if (rn.equals(className)) {
  1065                 params.append(className).append(".this");
  1066                 continue;
  1067             }
  1068             error(
  1069                 "@On method can only accept String named 'id' or " + className + " arguments",
  1070                 ee
  1071             );
  1072         }
  1073         return params;
  1074     }
  1075     
  1076     
  1077     private CharSequence wrapPropName(
  1078         ExecutableElement ee, String className, String propName, String propValue
  1079     ) {
  1080         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
  1081         StringBuilder params = new StringBuilder();
  1082         boolean first = true;
  1083         for (VariableElement ve : ee.getParameters()) {
  1084             if (!first) {
  1085                 params.append(", ");
  1086             }
  1087             first = false;
  1088             if (ve.asType() == stringType) {
  1089                 if (propName != null && ve.getSimpleName().contentEquals(propName)) {
  1090                     params.append('"').append(propValue).append('"');
  1091                 } else {
  1092                     error("Unexpected string parameter name. Try \"" + propName + "\".", ee);
  1093                 }
  1094                 continue;
  1095             }
  1096             String rn = fqn(ve.asType(), ee);
  1097             int last = rn.lastIndexOf('.');
  1098             if (last >= 0) {
  1099                 rn = rn.substring(last + 1);
  1100             }
  1101             if (rn.equals(className)) {
  1102                 params.append(className).append(".this");
  1103                 continue;
  1104             }
  1105             error(
  1106                 "@OnPrprtChange method can only accept String or " + className + " arguments",
  1107                 ee);
  1108         }
  1109         return params;
  1110     }
  1111     
  1112     private boolean isModel(TypeMirror tm) {
  1113         final Element e = processingEnv.getTypeUtils().asElement(tm);
  1114         if (e == null) {
  1115             return false;
  1116         }
  1117         for (Element ch : e.getEnclosedElements()) {
  1118             if (ch.getKind() == ElementKind.METHOD) {
  1119                 ExecutableElement ee = (ExecutableElement)ch;
  1120                 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
  1121                     return true;
  1122                 }
  1123             }
  1124         }
  1125         return models.values().contains(e.getSimpleName().toString());
  1126     }
  1127 
  1128     private void writeStringArray(List<String> strings, Writer w) throws IOException {
  1129         w.write("new String[] {\n");
  1130         String sep = "";
  1131         for (String n : strings) {
  1132             w.write(sep);
  1133             if (n == null) {
  1134                 w.write("    null");
  1135             } else {
  1136                 w.write("    \"" + n + "\"");
  1137             }
  1138             sep = ",\n";
  1139         }
  1140         w.write("\n  }");
  1141     }
  1142     
  1143     private void writeToString(Prprt[] props, Writer w) throws IOException {
  1144         w.write("  public String toString() {\n");
  1145         w.write("    StringBuilder sb = new StringBuilder();\n");
  1146         w.write("    sb.append('{');\n");
  1147         String sep = "";
  1148         for (Prprt p : props) {
  1149             w.write(sep);
  1150             w.append("    sb.append('\"').append(\"" + p.name() + "\")");
  1151                 w.append(".append('\"').append(\":\");\n");
  1152             w.append("    sb.append(org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toJSON(prop_");
  1153             w.append(p.name()).append("));\n");
  1154             sep =    "    sb.append(',');\n";
  1155         }
  1156         w.write("    sb.append('}');\n");
  1157         w.write("    return sb.toString();\n");
  1158         w.write("  }\n");
  1159     }
  1160     private void writeClone(String className, Prprt[] props, Writer w) throws IOException {
  1161         w.write("  public " + className + " clone() {\n");
  1162         w.write("    " + className + " ret = new " + className + "();\n");
  1163         for (Prprt p : props) {
  1164             if (!p.array()) {
  1165                 boolean isModel[] = { false };
  1166                 boolean isEnum[] = { false };
  1167                 boolean isPrimitive[] = { false };
  1168                 checkType(p, isModel, isEnum, isPrimitive);
  1169                 if (!isModel[0]) {
  1170                     w.write("    ret.prop_" + p.name() + " = prop_" + p.name() + ";\n");
  1171                     continue;
  1172                 }
  1173                 w.write("    ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
  1174             } else {
  1175                 w.write("    ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
  1176             }
  1177         }
  1178         
  1179         w.write("    return ret;\n");
  1180         w.write("  }\n");
  1181     }
  1182 
  1183     private String inPckName(Element e) {
  1184         StringBuilder sb = new StringBuilder();
  1185         while (e.getKind() != ElementKind.PACKAGE) {
  1186             if (sb.length() == 0) {
  1187                 sb.append(e.getSimpleName());
  1188             } else {
  1189                 sb.insert(0, '.');
  1190                 sb.insert(0, e.getSimpleName());
  1191             }
  1192             e = e.getEnclosingElement();
  1193         }
  1194         return sb.toString();
  1195     }
  1196 
  1197     private String fqn(TypeMirror pt, Element relative) {
  1198         if (pt.getKind() == TypeKind.ERROR) {
  1199             final Elements eu = processingEnv.getElementUtils();
  1200             PackageElement pckg = eu.getPackageOf(relative);
  1201             return pckg.getQualifiedName() + "." + pt.toString();
  1202         }
  1203         return pt.toString();
  1204     }
  1205 
  1206     private String checkType(Prprt p, boolean[] isModel, boolean[] isEnum, boolean[] isPrimitive) {
  1207         TypeMirror tm;
  1208         try {
  1209             String ret = p.typeName(processingEnv);
  1210             TypeElement e = processingEnv.getElementUtils().getTypeElement(ret);
  1211             if (e == null) {
  1212                 isModel[0] = true;
  1213                 isEnum[0] = false;
  1214                 isPrimitive[0] = false;
  1215                 return ret;
  1216             }
  1217             tm = e.asType();
  1218         } catch (MirroredTypeException ex) {
  1219             tm = ex.getTypeMirror();
  1220         }
  1221         tm = processingEnv.getTypeUtils().erasure(tm);
  1222         isPrimitive[0] = tm.getKind().isPrimitive();
  1223         final Element e = processingEnv.getTypeUtils().asElement(tm);
  1224         final Model m = e == null ? null : e.getAnnotation(Model.class);
  1225         
  1226         String ret;
  1227         if (m != null) {
  1228             ret = findPkgName(e) + '.' + m.className();
  1229             isModel[0] = true;
  1230             models.put(e, m.className());
  1231         } else if (findModelForMthd(e)) {
  1232             ret = ((TypeElement)e).getQualifiedName().toString();
  1233             isModel[0] = true;
  1234         } else {
  1235             ret = tm.toString();
  1236         }
  1237         TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
  1238         enm = processingEnv.getTypeUtils().erasure(enm);
  1239         isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
  1240         return ret;
  1241     }
  1242     
  1243     private static boolean findModelForMthd(Element clazz) {
  1244         if (clazz == null) {
  1245             return false;
  1246         }
  1247         for (Element e : clazz.getEnclosedElements()) {
  1248             if (e.getKind() == ElementKind.METHOD) {
  1249                 ExecutableElement ee = (ExecutableElement)e;
  1250                 if (
  1251                     ee.getSimpleName().contentEquals("modelFor") &&
  1252                     ee.getParameters().isEmpty()
  1253                 ) {
  1254                     return true;
  1255                 }
  1256             }
  1257         }
  1258         return false;
  1259     }
  1260 
  1261     private Iterable<String> findParamNames(Element e, String url, StringBuilder assembleURL) {
  1262         List<String> params = new ArrayList<>();
  1263 
  1264         for (int pos = 0; ;) {
  1265             int next = url.indexOf('{', pos);
  1266             if (next == -1) {
  1267                 assembleURL.append('"')
  1268                     .append(url.substring(pos))
  1269                     .append('"');
  1270                 return params;
  1271             }
  1272             int close = url.indexOf('}', next);
  1273             if (close == -1) {
  1274                 error("Unbalanced '{' and '}' in " + url, e);
  1275                 return params;
  1276             }
  1277             final String paramName = url.substring(next + 1, close);
  1278             params.add(paramName);
  1279             assembleURL.append('"')
  1280                 .append(url.substring(pos, next))
  1281                 .append("\" + ").append(paramName).append(" + ");
  1282             pos = close + 1;
  1283         }
  1284     }
  1285 
  1286     private static Prprt findPrprt(Prprt[] properties, String propName) {
  1287         for (Prprt p : properties) {
  1288             if (propName.equals(p.name())) {
  1289                 return p;
  1290             }
  1291         }
  1292         return null;
  1293     }
  1294 
  1295     private boolean isPrimitive(String type) {
  1296         return 
  1297             "int".equals(type) ||
  1298             "double".equals(type) ||
  1299             "long".equals(type) ||
  1300             "short".equals(type) ||
  1301             "byte".equals(type) ||
  1302             "float".equals(type);
  1303     }
  1304 
  1305     private static Collection<String> findDerivedFrom(Map<String, Collection<String>> propsDeps, String derivedProp) {
  1306         Set<String> names = new HashSet<>();
  1307         for (Map.Entry<String, Collection<String>> e : propsDeps.entrySet()) {
  1308             if (e.getValue().contains(derivedProp)) {
  1309                 names.add(e.getKey());
  1310             }
  1311         }
  1312         return names;
  1313     }
  1314     
  1315     private Prprt[] createProps(Element e, Property[] arr) {
  1316         Prprt[] ret = Prprt.wrap(processingEnv, e, arr);
  1317         Prprt[] prev = verify.put(e, ret);
  1318         if (prev != null) {
  1319             error("Two sets of properties for ", e);
  1320         }
  1321         return ret;
  1322     }
  1323     
  1324     private static class Prprt {
  1325         private final Element e;
  1326         private final AnnotationMirror tm;
  1327         private final Property p;
  1328 
  1329         public Prprt(Element e, AnnotationMirror tm, Property p) {
  1330             this.e = e;
  1331             this.tm = tm;
  1332             this.p = p;
  1333         }
  1334         
  1335         String name() {
  1336             return p.name();
  1337         }
  1338         
  1339         boolean array() {
  1340             return p.array();
  1341         }
  1342 
  1343         String typeName(ProcessingEnvironment env) {
  1344             try {
  1345                 return p.type().getName();
  1346             } catch (IncompleteAnnotationException | AnnotationTypeMismatchException ex) {
  1347                 for (Object v : getAnnoValues(env)) {
  1348                     String s = v.toString().replace(" ", "");
  1349                     if (s.startsWith("type=") && s.endsWith(".class")) {
  1350                         return s.substring(5, s.length() - 6);
  1351                     }
  1352                 }
  1353                 throw ex;
  1354             }
  1355         }
  1356         
  1357         
  1358         static Prprt[] wrap(ProcessingEnvironment pe, Element e, Property[] arr) {
  1359             if (arr.length == 0) {
  1360                 return new Prprt[0];
  1361             }
  1362             
  1363             if (e.getKind() != ElementKind.CLASS) {
  1364                 throw new IllegalStateException("" + e.getKind());
  1365             }
  1366             TypeElement te = (TypeElement)e;
  1367             List<? extends AnnotationValue> val = null;
  1368             for (AnnotationMirror an : te.getAnnotationMirrors()) {
  1369                 for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : an.getElementValues().entrySet()) {
  1370                     if (entry.getKey().getSimpleName().contentEquals("properties")) {
  1371                         val = (List)entry.getValue().getValue();
  1372                         break;
  1373                     }
  1374                 }
  1375             }
  1376             if (val == null || val.size() != arr.length) {
  1377                 pe.getMessager().printMessage(Diagnostic.Kind.ERROR, "" + val, e);
  1378                 return new Prprt[0];
  1379             }
  1380             Prprt[] ret = new Prprt[arr.length];
  1381             BIG: for (int i = 0; i < ret.length; i++) {
  1382                 AnnotationMirror am = (AnnotationMirror)val.get(i).getValue();
  1383                 ret[i] = new Prprt(e, am, arr[i]);
  1384                 
  1385             }
  1386             return ret;
  1387         }
  1388         
  1389         private List<? extends Object> getAnnoValues(ProcessingEnvironment pe) {
  1390             try {
  1391                 Class<?> trees = Class.forName("com.sun.tools.javac.api.JavacTrees");
  1392                 Method m = trees.getMethod("instance", ProcessingEnvironment.class);
  1393                 Object instance = m.invoke(null, pe);
  1394                 m = instance.getClass().getMethod("getPath", Element.class, AnnotationMirror.class);
  1395                 Object path = m.invoke(instance, e, tm);
  1396                 m = path.getClass().getMethod("getLeaf");
  1397                 Object leaf = m.invoke(path);
  1398                 m = leaf.getClass().getMethod("getArguments");
  1399                 return (List)m.invoke(leaf);
  1400             } catch (Exception ex) {
  1401                 return Collections.emptyList();
  1402             }
  1403         }
  1404     }
  1405     
  1406 }