Friday, August 20, 2010

Method calling in ELENA: overhaul

As I already told several times ELENA is developed in "evolutional" mode (which is quite suitable for an open source project where there are no major releases and new versions are released often). It has its pros and cons but it is fun because you never know what will be next (except the pain from rewriting the whole code again and again).

When I introduced a new syntax for sending messages in 1.5.5 I had no idea that already in 1.5.6 it will be overhauled once again (though this time I will try hard to keep backward compatibility).

Before I will outline what will be new in 1.5.6 I will shortly describe the history of the problem.

I told this hundred times but it's worth repeating it again. ELENA is a highly dynamic language. This means that many approaches which are suitable and easy in the world of static languages may be problematic in the dynamic one. One of them is sending messages. You may ask what problem may be with calling a method? Yes, in a statically typed language it is not a problem (though with typecasting you may shoot your feet easily) but in a dynamic one there is a chance that message meaning was overloaded (after all human languages are very ambiguous). You send "or" message supposing the bit wise operation while a receptor treats it like Boolean one. So you either check the object type or pray that this time it will be ok. In ELENA it is even worse. A group object may consist of several objects many of them were not designed to work with each other so the chance of name conflict are quite high. After trying several other techniques I proposed the concept of a message namespace (though it was designed for other purpose).

In 1.5.5 this concept gets final implementation (I hoped so but the time proved that I was wrong). Every message consists of a subject and a verb. The number of verbs are limited (like in many human languages) and well defined (in a theory, in reality it is more or less defined :)). The subject have to be defined in the program and usually belongs to the program use case. For example "or" is a verb. "Int" and "bool" are subjects (representing integer and Boolean values). So if you need bitwise "or" - "int'or" should be used, otherwise "bool'or".

It appeared that the concept of subjects may be used not only for calling methods but for implementing multi-dispatching as well. std'basic'Integer and std'basic'LongInteger may support "int" subject, std'basic'Boolean, std'basic'True and std'basic'False support "bool" one. So if the receptor is dispatchable (it means the object support mutli-dispatching) the operation - receptor or:parameter - will produce different results depending on the parameter subject (in contrast to polymorphism where the result depends on the receptor type). If a parameter is an integer number - "int'or" will be executed. If a parameter is a boolean value - "bool'or". And so on.

Moreover I found that the subject may help me with another problem. ELENA is a language with a limited operational set. It means that the object method may have only one parameter. Actually it is not a big problem. If you need to pass several parameters you may use something like this - control location'set: gui'common'Point { location'x'get = 0. location'x'get = 0} (where x and y are second level subjects). But the resulting code is quite clumsy. So with the help of the subject I was able to simplify it (though keeping original concept) - control set &location'x:0 &y:0.
This approach made me happy until I started to migrate the code. It appeared that as a result I was forced to have two set of methods to support both of these expressions. And finally in 1.5.6 I found the way how to avoid it.

So the new version of the code will look like this - control location'set &x:0 &y:0. Not a big difference you may say. In fact it is. This could will be translated by the compiler to the following one - control location'set:#hint[subj:location]{ location'x'get = 0. location'y'get = 0. }. Which is equivalent to the original one. So no need to duplicate. And "location'set" method may look like this - #method location'set &x:anX &y:anY [ ... ]. This method will be able to support both type of passing multiple parameters and multi-dispatching one as well - control set:point .
Moreover I found that (once again :)) it may resolve another problem. Every time inline object was used the compiler create an appropriate VMT. As a result the code contains several duplicate VMTs. To resolve this some complex logic should be involved. Subject will fix this problem. Every time a subject with secondary items are declared the compiler will create a VMT. So no need to create them in place.

No one can stop me from continuing :). If a subject is declared with VMT I may customize get method. So it may help to reuse some common patterns. E.g. in location'set I have to call int'get for x and y every time I used them (don't forget a parameter may be a group or proxy object). Instead of this I will be able to write something like this - #xsubject location ( x => x int'get, y => y int'get ) (#xsubject will be used instead of #subject for backward compatibility with 1.5.5).

And finally (at least at the moment) I decided to simplify another thing. If you wish to return an object field you usually use the get method with secondary subject - point location'x'get. From 1.5.6 it will be possible to ommit get (and set) verb - point location'x (a subject cannot have a name coinciding with verb).

If you ask me what will be in 1.5.7? I will honestly answer - no idea :)

6 comments:

  1. interesting, but in version 1.5.6 will be more changes in syntax?

    Or just this change in the syntax of the parameters?

    ReplyDelete
  2. At the moment no. The proposed changes are rather syntax refining. So they should simplify code syntax.

    Still the code change will be throughout. For example I will drop "gui" prefix for gui operations - control location'set:caption instead of control gui'location'set:caption.

    Some subjects will be split and so on.

    But As I told I will try hard to keep the compatibility.

    ReplyDelete
  3. Здравствуйте Спасибо за создание языка.
    Скажите пожалуйста
    1. Чем язык Elena отличается от Gentee какие у него преимущества и недостатки.
    2. Почему антивирус Avira в примерах созданных *.exe файлов обнаруживает троян TR/Crypt.XPACK.Gen
    3. Какие планы по развитию языка вы преследуете и не будет ли он приостановлен через пол года на неопределенный срок как Gentee
    4. Планируется ли создавать GUI builder

    ReplyDelete
  4. Здравствуйте, попробую ответить на ваши вопросы.

    1) Я не очень знаком с gentee. Но на первый взгляд gentee классический процедурный язык. Автор заявляет что он пытался создать быстрый и компактный компилятор. То есть его можно отнести к языкам класса С. ELENA наоборот чисто объектно ориентированный язык класса Smalltalk. То есть сравнивать их между собой не очень коректно. К достоинствам языка можно отнести его динамическую натуру (например можно динамически переопределять методы, создавать группы объектов). ELENA динамически развивающийся язык, то есть каждая новая версия может нести иногда радикальные изменения. Это же можно отнести и к недостаткам. Порой предыдущая версия не совместима с последующей (это как раз происходит сейчас, этому и посвещена эта запись в журнале). У языка еще не очень развита библиотека классов. Код не оптимизирован (я планирую этим плотнее заняться позже). Динамическая природа языка приводит к тому что даже в самом лучшем случае мне не удастся приблизиться к c# или java в отношении производительности.

    2. Этот вопрос лучше всего задать производителям антивирусов (в том числе FSecure). По какому такому мифическому принципу они находят некоторые exe файлы зараженными у меня нет идей. Возможно сбоит эвристический алгоритм. Если вы посмотрите описания этого вируса - A generic detection routine designed to detect common family characteristics shared in several variants - то нетрудно заметить что это в самом деле проблема эвристический алгоритма а не моего компилятора. Я даже думал написать им, но очевидно что ради любительского компилятора они небудут что-либо менять.

    3. Я языком занимаюсь с 2000 года. 2006 году я разместил его на sourceforge и с тех пор выпускаю новую версию раз в один или два месяца. Сейчас плонирую перейти не еженедельные релизы (раз в 1-3 недели). Язык динамично развивается и у меня полно планов. Самое главное у меня нет илюзий что можно добиться некоторого признания языка в короткие сроки и поэтому я занимаюсь им в свое удовольствие. Так что бросать его я не собираюсь :)

    4. Да я планирую добавить инструменты для автомотического генерирования кода, в том числе и GUI.

    Надеюсь я смог ответить на все ваши вопросы. В любом случае я буду рад ответить на любые ваши вопросы здесь или на форуме sourceforge - http://sourceforge.net/projects/elenalang/forums

    ReplyDelete
  5. I like your program! thanks

    ReplyDelete
  6. You are welcome. I tried my best and will continue :)

    ReplyDelete