Showing posts with label DART_BUG. Show all posts
Showing posts with label DART_BUG. Show all posts

Friday, November 1, 2013

Big restriction: Dart's Stream does not support synchronous mode

When I tried to support getter property of another referenced entity, I came to recognize that it is NOT possible in current Dart.

This is ridiculous restriction.
And it was supported until M3 deprecated the previous synchronous Stream classes.
I think this is pretty much nutty stupid decision.
It must have been done by young limited experienced people who can believe such single bullet approach can solve every thing. Probably it may solve every thing they knew.
That is the problem of the lack of experience.

Whole Dart development somehow has resemblance to early stage of Java around 1995. Probably many of developer of Dart does not remember.

Java has been introduced as a language for Applet. And marketed as such, then it was mainly used for server side. The main reason for the adaption can be contributed several reasons. one aspect is it was free, and it provided a lot of library. Compared to C/C++, these are big difference. Also from language point of view, Java supported class, object oriented features and garbage collection.(and lack of pointer). So compared to C/C++, it was significantly high level language, it was good enough for the most of server side application.

(but it was really backward step compared to other advanced moduler languages, like Mesa/Cedar, Ada, Modula-2, etc. but they never became known to wider audiences, that may have helped Java to proliferated also..)

For Dart,  the current marketing Buz is for browser side language(to replace JavaScript (eventually..)), but as a language, it has also unique feature integrating object/functional idioms in a single language.
Although there are many of such languages(Like Scala), there are no other language which can support both browser and server side.

I think  these two aspects are quite important. Although current marketing focus is in browser side, like polymer, dart:io etc, but it will be used more on server side.
Since the combination of object/functional style is very powerful, once people realized how it is productive, they will never want to write huge amount of equivalent codes in Java. Also sharing the same class from both sides is big plus.

Bottom line is  Dart should target such server side development in much higher priority. Right now, many people seems not developing significant application, they will not complain, but eventually, more people start using Dart, this kind of biased API design will bring a lot of complaints.

Saturday, October 26, 2013

Several Dart bugs I encountered => found how to avoid the problem

The problem I reported in the previous post was really annoying.
It caused bunch of strange problems and there was no clue for the real reason why import fail, why 'a is A' does not have expected value.
The actual fix was to change return type of get listeners from List<ComponnetAction> to List<RowAction>. these types are defined by typedefs. After this change, everything got normal .
  
typedef void ComponentAction(Event event, Component c);
typedef void RowAction(Event event, Row row);

// this caused the problem:
//List<ComponentAction> get listeners => table.row_listeners;

// shoudl use this instead.
List<RowAction> get listeners => table.row_listeners;

Such a subtle difference caused a lot of strange problems without any meaningful error messages. Actually, the main bug may be the failed handling of ComponentAction, but even if it cannot be used there, Dart should report such error so that it can be corrected easily. 

I was a bit feeling not to use Dart if the quality of system is such low.
In facts, there were other bugs which is quite disappointing to know  the level of quality control of bug fixes.

1) wrong type of methods for reflect(new List<A>()).type,

{
    ClassMirror cmirr = reflect(new List()).type;
    print(">>0@@ cmirr.reflectedType: ${cmirr.reflectedType}");
    cmirr.getters.forEach((k, MethodMirror md){
      Type tm = null;
      if (md.returnType is ClassMirror) {
        tm = (md.returnType as ClassMirror).reflectedType;
        print(">>1@@ k: ${k}, tm: ${tm}");
      } else if (md.returnType is TypeVariableMirror) {
        TypeVariableMirror tvmirr = md.returnType;
        print(">>2@@ tvmirr: ${tvmirr.runtimeType}");
      }
    });
  }

The result of executing this is:

>>0@@ cmirr.reflectedType: List<A>
>>1@@ k: Symbol("length"), tm: int
>>1@@ k: Symbol("_capacity@0x36924d72"), tm: int
>>1@@ k: Symbol("first"), tm: A
>>1@@ k: Symbol("last"), tm: A
>>1@@ k: Symbol("single"), tm: A
>>1@@ k: Symbol("isEmpty"), tm: bool
>>1@@ k: Symbol("isNotEmpty"), tm: bool
>>1@@ k: Symbol("reversed"), tm: Iterable<T>
>>1@@ k: Symbol("iterator"), tm: Iterator<T> 

