internal

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2022 License: MIT Imports: 51 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RETURN_1_MODULE_HASH        = "SG2a/7YNuwBjsD2OI6bM9jZM4gPcOp9W8g51DrQeyt4="
	RETURN_GLOBAL_A_MODULE_HASH = "UYvV2gLwfuQ2D91v7PzQ8RMugUTcM0lOysCMqMqXfmg"
)
View Source
const (
	TOKEN_BUCKET_CAPACITY_SCALE = 100
	TOKEN_BUCKET_INTERVAL       = time.Second / TOKEN_BUCKET_CAPACITY_SCALE
)
View Source
const (
	EXECUTION_TOTAL_LIMIT_NAME    = "execution/total-time"
	COMPUTE_TIME_TOTAL_LIMIT_NAME = "execution/total-compute-time"
	IO_TIME_TOTAL_LIMIT_NAME      = "execution/total-io-time"
)
View Source
const (
	MAX_OBJECT_KEY_BYTE_LEN      = 64
	MAX_PATTERN_OCCURRENCE_COUNT = 1 << 24
)
View Source
const (
	REQUIRE_KEYWORD_STR = "require"
	CONST_KEYWORD_STR   = "const"
)
View Source
const (
	LOOSE_URL_EXPR_PATTERN          = "" /* 138-byte string literal not displayed */
	LOOSE_HTTP_HOST_PATTERN_PATTERN = "^https?:\\/\\/(\\*|(www\\.)?[-a-zA-Z0-9.*]{1,32}\\.[a-zA-Z0-9*]{1,6})(:[0-9]{1,5})?$"
	HTTP_URL_PATTERN                = "^https?:\\/\\/(localhost|(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,32}\\.[a-zA-Z0-9]{1,6})\\b([-a-zA-Z0-9@:%_+.~#?&//=]{0,100})$"
)
View Source
const (
	INVALID_PATH_INTERP_ERR                                                       = "invalid path interpolation"
	PATH_INTERP_EXPLANATION                                                       = "a path interpolation should contain an identifier without spaces, example: $name$ "
	UNTERMINATED_PATH_INTERP                                                      = "unterminated path interpolation"
	QUERY_PARAM_INTERP_EXPLANATION                                                = "a query parameter interpolation should contain an identifier without spaces, example: $name$ "
	UNTERMINATED_QUERY_PARAM_INTERP                                               = "unterminated query parameter interpolation"
	INVALID_PATH_PATT_NAMED_SEGMENTS                                              = "invalid path pattern literal with named segments"
	PATH_EXPR_INTERP_EXPLANATION                                                  = "a path expression cannot contain empty interpolations or interpolations next to each others"
	URL_LIKE_PATTERN_SUBSEQUENT_DOT_EXPLANATION                                   = "URL-like patterns cannot contain more than two subsequents dots except /... at the end for URL patterns"
	UNTERMINATED_COMPLEX_PATT                                                     = "unterminated pattern: '%'"
	UNTERMINATED_OBJ_PATT_MISSING_CLOSING_BRACE                                   = "unterminated object pattern literal, missing closing brace '}'"
	KEY_TOO_LONG                                                                  = "key is too long"
	ONLY_IDENTS_AND_STRINGS_VALID_OBJ_PATT_KEYS                                   = "Only identifiers and strings are valid object pattern keys"
	INVALID_PATT_UNION_ELEMENT_SEPARATOR_EXPLANATION                              = "invalid pattern union : elements should be separated by '|'"
	INVALID_PATTERN_INVALID_OCCURENCE_COUNT                                       = "invalid pattern: invalid exact ocurrence count"
	ONLY_IDENTS_AND_STRINGS_VALID_OBJ_KEYS                                        = "Only identifiers and strings are valid object literal keys"
	UNTERMINATED_OBJ_MISSING_CLOSING_BRACE                                        = "unterminated object literal, missing closing brace '}'"
	UNTERMINATED_PATT_UNTERMINATED_EXACT_OCURRENCE_COUNT                          = "unterminated pattern: unterminated exact ocurrence count: missing count after '='"
	UNTERMINATED_PAREN_PATTERN_MISSING_PAREN                                      = "unterminated parenthesized pattern, missing closing parenthesis"
	UNTERMINATED_PAREN_PATTERN                                                    = "unterminated parenthesized pattern"
	UNTERMINATED_KEY_LIST_MISSING_BRACE                                           = "unterminated key list, missing closing brace '}'"
	KEY_LIST_CAN_ONLY_CONTAIN_IDENTS                                              = "a key list can only contain identifiers"
	UNTERMINATED_MEMB_EXPR                                                        = "unterminated identifier member expression"
	HTTP_HOST_LIT_CANNOT_CONTAIN_QUERY_PART                                       = "HTTP host literals cannot contain a query part"
	URL_PATT_LITS_WITH_QUERY_PART_NOT_SUPPORTED_YET                               = "URL pattenrn literals with a query part are not supported yet"
	INVALID_URL                                                                   = "invalid URL"
	INVALID_QUERY                                                                 = "invalid query"
	URL_EXPR_CANNOT_CONTAIN_INTERP_NEXT_TO_EACH_OTHER                             = "an URL expression cannot contain interpolations next to each others"
	URL_EXPR_CANNOT_END_WITH_SLASH_3DOTS                                          = "an URL expression cannot ends with /..."
	INVALID_HTTP_HOST_PATT                                                        = "invalid HTTP host pattern"
	UNTERMINATED_BLOCK_MISSING_BRACE                                              = "unterminated block, missing closing brace '}"
	EMPTY_CSS_SELECTOR                                                            = "empty CSS selector"
	INVALID_PSEUDO_CSS_SELECTOR_INVALID_NAME                                      = "invalid CSS pseudo element selector, invalid name"
	INVALID_CSS_CLASS_SELECTOR_INVALID_NAME                                       = "invalid CSS class selector, invalid name"
	INVALID_CSS_SELECTOR                                                          = "invalid CSS selector"
	UNTERMINATED_CSS_ATTRIBUTE_SELECTOR_MISSING_BRACKET                           = "unterminated CSS attribute selector, missing closing bracket"
	UNTERMINATED_CSS_ATTR_SELECTOR_INVALID_MATCHER                                = "unterminated CSS attribute selector, invalid matcher"
	UNTERMINATED_CSS_ATTR_SELECTOR_MATCHER_EXPECTED_AFTER_NAME                    = "unterminated CSS attribute selector, a matcher is expected after the name"
	CSS_ATTRIBUTE_NAME_SHOULD_START_WITH_ALPHA_CHAR                               = "an attribute name should start with an alpha character like identifiers"
	UNTERMINATED_CSS_ATTR_SELECTOR_NAME_EXPECTED                                  = "unterminated CSS attribute selector, an attribute name was expected"
	UNTERMINATED_CSS_ID_SELECTOR_NAME_EXPECTED                                    = "unterminated CSS id selector, a name was expected after '#'"
	UNTERMINATED_CSS_CLASS_SELECTOR_NAME_EXPECTED                                 = "unterminated CSS class selector, a name was expected"
	UNTERMINATED_LIST_LIT_MISSING_BRACE                                           = "unterminated list literal, missing closing bracket ']'"
	UNTERMINATED_RUNE_LIT                                                         = "unterminated rune literal"
	INVALID_RUNE_LIT_NO_CHAR                                                      = "invalid rune literal : no character"
	INVALID_RUNE_LIT_INVALID_SINGLE_CHAR_ESCAPE                                   = "invalid rune literal: invalid single character escape"
	UNTERMINATED_RUNE_LIT_MISSING_QUOTE                                           = "unterminated rune literal, missing ' at the end"
	INVALID_RUNE_RANGE_EXPR                                                       = "invalid rune range expression"
	UNTERMINATED_STRING_LIT                                                       = "unterminated string literal"
	DOT_SHOULD_BE_FOLLOWED_BY                                                     = "'.' should be followed by (.)?(/), or a letter"
	DASH_SHOULD_BE_FOLLOWED_BY_OPTION_NAME                                        = "'-' should be followed by an option name"
	DOUBLE_DASH_SHOULD_BE_FOLLOWED_BY_OPTION_NAME                                 = "'--' should be followed by an option name"
	OPTION_NAME_CAN_ONLY_CONTAIN_ALPHANUM_CHARS                                   = "the name of an option can only contain alphanumeric characters"
	UNTERMINATED_OPION_EXPR_EQUAL_ASSIGN_SHOULD_BE_FOLLOWED_BY_EXPR               = "unterminated option expression, '=' should be followed by an expression"
	AT_SYMBOL_SHOULD_BE_FOLLOWED_BY                                               = "'@' should be followed by '(' <expr> ')' or a host alias (@api/path)"
	UNTERMINATED_ALIAS_RELATED_LITERAL                                            = "unterminated AtHostLiteral | URLExpression | HostAliasDefinition"
	INVALID_HOST_ALIAS_DEF_MISSING_VALUE_AFTER_EQL_SIGN                           = "unterminated HostAliasDefinition, missing value after '='"
	INVALID_BIN_EXPR_NON_EXISTING_OPERATOR                                        = "invalid binary expression, non existing operator"
	UNTERMINATED_BIN_EXPR_MISSING_OPERATOR                                        = "unterminated binary expression: missing operator"
	UNTERMINATED_BIN_EXPR_MISSING_OPERAND_OR_INVALID_OPERATOR                     = "unterminated binary expression: missing right operand and/or invalid operator"
	UNTERMINATED_BIN_EXPR_MISSING_OPERAND                                         = "unterminated binary expression: missing right operand"
	UNTERMINATED_BIN_EXPR_MISSING_PAREN                                           = "unterminated binary expression: missing closing parenthesis"
	UNTERMINATED_MEMB_OR_INDEX_EXPR                                               = "unterminated member/index expression"
	UNTERMINATED_INDEX_OR_SLICE_EXPR                                              = "unterminated index/slice expression"
	INVALID_SLICE_EXPR_SINGLE_COLON                                               = "invalid slice expression, a single colon should be present"
	UNTERMINATED_SLICE_EXPR_MISSING_END_INDEX                                     = "unterminated slice expression, missing end index"
	UNTERMINATED_INDEX_OR_SLICE_EXPR_MISSING_CLOSING_BRACKET                      = "unterminated index/slice expression, missing closing bracket ']'"
	UNTERMINATED_CALL_MISSING_CLOSING_PAREN                                       = "unterminated call, missing closing parenthesis ')'"
	UNTERMINATED_GLOBAL_CONS_DECLS                                                = "unterminated global  declarations"
	INVALID_GLOBAL_CONST_DECLS_OPENING_PAREN_EXPECTED                             = "invalid global  declarations, expected opening parenthesis after ''"
	INVALID_GLOBAL_CONST_DECLS_MISSING_CLOSING_PAREN                              = "invalid global  declarations, missing closing parenthesis"
	INVALID_GLOBAL_CONST_DECL_LHS_MUST_BE_AN_IDENT                                = "invalid global  declaration, left hand side must be an identifier"
	INVALID_SPAWN_EXPR                                                            = "invalid spawn expression"
	INVALID_SPAWN_EXPR_SR_SHOULD_BE_FOLLOWED_BY_TWO_EXPRS                         = "invalid spawn expression: sr should be followed by two expressions"
	SPAWN_EXPR_ARG_SHOULD_BE_FOLLOWED_BY_ALLOW_KEYWORD                            = "spawn expression: argument should be followed by a the 'allow' keyword"
	SPAWN_EXPR_ALLOW_KEYWORD_SHOULD_BE_FOLLOWED_BY_OBJ_LIT                        = "spawn expression: 'allow' keyword should be followed by an object literal (permissions)"
	FN_KEYWORD_OR_FUNC_NAME_SHOULD_BE_FOLLOWED_BY_PARAM_LIST                      = "function : fn keyword (or function name) should be followed by '(' <param list> ')' "
	PARAM_LIST_OF_FUNC_SHOULD_CONTAIN_VARS_SEP_BY_COMMAS                          = "the parameter list of a function should contain variables separated by commas"
	UNTERMINATED_PARAM_LIST_MISSING_CLOSING_PAREN                                 = "unterminated parameter list : missing closing parenthesis"
	INVALID_FUNC_SYNTAX                                                           = "invalid function syntax"
	PARAM_LIST_OF_FUNC_SHOULD_BE_FOLLOWED_BY_BLOCK                                = "function : parameter list should be followed by a block"
	UNTERMINATED_IF_STMT_MISSING_BLOCK                                            = "unterminated if statement, missing block"
	UNTERMINATED_LIST_PATT_LIT_MISSING_BRACE                                      = "unterminated list pattern literal, missing closing bracket ']'"
	UNTERMINATED_SWITCH_CASE_MISSINGè_BLOCK                                       = "invalid switch case : missing block"
	UNTERMINATED_MATCH_CASE_MISSINGè_BLOCK                                        = "invalid match case : missing block"
	UNTERMINATED_SWITCH_STMT_MISSING_CLOSING_BRACE                                = "unterminated switch statement : missing closing body brace '}'"
	UNTERMINATED_MATCH_STMT_MISSING_CLOSING_BRACE                                 = "unterminated match statement : missing closing body brace '}'"
	INVALID_SWITCH_CASE_VALUE_EXPLANATION                                         = "invalid switch case : only simple value literals are supported (1, 1.0, /home, ..)"
	INVALID_MATCH_CASE_VALUE_EXPLANATION                                          = "invalid match case : only simple value literals are supported (1, 1.0, /home, ..)"
	UNTERMINATED_MATCH_STMT                                                       = "unterminated match statement"
	UNTERMINATED_SWITCH_STMT                                                      = "unterminated switch statement"
	UNTERMINATED_SWITCH_STMT_MISSING_BODY                                         = "unterminated switch statement: missing body"
	UNTERMINATED_MATCH_STMT_MISSING_BODY                                          = "unterminated match statement: missing body"
	UNTERMINATED_SWITCH_STMT_MISSING_VALUE                                        = "unterminated switch statement: missing value"
	UNTERMINATED_MATCH_STMT_MISSING_VALUE                                         = "unterminated match statement: missing value"
	DROP_PERM_KEYWORD_SHOULD_BE_FOLLOWED_BY                                       = "permission dropping statement: 'drop-perms' keyword should be followed by an object literal (permissions)"
	IMPORT_STMT_IMPORT_KEYWORD_SHOULD_BE_FOLLOWED_BY_IDENT                        = "import statement: import should be followed by an identifier"
	IMPORT_STMT_URL_SHOULD_BE_AN_URL_LIT                                          = "import statement: URL should be a URL literal"
	IMPORT_STMT_CHECKSUM_SHOULD_BE_A_STRING_LIT                                   = "import statement: checksum should be a string literal"
	IMPORT_STMT_ARG_SHOULD_BE_AN_OBJECT_LIT                                       = "import statement: argument should be an object literal"
	IMPORT_STMT_ARG_SHOULD_BE_FOLLOWED_BY_ALLOW_KEYWORD                           = "import statement: argument should be followed by the 'allow' keyword"
	IMPORT_STMT_ALLOW_KEYWORD_SHOULD_FOLLOWED_BY_OBJ_LIT                          = "import statement: 'allow' keyword should be followed by an object literal (permissions)"
	UNTERMINATED_EMBEDDED_MODULE                                                  = "unterminated embedded module"
	INVALID_FOR_STMT                                                              = "invalid for statement"
	UNTERMINATED_FOR_STMT                                                         = "unterminated for statement"
	INVALID_FOR_STMT_MISSING_IN_KEYWORD                                           = "invalid for statement : missing 'in' keyword "
	INVALID_FOR_STMT_IN_KEYWORD_SHOULD_BE_FOLLOWED_BY_SPACE                       = "invalid for statement : 'in' keyword should be followed by a space"
	INVALID_FOR_STMT_MISSING_VALUE_AFTER_IN                                       = "unterminated for statement, missing value after 'in'"
	UNTERMINATED_FOR_STMT_MISSING_BLOCK                                           = "unterminated for statement, missing block"
	UNTERMINATED_MULTI_ASSIGN_MISSING_EQL_SIGN                                    = "unterminated multi assign statement, missing '='"
	ASSIGN_KEYWORD_SHOULD_BE_FOLLOWED_BY_IDENTS                                   = "assign keyword should be followed by identifiers (assign a b = <value>)"
	UNTERMINATED_ASSIGNMENT_MISSING_VALUE_AFTER_EQL_SIGN                          = "unterminated assignment, missing value after '='"
	INVALID_ASSIGN_A_PIPELINE_EXPR_WAS_EXPECTED_AFTER_PIPE                        = "invalid assignment, a pipeline expression was expected after '|'"
	UNTERMINATED_PIPE_STMT_LAST_STAGE_EMPTY                                       = "unterminated pipeline statement, last stage is empty"
	INVALID_PIPE_STATE_ALL_STAGES_SHOULD_BE_CALLS                                 = "invalid pipeline stage, all pipeline stages should be calls"
	UNTERMINATED_CALL                                                             = "unterminated call"
	A_NON_PAREN_CALL_EXPR_SHOULD_HAVE_ARGS_AND_CALLEE_SHOULD_BE_FOLLOWED_BY_SPACE = "a non-parenthesized call expression should have arguments and the callee (<name>$) should be followed by a space"
	INVALID_INT_LIT                                                               = "invalid integer literal"
	UNTERMINATED_INT_RANGE_LIT                                                    = "unterminated integer range literal"
	INVALID_FLOAT_LIT                                                             = "invalid floating point literal"
	INVALID_RATE_LIT                                                              = "invalid rate literal"
	INVALID_RATE_LIT_DIV_SYMBOL_SHOULD_BE_FOLLOWED_BY_IDENT                       = "invalid rate literal: '/' should be immeditately followed by an identifier ('s' for example)"
	INVALID_ELEM_IN_OBJ_LIT                                                       = "invalid element in object literal"
	UNTERMINATED_IF_STMT_MISSING_BLOCK_AFTER_ELSE                                 = "unterminated if statement, missing block after 'else'"
	SPREAD_ARGUMENT_CANNOT_BE_FOLLOWED_BY_ADDITIONAL_ARGS                         = "a spread argument cannot be followed by additionnal arguments"
	VARIADIC_PARAM_IS_UNIQUE_AND_SHOULD_BE_LAST_PARAM                             = "the variadic parameter should be unique and should be the last parameter"
)
View Source
const (
	BACKSPACE_CODE      = 8
	DEL_CODE            = 127
	CTRL_BACKSPACE_CODE = 23
	ENTER_CODE          = 13
	CTRL_C_CODE         = 3
	TAB_CODE            = 9
	ESCAPE_CODE         = 27

	ARROW_UP_FINAL_CODE    = 65
	ARROW_DOWN_FINAL_CODE  = 66
	ARROW_RIGHT_FINAL_CODE = 67
	ARROW_LEFT_FINAL_CODE  = 68
	END_FINAL_CODE         = 70
	HOME_FINAL_CODE        = 72
	DELETE_FINAL_CODE      = 126
	CTRL_LEFT_FINAL_CODE   = 68
	CTRL_RIGHT_FINAL_CODE  = 67
)
View Source
const (
	DEFAULT_FILE_FMODE          = fs.FileMode(0o400)
	DEFAULT_RW_FILE_FMODE       = fs.FileMode(0o600)
	DEFAULT_DIR_FMODE           = fs.FileMode(0o500)
	DEFAULT_HTTP_CLIENT_TIMEOUT = 10 * time.Second
)
View Source
const (
	PATH_ARG_PROVIDED_TWICE           = "path argument provided at least twice"
	CONTENT_ARG_PROVIDED_TWICE        = "content argument provided at least twice"
	MISSING_URL_ARG                   = "missing URL argument"
	HTTP_OPTION_OBJECT_PROVIDED_TWICE = "http option object provided at least twice"
)
View Source
const (
	JSON_CTYPE       = "application/json"
	HTML_CTYPE       = "text/html"
	PLAIN_TEXT_CTYPE = "text/plain"
)
View Source
const (
	FS_WRITE_LIMIT_NAME          = "fs/write"
	FS_READ_LIMIT_NAME           = "fs/read"
	FS_TOTAL_NEW_FILE_LIMIT_NAME = "fs/total-new-file"
	FS_NEW_FILE_RATE_LIMIT_NAME  = "fs/new-file"

	HTTP_REQUEST_RATE_LIMIT_NAME = "http/request"
	NO_TIMEOUT_OPTION_NAME       = "no-timeout"
)
View Source
const (
	FS_WRITE_MIN_CHUNK_SIZE     = 100_000
	FS_READ_MIN_CHUNK_SIZE      = 1_000_000
	DEFAULT_EX_TIMEOUT_DURATION = 500 * time.Millisecond
)
View Source
const (
	CONTROL_KEYWORD_COLOR = termenv.ANSIBrightMagenta
	OTHER_KEYWORD_COLOR   = termenv.ANSIBlue
	STRING_LITERAL_COLOR  = termenv.ANSI256Color(209)
	PATH_LITERAL_COLOR    = termenv.ANSI256Color(209)
	NUMBER_LITERAL_COLOR  = termenv.ANSIBrightGreen
	CONSTANT_COLOR        = termenv.ANSIBlue
)
View Source
const COOKIE_KV_KEY = "cookies"
View Source
const DEFAULT_MAX_STACK_HEIGHT = 5
View Source
const GOSH_MIMETYPE = "application/gosh"
View Source
const HTTP_PROFILE_OPTION_SHOULD_BE_AN_IDENT = "the value of the option 'profile should be an identifier"
View Source
const IMPLICIT_KEY_LEN_KEY = "__len"
View Source
const OPTION_DOES_NOT_EXIST_FMT = "option '%s' does not exist"
View Source
const TRULY_MAX_STACK_HEIGHT = 10

Variables

View Source
var (
	CTX_PTR_TYPE            = reflect.TypeOf(&Context{})
	ERROR_INTERFACE_TYPE    = reflect.TypeOf((*error)(nil)).Elem()
	ITERABLE_INTERFACE_TYPE = reflect.TypeOf((*Iterable)(nil)).Elem()
	BYTE_SLICE_TYPE         = reflect.TypeOf(([]uint8)(nil))
	RUNE_SLICE_TYPE         = reflect.TypeOf(([]rune)(nil))
)
View Source
var (
	HTTP_URL_REGEX                = regexp.MustCompile(HTTP_URL_PATTERN)
	LOOSE_HTTP_HOST_PATTERN_REGEX = regexp.MustCompile(LOOSE_HTTP_HOST_PATTERN_PATTERN)
	LOOSE_URL_EXPR_PATTERN_REGEX  = regexp.MustCompile(LOOSE_URL_EXPR_PATTERN)
)
View Source
var ALLOWED_PROMPT_FUNCTION_NAMES = []string{
	"pwd", "whoami", "hostname", "now",
}
View Source
var BINARY_OPERATOR_STRINGS = []string{
	"+", "+.", "-", "-.", "*", "*.", "/", "/.", "++", "<", "<.", "<=", "<=", ">", ">.", ">=", ">=.", "==", "!=",
	"in", "not-in", "keyof", ".", "..", "..<", "and", "or", "match", "not-match", "Substrof",
}
View Source
var COLOR_NAME_TO_COLOR = map[Identifier]termenv.Color{
	"red":        termenv.ANSIRed,
	"bright-red": termenv.ANSIBrightRed,

	"blue":        termenv.ANSIBlue,
	"bright-blue": termenv.ANSIBrightBlue,

	"cyan":        termenv.ANSICyan,
	"bright-cyan": termenv.ANSIBrightCyan,

	"yellow":        termenv.ANSIYellow,
	"bright-yellow": termenv.ANSIBrightYellow,

	"green":        termenv.ANSIGreen,
	"bright-green": termenv.ANSIBrightGreen,

	"white":        termenv.ANSIWhite,
	"bright-white": termenv.ANSIBrightWhite,

	"black":        termenv.ANSIBlack,
	"bright-black": termenv.ANSIBrightBlack,

	"magenta":        termenv.ANSIMagenta,
	"bright-magenta": termenv.ANSIBrightMagenta,
}
View Source
var DEFAULT_HTTP_REQUEST_OPTIONS = &HttpRequestOptions{
	Timeout:            DEFAULT_HTTP_CLIENT_TIMEOUT,
	InsecureSkipVerify: true,
}
View Source
var DEFAULT_LIMITATIONS = []Limitation{
	{Name: FS_READ_LIMIT_NAME, ByteRate: 1_000},
	{Name: FS_WRITE_LIMIT_NAME, ByteRate: 1_000},

	{Name: FS_NEW_FILE_RATE_LIMIT_NAME, SimpleRate: 1},
	{Name: FS_TOTAL_NEW_FILE_LIMIT_NAME, ByteRate: 1},

	{Name: HTTP_REQUEST_RATE_LIMIT_NAME, ByteRate: 1},
}
View Source
var FILE_EXTENSION_TO_MIMETYPE = map[string]mimetype{
	".json": JSON_CTYPE,
	".html": HTML_CTYPE,
	".htm":  HTML_CTYPE,
	".txt":  PLAIN_TEXT_CTYPE,
}
View Source
var KEYWORDS = []string{"if", "else", "require", "drop-perms", "for", "assign", "const", "fn", "switch", "match", "import", "sr", "return", "break", "continue", "allow"}
View Source
var KEY_PRIORITY = map[string]int{
	"id":    -1000,
	"name":  -999,
	"title": -998,
}
View Source
var PERMISSION_KIND_STRINGS = []string{"read", "update", "create", "delete", "use", "consume", "provide"}

