-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
keyuchang
committed
Feb 8, 2022
1 parent
173a172
commit 79e2ea9
Showing
3 changed files
with
94 additions
and
4 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
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
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,74 @@ | ||
// language: go | ||
|
||
%{ | ||
|
||
package main | ||
|
||
import ( | ||
|
||
"fmt" | ||
|
||
) | ||
|
||
%} | ||
|
||
%union { | ||
val int | ||
} | ||
|
||
%type <val> E | ||
%token PLUS NL | ||
%token <val> NUM | ||
%token NUM 100 | ||
%start PROG | ||
%left PLUS | ||
%% | ||
PROG: | ||
/*empty*/ | ||
| PROG E NL | ||
E: | ||
E PLUS E { | ||
$$ = $1 + $3 | ||
} | ||
| NUM { | ||
$$ = $1 | ||
} | ||
|
||
%% | ||
const EOF = -1 | ||
// The parser expects the lexer to return 0 on EOF. Give it a name | ||
// for clarity. | ||
func GetToken(input string, valTy *ValType, pos *int) int { | ||
if *pos >= len(input) { | ||
return -1 | ||
} else { | ||
*valTy = ValType{0} | ||
loop: | ||
if *pos >= len(input) { | ||
return EOF | ||
} | ||
c := input[*pos] | ||
*pos++ | ||
switch c { | ||
case '+': | ||
return PLUS | ||
case '\n': | ||
return NL | ||
default: | ||
if c >= '0' && c <= '9' { // is digit | ||
valTy.val = (valTy.val)*10 + int(c) - '0' | ||
// next is digit | ||
if *pos < len(input) && input[*pos] >= '0' && input[*pos] <= '9' { | ||
goto loop | ||
} | ||
return NUM | ||
} | ||
|
||
} | ||
return 0 | ||
} | ||
} | ||
func main() { | ||
v := Parser("1+2\n").val | ||
fmt.Println(v) | ||
} |