Saturday, September 28, 2013

Entity annotations for GUI/Persistence

It is useful to use annotations to excludes hints information from the main source code and to avoid cluttering files which are used in program but not integrated in language source code file system.
Such files will become maintenance problem later.

There are mainly two usage cases for entity class.
  • GUI annotation. for instance, we may want to use customized label name other than default field name, we can attach such information as annotation for the getter definition.
  • Persistence mapping. This is essentially the same as JPA. we may want to more info how OR or DB scheme is associated with the entity.


CouchDB and generic DAO class

Generic GUI and CouchDB will be a good match.
Since Couch does not require scheme definition, it will be possible to develop generic  class to support CRUD features.

class DAO<T> {
 void  save(T t);
 void update(T t);
void delete(T t);
Iterable<T> query(String condition);

}

In particular, such application will be running on server side, we will not have constraint using mirror.

Actually I already created such library for DartExpenseServer mentioned in earlier post.
One of the issue was to support a mapping to/from Json object for the entity class.
In the application, this mapping methods were hand coded. But it is desireble to automate this step by a library.

Such Library should be easily implemented with mirror.

Restriction of Mirror in JS mode

I almost finished developing CRUD features for generic GUI library.



It just consists from Table and Form, and additional supporting components for Input.
Although there are more rooms for refinements, but it's working and written as I hoped.

The size of code is quite small, and is general enough.
For this type of library to be meaningful, it must be easily customized without touching the library itself.
In order to do so, it provides mechanism to inject features from outside.

Also it defines some basic patterns, like create, update to follow so that recursive operation would work properly.

But when I tried running it with javascript mode, I found out it does not run.
It looks like such mirror features are not yet supported in javascript mode.(there is a note on 5/2013).

Also there is an issue for the generated javascript code.
if we include dart:mirrors, the current code generates  7238 total methods!(impressive, I will never able to write such lines(methods) of javascript code)

Out of it,  5318 methods retained for use by dart:mirrors.
(But still my codes generated 2000 methods!)

So it seems not good idea to use dart:mirror for javascript mode.

One of the approach to overcome this restriction, and run generic GUI library application on browser is to avoid using mirror library itself.
This can be done if we generate an implementation class for some mirror like API  from concrete classes which is used in a application.

And we can also use two versions of implementations, one is for Dartium mode using the mirror library,  and the other is for javascript mode, the implementation classes are to be generated by a Dart application in Dartium mode.

Sunday, September 22, 2013

Generic GUI Library in Dart (Part 2)

In the Part 1 of this post, I used Polymer to create the web page, or to construct the page DOM object.(here is Part3)
In this revised version(generic-gui-v1), I removed such dependency to Polymer, and directly created DOM in Dart classes.



The major reason for doing this was to support component style GUI development.
In Polymer, or some other template mechanism based on some extension of HTML, the logic associated with such GUI element and actual code which would be implemented in a Dart class are separated, and basically things are getting messy.

Component will keep such DOM creation logic in itself. therefore we can construct a new component using the DOM associated with the sub components. This is the power of integrating them rather than delegating to a separate template files.

Another idea introduced here is automatic component management.
when components are created, implicitly corresponding tree node structure is created. This will provide better Query feature against components.
Although DOM can be found by Dart's query method for DOM, but we cannot identify a component associated with the DOM node. So this should be very useful.
On the other hand, if we have a component, we can have the corresponding DOM node immediately.

Following Component and TopComponent classes were introduced to support such abstract component structures.
The Component class will be used as super class of all UI component class like Table, Row etc.
It contains DOM element and its sub components.

The management of these structure are almost automatic, so each component class need not have to aware of these underlying structure building.

Fine point is the order of component creation and Element creation. To create a component, the parent component must be created first, but in order to create a DOM element, we need to create from the children.

So this means we cannot create element inside of component constructor.
But this will be taken care by init method in TopComponent. Namely this class is top level component, and only for this object, init is supported. The constructor of the subclass of TopComponent should invoke init in the end of the constructor.

 /*
 * Component should be created from top down, while DOM node should be created from bottom up
 */

