Vacation!

July 1, 2008

Today is the first day of my four week long vacation.
So I will finally get some time to get some work done on Caramel.

Well I’m off to get some sun and some beer :-)

I have added the Caramel code generator to my public repository at google code.
http://code.google.com/p/alsing/

Please note that this is very very alpha and not actually useful yet.

Before it can be used I need to finish the template support and fully implement the DB meta data importer.

But if you are interested in this kind of stuff and want to help out building it, please let me know.

Parsing and languages have always been one of my main interests when it comes to programming.
So a few weeks ago I decided to buy the “red dragon book” from Amazon.com.
http://www.amazon.com/Compilers-Principles-Techniques-Alfred-Aho/dp/0201100886
(note: For some reason I managed to buy the edition from 1986 instead of 2006)

It is definetly one of the most interesting books I’ve ever read.
Maybe the most interesting part is that It is very humbeling to see how bloody brilliant those old computer science language guys are.

My biggest problem at the moment is that I fall asleep every 3-4 pages.
It is not because of boredom or anything, it’s just that I have to pause and reflect on what I have read for each page and that’s when I fall asleep :-)

So if you are into geeky stuff like domain specific languages and such, read the book, it’s awesome!

A few days ago I and Fredrik Normén had a discussion about argument validation here: http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx

The discussion got kind of stuck in my head, so I have been thinking a bit more about it.
And today I came up with a solution that I think is both clean and easy to extend.

Fluent Argument Validation Specification

The idea is to transform the value of the argument that should be validated into an object which contains both value and argument name, so that this object can be passed around to different fluent validation methods.
By doing this, we can now add new extension methods for the generic argument class in order to extend our fluent validation API.

A fulent API will let us read and write the requirements just like a specification for each argument.

Here is an example of the consumer:

public static void MyMethod(string someArg,int someOtherArg)
{
    someArg.RequireArgument("someArg")
           .NotNull()
           .ShorterThan(10)
           .StartsWith("Roger");

    someOtherArg.RequireArgument("someOtherArg")
                .InRange(10,100)
                .NotEqual(33)
                .NotEqual(51)
    //do stuff
}

As you can see, we only have to specify the argument name in the require method.
The require method will return an instance of “Validation<T>” which is our generic argument class.

The argument class have no own instance methods, instead we have extension methods which are fluent so that we can call them in a chain.

These extension methods can operate directly on “Validation<T>”,with or without generic constraints.
We can also add extension methods for specific types, like: “Validation<string>”, and thus allow us to validate strings in different ways than other types.

But enough talking, here is the required code to accomplish this:

The implementation of the Validation<T> class:

public class Validation<T>
{
    public T Value { get; set; }
    public string ArgName { get; set; }
    public Validation(T value, string argName)
    {
        Value = value;
        ArgName = argName;
    }
}

The implementation of the Require method:

public static class Extensions
{
    public static Validation<T> RequireArgument<T>(this T item, string argName)
    {
        return new Validation<T>(item, argName);
    }
}

And the implementation of the different validation methods:

public static class ValidationExtender
{
    [DebuggerHidden]
    public static Validation<T> NotNull<T>
    (this Validation<T> item) where T : class
    {
        if (item.Value == null)
            throw new ArgumentNullException(item.ArgName);
        return item;
    }
    [DebuggerHidden]
    public static Validation<string> ShorterThan
    (this Validation<string> item, int limit)
    {
        if (item.Value.Length >= limit)
            throw new ArgumentException(
                  string.Format(”Parameter {0} must be shorter than {1} chars”,
                  item.ArgName,limit)
                                        );
        return item;
    }
    [DebuggerHidden]
    public static Validation<string> StartsWith
    (this Validation<string> item, string pattern)
    {
        if (!item.Value.StartsWith(pattern))
            throw new ArgumentException(
      string.Format (”Parameter {0} must start with {1}”,item.ArgName, pattern)
                                       );
        return item;
    }
    //other validation methos
    …..
}

The [DebuggerHidden] attribute is optional, but it will make your stacktrace look better since it will break in the method that performs the Require call, and not inside the validation methods.

So by using the debugger hidden attribute we can get the behaviour as seen on this screenshot:


 

Enjoy

//Roger

I’ve been working some more on the UML editor for Caramel.
I’ve added comment elements and relations to the editor now:

 

Caramel - Screenshots

April 20, 2008

I’ve been working on the class designer this weekend and made some nice progress.
It is now possible to add interfaces and enums to the designer surface.
(and alter their members ofc)

The next thing I have to dig into is to add support for association and inheritance lines.

//Roger

I’ve created a little sample on how to make your own .NET compiler.
The compiler uses Gold parser for parsing and Reflection.Emit to generate the compiled .exe file.

Initially I intended to make a sample on how to use Gold parser to parse and then compile Linq expressions, thus the name GoldLinq, however, Linq have now been replaced with Reflection.Emit.

Links:
My compiler source: http://www.puzzleframework.com/Roger/GoldLinq.zip
(C# VS.NET 2008 solution)

Gold parser: http://www.devincook.com/goldparser/
Grammar: http://www.devincook.com/goldparser/grammars/index.htm

How it works:

  • Gold parser - Calitha engine is used to parse the source code into a parse tree
  • The parse tree is transformed into a typed AST
  • The AST is verified using visitor pattern, the verifier handles type inferrence and auto casts.
  • The AST is optimized using visitor pattern, the optimizer replaces constant expressions and statements.
  • The AST is compiled into CIL/MSIL using visitor pattern.
  • If successful, the compiler will generate a file called “output.exe” in the same folder as the compiler

Samples:

Hello world 

display 'Hello World!'

 Have a nice day:

Display 'What is your name?' Read Name
Display 'Hello, ' & Name & '. Have a nice day!'

Blastoff: 

assign n = 10
while n >= 1 do
    display n
    assign n = n - 1
end
display 'Blast off!'

Miles and kilometers: 

Display
'Do you want to convert 1) Miles to Kilometers or 2) Kilometers to Miles?'
Read Choice        

if Choice == 1 then
    Display 'Please enter the number of miles' Read Miles
    Display Miles & ' Miles = ' & (Miles * 1.609)  & ' Kilometers'
else
    Display 'Please enter the number of kilometers' Read Kilometers
    Display Kilometers & ' Kilometers = ' & (Kilometers / 1.609)  & ' Miles'
end

Secret number: 

Assign SecretNumber = 64 

Display 'Please guess the secret number'
Read Guess          

While Guess <> SecretNumber Do
    If Guess < SecretNumber Then
        Display 'Your guess was too LOW. Try again.' Read Guess
    End    
If Guess > SecretNumber Then
        Display 'Your guess was too HIGH. Try again.' Read Guess
    End
End     

Display 'Correct!'

How to compile the samples:

First you need a source file to compile, just create a normal textfile and paste one of the samples above into it.
Once you have the code file you can compile it using the compiler:

c:whatever\bin\debug> GoldSample.exe mysource.txt

When the compiler is done, you can start the compiled application with:

c:\whatever\bin\debug> output.exe

The code is somewhat too big to cover in a blog post, so if you have any questions feel free to ask in the comment section.

//Roger

DSLisp

February 12, 2008

MyLisp is now named DSLisp - Domain Specific (Language) Lisp.

I have published it as a project on CodePlex:
http://www.codeplex.com/DSLisp

The new name imples the purpose of the project.
To act as a host for DSL’s.

The idea is to compile your DSL into the DSLisp AST.
And then run your DSL inside the DSLisp engine.
By doing this you can very easily add single step debugging and breakpoint support to your DSL. 

See the codeplex site for more info.

I’ve added multi threading support to MyLisp today.

The earlier implementation of the callstack was not up to the task, so I had to rewrite it completely.
The new callstack is based on stack frames which can hold local symbols.

So behold! :-) , the first multi threaded application in MyLisp

(func FooBar ()
  (
    (let i 0
      (for i 0 1000000
        (print (format "thread {0}" i)))))) 

(= thread (new-thread FooBar))
(call thread Start)
(for i 0 1000000
  (print (format "main {0}" i)))

Sure , the “new-thread” function is a bit of cheating, I dont have any generic code for .NET delegate <-> MyLisp delegate yet.
So I have to use hard coded methods to cast from and to delegates for now.

OK, this was not much of a real post, more of a “yay, it works!” shout :-)

Lazy evaluation

February 3, 2008

My Lisp now supports Lazy evaluation.

I’ve made it possible to define per function if it should use lazy or eager evaluation.
(The next step will be to decide that through code analysis.)

For those who don’t know what lazy evaluation is about, the purpose of lazy evaluation is to avoiding unnecessary calculations.

Take the following example (in C#)

public static void FooBar ()
{
  int res = GetSomeValue();        
  //pass the value to a logger
  Logger.Log ("value of GetSomeValue was:" , res);
}          

public static int GetSomeValue()
{
 //some realy heavy algorithm here
 ... heavy code ...
 ... more heavy code ...  
 return res;
}           

... logger code ...           

public void Log (string message,params object[] args)
{
 //lets assume we can attach multiple providers to our logger
 foreach (LogProvider provider in LogProviders)
 {
  provider.WriteString(message,args);
 }
}

In this case, we would always need to execute “GetSomeValue” first in order to call our logger.
EVEN if there is no provider attached to the logger.
So, even if we don’t want to write anything to disc or DB or anywhere, we would still have to call “GetSomeValue”.

It is ofcourse possible to add special code to your consumer , “if (logger.Providers.Count == 0) then ignore…”.
But that forces you to add responsibility to your code that isn’t supposed to be there.
My FooBar method should not have to care about the number of log providers etc.

Lazy evaluation can solve this for us.
By applying Lazy evaluation to ”GetSomeValue” method, we would only need to call the method once the result of it is used.
Sounds odd?
How can you use the result before the code have executed?

It’s quite simple, its done through delegates, we can even do this in C# by passing delegates around.
However, you do have to know that you are passing delegates and not simple values, so it is not very implicit in C#.

In My Lisp, the code would look something like this:

(func FooBar ()
    (
        (= res (GetSomeValue))
        (call logger log "value of GetSomeValue was:" res)))     

(lazy-func GetSomeValue ()
    (
         ... heavy code ...
         ... more heavy code ...
        (return res)))     

...logger...     

(func Log (message data)
    (
        (foreach provider Providers     

            ;;; GetSomeValue will be called here
            (call provider WriteString message data))))

As you see, there is no special code to handle the lazy evaluation.
The only thing that I need to do was define “GetSomeValue” as a lazy function.

So if we do not have any log providers attached to our logger, “GetSomeValue” will never be executed, since its result is never needed.

And if there are providers attached, “GetSomeValue” will be executed from within the foreach loop inside the logger.
(Once, then caching its value)

Pretty slick IMO.