Created
January 5, 2012 20:54
-
-
Save itsbth/1567233 to your computer and use it in GitHub Desktop.
Uploaded by UploadToGist for Sublime Text 2
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
| {Parser} = require 'jison' | |
| # Stolen from coffee-script | |
| # Since we're going to be wrapped in a function by Jison in any case, if our | |
| # action immediately returns a value, we can optimize by removing the function | |
| # wrapper and just returning the value directly. | |
| unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/ | |
| # Our handy DSL for Jison grammar generation, thanks to | |
| # [Tim Caswell](http://github.com/creationix). For every rule in the grammar, | |
| # we pass the pattern-defining string, the action to run, and extra options, | |
| # optionally. If no action is specified, we simply pass the value of the | |
| # previous nonterminal. | |
| o = (patternString, action, options) -> | |
| patternString = patternString.replace /\s{2,}/g, ' ' | |
| return [patternString, '$$ = $1;', options] unless action | |
| action = if match = unwrap.exec action then match[1] else "(#{action}())" | |
| action = action.replace /\bnew /g, '$&yy.' | |
| action = action.replace /\b(?:Block\.wrap|extend)\b/g, 'yy.$&' | |
| [patternString, "$$ = #{action};", options] | |
| t = (regex, name) -> | |
| [regex.toString().slice(1, -1), if name then "return #{JSON.stringify(name)};" else "/* om nom nom */"] | |
| grammar = lex: {} | |
| grammar.lex.rules = [ | |
| #t /\n/, 'EOL' | |
| t /\s+/ | |
| t /[0-9]+(?:\.[0-9]+)?\b/, 'NUMBER' | |
| t /\*/, '*' | |
| t /\//, '/' | |
| t /\+/, '+' | |
| t /\-/, '-' | |
| t /\=/, '=' | |
| t /\(/, '(' | |
| t /\)/, ')' | |
| t /\?/, '?' | |
| t /:/, ':' | |
| t /\{/, '{' | |
| t /\}/, '}' | |
| t /\[/, '[' | |
| t /\]/, ']' | |
| t /;/, ';' | |
| t /if/, 'IF' | |
| t /else/, 'ELSE' | |
| t /elseif/, 'ELSEIF' | |
| t /while/, 'WHILE' | |
| t /[a-z][A-Za-z0-9_]+/, 'FUNC' | |
| t /[A-Z][A-Za-z0-9_]+/, 'VAR' | |
| t /@/, '@' | |
| t /$/, 'EOF' | |
| ] | |
| grammar.bnf = | |
| Root: [ | |
| o 'DirectiveList StatementList EOF', -> new Root $1, $2 | |
| ] | |
| DirectiveList: [ | |
| o 'Directive DirectiveList', -> $2.push $1 | |
| o '', -> [] | |
| ] | |
| Directive: [ | |
| o '@ VAR EOL' | |
| ] | |
| StatementList: [ | |
| o 'Statement ; StatementList', -> $3.push $1 | |
| o '', -> [] | |
| ] | |
| Statement: [ | |
| o 'VAR = Expression', -> new Assignment $1, $3 | |
| o 'Expression' | |
| ] | |
| Expression: [ | |
| o 'Literal', -> new Literal $1 | |
| o '( Expression )', -> $2 | |
| ] | |
| Literal: [ | |
| o 'NUMBER', -> parseFloat($1) | |
| ] | |
| exports.parser = new Parser(grammar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment