Created
August 29, 2011 14:18
-
-
Save nathggns/1178481 to your computer and use it in GitHub Desktop.
Source code for my parser
This file contains hidden or 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 | |
| require_once 'util.php'; | |
| class parser { | |
| public $instructions = array(); // Array - Instructions for the interpreter | |
| public $css; // String - The formatted css code | |
| public $tree = array(); // Array - The output tree | |
| public $lines = array(); // Array - Lines of the formatted css code | |
| public $level = array(); // Array - List of different arrays to append to | |
| public $nest = 0; // Int - How far nested are we? | |
| public function tokenize() { | |
| $in = $this->instructions; | |
| $lines = $this->lines; | |
| foreach ($lines as $line) { | |
| $parts = explode(" ", $line); | |
| $ending = $parts[count($parts) - 1]; | |
| switch ($ending) { | |
| case '{': | |
| $in[] = array('opcode' => 'OPEN_BRACE', 'args' => $parts); | |
| break; | |
| case '}': | |
| $in[] = array('opcode' => 'CLOSE_BRACE', 'args' => $parts); | |
| break; | |
| case "\n": | |
| $in[] = array('opcode' => 'END_LINE', 'args' => $parts); | |
| break; | |
| default: | |
| $in[] = array('opcode' => 'OTHER', 'args' => $parts); | |
| break; | |
| } | |
| } | |
| $this->instructions = $in; | |
| } | |
| public function interpret() { | |
| $name = ''; | |
| foreach ($this->instructions as $index => $in) { | |
| $code = $in['opcode']; | |
| $args = $in['args']; | |
| switch ($code) { | |
| case 'OPEN_BRACE': | |
| $this->level[] = array('name' => $args[0], 'contents' => array()); | |
| $this->nest++; | |
| break; | |
| case 'CLOSE_BRACE': | |
| $this->nest--; | |
| $branch = $this->level[count($this->level)-1]; | |
| array_pop($this->level); | |
| $this->tree[$branch['name']] = $branch['contents']; | |
| break; | |
| case 'OTHER': | |
| $count = count($this->level); | |
| $rule = implode(' ', $args); | |
| if ($count == 0) { | |
| $this->tree[] = $rule; | |
| } else { | |
| $this->level[$count-1]['contents'][] = $rule; | |
| } | |
| break; | |
| } | |
| } | |
| print_r($this->tree); | |
| } | |
| public function parse($css) { | |
| $this->css = Util::normalise($css, false); | |
| $this->lines = explode("\n", $this->css); | |
| $this->lines = array_map("trim", $this->lines); | |
| $this->lines = array_filter($this->lines); | |
| $this->tokenize(); | |
| $this->interpret(); | |
| //print_r($this->tree); | |
| } | |
| } | |
| $parser = new parser(); | |
| $parser->parse(file_get_contents('css.css')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment