Showing posts with label annotations. Show all posts
Showing posts with label annotations. Show all posts

Thursday, November 19, 2015

Creating and Reading Dart Annotations in Flyweights


I am settling comfortably into Dart mirrors as a solution for obtaining concrete instances in the Flyweight pattern. They are not a one-size-fits-all solution, but they strike a nice balance between usability in the client context (especially when paired with Dart's factory constructors) and maintainability of the flyweight code. That said, I do not want to leave reasonable options unexplored.

While reasonable people can disagree on what reasonable options are, I felt the siren's song of code annotation more than once while working with this pattern. So today, I give into that temptation. Hopefully I won't be dashed on rocks for my trouble.

While working other angles on the problem of concrete classes, annotations were appealing mostly because of their constant nature. My current CoffeeFlavor interface is a regular (non-constant) class:
class CoffeeFlavor {
  // Lots of static, mirror code from last night here...
  // Factory constructor:
  factory CoffeeFlavor(name) {
    return _cache.putIfAbsent(name, () =>
        classMirrors[new Symbol(name)].
            newInstance(new Symbol(''), []).
            reflectee
    );
  }
  // Normal class stuff:
  String get name => "Fake Coffee";
  double get profitPerOunce => 0.0;
}
Concrete implementations that get used as flyweights are similarly non-constant:
class Cappuccino implements CoffeeFlavor {
  String get name => 'Cappuccino';
  double get profitPerOunce => 0.35;
}
Due to the factory constructor, various solutions to the flyweight caching felt like a constant was the only solution. In the end, I could not make them work — hence last night's mirror solution.

Somewhere in my brain I thought that, since annotations are constants, maybe they can help here. But now that I am faced with the blank page, all I can think to do is mark a concrete class with an annotation to help finding and caching it:
@flavor
class Cappuccino implements CoffeeFlavor {
  String get name => 'Cappuccino';
  double get profitPerOunce => 0.35;
}
That seems to offer nothing new over yesterday's solution which made use of the implemented interface to find concrete classes. If anything, the annotation is one extra line.

Still, while I am here, it might be fun to write some Dart code that can read and apply annotations. I start by defining the class and annotation const:
// Annotation Class
class Flavor { const Flavor(); }
// Annotation instance
const flavor = const Flavor();
Yesterday's code found concrete classMirrors by filtering for “super interfaces” that contained CoffeeFlavor:
  static Map classMirrors = _allDeclarations.
    keys.
    where((k) => _allDeclarations[k] is ClassMirror).
    where((k) =>
      _allDeclarations[k].superinterfaces.contains(reflectClass(CoffeeFlavor))
    ).
    fold({}, (memo, k) => memo..[k]= _allDeclarations[k]);
Tonight, I need to similarly work though all class declarations, but filter on metadata (annotations):
  static Map classMirrors = _allDeclarations.
    keys.
    where((k) => _allDeclarations[k] is ClassMirror).
    where((k) =>
      _allDeclarations[k].metadata.map((m)=> m.type.reflectedType).contains(Flavor)
    ).
    fold({}, (memo, k) => memo..[k]= _allDeclarations[k]);
The _allDeclarations.keys is a map of symbols (e.g. #Cappuccino) pointing to declaration mirrors. So iterating over all the keys, then filtering on _allDeclarations[k] gives me individual declarations like the concrete class definition. From there, I map the annotations/metadata to the corresponding annotation type. In this case I want the Flavor annotation so that any classes with the Flavor annotation are returned.

If I had declared Flavor with properties and set them in the const declaration, then I could get those properties with the getField() method. Here, however, I just need to know if the @flavor annotation is being used. So I am already done!

My code continues to pass dartanalyzer and the coffee shop code that relies on this flyweight code similarly continues to work. Annotations do not buy me anything substantive in this case (at least that I can see). Still it is good to know how to extract and apply them.

(Play with this code on DartPad: https://dartpad.dartlang.org/c7dabc0c57a93e8d88d7)


Day #8

Thursday, August 7, 2014

What's the Difference Between Attribute and Property?


I'll be the first to admit that I am far too obsessed with the new annotations in Polymer.dart. No matter what they do, they are not that important to the overall function of Polymer elements—they just make certain things nicer. And yet, I have been investigating (mostly poorly) these things for a week now.

And it continues tonight.

I have been so deep in trying to understand how these annotations work, that I have not really given much consideration to best practices. That is the whole point of this Patterns in Polymer research, so I will take at least a night to give it some thought. I start with, what is the difference between a property and an attribute?

I realize now that this is not an original thought. The mailing list is replete with concerns that the word “attribute” is not used in at least some of these annotations, but I had not understood the annotations well enough to join in the consternation. I now know that the @PublishedProperty annotation is used for… attributes. And I think that @ComputedProperty is used for properties. This certainly seems confusing, so I first want to double-check this understanding.

First up, is @ComputedProperty an attribute like @PublishedProperty? I get the feeling that the “published” part of @PublishedProperty is meant to make it an element attribute, but let's be sure. In my <x-pizza> element, I already have a special_name attribute that is updated when certain conditions are met. It is an attribute by virtue of the @PublishedProperty annotation in the backing class:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  @PublishedProperty(reflect: true)
  String get special_name => readValue(#special_name);
  set special_name(String newValue) => writeValue(#special_name, newValue);
  // ...
}
The reflect option indicates that changes will be reflected in the attributes in the DOM. This works just fine. One of the conditions updates the specialty pizza name from “Plain” if the first half has pepperoni on it:



So is @ComputedProperty an attribute? I declare the num_toppings computed attribute as the sum of toppings on various sides of the pizza:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  @ComputedProperty("firstHalf.model.length + secondHalf.model.length + whole.model.length")
  int get num_toppings => readValue(#num_toppings);

  @PublishedProperty(reflect: true)
  String get special_name => readValue(#special_name);
  set special_name(String newValue) => writeValue(#special_name, newValue);
  // ...
}
If I set a listener on this element:
  // ...
  XPizza.created(): super.created() {
    changes.listen((changes){
      print(changes);
    });
  }
  // ...
Then I see this value change as I add toppings:
[#<PropertyChangeRecord Symbol("num_toppings") from: 3 to: 4>]
But, if I add this as an attribute on the element:
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <x-pizza special_name="Plain" num_toppings=""></x-pizza>
Then I do not see values being updated. So @ComputedProperty is not an attribute:



Which, in my mind, begs the question, how you make a computed property an attribute? Putting reflect: true in the annotation does not work (it only accepts a single argument with no optional parameters. Stacking the @PublishedProperty annotation on top of @ComputedProperty seems to ignore @PublishedProperty:
  @PublishedProperty(reflect: true)
  @ComputedProperty("firstHalf.model.length + secondHalf.model.length + whole.model.length")
  int get num_toppings => readValue(#num_toppings);
The computed changes are still seen, but the attribute is never updated. I try futzing with the readValue() symbol and redefining the num_toppings getter, but to no avail. If there is an easy way to “publish” a @ComputedProperty, I cannot find it. Tonight.


Day #145

Wednesday, August 6, 2014

I Know What ComputedProperty Does!


After two night's of experimentation, I swear to you that the @ComputedProperty annotation in Polymer.dart serves no purpose. No purpose whatsoever!

Well, OK, it does something, but as far as my experiments have determined, it does exactly what a much simpler and syntactically cleaner Dart getter would do. Consider a @ComputedProperty and a vanilla getter that produce identical results in the <x-pizza-toppings> Polymer element:
@CustomTag('x-pizza-toppings')
class XPizzaToppings extends PolymerElement {
  // ...
  List<String> model = toObservable([]);

  @ComputedProperty("model.length")
  int get numToppings => readValue(#numToppings);

  int get numToppings_old => model.length;
  // ...
}
The values of both will report the number of toppings that are included on a half or whole of pizza in the parent <x-pizza> element. To prove that both the getter and the much more verbose @ComputedValue are IDENTICAL IN EVERY WAY, I include both in the <template>:
<link rel="import" href="../../../packages/polymer/polymer.html">
<polymer-element name="x-pizza-toppings">
<template>
<p>
<!-- ... -->
      (Currently: {{ numToppings }}, {{ numToppings_old }})
</p>
</template>
<script type="application/dart" src="x_pizza_toppings.dart"></script>
</polymer-element>
And, when I update the different sides of the pizza in the UI, these bindings are updated in exact unison:



But there must be a reason for @ComputedValue. There simply must be!

Experimentation is clearly getting me nowhere, so I switch back to reading the actual code. And, thankfully, the code is beautiful. Well, documented, easy to follow for the most part. I could (and probably should) read through this all night long. But first, I must know.

And I finally have my answer from the _PropertyAccessor internal class which services both the @ComputedValue and @published annotations. In there, I find that, when these are updated, they perform the following:
  /// Updates the underlyling value and fires the expected notifications.
  void updateValue(T newValue) {
    var oldValue = _value;
    _value = _target.notifyPropertyChange(_name, oldValue, newValue);
    _target.emitPropertyChangeRecord(_name, newValue, oldValue);
  }
There is even documentation expressing what I should have expected all along—that a changed record is emitted by the Polymer element. And, sure enough, such a record is emitted. I add a listener in the parent <x-pizza> element:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizzaToppings get firstHalf => $['firstHalfToppings'];
  XPizzaToppings get secondHalf => $['secondHalfToppings'];
  XPizzaToppings get whole => $['wholeToppings'];
  // ...
  XPizza.created(): super.created() {
    firstHalf.changes.listen((changes) {
      print(changes);
    });

    /*** I previously tried this (I was so close) ***/
    // firstHalf.numToppings.changes.listen((changeRecord) {
    //   print("$changeRecord");
    // });
  }
  // ...
}
Which reports that a change has occurred:
[#<PropertyChangeRecord Symbol("numToppings") from: 0 to: 1>]
[#<PropertyChangeRecord Symbol("numToppings") from: 1 to: 2>]
[#<PropertyChangeRecord Symbol("numToppings") from: 2 to: 3>]
I have my answer. And it is one that I really should have gotten to faster had I thought about it a bit more. Ah well, in the end I had some frustration but was rewarded with some pleasant code reading—and the answer to my question.


Day #145

Tuesday, August 5, 2014

Does @ComputedProperty Make Observables?


I remain somewhat confused about the purpose of the @ComputedProperty annotation in the latest 0.12 release of Polymer.dart. I had planned on further exploring “timing” issues that may have necessitated this annotation, but Matthew Butler was kind enough to point me in a different direction. Specifically, he indicated that the primary utility of @ComputedProperty was that it marked its properties as observable.

I, being slightly dense, took this a little too literally. Given a @ComputedProperty of numToppings in child elements of <x-pizza>:
@CustomTag('x-pizza-toppings')
class XPizzaToppings extends PolymerElement {
  List<String> model = toObservable([]);

  @ComputedProperty("model.length")
  int get numToppings => readValue(#numToppings);

  int get numToppings_old => model.length;
  // ...
}
I first tried listening to changes to numToppings in the parent element's constructor:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizza.created(): super.created() {
    firstHalf.numToppings.changes.listen((changeRecord) {
      print("$changeRecord");
    });
  }
  // ...
}
But that is not what Matthew meant. At least I don't think so. Mostly because numToppings is not a real observable. It is a simple integer with no changes stream:
Exception: Class 'int' has no instance getter 'changes'.
NoSuchMethodError: method not found: 'changes'
Receiver: 0
Arguments: []
Instead, perhaps this is something that updates the template:
<link rel="import" href="../../../packages/polymer/polymer.html">
<polymer-element name="x-pizza-toppings">
  <template>
    <p>
      <select id="ingredients" class="form-control" value="{{current}}">
        <option value="">Choose an ingredient...</option>
        <option template repeat="{{ingredient in ingredients}}">
          {{ingredient}}
        </option>
      </select>
      <button id="add" on-click="{{add}}" type="button" class="btn btn-default">
        Add {{name}}
      </button>
      (Currently: {{ numToppings }}, {{ numToppings_old }})
    </p>
  </template>
  <script type="application/dart" src="x_pizza_toppings.dart"></script>
</polymer-element>
Except it doesn't.

The numToppings property is a @ComputedProperty. The numToppings_old is a plain-old, un-annotated getter property. So if the benefit of @ComputedProperty is that it is observable, I would expect only the first number to change when I add a topping. But, when I add a topping, both are immediately changed in the UI:



So I remain confused over the utility of @ComputerProperty. Both it and plain-old getter properties seem to behave the same both in the template and in simple created() life cycle checks (the latter from last night). Am I doing something wrong here?


Day #144

Monday, August 4, 2014

The Polymer.dart ComputedProperty Annotation


The new annotations in Polymer.dart are… interesting.

As best I can tell, the purpose behind them is mostly to ensure that the values that they annotate are available regardless of when they are accessed. To better understand that, I need to explore timing accessors. But first, I would like to complete the new annotation tour with a look at @ComputedProperty.

The old way of creating a setting property, for example the number of toppings on a particular side of the <x-pizza> element, might look something like:
@CustomTag('x-pizza-toppings')
class XPizzaToppings extends PolymerElement {
  // ...
  int get numToppings => model.length;
  // ...
}
That is a nice, straight-forward getter method. How could @ComputedValue possibly improve on that?

To answer that question, I renamed the “old” way of setting a computed property as numToppings_old and re-implement numToppings with @ComputedProperty:
@CustomTag('x-pizza-toppings')
class XPizzaToppings extends PolymerElement {
  // ...
  @ComputedProperty("model.length")
  int get numToppings => readValue(#numToppings);

  int get numToppings_old => model.length;
  // ...
}
I have to admit that there is some pretty cool meta programming going on in there. The @ComputedProperty annotation declares that the next getter is obtained via the Polymer expresssion of model.length. Then, the readValue() method works in conjunction with this annotation to compute the property value. It seems a little strange to repeat numToppings like that—once to declare the name of the computed property and once as a symbol argument to readValue(). My guess is that this is a limitation of annotations—that even though @ComputedProperty is able to associate its argument with the getter immediately below it, readValue() is not able to do the same.

The end result is seemingly unnecessary indirection and the slight DRY violation. So is it worth it?

To answer, I update the containing <x-pizza> element to print both the new and old ways of computing the property:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizzaToppings get firstHalf => $['firstHalfToppings'];
  XPizzaToppings get secondHalf => $['secondHalfToppings'];
  XPizzaToppings get whole => $['wholeToppings'];

  updatePizzaState([_]) {
    print("First half: ${firstHalf.numToppings} (${firstHalf.numToppings_old})");
    print("Second half: ${secondHalf.numToppings} (${secondHalf.numToppings_old})");
    print("Whole: ${whole.numToppings} (${whole.numToppings_old})");
  }
  // ...
}
The result when loading <x-pizza>? Both values are identical:
First half: 0 (0)
Second half: 0 (0)
Whole: 0 (0) 
And, when I update the toppings… Both computed properties are identical for all toppings:
First half: 2 (2)
Second half: 1 (1)
Whole: 2 (2)
So I am a little at loss to explain why I might want to use the @ComputedValue instead of the more concise, simple getter format that I have been using all along.

My understanding for the inspiration behind the new annotation is that, without them, timing issues can arise. I probably need to come up with a better way to produce such issues, but my first inclination is to try to access the properties when the parent <x-pizza> element is first created:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  XPizza.created(): super.created() {
    print("[ctor] First half: ${firstHalf.numToppings} (${firstHalf.numToppings_old})");
    print("[ctor] Second half: ${secondHalf.numToppings} (${secondHalf.numToppings_old})");
    print("[ctor] Whole: ${whole.numToppings} (${whole.numToppings_old})");
  }
  // ...
}
But even that produces valid results:
[ctor] First half: 0 (0)
[ctor] Second half: 0 (0)
[ctor] Whole: 0 (0)
There must be a use-case in which these annotations come in handy, but this is clearly not one of them.

I have a decent handle on how to use the new annotations in Polymer.dart at this point. Tomorrow I will dig through some unit tests to see if I can better understand when to use them.


Day #143

Saturday, May 10, 2014

Reflecting on Class, Reflecting on Object


I don't want to classify reflection in Dart as bewildering, but I confess to being a bit befuddled, at the least.

Let me be clear: I am not criticizing dart:mirrors. I know very little about reflection in static languages, but the little that I do know seems similar to what I see in Dart. In other words, this is probably just the nature of the beast that is reflection. Given that, I seek tonight to better understand reflection of classes—in particular the means to obtaining code information vs. obtaining a reference to the running code.

To obtain a reference to a runtime function, I reflect() on the function by name. To obtain an object that encapsulates the code as it was defined / declared, I can use a property of that reflected function (that property being the function property of a ClosureMirror).

As I found last night, things seem different with classes than functions. Instead of reflecting on a class to obtain a runtime mirror which has a property that points to the class's declaration mirror, there is the reflectClass(), which gives direct access to the code declaration. I am curious why this is the case—why doesn't reflect() on a class return an object reference that has a code declaration property?

To answer, I explore the InstanceMirror that is returned when reflect() is called on a class. If main() is a function and Foo is a class, then the following:
main() {
  print(reflect(main));
  print(reflect(Foo));
}
Will place the following on command output:
ClosureMirror on 'Closure: () => dynamic from Function 'main': static.'
InstanceMirror on Type: class 'Foo'
So what good is an instance mirror on class Foo?

There does not seem to be a way to create a new object from the class instance mirror:
main(){
  var fooMirror = reflect(Foo);
  var foo2 = new (fooMirror.reflectee)();
}
Produces:
$ dartanalyzer main.dart && dart main.dart
Analyzing main.dart...
[error] Expected a type name (/home/chris/repos/gists/reflecting_annotations/main.dart, line 22, col 18)
[warning] Undefined class '' (/home/chris/repos/gists/reflecting_annotations/main.dart, line 22, col 18)
1 error and 1 warning found.
I am unable to find any particular use for reflect(Foo). The Type that the instance mirror is reflecting seems to have no useful properties. I am unable to even access the Foo class from it. The only thing I can do is grab the actual class from the reflectee property so that I can then do useful work with the reflectClass() function:
main() {
  print(reflect(main));
  print(reflect(Foo));
  print(reflectClass(reflect(Foo).reflectee).metadata[0].reflectee);
}
Which produces:
ClosureMirror on 'Closure: () => dynamic from Function 'main': static.'
InstanceMirror on Type: class 'Foo'
[meta] Foo should not be used in real life
Ah, so perhaps that is the use case for reflecting on a class. When the class is not known as runtime (e.g. it is passed into a function), one could reflect on the supplied class, grab the reflectee property, and then use reflectClass(). Or is there some other use that I am missing?


Day #59

Friday, May 9, 2014

Reflecting on Dart Classes and Variables


I have the beginnings of understanding for reflection in Dart.

Coming from a predominantly dynamic language background, I confess that I find most of this painful and awkward. Still, there is something fascinating about it—and not just in a gawking-at-a-car-crash kind of way (though there is definitely some of that). Even if I stick mostly to dynamic languages, this stuff will give me a better appreciation for what is going on. But as Anguar.dart has proven, there is something inherently useful about this by itself.

I left off last night with the ability to reflect on annotations on the current function:
import 'dart:mirrors';

@meta('This is main!')
main() {
  print('[main] Hello!');

  var selfMirror = (reflect(main) as ClosureMirror).function;
  var metaData = selfMirror.metadata;
  print('[main] Meta is: ${metaData[0].reflectee.note}');
}

// The @meta annotation definition
class meta {
  final String note;
  const meta(this.note);
}
The above prints out the following when run from the command-line:
[main] Hello!
This foo is Bob.
[main] Meta is: This is main!
What I would like tonight is to figure out how to reflect on class metadata (i.e. annotations). Just to make things interesting, I move my annotation class and the class on which I would like to reflect into a new code file, foo.dart:
@meta('Foo should not be used in real life')
class Foo {
  String name;
  Foo(this.name);
  toString() => "This foo is $name.";
}

class meta {
  final String note;
  const meta(this.note);
}
Back in main.dart, I import foo.dart, create and use an instance of the imported Foo to make sure it works, and then reflect on the Foo class:
import 'foo.dart';
import 'dart:mirrors';

@meta('This is main!')
main() {
  print('[main] Hello!');

  var selfMirror = (reflect(main) as ClosureMirror).function;
  var metaData = selfMirror.metadata;
  print('[main] Meta is: “${metaData[0].reflectee.note}”');

  var foo = new Foo('Bob');
  print(foo.toString());

  var fooMirror = reflect(Foo);
  print(fooMirror);
}
This prints out the following when run:
$ dartanalyzer main.dart && dart main.dart
Analyzing main.dart...
No issues found
[main] Hello!
[main] Meta is: “This is main!”
This foo is Bob.
InstanceMirror on Type: class 'Foo'
So the toSting() method on Foo seems to work just fine. That is not the problem that I am trying to solve here. What I want is a way to extract metadata from the code. As I found last night, that InstanceMirror that I get by reflecting on Foo is not going to help me. I need something that implements a DeclarationMirror. For last night's function, that was a MethodMirror. For classes, that would appear to be a ClassMirror, but I can find no way to get to a ClassMirror from the reflected InstanceMirror.

The answer turns out to be that I should not be reflecting on the Foo class. Instead I should be reflect-classing on the Foo class with with reflectClass() function:
main() {
  // ...
  var fooMirror = reflectClass(Foo);
  var fooMetaData = fooMirror.metadata;
  print('[main] Foo meta is: “${fooMetaData[0].reflectee.note}”');
}
With that, I am successfully able to grab the note from the @meta annotation:
$ dartanalyzer main.dart && dart main.dart
Analyzing main.dart...
No issues found
[main] Hello!
[main] Meta is: “This is main!”
This foo is Bob.
[main] Foo meta is: “Foo should not be used in real life”
To summarize, to grab metadata from a function, I reflect on the function, access the function property from the ClosureMirror to get a MethodMirror, which contains the metadata. To grab metadata from a class, I reflect-class on the class, which gives me direct access to the metadata. I do not have high hopes that I am going to remember that next week.

Because that is not confusing enough, I find myself wondering about variable declaration annotations. So, what the heck, I annotate the name instance variable in my Foo class with my same custom @meta annotation:
@meta('Foo should not be used in real life')
class Foo {
  @meta('This is the name of the Foo')
  String name;
  Foo(this.name);
}
Getting this meta information at runtime turns out to be fairly easy. Well, maybe not “fairly”—let's call it “relatively” easy. The ClassMirror from reflectClass() has a declarations Map. I can iterate over that to get any declarations that contain annotation metadata with:
main() {
  // ...
  var fooMirror = reflectClass(Foo);
  var fooMetaData = fooMirror.metadata;
  print('[main] Foo meta is: “${fooMetaData[0].reflectee.note}”');

  for (var k in fooMirror.declarations.keys) {
    if (fooMirror.declarations[k].metadata.length == 0) continue;
    var _m = fooMirror.declarations[k].metadata;
    print("[main] $k: ${_m[0].reflectee.note}");
  }
}
I rather like that. It is nice that the ClassMirror has such nice information readily available. I'm not saying that I am going to drop all my dynamic languages or anything, but reflecting on variables makes merciful sense to me.

Day #58

Thursday, May 8, 2014

Reflecting on Annotations


Last night's exploration of annotations in Dart piqued my curiosity over how Angular.dart uses annotations so effectively.

To date, I have only used annotations as glorified code comments. But there is clearly great potential that I am overlooking. So I start with a simple main.dart file that contains a main entry point with an annotation:
@meta('This is main!')
main() {
  print('[main] Hello!');
}
Simple enough, when run from the command-line, it prints out:
$ dart main.dart 
[main] Hello!
It fails dartanalyzer analysis without defining that annotation:
$ dartanalyzer main.dart
Analyzing main.dart...
[error] Annotation can be only constant variable or constant constructor invocation (/home/chris/repos/gists/reflecting_annotations/main.dart, line 5, col 1)
1 error found.
So I define a simple “meta” annotation class:
/// Sweet meta data about a class (or thing)
///
///     @meta('Nice code')
///     class Bar { /* ... */}
class meta {
  final String note;
  const meta(this.note);
}
That satisfies dartanalyzer while my code still runs as before.

That's all well and good, but how do I get at that annotation data? For that, I am going to need to start with the dart:mirrors library:
import 'dart:mirrors';

@meta('This is main!')
main() {
  print('[main] Hello!');
}
Now I need to do something with those mirrors. I have to confess that I find this a non-obvious path from this point. I know that I need to start by reflecting on main():
  var selfMirror = reflect(main);
Reading through Angular.dart source, I know that I need to extract metadata, but it is not entirely clear to me how it does this. What is clear is that metadata is a property of DeclarationMirror. But reflect() is giving me a ClosureMirror, which does not have a DeclarationMirror property or method. After a bit of meandering, I find that ClosureMirror has a function property which just so happens to implement DeclarationMirror.

I can get that meta data (for the @meta annotation which I would have named differently had I known the name of the getter) as a list of InstanceMirror objects. I access just the first and print it out:
import 'dart:mirrors';

@meta('This is main!')
main() {
  print('[main] Hello!');

  var selfMirror = (reflect(main) as ClosureMirror).function;
  var metaData = selfMirror.metadata;
  print('[main] Meta is: ${metaData[0]}.');
}
Which gives me:
$ dartanalyzer main.dart; dart main.dart
Analyzing main.dart...
No issues found
[main] Hello!
[main] Meta is: InstanceMirror on Instance of 'meta'.
I try accessing the note field from my meta class:
  print('[main] Meta is: ${metaData[0].getField(#note)}.');
That gets me the actual notation that I wanted, but I am still working with an object instead of the actual string note:
[main] Meta is: InstanceMirror on "This is main!".
To get the note property, I access the relfectee property of the meta data (which is an InstanceMirror):
import 'dart:mirrors';

@meta('This is main!')
main() {
  print('[main] Hello!');

  var selfMirror = (reflect(main) as ClosureMirror).function;
  var metaData = selfMirror.metadata;
  print('[main] Meta is: ${metaData[0].reflectee.note}');
}
That finally gets me access to the value that I wanted from the annotation:
$ dartanalyzer main.dart; dart main.dart
Analyzing main.dart...
No issues found
[main] Hello!
[main] Meta is: This is main!
I probably have to work with this mirror stuff more to appreciate it. Right now, I am going from ClosureMirror to MethodMirror to InstanceMirror to “reflectee”—all of which seems like quite a journey.

Thinking about it, I can understand the InstanceMirror / “reflectee” relationship. The former has to hold any number of different types of objects (reflectees) in a consistent API, but also allow direct access to the actual object.

I also get the MethodMirror / InstanceMirror relationship. The meta data is made available as a list of these instance mirrors, which it can build via the mirror class definition.

I am not sure that I fully understand the difference between ClosureMirror and MethodMirror. The latter, as a class that implements DeclarationMirror, would seem to have more to do with the language. The ClosureMirror, which implements InstanceMirror would seem to have more to do with the running of the code. I suppose I begin to understand the difference, but it feels like there are some bigger concepts that I would only fully grasp with more experience. Which I may try to get more of tomorrow.



Day #57

Wednesday, May 7, 2014

Dart Annotations Are No Longer Structured


I am down to the very last unaccounted code analysis warnings in the Dart for Hipsters source.

Similar to the problems of the past few days, these manifest as unused imports in my Dart code:
Analyzing test.dart...
[hint] Unused import (/home/chris/repos/csdart/Book/code/classes/private.dart, line 4, col 8)
[hint] Unused import (/home/chris/repos/csdart/Book/code/primitives/types.dart, line 5, col 8)
Both of these two warnings come from custom-coded annotations:
library private_snippet;

import 'package:unittest/unittest.dart';
import '../annotations.dart';
// ...
And:
library types_snippet;

import 'package:unittest/unittest.dart';
import 'dart:collection';
import '../annotations.dart';
// ...
I have already removed some instances of importing this annotations.dart library where it was not being used, but in both of these last two files, the annotations are being used:
      @IntentionalError('Demonstrating no compiler or run error')
      String muppet = 'Piggy';
      muppet = 42;
So what's the deal Dart? I am using these annotations, darn it.

In the annotations.dart file, I define the @IntentionalError annotation as optionally accepting a note:
/// Use when intentionally causing an error.
///
///     @IntentionalError('Demo when semi-colon is omitted')
///     var foo = "bar"
class IntentionalError {
  final String note;
  const IntentionalError([this.note]);
}
I originally introduced annotations in the book's source code because dartanalyzer would include them in its output:
➜  classes git:(master) ✗ dart_analyzer test.dart
file:/home/chris/repos/csdart/Book/code/classes/private.dart:26:31: Field 'collection' has no setter
    25:         @IntentionalError('Demonstrate non-existent setter call')
    26:         var collection = view.collection = new ComicsCollection();
                                      ~~~~~~~~~~
Unfortunately this is no longer the case—dartanalyzer currently includes only the line number and error generated. Still, I like the idea of including structured annotations as a means of consistently annotating my code in a way that unstructured code comments cannot. Except even that no longer seems to apply. If I intentionally use an incorrect format for my @IntentionalError annotation:
      @IntentionalError(1, 2, 3, [4, 5], 'Demonstrating no compiler or run error')
      String muppet = 'Piggy';
      muppet = 42;
Then dartanalyzer proceeds blissfully unaware of a problem. Even if I remove the import of the annotations.dart file and include the annotations class directly in my source file it has no effect. Annotation classes now seem to serve as little more than documentation for a code documentation tool.

I am already grep-ignoring these intentional errors in my test_runner.sh Bash script, so this is not a huge loss. The unused library warnings annoy me though, so I will comment out the import for the time being. If nothing else, the commented annotations.dart will serve to point me in the direction of documentation for my annotations—even if nothing is enforcing the format.

With that, I have all of my Dart for Hipsters tests passing, am ignoring only intentional and/or expected type errors, and have everything passing:
➜  code git:(master) ✗ ./test_runner.sh
#READY
CONSOLE MESSAGE: unittest-suite-wait-for-done
CONSOLE MESSAGE: PASS: [skeleton] the skeleton app returns OK
CONSOLE MESSAGE: PASS: [main] the app returns OK
CONSOLE MESSAGE: PASS: [main] populates the list
CONSOLE MESSAGE: PASS: [numbers] 2 + 2 = 4
...
CONSOLE MESSAGE: PASS: [canvas] player is drawn
CONSOLE MESSAGE:
CONSOLE MESSAGE: All 163 tests passed.
CONSOLE MESSAGE: unittest-suite-success

Static type analysis...
Analyzing test.dart... 

Looks good!
Satisfied, I call it a night. I may still investigate structured annotations in Dart in the context of code reflection (they are used to great effect in Angular.dart). Tomorrow.

Update: Annotation imports (and annotations parameter signatures) DO work if the annotations appear before classes or methods/functions. In the above examples, I am using annotations in variable declarations. I think that should still work—that is, dartanalyzer should see those as legitimate annotations and recognize that they have been imported and/or have invalid parameters.

Actually, this may be more a question of where annotations are allowed to be in Dart code (they were definitely allowed above variable declarations at one point) and what, if anything dartanalyzer should do when annotations are placed in invalid locations.

Day #57

Monday, August 26, 2013

Bleeding Edge May Be Incomplete


I need to stay away from the Dart mailing list because there is so much exciting stuff coming out that it is distracting me from what I need to do in order to finish up the next edition of Dart for Hipsters. That said…

Ooh, shiny! There is a new constant in the meta package: @proxy. The purpose is to indicate to tooling like dartanalyzer and the Dart Editor that a class is a proxy class. I believe that this comes primarily from js-interop proxy classes, which can wrap a whole bunch of JavaScript methods and properties in a fairly empty class.

The js-interop package make calling JavaScript from Dart very nice. But is seems to confuse dartanalyzer to no end. I make extensive use of js-interop in the ICE Code Editor to wrap classes from the JavaScript-based ACE code editor (sorry for the name similarity—I had not heard of ACE before I settled on ICE). The result of wrapping those classes is a barrage of dartanalyzer warnings:
➜  ice-code-editor git:(master) dartanalyzer lib/ice.dart
Analyzing lib/ice.dart...
[warning] There is no such getter 'ace' in 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 226, col 16)
[warning] The method 'setFontSize' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 295, col 40)
[warning] The method 'setTheme' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 296, col 38)
[warning] The method 'setPrintMarginColumn' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 297, col 44)
[warning] The method 'setDisplayIndentGuides' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 298, col 46)
[warning] The method 'setValue' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 300, col 40)
[warning] The method 'getValue' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 301, col 31)
[warning] The method 'focus' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 302, col 27)
[warning] The method 'getCursorPosition' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 307, col 33)
[warning] The method 'gotoLine' is not defined for the class 'Proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 309, col 13)
...
26 warnings found.
In dartanalyzer's defense, the proxy class really does not define these methods, so the warnings are correct. On the other hand, each of these methods is callable once the proxied JavaScript code is ready. Enter the @proxy annotation.

At least hopefully. If I add it to the ICE class in question:
@proxy
class Ace extends jsw.TypedProxy {
  // ...
}
I succeed only in adding yet another warning:
➜  ice-code-editor git:(master) dartanalyzer lib/ice.dart
Analyzing lib/ice.dart...
[warning] Undefined name 'proxy' (/home/chris/repos/ice-code-editor/lib/editor.dart, line 287, col 2)
...
27 warnings found.
Looks like I need an updated version of the meta package.

As awesome as Dart Pub is, one thing that is a pain is the need to peg libraries to specific versions in pubspec.yaml:
name: ice_code_editor
version: 0.0.10
description: Code Editor + Preview
# ...
dependencies:
  crypto: ">=0.6.17+2 <0.6.18"
  js: ">=0.0.24 <0.0.25"
  unittest: ">=0.6.15+3 <0.6.16"
  ctrl_alt_foo: ">=0.1.2 <0.1.3"
Everytime I want to update to the most recent versions, I have to change all of those to any:
name: ice_code_editor
# ...
dependencies:
  crypto: any
  js: any
  unittest: any
  ctrl_alt_foo: any
Then I have to pub update to get the generated pubspec.lock to use the correct versions:
➜  ice-code-editor git:(master) ✗ pub update
Resolving dependencies............
Downloading crypto 0.6.19 from hosted...
Dependencies updated!
Then, to get back to the specific versions, I pub lish the package even though I have no intention of actually publishing. Instead I publish to get the pre-publish warnings, which include the correct version ranges:
➜  ice-code-editor git:(master) ✗ pub lish
Publishing "ice_code_editor" 0.0.10:
...
Suggestions:
* Your dependency on "crypto" should have a version constraint. For example:

  dependencies:
    crypto: ">=0.6.19 <0.6.20"
...
After re-satisfying Pub by copying all listed dependencies back into pubspec.yaml, I try out dartanalyzer on the @proxy again, only to find that nothing has changed.

It turns out that I really, really need to stay away from the mailing list because this is a bleeding edge feature. So I install bleeding edge and do the pub dance again:
➜  ice-code-editor git:(master) ✗ dart --version                                        
Dart VM version: 0.1.2.0_r26680 (Mon Aug 26 17:57:26 2013) on "linux_x64"

➜  ice-code-editor git:(master) ✗ pub update
Resolving dependencies...........
Downloading crypto 0.6.21+3 from hosted...
Downloading stack_trace 0.6.21+3 from hosted...
Downloading meta 0.6.21+3 from hosted...
Downloading browser 0.6.21+3 from hosted...
Downloading path 0.6.21+3 from hosted...
Dependencies updated!
And find… I still get the same dartanalyzer warnings.

Ah well. My current solution that ignores the proxy warning in my Bash test runner will have to do:
results=$(dartanalyzer lib/ice.dart 2>&1)
non_js_results=$(
  echo "$results" | \
    grep -v "is not defined for the class 'Proxy'" | \
    grep -v "There is no such getter '.*' in 'Proxy'"
)
echo "$non_js_results"
non_js_count=$(echo "$non_js_results" | wc -l)
if [[ "$non_js_count" != "2" ]]
then
  exit 1
fi
if [[ "$non_js_results" == *"warnings found."* ]]
then
  echo "Ignoring js-interop warnings..."
fi
echo
...
I suppose that is about the same as the proposed @proxy so I will plan on switching over once it is fully baked.

The lesson learn tonight is that I must avoid the Dart mailing list. No wait, that's probably not a good idea. Bah, there is probably no lesson to be learned. Bleeding edge features sometimes are not quite ready, but are still fun to play with.


Day #855

Tuesday, January 1, 2013

I Love Dart Annotations

‹prev | My Chain | next›

When I first played with annotations in Dart, they seemed neat and all, but I could think of no practical uses. I realize now that I use annotation-like conventions all the time in Rails code—the dreaded FIXME (and its TODO and OPTIMIZE cousins). In fact, in Rails, these are more than conventions, Rails includes rake machinery to extract these comments:
$ rake notes:fixme

app/models/user.rb:
  * [1140] There should be fewer than 1140 lines in this class
  ...
It did not occur to me at first, but, thanks to annotations, "FIXME" notes in Dart can be more than conventions as well. To demonstrate, I create a FixMe constant constructor:
class FixMe {
  final String note, author, date;
  const FixMe(this.note, {this.author, this.date});
}
Using them is a simple matter of including the annotation syntax in my code:
main() {
  @FixMe("Moar better code")
  var cookie = new Cookie();
  print("cookie has ${cookie.number_of_chips} chips");
}
That does not do much of anything just yet. Presumably, in the future, Dart will include mechanisms to interact with the AST in order to extract those easily.

There is a way that I can use annotations today. At times in the code for Dart for Hipsters I include intentionally broken code to demonstrate errors:
class ComicsView {
  // Private because it starts with underscore
  ComicsCollection _collection;
}

main() {
  group("[private]", (){
    test('has no setter', (){
      var view = new ComicsView();

      assign_non_existent_setter() {
        view.collection = new ComicsCollection();
      };

      expect(
        assign_non_existent_setter,
        throwsNoSuchMethodError
      );
    });
  });
}
This unit test passes just fine thanks to the throwsNoSuchMethodError matcher. But when I run dart_analyzer against my code, it catches this as an error:
classes git:(master) ✗ dart_analyzer test.dart
file:/home/chris/repos/csdart/Book/code/classes/private.dart:25:31: Field 'collection' has no setter
    24:       assign_non_existent_setter() {
    25:         view.collection = new ComicsCollection();
                     ~~~~~~~~~~
That is not a huge deal, but when I have hundreds of tests that help me identify parts of the book that are out of sync with the Dart language, I want a way to ignore intentional errors at a glance. Enter my very own annotations.dart library for internal use in my book:
library annotations;

/// Use when intentionally causing an error.
///
///     @IntentionalError('Demo when semi-colon is omitted')
///     var foo = "bar"
class IntentionalError {
  final String note;
  const IntentionalError([this.note]);
}
Now, I can import that library and put it to some use:
library private_snippet;

import 'package:unittest/unittest.dart';
import '../annotations.dart';

// ...

main() {
  group("[private]", (){
    test('has no setter', (){
      // ...
      assign_non_existent_setter() {
        @IntentionalError('Demonstrate non-existent setter call')
        var collection = view.collection = new ComicsCollection();
      };
      // ...
    });
  });
}
Now, when I run my code, the tests still pass:
classes git:(master) ✗ dart test.dart    
PASS: [private] has no setter
And I can identify that this was intentional with a glance as the dart_analyzer output:
➜  classes git:(master) ✗ dart_analyzer test.dart
file:/home/chris/repos/csdart/Book/code/classes/private.dart:26:31: Field 'collection' has no setter
    25:         @IntentionalError('Demonstrate non-existent setter call')
    26:         var collection = view.collection = new ComicsCollection();
                                      ~~~~~~~~~~
The only drawback was that, due to a limitation in Dart annotations, I had to introduce an unnecessary variable assignment. Still, this seems worth the minor inconvenience if it helps me produce a better book.


Day #617

Sunday, December 30, 2012

Annotations in Dart

‹prev | My Chain | next›

While mucking about with constant constructors in Dart, I happened across a mention of a feature that is new to me: annotations. This mention in the spec was the first time that I have ever heard of annotations, so it seems worth stopping for a bit of investigation. I tend to doubt that understanding will come today, but stranger things have happened.

A bit of research reveals that annotations are similar to annotations in Java or attributes in C#, which goes a long way toward explaining why I have never heard of them. That also might explain why I may find it difficult to wrap my brain around them.

Per the spec:
Reflective access to metadata is not yet implemented as of the M2 release.
In other words, I will not be able to use Dart annotations directly in my code—at least not yet. That's just as well, because I doubt that I could figure them out tonight anyway.

What I can do is adopt the BugFix example from C# attributes in Programming C#. The example in there presents attributes / annotations as a mechanism for formalizing comments. In this case, bug fixes. Using what I know about constant constructors, I create a constant constructor for a BugFix class:
class BugFix {
  final int number;
  final String author;
  final String comment;
  const BugFix({this.number, this.author, this.comment});
}
Now, above the Cookie class upon which I have been working laboriously, I can indicate when I have applied bug fixes and a bit of information about them:
@BugFix(number: 42, comment: "Typo")
@BugFix(number: 45, author: "Chris", comment: "Typo")
class Cookie {
  int number_of_chips;
  Cookie({this.number_of_chips:0});
}
If I code up a main clause that puts this code to good use:
main() {
  var cookie = new Cookie();
  print("cookie has ${cookie.number_of_chips} chips");
}
I find that the code is executed normally—as if the annotation did not exist:
$ dart annotations.dart 
cookie has 0 chips
But I have formalize the manner in which bug fixes are associated with code.

I cannot say that I have have ever wanted something like that in a real codebase, but it does help to get a better feel for these beasties. Perhaps tomorrow I can come up with a better example of how I might want to use annotations—at least until they are available in reflection.


Day #615