From 792f6a779b763f00b08da16f3afbed9a285baa72 Mon Sep 17 00:00:00 2001 From: Mitchell Paulus Date: Thu, 19 Sep 2024 10:04:47 -0500 Subject: [PATCH] Add true/false, strings --- mshell-go/Evaluator.go | 10 +++++++++ mshell-go/MShellObject.go | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/mshell-go/Evaluator.go b/mshell-go/Evaluator.go index af99445..5cfaf3b 100644 --- a/mshell-go/Evaluator.go +++ b/mshell-go/Evaluator.go @@ -148,6 +148,16 @@ func (state EvalState) Evaluate(tokens []Token, stack *MShellStack, context Exec if t.Type == QUESTION { stack.Push(&MShellInt { exitCode }) } + } else if t.Type == TRUE { + stack.Push(&MShellBool { true }) + } else if t.Type == FALSE { + stack.Push(&MShellBool { false }) + } else if t.Type == STRING { + parsedString, err := ParseRawString(t.Lexeme) + if err != nil { + return FailWithMessage(fmt.Sprintf("%d:%d: Error parsing string: %s\n", t.Line, t.Column, err.Error())) + } + stack.Push(&MShellString { parsedString }) } else { return FailWithMessage(fmt.Sprintf("%d:%d: We haven't implemented the token type '%s' yet.\n", t.Line, t.Column, t.Type)) } diff --git a/mshell-go/MShellObject.go b/mshell-go/MShellObject.go index c844080..2fc45b9 100644 --- a/mshell-go/MShellObject.go +++ b/mshell-go/MShellObject.go @@ -4,6 +4,7 @@ import ( "io" "strconv" "strings" + "fmt" ) type MShellObject interface { @@ -240,3 +241,46 @@ func (obj *MShellPipe) DebugString() string { func (obj *MShellInt) DebugString() string { return strconv.Itoa(obj.Value) } + +func ParseRawString(inputString string) (string, error) { + // Purpose of this function is to remove outer quotes, handle escape characters + if len(inputString) < 2 { + return "", fmt.Errorf("input string should have a minimum length of 2 for surrounding double quotes") + } + + var b strings.Builder + index := 1 + inEscape := false + + for index < len(inputString) - 1 { + c := inputString[index] + + if inEscape { + switch c { + case 'n': + b.WriteRune('\n') + case 't': + b.WriteRune('\t') + case 'r': + b.WriteRune('\r') + case '\\': + b.WriteRune('\\') + case '"': + b.WriteRune('"') + default: + return "", fmt.Errorf("invalid escape character '%c'", c) + } + inEscape = false + } else { + if c == '\\' { + inEscape = true + } else { + b.WriteRune(rune(c)) + } + } + + index++ + } + + return b.String(), nil +}