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