abstract class Component {
  static int _gid = 0;
 
  final int id = _gid++;
  final List<String> classes;
  Element _element;
 
  final Component parent;
  final List<Component> children = [];
 
  Component(Component this.parent, List<String> this.classes) {
    if (parent != null) parent.children.add(this);
  }
 
  // DOM
  Element get element => (_element == null)?_element = _createElement():_element;
   
  // invoked from top level node.
  void _init() {
    children.forEach((Component child)=>child._init());
    _element = _createElement();
  }

  Element _createElement() =>
    createElement()
      ..id = "id-${id}"
      ..classes.addAll(classes);

  // this should not be invoked execpt from _init!
  Element createElement();
 
  //
  // utils
  //

  TopComponent topComponent() =>  (parent == null)?(this as TopComponent):parent.topComponent();
 
  Component findById(int id0) {
    if (id0 == id) {
      return this;
    }
    for (Component c in children) {
      Component c0 = c.findById(id0);
      if (c0 != null) {
        return c0;
      }
    }
    return null;
  }
 
  dynamic fold(var initialValue, dynamic combine(var previousValue, Component child)) =>
    children.fold(combine(initialValue, this), (pr, child) => child.fold(pr, combine));

}

abstract class TopComponent extends Component {
  static const String TOP_NODE = "g_top";
 
  TopComponent(): super(null, [TOP_NODE]);
 
  void init() {
    _init();
  }
}
The Table classes have been revised as followings:

class HeaderCell extends Component {
  static const String HCELL = "g_hcell";
  TableHeader tableHeader;
  Symbol symbol;
  Type type;
 
  // GUI
  String label;
 
  HeaderCell(TableHeader parent, this.symbol, this.type, this.label, {List<String> classes: const [HCELL]}): super(parent, classes), this.tableHeader = parent;
 
  factory HeaderCell.fromSymbol(TableHeader tableHeader, Symbol symbol, Type type) =>
    new HeaderCell(tableHeader, symbol, type, MirrorSystem.getName(symbol));
 
  RowCell defaultRowCell(Row row) => new RowCell(row, this);
 
  // DOM
  Element createElement() => new Element.td()..text = label;
}

class RowCell extends Component {
  static const String RCELL = "g_rcell";
  HeaderCell headerCell;
  Object value = null;
 
  RowCell(Row parent, this.headerCell, {Object init, List<String> classes : const [RCELL]}): super(parent, classes) {
    value = init;
  }
 
  // DOM
  Element createElement() => new Element.td()..text = (value == null)?'':value.toString();
}

class TableHeader<E> extends Component {
  static const String TH = "g_th";
  final Table<E> table;
  final List<HeaderCell> headerCells;
 
  TableHeader(Table parent, this.headerCells, {List<String> classes: const [TH]}): super(parent, classes), table = parent;
 
  factory TableHeader.fromType(Table parent, Type modelType) {
    var th = new TableHeader(parent, []);
    reflectClass(modelType).getters.forEach((Symbol symbol, MethodMirror md){
      //print(">> symbol: ${symbol}, returnType: ${(md.returnType as ClassMirror).reflectedType}");
      th.headerCells.add(new HeaderCell.fromSymbol(th, symbol, (md.returnType as ClassMirror).reflectedType));
    });
    return th;
  }
 
  // DOM
  Element createElement() => headerCells.fold(new Element.tag("thead"), (Element thead, HeaderCell hc)=>thead..nodes.add(hc.element));
}

class Row<E> extends Component {
  static const String TR = "g_tr";
  final Table<E> table;
  final E e;
  final List<RowCell> rowCells = [];

  Row(Table parent, this.e, {List<String> classes: const [TR]}): super(parent, classes), table = parent;
   
  factory Row.defaultRow(Table<E> _table) =>
    table.theader.headerCells.fold(new Row(table, null), (Row row, HeaderCell hc) => row..rowCells.add(hc.defaultRowCell(row)));
 
