Making Languages

Part 6: Compilation

← Back | More coming soon…

Edit:

Anthony Ferrara points out that my wording is unclear here. Compilers convert code from one programming language to another.


It’s much easier to convert code from a high-level language to a fast, low-level language than it is to make that language. Perhaps you are tied into using a language like PHP, but you’d like to use a different syntax. You can do just that!

Compiling

Most of the work was done during parsing and interpretation. We just need to add a few render() methods to our constructs:

/**
* @param array $context
*
* @return string
*/
public function render(array $context)
{
return '$' . $this->identity .' = '.
$this->value->render($context);
}
This is from Assignment.php
/**
* @param array $context
*
* @return string
*/
public function render(array &$context)
{
return (string) $this->value;
}
This is from Number.php
/**
* @param array $context
*
* @return string
*/
public function render(array &$context)
{
return $this->left->render($context) . ' + ' .
$this->right->render($context);
}
This is from Addition.php

That’s it! We no longer have to worry about calculating values — we’ve moved on to rendering valid PHP from our Abstract Syntax Tree:

$context = [];

$nodes = [
new Assignment('foo',
new Addition(
new Addition(
new Number(1),
new Number(2)
),
new Number(3)
)
),
new Assignment('bar',
new Number(5)
)
];

foreach ($nodes as $node) {
print $node->render($context) . ";\n";
}

/*
* $foo = 1 + 2 + 3;
* $bar = 5;
*/

Context

Even though we don’t use the $context; it will be useful later on. Context can store type data, as well as value data. This means we can type-check our code, even if the target language doesn’t support static typing.

← Back | More coming soon…

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.