add split function

This commit is contained in:
Aidan 2020-08-14 15:59:38 -07:00
parent 546e1711e5
commit 37e6e24447
No known key found for this signature in database
GPG key ID: 327711E983899316
2 changed files with 49 additions and 0 deletions

View file

@ -143,6 +143,13 @@ func GenFuncTable() ast.FuncTable {
Args: -1, Args: -1,
}, },
"split": &ast.Function{
Function: Split,
Name: "split",
TimesCalled: 0,
Args: 2,
},
"exit": &ast.Function{ "exit": &ast.Function{
Function: ExitShell, Function: ExitShell,
Name: "exit", Name: "exit",

View file

@ -19,6 +19,7 @@ package stdlib
import ( import (
"fmt" "fmt"
"strings"
"strconv" "strconv"
"gitlab.com/whom/shs/ast" "gitlab.com/whom/shs/ast"
"gitlab.com/whom/shs/log" "gitlab.com/whom/shs/log"
@ -59,6 +60,47 @@ func StrCast(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
return res return res
} }
/* Takes 2 arguments, a string and a delimiter
* returns a list of substrings found delimited by the delimiter from the parent string
* Filters out all empty segments between delimiters
*
* Example: (split "/path/to/file" "/") -> ("path" "to" "file")
*/
func Split(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
in = in.Eval(ft, vt, false)
if in == nil || in.Tag != ast.STRING || in.Next == nil || in.Next.Tag != ast.STRING {
log.Log(log.ERR,
"Args must be two strings",
"split")
return nil
}
body := in.Value()
delim := in.Next.Value()
if len(body) < len(delim) {
log.Log(log.DEBUG,
"possibly mismatched args" +
"delimiter longer than body",
"split")
}
var res *ast.Token
builder := &res
strtoks := strings.Split(body, delim)
for _, i := range strtoks {
if i == "" {
continue
}
*builder = &ast.Token{Tag: ast.STRING}
(*builder).Set(i)
builder = &(*builder).Next
}
return res
}
/* Takes one arg, returns nil /* Takes one arg, returns nil
* Prints a string to stdout * Prints a string to stdout
* Unquotes string so user can add escaped chars like \n, \t, etc * Unquotes string so user can add escaped chars like \n, \t, etc