  factory Row.fromEntity(Table<E> table, E e) {
    InstanceMirror imirr = reflect(e);
    return table.theader.headerCells.fold(new Row(table, e), (Row row, HeaderCell hc) => row..rowCells.add(new RowCell(row, hc, init: imirr.getField(hc.symbol).reflectee)));
  }
 
  // DOM
  TableRowElement createElement() => rowCells.fold(new Element.tag("tr"), (TableRowElement row, RowCell rc)=>row..nodes.add(rc.element));
}

class Table<E> extends Component {
  static const String TABLE = "g_table";
  Type modelType;
  String name;
  TableHeader theader;
  final List<Row<E>> rows;
 
  Table(Component parent, this.modelType, {List<String>  classes: const [TABLE]}): super(parent, classes), rows = [];
 
  factory Table.fromModelType(Component parent, Type modelType) =>
    [new Table(parent, modelType)].fold(null, (p, tbl)=>tbl..theader = new TableHeader.fromType(tbl, modelType)); 
 
  //
  void newRow() => rows.add(new Row<E>.defaultRow(this));
 
  void addRow(Row<E> row) {
    // check row.tabel == this
    if (row.table != this) {
      print(">> addRow error");
      throw new Exception("Table<1>");
    }
    rows.add(row);
    element.nodes.add(row.element);
  }
 
  void addRowFromEntity(E e) => addRow(new Row<E>.fromEntity(this, e));
 
  void clear() {
    element.nodes.clear();
    element.nodes.add(theader.element);
    rows.clear();
  }
 
  void load(Iterable<E> es) {
    clear();
    es.forEach(addRowFromEntity);
  }
 
  // DOM
  Element createElement() => rows.fold(new Element.tag("table"), (Element tab, Row row)=>tab..nodes.add(row.element));
}
This is the sample application using these library.
 class AppController extends TopComponent {
  final DivElement _uiRoot;
  DivElement _content;
  DivElement _actions;
 
  Table<Expense> _table;
 
  AppController(this._uiRoot, {List<Expense> expenses}) {
    _table = new Table<Expense>.fromModelType(this, Expense);
    if (expenses != null) {
      _table.load(expenses);
    }
    init();
    _uiRoot.nodes.add(element);
  }

  Element createElement() =>
    new Element.tag("div")
      ..classes.add("section")
      ..nodes.add(new Element.html("<header class='section'>Generic Table</header>"))
      ..nodes.add(_content = new Element.tag("div")
        ..nodes.add(_table.element))
      ..nodes.add(_actions = new Element.tag("div")
        ..id = "actions"
        ..classes.add("section"))
      ..nodes.add(new Element.html("<footer class='section' id='footer'></footer>"));
 
  Table<Expense> get table => _table;
}

main() {
  List<Expense> expenses = [
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random()];
  Element uiContainer = document.query("#generic_table");
  AppController app = new AppController(uiContainer);
  app.table.load(expenses);

}
 The html file is very simple.
<html>
  <head>
    <meta charset="utf-8">
    <title>Sample app</title>
    <link rel="stylesheet" href="generic_table.css">
  </head>
  <body>
    <div id="generic_table"></div>
    <script type="application/dart" src="generic_table.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>


Saturday, September 21, 2013

Generic GUI library in Dart (Part 1)

Most of Web application depend on  table view, and edit view.
Often these are related to database application.

These views are used to support CRUD operation.
The table view is essentially for query, to find a data.
The editor view is to create a new entity or edit existing entity.
Often these entities  reside in a remote database.

To achieve these thing, like Ruby on Rails, often code generation approach has been used. But this approach is not component oriented since generating code make it difficult to reuse codes

The better approach would be to develop generic GUI library.

The reason why this has not been used had several reasons coming from language short coming.

In order to support this approach, following language features are essential.
  • Class
  • Generics
  • Reflection
  • Annotation
  • direct DOM manipulation
Essentially, Java cannot  support direct DOM manipulation, and JavaScript doe not have all of class related feature as standard language feature.

