blynn / nex

Lexer for Go
http://cs.stanford.edu/~blynn/nex/
GNU General Public License v3.0
416 stars 47 forks source link

generating syntax errors #17

Closed geraldstanje closed 9 years ago

geraldstanje commented 9 years ago

hi,

how can i generate a syntax error using nex and add more information the the syntax error?

i tried to create a costum error function for nex: nex -e=true lexer.nex

here my nex file: /while/ { return WHILE } /print/ { return PRINT } /;/ { return END_LINE } /+|-/ { lval.s = yylex.Text(); return ADD_OP } /|\// { lval.s = yylex.Text(); return MUL_OP } /=/ { return ASSIGN } /(/ { return BEGIN_EXPRESSION } /)/ { return END_EXPRESSION } /{/ { return BEGIN_BLOCK } /}/ { return END_BLOCK } /[0-9]+/ { lval.s = yylex.Text(); return NUMBER } /[a-z][a-z0-9]/ { lval.s = yylex.Text(); return IDENTIFIER } /\n+/ { lineno += len(yylex.Text()) } // package dsl import "fmt"

var lineno int // idk if thats good to put it global?

func (yylex Lexer) Error(e string) { yylex.p.err = fmt.Sprintf("Syntax error in line %d", lineno+1) }

i can print the line number where the syntax error happend. EDIT: there are those 2 variables in the type Lexer struct: l, c int // line number and character position are they incremented automatically and can i remove my lineno variable?

how can you add more information to the error message? i want to add the token/s that was not recognized in the parsing...

e.g. how can i keep track of the last token that i sent to the parser, then on error just say Printf("error after %s on line %d" , humanReadable(lastToken,lastLine) ??

blynn commented 9 years ago

I implemented Line() and Column() methods which should help with this.