scpt

package module
v0.0.0-...-31c3a2f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2021 License: MIT Imports: 13 Imported by: 0

README

scpt

scpt is an applescript-inspired scripting language written for fun and to see if I could.

Go Reference


Usage

scpt is to be used as a library imported into Go. A basic interpreter with no extra functionality would look like this:

package main

import (
	"gitea.arsenm.dev/Arsen6331/scpt"
	"log"
	"os"
	"path/filepath"
)

func main() {
	filename := os.Args[1]
	file, err := os.Open(filepath.Clean(filename))
	if err != nil {
		log.Fatalln(err)
	}
	defer file.Close()
	ast, err := scpt.Parse(file)
	if err != nil {
		log.Fatalln(err)
	}
	err = ast.Execute()
	if err != nil {
		log.Fatalln(err)
	}
}

Basic Syntax

The basic syntax of scpt can be learned from the test.scpt file.


Default Functions

scpt comes with the following default functions:

  • str: Convert value to string
  • num: Parse string to number (float64)
  • bool: Parse string to boolean
  • break: Break out of loop (Errors if not in loop)
  • append: Return an array with given items appended
  • exit: Exit with given exit code
  • return: Return value in function (Errors if not within function)
  • print: Print using fmt.Println()

Adding functionality:

Adding functionality is simple and requires a call to scpt.AddFuncs() or scpt.AddVars(). Here are some examples:

scpt.AddFuncs(scpt.FuncMap{
	"my-function": myFunction
})

Where myFunction is:

func myFunction(args map[string]interface{}) (interface{}, error) {
	fmt.Println(args)
	return nil, nil
}

After the call to scpt.AddFuncs(), my-function can be used to run the function from within an scpt script. Variables work similarly.

Documentation

Overview

Package scpt provides an interpreter for my simple applescript-like scripting language

Index

Constants

This section is empty.

Variables

View Source
var Funcs = FuncMap{
	"str":    toString,
	"num":    parseNumber,
	"bool":   parseBool,
	"break":  setBreakLoop,
	"append": appendArray,
	"exit":   scptExit,
	"return": setReturn,
	"print":  scptPrint,
}

Funcs stores the functions allowed for use in a script

View Source
var Vars = map[string]interface{}{}

Vars stores any variables set during script runtime

Functions

func AddFuncs

func AddFuncs(fnMap FuncMap)

AddFuncs adds all functions from the provided FuncMap into the Funcs variable

func AddVars

func AddVars(varMap map[string]interface{})

AddVars adds all functions from the provided map into the Vars variable

func CallFunction

func CallFunction(call *FuncCall) (interface{}, error)

CallFunction executes a given function call in the form of a FuncCall struct

func IsFuncCall

func IsFuncCall(val interface{}) bool

IsFuncCall checks if val is a FuncCall struct

func ParseValue

func ParseValue(val *Value) (interface{}, error)

ParseValue parses a Value struct into a go value

func UnwrapArgs

func UnwrapArgs(args []*Arg) (map[string]interface{}, error)

UnwrapArgs takes a slice of Arg structs and returns a map storing the argument name and its value. If the argument has no name, its key will be an empty string

Types

type AST

type AST struct {
	Pos      lexer.Position
	Commands []*Command `@@*`
}

AST stores the root of the Abstract Syntax Tree for scpt

func LoadAST

func LoadAST(data []byte) (*AST, error)

func Parse

func Parse(r io.Reader) (*AST, error)

Parse uses participle to parse a script from r into a new AST

func (*AST) Dump

func (ast *AST) Dump() ([]byte, error)

func (*AST) DumpPretty

func (ast *AST) DumpPretty() ([]byte, error)

func (*AST) Execute

func (ast *AST) Execute() error

Execute traverses the AST and executes any commands, it returns an error containing the position at which the error was encountered and the error itself

type Arg

