optimizations
This commit is contained in:
@@ -82,6 +82,7 @@ func New(fn string, l *lexer.Lexer) *Parser {
|
||||
p.prefixParseFns = make(map[token.TokenType]prefixParseFn)
|
||||
p.registerPrefix(token.IDENT, p.parseIdentifier)
|
||||
p.registerPrefix(token.INT, p.parseIntegerLiteral)
|
||||
p.registerPrefix(token.FLOAT, p.parseFloatLiteral)
|
||||
p.registerPrefix(token.MINUS, p.parsePrefixExpression)
|
||||
p.registerPrefix(token.TRUE, p.parseBoolean)
|
||||
p.registerPrefix(token.FALSE, p.parseBoolean)
|
||||
@@ -622,6 +623,21 @@ func (p *Parser) parseImportExpression() ast.Expression {
|
||||
return expression
|
||||
}
|
||||
|
||||
func (p *Parser) parseFloatLiteral() ast.Expression {
|
||||
lit := &ast.FloatLiteral{Token: p.curToken}
|
||||
|
||||
value, err := strconv.ParseFloat(p.curToken.Literal, 64)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("could not parse %q as float", p.curToken.Literal)
|
||||
p.errors = append(p.errors, msg)
|
||||
return nil
|
||||
}
|
||||
|
||||
lit.Value = value
|
||||
|
||||
return lit
|
||||
}
|
||||
|
||||
// Parse parses the input source into a top-level AST for either evaluation
|
||||
// or compilation to bytecode. The parameter fn denotes the filename the source
|
||||
// originated from.
|
||||
|
||||
@@ -126,6 +126,37 @@ func TestIntegerLiteralExpression(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloatLiteralExpression(t *testing.T) {
|
||||
input := "2.5;"
|
||||
|
||||
l := lexer.New(input)
|
||||
p := New("<test>", l)
|
||||
program := p.ParseProgram()
|
||||
checkParserErrors(t, p)
|
||||
|
||||
if len(program.Statements) != 1 {
|
||||
t.Fatalf("program has not enough statements. got=%d",
|
||||
len(program.Statements))
|
||||
}
|
||||
stmt, ok := program.Statements[0].(*ast.ExpressionStatement)
|
||||
if !ok {
|
||||
t.Fatalf("program.Statements[0] is not ast.ExpressionStatement. got=%T",
|
||||
program.Statements[0])
|
||||
}
|
||||
|
||||
literal, ok := stmt.Expression.(*ast.FloatLiteral)
|
||||
if !ok {
|
||||
t.Fatalf("exp not *ast.FloatLiteral. got=%T", stmt.Expression)
|
||||
}
|
||||
if literal.Value != 2.5 {
|
||||
t.Errorf("literal.Value not %f. got=%f", 2.5, literal.Value)
|
||||
}
|
||||
if literal.TokenLiteral() != "2.5" {
|
||||
t.Errorf("literal.TokenLiteral not %s. got=%s", "2.5",
|
||||
literal.TokenLiteral())
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsingPrefixExpressions(t *testing.T) {
|
||||
prefixTests := []struct {
|
||||
input string
|
||||
|
||||
Reference in New Issue
Block a user