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