Tuesday, September 11, 2012

I've released a new version of akmacros library for Scala 2.10.
The release includes a new macro called 'factory'. Thanks to the new macro it is possible to construct a class
with a public default constructor just passing a function to the generated factory of the class. The function
receives symbol of an argument of the constructor and returns value for this argument. If function returns None, then
default value for the argument is evaluated (provided that it is defined for the given argument). Here is the example:

Writing less boilerplate code for Play Json

Just to demonstrate the way macro functions can simplify your code I've created a small project on github.
The project includes Json library from the Play2.0 framework mostly as-is. The only changes I did are related to making it work on scala 2.10
(upgraded it to patched jerkson and so on).
You might be interested in this file.
It is the only file that I implemented in that project in order to add support for macros to the Play Json.
Following the same pattern, you can easily use almost any other Json library like this.

Lets look what it gives you without any reflections.. Lets start with something simple:

Note that we parsed halfObjJs three times. And 'num' was always different. That is because value for 'num' is missing in the halfObjJs and so the expression for default
value was used (which is Random().nextInt, see defintion of Simple class). How about parametrized classes? Lets try:

In the real world it is unlikely that you will use completely unrestricted types (like T in the example above) in your case classes with json.
It is more likely that there will be a (sealed) trait and some set of its subtypes. Lets see how it works. First, we will define some more case classes:

Pay attention, that Json for QuitMessage and Heartbeat classes has no type information or anything! It's just plain json with domain fields only.
That's why messageReads has those jsHas occurances in its implementation, that is a little help for identifying which json object is what subtype of Message.
Lets see that reading from json still works:

Actually there is another way to do the same. You can inject an extra field into json object when serializing one of subtypes of an abstract type and use it
as a guidance for reconstructing objects from json. It is really easy. Lets modify messageReads and messageWrites like this:

It works.. But you can do more. Recall (if you looked at the implementation) that jsonate function was defined like this:

defjsonate[T: Writes](t: T, args: Any): JsValue = Json.toJson(t)

The function is used to make a json value out of field's value. It is applied to each field.
So you can define your our function that does post-processing (pre-processing?) and use it with a macro. The second argument (args) might be a parameter set given to annotation,
this gives you even more power for writing complex json serialization easily.

And not only JSON. Using the same approach you can (de)serialize object from/to XML...

Pros of akmacros-json

Domain classes are separated from any notion of JSON

Full control over serialization/deserialization

Easy to use

Easy to extend or implement your own

No runtime reflections used

Cons of akmacros-json

Depends on Jerkson which is officially unavailable for Scala 2.10 (you need to build it from my fork
(in order to build it you will need also this forked project))

Includes a copy of Play Json

Scala 2.10-M7 has many bugs related to implicits, value classes... so implementation as you might have noticed is not perfect in terms
of performance (defs are used instead of vals)

I hope things will change really soon with the release of Scala 2.10.

About general purpose macros

This tiny macros addition is built on top of Play JSON (which is built on top of Jerkson (which is built on top of Jackson))
and akmacros (which doesn't have dependencies).
Checkout 78 lines long implementation here.
See https://github.com/akshaal/akmacros for a bit more
information about using akmacros with sbt.

Wednesday, September 5, 2012

I liked the idea of using fields macro in scala so much so I created a dedicated project for this macro to start reusing it in the different projects I did. Here it is.

Few words about implementation of this macro

The code has been reworked and now it is possible to transform field value using a supplied function. It means that Field and Fields types, and fields macro signatures are changed. In addition, there is a new convenient macro called allFields. I.e.:

allFields is the new function that lists all public value members enclosed in the given type regardless of annotations.
R in a Field(s) type stands for RETURN and represents type of a value returned by the field getter transformed using the supplied function. Value transformer function is passed into the macro using its symbol. You might wonder why aren't we just using something like f : T => R forSome { typeT } ? That's because you can't pass the following function that way:

deftrans[T : TypeClass](x : T) : Int = ???

(which is just a sweet way of saving some keystrokes by not writing this:)

deftrans[T](x : T)(implicittc : TypeClass[T]) : Int = ???

i.e. you can't pass function with TWO parameters (one of which is implicit parameter) where a ONE parameter function is expected. That is quite obvious but anyway.. So we use Symbol (in the spirit of Lisp). As you might guess by looking at the snippet below, it is expected that the symbol is constructed directly and not passed by reference:

getFunBodyTree illustrates what signature is really expected for the transformer function: in addition to field value, all arguments of the annotation are passed into the function (or None if no annotation used or annotation has no arguments). For example, you can't use Predef.identity function, instead, you should use valueIdentity which is (already) defined like this:

defvalueIdentity[X] (value : X, annotationArgs : Any) : X= value

Having annotation arguments provided for the currently processing field gives you possibility for further customization of how the value is transformed. Now lets do an example.

Real-world example

Suppose you want to serialize your custom classes into JSON with no boilerplate code what so ever. That is how you can do it with this only (general-purpose) macro. Lets define some generic Writes typeclase provider:

The function shown above implicitly creates Writes for any type T which has an implicit instance of type Fields[T, JsValue, _] (read it like "List of fields of class T along with function to get value of type JsValue for each field"). Now lets define the transformer function, it will be used for serialization of field values:

Saturday, August 18, 2012

Here is a short example of how one can leverage SIP-16 introduced in Scala-2.10.
(The source code you will find below is expected to be compiled on Scala 2.10-M7. Note, that -M6 provides a slightly different set of API for macro.)

Lets define a macro that makes it possible to traverse value fields of a (case) class. First, we import what we will use:

The macros, we are implementing, will be located in 'annotated' object since Scala allows usage of type aliases inside object (unlike package namespace).

objectannotated {

Any field belongs to a class (denoted as I). An annotated field might have useful information given by arguments on annotation. Type of the annotation arguments is denoted as A. Here is the definition of the Field class:

/**
* An object of this class represents an annotated field.
* @tparam I type of class the field belongs to
* @tparam A type of annotation arguments (TupleX or None)
* @param name name of the field
* @param get function that returns field value of an instance given as argument to the function
* @param args list of arguments to the annotation found on the field
*/caseclassField[I <: AnyRef, A <: Product](name : String, get : I => Any, args : A)

("Args
Note that here and further below we use types (like AbsTypeTag) which are from the context 'c'. That is a compilation context of the application which the scala compiler will construct for the source code where the macro invocation is faced (not exactly but..).

Now lets import types and values (like Select, Ident, newTermName) from the universe of the application the macro is currently used in:

Still no macro was used. Now here it comes. First, we define case class. Next, we gather annotated fields in the definition of personPrettyFields. When you run it in REPL, it is quite important to use :paste, otherwise annotation of the case class will be lost because subtypes of StaticAnnotation are visible during compilation only (REPL calls a new scala compiler for each expression reusing binary classes compiled during previous steps). So: