summaryrefslogtreecommitdiff
path: root/internal/rpn/variable.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/rpn/variable.go')
-rw-r--r--internal/rpn/variable.go72
1 files changed, 72 insertions, 0 deletions
diff --git a/internal/rpn/variable.go b/internal/rpn/variable.go
new file mode 100644
index 0000000..f3302df
--- /dev/null
+++ b/internal/rpn/variable.go
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Paul Buetow
+
+package rpn
+
+import (
+ "fmt"
+)
+
+// VariableOperations provides variable management operator implementations.
+type VariableOperations struct {
+ vars VariableStore
+}
+
+// NewVariableOperations creates a new VariableOperations instance.
+func NewVariableOperations(vars VariableStore) *VariableOperations {
+ return &VariableOperations{vars: vars}
+}
+
+// AssignVariable assigns a value from the stack to a variable.
+// Usage: `name value =`
+func (o *VariableOperations) AssignVariable(stack *Stack, name string) error {
+ val, err := stack.Pop()
+ if err != nil {
+ return err
+ }
+
+ // Convert Number to float64 for variable storage
+ return o.vars.SetVariable(name, val.Float64())
+}
+
+// UseVariable pushes a variable's value onto the stack.
+// Usage: `varname` (pushes stored value)
+func (o *VariableOperations) UseVariable(stack *Stack, name string) error {
+ if name == "" {
+ return fmt.Errorf("variable name cannot be empty")
+ }
+
+ val, exists := o.vars.GetVariable(name)
+ if !exists {
+ return fmt.Errorf("%w: %s", ErrVariableNotFound, name)
+ }
+
+ stack.Push(NewNumber(val, FloatMode))
+ return nil
+}
+
+// DeleteVariable removes a variable.
+// Usage: `name d`
+func (o *VariableOperations) DeleteVariable(name string) error {
+ if name == "" {
+ return fmt.Errorf("variable name cannot be empty")
+ }
+
+ deleted := o.vars.DeleteVariable(name)
+ if !deleted {
+ return fmt.Errorf("%w: %s", ErrVariableNotFound, name)
+ }
+ return nil
+}
+
+// ListVariables returns a string listing all variables.
+// Usage: `vars`
+func (o *VariableOperations) ListVariables() (string, error) {
+ return o.vars.FormatVariables(), nil
+}
+
+// ClearVariables removes all variables.
+// Usage: `clear`
+func (o *VariableOperations) ClearVariables() {
+ o.vars.ClearVariables()
+}