Zero

Zero
Zero

04 junio 2013

Source code published

I have released the source code of the Zero programming system today.

Yes, I'm afraid that means this project is ended. I won't develop it anymore. This does not mean that it would not be possible to develop interesting tasks of polishing, improvement and new functionality. However, you have to say enough at some time, and actually the subject that motivated this software is not even active anymore.

And it should be noted that the software is good enough, i.e. it can be used for what it was initially designed (though it is true that the Prowl and J-- compiler could use a rewriting), and its inner workings can be perfectly shown.

Actually the source code contains a folder called prowlc, which is a true multiplatform compiler. Unfortunaltely, it is not complete, as it lacks decision and looping structures.

This has been an interesting story, in which I've learned a lot. I've learned it so well that I am perfectly sure I wouldn't had started this project if I knew (like today I know) the amount of work needed. I've also realised the problems related to multiplatform software: problems will arise there where you would not expect them to happen.

In the end, the important thing is that his software has accomplished its designed task. And probably, it will be useful for a few years still to come.

Código fuente liberado

Hoy he puesto el código fuente de Zero a disposición de cualquiera que le interese.

Sí, esto significa que este proyecto está acabado. No seguiré desarrollándolo. Esto no quiere decir que no se pudieran hacer labores interesantes de pulido, de mejora, y sobre todo, añadirle más funcionalidades. Sin embargo, en algún momento hay que decir basta, y lo cierto es que ya ni siquiera la asignatura que motivó este software está en activo.

Y en cualquier caso, el software es "suficientemente bueno", esto es, se puede usar para lo que se diseñó inicialmente (si bien los compiladores Prowl y J-- necesitarían una reescritura) y se puede mostrar el funcionamiento perfectamente.

El código incluye una carpeta prowlc, que es un compilador multiplataforma real, a medio escribir, es decir, es perfectamente funcional pero no soporta estructuras de decisión y repetición.

Ha sido una anadadura interesante, en la que he aprendido muchísimo. Tanto, que estoy perfectamente seguro que de saber inicialmente el trabajo que supondría, no lo habría abordado. También me ha permitido darme cuenta de las penalidades involucradas en crear software multiplataforma: las vías de agua surgen allí donde menos te lo esperas.

En fin, lo importante es que el software ha cumplido, y seguirá cumpliendo durante al menos algunos años más, su cometido.

11 diciembre 2012

Pooi

Aunque no está directamente relacionado con Zero, sí está relacionado con la programación basada en prototipos, por lo que he pensado que merecía la pena comentarlo aquí.

Pooi es un intérprete de objetos basados en prototipos. Lleva bastante tiempo en desarrollo, aunque justo hasta ahora no soportaba métodos... ¡Ahora está completo!

Hay también disponible un tutorial sobre Pooi, que permite adentrarse en este interesante mundillo.

Pooi

Though not directly related to Zero, it is related to object-oriented, prototype-based programming, so I think it can be interesting.

Pooi is a prototype-based object-oriented interpreter. It has been in development for a while, and until now it did not support methods. Now is complete! There is also a nice tutorial to follow available.

07 diciembre 2012

Persistencia en Zero

He actualizado el tutorial (también práctica de la asignatura Tecnología de Objetos de la ESEI), sobre persistencia cuasi-ortogonal en Zero.

El tutorial ahora incluye un nuevo ejemplo, mucho más sencillo, como introducción, y explica cómo se pueden guardar objetos con un programa y recuperarlos con otro, y, aprovechando la existencia de la excepción EObjectNotFound, fusionar ambos programas en uno, como de hecho hace la agenda telefónica, presente al final del tutorial.

La implantación de persistencia, y su uso educativo como muestra de cómo debería haberse implantado persistencia mediante sistemas operativos orientados a objetos, son la verdadera razón de ser del sistema de programación Zero. La mayor influencia sobre Zero para su sistema de persistencia proviene de Barbados. El PS (almacenamiento persistente) se divide en contenedores, que guardan los objetos como si de directorios se tratase. El objetivo es no padecer el problema de que los spaghetti pointer hagan que sacar un solo objeto del PS suponga llevarse, eventualmente, todos los objetos residentes en él.

El tutorial comienza con un primer ejemplo muy sencillo, que se reproduce a continuación.

Supóngase que se desea almacenar un objeto como el punto:

object Punto
    attribute + x = 0;
    attribute + y = 0;
   
    method + set(a, b)
    {
        x = a;
        y = b;
       
        return;
    }
   
    method + toString()
    {
        reference toret = x.toString();
       
        toret = toret.concat( ", " );
        toret = toret.concat( y.toString() );
       
        return toret;
    }