type Arg struct {
	Pos   lexer.Position
	Key   string `("with" @Ident)?`
	Value *Value `@@`
}

Arg stores arguments for function calls

type Bool

type Bool bool

Bool stores boolean values encountered while parsing a script. It is required for the Capture method

func (*Bool) Capture

func (b *Bool) Capture(values []string) error

Capture parses a boolean literal encountered in the script into a Go boolean value

type Command

type Command struct {
	Pos        lexer.Position
	Vars       []*Var       `( @@`
	Ifs        []*If        `| @@`
	RptLoops   []*RptLoop   `| @@`
	WhlLoops   []*WhlLoop   `| @@`
	Defs       []*FuncDef   `| @@`
	Goroutines []*Goroutine `| @@`
	Calls      []*FuncCall  `| @@ )`
}

Command stores any commands encountered while parsing a script

type ExprRightSeg

type ExprRightSeg struct {
	Op    string `@Operator`
	Right *Value `@@`
}

ExprRightSeg stores segments of the right side of an expression

type Expression

type Expression struct {
	Pos       lexer.Position
	Left      *Value          `@@`
	RightSegs []*ExprRightSeg `@@*`
}

Expression stores any expressions encountered while parsing a script for later evaluation

type FuncCall

type FuncCall struct {
	Pos  lexer.Position
	Name string `@Ident @("-" Ident)*`
	Args []*Arg `@@*`
}

FuncCall stores any function calls encountered while parsing a script

type FuncDef

type FuncDef struct {
	Pos       lexer.Position
	Name      *string    `"define" @Ident @("-" Ident)* "{"`
	InnerCmds []*Command `@@* "}"`
}

FuncDef stores any function definitions encountered while parsing a script

type FuncMap

type FuncMap map[string]func(map[string]interface{}) (interface{}, error)

FuncMap is a map of strings mapped to suitable script functions

type Goroutine

type Goroutine struct {
	Pos  lexer.Position
	Call *FuncCall `"go" @@`
}

type If

type If struct {
	Pos       lexer.Position
	Condition *Value     `"if" @@ "{"`
	InnerCmds []*Command `@@* "}"`
}

If stores any if statements encountered while parsing a script

type MapKVPair

type MapKVPair struct {
	Key   *Value `@@`
	Value *Value `":" @@`
}

MapKVPair stores any key/value pairs encountered while parsing map literals

type RptLoop

type RptLoop struct {
	Pos       lexer.Position
	Times     *int       `"repeat" @Number "times" "{"`
	IndexVar  *string    `(@Ident "in")?`
	InnerCmds []*Command `@@* "}"`
}

RptLoop stores any repeat loops encountered while parsing a script

type Value

type Value struct {
	Pos      lexer.Position
	String   *string      `  @String`
	Number   *float64     `| @Number`
	Bool     *Bool        `| @("true" | "false")`
	SubCmd   *FuncCall    `| "(" @@ ")"`
	VarVal   *VarVal      `| @@`
	Expr     *Expression  `| "{" @@ "}"`
	Map      []*MapKVPair `| "[" (@@ ("," @@)* )? "]"`
	Array    []*Value     `| "[" (@@ ("," @@)* )? "]"`
	Opposite *Value       `| "!" @@`
}

Value stores any literal values encountered while parsing a script

type Var

type Var struct {
	Pos   lexer.Position
	Key   string `"set" @Ident`
	Index *Value `("[" @@ "]")?`
	Value *Value `"to" @@`
}

Var stores any variables encountered while parsing a script

type VarVal

type VarVal struct {
	Name  *string `"$" @Ident`
	Index *Value  `("[" @@ "]")?`
}

VarVal stores any references to a variable encountered while parsing a script

type WhlLoop

type WhlLoop struct {
	Pos       lexer.Position
	Condition *Value     `"loop" "while" @@ "{"`
	InnerCmds []*Command `@@* "}"`
}

WhlLoop stores any while loops encountered while parsing a script

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL