add comments support (#7)

This commit is contained in:
T.v.Dein
2023-11-07 14:18:46 +01:00
committed by GitHub
parent e963a770a7
commit 2ce8cc7a7e
5 changed files with 90 additions and 3 deletions

View File

@@ -57,8 +57,8 @@ test:
go test -v ./...
singletest:
@echo "Call like this: ''make singletest TEST=TestPrepareColumns MOD=lib"
go test -run $(TEST) github.com/tlinden/rpn/$(MOD)
@echo "Call like this: ''make singletest TEST=TestPrepareColumns"
go test -run $(TEST)
cover-report:
go test ./... -cover -coverprofile=coverage.out

View File

@@ -21,6 +21,7 @@ Features:
- provides interactive repl
- completion
- history
- comments (comment character is `#`)
## Working principle

View File

@@ -38,6 +38,7 @@ type Calc struct {
completer readline.AutoCompleter
interpreter *Interpreter
Space *regexp.Regexp
Comment *regexp.Regexp
Constants []string
LuaFunctions []string
@@ -133,6 +134,7 @@ func NewCalc() *Calc {
)
c.Space = regexp.MustCompile(`\s+`)
c.Comment = regexp.MustCompile(`#.*`) // ignore everything after #
// pre-calculate mode switching arrays
c.Constants = strings.Split(Constants, " ")
@@ -189,7 +191,8 @@ func (c *Calc) Prompt() string {
// the actual work horse, evaluate a line of calc command[s]
func (c *Calc) Eval(line string) {
line = strings.TrimSpace(line)
// remove surrounding whitespace and comments, if any
line = strings.TrimSpace(c.Comment.ReplaceAllString(line, ""))
if line == "" {
return

View File

@@ -22,6 +22,79 @@ import (
"testing"
)
func TestCommentsAndWhitespace(t *testing.T) {
calc := NewCalc()
var tests = []struct {
name string
cmd []string
exp float64 // last element of the stack
}{
{
name: "whitespace prefix",
cmd: []string{" 5"},
exp: 5.0,
},
{
name: "whitespace postfix",
cmd: []string{"5 "},
exp: 5.0,
},
{
name: "whitespace both",
cmd: []string{" 5 "},
exp: 5.0,
},
{
name: "comment line w/ spaces",
cmd: []string{"5", " # 19"},
exp: 5.0,
},
{
name: "comment line w/o spaces",
cmd: []string{"5", `#19`},
exp: 5.0,
},
{
name: "inline comment w/ spaces",
cmd: []string{"5 # 19"},
exp: 5.0,
},
{
name: "inline comment w/o spaces",
cmd: []string{"5#19"},
exp: 5.0,
},
}
for _, tt := range tests {
testname := fmt.Sprintf("%s .(expect %.2f)",
tt.name, tt.exp)
t.Run(testname, func(t *testing.T) {
for _, line := range tt.cmd {
calc.Eval(line)
}
got := calc.stack.Last()
if len(got) > 0 {
if got[0] != tt.exp {
t.Errorf("parsing failed:\n+++ got: %f\n--- want: %f",
got, tt.exp)
}
}
if calc.stack.Len() != 1 {
t.Errorf("invalid stack size:\n+++ got: %d\n--- want: 1",
calc.stack.Len())
}
})
calc.stack.Clear()
}
}
func TestCalc(t *testing.T) {
calc := NewCalc()

10
rpn.pod
View File

@@ -213,6 +213,16 @@ Search through history.
=back
=head1 COMMENTS
Lines starting with C<#> are being ignored as comments. You can also
append comments to rpn input, e.g.:
# a comment
123 # another comment
In this case only 123 will be added to the stack.
=head1 EXTENDING RPN USING LUA
You can use a lua script with lua functions to extend the