Angel \”Java\” Lopez on Blog

September 21, 2009

AjSharp programming language: a C#-like dynamic language

Filed under: .NET, AjSharp, Programming Languages — ajlopez @ 8:58 am

During the creation of AjGenesis, my code generation project, I defined an interpreted language, named AjBasic, used to write templates and tasks for code generation process. Last year, I began to separate AjBasic implementation of AjGenesis core, and as a proof of concept, I wrote AjSharp, another interpreted language but with more C#-like syntax, using the same core interpreter that I wrote for AjBasic. The core machine was AjInterpreter. More info at:

AjSharp- a C Sharp-like interpreter, work in progress

Now, this year, I started a clean implementation, inside my AjCodeKatas Google Code. The core interpreter is now AjLanguage, and AjSharp is the language with a parser that relies on the core “virtual machine” to build and execute an abstract tree:

Current source code (under development) can be downloaded from:

http://code.google.com/p/ajcodekatas/source/browse/#svn/trunk/AjLanguage

Variables, expressions and commands

Variables are untyped, and are automatically declared when they are used:

a = 1;
b = 2;

These variables contain integer values, but they can be assigned to values of other types:

a = “one”;
b = “two”;

The common commands are supported:


if (k>0)
 return;

for (k=1; k<=10;
k++)
 sum = k+sum;

while
(j<10)
 DoProcess(j);

foreach (element in
elements)
 AddElement(element);

Conditional expressions can be any expression, not only boolean ones. See above, False value explanation.

Functions and Subroutines

This is the sintax to write down a factorial function:

function Factorial(n)
{
 if
(n<=1)
 return
1;
 return n * Factorial(n-1);
}

The word “sub” can be used to define subroutines.

Functions and subroutines are like any other values. They can be defined without name and assigned to variables:


Add1 = function (n) { return n+1; }
two = Add1(1);
function Apply(func,values)
{
 list = new
List();
 foreach (value in
values)
list.Add(func(value));
 return list;
}
numbers = new
List();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
function Square(n) { return n*n; }
squared = Apply(Square, numbers);
squared2 = Apply(function (n) { return
n*n; }, numbers);


Native .NET objects

One of the design goals of AjLanguage core is to have access to .NET objects. They can be created using the new keyword:


ds = new System.Data.DataSet();
dinfo = new System.IO.DirectoryInfo(“.”);
foreach (fi in dinfo.GetFiles()) {
PrintLine(fi.FullName);
}

Dynamic objects

Dynamic objects can be created using the new keyword. A dynamic object accepts new members (variables and methods):


dynobj = new DynamicObject();
dynobj.FirstName = “Adam”;
dynobj.LastName = "Genesis”;
dynobj.Age =
800;
dynobj.FullName = function() { return FirstName + “ “ + LastName; }

Another notation:

dynobj = new { Name = “Adam”, Age = 800 };

Another notation:


dynobj = new { var FirstName = “Adam”; var LastName = “Genesis”; function
FullName() { return FirstName + “ “ + LastName; }

Dynamic objects are defined automatically, setting theirs properties:


Project.Database.Provider = “…”;
Project.Database.ConnectionString =
“…”;

creates Project dynamic object, with a Database property pointing to another dynamic object. It’s equivalent to:


Project = new DynamicObject();
Project.Database = new
DynamicObject();
Project.Database.Provider =
“…”;
Project.Database.ConnectionString = “…”;

An experiment: lists are defined automatically using Add method:

Project.Entities.Add(new { Name = “Customer”, Table = “dbo.Customers” });

it’s equivalent to:


Project = new DynamicObject();
Project.Entities = new
List();
Project.Entities.Add(new { Name = “Customer”, Table = “dbo.Customers”
});

Dynamic classes

A class can be defined using this sintax:


class Person {
 var FirstName;
 var
LastName;
 var Age;

 function
FullName {
 return FirstName + “ “ +
LastName;
 }
}

A new instance can be created as usual:

adam = new Person() { FirstName = “Adam”, LastName = “Genesis”, Age = 800 };

The instance is dynamic: new members can be attached to it, and methods could be redefined:

adam.FullName = function() { return “The “ + FirstName; };

You can create class as values:

Person = new DynamicClass();

but the interface to add members is still in flux.

Defined Classes

There are some predefined classes:


dynobj = new DynamicObject();
list = new List(); // implementing 
IList
dict= new Dictionary(); // implementing IDictionary

Primitive Functions

A few functions and subroutines are predefined:


Print(“Hello”);
PrintLine(“Hello World”);

There three predefined functions to execute and evaluate dinamic code:

Include("program.ajs");
Evaluate("k+1");
Execute("k=1;");
Include execute the commands in a file. Evaluate parses and evaluate an expression. And Execute compile and execute commands.

False value

Anything that is false, null, zero or empty string, is evaluated as false in conditional expression:


if (k)
 PrintLine(“true”);
else
PrintLine(“false”);

The above command prints “false” on execution, if k is zero or undefined. If a variable is undefined, any access to its member returns null, instead of a null exception:


if (Project.Database.ConnectionString)
PrintLine(“true”);
else
 PrintLine(“false”);

This command prints “false” again, if variable Project is undefined.

Arrays, List and Dictionaries

Native arrays can be defined with length:


firstprimes = new int[10];

or with values:


firstprimes = new int[] { 1, 2, 3, 5, 7, 9 };

A list is created if you need a dynamic array:


numbers[0] = “zero”;
numbers[1] = “one”;
numbers[2] =
“two”;
numbers[3] = “three”;

A dictionary is automatically created if the subindices are not numeric:


numbers[“one”] = 1;
numbers[“two”] = 2;
numbers[“three”] = 3;

If you need more feature, remember, you can use the native .NET framework.

Console interface

The project AjSharp.Console is a console application, where you can enter and execute AjSharp commands (not expressions):

No command to exit, yet. Just control+c in Windows.

Next steps

There are so many features I want to add. Partial list:

- AjBasic as another language over AjLanguage

- Generics support

- Template support (as in AjGenesis)

- Integrate to AjGenesis code generation

- Compile AST to Dynamic Language Runtime

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

2 Comments »

  1. [...] AjSharp Programming Language a C#-like Dynamic Language AjSharp: un lenguaje dinámico en C# Pueden bajarse la versión actual desde http://code.google.com/p/ajcodekatas en trunk/AjLanguage (AjLanguage define el árbol de ejecución del intérprete, AjSharp tiene un parser, un lenguaje definido para construir ese árbol; la idea es colocar otros parsers sobre AjLanguage, por ejemplo, AjBasic). [...]

    Pingback by AjSharp: objectos y clases dinámicas - Angel "Java" Lopez — December 27, 2009 @ 2:42 pm

  2. [...] AjSharp Programming Language a C#-like Dynamic Language AjSharp: un lenguaje dinámico en C# Pueden bajarse la versión actual desde http://code.google.com/p/ajcodekatas en trunk/AjLanguage (AjLanguage define el árbol de ejecución del intérprete, AjSharp tiene un parser, un lenguaje definido para construir ese árbol; la idea es colocar otros parsers sobre AjLanguage, por ejemplo, AjBasic). [...]

    Pingback by ALT.NET Hispano – Blogs » Blog Archive » AjSharp: objetos y clases dinámicas — January 3, 2010 @ 7:25 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 65 other followers

%d bloggers like this: