Skip to content

Instantly share code, notes, and snippets.

@marcioAlmada
Last active August 29, 2015 14:17
Show Gist options
  • Save marcioAlmada/21a28127d24a4430f8d2 to your computer and use it in GitHub Desktop.
Save marcioAlmada/21a28127d24a4430f8d2 to your computer and use it in GitHub Desktop.
A more general idea involving ast composition
<?php
// User land implementation of generics using "AST composition"
// {% <code> %} would be a "quasi code" construct used to build AST objects
// that can be conveniently post-processed and lazily executed
function new_list(Php\Ast $type) : obj {
// The anonymous class ast to be used as a template
$ast = {%
new class {
protected $itens = [];
public function push( {% type %} $element) {
$this->itens[] = $element;
}
public function pop() : {% type %} {
return array_pop($this->itens);
}
// etc...
}
%};
return $ast();
}
$taskList = new_list({% Task::class %});
$taskList->push(new Task('Feed the troll')); // ok
$taskList->push(new NotTask); // oops
// Error: Argument 1 passed to %s::push() must be an instance of Task, NotTask given...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment