Hijacking Ioke syntax


One of the nicer things with Ioke is that the syntax is highly flexible. This means that features that are generally considered part of the parsing step is not so in Ioke. There are still limitations on what you can take over, of course.

Another reason you can do much with Ioke’s syntax is that all operators are just method calls. This means you can override them in subclasses, which means these syntax changes can be totally localized.

A third way you can change things is by changing things at a global level, but only temporarily. This is possible since any cell in Ioke can act as a dynamic cell (or special) – by using the “let” method. This means you can make some very interesting changes to the syntax.

Understanding these three techniques make it possible to very easily create internal DSLs in Ioke, that feel like they are external. A fourth way of achieving this can be to massage message chains after the fact, to transform them into a different structure. You can do this directly, by working with the first class message structures – or if you don’t have to extravagant needs, you can interject specific behavior into the operator tables.

This post will give a quick introduction to these techniques, but it can’t really cover them all in full.

Flexible and polymorphic syntax elements

The things that in Ioke look like syntax elements but are mostly just message sends allow you to change the behavior locally of some things. Some examples of things where this is possible is in the creation of literals (such as numbers, texts and regexps), regular cell assignment (with =), and the creation of literal lists and dicts.

OK, to make this concrete, let me show a few examples. To start with, take the literals. The way literals work is that they will actually be translated into message sends. So when the parser see a number, it will generate a message send to “internal:createNumber”, and insert that into the message chain. This means you can override and change this behavior, which is something I do with my parser combinators example. As an extremely small example, take this code:

Parser(
  "foo" | "bar" | 42
)

This example creates a new parser that will parse either the literal string foo, the literal string bar, or the number 42. But how can we implement this? The method “|” is not even implemented for Texts in Ioke, and they definitely doesn’t return anything useful for the parser. We don’t want to override it to return the right thing either – it wouldn’t be a general solution – and what if someone wanted a parser that only matched one literal string? It’s clear that we need to hook into the handling of literals. (There is an alternative, we will talk about that in the final piece).

At this stage it might help to take a look at the canonical AST structure of the above code. It would look like this: internal:createText(“foo”) |(internal:createText(“bar”)) |(internal:createNumber(“42”)). With this structure, it should be more obvious how we can implement everything. The code for the above would look like this:

BaseParser = Origin mimic do(
  | = method(other,
    OrParser with(context: context, first: self, second: other)
  )
)

TextParser = BaseParser mimic
NumberParser = BaseParser mimic

ParserContext = Origin mimic do(
  internal:createText   = method(raw,
    TextParser with(context: self, text:   super(raw)))
  internal:createNumber = method(raw,
    NumberParser with(context: self, number: super(raw)))
)

Parser = dmacro(
  [code]
  context = ParserContext mimic
  code evaluateOn(context, context)
  context
)

The interesting pieces are in ParserContext. Inside it we override internal:createText and internal:createNumber to return parsers for their corresponding type. Notice how we call out to “super” to get the actual literal result. We then evaluate the argument to the Parser-method in the context of a newly created parser context. The only thing missing in the above code is the OrParser, and the actual matching pieces.

The other ways of hijacking syntax generally depend on executing code in a specific context, like the above.

I mentioned that “=”, [] and {} are overridable. Say that you for example like the syntax of blocks in Smalltalk, and want to use that within an internal DSL. That is actually extremely easy:

Smalltalk = Origin mimic do(
  [] = cell(:fn)
)

Smalltalk do(
  x = ["hello world" println]
  x call
  x call
)

Here we just assign [] to be the same as the method “fn” within the Smalltalk object. The same thing can be done for other operators, if wanted.

Using let to override syntax

As mentioned above, you can use the let method to override syntax (or any method really) for a specific bounded time. Lets say we want to do the above operation (Smalltalk blocks) for the duration of some execution. We can do it like this:

let(DefaultBehavior Literals cell("[]"), cell(:fn),
  x = ["hello world" println]
  x call
  x call
)

This will override the cell specified in the first argument with the value in the second argument – and then restore it at the end of the let-method. This is really not recommended for something like the [] method – as it will cause all kinds of problems in the internal implementations of methods. But you can definitely do it.

