-
-
Save marcioAlmada/21a28127d24a4430f8d2 to your computer and use it in GitHub Desktop.
A more general idea involving ast composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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