About Me

I am a computer programmer. I do programming professionally and for a laugh.

Technical stuff on programming, java, DSLs, etc...

Showing posts with label dsl. Show all posts
Showing posts with label dsl. Show all posts

Saturday, 10 April 2010

GUIs, how we learned to love them

Imagine this conversation;

You: H.A.L.?
H.A.L.: Yeah?
You: Buy me a Credit Default Swap on Ford Motor Company to expire next year! (replace CDS with your favorite purchase that does not require visual liking; Broad band connection, mobile phone contract, airline ticket etc. )
H.A.L.: You forgot the magic word.
You: Please?
H.A.L.: Only because you asked so nicely...

We are not quite there yet, natural language processing and all those bots are not mature enough to carry out a meaningful task reliably. So what do we do instead?

We create tasteless, over crowded GUI forms. There is a fundamental problem in our understanding of Graphical User Interfaces. We just assume that they are simple and user friendly. They are not. May be they are to a new user for the first 3 days. After that, your user becomes an experienced user and clicking 12 drop downs and the next button 4 times becomes a burden.

Simply typing into the system what you are trying to do in a specific language is a lot faster for an experienced user. Anyone who watched an airline reservation operator using ALCS terminal would understand what I am talking about. It is a dumb text based terminal from 70s but it is immensely fast. Operators check tens of flights, do bookings etc. in a very short amount of time;

To display the avaliabilty for Delta Airline on 28 October between New York and Los Angeles, type something like:
AN28OCTNYCLAX/ADL
So how about the below to book a CDS;

      define buy CDS "20090409001"
            from 03-Apr-2010 effectiveDate 09-Apr-2010 to 03-Oct-2010   {
                  in LehmanHedge by Ozgur through BankOfAmerica
            } notional of 3000000.0
            on Ford 
            coupons E30_360 {
                  from 03-Apr-2010 to 03-Oct-2010
                  pay on 03-Oct-2010 rate 0.15
            };

Tuesday, 30 March 2010

Embedded Translation

A little semantics goes a long way. I never thought Language Processor as a means of Embedded Translation until I read the article by Martin Fowler.

That is exactly what it does. In a very nice way. Because the language definition and the translation and the interpretation is all in Java, there are no external BNF files of any kind. You even do not ordinarily need to generate a parse tree.

Define you grammar and semantic model together. No Foreign Code or Embedded Helper. Happy Days.

    addProduction("T -> / T T", new Semantic() {
          public Object evaluate(List<Object> childEvals) {
         return ((BigInteger) childEvals.get(1)).divide((BigInteger) childEvals.get(2));
     }
  });

Another DSL Framework

When I joined Thoughtworks back in 2005, the hottest subject was domain specific languages(DSLs).

Martin Fowler wrote about them, a few people in TW developed a few projects with nice DSLs in Ruby and intellij people was developing an ide for crafting your dsl and tools to go with it.

So I took interest not to miss on pub chat. I have had a look at a few of the tools, like antlr and javacc, that one can develop a dsl. They are not easy to work with. You define your language in a BNF format in a text file and then there is a compiler to convert your language to a model and lots of other things you need to do to get a language.

So I did what any real geek would do; I have written a compiler compiler. It is called Language Processor. A software that you can feed in a language definition with its semantic and you get an object that can run your program in your defined language.

The trick is that everything stays in Java. No external files definitions etc. Define your syntax, semantic everyhing and run it all in Java.

I have never found it in me to opensource it. The project has been parked for some years now. My original cunning plan was to also develop an eclipse plug-in to go with your defined language. So you develop a DSL, the plug-in would automagically provide an editor that support syntax highlighting, code completion, outline view build support, run support etc. It is a big task. I have programmed some of it but now I feel like might take a while with 1 hour max to spare between day job and various domestic duties. Besides some clever people with more time in their hands had already came up with a similar thing:- Xtext

So here we are, I am open-sourcing the DSL generator. Productionizing is an important feature anyway eh? It is here: http://sourceforge.net/projects/languageprocess/  You can dowload the eclipse project or check-out the code. Below is a brief tutorial to show what can be done with it.

tutorial 1, 2, 3

My dear friend Shaun Smith once promised to write a logo language like tortoise pen in Language Processor and a tutorial of how to. He is very welcome anytime.

Feel free to nick the entire project or parts of the code. Drop me a note if you use it for something useful.

Another DSL Framework - tutorial 1

Lets start with a simple arithmetic language;

An arithmetic language, a fancy name for a simple calculator, is the simplest DSL to define. The task in hand is to take an arbitrary text of numbers and operators, parse the text and calculate the result watching the precedence of *|/ over +|-. Sounds simple, it is not. If you keep reading, the last bit of the tutorial shows how to define a bit of the Lisp language. But you get the idea, with a Language Framework you can define any language.

E -> E + T | E - T | T
T -> T * n | T / n | n

An expression is either a number or (*|/|+|-) of 2 expressions.
We define 2 different kinds of expressions (E and T) to enforce precedence of *|/ over +|-
This language requires 5 terminals. The number terminal and 4 operation terminals.
We define a terminal in java regexp; so a digit is \\p{Digit}+ and 4 operation terminals are "\\+", "\\-", "\\*", "\\/"

The semantic is the simplest possible; a digit is the value of the identifier and an any of +|-|*|/ is the corresponding operation.

The way you define the semantic is an inlined semantic class where you over-ride the method evaluate. By the time your evaluate method is called, the children parameters are already calculated, so for addition all you have to do is get the first and the third child and add them up. The second child is the + sign. For terminals like digit, you should get the lexeme and convert it to a type meaningful for your language. A BigInteger in our case.

The way you run the calculator is as below:-

            assertEquals(new BigInteger("3"), language.getTargetLanguage().evaluate("2 * 3 - 5 - 7 / 7 * 3 + 2 * 2 + 2 / 2"));

The complete listing of the calculator language is as below;


            BNFLanguage language = new BNFLanguage(); 
            language.addLanguageTerminal("digit", "\\p{Digit}+", new TerminalSemantic() {
                  public Object evaluate(String lexeme){
                        return new BigInteger(lexeme);
                  }
            });
            language.addLanguageTerminal("add", "\\+");
            language.addLanguageTerminal("sub", "\\-");
            language.addLanguageTerminal("mult", "\\*");
            language.addLanguageTerminal("div", "\\/");
            language.addLanguageTerminal(new WhiteSpace());
            language.addProduction("E -> E add T ", new Semantic(){
                  @Override
                  public Object evaluate(List<Object>childEvals) {
                        return ((BigInteger) childEvals.get(0)).add((BigInteger) childEvals.get(2));
                  }
            });
            language.addProduction("E -> E sub T ", new Semantic(){
                  @Override
                  public Object evaluate(List<Object>childEvals) {
                        return ((BigInteger)childEvals.get(0)).subtract((BigInteger) childEvals.get(2));
                  }
            });
            language.addProduction("E -> T ");
            language.addProduction("T -> T mult digit ", new Semantic(){
                  @Override
                  public Object evaluate(List<Object>childEvals) {
                        return ((BigInteger)childEvals.get(0)).multiply((BigInteger) childEvals.get(2));
                  }
            });
            language.addProduction("T -> T div digit ", new Semantic(){
                  @Override
                  public Object evaluate(List<Object>childEvals) {
                        return ((BigInteger)childEvals.get(0)).divide((BigInteger) childEvals.get(2));
                  }
            });
            language.addProduction("T -> digit");
            language.resolveRecursion();

Another DSL Framework - tutorial 2