Transforming message chains

There are basically two techniques here. The first one is simply to add or remove or update the operator table
so that you can add operators that weren’t there before, or change the way they behave. This is not restricted to things with weird characters in them – indeed, in Ioke anything that appears in the operator tables count as an operator. A specific example of this is “return”. It can act as a unary operator, meaning it is possible to give return an argument without having parenthesis surrounding that argument.

To find out more information you can take a look at the documentation for Message OperatorTable here: http://ioke.org/dok/kinds/Message/OperatorTable.html.

The other way of transforming message chains is to actually take them apart and put them together again. I am planning a blog post dedicated to how to work with this, but I’ll take a quick peek at how to do it now. Lets take the earlier Parser example and see an alternative way of creating the text and number parsers without actually overriding the literals creation.

reformatCodeForParsing = method(code,
  ourCode = 'nil
  head = ourCode
  code each(msg,
    case(msg name,
      :internal:createText, ourCode -> ''createTextParser('msg),
      :internal:createNumber, ourCode -> ''createNumberParser('msg),
      :"|", ourCode -> ''withOrParser('(reformatCodeForParsing(msg arguments[0]))),
      else, ourCode -> msg mimic
    )
    ourCode = ourCode last
  )
  head
)

Parser = dmacro(
  [code]
  reformatCodeForParsing(code) evaluateOn(Ground, Ground)
)

This code is actually a bit annoying, but what it does is quite useful. What it does is that it will take the code above (“foo” | “bar” | 42) and restructure that into (createTextParser(“foo”) withOrParser(createTextParser(“bar”)) withOrParser(createNumberParser(42))).

The only thing that is a bit inscrutable is the way new message chains are put together using quoting of different kinds. I’m going to go into this with more depth in the next blog post. I am also working on a tree rewriting approach for making these kind of transformations much more idiomatic and readable.

So, this post have been a small introduction to several things you can do with Ioke to tweak its syntax. There is much more behind all these features, of course, and they all come from the fact that Ioke tries to unify and simplify all concepts as much as possible.



The Ioke reflector


Ioke is a very object oriented language. The amount of concepts in it is also quite small. I’ve tried to factor the implementation into smaller pieces, which are then composed into the full object hierarchy. One of the side effects of this is that it is possible to make objects that can’t be handled generically, since they don’t have all those things you expect objects to have. There is no requirement on Ioke objects to actually have a core set of methods. Things can be totally blank. Of course, a completely blank object is not very useful in itself…

So what kind of things become problematic then? Well, lets first talk about blank slates. In Ioke it’s pretty simple to create one – you just create an object, and then call the method “removeAllMimics!”. What you have after that point is something that is totally empty (unless if you added cells to the object itself before hand).

Now say that you want to add back a mimic to that object. Or say you want to add a new cell. As it happens, “=” is just a method on the Base kind. To add a new mimic, you generally use either “mimic!” or “prependMimic!”. These are both methods on ReflectionBehavior. So none of these methods are available.

Another example is mixins. In Ioke, a Mixin is nothing other than a regular object, except that it doesn’t have Base or DefaultBehavior in its mimic chain. Instead, the root of all mixins is the kind Mixin. Now, Mixin actually defines a copy of “=” and a few other things from Base. But it doesn’t allow you to add new mimics to mixins for example. This is a bit annoying – but since you have access to “=” you can actually fix it, by coping the “mimic!” method from ReflectionBehavior.

There are other circumstances where you want to be able to handle any object whatsoever in a uniform manner, introspect on a few things and so on. That wasn’t possible.

I’ve been considering these problems for a while, and finally decided that the pragmatic way of solving it is to add some methods that can be used to take a part and modify objects from the outside. I call the namespace that gives this functionality Reflector. Now, remember that you shouldn’t use the Reflector unless you’re certain that your objects need to be handled in that specific way. It’s more verbose, and not as object oriented as the methods that exist on regular objects. But it does allow you to do certain things on all objects in the system.

The rules are simple – all methods on Reflector are based on other methods in Base or ReflectionBehavior. They have the same name, except that they all start with “other:”. They all take an initial argument that is the object to work on. So, say we have an object “bs” that is a blank slate. We want to add a cell to it. We can do that simply like this:

Reflector other:cell(bs, :foo) = 42

Here we set the cell “foo” on the blank slated object to the value 42.

The problem of adding a new mimic to a mixin is easily solved too. Say we have an object ExtraEnum that we want to mix in to Enumerable. We can do it like this:

Reflector other:mimic!(Mixins Enumerable, ExtraEnum)

And so on. You can see all the methods available on Reflector in the doks.

As mentioned, the Reflector is a pretty specialized tool, but it’s totally indispensable when you need it. I will pretty soon sit down and rewrite DokGen to use it, since DokGen is a typical example of something that really need to be able to handle all objects in a generic way.



Ioke talk at the Chicago ACM


On June 10th, I will give a talk about Ioke at the Chicago ACM. This is very exciting, and I hope to see many languages people there. It’s bound to be an interesting presentation, I think.

The talk is going to be held at Roosevelt University. You can find more information here: http://www.chicagoacm.org/.



Ioke geek night in London


I will hold a presentation about Ioke in London, Thursday 14th. This will be held at Skills Matters location. You can find more information, and sign up, here: http://skillsmatter.com/event/java-jee/ljc-meetup-346.



Ioke for the CLR released


The last two weeks I’ve been furiously coding away to be able to do this. And I’m finally at the goal. I am very happy to announce that the first release of Ioke for the CLR is finished. It runs on both Mono and .NET.

Ioke is a language that is designed to be as expressive as possible. It is a dynamic language targeted at several virtual machines. It’s been designed from scratch to be a highly flexible general purpose language. It is a prototype-based programming language that is inspired by Io, Smalltalk, Lisp and Ruby.

Homepage: http://ioke.org
Download: http://ioke.org/download.html
Programming guide: http://ioke.org/wiki/index.php/Guide
Wiki: http://ioke.org/wiki

Ioke E ikc is the first release of the ikc Ioke machine. The ikc machine is implemented in C# and F# and run’s on Mono and .NET. It includes all the features of Ioke E ikj, except for Java integration. Integration with .NET types will come in another release.

Features:

  • Expressiveness first
  • Strong, dynamic typing
  • Prototype based object orientation
  • Homoiconic language
  • Simple syntax
  • Powerful macro facilities
  • Condition system
  • Aspects
  • Runs on both the JVM and the CLR
  • Developed using TDD
  • Documentation system that combines documentation with specs

There are several interesting pieces in ikc. Among them I can mention a new regular expression engine (called NRegex), a port of many parts of gnu.math, providing arbitrary precision math, and also an implementation of BigDecimal in C#.



Ioke Geek night at ThoughtWorks Bangalore


Tomorrow (Tuesday) evening, at 6pm, I will give a presentation about Ioke, at the ThoughtWorks office in Bangalore. This is an open event. More information and registration here: http://www.thoughtworker.com/events/geeknight-ola-bini.



Ioke E released


After a slightly longer development cycle then the last time, I am finally happy to announce that Ioke E has been released.

Ioke is a language that is designed to be as expressive as possible. It is a dynamic language targeted at the Java Virtual Machine. It’s been designed from scratch to be a highly flexible general purpose language. It is a prototype-based programming language that is inspired by Io, Smalltalk, Lisp and Ruby.

Homepage: http://ioke.org
Download: http://ioke.org/download.html
Programming guide: http://ioke.org/wiki/index.php/Guide
Wiki: http://ioke.org/wiki

Ioke E is the third release of Ioke. It includes many new features from Ioke S, among them full support for Java integration (including implementing interfaces and extending classes), many new methods in the core libraries, IOpt, TextScanner, BlankSlate, better support for regexp interpolation and escapes in regexps, support for Unicode analysis and much more.

Ioke E also includes a large amount of bug fixes.

Features:

  • Expressiveness first
  • Strong, dynamic typing
  • Prototype based object orientation
  • Homoiconic language
  • Simple syntax
  • Powerful macro facilities
  • Condition system
  • Aspects
  • Java integration
  • Developed using TDD
  • Documentation system that combines documentation with specs
  • Wedded to the JVM

The many things added in Ioke E could not have been done without the support of several contributors. I would like to call out and thank:
T W <twellman@gmail.com>
Sam Aaron <samaaron@gmail.com>
Carlos Villela <cv@lixo.org>
Brian Guthrie <btguthrie@gmail.com>
Martin Elwin <elvvin@gmail.com>
Felipe Rodrigues de Almeida <felipero@gmail.com>
Wes Oldenbeuving <narnach@gmail.com>
Martin Dobmeier <martin.dobmeier@googlemail.com>
Victor Hugo Borja <vic.borja@gmail.com>
Bragi Ragnarson <bragi@ragnarson.com>
Petrik de Heus



Laziness in Ioke


Since all the rage in blog posts at the moment is laziness, I thought I’d take a look at how something can be lazy in Ioke. There are several ways of doing this, but most of them are really easy. I haven’t decided exactly how the implementation in core should look like, but it would probably be something like the following.

Basically, for laziness in a dynamic language you want something that lazily evaluates itself when requested the first time, and after that always return that value. Something like this:

foo = Origin mimic
foo bar = lazy("laziness has run!" println. 42)
"helo" println
foo bar println
foo bar println

Here we create a lazy values that returns 42, and prints something to prove what is happening. The lazy-method contains the magic. Any code could be submitted here. In this case the code can lexically close over variables outside, if wanted.

How would we implement “lazy” then? Something like this would suffice:

DefaultBehavior lazy = dmacro(
  [code]
  laziness = fnx(
    result = code evaluateOn(call ground)
    cell(:laziness) become!(result)
    result
  )
)

This code creates a lexical block and returns it. That block is a closure around the argument code. When called, it will evaluate that code, and then change itself to become that result value. Most of the magic here is really in the “become!” operation. And that is how simple it is. Since Ioke tries to make things representation independent, this implementation of lazy works in basically all cases.



IKanServe – an Ioke web framework


The last few days I’ve cobbled together IKanServe, which could be called a web framework, if you’re really generous about the meaning of the words. It doesn’t really do that much right now. But it does allow you to serve dynamic web pages using Ioke.

Much of the hard parts in the Ioke servlet was totally cribbed from Nick Sieger’s JRuby-rack, which is a very well-engineered project.

IKanServe is basically three different parts. First and most importantly, it’s an IokeServlet, that takes care of starting runtimes and pooling them. The second part is the Ioke parts of dispatching, that will turn headers and parameters into a dict, and then find matching actions and dispatch them. The third part is a very small builder library that lets you create HTML with Ioke code. In fact, the code for the html builder could be quite interesting, so let’s start with that. It’s very small, promise!

use("blank_slate")
IKanServe HtmlBuilder = BlankSlate create(fn(bs,
    bs pass = method(+args, +:attrs,
      args "<%s%:[ %s=\"%s\"%]>%[%s%]</%s>\n" format(
        currentMessage name, attrs, args, currentMessage name))))

As you can see, we use a blank_slate library, that is part of the standard library of Ioke. If you’re familiar with Ruby, you know what a blank slate is. Ioke’s blank slate is a bit more blank than the Ruby equivalent, though. To create a blank slate, we call the create method, and then send in a lexical block where we can set up anything we want to have on the blank slate. After create is finished, it will be impossible to add new stuff to the blank slate, so this is the only place we can do that. What we do here is to add a “pass” method. Pass is mostly the same as method_missing in Ruby. That method will create a tag from the method name, add all keyword arguments as attributes, then add all the content inside the tag and finally close the tag. The funky looking syntax in the Text literal is mostly the same as the % or sprintf methods in Ruby.

There is some subtle things going on in this method, but to go into them would derail this whole post. Before abandoning the HTML stuff, you might want to know how to use it. This is how:

h = IKanServe HtmlBuilder
title = "I kan serve HTML!"
h html(
  h head(h title(title)),
  h body(
    h h1(
      style: "font-size: 1.5em",
      "Isn't this cool?"
    )
  )
)

HtmlBuilder doesn’t have any state, so you just use it immediately. I alias it as “h” to make it easier on the eyes. That means that every call to the “h” object will return html. That’s how I can differentiate between creating the tag “title” and referring to the variable “title”. This is very easy stuff, but it seems to work well for smaller cases.

OK. Let’s get back to the rest of IKanServe. What do you need to use it? In your WEB-INF, you need to have three files in the “lib” directory – namely “ioke.jar”, “ioke-lib.jar” and “ikanserve.jar”. Since Ioke is inbetween releases you will have to build these yourselves, but it’s pretty simple. You can build the first two using the target “jar-lib” in the Ioke source. The third can be created by checking out ikanserve from Github: http://github.com/olabini/ikanserve, and then building it with ant.

Once you have those in your WEB-INF, you also need a web.xml file. It should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE web-app PUBLIC
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <context-param>
    <param-name>ioke.max.runtimes</param-name>
    <param-value>2</param-value>
  </context-param>

  <context-param>
    <param-name>ioke.min.runtimes</param-name>
    <param-value>1</param-value>
  </context-param>

  <servlet>
    <servlet-name>IokeServlet</servlet-name>
    <servlet-class>ioke.lang.ext.ikanserve.IokeServlet</servlet-class>
    <load-on-startup/>
  </servlet>

  <servlet-mapping>
    <servlet-name>IokeServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>ioke.lang.ext.ikanserve.IokeServletContextListener</listener-class>
  </listener>
</web-app>

Nothing spectacular, just set up the number of runtimes, the servlet and a servlet context listener.

And that’s it. Now you can build a war file and it will be ready to serve. Of course, if you deploy it and try to go to any URL, you will get a message that says: “Couldn’t find any action corresponding to your request. Sorry!”. That’s the default 404 action.

To actually create some code that does something, you need to create a file called iks_application.ik. This file should be places in WEB-INF/classes. Any other Ioke files you want to use should be on the classpath, and you can just use “use” to load those files. What can you do in IKanServe then? Well, basically you can bind actions to urls. Right now there is only one way to bind urls, and that is with regular expressions. A typical small action can be bound like this:

IKanServe actionForPath(#r[^/bar],
  method("you requested this: #{request pathInfo}"))

Here we bind any URL that starts with /bar to the method sent in. At the moment you have access to a request object, and the return value of the method will be rendered as the result. And that’s basically it. As mentioned above, it’s not so much a framework as the initial skeleton for one – but it still works quite well.

If you want to try this out in the easiest way possible, you can do “ant example-app” in the ikanserve source tree, then do “cd jetty” and finally do “java -jar start.jar”. This will build and deploy an example application and then start a Jetty instance to serve it. Go to localhost:8080 and try /foo, /bar or any other URL, and see it in action. You can see the code for this small app in web/WEB-INF/classes/iks_application.ik.

And that’s all for this time. Have fun.



QCon London and Ioke Geek night


In one and a half week, QCon London is coming up. That will be a week of great fun, and I definitely recommend it to anyone who has the possibility to be there. I have the highest respect for Trifork and InfoQ who are organizing the QCon conferences, and I’m definitely looking forward to it.

This year I am actually not speaking at the conference itself. Instead I’m hosting a track where other people speak. My track is called “Emerging Languages in the Enterprise” and I’ve managed to convince some amazing people to show up and talk there. To be specific, my speakers are: Jonas Boner, Michael Foord, Attila Szegedi, Rich Hickey and Martin Fowler. So, if you are interested in languages, be there; it will be a blast.

ThoughtWorks UK have a tradition to organize geek nights around QCon, and this time is no exception. On the evening March 10th (that is a Tuesday) I will be talking about how to create a JVM language. I will use Ioke for most examples, but will also contrast with details from JRuby. The presentation will be quite audience controlled, so exactly what will be presented is not determined. But it should give people a good grounding in Ioke, at least. More information here. Hope to see you there!