Improve error checking on number parsing

This commit is contained in:
Thomas Pelletier
2015-12-01 14:38:33 +01:00
parent fa1c2ab68c
commit 6d743bb19f
4 changed files with 56 additions and 3 deletions
+23 -2
View File
@@ -5,6 +5,7 @@ package toml
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
@@ -211,6 +212,16 @@ func (p *tomlParser) parseAssign() tomlParserStateFn {
return p.parseStart
}
var numberUnderscoreInvalidRegexp *regexp.Regexp
func cleanupNumberToken(value string) (string, error) {
if numberUnderscoreInvalidRegexp.MatchString(value) {
return "", fmt.Errorf("invalid use of _ in number")
}
cleanedVal := strings.Replace(value, "_", "", -1)
return cleanedVal, nil
}
func (p *tomlParser) parseRvalue() interface{} {
tok := p.getToken()
if tok == nil || tok.typ == tokenEOF {
@@ -225,14 +236,20 @@ func (p *tomlParser) parseRvalue() interface{} {
case tokenFalse:
return false
case tokenInteger:
cleanedVal := strings.Replace(tok.val, "_", "", -1)
cleanedVal, err := cleanupNumberToken(tok.val)
if err != nil {
p.raiseError(tok, "%s", err)
}
val, err := strconv.ParseInt(cleanedVal, 10, 64)
if err != nil {
p.raiseError(tok, "%s", err)
}
return val
case tokenFloat:
cleanedVal := strings.Replace(tok.val, "_", "", -1)
cleanedVal, err := cleanupNumberToken(tok.val)
if err != nil {
p.raiseError(tok, "%s", err)
}
val, err := strconv.ParseFloat(cleanedVal, 64)
if err != nil {
p.raiseError(tok, "%s", err)
@@ -361,3 +378,7 @@ func parseToml(flow chan token) *TomlTree {
parser.run()
return result
}
func init() {
numberUnderscoreInvalidRegexp = regexp.MustCompile(`([^\d]_|_[^\d]|_$|^_)`)
}