This issue was discussed with Gilad, and he told me Google team is working on this issue. At the time, first 's type was not substituted to A, this issues was definitely fixed.
But the type parameter of the generic type of  reversed an iterator is still T, not substituted to A.
These type related implementation is quite basic, must have highest quality.
Although they fixed, the way to fix without addressing all problem was very sloppy.
I reported this issue, but they looks not setting higher priority.

2) Another case was dart2js bug, which crashed dart2js. For this issue I observed the same problem after they 'fixed' the issue, but  they could not fix all the cases. Although the response time and fixed time was good, related issued should be checked when one issue was reported.(take more time to examine related issues rather than fixing fast)

3) the reflectClass behavior is really bad. and alternative way to get runtimeType though instantiating object is just absurd.
These things indicate the design of mirror is not well guided.
They may be busy for many stuff, but some basic language core thing should be implemented in highest quality.

My impression is Dart team is too much focusing on Polymer.
Often such politically overselling approach is proved to be misguiding/useless in the end, but it will waste a lot of people's energy and time.

Friday, October 18, 2013

Several Dart bugs I encountered

I refactored the codes so that new implicit delayed UI component initialization can be used.
And I found a few restriction and bugs of Dart.

  1. I needed to define default constructor without taking optional values. this is required to create UI component object without taking any parameters, in particular, parent value can not be passed at the property declaration time.
    So I first tried to use optional parameter '{}', but when I combined with Monitor suing Mixen, I found it does not allow to use mixin with a class in which the default constructor has optional parameters.
  2. So I first try to avoid changing existing constructors(although it was not bad idea to change so, but it needed more changes), I moved Monitor class to be used as super class of the top level Component class. Then what I saw during execution was very strange problem. There was annotation class called Monitored, and reflection will get the instance through metadata, and in order to identify proper annotation class, it uses 'is" operator.
    What happened was that 'obj is Monitored' was not true even obj's runtimeType is Monitored!
    This kind of things happen in Java when different class loaders are used to instantiate an object, but in Dart, we will not manipulate class loading, so quite strange. So I basically abandoned this approach, and took the mixin approach again.(this was OK, since this approach would be more narrowly scoped, and appropriate for the purpose).
  3. after all required changes are finished, and could run properly with DartVM mode, I tested this app with static mirror library which are to be used for javascript mode.
    If I run this with Dart VM, it run properly, but if we use javascript mode, the dart2js compiler crashed.
    Actually the message of the compiler problem was the same as a bug I reported before, and it was quickly fixed(but  I did not verify it for myself.) So I thought this would be fixed if I update the dart sdk(r28355) since the fixed version was older that that revision.
    But I found it was not fixed. Actually there were some workaround to fix previous problem using variable instead of direct type value, but this issue was not fixed by this workaround. So this may indeed be another bug.
  4. Another problem I faced was the getting ClasssMirror of generic type. In order to provide javascript mode, portal mirror need to provide basic reflection features from concrete classes.
    For instance it need to use generic type's type(Type). right now, in order to have right type value, namely the type where parameters are substituted is only to go through instantiating the object.
    but new implicit delayed UI component initialization will call reflection library when  the default constructor is called. So this introduced infinite loop. Actually these kind of problems were I anticipated when I knew the current  way to get Type. Essentially this is very dirty trick. Also some case, this will case unnecessary resource usage as well. I avoided this problem using dirty trick to use static variable not to call the sub component initialization(although the global variable is defined as private, so it is not so bad way..).
  5. This issue also made clear the current constructor has a lot of restriction, lack of flexibility. The simple way to avoid this in Java was to define another constructor to take such flag to disable calling sub component initialization. But in Dart, if we define one constructor, there is no other way to define another.   So I was forced to use global variable.

Tuesday, October 8, 2013

Dart's reflection details

Since I needed to manipulate reflection library to develop reflective json_mapper, I investigated some fine details of library. And found strange behavior.
So I asked to dart-misc mailing list.
Fortunately these question was answered by Gilad Bracha(main designer of Dart), so it became clear for what I should expect from Dart now.

Following style will return a mirror for generic class 'declaration'.

ClassMirror cmirror = reflectClass(new List<A>().runtimeType) 
(ClassMirror cmirror = reflectClass(List<A>)) // not supported yet