So only Dart can support all of this.
In Java, it might be possible to use Pivot and running with Applet on browser.
But applet is not popular these days, and if we have more suitable language for web application, this approach is not so attractive. The Dart's concise syntax, and server side usage make it much simpler to develop web application than Java.

So I developed  first such application(generic-table-v1) in Dart.
Since this is rather primitive level of implementation, it will be easier to understand the basic of this approach.
In order to add more feature, it will be better not to rely on polymer.
These improvement will be the next step.

The following short code is all we need to have a class specific table view.
 main() {
  List<Expense> expenses = [
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random()];
  Table table = new Table.fromModelType(Expense)
    ..load(expenses)
    ..newRow()
    ;
 
  query('#tmpl').model = table;
}
and I used polymer to create corresponding template:
  <body>
    <h1>Generic table</h1>
    <template id="tmpl" bind>
      <table border="1"> 
        <tr>    
          <th template repeat="{{ theader.headerCells }}">
            {{label}}
          </th> 
        </tr>         
        <tr template repeat="{{ rows }}">
          <td template repeat="{{ rowCells }}"><input type="text" value="{{value}}"></td>
        </tr>
      </table>
    </template> 
    <script type="application/dart" src="generic_table.dart"></script>
  </body>
This is the shapshot of this table.


The point of this approach is if we have some entity class like Expense, we just need to pass this class to have different Table view.

A specific table view associated with an entity class is  implemented by the same generic class. So no code generation are required.
Even if we have 500 of entity tables, we still don't need to generate 500 of JSP files or something similar. just a single generic class can handle all of these cases.
This would reduce the build time as well as code size.

But the main advantage of this approach  is to allow developing component based GUI library.  If properly designed, subcomponents of table, like row, cell may be specialized using separate GUI libraries.
Reusing code will be as usual as normal software development.

This Table class was written to prove the feasibility of generic GUI approach in Dart,  but there are more potentials in this approach to enhance sophisticated interaction between GUI DOM node operations,  entities and GUI views. Also these can be combined with backend server as well.

 Since the code is still manageable size, I will show all the codes.
 library generic_gui;

import 'dart:mirrors';


class Cell {
}


class HeaderCell extends Cell {

  TableHeader tableHeader;
  String label;
  Type type;
  Symbol symbol;
 
  HeaderCell(this.tableHeader, this.symbol, this.type, this.label);
 
  factory HeaderCell.fromSymbol(TableHeader tableHeader, Symbol symbol, Type type) =>
    new HeaderCell(tableHeader, symbol, type,MirrorSystem.getName(symbol));
 
  RowCell defaultRowCell() => new RowCell(this);
}

class RowCell extends Cell {

  HeaderCell headerCell;
  Object value = null;
  RowCell(this.headerCell, {Object initv}) {
    if (initv != null) {
      value = initv;
    } else {
      // we may introduce  default value assignment depending on the type.
    }
  }
}

class TableHeader<E> {

  Table<E> table;
  List<HeaderCell> headerCells;
 
  TableHeader(this.headerCells);
 
  factory TableHeader.fromType(Type modelType) {
    var th = new TableHeader([]);
    reflectClass(modelType).getters.forEach((Symbol symbol, MethodMirror md){
      th.headerCells.add(new HeaderCell.fromSymbol(th, symbol, (md.returnType as ClassMirror).reflectedType));
    });
    return th;
  }
}

class Row<E> {

  final Table<E> _table;
  final E e;
  final List<RowCell> rowCells;

  Row(this._table, this.e, this.rowCells);

    
// I like this kind of single expression style. 
factory Row.defaultRow(Table<E> _table) => new Row(_table, null,

    _table.theader.headerCells.fold([], (rowCells, HeaderCell hcell)=>rowCells..add(hcell.defaultRowCell())));
// '..' syntax is perfect match with this fold function.
  // Sometimes, we need to declare variable, then we must use block statement, but if Dart supports FAMOUS 'let' syntax of ML(or F#), then this can be written as a single expression, s.t. ' => let var imirr = ... in ... end;'
  factory Row.fromEntity(Table<E> table, E e) {
    InstanceMirror imirr = reflect(e);
    return new Row(table, e, table.theader.headerCells.fold([], (cells, HeaderCell hc)=>
        cells..add(new RowCell(hc, init: imirr.getField(hc.symbol).reflectee))));
  }

  Table get table => _table;

}

class Table<E> {

  Type modelType;
  String name;
  TableHeader _theader;
  final List<Row<E>> rows;
  List<E> _es;
 
  Table(this.modelType, this._theader): rows = [], _es = [] {
    _theader.table = this;
  }
 
  factory Table.fromModelType(Type modelType) {
    TableHeader th = new TableHeader.fromType(modelType);
    Table tbl = new Table(modelType, th);
    th.table = tbl;
    return tbl;
  }
   
  TableHeader get theader => _theader;
 
  void newRow() => rows.add(new Row<E>.defaultRow(this));
 
  void addRow(Row<E> row) {
    // check row.tabel == this
    if (row.table != this) {
      print(">> addRow error");
      throw new Exception("Table<1>");
    }
    rows.add(row);
  }
 
  Row<E> addRowFromEntity(E e) {
    addRow(new Row<E>.fromEntity(this, e));
  }
  // there should be more methods like these, but they should be associated with DOM operation.
  void clear() {
    _es.clear();
    rows.clear();
  }
 
  load(Iterable<E> es) {
    clear();
    _es.addAll(es);
    for (E e in es) {
      addRowFromEntity(e);
    }
  }
}

//

String getMethodName(MethodMirror md) =>MirrorSystem.getName(md.simpleName);

List<Symbol> getSymbols(Type t) => reflectClass(t).getters.values.

  fold([], (List symbs, MethodMirror mtd) =>(mtd.isGetter)?(symbs..add(mtd.simpleName)):symbs);


Polymer for component based Web development?

I investigated polymer.
First I tried all samples in dart-plolymer-dart-examples.

The thing I found was the last half of samples are not working.
The typical error is:

Exception: The null object does not have a method 'callSync'.

NoSuchMethodError : method not found: 'callSync'
Receiver: null
Arguments: [GrowableObjectArray len:0]
  Object.noSuchMethod (dart:core-patch/object_patch.dart:20:25)
  context (dart:js:9:58)
  PolymerElement._shimCss (package:polymer/polymer_element.dart:185:16)
  PolymerElement._initShadowRoot (package:polymer/polymer_element.dart:162:15)
  PolymerElement.created (package:polymer/polymer_element.dart:125:20)
  _initCustomElement (package:custom_element/custom_element.dart:584:18)
  registerCustomElement (package:custom_element/custom_element.dart:53:25)
  registerPolymerElement (package:polymer/polymer_element.dart:27:24)
  _loadLibrary (package:polymer/polymer.dart:109:31)
  initPolymer.<anonymous closure> (package:polymer/polymer.dart:63:19)
Essentially this  problem has been introduced after dart.js removed interop.js.
So I needed to add <script src="packages/browser/interop.js"></script> for most of index.html as following:

    <script src='packages/polymer/boot.js'></script>
    <script src="packages/browser/interop.js"></script>
Since boot.js is always used, it would be simpler to include this in boot.js.

After this fix, I still observered two errors, which I will append to teh end of this post.

Polymer is several useful features like model binding and jps like control extentions in html.
So basic idea is actually closer to traditional extended html approach.

Some interesting feature is  synchronization mechanism through Observable.(using annotation for observable field).
Although it looked good, but when I used this feature in dynamically allocated entity, it did not work.

So overall, I was a bit dis illusioned for polymer.
Essentially, these approach may be useful for more static type of application.
But if we want to do something more dynamic and/or generic, polymer will not be useful approach.
For instance, Apache Pivot has it own XML like GUI definition language(this seems sort of popular approach these days). it has similar problem as Polymer for generic GUI class development.

Still Polymer be useful to package such a generic library even that library may not be using Polymer.

But if we want to take more programatical approach for GUI development, it may not be so useful at all.

