1
0
mirror of https://github.com/MontFerret/ferret.git synced 2025-07-03 00:46:51 +02:00

build core.Functions with map

This commit is contained in:
3timeslazy
2019-10-15 21:06:48 +03:00
parent 55e82a9791
commit ad2ec2e817
12 changed files with 231 additions and 207 deletions

View File

@ -11,15 +11,19 @@ import (
) )
func HTTPHelpers(ns core.Namespace) error { func HTTPHelpers(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"GET": httpGet, core.NewFunctionsFromMap(map[string]core.Function{
}) "GET": httpGet,
}),
)
} }
func Assertions(ns core.Namespace) error { func Assertions(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"EXPECT": expect, core.NewFunctionsFromMap(map[string]core.Function{
}) "EXPECT": expect,
}),
)
} }
func expect(_ context.Context, args ...core.Value) (core.Value, error) { func expect(_ context.Context, args ...core.Value) (core.Value, error) {

View File

@ -60,8 +60,10 @@ func (nc *NamespaceContainer) RemoveFunction(name string) {
nc.funcs.Unset(nc.makeFullName(name)) nc.funcs.Unset(nc.makeFullName(name))
} }
func (nc *NamespaceContainer) RegisterFunctions(funcs core.FunctionsMap) error { func (nc *NamespaceContainer) RegisterFunctions(funcs *core.Functions) error {
for name, fun := range funcs { for _, name := range funcs.Names() {
fun, _ := funcs.Get(name)
if err := nc.RegisterFunction(name, fun); err != nil { if err := nc.RegisterFunction(name, fun); err != nil {
return err return err
} }

View File

@ -12,7 +12,7 @@ type (
Namespace interface { Namespace interface {
Namespace(name string) Namespace Namespace(name string) Namespace
RegisterFunction(name string, fun Function) error RegisterFunction(name string, fun Function) error
RegisterFunctions(funs FunctionsMap) error RegisterFunctions(funs *Functions) error
RegisteredFunctions() []string RegisteredFunctions() []string
RemoveFunction(name string) RemoveFunction(name string)
} }
@ -37,12 +37,9 @@ func ValidateArgs(args []Value, minimum, maximum int) error {
type ( type (
// Functions is a container for functions. // Functions is a container for functions.
Functions struct { Functions struct {
functions FunctionsMap functions map[string]Function
} }
// FunctionsMap is a map of functions and their names.
FunctionsMap map[string]Function
// Function is a common interface for all functions of FQL. // Function is a common interface for all functions of FQL.
Function = func(ctx context.Context, args ...Value) (Value, error) Function = func(ctx context.Context, args ...Value) (Value, error)
) )
@ -50,10 +47,22 @@ type (
// NewFunctions returns new empty Functions. // NewFunctions returns new empty Functions.
func NewFunctions() *Functions { func NewFunctions() *Functions {
return &Functions{ return &Functions{
functions: make(FunctionsMap), functions: make(map[string]Function),
} }
} }
// NewFunctionsFromMap creates new Functions from map, where
// key is the name of the function and value is the function.
func NewFunctionsFromMap(funcs map[string]Function) *Functions {
fns := NewFunctions()
for name, fn := range funcs {
fns.Set(name, fn)
}
return fns
}
// Get returns the function with the given name. If the function // Get returns the function with the given name. If the function
// does not exist it returns nil, false. // does not exist it returns nil, false.
func (fns *Functions) Get(name string) (Function, bool) { func (fns *Functions) Get(name string) (Function, bool) {
@ -67,7 +76,7 @@ func (fns *Functions) Set(name string, fn Function) {
// the preferred way to create Functions is NewFunctions. // the preferred way to create Functions is NewFunctions.
// But just in case, if someone creates differently // But just in case, if someone creates differently
if fns.functions == nil { if fns.functions == nil {
fns.functions = make(FunctionsMap, 1) fns.functions = make(map[string]Function, 1)
} }
fns.functions[strings.ToUpper(name)] = fn fns.functions[strings.ToUpper(name)] = fn

View File

@ -6,30 +6,31 @@ import (
) )
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"APPEND": Append, core.NewFunctionsFromMap(map[string]core.Function{
"FIRST": First, "APPEND": Append,
"FLATTEN": Flatten, "FIRST": First,
"INTERSECTION": Intersection, "FLATTEN": Flatten,
"LAST": Last, "INTERSECTION": Intersection,
"MINUS": Minus, "LAST": Last,
"NTH": Nth, "MINUS": Minus,
"OUTERSECTION": Outersection, "NTH": Nth,
"POP": Pop, "OUTERSECTION": Outersection,
"POSITION": Position, "POP": Pop,
"PUSH": Push, "POSITION": Position,
"REMOVE_NTH": RemoveNth, "PUSH": Push,
"REMOVE_VALUE": RemoveValue, "REMOVE_NTH": RemoveNth,
"REMOVE_VALUES": RemoveValues, "REMOVE_VALUE": RemoveValue,
"SHIFT": Shift, "REMOVE_VALUES": RemoveValues,
"SLICE": Slice, "SHIFT": Shift,
"SORTED": Sorted, "SLICE": Slice,
"SORTED_UNIQUE": SortedUnique, "SORTED": Sorted,
"UNION": Union, "SORTED_UNIQUE": SortedUnique,
"UNION_DISTINCT": UnionDistinct, "UNION": Union,
"UNIQUE": Unique, "UNION_DISTINCT": UnionDistinct,
"UNSHIFT": Unshift, "UNIQUE": Unique,
}) "UNSHIFT": Unshift,
}))
} }
func ToUniqueArray(arr *values.Array) *values.Array { func ToUniqueArray(arr *values.Array) *values.Array {

View File

@ -3,8 +3,9 @@ package collections
import "github.com/MontFerret/ferret/pkg/runtime/core" import "github.com/MontFerret/ferret/pkg/runtime/core"
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"LENGTH": Length, core.NewFunctionsFromMap(map[string]core.Function{
"REVERSE": Reverse, "LENGTH": Length,
}) "REVERSE": Reverse,
}))
} }

View File

@ -2,8 +2,8 @@ package datetime
import "github.com/MontFerret/ferret/pkg/runtime/core" import "github.com/MontFerret/ferret/pkg/runtime/core"
func NewLib() core.FunctionsMap { func NewLib() map[string]core.Function {
return core.FunctionsMap{ return map[string]core.Function{
"NOW": Now, "NOW": Now,
"DATE": Date, "DATE": Date,
"DATE_DAYOFWEEK": DateDayOfWeek, "DATE_DAYOFWEEK": DateDayOfWeek,

View File

@ -11,64 +11,65 @@ import (
) )
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"ATTR_GET": AttributeGet, core.NewFunctionsFromMap(map[string]core.Function{
"ATTR_REMOVE": AttributeRemove, "ATTR_GET": AttributeGet,
"ATTR_SET": AttributeSet, "ATTR_REMOVE": AttributeRemove,
"BLUR": Blur, "ATTR_SET": AttributeSet,
"COOKIE_DEL": CookieDel, "BLUR": Blur,
"COOKIE_GET": CookieGet, "COOKIE_DEL": CookieDel,
"COOKIE_SET": CookieSet, "COOKIE_GET": CookieGet,
"CLICK": Click, "COOKIE_SET": CookieSet,
"CLICK_ALL": ClickAll, "CLICK": Click,
"DOCUMENT": Open, "CLICK_ALL": ClickAll,
"DOWNLOAD": Download, "DOCUMENT": Open,
"ELEMENT": Element, "DOWNLOAD": Download,
"ELEMENT_EXISTS": ElementExists, "ELEMENT": Element,
"ELEMENTS": Elements, "ELEMENT_EXISTS": ElementExists,
"ELEMENTS_COUNT": ElementsCount, "ELEMENTS": Elements,
"FOCUS": Focus, "ELEMENTS_COUNT": ElementsCount,
"HOVER": Hover, "FOCUS": Focus,
"INNER_HTML": GetInnerHTML, "HOVER": Hover,
"INNER_HTML_SET": SetInnerHTML, "INNER_HTML": GetInnerHTML,
"INNER_HTML_ALL": GetInnerHTMLAll, "INNER_HTML_SET": SetInnerHTML,
"INNER_TEXT": GetInnerText, "INNER_HTML_ALL": GetInnerHTMLAll,
"INNER_TEXT_SET": SetInnerText, "INNER_TEXT": GetInnerText,
"INNER_TEXT_ALL": GetInnerTextAll, "INNER_TEXT_SET": SetInnerText,
"INPUT": Input, "INNER_TEXT_ALL": GetInnerTextAll,
"INPUT_CLEAR": InputClear, "INPUT": Input,
"MOUSE": MouseMoveXY, "INPUT_CLEAR": InputClear,
"NAVIGATE": Navigate, "MOUSE": MouseMoveXY,
"NAVIGATE_BACK": NavigateBack, "NAVIGATE": Navigate,
"NAVIGATE_FORWARD": NavigateForward, "NAVIGATE_BACK": NavigateBack,
"PAGINATION": Pagination, "NAVIGATE_FORWARD": NavigateForward,
"PDF": PDF, "PAGINATION": Pagination,
"SCREENSHOT": Screenshot, "PDF": PDF,
"SCROLL": ScrollXY, "SCREENSHOT": Screenshot,
"SCROLL_BOTTOM": ScrollBottom, "SCROLL": ScrollXY,
"SCROLL_ELEMENT": ScrollInto, "SCROLL_BOTTOM": ScrollBottom,
"SCROLL_TOP": ScrollTop, "SCROLL_ELEMENT": ScrollInto,
"SELECT": Select, "SCROLL_TOP": ScrollTop,
"STYLE_GET": StyleGet, "SELECT": Select,
"STYLE_REMOVE": StyleRemove, "STYLE_GET": StyleGet,
"STYLE_SET": StyleSet, "STYLE_REMOVE": StyleRemove,
"WAIT_ATTR": WaitAttribute, "STYLE_SET": StyleSet,
"WAIT_NO_ATTR": WaitNoAttribute, "WAIT_ATTR": WaitAttribute,
"WAIT_ATTR_ALL": WaitAttributeAll, "WAIT_NO_ATTR": WaitNoAttribute,
"WAIT_NO_ATTR_ALL": WaitNoAttributeAll, "WAIT_ATTR_ALL": WaitAttributeAll,
"WAIT_ELEMENT": WaitElement, "WAIT_NO_ATTR_ALL": WaitNoAttributeAll,
"WAIT_NO_ELEMENT": WaitNoElement, "WAIT_ELEMENT": WaitElement,
"WAIT_CLASS": WaitClass, "WAIT_NO_ELEMENT": WaitNoElement,
"WAIT_NO_CLASS": WaitNoClass, "WAIT_CLASS": WaitClass,
"WAIT_CLASS_ALL": WaitClassAll, "WAIT_NO_CLASS": WaitNoClass,
"WAIT_NO_CLASS_ALL": WaitNoClassAll, "WAIT_CLASS_ALL": WaitClassAll,
"WAIT_STYLE": WaitStyle, "WAIT_NO_CLASS_ALL": WaitNoClassAll,
"WAIT_NO_STYLE": WaitNoStyle, "WAIT_STYLE": WaitStyle,
"WAIT_STYLE_ALL": WaitStyleAll, "WAIT_NO_STYLE": WaitNoStyle,
"WAIT_NO_STYLE_ALL": WaitNoStyleAll, "WAIT_STYLE_ALL": WaitStyleAll,
"WAIT_NAVIGATION": WaitNavigation, "WAIT_NO_STYLE_ALL": WaitNoStyleAll,
"XPATH": XPath, "WAIT_NAVIGATION": WaitNavigation,
}) "XPATH": XPath,
}))
} }
func OpenOrCastPage(ctx context.Context, value core.Value) (drivers.HTMLPage, bool, error) { func OpenOrCastPage(ctx context.Context, value core.Value) (drivers.HTMLPage, bool, error) {

View File

@ -16,41 +16,42 @@ const (
) )
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"ABS": Abs, core.NewFunctionsFromMap(map[string]core.Function{
"ACOS": Acos, "ABS": Abs,
"ASIN": Asin, "ACOS": Acos,
"ATAN": Atan, "ASIN": Asin,
"ATAN2": Atan2, "ATAN": Atan,
"AVERAGE": Average, "ATAN2": Atan2,
"CEIL": Ceil, "AVERAGE": Average,
"COS": Cos, "CEIL": Ceil,
"DEGREES": Degrees, "COS": Cos,
"EXP": Exp, "DEGREES": Degrees,
"EXP2": Exp2, "EXP": Exp,
"FLOOR": Floor, "EXP2": Exp2,
"LOG": Log, "FLOOR": Floor,
"LOG2": Log2, "LOG": Log,
"LOG10": Log10, "LOG2": Log2,
"MAX": Max, "LOG10": Log10,
"MEDIAN": Median, "MAX": Max,
"MIN": Min, "MEDIAN": Median,
"PERCENTILE": Percentile, "MIN": Min,
"PI": Pi, "PERCENTILE": Percentile,
"POW": Pow, "PI": Pi,
"RADIANS": Radians, "POW": Pow,
"RAND": Rand, "RADIANS": Radians,
"RANGE": Range, "RAND": Rand,
"ROUND": Round, "RANGE": Range,
"SIN": Sin, "ROUND": Round,
"SQRT": Sqrt, "SIN": Sin,
"STDDEV_POPULATION": StandardDeviationPopulation, "SQRT": Sqrt,
"STDDEV_SAMPLE": StandardDeviationSample, "STDDEV_POPULATION": StandardDeviationPopulation,
"SUM": Sum, "STDDEV_SAMPLE": StandardDeviationSample,
"TAN": Tan, "SUM": Sum,
"VARIANCE_POPULATION": PopulationVariance, "TAN": Tan,
"VARIANCE_SAMPLE": SampleVariance, "VARIANCE_POPULATION": PopulationVariance,
}) "VARIANCE_SAMPLE": SampleVariance,
}))
} }
func toFloat(arg core.Value) float64 { func toFloat(arg core.Value) float64 {

View File

@ -3,13 +3,14 @@ package objects
import "github.com/MontFerret/ferret/pkg/runtime/core" import "github.com/MontFerret/ferret/pkg/runtime/core"
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"HAS": Has, core.NewFunctionsFromMap(map[string]core.Function{
"KEYS": Keys, "HAS": Has,
"KEEP_KEYS": KeepKeys, "KEYS": Keys,
"MERGE": Merge, "KEEP_KEYS": KeepKeys,
"ZIP": Zip, "MERGE": Merge,
"VALUES": Values, "ZIP": Zip,
"MERGE_RECURSIVE": MergeRecursive, "VALUES": Values,
}) "MERGE_RECURSIVE": MergeRecursive,
}))
} }

View File

@ -3,39 +3,40 @@ package strings
import "github.com/MontFerret/ferret/pkg/runtime/core" import "github.com/MontFerret/ferret/pkg/runtime/core"
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"CONCAT": Concat, core.NewFunctionsFromMap(map[string]core.Function{
"CONCAT_SEPARATOR": ConcatWithSeparator, "CONCAT": Concat,
"CONTAINS": Contains, "CONCAT_SEPARATOR": ConcatWithSeparator,
"ESCAPE_HTML": EscapeHTML, "CONTAINS": Contains,
"DECODE_URI_COMPONENT": DecodeURIComponent, "ESCAPE_HTML": EscapeHTML,
"ENCODE_URI_COMPONENT": EncodeURIComponent, "DECODE_URI_COMPONENT": DecodeURIComponent,
"FIND_FIRST": FindFirst, "ENCODE_URI_COMPONENT": EncodeURIComponent,
"FIND_LAST": FindLast, "FIND_FIRST": FindFirst,
"JSON_PARSE": JSONParse, "FIND_LAST": FindLast,
"JSON_STRINGIFY": JSONStringify, "JSON_PARSE": JSONParse,
"LEFT": Left, "JSON_STRINGIFY": JSONStringify,
"LIKE": Like, "LEFT": Left,
"LOWER": Lower, "LIKE": Like,
"LTRIM": LTrim, "LOWER": Lower,
"RANDOM_TOKEN": RandomToken, "LTRIM": LTrim,
"MD5": Md5, "RANDOM_TOKEN": RandomToken,
"REGEXP_MATCH": RegexMatch, "MD5": Md5,
"REGEXP_SPLIT": RegexSplit, "REGEXP_MATCH": RegexMatch,
"REGEXP_TEST": RegexTest, "REGEXP_SPLIT": RegexSplit,
"REGEXP_REPLACE": RegexReplace, "REGEXP_TEST": RegexTest,
"RIGHT": Right, "REGEXP_REPLACE": RegexReplace,
"RTRIM": RTrim, "RIGHT": Right,
"SHA1": Sha1, "RTRIM": RTrim,
"SHA512": Sha512, "SHA1": Sha1,
"SPLIT": Split, "SHA512": Sha512,
"SUBSTITUTE": Substitute, "SPLIT": Split,
"SUBSTRING": Substring, "SUBSTITUTE": Substitute,
"TO_BASE64": ToBase64, "SUBSTRING": Substring,
"FROM_BASE64": FromBase64, "TO_BASE64": ToBase64,
"TRIM": Trim, "FROM_BASE64": FromBase64,
"UPPER": Upper, "TRIM": Trim,
"FMT": Fmt, "UPPER": Upper,
"UNESCAPE_HTML": UnescapeHTML, "FMT": Fmt,
}) "UNESCAPE_HTML": UnescapeHTML,
}))
} }

View File

@ -6,27 +6,28 @@ import (
) )
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"TO_BOOL": ToBool, core.NewFunctionsFromMap(map[string]core.Function{
"TO_INT": ToInt, "TO_BOOL": ToBool,
"TO_FLOAT": ToFloat, "TO_INT": ToInt,
"TO_STRING": ToString, "TO_FLOAT": ToFloat,
"TO_DATETIME": ToDateTime, "TO_STRING": ToString,
"TO_ARRAY": ToArray, "TO_DATETIME": ToDateTime,
"IS_NONE": IsNone, "TO_ARRAY": ToArray,
"IS_BOOL": IsBool, "IS_NONE": IsNone,
"IS_INT": IsInt, "IS_BOOL": IsBool,
"IS_FLOAT": IsFloat, "IS_INT": IsInt,
"IS_STRING": IsString, "IS_FLOAT": IsFloat,
"IS_DATETIME": IsDateTime, "IS_STRING": IsString,
"IS_ARRAY": IsArray, "IS_DATETIME": IsDateTime,
"IS_OBJECT": IsObject, "IS_ARRAY": IsArray,
"IS_HTML_ELEMENT": IsHTMLElement, "IS_OBJECT": IsObject,
"IS_HTML_DOCUMENT": IsHTMLDocument, "IS_HTML_ELEMENT": IsHTMLElement,
"IS_BINARY": IsBinary, "IS_HTML_DOCUMENT": IsHTMLDocument,
"IS_NAN": IsNaN, "IS_BINARY": IsBinary,
"TYPENAME": TypeName, "IS_NAN": IsNaN,
}) "TYPENAME": TypeName,
}))
} }
func isTypeof(value core.Value, ctype core.Type) core.Value { func isTypeof(value core.Value, ctype core.Type) core.Value {

View File

@ -3,8 +3,10 @@ package utils
import "github.com/MontFerret/ferret/pkg/runtime/core" import "github.com/MontFerret/ferret/pkg/runtime/core"
func RegisterLib(ns core.Namespace) error { func RegisterLib(ns core.Namespace) error {
return ns.RegisterFunctions(core.FunctionsMap{ return ns.RegisterFunctions(
"WAIT": Wait, core.NewFunctionsFromMap(map[string]core.Function{
"PRINT": Print, "WAIT": Wait,
}) "PRINT": Print,
}),
)
} }