Skip to content

Commit

Permalink
Add true/false, strings
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchpaulus committed Sep 19, 2024
1 parent 0d6312d commit 792f6a7
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
10 changes: 10 additions & 0 deletions mshell-go/Evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
44 changes: 44 additions & 0 deletions mshell-go/MShellObject.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"io"
"strconv"
"strings"
"fmt"
)

type MShellObject interface {
Expand Down Expand Up @@ -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
}

0 comments on commit 792f6a7

Please sign in to comment.