spiker

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2025 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Spiker

PkgGoDev Go Report Card codecov GitHub top language

A Go package implementation of real-time computing

lexer is inspired by tdop

English | 中文

Install

go get -u github.com/shockerli/spiker

Usage

  • Execute
spiker.Execute(`1 + 2 * 3 / 4`)
  • ExecuteWithScope
var scopes = spiker.NewScopeTable("demo", 1, nil)
scopes.Set("a", 3)
scopes.Set("b", 4)

spiker.ExecuteWithScope(`a * 2 + b`, )
  • Format
spiker.Format(`a + b * 3`)

Architecture

architecture

Examples

Keywords
true/false/if/else/in/...
Instruction separation

Spiker requires instructions to be terminated with a semicolon at the end of each statement

Data type
  • Number

Integer, Float

123;
-123;
12.34;
-12.34;
  • String
"abc"
  • Boolean
true;
false;
  • Array
[];
[1, 2, "a"];
[1, [], [2,], [3, 4,], 5];
  • Dict
v = [9:99, 8:8.8, "hello":12.02];
v = ["name":"jioby", "age":18, "log":[1:2, 3:4]];
v = [1, 9:9.9, 3];
Arithmetic Operators
1 + 2 - 3 * 4 / 5 % 6;
-0.19 + 3.2983;
3 ** 2;
Bitwise Operators
1 & 2;
1 | 2;
1 ^ 2;
1 >> 2;
1 << 2;
Comparison Operators
3 == 2;
3 != 2;
3 > 2;
3 >= 2;
3 < 2;
3 <= 2;
Logical Operators
!2;
1 && 2;
1 || 2;
Assignment Operators
v = 2;
v += 2;
v -= 2;
v *= 2;
v /= 2;
v %= 2;

a = b = c = 100;
In Operator
"john" in ["joy", "john"]; // true
100 in [100, 200, 300]; // true
9 in [9:"999", 8:"888"]; // true
9 in "123456789"; // true
Build-in functions
  • export

return the expression value and interrupt script

export(v);
export(v[i]);
  • exist

determines whether a variable or index exists

exist(v);
exist(v[i]);
  • len

return the length of a value

len("123");
len(v);
len(v[i]);
  • del

delete one or more variable or index

del(a)
del(a, b)
del(a, b[1])
del(a[i], b[i])
Custom function
  • single
sum = (a, b) -> a + b;

export(sum(1, 2)); # 3
pow2 = x -> x ** 2;

export(pow2(5)); # 25
  • block
max = (a, b) -> {
    if (a > b) {
        return a;
    } else {
        return b;
    }
};

export(max(1, 2)); # 2
Control structures
  • if/else
if (a > b && c != d) {
    a = b;
} else if (c > b) {
    a = c;
} else {
    export(c + d);
}
  • while
while (true) {
  a = 0;
  while (a < 10) {
    print(a, "\n");
    a += 1;
  }
}
More
a = 101;
b = 102;
c = "103";
d = [1, 2, a, b, c+b, "abc"];

if (a > b) {
    export(len(d));
} else if (a < b) {
    if (c) {
        d = -1000;
    } else {
        d = 0;
    }

    d += len(c);
    export(d);
}

export(d[2]);

License

This project is licensed under the terms of the MIT license.

Documentation

Overview

Package spiker - real-time computing package

Index

Examples

Constants

This section is empty.

Variables

View Source
var EnableAstCache = false

EnableAstCache enable ast cache, default is false

Functions

func EvalExpr added in v0.0.3

func EvalExpr(node AstNode, scope *VariableScope) interface{}

EvalExpr returns the value of the expression

func EvaluateWithScope

func EvaluateWithScope(nodeList []AstNode, scope *VariableScope) (res interface{}, err error)

EvaluateWithScope same as Evaluator, evaluate with scope

func Evaluator

func Evaluator(nodeList []AstNode) (res interface{}, err error)

Evaluator run the expression and evaluate the value

func Execute

func Execute(code string) (val interface{}, err error)

Execute return the computed result of a string expression

Example

ExampleExecute

package main

import (
	"fmt"

	"github.com/shockerli/spiker"
)

func main() {
	src := `
a = 100;
a = len("abc");
if (a > 1) {
    b = 10;
}
export(b + "10");
`
	fmt.Println(spiker.Execute(src))
}
Output:
20 <nil>

func ExecuteWithScope

func ExecuteWithScope(code string, scope *VariableScope) (val interface{}, err error)

ExecuteWithScope return the execute result with scope

func Format

func Format(code string) (s string, err error)

Format return the formatted expression

func FormatAst

func FormatAst(nodeList []AstNode) (f string, err error)

