Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add yacc and cmd/yacc templates * remove set nocompatible
- Loading branch information
Showing
3 changed files
with
113 additions
and
2 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
%{ | ||
package main | ||
|
||
import "text/scanner" | ||
|
||
type Expression interface{} | ||
type Token struct { | ||
token int | ||
literal string | ||
} | ||
type NumExpr struct { | ||
literal string | ||
} | ||
type BinOpExpr struct { | ||
left, right Expression | ||
operator rune | ||
} | ||
%} | ||
|
||
%union{ | ||
token Token | ||
expr Expression | ||
} | ||
|
||
%type<expr> program | ||
%type<expr> expr | ||
%token<token> NUMBER | ||
|
||
%left '+' | ||
|
||
%% | ||
|
||
program | ||
: expr | ||
{ | ||
$$ = $1 | ||
yylex.(*Lexer).result = $$ | ||
} | ||
|
||
expr | ||
: NUMBER | ||
{ | ||
$$ = NumExpr{literal: $1.literal} | ||
} | ||
| expr '+' expr | ||
{ | ||
$$ = BinOpExpr{left: $1, operator: '+', right: $3} | ||
} | ||
|
||
%% | ||
|
||
type Lexer struct { | ||
scanner.Scanner | ||
result Expression | ||
} | ||
|
||
func (l *Lexer) Lex(lval *yySymType) int { | ||
token := int(l.Scan()) | ||
if token == scanner.Int { | ||
token = NUMBER | ||
} | ||
lval.token = Token{token: token, literal: l.TokenText()} | ||
return token | ||
} | ||
|
||
func (l *Lexer) Error(e string) { | ||
panic(e) | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
%{ | ||
// headers | ||
%} | ||
|
||
%union{ | ||
expr Expression | ||
token Token | ||
} | ||
|
||
%type<expr> program | ||
%type<expr> expr | ||
%token<token> NUMBER | ||
|
||
%left '+' | ||
|
||
%% | ||
|
||
program | ||
: expr | ||
{ | ||
$$ = $1 | ||
yylex.(*Lexer).Result = $$ | ||
} | ||
|
||
expr | ||
: NUMBER | ||
{ | ||
} | ||
| expr '+' expr | ||
{ | ||
} | ||
|
||
%% | ||
|
||
// body |
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