Functions

func AtIndex

func AtIndex(value interface{}, index int) (interface{}, error)

func CallFunc

func CallFunc(calleeNode Node, state *State, arguments interface{}, must bool) (interface{}, error)

CallFunc calls calleeNode, whatever its kind (Gosh function or Go function). If must is true and the second result of a Go function is a non-nil error, CallFunc will panic.

func CanonicalHost

func CanonicalHost(host string) (string, error)

extracted from net/http/jar.go canonicalHost strips port from host if present and returns the canonicalized host name.

func Check

func Check(node Node) error

Check performs various checks on an AST, like checking that return, break and continue statements are not misplaced. Some checks are done while parsing : see the ParseModule function.

func Eval

func Eval(node Node, state *State) (result interface{}, err error)

Evaluates a node, panics are always recovered so this function should not panic.

func ExtValOf

func ExtValOf(v interface{}, state *State) interface{}

func GetSlice

func GetSlice(value interface{}, start, end int) (interface{}, error)

func HasPathLikeStart

func HasPathLikeStart(s string) bool

func Is

func Is(s string) bool

Is returns whether s is ASCII.

func IsGoshVal

func IsGoshVal(v interface{}) bool

func IsIndexKey

func IsIndexKey(key string) bool

func IsPrint

func IsPrint(s string) bool

IsPrint returns whether s is ASCII and printable according to https://tools.ietf.org/html/rfc20#section-4.2.

func IsSimpleGoshVal

func IsSimpleGoshVal(v interface{}) bool

func IsSimpleValueLiteral

func IsSimpleValueLiteral(node Node) bool

func Memb

func Memb(value interface{}, name string) (interface{}, *reflect.Type, error)

func MustEval

func MustEval(node Node, state *State) interface{}

MustEval calls Eval and panics if there is an error.

func NodeIs

func NodeIs(node Node, typ interface{}) bool

func ReadParseScript

func ReadParseScript(fpath string, defaultLimitations []Limitation, handleCustomType CustomPermissionTypeHandler) (string, *Module, []Permission, []Limitation)

func RunScript

func RunScript(fpath string, passedArgs []string, perms string) (interface{}, error)

func SetAtIndex

func SetAtIndex(value interface{}, index int, e interface{}) error

func SetSlice

func SetSlice(value interface{}, start, end int, slice interface{}) error

func StartShell

func StartShell(state *State, ctx *Context, config REPLConfiguration)

starts the shell, the execution of this function ends when the shell is exited

func ToLower

func ToLower(s string) (lower string, ok bool)

ToLower returns the lowercase version of s if s is ASCII and printable.

func ToReflectVal

func ToReflectVal(v interface{}) reflect.Value

Wraps its argument in a reflect.Value if it is not already wrapped.

func Traverse

func Traverse(v interface{}, fn func(interface{}) (TraversalAction, error), config TraversalConfiguration) (terror error)

Traverse a graph of values starting from v. Only objects & lists are considered source nodes, the other ones are sinks (leafs). A list of encountered source nodes is used to prevent cycling

func UnwrapReflectVal

func UnwrapReflectVal(v interface{}) interface{}

Unwraps the content of a reflect.Value.

func ValOf

func ValOf(v interface{}) interface{}

Unwraps any reflect.Value that wraps a Gosh value. Wraps its argument in a reflect.Value if it is not a Gosh value.

func Walk

func Walk(node Node, fn func(node Node, parent Node, scopeNode Node, ancestorChain []Node) (TraversalAction, error)) (err error)

This functions performs a pre-order traversal on an AST (depth first).

Types

type AbsolutePathExpression

type AbsolutePathExpression struct {
	NodeBase
	Slices []Node
}

type AbsolutePathLiteral

type AbsolutePathLiteral struct {
	NodeBase
	Value string
}

type AbsolutePathPatternLiteral

type AbsolutePathPatternLiteral struct {
	NodeBase
	Value string
}

type Assignment

type Assignment struct {
	NodeBase
	Left  Node
	Right Node
}

type AtHostLiteral

type AtHostLiteral struct {
	NodeBase
	Value string
}

type BinaryExpression

type BinaryExpression struct {
	NodeBase
	Operator BinaryOperator
	Left     Node
	Right    Node
}

type BinaryOperator

type BinaryOperator int
const (
	Add BinaryOperator = iota
	AddF
	Sub
	SubF
	Mul
	MulF
	Div
	DivF
	Concat
	LessThan
	LessThanF
	LessOrEqual
	LessOrEqualF
	GreaterThan
	GreaterThanF
	GreaterOrEqual
	GreaterOrEqualF
	Equal
	NotEqual
	In
	NotIn
	Keyof
	Dot //unused, present for symmetry
	Range
	ExclEndRange
	And
	Or
	Match
	NotMatch
	Substrof
)

func (BinaryOperator) String

func (operator BinaryOperator) String() string

type Block

type Block struct {
	NodeBase
	Statements []Node
}

type BooleanConversionExpression

type BooleanConversionExpression struct {
	NodeBase
	Expr Node
}

type BooleanLiteral

type BooleanLiteral struct {
	NodeBase
	Value bool
}

type BreakStatement

type BreakStatement struct {
	NodeBase
	Label *IdentifierLiteral //can be nil
}

type ByteCount

type ByteCount int

type ByteRate

type ByteRate int

type Call

type Call struct {
	NodeBase
	Callee    Node
	Arguments []Node //can include a SpreadArgument
	Must      bool
}

type Case

type Case struct {
	NodeBase
	Value Node
	Block *Block
}

type ColorizationInfo

type ColorizationInfo struct {
	// contains filtered or unexported fields
}

type CommandPermission

type CommandPermission struct {
	CommandName         string
	SubcommandNameChain []string //can be empty
}

func (CommandPermission) Includes

func (perm CommandPermission) Includes(otherPerm Permission) bool

func (CommandPermission) Kind

func (perm CommandPermission) Kind() PermissionKind

func (CommandPermission) String

func (perm CommandPermission) String() string

type CommandResult

type CommandResult struct {
}

type Context

type Context struct {
	// contains filtered or unexported fields
}

func NewContext

func NewContext(permissions []Permission, forbiddenPermissions []Permission, limitations []Limitation) *Context

func (*Context) CheckHasPermission

func (ctx *Context) CheckHasPermission(perm Permission) error

func (*Context) DropPermissions

func (ctx *Context) DropPermissions(droppedPermissions []Permission)

func (*Context) GetDefaultHttpProfile

func (ctx *Context) GetDefaultHttpProfile() *HttpProfile

func (*Context) GetHttpProfile

func (ctx *Context) GetHttpProfile(name interface{}) (*HttpProfile, error)

func (*Context) GetRate

func (ctx *Context) GetRate(name string) (ByteRate, error)

func (*Context) HasPermission

func (ctx *Context) HasPermission(perm Permission) bool

func (*Context) NewWith

func (ctx *Context) NewWith(additionalPerms []Permission) (*Context, error)

Creates a new Context with additional permissions

func (*Context) NewWithout

func (ctx *Context) NewWithout(removedPerms []Permission) (*Context, error)

Creates a new Context with the permissions passed as argument removed. The limiters are shared between the two contexts.

func (*Context) SetHttpProfile

func (ctx *Context) SetHttpProfile(name Identifier, configObject Object) error

func (*Context) Take

func (ctx *Context) Take(name string, count int64)

type ContextlessCallPermission

type ContextlessCallPermission struct {
	FuncMethodName   string
	ReceiverTypeName string
}

func (ContextlessCallPermission) Includes

func (perm ContextlessCallPermission) Includes(otherPerm Permission) bool

func (ContextlessCallPermission) Kind

func (ContextlessCallPermission) String

func (perm ContextlessCallPermission) String() string

type ContinueStatement

type ContinueStatement struct {
	NodeBase
	Label *IdentifierLiteral //can be nil
}

type CssAttributeSelector

type CssAttributeSelector struct {
	NodeBase
	AttributeName *IdentifierLiteral
	Matcher       string
	Value         Node
}

type CssClassSelector

type CssClassSelector struct {
	NodeBase
	Name string
}

type CssCombinator

type CssCombinator struct {
	NodeBase
	Name string
}

type CssIdSelector

type CssIdSelector struct {
	NodeBase
	Name string
}

type CssPseudoClassSelector

type CssPseudoClassSelector struct {
	NodeBase
	Name      string
	Arguments []Node
}

type CssPseudoElementSelector

type CssPseudoElementSelector struct {
	NodeBase
	Name string
}

type CssSelectorExpression

type CssSelectorExpression struct {
	NodeBase
	Elements []Node
}

type CssTypeSelector

type CssTypeSelector struct {
	NodeBase
	Name string
}

type CustomPermissionTypeHandler

type CustomPermissionTypeHandler func(kind PermissionKind, name string, value Node) (perms []Permission, handled bool, err error)

type EmbeddedModule

type EmbeddedModule struct {
	NodeBase
	Requirements *Requirements //can be nil
	Statements   []Node
}

type EntryMatcher

type EntryMatcher struct {
	Key   Matcher
	Value Matcher
}

type ExactSimpleValueMatcher

type ExactSimpleValueMatcher struct {
	// contains filtered or unexported fields
}

func (ExactSimpleValueMatcher) Random

func (matcher ExactSimpleValueMatcher) Random() interface{}

func (ExactSimpleValueMatcher) Regex

func (matcher ExactSimpleValueMatcher) Regex() string

func (ExactSimpleValueMatcher) Test

func (matcher ExactSimpleValueMatcher) Test(v interface{}) bool

type ExternalValue

type ExternalValue struct {
	// contains filtered or unexported fields
}

type ExtractionExpression

type ExtractionExpression struct {
	NodeBase
	Object Node
	Keys   *KeyListExpression
}

type FilesystemPermission

type FilesystemPermission struct {
	Kind_  PermissionKind
	Entity interface{} //Path, PathPattern ...
}

func (FilesystemPermission) Includes

func (perm FilesystemPermission) Includes(otherPerm Permission) bool

func (FilesystemPermission) Kind

func (FilesystemPermission) String

func (perm FilesystemPermission) String() string

type FlagLiteral

type FlagLiteral struct {
	NodeBase
	SingleDash bool
	Name       string
}

type FloatLiteral

type FloatLiteral struct {
	NodeBase
	Raw   string
	Value float64
}

type ForStatement

type ForStatement struct {
	NodeBase
	KeyIndexIdent  *IdentifierLiteral //can be nil
	ValueElemIdent *IdentifierLiteral //can be nil
	Body           *Block
	IteratedValue  Node
}

type Func

type Func Node

type FunctionDeclaration

type FunctionDeclaration struct {
	NodeBase
	Function *FunctionExpression
	Name     *IdentifierLiteral
}

type FunctionExpression

type FunctionExpression struct {
	NodeBase
	Parameters   []*FunctionParameter
	IsVariadic   bool
	Body         *Block
	Requirements *Requirements
}

func (FunctionExpression) NonVariadicParamCount

func (expr FunctionExpression) NonVariadicParamCount() int

type FunctionParameter

type FunctionParameter struct {
	NodeBase
	Var        *IdentifierLiteral
	IsVariadic bool
}

type GenerativePattern

type GenerativePattern interface {
	Random() interface{}
}

todo: improve name

type GlobalConstantDeclaration

type GlobalConstantDeclaration struct {
	NodeBase
	Left  *IdentifierLiteral
	Right Node
}

type GlobalConstantDeclarations

type GlobalConstantDeclarations struct {
	NodeBase
	Declarations []*GlobalConstantDeclaration
}

type GlobalVarPermission

type GlobalVarPermission struct {
	Kind_ PermissionKind
	Name  string //"*" means any
}

func (GlobalVarPermission) Includes

func (perm GlobalVarPermission) Includes(otherPerm Permission) bool

func (GlobalVarPermission) Kind

func (perm GlobalVarPermission) Kind() PermissionKind

func (GlobalVarPermission) String

func (perm GlobalVarPermission) String() string

type GlobalVariable

type GlobalVariable struct {
	NodeBase
	Name string
}

type GroupMatcher

type GroupMatcher interface {
	Matcher
	MatchGroups(interface{}) (ok bool, groups map[string]interface{})
}

type HTTPHost

type HTTPHost string

func (HTTPHost) WithoutScheme

func (host HTTPHost) WithoutScheme() string

type HTTPHostLiteral

type HTTPHostLiteral struct {
	NodeBase
	Value string
}

type HTTPHostPattern

type HTTPHostPattern string

func (HTTPHostPattern) Test

func (patt HTTPHostPattern) Test(v interface{}) bool

type HTTPHostPatternLiteral

type HTTPHostPatternLiteral struct {
	NodeBase
	Value string
}

type HostAliasDefinition

type HostAliasDefinition struct {
	NodeBase
	Left  *AtHostLiteral
	Right Node
}

type HttpPermission

type HttpPermission struct {
	Kind_  PermissionKind
	Entity interface{} //URL, URLPattern, HTTPHost, HTTPHostPattern ....
}

func (HttpPermission) Includes

func (perm HttpPermission) Includes(otherPerm Permission) bool

func (HttpPermission) Kind

func (perm HttpPermission) Kind() PermissionKind

func (HttpPermission) String

func (perm HttpPermission) String() string

type HttpProfile

type HttpProfile struct {
	Config  HttpProfileConfig
	Options HttpRequestOptions
}

type HttpProfileConfig

type HttpProfileConfig struct {
	SaveCookies bool
	Headers     http.Header
	Store       KVStore
}

type HttpRequestOptions

type HttpRequestOptions struct {
	Timeout            time.Duration
	InsecureSkipVerify bool
	Jar                http.CookieJar
}

type Identifier

type Identifier string

type IdentifierLiteral

type IdentifierLiteral struct {
	NodeBase
	Name string
}

type IdentifierMemberExpression

type IdentifierMemberExpression struct {
	NodeBase
	Left          *IdentifierLiteral
	PropertyNames []*IdentifierLiteral
}

type IfStatement

type IfStatement struct {
	NodeBase
	Test       Node
	Consequent *Block
	Alternate  *Block //can be nil
}

type ImportStatement

type ImportStatement struct {
	NodeBase
	Identifier         *IdentifierLiteral
	URL                *URLLiteral
	ValidationString   *StringLiteral
	ArgumentObject     *ObjectLiteral
	GrantedPermissions *ObjectLiteral
}

type IndexExpression

type IndexExpression struct {
	NodeBase
	Indexed Node
	Index   Node
}

type IntLiteral

type IntLiteral struct {
	NodeBase
	Raw   string
	Value int
}

type IntRange

type IntRange struct {
	Start int
	End   int
	Step  int
	// contains filtered or unexported fields
}

func (IntRange) Iterator

func (r IntRange) Iterator() Iterator

func (IntRange) Random

func (r IntRange) Random() interface{}

type IntRangeIterator

type IntRangeIterator struct {
	// contains filtered or unexported fields
}

func (*IntRangeIterator) GetNext

func (it *IntRangeIterator) GetNext(ctx *Context) interface{}

func (IntRangeIterator) HasNext

func (it IntRangeIterator) HasNext(*Context) bool

type IntegerRangeLiteral

type IntegerRangeLiteral struct {
	NodeBase
	LowerBound *IntLiteral
	UpperBound *IntLiteral
}

type InvalidAliasRelatedNode

type InvalidAliasRelatedNode struct {
	NodeBase
	Value string
}

type InvalidCSSselectorNode

type InvalidCSSselectorNode struct {
	NodeBase
}

type InvalidComplexPatternElement

type InvalidComplexPatternElement struct {
	NodeBase
}

type InvalidMemberLike

type InvalidMemberLike struct {
	NodeBase
	Left  Node
	Right Node //can be nil
}

type InvalidObjectElement

type InvalidObjectElement struct {
	NodeBase
}

type InvalidPathPattern

type InvalidPathPattern struct {
	NodeBase
	Value string
}

type InvalidPathSlice

type InvalidPathSlice struct {
	NodeBase
}

type InvalidURL

type InvalidURL struct {
	NodeBase
	Value string
}

type InvalidURLPattern

type InvalidURLPattern struct {
	NodeBase
	Value string
}

type Iterable

type Iterable interface {
	Iterator() Iterator
}

type IterationChange

type IterationChange int
const (
	NoIterationChange IterationChange = iota
	BreakIteration
	ContinueIteration
)

type Iterator

type Iterator interface {
	HasNext(*Context) bool
	GetNext(*Context) interface{}
}

type JSONstring

type JSONstring string

special string types

type KVStore

type KVStore interface {
	Set(*Context, string, interface{})
	Get(*Context, string) (interface{}, bool)
	Has(*Context, string) bool
	Lock()
	Unlock()
}

type KeyList

type KeyList []string

type KeyListExpression

type KeyListExpression struct {
	NodeBase
	Keys []*IdentifierLiteral
}

type LazyExpression

type LazyExpression struct {
	NodeBase
	Expression Node
}

type Limitation

type Limitation struct {
	Name        string
	SimpleRate  SimpleRate
	ByteRate    ByteRate
	Total       int64
	DecrementFn func(time.Time) int64
}

type Limiter

type Limiter struct {
	// contains filtered or unexported fields
}

type LineCount

type LineCount int

type List

type List []interface{}

func (List) ContainsSimple

func (list List) ContainsSimple(v interface{}) bool

type ListLiteral

type ListLiteral struct {
	NodeBase
	Elements []Node
}

type ListPattern

type ListPattern struct {
	ElementMatchers []Matcher
}

func (ListPattern) Test

func (patt ListPattern) Test(v interface{}) bool

type ListPatternLiteral

type ListPatternLiteral struct {
	NodeBase
	Elements []Node
}

type LoadType

type LoadType int
const (
	ComputeLoad LoadType = iota
	IOLoad
)

type MatchStatement

type MatchStatement struct {
	NodeBase
	Discriminant Node
	Cases        []*Case
}

type Matcher

type Matcher interface {
	Test(interface{}) bool
}

func CompilePatternNode

func CompilePatternNode(node Node, state *State) (Matcher, error)

type MemberExpression

type MemberExpression struct {
	NodeBase
	Left         Node
	PropertyName *IdentifierLiteral
}

type MissingExpression

type MissingExpression struct {
	NodeBase
}

type Module

type Module struct {
	NodeBase
	GlobalConstantDeclarations *GlobalConstantDeclarations //nil if no const declarations at the top of the module
	Requirements               *Requirements               //nil if no require at the top of the module
	Statements                 []Node
	IsShellChunk               bool
}

func MustParseModule

func MustParseModule(str string) (result *Module)

func ParseAndCheckModule

func ParseAndCheckModule(s string, fpath string) (*Module, error)

func ParseModule

func ParseModule(str string, fpath string) (result *Module, resultErr error)

parses a file module, resultErr is either a non-syntax error or an aggregation of syntax errors. result and resultErr can be both non-nil at the same time because syntax errors are also stored in nodes.

type MultiAssignment

type MultiAssignment struct {
	NodeBase
	Variables []Node
	Right     Node
}

type NamedSegmentPathPattern

type NamedSegmentPathPattern struct {
	// contains filtered or unexported fields
}

func (NamedSegmentPathPattern) MatchGroups

func (patt NamedSegmentPathPattern) MatchGroups(v interface{}) (bool, map[string]interface{})

func (NamedSegmentPathPattern) Test

func (patt NamedSegmentPathPattern) Test(v interface{}) bool

type NamedSegmentPathPatternLiteral

type NamedSegmentPathPatternLiteral struct {
	NodeBase
	Slices []Node //PathSlice | Variable
}

TODO: rename

type NilLiteral

type NilLiteral struct {
	NodeBase
}

type Node

type Node interface {
	Base() NodeBase
	BasePtr() *NodeBase
}

all node types embed NodeBase, implements the Node interface

type NodeBase

type NodeBase struct {
	Span            NodeSpan
	Err             *ParsingError
	ValuelessTokens []Token
}

func (NodeBase) Base

func (base NodeBase) Base() NodeBase

func (*NodeBase) BasePtr

func (base *NodeBase) BasePtr() *NodeBase

func (NodeBase) IncludedIn

func (base NodeBase) IncludedIn(node Node) bool

type NodeSpan

type NodeSpan struct {
	Start int
	End   int
}

type NotAllowedError

type NotAllowedError struct {
	Permission Permission
	Message    string
}

func (NotAllowedError) Error

func (err NotAllowedError) Error() string

type Object

type Object map[string]interface{}

int, float64, string, bool, reflect.Value

func NewTuiNamespace

func NewTuiNamespace(state *State) Object

func (Object) GetOrDefault

func (obj Object) GetOrDefault(key string, defaultVal interface{}) interface{}

func (Object) Indexed

func (obj Object) Indexed() Iterator

func (Object) IndexedItemCount

func (obj Object) IndexedItemCount() int

type ObjectLiteral

type ObjectLiteral struct {
	NodeBase
	Properties     []ObjectProperty
	SpreadElements []*PropertySpreadElement
}

func (ObjectLiteral) PermissionsLimitations

func (objLit ObjectLiteral) PermissionsLimitations(
	globalConsts *GlobalConstantDeclarations,
	runningState *State,
	defaultLimitations []Limitation,
	handleCustomType CustomPermissionTypeHandler,
) ([]Permission, []Limitation)

this function gets permissions limitations & by evaluating a "requirement" object literal custom permissions & most limitations are handled by the handleCustomType argument (optional)

type ObjectPattern

type ObjectPattern struct {
	EntryMatchers map[string]Matcher
}

func (ObjectPattern) Test

func (patt ObjectPattern) Test(v interface{}) bool

type ObjectPatternLiteral

type ObjectPatternLiteral struct {
	NodeBase
	Properties []ObjectProperty
}

type ObjectProperty

type ObjectProperty struct {
	NodeBase
	Key           Node //can be nil (implicit key)
	Value         Node
	IsValueShared bool
}