the above cmirror correspond to the generic class 'declaration', which is equivalent to none applied generic type, so the type including type variables in the generic class still contain type variables when it is inspected by reflection library. This is called a generic declaration.

So the strange things are even List<A> are applied generic class(type variable are substituted by A), but the  reflectClass returns List<T> class which does not corresponding to any runtime type of an object. I don't know why this is so designed, but this is confusing, and quite useless return result for most of the applications.

But as long as there are some way to return Type of applied generic class, it will be OK.
in fact, there is such a way, but it would be difficult to know without having told the difference!

This will return a mirror for applied generic class. (but not complete yet.. since there is a bug now)

ClassMirror cmirror = reflect(new List<A>()).type;
(ClassMirror cmirror = reflectType(List<A>)) // not supported yet

This cmirror is corresponding to applied generic class, and if we do print  cmirror.reflectedType, it prints List<A>.
So it seems OK, but in fact, I already knew this was not OK.

For json_mapper, we need to get field's type in order to process sub json string.

but if we run following code, the field types are none applied generic types. namely including type variables, not substituted by applied types.

ClassMirror cmirr = reflect(new List()).type;
    print(">>0@@ cmirr.reflectedType: ${cmirr.reflectedType}");
    cmirr.getters.forEach((k, MethodMirror md){
      Type tm = null;
      if (md.returnType is ClassMirror) {

        tm = (md.returnType as ClassMirror).reflectedType;
        print(">>1@@ k: ${k}, tm: ${tm}");
      } else if (md.returnType is TypeVariableMirror) {
        TypeVariableMirror tvmirr = md.returnType;
        print(">>2@@ tvmirr: ${tvmirr.runtimeType}");
      }
    });
output:

>> type: ChouchDBFetchData
>>0@@ cmirr.reflectedType: List
>>1@@ k: Symbol("length"), tm: int
>>1@@ k: Symbol("_capacity"), tm: int
>>2@@ tvmirr: _LocalTypeVariableMirrorImpl
>>2@@ tvmirr: _LocalTypeVariableMirrorImpl
>>2@@ tvmirr: _LocalTypeVariableMirrorImpl
>>1@@ k: Symbol("isEmpty"), tm: bool
>>1@@ k: Symbol("isNotEmpty"), tm: bool
>>1@@ k: Symbol("reversed"), tm: Iterable
>>1@@ k: Symbol("iterator"), tm: Iterator

So essentially right now, there is no way to handle generic class properly.
Fortunately, Gilad agreed this is bug, and google teams is now working on fixing this problem. Actually this is a big bug.

So maybe we will get better mirror lib soon.
Other related issues seems also addressed later release.

like reflectClass(typedef List<A>)(here typedef keyword is 'required' to avoid parsing issue..)
and 'invariant'  reflectType, which probablly it returns applied generic class.

here is his answers:
I've been meaning to update the mirror tutorial on our site, but because significant changes are coming soon, I'm delaying that just a tad longer. That said, those changes have nothing to do with this issue, so I'll try and answer your question here. Bear with me, as it is slightly non-obvious and requires some background.

(A)  ClassMirrors reflect both the classes of objects and class declarations. What's the difference between the class of an object and a class declaration?  Well, in a world without generics you can leave the distinction to philosophers, but once you have generics, you want to distinguish between the one declaration of the generic (i.e, the declaration in the source code) and its many invocations (such as List<String>, List<bool> etc.), aka parameterized types.  All the invocations share the same declaration.

This matters when you ask a class mirror for its methods, and then look up a method and ask for its return type. If the mirror is on List<int>, then the return type of the method #first will be int; if it is List<Element> it will be Element etc.  If ask the same question on a declaration, the return type is E, which is a type variable (and no actual object has a type variable as its type; the type variable is always bound to some specific type).

There is never an object whose type is a generic declaration. Hence there is no Type object that corresponds to a generic declaration, and so a mirror on generic declaration has no Type object associated with it. Which is why hasReflectedType on such a mirror returns false. If you still try and get the reflectedType, it throws. 

Hence the behavior you are seeing. 

Now you might ask why.  We could have reflectClass give you a mirror on the specific Type you passed in, and then the invariant you expected would hold. However, then we'd have a problem if you wanted to get at the declaration. If you wrote reflectClass(List) you might well expect the result to be a mirror on the declaration, but you'd be disappointed. Let's say we have a class 

class G<T> ...

In Dart, the identifier G, used without type arguments, always denotes G<dynamic>.  So you would not get a mirror on the declaration of G (or of List) but a mirror on a specific parameterized type (G<dynamic> or List<dynamic> as the case might be).

We decided to keep reflectClass for the declaration. If you want a mirror on a specific parameterized type, you can get it by reflecting on an instance and asking the instance mirror for its type

reflect(new List<A>()).type

we are planning on adding a function reflectType() that would always return a mirror on the specific Type object passed to it. The the invariant

reflectType(t).reflectedType == t

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();
}

Saturday, September 28, 2013

Generic GUI Library in Dart (Part 3)

I could run the generic GUI lib application on browsers(in javascript mode).
Since Dart does not support mirror in JavaScript mode, I needed to do this kind of things(see previous post).
The following snapshot shows running the app on Dartium , Chrome and Firefox:


In order to achieve this, I re-factored the code so that it eliminates the direct reference to 'dart:mirrors' by introducing minimal mirror interfaces.

 library mirror_api;

typedef IClassMirror CMirrorFun(Type type);

class ClassMirrorFactory {
  static CMirrorFun _cmf;
  static IClassMirror create(Type type) => _cmf(type);
  static void register(CMirrorFun cmf) { _cmf = cmf; }
}

//
abstract class IClassMirror {
  IInstanceMirror newInstance();
  IInstanceMirror reflect(Object obj);
 
  Map<Symbol, IFieldType> get fieldTypes;
}

abstract class IFieldType {
  Symbol get symbol;
  String get name; // convert symol to string
  Type get type;
}

//
abstract class IInstanceMirror {
  IClassMirror get cmirror;
  Object get reflectee;
 
  IField getField(Symbol name);
}

abstract class IField {
  Symbol get symbol;
  String get name; // convert symol to string
 
  Object get value;
  void set value(Object obj);
 
  Type get type;
}
 Then I provided two implementations of this interfaces:
  •  mirror_dynamic_lib.dart
  •  mirror_static_lib.dart
 mirror_dynamic_lib will use 'dart:mirrors', so this will be useful to run on server side, and no extra information are required to use this lib.
the second one is for javascript mode, it require additional meta  information for the class which is to be used in a generic class.
Following dart file is to provide such information for Expense class.  As shown in the last part, there is a dart2js compiler bug, I could not use the simpler version(commented one), but if we use this code, I could avoid the compiler bug(compiler was crashed).(this bug was fixed after I reported this issue in rev 28044)

library sample_mirror;

import 'mirror_libs/mirror_api_lib.dart';
import 'mirror_libs/mirror_static_lib.dart';
import 'shared/models.dart';

/*
 * This must be invoked before calling any of these simple mirror APIs.
 */

void initClassMirrorFactory() {
  ClassMirrorFactory.register((Type type)=>(type == Expense)?
      new StaticClassMirror(()=>new Expense.Default(), expenseFieldInfo)
  :null);
}

Type _String = String;
Type _ExpenseType = ExpenseType;
Type _DateTime = DateTime;
Type _num = num;
Type _bool = bool;

Map<Symbol, FieldInfo> expenseFieldInfo =
[
 new FieldInfo(const Symbol('id'), _String, (Expense e)=>e.id, (Expense e, String value) { e.id = value; }),
 new FieldInfo(const Symbol('rev'), _String, (Expense e)=>e.rev, (Expense e, String value) { e.rev = value; }),
 new FieldInfo(const Symbol('expenseType'), _ExpenseType, (Expense e)=>e.expenseType, (Expense e, ExpenseType value) { e.expenseType = value; }),
 new FieldInfo(const Symbol('date'), _DateTime, (Expense e)=>e.date, (Expense e, DateTime value) { e.date = value; }),
 new FieldInfo(const Symbol('amount'), _num, (Expense e)=>e.amount, (Expense e, num value) { e.amount = value; }),
 new FieldInfo(const Symbol('detail'), _String, (Expense e)=>e.detail, (Expense e, String value) { e.detail = value; }),
 new FieldInfo(const Symbol('isClaimed'), _bool, (Expense e)=>e.isClaimed, (Expense e, bool value) { e.isClaimed = value; })
 ].fold({}, (Map map, FieldInfo fh) => map..[fh.symbol] = fh);

/*
//
// This works for DartVM, but it fails dart2js.
//
Map<Symbol, FieldInfo> expenseFieldInfo =
    [
     new FieldInfo(const Symbol('id'), String, (Expense e)=>e.id, (Expense e, String value) { e.id = value; }),
     new FieldInfo(const Symbol('rev'), String, (Expense e)=>e.rev, (Expense e, String value) { e.rev = value; }),
     new FieldInfo(const Symbol('expenseType'), ExpenseType, (Expense e)=>e.expenseType, (Expense e, ExpenseType value) { e.expenseType = value; }),
     new FieldInfo(const Symbol('date'), DateTime, (Expense e)=>e.date, (Expense e, DateTime value) { e.date = value; }),
     new FieldInfo(const Symbol('amount'), num, (Expense e)=>e.amount, (Expense e, num value) { e.amount = value; }),
     new FieldInfo(const Symbol('detail'), String, (Expense e)=>e.detail, (Expense e, String value) { e.detail = value; }),
     new FieldInfo(const Symbol('isClaimed'), bool, (Expense e)=>e.isClaimed, (Expense e, bool value) { e.isClaimed = value; })
     ].fold({}, (Map map, FieldInfo fh) => map..[fh.symbol] = fh);
*/
From the top level dart file, we can change the  library by just switching to import file as following. I'll attach the entire main dart file for this app. this is  all required codes  to run this application using the generic GUI library. the layout of several components like table, buttons etc, and the controlling logic  are defined here.


 library sample_generic_gui;

import 'dart:html';
import "shared/models.dart";
import "gui_generic_lib/gui_generic_lib.dart";
//import "mirror_libs/mirror_dynamic_lib.dart"; // <== use 'dart:mirrors'
import "sample_mirror_impl.dart";; // <== no use of 'dart:mirrors'

class AppController extends Component {
  static const String APP = "g_app_ctlr";
  final DivElement _uiRoot;
  DivElement _content;
  DivElement _actions;
 
  Table<Expense> table;
  Form<Expense> form;
  ButtonComp newButtom;
  ButtonComp saveButtom;
  ButtonComp deleteButtom;
 
  AppController(Component parent, this._uiRoot, {List<Expense> expenses}): super(parent, const[APP]) {
    table = new Table<Expense>.fromModelType(this, Expense, formatFunctionMap: {ExpenseType: ExpenseTypeComp.format});
    form = new Form<Expense>(this, Expense,
        specialInputCompMap: {ExpenseType: ExpenseTypeComp.inputCompFactory},
        adhocCompMap: {'detail': 'textarea'}  // temp
    );
  
    Expense e = null;
    newButtom = new ButtonComp(this, "New", (_) {
      e = form.create();
      _changeButtonState(false, create: true);
    
    });
    saveButtom = new ButtonComp(this, "Save", (_) {
      Expense e0 = form.save();
      if (e0 != null) {
        e = e0;
        table.addOrUpdate(e);
        _changeButtonState(true);
      }
    });
    deleteButtom = new ButtonComp(this, "Delete", (_) {
      Expense e = form.delete();
      if (e != null) {
        table.delete(e);
        _changeButtonState(true);
      }
    });
    _changeButtonState(true);
  
  
   table.row_listeners.add((ev, row){
      //print("row clicked.. ${ev}, row: ${row}");
      e = row.e;
      form.load(e);
      _changeButtonState(false);
    });
  
    if (expenses != null) {
      table.load(expenses);
    }
    _uiRoot.nodes.add(element); // this 'element' tiggers DOM node creation!
  }
 
  void _changeButtonState(bool isEmpty, {create: false}) {
    (newButtom.element as ButtonElement).disabled = !isEmpty;
    (saveButtom.element as ButtonElement).disabled = isEmpty;
    (deleteButtom.element as ButtonElement).disabled = (create)?true:isEmpty;  
  }

  Element createElement() => addSubComponents0(newElem("div"));
 
  Element update() => addSubComponents0(initElem());
    