The BNF like language we used to define the calculator is a language created in the Language Processor itself. Actually you can define your language in the object model. This is what you would do to define E -> E + E

            Terminal terminal = digit();
            Terminal plus = new RegExpTerminal("\\+");
     
            Grammer additonGrammer = new Grammer();
           
            NonTerminal expr = new NonTerminal("E");
            NonTerminal rest = new NonTerminal("T");
           
            Production exprProd = new Production(new ProductionElement[] { terminal, rest }, new Semantic() {
                  public Object evaluate(List<Object> childEvals) { 
                        if (childEvals.get(1).equals(Collections.EMPTY_LIST)) 
                              return childEvals.get(0); 
                        return new Integer(((Integer) childEvals.get(0)).intValue() + ((Integer) childEvals.get(1)).intValue()); 
                  } 
            }); 
     
            Production restProd = new Production(new ProductionElement[] { plus, expr }, new Semantic() { 
                  public Object evaluate(List<Object> childEvals) { 
                        return childEvals.get(1); 
                  } 
            });  
            expr.addProduction(exprProd); 
            rest.addProduction(restProd); 
            rest.addProduction(new EmptyProduction(){ 
                  @Override
                  public Object evaluate(List childResults) {
                        return new Integer(0);
                  } 
            }); 
           
            additonGrammer.addProductionElement(expr); 
            additonGrammer.addProductionElement(rest); 
            additonGrammer.addProductionElement(terminal);

The grammar is actually defined as

E -> TE'
E' -> +TE' | e
 
as the Language Processor is a recursive descent parser and you need to left factorize your grammar to consume tokens as you recurse.

This is a boring subject and the BNF like grammar sorts it out for you. If anyone is really interested, buy me a beer, I will tell you all about it.

Another DSL Framework - tutorial 3

I went as far as defining a bit of the lisp language, up to the point where you can define a function and call it. Designing a language is not an easy task and it was never my intension to write a tool to replace the Java parser.

Where I see the DSLs to be most useful is to replace user interfaces that naturally fall into a language like area but utilized by end-users rather than programmers. For example, a scenario engine would be a very natural fit for a DSL where you have light weight nature of text to define scenarios and the power of a structured language. I will write more about how DSLs can very naturally replace some of the most cumbersome UIs.

Below is a snippet from the Lisp language. If you check out the project, all of this is in the class

com.leantell.lp.lisp.LispArithmeticLanguage.

Have fun, let me know if you do anything interesting with Language Processor.

Function defintion in Lisp;

addProduction("DEFUNC -> ( defun identifier ( IDENTIFIERS ) STM )", new Semantic() {
            @Override
            public java.util.List<Object> evaluateChildren(java.util.List<ParseNode> children) {
                  String name = ((String) children.get(2).evaluate()).toUpperCase();
                  List<String>parameters = (List<String>) children.get(4).evaluate();

                  ParseNode code = children.get(6);
                  Function function = new Function(name, parameters, code);

                  context.put(name, function);

                  List<Object> result = new ArrayList<Object>();
                  result.add(name);
                  return result;
            };

            @Override
            public Object evaluate(List<Object> childEvals) {
                  return childEvals.get(0);
            }
      });

Function call in Lisp;

addProduction("FUNCTION_CALL -> (identifier ATOMS )", new Semantic() {
      @Override
      public Object evaluate(List<Object> childEvals) {
            String name = ((String) childEvals.get(1)).toUpperCase();
            List<Object>values = (List<Object>) childEvals.get(2);

            Function function = (Function) context.get(name);
            List<String> parameters = function.getParameters();
            for (int i = 0; i < parameters.size(); i++) {
                  targetLanguage.setVariableValue(parameters.get(i),  values.get(i));
            }
            return function.getCode().evaluate();
      }
});

How to define and call a function;

            assertEquals("FACT", lisp.evaluate("(defun fact (x) (if (eq x 0) 1 (*  x (fact (- x 1)))))"));
            assertEquals(new BigInteger("1"), lisp.evaluate("(fact 0)"));
            assertEquals(new BigInteger("6"), lisp.evaluate("(fact 3)"));
            assertEquals(new BigInteger("24"), lisp.evaluate("(fact 4)"));

Followers