==========================================
[interop_with_polymer_elements]
Uncaught TypeError: Cannot call method 'querySelectorAll' of undefined
  inlinePolymerElements (http://127.0.0.1:3030/opt/dart-workspace/dart-polymer-dart-examples/web/interop_with_polymer_elements/packages/polymer/boot.js:83:25)
  inlinePolymerElements (http://127.0.0.1:3030/opt/dart-workspace/dart-polymer-dart-examples/web/interop_with_polymer_elements/packages/polymer/boot.js:92:7)
   ....
==========================================
[nested_templates]

Uncaught Error: EvalException: variable not found: name in 91145084
Stack Trace:
#0      Scope.[] (package:polymer_expressions/eval.dart:169:7)
#1      IdentifierObserver._updateSelf (package:polymer_expressions/eval.dart:406:19)
#2      ExpressionObserver._observe (package:polymer_expressions/eval.dart:252:16)
#3      Updater.visitExpression (package:polymer_expressions/eval.dart:268:15)
....

Saturday, September 14, 2013

Functional Program for compilers(language processors)

Compiler/Interpreter has been used since assembler/FORTRAN era.
It was one of most powerful software.
But the behavior is rather different from typical programs which takes a limited pattern of data structure as input and return  also limited pattern of data.
for instance typical method/function takes some data like int, and returns another object or data like if you put a coin to a vendor machine and push selection button, you get candy etc. quite mechanical.
On the other hand compiler can take million of line code code and generate something which can perform very complex thing as output, this is more like something only human can do.

the interesting nature is in compiler,  in the tree like data structure, each node is mapped to a closure recursively and the top node behavior can be constructed from these behaviors.
So this is quite good fit for functional programming language.
Often there are a but none standard interpretation between compiler and interpreter from none computer science oriented people.
for latter, interpreter mean tree traversing program, i.e, it take program(tree) as input and return some result.
The compiler mean it return some closure(function) from input program(tree), and no specific result is not yet given. the result can be only available by applying the function some context.
so if in compiler, we don't have to traverse program many times for different program inputs. just compile once and get function, and the different values can be obtained by just applying the function with different input values. in this function evaluation, no tree node data used.

for instance, a very simple compiler program will be as following:
typedef Object Code(RContext ctx);

class AddNode implements INode {
  INode node1;
  INode node2;

  Code compile(Context ctx) {
    Code c1 = node1.compile(ctx);
    Code c2 = node2.compile(ctx)
    return (RContext rctx)=>(add(c1(rctx), c2(rctx)));
} 

var addNode = new AddNode(new IntNode(1), new IntNode(2));
Context ctx = new Context();
Code code = addNode.compile(ctx);

RContext rctx = new RContext();
var v1 = code(ctx);
 In fact, Dart does not support overloading, so this will use overriding of methods(even if it supports overloading, this  overriding approach is better though).
Subsequently the metaphor is changed in object oriented way, i.e, a node object has a compile method which  generates a compiled closure.
 This  is actually a good example of usefulness of mixing  two object oriented approach and functional approach.(although it became a matter of course nowadays for javascript programmers, but early days in 80's, many people were not much interested in such impure approach. Probably their target application(e.g, 5th generation Hardware) were different. but from pragmatic programming point of view, this should have been more emphasized. Some Lisp dialects were actually advocated these things, but Lisp had too poor syntax to be accepted by normal people, so there were no impact for general programmers.

------------
There were  bit of digression,  but bottom line is Dart will assist to write such compiler like application in wide range.
These are the reason to have appropriate syntax to express a conceptual idea directly in a language without any technical transformation(see anonymous object in Java). I remember Gosling called Java as functional language since it supports anonymous object. I thought what a silly statement it was..

Also functional approach has also very good fit with asynchronous programming.
Since we need to generate a function which will be called later time. So this requires to generate a  functions from combining other functions to be executed in later time. (many Stream program depend on then method, which is essentially Future to Future function.)

Asynchronous approach and  Compilation can be also combined further to have a distributed compiler at fine grained level. This will be discussed in another post.