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