  Element addSubComponents0(Element elm) => addListeners(
      elm
      ..classes.add("section")
      ..nodes.add(new Element.html("<header class='section'>${table.modelType} 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(newButtom.element)
        ..nodes.add(saveButtom.element)
        ..nodes.add(deleteButtom.element))
      ..nodes.add(form.element)
      ..nodes.add(new Element.html("<footer class='section' id='footer'></footer>")));
}

class ExpenseTypeComp extends SelectComp<ExpenseType> {
  static const String EXPENSE_TYPE_INPUT = "g_expense_type_input";
 
  static final Map<String, ExpenseType> _expenseTypes = {
    "TRV": const ExpenseType("Travel","TRV"),
    "BK": const ExpenseType("Books","BK"),
    "HT": const ExpenseType("Hotel","HT")                        
  };
 
  ExpenseTypeComp(Component parent, String label, {List<String> classes: const [SelectComp.SELECT_INPUT, EXPENSE_TYPE_INPUT]})
    : super(parent, label, ExpenseType, classes: classes);
 
  static ExpenseTypeComp inputCompFactory(Component c, String name, Type t)=>new ExpenseTypeComp(c, name);
  static String format(ExpenseType et) => (et == null)?'':et.name;
 
  Map<String, ExpenseType> get entityTypes => _expenseTypes;
 