endObject

Así, para guardar un objeto en el almacenamiento persistente es necesario crear un contenedor, e introducir el objeto en él.

       object GuardaPunto: ConsoleApplication
            method + doIt()
            {
                reference p = Punto.createChild( "p" );
                reference c = ContainerInstance.copy( "PruebaPunto" );
                   
                // Rellenar el punto
                p.set( 100, 150 );
                   
                // Hacerlo persistente
                c.add( p );
                psRoot.add( c );
                   
                return;
            }
        endObject

Lo lógico sería hacer ahora un programa para recuperarlo, aunque sucede que este programa es extremadamente sencillo:

            object RecuperaPunto: ConsoleApplication
                method + doIt()
                {
                    System.console.writeLn( psRoot.PruebaPunto.p );
                   
                    return;
                }
            endObject

Resulta mucho más lógico y coherente fusionar ambos programas en uno, aprovechándose del hecho de que se lanzará una excepción si no se encuentra el objeto en el PS, pasando por tanto a crearlo.

 object RecuperaPruebaPersistenciaPunto: ConsoleApplication
    method + crea()
    {
        reference p = Punto.createChild( "p" );
        reference c = ContainerInstance.copy( "PruebaPunto" );
       
        // Rellenar el punto
        p.set( 100, 150 );
       
        // Hacerlo persistente
        c.add( p );
        psRoot.add( c );
       
        return;
    }
   
    method + recupera()
    {
        return psRoot.PruebaPunto.p;
       
        onException( e ) {
            System.console.writeLn( "Creando punto..." );
            this.crea();
            return psRoot.PruebaPunto.p;
        }
    }
   
    method + doIt()
    {
        System.console.writeLn( this.recupera() );
        return;
    }
   
endObject

06 junio 2012

The history of Zero

It is curious how fast time goes by. I started Zero in 2003, with the assembler and bytecode specifications, and the next year, around this dates, Zero will turn 10.

The development of Zero is not competely stopped. I still have the PROWL compiler very present, obtaining a lot more stability and portability, specially with Windows 7 (it seems that with Win7 it does not feel comfortable, in contrast to the Linux version, maybe the first example of a non-deterministic program). It is nevertheless true that the system is quite complete since a few years ago, and it has been used for the practices part of an undergraduate subject, as a multilanguage, programmable systems offering dynamicity and persistence. Students have also volunteered with exercises written in PROWL, such as polish calculator, interactive fiction, etc.

The question I have been more frequently asked during these years is about the VM's registers... why so few? The answer is that, when I designed it, I was trying to make it as minimalist as possible, and that within the reasonable, to be as simple as possible so its characteristics and registers could easily be mapped to the x86 family, with a possible JITter in mind. So, it presents the __ip, i.e., the program counter, hidden but modified by JMP, JOT and JOF; __exc holding a reference to the object describing the exception thrown. It could be used as a generic, extra register, but this would be more hacking that anything else. The accumulator, or __acc, working as in x86, since the result of any assembler opcode goes there (I was however, more romatically inspired by the Z80; this chip derives from the 8080, and that is the father of the x86 family ).

There are four general purpuse registers, abbreviated as gp: __gp1, __gp2, __gp3 and __gp4. Finally, the __rr register holds a references to the result returned by a given method. This register is of course manipulable during the method execution, provided that the it holds the final result at the end of the method (it is directly set by RET, which must be the last instruction in the method).

The programmer can also count with __this, which references the object executing the method (not the method containing the method, that's another, rather different concept). It won't be a good idea to manipulate that, unless you exactly now what you're doing.

The meaning of general purpose for registers has something anecdotical: the now famous jeep of the USA army during WWII have their name deriving from exactly "general purpose" -> "gp" -> "jeep". Actually, the name of this cars does not mean anything specific. The name of the Zero's registers then is general purpose 1, general purpose 2... and for me, just jeep1, jeep2...

Anécdotas sobre Zero

Es curioso como pasa el tiempo. Comencé Zero en el 2003, con la especificación del ensamblador y del bytecode. El año que viene serán ya 10 años los que se cumplan desde aquel nacimiento.

El desarrollo en Zero no está parado del todo, sigo teniendo muy presente el compilador de PROWL, que proporcionará muchísima más estabilidad, y compatibilidad con Windows 7 (parece que con Win7 no acaba de funcionar bien, en contraste con Linux, es el primer ejemplo de programa no determinista). Lo que sí es cierto es que hace ya algunos años que el sistema está ya lo bastante completo como para que se utilice en las prácticas de la asignatura, como un ejemplo de sistema programable multilenguaje que presenta dinamicidad y persistencia. Los alumnos también lo han utilizado, creando prácticas como aventuras conversacionales, calculadoras polacas, etc.

Una de las preguntas que más me han realizado a lo largo de estos años es sobre los registros... ¿por qué tiene tan pocos? La respuesta es que, cuando la diseñé, pensaba en que fuera lo más minimalista posible, y que, dentro de lo razonable, pudiesen mapearse con facilidad los registros de Zero a los registros de la arquitectura x86 (pensando en un futuro JITer). Así, tiene los siguientes registros: __ip (contador de instrucciones, que es oculto pero modificado por JMP, JOT y JOF), __exc, que lleva la referencia al objeto de descripción de excepciones cuando se produce una (se podría usar de manera genérica, aunque eso ya sería más para hacking que para cosas normales). El __acc, el acumulador, que funciona efectivamente como en un 486, ya que el resultado de cualquier operación va ahí (aunque yo me inspiré más en un Z80 de Zilog cuando lo diseñé, quizás por algún sentimiento romántico [por otra parte, el z80 "viene del" 8080, y el 8080 es la base de todos los 80x86, especialmente el 8086).

Hay cuatro registros de propósito general (general purpose), ó gp: __gp1, __gp2, __gp3 y __gp4. Finalmente, el registro __rr lleva la referencia a devolver por un método. También se puede manipular durante la ejecución de un método, siempre que al final tenga lo que se quiere devolver.

También está __this, que señala al objeto que está ejecutando el método. No creo que sea muy buena idea manipularlo, a no ser que se sepa exactamente lo que se está haciendo.

Por cierto, lo de "general purpose" tiene un significado anecdótico: los famosos jeep del ejército estadounidense deben su nombre a "general purpose" -> "gp" -> "jeep". En realidad, es un coche sin un nombre realmente significativo. Así, para mi "__gp1" es "jeep1", "__gp2", es "jeep2"... etc.

08 mayo 2012

The scite-bin-* package has been updated, and the color schema improved, with a better (monospaced) font.
Actualizado el paquete scite-bin-*, de tal forma que se ha actualizado tanto el editor como el esquema de colores y la fuente utilizada, ampliamente mejorada.

07 abril 2011

Prowl 2.0

The development of the new Prowl compiler is steaming at good pace, only lacking:

- decission: if
- loops: for, foreach, do... while y while.
- Dynamic inheritance.

It is already fully implemented:

- definition of local references
. messages
. assignments

It is able to compile most programs except those with loops and decisions

Prowl 2.0

El desarrollo del compilador sigue avanzando, y en este momento sólo le faltan:

- decisión: if
- repetición: for, foreach, do... while y while.
- Herencia dinámica

Estando ya implementado:

- definición de variables locales
. mensajes
. asignaciones

Es capaz de compilar la mayoría de programas, excepto aquellos con decisiones o repeticiones

08 marzo 2011

prowlc

prowlc, the new compiler for PROWL, said: ¡Hola, mundo!

With this program as input:


/*
Hola, mundo desde PROWL

jbgarcia@uvigo.es
*/


obj HolaMundo: ConsoleApplication {
mth + doIt()
{
System.console.writeLn( "¡Hola mundo!" );
return;
}
}


There are a few minor syntax changes. Before, the end of the object was marked with the reserved word endObject, while now it is possible to use the curl braces. Before, the programmer had to write object, method and attribute, when obj, atr and mth are just as valid. As it can be inferred from this, the old syntax is still valid as well.

prowlc published:


Prowl - PROtotype-Writing Language - A Zero's programming language
v2.0 20100831


f: 'HolaMundo.pwl'
Compilando...
Generando...

Obj(s): 1
EOF('HolaMundo')


Generating...


OBJ HolaMundo ConsoleApplication

MTH + doIt
STR ¡Hola mundo!

ASG __gp1
MTH System.console writeLn __gp1
RET
ENM

ENO


Though it is not finished (not at all, only some kind of messages are allowed), it is a big first step. The objective is to have a compiler as stable as the virtual machine. Unfortunately, the current compiler was developed by a student and it has too many cumbersome cases.

About implementation, it is not lex&yacc based, nor it is based in any of its variants. PROWL has a simple syntax that allows to write a simple syntax and semantic analyzers. The different behaviours of the linux and windows versions of the current compiler decided me about this.

prowlc

prowlc, el nuevo compilador de PROWL, ha dicho: ¡Hola, mundo!

Ante este programa:


/*
Hola, mundo desde PROWL

jbgarcia@uvigo.es
*/


obj HolaMundo: ConsoleApplication {
mth + doIt()
{
System.console.writeLn( "¡Hola mundo!" );
return;
}
}


Nótese que hay algunos cambios de sintaxis. Antes, el fin de objeto se marcaba con endObject, mientras que ahora se pueden usar llaves. Antes, era necesario teclear object, method y attribute, cuando obj, atr y mth son igual de válidas. Tal y como se deduce de lo escrito, la antigua sintaxis sigue siendo perfectamente válida.

prowlc ha dicho:


Prowl - PROtotype-Writing Language - A Zero's programming language
v2.0 20100831


f: 'HolaMundo.pwl'
Compilando...
Generando...

Obj(s): 1
EOF('HolaMundo')


Y ha generado esto:


OBJ HolaMundo ConsoleApplication

MTH + doIt
STR ¡Hola mundo!

ASG __gp1
MTH System.console writeLn __gp1
RET
ENM

ENO


Aunque no está terminado, ni mucho menos (sólo soporta algunos tipos de mensajes en este momento), es un gran primer paso. El objetivo es tener un compilador de prowl tan estable como la máquina virtual. Desgraciadamente, el compilador actual fue desarrollado por una estudiante y tiene demasiados casos particulares.

Sobre la implementación, decir que no está basado en Lex & Yacc o variantes. De hecho, no está basado en nada: todo ha sido construido desde el principio. La gramática de PROWL es suficientemente sencilla como para no tener que escribir una analizador léxico y sintáctico complicadísimo, y la diferencia de comportamiento entre las versiones de Linux y Windows del actual compilador me decidieron en este sentido. No me arrepiento, desde luego.

29 diciembre 2009

Instalador para Zero

Desde hoy, está a disposición de aquellos interesados en Zero, o en probar la persistencia, y la programación orientada a objetos basada en prototipos, de un instalador que permite bajarse y probar Zero en segundos, en lugar de descargar y descomprimir cada paquete manualmente.

Necesita de Java para funcionar, aunque es un software que está instalado en casi todas las máquinas hoy en día.

Como siempre, disponible en la página de descargas del Proyecto Zero.

Zero installer

From today on, people wishing to learn about persistence, and Prototype-based object-oriented programming, or simply interested in Zero, can use the Zero installer in order to test it, instead of downloading and decompressing the packages manually.

The Zero installer is written in Java, though today that software is installed in nearly any machine.

You can find that in the download page:

Zero project

25 septiembre 2009

PROWL compiler for Linux

The PROWL compiler for Linux has shown various strange errors. They are strange because they don't show in Windows, and it has been compiled from the same sources.

The strangest of all of them is that two instructions (messages) as simple as the following ones make the compiler (oddly) complain:


System.console.writeLn( "Hola" );
System.console.lf();


They'll have to be substituted with similar instructions, in which the return value must be stored.


reference retVal;
// ...
retVal = System.console.writeLn( "Hola" );
retVal = System.console.lf();


While it is true that this compilers (prowl and J--) have been excelent for showing Zero's capabilities, they have turned out to be not very stable, thus making the need to replace them in the medium-term.

Compilador de PROWL para Linux

El compilador de PROWL para linux tiene varios errores extraños, puesto que es compilado con los mismos fuentes que el compilador para Windows.

El más raro de todos ellos es que dos instrucciones (mensajes) tan simples como estas provocan error:


System.console.writeLn( "Hola" );
System.console.lf();


Teniendo que ser sustituidas por sentencias similares, pero guardando el valor de retorno.


reference retVal;
// ...
retVal = System.console.writeLn( "Hola" );
retVal = System.console.lf();


Lo cierto es que estos compiladores (prowl y J--), pese a ser excelentes en cuanto a que han demostrado características de Zero, no han resultado ser demasiado estables, lo que supone la necesidad de relevarlos a término medio.

Small correction of the standard library

I've fixed some problems in the standard library (IntStdLib). The source and the compiled files are now corrected in the current pacckages for the 3.2 version of Zero: zero-bin-3.2-xxx.zip

Pequeña corrección de la librería estandar

He corregido algunos problemas en la librería estándar (IntStdLib). Tanto la fuente como el ensamblador modificado están en la web, en los paquetes para Windows y Linux zero-bin-3.2-xxx.zip

30 mayo 2008

Nueva versión de Prowl

El compilador Prowl ha sido mejorado, en cuanto a estabilidad.
La nueva versión es la 1.31, sólo es necesario bajarse los paquetes Prowl-bin-win32-1.3.zip, o Prowl-bin-linux-1.3.zip.