Tuesday, October 8, 2013

Dart's annotation

I refined the look and feel of sample app using Dart's annotation.

This feature is very useful for customizing a lot of thing without touching the code itself.
So there are quite a lot of area to use annotations.

The annotation mechanism of Dart is quit easy to use, it is also part of dart:mirrors. So in order to use this on browser, we still need to use my portable_mirror library(I extended the API for this).

The things I have done is:
  1. Table
    • remove id and rev column from table
    • change expenseType to type
       
  2. Form
    • disable id, rev text input
These are specified by annotation for the getter  in Expense class.
Also I fixed table so that it has max height and can use scroll.
So this GUI is now looks beter. but it will be useful to support more annotations to adjust look and feel such as ordering specification. location to put text etc.

class Expense  {
  ....
  
  @GUI_Table(invisible: true)
  @GUI_Form(disabled: true)
  String get id => _id;
  void set id(String i) { _id = i; }
  
  @GUI_Table(invisible: true)
  @GUI_Form(disabled: true)
  String get rev => _rev;
  void set rev(String value) { _rev = value; }
  
  @GUI_Table(label: "type")
  ExpenseType get expenseType => _type;
  void set expenseType(ExpenseType i) { _type = i; }
  
  ...
}

Sunday, October 6, 2013

Reflective JsonMapper (Part 3)

Originally I planed to use generics, but now it is better not to call it generic, but we call it reflective.
  
I completed the support of List(and Map) property in Entity class, and this works for both dynamic(with dart:mirrors lib for Dart VM) and static mode(for javascript).
But I haven't tested on javascript mode yet, but it should work. Also I haven't tested the map case. I will do it later.
This version was committed to Github.

Following is the sample code to show the support of List field in a class.

class A {
  int _i = 0;
  List<B> _bs = [];
  
  A(this._i, this._bs);
  factory A.create() => new A(111, []);
  
  int get i => _i;
  void set i(int ii) { _i == ii; }
  
  List<B> get bs => _bs;
  void set bs(List<B> bs) {_bs = bs; }
}

class B {
  String _s = 'zz';
  B(this._s);
  factory B.create() => new B('ss');
  String get s => _s;
  void set s(String ss) { _s == ss; }
}

test_simple_model() {
      A a = new A.create()..i = 10
        ..bs.add(new B.create()..s = "vvv")
        ..bs.add(new B.create()..s = "eee");
      
      String json = sampleJsonMapper.toJson(a);
      print(">>A@1 test_toJson json: ${json}");
      
      A a1 = sampleJsonMapper.fromJson(A, json);
      print(">>A@2 test_Json a1: ${a1}");
}

And the output of execution:
>>A@1 test_toJson json: {"i": 111,"bs": [{"s": "ss"},{"s": "ss"}]}
>> obj: Instance of 'A'
>>A@2 test_Json a1: Instance of 'A'
>> json: {"i": 10,"bs": [{"s": "ss"},{"s": "vv"}]}

Actually the support of generic type property was a bit difficult due to some confusing behavior of reflectedType property of ClassMirror. And some irreversible operation of types and  typeArguments behavior.

But by keeping type instead of extracting from ClassMirror, I could avoid the current restriction of Miror library. Probably Dart is still early stage, such mirror behavior should be refined.

Following are the problems I found:

1) why we cannot do followings:

var t1 = List<A>;
var cmirr = reflectClass(List<A>);

while we can do for none generic class:
car t = A;
var cmirr = reflectClass<A);

2) how can I create ClassMirror object which has reflectedType.
if we create CirrorClass through reflectClass(new List<B>().runtimeType),
it does not have reflectedType. but if we get ClassMirror from  bs of  A, it has a reflectedType. So there should be some way to create Mirror class which has reflectedType.

3) the reflectClass<List<A>) has all information to make cmirror to have reflectedType(since argumentType A is provided).
It should return ClassMirror with reflectedType.
I think this is very inconvenient behavior, and should be called a bug.

library dart_generics_test;

import 'dart:mirrors';

class A {
  int _i = 0;
  List<B> _bs = [];
  
  int get i => _i;
  void set i(int ii) { _i == ii; }
  
  List<B> get bs => _bs;
  void set bs(List<B> bs) {_bs = bs; }
}

class B {
  String _s = 'zz';
  
  String get s => _s;
  void set s(String ss) { _s == ss; }
}

test_generics() {
  {
    /*
    ClassMirror immir0 = reflectClass(List<B>); // <== this cannot be compiled!
    Type t0 = immir0.reflectedType;
    print(">> ${t0}");
    */
    
    // following code is to get a Type of List<B>, a work around to avoid above problem.  
    InstanceMirror immir = reflect(new List<B>());
    Type t = immir.type.reflectedType;
    print(">>1.1 ${t}");
    
    /*
    ClassMirror cmirr = reflectClass(t);
    Type t2 = cmirr.reflectedType; // here t2 == t, but it throws exception
    print(">>1.2 ${t2}");
    */
  /*
   * Unhandled exception:
Unsupported operation: Declarations of generics have no reflected type
#0      _LocalClassMirrorImpl.reflectedType (dart:mirrors-patch/mirrors_impl.dart:304:7)
#1      test_generics (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:76:21)
#2      main (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:81:16)
   * 
   */
  }

  {
    Type t1 = new B("nn").runtimeType;
    print(">>2.1 ${t1}");
  
    ClassMirror cmirr1 = reflectClass(t1);
    Type t2 = cmirr1.reflectedType; // this is ok
    print(">>2.1 ${t2}");
  }

  {
    Type t1 = new List<B>().runtimeType; // return List<B>
    print(">>3.1 t1: ${t1}");
  
    ClassMirror cmirr1 = reflectClass(t1);
    Type t2 = cmirr1.runtimeType; // return _LocalClassMirrorImpl
    print(">>3.2 t2: ${t2}"); 
    print(">>3.3 cmirr1.hasReflectedType: ${cmirr1.hasReflectedType}"); 
    
    Type t4 = cmirr1.reflectedType; // here it should be t4 == t0, but it throws exception
    print(">>3.3 t4: ${t4}");
  }

  {
    ClassMirror cmirr = reflectClass(A);
    cmirr.getters.forEach((k, MethodMirror md){
      Type tm = (md.returnType as ClassMirror).reflectedType; // this is OK
      print(">>4.1 k: ${k}, tm: ${tm}");
    });
  }
}

main() {
  test_generics();
}

Blogger tip: how to use pretty print

I did not like embedding dart code using quote.
So I a bit investigated to support pretty print in blogger.

Following is the way I found:

  •  open template HTML edit
    add following code just before </head> 
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
    • Blogger Template Designer->Adbanced->Add CSS

      Add following codes:
      pre {
      overflow: auto;
      width: 580px;
      
       white-space: pre-wrap;       /* css-3 */
       white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
       white-space: -pre-wrap;      /* Opera 4-6 */
       white-space: -o-pre-wrap;    /* Opera 7 */
       word-wrap: break-word;       /* Internet Explorer 5.5+ */
      }
      
      /* https://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css */
      
      .prettyprint {
          background: #EEE;
      }
      
      
    •  when you want to embed code, use HTML view, and put code snippets in:
      <pre class="prettyprint lang-dart">Code!</pre>
    https://code.google.com/p/google-code-prettify/wiki/GettingStarted

    http://google-code-prettify.googlecode.com/svn/trunk/README.html

    http://google-code-prettify.googlecode.com/svn/trunk/styles/index.html

    But there is an issue for <, >. they will be recognized as special characters(by html parser?), and enclosed parts are not shown. So if we have these characters, we need to replace them with &lt;, &gt; respectively(i.e, in Code).
    This should be handled by run_prettify.js though.

    GUI action design pattern

    The sample app(CRUDView) class is not so clean with respect to the implementation of how mouse action would trigger window state changes, like some button are disabled and the others are enabled etc.

    Each component class should not have to know anything except what they suppose to do, i.e, some state change.

    All the GUI action should be understood as state transition.
     if we append listener to each node's listener, that is still bad.

    the controlling logic is tightly associated with specific GUI action.
    But what the mouse action will change is the state and that state change is the reason for the logic of GUI change.

    so the logic should be centered around the state change.

    for instance, following code may describe the state transition of each mouse click for the buttons.

    state('a1')..>state('a2')['load'] = load
        ..>state('s3')['save'] = save;
    
    state('a2')..>state('a2')['clear'] = clear
        ..>state('s3')['edit'] = edit;
    

    That way, we see the real logic behind the GUI action. often such a  state is not explicitly expressed in the application code as in the current CRUDView code. and action methods are called from many places associated with buttons.
    That messy way should be avoided.


    GenericType spec in test code

    It is always useful if we have a good unit tests to understand the language spec in details. It is much easier to understand from concrete examples than hight level abstract and often ambiguous description.

    For dart mirror, the code API is not useful, and there are not much detailed explanation of mirror features, so I checked   /dart/tests/lib/mirrors/ folder.

    following test code is useful to understand mirror for generic classes.


    // Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
    // for details. All rights reserved. Use of this source code is governed by a
    // BSD-style license that can be found in the LICENSE file.
    
    library test.type_arguments_test;
    
    import 'dart:mirrors';
    
    import 'package:expect/expect.dart';
    
    class A<T> {}
    class B extends A {}            // Same as class B extends A<dynamic>.
    class C extends A<num, int> {}  // Same as class C extends A<dynamic>.
    class D extends A<int> {}
    class E<S> extends A<S> {}
    class F<R> extends A<int> {}
    class G {}
    class H<A,B,C> {}
    
    typeParameters(mirror, parameterNames) {
      Expect.listEquals(parameterNames.map((n) => new Symbol(n)).toList(),
                        mirror.typeVariables.keys.toList());
    }
    
    typeArguments(mirror, argumentMirrors) {
      Expect.listEquals(argumentMirrors,
                        mirror.typeArguments.values.toList());
      if (!mirror.isOriginalDeclaration) {
        Expect.listEquals(mirror.typeVariables.keys.toList(),
                          mirror.typeArguments.keys.toList());
      }
    }
    
    main() {
      // Declarations.
      typeParameters(reflectClass(A), ['T']);
      typeParameters(reflectClass(B), []);
      typeParameters(reflectClass(C), []);
      typeParameters(reflectClass(D), []);
      typeParameters(reflectClass(E), ['S']);
      typeParameters(reflectClass(F), ['R']);
      typeParameters(reflectClass(G), []);
    
      typeArguments(reflectClass(A), []);
      typeArguments(reflectClass(B), []);
      typeArguments(reflectClass(C), []);
      typeArguments(reflectClass(D), []);
      typeArguments(reflectClass(E), []);
      typeArguments(reflectClass(F), []);
      typeArguments(reflectClass(G), []);
    
      Expect.isTrue(reflectClass(A).isOriginalDeclaration);
      Expect.isTrue(reflectClass(B).isOriginalDeclaration);
      Expect.isTrue(reflectClass(C).isOriginalDeclaration);
      Expect.isTrue(reflectClass(D).isOriginalDeclaration);
      Expect.isTrue(reflectClass(E).isOriginalDeclaration);
      Expect.isTrue(reflectClass(F).isOriginalDeclaration);
      Expect.isTrue(reflectClass(G).isOriginalDeclaration);
    
      Expect.equals(reflectClass(A), reflectClass(A).originalDeclaration);
      Expect.equals(reflectClass(B), reflectClass(B).originalDeclaration);
      Expect.equals(reflectClass(C), reflectClass(C).originalDeclaration);
      Expect.equals(reflectClass(D), reflectClass(D).originalDeclaration);
      Expect.equals(reflectClass(E), reflectClass(E).originalDeclaration);
      Expect.equals(reflectClass(F), reflectClass(F).originalDeclaration);
      Expect.equals(reflectClass(G), reflectClass(G).originalDeclaration);
    
      // Instantiations.
      typeParameters(reflect(new A<num>()).type, ['T']);
      typeParameters(reflect(new B<num>()).type, []);
      typeParameters(reflect(new C()).type, []);
      typeParameters(reflect(new D()).type, []);
      typeParameters(reflect(new E()).type, ['S']);
      typeParameters(reflect(new F<num>()).type, ['R']);
      typeParameters(reflect(new G()).type, []);
      typeParameters(reflect(new H()).type, ['A', 'B', 'C']);
    
      var numMirror = reflectClass(num);
      var dynamicMirror = currentMirrorSystem().dynamicType;
      typeArguments(reflect(new A<num>()).type, [numMirror]);
      typeArguments(reflect(new A<dynamic>()).type, [dynamicMirror]);
      typeArguments(reflect(new A()).type, [dynamicMirror]);
      typeArguments(reflect(new B()).type, []);
      typeArguments(reflect(new C()).type, []);
      typeArguments(reflect(new D()).type, []);
      typeArguments(reflect(new E<num>()).type, [numMirror]);
      typeArguments(reflect(new E<dynamic>()).type, [dynamicMirror]);
      typeArguments(reflect(new E()).type, [dynamicMirror]);
      typeArguments(reflect(new F<num>()).type, [numMirror]);
      typeArguments(reflect(new F<dynamic>()).type, [dynamicMirror]);
      typeArguments(reflect(new F()).type, [dynamicMirror]);
      typeArguments(reflect(new G()).type, []);
      typeArguments(reflect(new H<dynamic, num, dynamic>()).type,
          [dynamicMirror, numMirror, dynamicMirror]);
    
      Expect.isFalse(reflect(new A<num>()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new B()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new C()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new D()).type.isOriginalDeclaration);
      Expect.isFalse(reflect(new E<num>()).type.isOriginalDeclaration);
      Expect.isFalse(reflect(new F<num>()).type.isOriginalDeclaration);
      Expect.isTrue(reflect(new G()).type.isOriginalDeclaration);
      Expect.isFalse(reflect(new H()).type.isOriginalDeclaration);
    
      Expect.equals(reflectClass(A),
                    reflect(new A<num>()).type.originalDeclaration);
      Expect.equals(reflectClass(B),
                    reflect(new B()).type.originalDeclaration);
      Expect.equals(reflectClass(C),
                    reflect(new C()).type.originalDeclaration);
      Expect.equals(reflectClass(D),
                    reflect(new D()).type.originalDeclaration);
      Expect.equals(reflectClass(E),
                    reflect(new E<num>()).type.originalDeclaration);
      Expect.equals(reflectClass(F),
                    reflect(new F<num>()).type.originalDeclaration);
      Expect.equals(reflectClass(G),
                    reflect(new G()).type.originalDeclaration);
      Expect.equals(reflectClass(H),
                    reflect(new H()).type.originalDeclaration);
    
      Expect.notEquals(reflect(new A<num>()).type,
                       reflect(new A<num>()).type.originalDeclaration);
      Expect.equals(reflect(new B()).type,
                    reflect(new B()).type.originalDeclaration);
      Expect.equals(reflect(new C()).type,
                    reflect(new C()).type.originalDeclaration);
      Expect.equals(reflect(new D()).type,
                    reflect(new D()).type.originalDeclaration);
      Expect.notEquals(reflect(new E<num>()).type,
                       reflect(new E<num>()).type.originalDeclaration);
      Expect.notEquals(reflect(new F<num>()).type,
                       reflect(new F<num>()).type.originalDeclaration);
      Expect.equals(reflect(new G()).type,
                    reflect(new G()).type.originalDeclaration);
      Expect.notEquals(reflect(new H()).type,
                       reflect(new H()).type.originalDeclaration);
    
      // Library members are all uninstantaited generics or non-generics.
      currentMirrorSystem().libraries.values.forEach((libraryMirror) {
        libraryMirror.classes.values.forEach((classMirror) {
          // TODO(12282): Deal with generic typedefs.
          if (classMirror is! TypedefMirror) {
            Expect.isTrue(classMirror.isOriginalDeclaration);
            Expect.equals(classMirror, classMirror.originalDeclaration);
          }
        });
      });
    }
    

    Generic Class is not a first class citizen?

    I tried to complete fromJson implementation, a method to instantiate an object of given type from its serialized json string, then I found some interesting limitation of Dart language.
    I guess this is not planed feature, but something which are to be improved later.

    for instance, the support of getClass in Java is not supported in dart now. (this will be obj.type getter). but I read a proposal, this is going to be supported.

    there are two issues.

    if we have a function taking Type value as the argument,  like f(A), this works as expected. but we cannot write f(A<B>)!.
    also Type a = A<B> is not allowed.
    So in a sense, generic class is not a first class citizen in Dart now.

    Also similar, but more strange problem is following:

      InstanceMirror immir = reflect(new List<B>());
      Type t = immir.type.reflectedType;
      print(">> ${t}");
      ClassMirror mirr = reflectClass(t);
      print("2>> ${mirr.reflectedType}");
    

    Since we cannot use List<B>, we need to create this type by reflect(new List<B>()).type.reflectedType. and this will be shown as List<B>.
    but if we use this type to create ClassMirror, the getter call, mirr.reflectedType will cause runtime error.

    >> List<B>
    Unhandled exception:
    Unsupported operation: Declarations of generics have no reflected type
    #0      _LocalClassMirrorImpl.reflectedType (dart:mirrors-patch/mirrors_impl.dart:304:7)
    #1      test_generics (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:77:21)
    #2      main (file:///opt/dart-workspace/reflective_web_dev_kit/sample_app/bin/sample_json_mapper_test.dart:82:16)
    

    This is actually not good for portable_mirror librray.
    Since creating Type through dart:mirrors library is not allows in javascript mode.

    For example, couchdb_client_dao(in browser side) need to convert json string of list to list of entity. So ideally, this should be parsed by jsonMapper's fromJson. and it requires type value in the first argument, e.g, fromJson(List<modelType>, json).

    This issue would not be limited to javascript mode. but it would also affect to the Dart VM mode.
    So in order to avoid this problem in DartVM mode(as well as JavaScript mode), it will be necessary to avoid using Type. Instead, it should always use IClassMirror.

    Although that may fix the jsonMapper, but this issue may influence in entire application
    So one approach is not to worry about the generic type case(including list/map), and wait until this mirror issue is fixed..

    Saturday, October 5, 2013

    Github: Reflective Web dev kit

    Since several components based on reflection approach are now integrated, and working fine,  I uploaded the Dart project to Github:

    https://github.com/calathus/reflective_web_dev_kit

    There are a few more things to do, but this is not bad timing to clean up the project structure and store it to github.

    here is the readme file:

    Reflective Web Dev Kit

    Overview

    The goal of this project is to create a small end2end sample application using component based approach. Dart's mirror library will be applied to several area of web application, GUI, Database Access, client/server communication. Thus the project is called 'reflective' web dev kit.
    See following blog site: http://dartathus.blogspot.com

    1. portable_mirror

    right now, darts:mirrors library cannot be used in javascript mode. So if we directly use this library, most of code cannot be run on browser. This lib provides a portable mirror API to support (small subset of) mirror features. There are two implementations for this API class. one depends on static classes, and the other depends on dart:mirror. No code changes are required to run application on javascripts mode or Dartium mode(using Dart VM).

    2. json_mapper

    json mapping based on mirror library. this automatically map json to corresponding entity instance

    3.couchdb

    dao api for couchdb based on mirror/json_mapper. this provides server side json_proxy, and client side couchdb dao library

    4. gui_component

    a framework to create web application using component based design, also table/form are implemented as generic class using mirror.

    5. sample_app

    This is a sample web application using these libraries. This web application supports CRUD operation using Table and Form.