func (ObjectProperty) HasImplicitKey

func (prop ObjectProperty) HasImplicitKey() bool

func (ObjectProperty) Name

func (prop ObjectProperty) Name() string

type OcurrenceCountModifier

type OcurrenceCountModifier int
const (
	ExactlyOneOcurrence OcurrenceCountModifier = iota
	AtLeastOneOcurrence
	ZeroOrMoreOcurrence
	OptionalOcurrence
	ExactOcurrence
)

type Option

type Option struct {
	Name  string
	Value interface{}
}

type OptionExpression

type OptionExpression struct {
	NodeBase
	SingleDash bool
	Name       string
	Value      Node
}

type ParsingError

type ParsingError struct {
	Message string
}

func (ParsingError) Error

func (err ParsingError) Error() string

type Path

type Path string

func (Path) IsDirPath

func (pth Path) IsDirPath() bool

func (Path) ToAbs

func (pth Path) ToAbs() Path

type PathPattern

type PathPattern string

func (PathPattern) IsPrefixPattern

func (patt PathPattern) IsPrefixPattern() bool

func (PathPattern) Prefix

func (patt PathPattern) Prefix() string

func (PathPattern) Test

func (patt PathPattern) Test(v interface{}) bool

func (PathPattern) ToAbs

func (patt PathPattern) ToAbs() PathPattern

type PathSlice

type PathSlice struct {
	NodeBase
	Value string
}

type PatternDefinition

type PatternDefinition struct {
	NodeBase
	Left  *PatternIdentifierLiteral
	Right Node
}

type PatternIdentifierLiteral

type PatternIdentifierLiteral struct {
	NodeBase
	Name string
}

type PatternKind

type PatternKind int
const (
	UnspecifiedPatternKind PatternKind = iota
	StringPattern
	IntegerPattern
	FloatPattern
)

type PatternPiece

type PatternPiece struct {
	NodeBase
	Kind     PatternKind
	Elements []*PatternPieceElement
}

type PatternPieceElement

type PatternPieceElement struct {
	NodeBase
	Ocurrence           OcurrenceCountModifier
	ExactOcurrenceCount int
	Expr                Node
}

type PatternUnion

type PatternUnion struct {
	NodeBase
	Cases []Node
}

type Permission

type Permission interface {
	Kind() PermissionKind
	Includes(Permission) bool
	String() string
}

type PermissionDroppingStatement

type PermissionDroppingStatement struct {
	NodeBase
	Object *ObjectLiteral
}

type PermissionKind

type PermissionKind int
const (
	ReadPerm PermissionKind = iota
	UpdatePerm
	CreatePerm
	DeletePerm
	UsePerm
	ConsumePerm
	ProvidePerm
)

func PermissionKindFromString

func PermissionKindFromString(s string) (PermissionKind, bool)

func (PermissionKind) String

func (kind PermissionKind) String() string

type PipelineExpression

type PipelineExpression struct {
	NodeBase
	Stages []*PipelineStage
}

type PipelineStage

type PipelineStage struct {
	Kind PipelineStageKind
	Expr Node
}

type PipelineStageKind

type PipelineStageKind int
const (
	NormalStage PipelineStageKind = iota
	ParallelStage
)

type PipelineStatement

type PipelineStatement struct {
	NodeBase
	Stages []*PipelineStage
}

type PropertySpreadElement

type PropertySpreadElement struct {
	NodeBase
	Expr Node //should be an *ExtractionExpression if parsing is ok
}

type QuantityLiteral

type QuantityLiteral struct {
	NodeBase
	Raw   string
	Value float64
	Unit  string
}

type QuantityRange

type QuantityRange struct {
	Start interface{}
	End   interface{}
	// contains filtered or unexported fields
}

type REPLConfiguration

type REPLConfiguration struct {
	// contains filtered or unexported fields
}

func MakeConfig

func MakeConfig(startupResult interface{}, state *State) (config REPLConfiguration)

type RateLiteral

type RateLiteral struct {
	NodeBase
	Quantity *QuantityLiteral
	Unit     *IdentifierLiteral
}

type RegexMatcher

type RegexMatcher struct {
	// contains filtered or unexported fields
}

func (RegexMatcher) Regex

func (matcher RegexMatcher) Regex() string

func (RegexMatcher) Test

func (matcher RegexMatcher) Test(v interface{}) bool

type RegularExpressionLiteral

type RegularExpressionLiteral struct {
	NodeBase
	Raw   string
	Value string
}

type RelativePathExpression

type RelativePathExpression struct {
	NodeBase
	Slices []Node
}

type RelativePathLiteral

type RelativePathLiteral struct {
	NodeBase
	Value string
}

type RelativePathPatternLiteral

type RelativePathPatternLiteral struct {
	NodeBase
	Value string
}

type RepeatedPatternElement

type RepeatedPatternElement struct {
	// contains filtered or unexported fields
}

func (RepeatedPatternElement) Random

func (patt RepeatedPatternElement) Random() interface{}

func (RepeatedPatternElement) Regex

func (patt RepeatedPatternElement) Regex() string

func (RepeatedPatternElement) Test

func (patt RepeatedPatternElement) Test(v interface{}) bool

type Requirements

type Requirements struct {
	ValuelessTokens []Token
	Object          *ObjectLiteral
}

type ReturnStatement

type ReturnStatement struct {
	NodeBase
	Expr Node //can be nil
}

type Routine

type Routine struct {
	// contains filtered or unexported fields
}

func (*Routine) WaitResult

func (routine *Routine) WaitResult(ctx *Context) (interface{}, error)

type RoutineGroup

type RoutineGroup struct {
	// contains filtered or unexported fields
}

func (*RoutineGroup) WaitAllResults

func (group *RoutineGroup) WaitAllResults(ctx *Context) (interface{}, error)

type RoutinePermission

type RoutinePermission struct {
	Kind_ PermissionKind
}

func (RoutinePermission) Includes

func (perm RoutinePermission) Includes(otherPerm Permission) bool

func (RoutinePermission) Kind

func (perm RoutinePermission) Kind() PermissionKind

func (RoutinePermission) String

func (perm RoutinePermission) String() string

type RuneLiteral

type RuneLiteral struct {
	NodeBase
	Value rune
}

type RuneRange

type RuneRange struct {
	Start rune
	End   rune
}

TODO: implement Iterable

func (RuneRange) Random

func (r RuneRange) Random() interface{}

func (RuneRange) RandomRune

func (r RuneRange) RandomRune() rune

type RuneRangeExpression

type RuneRangeExpression struct {
	NodeBase
	Lower *RuneLiteral
	Upper *RuneLiteral
}

type RuneRangeStringPattern

type RuneRangeStringPattern struct {
	// contains filtered or unexported fields
}

func (RuneRangeStringPattern) Random

func (patt RuneRangeStringPattern) Random() interface{}

func (RuneRangeStringPattern) Regex

func (patt RuneRangeStringPattern) Regex() string

func (RuneRangeStringPattern) Test

func (patt RuneRangeStringPattern) Test(v interface{}) bool

type SequenceStringPattern

type SequenceStringPattern struct {
	// contains filtered or unexported fields
}

func (SequenceStringPattern) Random

func (patt SequenceStringPattern) Random() interface{}

func (SequenceStringPattern) Regex

func (patt SequenceStringPattern) Regex() string

func (SequenceStringPattern) Test

func (patt SequenceStringPattern) Test(v interface{}) bool

type SimpleRate

type SimpleRate int

type SliceExpression

type SliceExpression struct {
	NodeBase
	Indexed    Node
	StartIndex Node //can be nil
	EndIndex   Node //can be nil
}

type SmallKVStore

type SmallKVStore struct {
	// contains filtered or unexported fields
}

func OpenOrCreateStore

func OpenOrCreateStore(ctx *Context, filepath Path) (*SmallKVStore, error)

func (*SmallKVStore) Get

func (store *SmallKVStore) Get(ctx *Context, key string) (interface{}, bool)

func (*SmallKVStore) Has

func (store *SmallKVStore) Has(ctx *Context, key string) bool

func (*SmallKVStore) Lock

func (store *SmallKVStore) Lock()

func (*SmallKVStore) Set

func (store *SmallKVStore) Set(ctx *Context, key string, value interface{})

func (*SmallKVStore) Unlock

func (store *SmallKVStore) Unlock()

type SpawnExpression

type SpawnExpression struct {
	NodeBase
	GroupIdent         *IdentifierLiteral //can be nil
	Globals            Node
	ExprOrVar          Node
	GrantedPermissions *ObjectLiteral //nil if no "allow ...." in the spawn expression
}

type SpreadArgument

type SpreadArgument struct {
	NodeBase
	Expr Node
}

type StackPermission

type StackPermission struct {
	// contains filtered or unexported fields
}

func (StackPermission) Includes

func (perm StackPermission) Includes(otherPerm Permission) bool

func (StackPermission) Kind

func (perm StackPermission) Kind() PermissionKind

func (StackPermission) String

func (perm StackPermission) String() string

type State

type State struct {
	ScopeStack  []map[string]interface{}
	ReturnValue *interface{}
	IterationChange

	Script     []rune
	ScriptName string
	// contains filtered or unexported fields
}

func NewDefaultState

func NewDefaultState(ctx *Context) *State

func NewState

func NewState(ctx *Context, args ...map[string]interface{}) *State

func (State) CurrentScope

func (state State) CurrentScope() map[string]interface{}

func (State) GlobalScope

func (state State) GlobalScope() map[string]interface{}

func (*State) PopScope

func (state *State) PopScope()

func (*State) PushScope

func (state *State) PushScope()

type Statement

type Statement interface {
	Node
}

type StringLiteral

type StringLiteral struct {
	NodeBase
	Raw   string
	Value string
}

type StringPatternElement

type StringPatternElement interface {
	Matcher
	GenerativePattern
	Regex() string
}

func CompileStringPatternNode

func CompileStringPatternNode(node Node, state *State) (StringPatternElement, error)

type SwitchStatement

type SwitchStatement struct {
	NodeBase
	Discriminant Node
	Cases        []*Case
}

type TermAction

type TermAction int
const (
	NoAction TermAction = iota
	Up
	Down
	Right
	Left
	BackwardWord
	ForwardWord
	End
	Home
	Back
	DeleteWord
	Enter
	Stop
	SuggestComplete
	Escape
	EscapeNext
	Delete
)

func (TermAction) String

func (code TermAction) String() string

type Token

type Token struct {
	Type TokenType
	Span NodeSpan
}

func GetTokens

func GetTokens(node Node) []Token

type TokenBucket

type TokenBucket struct {
	// contains filtered or unexported fields
}

TokenBucket represents a token bucket (https://en.wikipedia.org/wiki/Token_bucket) which based on multi goroutines, and is safe to use under concurrency environments.

func (*TokenBucket) Availible

func (tb *TokenBucket) Availible() int64

Availible returns how many tokens are availible in the bucket.

func (*TokenBucket) Capability

func (tb *TokenBucket) Capability() int64

Capability returns the capability of this token bucket.

func (*TokenBucket) Destroy

func (tb *TokenBucket) Destroy()

Destroy destroys the token bucket and stop the inner channels.

func (*TokenBucket) Take

func (tb *TokenBucket) Take(count int64)

Take tasks specified count tokens from the bucket, if there are not enough tokens in the bucket, it will keep waiting until count tokens are availible and then take them.

func (*TokenBucket) TakeMaxDuration

func (tb *TokenBucket) TakeMaxDuration(count int64, max time.Duration) bool

TakeMaxDuration tasks specified count tokens from the bucket, if there are not enough tokens in the bucket, it will keep waiting until count tokens are availible and then take them or just return false when reach the given max duration.

func (*TokenBucket) TryTake

func (tb *TokenBucket) TryTake(count int64) bool

TryTake trys to task specified count tokens from the bucket. if there are not enough tokens in the bucket, it will return false.

func (*TokenBucket) Wait

func (tb *TokenBucket) Wait(count int64)

Wait will keep waiting until count tokens are availible in the bucket.

func (*TokenBucket) WaitMaxDuration

func (tb *TokenBucket) WaitMaxDuration(count int64, max time.Duration) bool

WaitMaxDuration will keep waiting until count tokens are availible in the bucket or just return false when reach the given max duration.

type TokenType

type TokenType int
const (
	//WITH NO VALUE
	IF_KEYWORD TokenType = iota
	ELSE_KEYWORD
	REQUIRE_KEYWORD
	DROP_PERMS_KEYWORD
	ASSIGN_KEYWORD
	CONST_KEYWORD
	FOR_KEYWORD
	IN_KEYWORD
	SPAWN_KEYWORD
	ALLOW_KEYWORD
	IMPORT_KEYWORD
	FN_KEYWORD
	SWITCH_KEYWORD
	MATCH_KEYWORD
	RETURN_KEYWORD
	BREAK_KEYWORD
	CONTINUE_KEYWORD
	OPENING_BRACKET
	CLOSING_BRACKET
	OPENING_CURLY_BRACKET
	CLOSING_CURLY_BRACKET
	OPENING_PARENTHESIS
	CLOSING_PARENTHESIS
	COMMA
	COLON
	SEMICOLON
	CSS_SELECTOR_PREFIX
	THREE_DOTS

	//WITH VALUE
	INT_LITERAL
	NIL_LITERAL
	FLOAT_LITERAL
	BOOLEAN_LITERAL
	STRING_LITERAL
	RATE_LITERAL
	QUANTITY_LITERAL
	FLAG_LITERAL
	RUNE_LITERAL
	AT_HOST_LITERAL
	HTTP_HOST_LITERAL
	URL_LITERAL
	URL_PATTERN_LITERAL
	HTTP_HOST_PATTERN_LITERAL
	PATTERN_IDENTIFIER_LITERAL
	IDENTIFIER_LITERAL
	ABSOLUTE_PATH_LITERAL
	RELATIVE_PATH_LITERAL
	ABSOLUTE_PATH_PATTERN_LITERAL
	RELATIVE_PATH_PATTERN_LITERAL
	BINARY_OPERATOR
)

type TraversalAction

type TraversalAction int
const (
	Continue TraversalAction = iota
	Prune
	StopTraversal
)

type TraversalConfiguration

type TraversalConfiguration struct {
	MaxDepth int
}

type TraversalOrder

type TraversalOrder int

type URL

type URL string

type URLExpression

type URLExpression struct {
	NodeBase
	Raw         string
	HostPart    Node
	Path        *AbsolutePathExpression
	QueryParams []Node
}

type URLLiteral

type URLLiteral struct {
	NodeBase
	Value string
}

type URLPattern

type URLPattern string

func (URLPattern) Prefix

func (patt URLPattern) Prefix() string

func (URLPattern) Test

func (patt URLPattern) Test(v interface{}) bool

type URLPatternLiteral

type URLPatternLiteral struct {
	NodeBase
	Value string
}

type URLQueryExpression

type URLQueryExpression struct {
	NodeBase
	Parameters map[string][]Node
}

type URLQueryParameter

type URLQueryParameter struct {
	NodeBase
	Name  string
	Value []Node
}

type URLQueryParameterSlice

type URLQueryParameterSlice struct {
	NodeBase
	Value string
}

type UnionStringPattern

type UnionStringPattern struct {
	// contains filtered or unexported fields
}

func (UnionStringPattern) Random

func (patt UnionStringPattern) Random() interface{}

func (UnionStringPattern) Regex

func (patt UnionStringPattern) Regex() string

func (UnionStringPattern) Test

func (patt UnionStringPattern) Test(v interface{}) bool

type UnknownNode

type UnknownNode struct {
	NodeBase
}

type UpperBoundRangeExpression

type UpperBoundRangeExpression struct {
	NodeBase
	UpperBound Node
}

type Variable

type Variable struct {
	NodeBase
	Name string
}

Jump to

Keyboard shortcuts

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