final function compile($code, $name = NULL, $file = NULL)
{
$this->name = $name;
if (count(self::$global_context) > 0) {
/* add global variables (if any) to the current context */
foreach (self::$global_context as $var) {
$this->set_context($var, $GLOBALS[$var]);
}
}
$parsed = Haanga_Compiler_Tokenizer::init($code, $this, $file);
$code = "";
$this->subtemplate = FALSE;
$body = new Haanga_AST();
$this->prepend_op = hcode();
if (isset($parsed[0]) && $parsed[0]['operation'] == 'base') {
/* {% base ... %} found */
$base = $parsed[0][0];
$code .= $this->get_base_template($base);
unset($parsed[0]);
}
if (defined('HAANGA_VERSION')) {
$body->decl('HAANGA_VERSION', HAANGA_VERSION);
}
if ($name) {
$func_name = $this->get_function_name($name);
if ($this->check_function) {
$body->do_if(hexpr(hexec('function_exists', $func_name), '===', FALSE));
}
if (!empty($this->file)) {
$body->comment("Generated from " . $this->file);
}
$body->declare_function($func_name);
}
if (count(self::$global_context) > 0) {
$body->do_global(self::$global_context);
}
$body->do_exec('extract', $this->getScopeVariable());
$body->do_if(hexpr(hvar('return'), '==', TRUE));
$body->do_exec('ob_start');
$body->do_endif();
$this->generate_op_code($parsed, $body);
if ($this->subtemplate) {
$expr = $this->expr_call_base_template();
$this->do_print($body, $expr);
}
$body->do_if(hexpr(hvar('return'), '==', TRUE));
$body->do_return(hexec('ob_get_clean'));
$body->do_endif();
if ($name) {
$body->do_endfunction();
if ($this->check_function) {
$body->do_endif();
}
}
if ($this->prepend_op->stack_size() > 0) {
$this->prepend_op->append_ast($body);
$body = $this->prepend_op;
}
$op_code = $body->getArray(TRUE);
$code .= $this->generator->getCode($op_code, $this->getScopeVariable(NULL, TRUE));
if (!empty($this->append)) {
$code .= $this->append;
}
if (!empty($this->debug)) {
$op_code['php'] = $code;
file_put_contents($this->debug, print_r($op_code, TRUE), LOCK_EX);
}
return $code;
}