  String getCode(ExpenseType et) => et.code;
  String getName(ExpenseType et) => et.name;
}

main() {
  // register reflection factory
  initClassMirrorFactory();
 
  List<Expense> expenses = [
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random(),
                            new Expense.random()];
  Element uiContainer = document.query("#sample_generic_gui");
  AppController app = new AppController(null, uiContainer);
  app.table.load(expenses);
-------------------------------

here is the implementation classes:

library dynamic_mirror;

import 'dart:mirrors';
import 'mirror_api_lib.dart';

/*
 * This must be invoked before calling any of these simple mirror APIs.
 */
void initClassMirrorFactory() {
  ClassMirrorFactory.register((Type type)=>new DynamicClassMirror.reflectClass(type));
}

//
// IClassMirror implementations
//
class DynamicClassMirror implements IClassMirror {
  static Map<Type, DynamicClassMirror>  cmirrs = {};
 
  final Type type;
  ClassMirror _cmirror;
  MethodMirror _ctor;
  Map<Symbol, IFieldType> _fieldTypes = {};
 
  DynamicClassMirror(this.type) {
    _cmirror = reflectClass(type);
   
    reflectClass(type).constructors.forEach((k, v){
      if (v.parameters.length == 0 && (_ctor == null || getSymbolName(k) == "${type}.Default")) {
        _ctor = v;
      }
    });
   
    _cmirror.getters.forEach((Symbol symbol, MethodMirror md){
      _fieldTypes[symbol] = new DynamicFieldType(symbol, md);
    });
  }
 
  factory DynamicClassMirror.reflectClass(Type type) {
    DynamicClassMirror cmirr = cmirrs[type];
    if (cmirr == null) {
      cmirr = new DynamicClassMirror(type);
    }
    return cmirr;
  }
 
  IInstanceMirror newInstance() =>
      reflect(_cmirror.newInstance(_ctor.constructorName, []).reflectee);

  IInstanceMirror reflect(Object obj) => new DynamicInstanceMirror(this, obj);

  Map<Symbol, IFieldType> get fieldTypes => _fieldTypes;

}

class DynamicFieldType implements IFieldType {
  Symbol _symbol;
  String _name;
  MethodMirror _md;
 
  DynamicFieldType(this._symbol, this._md) {
    _name = getSymbolName(_symbol);
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
  Type get type => (_md.returnType as ClassMirror).reflectedType;
}

//
// IInstanceMirror implementations
//
class DynamicInstanceMirror implements IInstanceMirror {
  Map<Symbol, DynamicField>  dfs = {};
 
  final IClassMirror _cmirror;
  InstanceMirror _imirror;
 
  DynamicInstanceMirror(this._cmirror, Object obj) {
    _imirror = reflect(obj);
  }
 
  IClassMirror get cmirror => _cmirror;
 
  Object get reflectee => _imirror.reflectee;
  IField getField(Symbol name) => new DynamicField.create(name, this);
}

class DynamicField implements IField {
  DynamicInstanceMirror _parent;
  Symbol _symbol;
  String _name;
 
  DynamicField(Symbol this._symbol, this._parent) {
    _name = getSymbolName(_symbol);
  }
 
  factory DynamicField.create(Symbol symbol, DynamicInstanceMirror _parent) {
    DynamicField df = _parent.dfs[symbol];
    if (df == null) {
      _parent.dfs[symbol] = df = new DynamicField(symbol, _parent);
    }
    return df;
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
 
  Object get value => _parent._imirror.getField(_symbol).reflectee;
  void set value(Object obj) { _parent._imirror.setField(_symbol, obj); }
 
  Type get type => _parent._cmirror.fieldTypes[_symbol].type;
 }

//
// utils
//
String getSymbolName(Symbol symbol) => symbol.toString().substring('Symbol("'.length, symbol.toString().length-2);
 ----------------------------
 library static_mirror;

import 'mirror_api_lib.dart';

//
// IClassMirror implementations
//
typedef Object Getter(Object entity);
typedef void Setter(Object entity, Object value);

class FieldInfo implements IFieldType {
  final Symbol _symbol;
  String _name;
  final Type _type;
 
  final Getter getter;
  final Setter setter;
 
  FieldInfo(this._symbol, this._type, this.getter, this.setter) {
    _name = getSymbolName(_symbol);
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
  Type get type => _type;
}

typedef Object DefaultConstructor();

class StaticClassMirror implements IClassMirror {
  final DefaultConstructor ctor;
  final Map<Symbol, FieldInfo> fieldInfos;
 
  StaticClassMirror(this.ctor, this.fieldInfos);
 
  IInstanceMirror newInstance() => reflect(ctor());
  IInstanceMirror reflect(Object obj) => new StaticInstanceMirror(this, obj);

  Map<Symbol, IFieldType> get fieldTypes => fieldInfos;
}

//
// IInstanceMirror implementations
//
class StaticInstanceMirror implements IInstanceMirror {
  Map<Symbol, StaticField>  dfs = {};
 
  final IClassMirror _cmirror;
 
  final Object _obj;
 
  StaticInstanceMirror(this._cmirror, Object this._obj);
 
  IClassMirror get cmirror => _cmirror;
 
  Object get reflectee => _obj;
  IField getField(Symbol name) => new StaticField.create(name, this);
}

class StaticField implements IField {
  StaticInstanceMirror _parent;
  Symbol _symbol;
  String _name;
 
  StaticField(Symbol this._symbol, this._parent) {
    _name = getSymbolName(_symbol);
  }
 
  factory StaticField.create(Symbol symbol, StaticInstanceMirror _parent) {
    StaticField df = _parent.dfs[symbol];
    if (df == null) {
      _parent.dfs[symbol] = df = new StaticField(symbol, _parent);
    }
    return df;
  }
 
  Symbol get symbol => _symbol;
  String get name => _name;
 
  Object get value => _cmirror.fieldInfos[symbol].getter(_parent.reflectee);
 
  void set value(Object obj) { _cmirror.fieldInfos[symbol].setter(_parent.reflectee, obj); }
 
  Type get type => _cmirror.fieldInfos[symbol].type;
 
  StaticClassMirror get _cmirror => (_parent._cmirror as StaticClassMirror);
 }

//
// utils
//
String getSymbolName(Symbol symbol) => symbol.toString().substring('Symbol("'.length, symbol.toString().length-2);

Wednesday, September 11, 2013

Dart Element.html bug

I found a bug in dart2js for handling Element.html.
when we run an app using this feature, Dartium can run properly, but js version, the  result is not correct.
It expects to show items in a table, but they are not shown in the js version.
I thought this comes from a problem handling Element.html, so I replaced it with Element.tag, and it worked on both ways.
In fact, Element.html looks too heavy way to construct page elements, so there might be a better way, (not go the other end of using tag constructors), but such difference are very annoying problem if we decide to use Dart.
So this problem should be fixed.

this is  the projects to test this problem.

I created simple test projects.
here is a snipe of code what cause the problem and how we can avoid the problem..
------------------------
// this is buggy version

  refreshUi(List<Expense> expenses) {
    _updateRootElement();

    Element tableElement = new Element.tag("table");
    Element head = new Element.html("""
          <thead>
            <td class="type">Type</td>
            <td class="date">Date</td>
            <td class="detail">Item</td>
            <td class="amount">Amount</td>
            <!--<td class="claimed>Claimed?</td>-->
            <td class="edit">&nbsp;</td>
          </thead>""");

     tableElement.nodes.add(head);

     for (Expense ex in expenses) {
       tableElement.nodes.add(_getRowElement(ex));
     }

    rootElement.nodes.add(tableElement);
  }
=====>
// this is a workaround.

  refreshUi(List<Expense> expenses) {
    _updateRootElement();

    Element tableElement = new Element.tag("table");
    rootElement.nodes.add(tableElement);
    Element thead = new Element.tag("thead");
    thead.nodes.addAll([
        newTd('type', 'Type'),
        newTd('date', 'Date'),
        newTd('detail', 'Item'),
        newTd('amount', 'Amount'),
        newTd('edit', ''),
        newTd('delete', '')
        ]);
 
    tableElement.nodes.add(thead);
    for (Expense ex in expenses) {
      tableElement.nodes.add(_getRowElement(ex));
    }
  }
Element newTd(cls, txt) {
  Element td = new Element.td();
  td.attributes['class'] = cls;
  td.text = txt;
  return td;
}


Tuesday, September 10, 2013

Dart Compiler bug

There is a strange behavior in Dart's setter declaration.
It should detect an error at compilation time(dart2js) or editing time using Eclipse dart plugin (or Dart Editor), but it is only detected at runtime.

let see following class definition.
In the class A, rev0 is defined without parameter type specification.
but only possible type allowed 'void' since the type of expression '_rev = value' must be equal to the setter's return type 'void', and that assignment expression's type is the type of value. so teh value type must be void.
This already quite ridiculous situation for setter  since we cannot declare type of a variable as void!
but aside from this issue, if we call a function in which  the return type is 'void', it works as (3).
and the null value's type seems void! anyway null is assigned to _rev.

So these things does not make sense, and practically, it introduce an error which can be detected at compilation time, but defered at the runtime.
Since this is so wird, people may not easily spot the bug in the setter definition!
As a workaround, we should always define type for the setter parameter(no dynamic also).

String _rev = null;
class A {
  String get id => _id;
  void set id(String i) { _id = i; }
  String _id = null;

  String _rev = null;
  String get rev => _rev;
  void set rev(String value) { _rev = value; }// (0) normal way..

  // void a; // compilation error

  void f(_) {}
  void set rev0(value) => _rev = value; // buggy, but no compile time error
  void set rev00(dynamic value) => _rev = value; // buggy, but no compile time error
  void set rev1(String value) => f(value); // (1) this is OK
  void set rev2(String value) => f(_rev = value); //(2)
  // void set rev3(String value) => _rev = value;  // compilation error
  String rev3(String value) => (_rev = value);

  factory A.fromJson(String json) {
    var map = parse(json);
    return new A.fromMap(map);
  }
....
}
main() {
    A e = new A.fromJson('{"id":null, "_rev":"NNNNN"}');
    log.info("1===> ${e.toJson()} ${e.rev}");
    e.id = e.rev = "ooo";
    log.info("2===>  ${e.toJson()} ${e.rev}");
    e.rev0 = e.f(1); // works!! but wird.. (3)
    log.info("3===>  ${e.toJson()} ${e.rev}");
    e.rev1 = "aa"; // works!! but wird..
    log.info("4===> ${e.toJson()} ${e.rev}");
    e.rev2 = "aa"; // works!! but wird..
    log.info("5===> ${e.toJson()} ${e.rev}");

    e.rev0 = "aa"; // runtime error!!

}
}

----------------------
The following is the execution logs.
when 'e.rev0 = "aa";' is called, it causes runtime error.
this error message "type 'String' is not a subtype of type 'void' of 'function result'." is also not easy to understand, but the reason is this rev0 is expecting void argument type!

dirt_server.log [INFO]: 1===>  {"id":null,"_rev":"NNNNN"} NNNNN
dirt_server.log [INFO]: 2===>  {"id":"ooo","_rev":"ooo"} ooo
dirt_server.log [INFO]: 3===>  {"id":"ooo"} null
dirt_server.log [INFO]: 4===>  {"id":"ooo"} null
dirt_server.log [INFO]: 5===>  {"id":"ooo", "_rev":"aa"} aa

Unhandled exception:
type 'String' is not a subtype of type 'void' of 'function result'.
#0      A.rev0= (file:///opt/A.dart:28:28)
#1      main (file:///opt/A.dart:138:34)

-----------------