FormatAst format AST to source code

func Interface2Float64

func Interface2Float64(inter interface{}) float64

Interface2Float64 convert interface{} to float64

func Interface2String

func Interface2String(inter interface{}) string

Interface2String convert interface{} to string

func IsNumber

func IsNumber(value string) bool

IsNumber is a number string

func IsTrue

func IsTrue(value interface{}) bool

IsTrue a variable is true

func ParseNumber

func ParseNumber(value string) (float64, error)

ParseNumber parses the number in the string

func RegisterFunc added in v0.0.3

func RegisterFunc(name string, fn Func)

RegisterFunc register builtin function

Types

type Ast

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

Ast syntax parsing infrastructure

func (Ast) Raw

func (ast Ast) Raw() *Token

Raw return the token

type AstNode

type AstNode interface {
	Format() string
	Raw() *Token
}

AstNode AST node interface

func ParseAst added in v0.0.4

func ParseAst(code string) (ast []AstNode, err error)

ParseAst lexer, statements, transform, and return the ast nodes if EnableAstCache is true, it will cache the ast nodes

func Transform

func Transform(tokList []*Token) (nodeList []AstNode, err error)

Transform token list to AST tree

type Func added in v0.0.3

type Func func(fnc *NodeFuncCallOp, scope *VariableScope) interface{}

Func builtin function type

type Lexer

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

Lexer lexical analyzer

func NewLexer

func NewLexer(source string) *Lexer

NewLexer return Lexer instance

type NodeAssignOp

type NodeAssignOp struct {
	Ast
	Var  NodeVariable
	Op   Symbol
	Expr AstNode
}

NodeAssignOp assignment operator node

func (NodeAssignOp) Format

func (as NodeAssignOp) Format() string

Format .

type NodeBinaryOp

type NodeBinaryOp struct {
	Ast
	Left  AstNode
	Op    Symbol
	Right AstNode
}

NodeBinaryOp binary operator node

func (NodeBinaryOp) Format

func (bin NodeBinaryOp) Format() string

Format .

type NodeBool

type NodeBool struct {
	Ast
	Value bool
}

NodeBool bool node

func (NodeBool) Format

func (num NodeBool) Format() string

Format .

type NodeBreak

type NodeBreak struct {
	Ast
}

NodeBreak break node

func (NodeBreak) Format

func (nb NodeBreak) Format() string

Format .

type NodeContinue

type NodeContinue struct {
	Ast
}

NodeContinue continue node

func (NodeContinue) Format

func (nc NodeContinue) Format() string

Format .

type NodeFuncCallOp

type NodeFuncCallOp struct {
	Ast
	Name   NodeVariable
	Params []AstNode
}

NodeFuncCallOp function call node

func (NodeFuncCallOp) Format

func (fnc NodeFuncCallOp) Format() string

Format .

type NodeFuncDef

type NodeFuncDef struct {
	Ast
	Name       NodeVariable
	Params     []NodeParam
	Body       []AstNode
	SingleStmt bool
}

NodeFuncDef function define

func (NodeFuncDef) Format

func (fn NodeFuncDef) Format() string

Format .

type NodeIf

type NodeIf struct {
	Ast
	Expr   AstNode
	Body   []AstNode
	ElseIf *NodeIf
	Else   []AstNode
}

NodeIf if statement node

func (NodeIf) Format

func (ifs NodeIf) Format() string

Format .

type NodeList

type NodeList struct {
	Ast
	List []AstNode
}

NodeList list node

func (NodeList) Format

func (arr NodeList) Format() string

Format .

type NodeMap

type NodeMap struct {
	Ast
	Map map[AstNode]AstNode
}

NodeMap map node

func (NodeMap) Format

func (nm NodeMap) Format() string

Format .

type NodeNumber

type NodeNumber struct {
	Ast
	Value float64
}

NodeNumber number node

func (NodeNumber) Format

func (num NodeNumber) Format() string

Format .

type NodeParam

type NodeParam struct {
	Ast
	Default interface{}
	Name    NodeVariable
}

NodeParam function param

func (NodeParam) Format

func (p NodeParam) Format() string

Format .

type NodeReturn

type NodeReturn struct {
	Ast
	Tuples []AstNode
}

NodeReturn return node

func (NodeReturn) Format

func (nr NodeReturn) Format() string

Format .

type NodeString

type NodeString struct {
	Ast
	Value string
}

NodeString string node

func (NodeString) Format

func (str NodeString) Format() string

Format .

type NodeUnaryOp

type NodeUnaryOp struct {
	Ast
	Op    Symbol
	Right AstNode
}

NodeUnaryOp unary operator node

func (NodeUnaryOp) Format

func (un NodeUnaryOp) Format() string

Format .

type NodeVarIndex

type NodeVarIndex struct {
	Ast
	Var   AstNode
	Index AstNode
}

NodeVarIndex return the value of the specified index(list, string)

func (NodeVarIndex) Format

func (vi NodeVarIndex) Format() string

Format .

type NodeVariable

type NodeVariable struct {
	Ast
	Value string
}

NodeVariable variable node

func (NodeVariable) Format

func (nv NodeVariable) Format() string

Format .

type NodeWhile

type NodeWhile struct {
	Ast
	Expr AstNode
	Body []AstNode
}

NodeWhile while statement node

func (NodeWhile) Format

func (nws NodeWhile) Format() string

Format .

type Parser

type Parser struct {
	Lexer *Lexer
}

Parser Lexer parser

func (*Parser) Statements

func (psr *Parser) Statements() (stmts []*Token, err error)

Statements parse statements

type Symbol

type Symbol string

Symbol lexical symbol

const (
	SymbolIdent  Symbol = "(IDENT)"
	SymbolNumber Symbol = "(NUMBER)"
	SymbolString Symbol = "(STRING)"
	SymbolEOF    Symbol = "(EOF)"
	SymbolTuple  Symbol = "()"
	SymbolArray  Symbol = "[]"
	SymbolMap    Symbol = "{}"
	SymbolPound  Symbol = "#"

	SymbolTrue     Symbol = "true"
	SymbolFalse    Symbol = "false"
	SymbolNone     Symbol = "none"
	SymbolIf       Symbol = "if"
	SymbolElse     Symbol = "else"
	SymbolReturn   Symbol = "return"
	SymbolContinue Symbol = "continue"
	SymbolBreak    Symbol = "break"
	SymbolWhile    Symbol = "while"

	SymbolColon       Symbol = ":"
	SymbolSemicolon   Symbol = ";"
	SymbolLparen      Symbol = "("
	SymbolRparen      Symbol = ")"
	SymbolLbrack      Symbol = "["
	SymbolRbrack      Symbol = "]"
	SymbolLbrace      Symbol = "{"
	SymbolRbrace      Symbol = "}"
	SymbolComma       Symbol = ","
	SymbolFuncDeclare Symbol = "->"

	// mathematical
	SymbolAdd Symbol = "+"
	SymbolSub Symbol = "-"
	SymbolMul Symbol = "*"
	SymbolDiv Symbol = "/"
	SymbolMod Symbol = "%"
	SymbolPow Symbol = "**"
	SymbolIn  Symbol = "in"

	// bit arithmetic
	SymbolAnd Symbol = "&"
	SymbolOr  Symbol = "|"
	SymbolXor Symbol = "^"
	SymbolNot Symbol = "~"
	SymbolSHL Symbol = "<<"
	SymbolSHR Symbol = ">>"

	// logic
	SymbolLogicNot Symbol = "!"
	SymbolLogicAnd Symbol = "&&"
	SymbolLogicOr  Symbol = "||"

	// assignment
	SymbolAssign    Symbol = "="
	SymbolAssignAdd Symbol = "+="
	SymbolAssignSub Symbol = "-="
	SymbolAssignMul Symbol = "*="
	SymbolAssignDiv Symbol = "/="
	SymbolAssignMod Symbol = "%="

	// comparison
	SymbolEQL Symbol = "=="
	SymbolNEQ Symbol = "!="
	SymbolGTR Symbol = ">"
	SymbolGTE Symbol = ">="
	SymbolLSS Symbol = "<"
	SymbolLTE Symbol = "<="
)

Supported symbol

func (Symbol) String

func (sym Symbol) String() string

type Token

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

Token lexical token

func (*Token) Format

func (t *Token) Format() string

Format simple format token info

type ValueList

type ValueList []interface{}

ValueList value list

type ValueMap

type ValueMap map[string]interface{}

ValueMap kv dict

type VariableScope

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

VariableScope variable scope

func NewScopeTable

func NewScopeTable(scopeName string, scopeLevel int, scope *VariableScope) *VariableScope

NewScopeTable return a new VariableScope

func (*VariableScope) Clean

func (scope *VariableScope) Clean()

Clean clean all of the vars

func (*VariableScope) Del

func (scope *VariableScope) Del(variable string)

Del delete a variable

func (*VariableScope) Get

func (scope *VariableScope) Get(variable string) (interface{}, bool)

Get fetch variable values

func (*VariableScope) Set

func (scope *VariableScope) Set(variable string, val interface{})

Set store variable values

Jump to

Keyboard shortcuts

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