Skip to content

Commit

Permalink
Merge pull request #79 from skx/78-hex-bin
Browse files Browse the repository at this point in the history
Allow hexadecimal/binary literals.
  • Loading branch information
skx authored Nov 6, 2022
2 parents c2aea12 + a49573d commit 86afc13
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
16 changes: 16 additions & 0 deletions eval/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,22 @@ func (ev *Eval) atom(token string) primitive.Primitive {
return primitive.Error(fmt.Sprintf("invalid character literal: %s", lit))
}

// See if this is a number with a hex/binary prefix
based := strings.ToLower(token)
if strings.HasPrefix(based, "0x") || strings.HasPrefix(based, "0b") {

// If so then parse as an integer
n, err := strconv.ParseInt(based, 0, 32)
if err == nil {

// Assuming it worked save it in our interned
// table and return it.
num := primitive.Number(n)
ev.symbols[token] = num
return num
}
}

// Is it a number?
f, err := strconv.ParseFloat(token, 64)
if err == nil {
Expand Down
14 changes: 14 additions & 0 deletions eval/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,20 @@ func TestEvaluate(t *testing.T) {
{"#!/usr/bin/yal\n", "nil"},
{"#!/usr/bin/yal\n#t", "#t"},

// integers: in hex
{"0xff", "255"},
{"0xFF", "255"},
{"0xFf", "255"},
{"0xfF", "255"},

// integers: in binary
{"0b00000000", "0"},
{"0b00000001", "1"},
{"0b00000010", "2"},
{"0b00000100", "4"},
{"0b00001000", "8"},
{"0b10000000", "128"},

// bools
{"#t", "#t"},
{"true", "#t"},
Expand Down

0 comments on commit 86afc13

Please sign in to comment.