1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
|
package data
import (
"bytes"
"github.com/viant/toolbox"
"math"
"strings"
)
const (
eofToken = -1
invalidToken = iota
beforeVarToken
varToken
incToken
decrementToken
shiftToken
enclosedVarToken
callToken
idToken
arrayIndexToken
unmatchedToken
keyIndexToken
whitespace
groupingToken
operatorTojeb
doubleQuoteEnclosedToken
comaToken
)
var matchers = map[int]toolbox.Matcher{
beforeVarToken: toolbox.NewTerminatorMatcher("$"),
varToken: toolbox.NewCharactersMatcher("$"),
comaToken: toolbox.NewTerminatorMatcher(","),
idToken: toolbox.NewCustomIdMatcher("_"),
incToken: toolbox.NewKeywordsMatcher(true, "++"),
decrementToken: toolbox.NewKeywordsMatcher(true, "--"),
shiftToken: toolbox.NewKeywordsMatcher(true, "<-"),
arrayIndexToken: toolbox.NewBodyMatcher("[", "]"),
callToken: toolbox.NewBodyMatcher("(", ")"),
enclosedVarToken: toolbox.NewBodyMatcher("{", "}"),
doubleQuoteEnclosedToken: toolbox.NewBodyMatcher(`"`, `"`),
keyIndexToken: toolbox.NewCustomIdMatcher("."),
unmatchedToken: toolbox.NewRemainingSequenceMatcher(),
groupingToken: toolbox.NewBodyMatcher("(", ")"),
operatorTojeb: toolbox.NewTerminatorMatcher("+", "-", "*", "/", "^", "%"),
whitespace: toolbox.NewCharactersMatcher(" \t\n\r"),
}
//Parse parses expression
func Parse(expression string, handler func(expression string, isUDF bool, argument interface{}) (interface{}, bool)) interface{} {
tokenizer := toolbox.NewTokenizer(expression, invalidToken, eofToken, matchers)
var value interface{}
var result = fragments{}
var ok bool
done := false
for tokenizer.Index < len(expression) && !done {
match := tokenizer.Nexts(beforeVarToken, varToken, unmatchedToken, eofToken)
switch match.Token {
case unmatchedToken:
result.Append(match.Matched)
done = true
continue
case eofToken:
break
case beforeVarToken:
result.Append(match.Matched)
continue
case varToken:
variable := "$"
match = tokenizer.Nexts(idToken, enclosedVarToken, incToken, decrementToken, shiftToken)
switch match.Token {
case eofToken:
result.Append(variable)
continue
case enclosedVarToken:
expanded := expandEnclosed(match.Matched, handler)
if toolbox.IsFloat(expanded) || toolbox.IsInt(expanded) {
value = expanded
result.Append(value)
continue
}
expandedText := toolbox.AsString(expanded)
if strings.HasSuffix(expandedText, ")") {
value = Parse("$"+expandedText, handler)
if textValue, ok := value.(string); ok && textValue == "$"+expandedText {
value = "${" + expandedText + "}"
}
result.Append(value)
continue
}
variable := "${" + expandedText + "}"
if value, ok = handler(variable, false, ""); !ok {
value = variable
}
result.Append(value)
continue
case incToken, decrementToken, shiftToken:
variable += match.Matched
match = tokenizer.Nexts(idToken) //enclosedVarToken, idToken ?
if match.Token != idToken {
result.Append(variable)
continue
}
fallthrough
case idToken:
variable += match.Matched
variable = expandVariable(tokenizer, variable, handler)
match = tokenizer.Nexts(callToken, incToken, decrementToken, beforeVarToken, unmatchedToken, eofToken)
switch match.Token {
case callToken:
arguments := string(match.Matched[1 : len(match.Matched)-1])
if value, ok = handler(variable, true, arguments); !ok {
value = variable + match.Matched
}
result.Append(value)
continue
case incToken, decrementToken:
variable += match.Matched
match.Matched = ""
fallthrough
case beforeVarToken, unmatchedToken, eofToken, invalidToken:
if value, ok = handler(variable, false, ""); !ok {
value = variable
}
result.Append(value)
result.Append(match.Matched)
continue
}
default:
result.Append(variable)
}
}
}
return result.Get()
}
func expandVariable(tokenizer *toolbox.Tokenizer, variable string, handler func(expression string, isUDF bool, argument interface{}) (interface{}, bool)) string {
match := tokenizer.Nexts(keyIndexToken, arrayIndexToken)
switch match.Token {
case keyIndexToken:
variable = expandSubKey(variable, match, tokenizer, handler)
case arrayIndexToken:
variable = expandIndex(variable, match, handler, tokenizer)
}
return variable
}
func expandIndex(variable string, match *toolbox.Token, handler func(expression string, isUDF bool, argument interface{}) (interface{}, bool), tokenizer *toolbox.Tokenizer) string {
variable += toolbox.AsString(Parse(match.Matched, handler))
match = tokenizer.Nexts(arrayIndexToken, keyIndexToken)
switch match.Token {
case keyIndexToken:
variable = expandSubKey(variable, match, tokenizer, handler)
case arrayIndexToken:
variable += toolbox.AsString(Parse(match.Matched, handler))
}
return variable
}
func expandSubKey(variable string, match *toolbox.Token, tokenizer *toolbox.Tokenizer, handler func(expression string, isUDF bool, argument interface{}) (interface{}, bool)) string {
variable += match.Matched
match = tokenizer.Nexts(idToken, enclosedVarToken, arrayIndexToken)
switch match.Token {
case idToken:
variable += match.Matched
variable = expandVariable(tokenizer, variable, handler)
case enclosedVarToken:
expanded := expandEnclosed(match.Matched, handler)
variable += toolbox.AsString(expanded)
case arrayIndexToken:
variable = expandIndex(variable, match, handler, tokenizer)
}
return variable
}
func expandEnclosed(expr string, handler func(expression string, isUDF bool, argument interface{}) (interface{}, bool)) interface{} {
if strings.HasPrefix(expr, "{") && strings.HasSuffix(expr, "}") {
expr = string(expr[1 : len(expr)-1])
}
tokenizer := toolbox.NewTokenizer(expr, invalidToken, eofToken, matchers)
match, err := toolbox.ExpectTokenOptionallyFollowedBy(tokenizer, whitespace, "expected operatorTojeb", groupingToken, operatorTojeb)
if err != nil {
return Parse(expr, handler)
}
switch match.Token {
case groupingToken:
groupExpr := string(match.Matched[1 : len(match.Matched)-1])
result := expandEnclosed(groupExpr, handler)
if !(toolbox.IsInt(result) || toolbox.IsFloat(result)) {
return Parse(expr, handler)
}
expandedGroup := toolbox.AsString(result) + string(expr[tokenizer.Index:])
return expandEnclosed(expandedGroup, handler)
case operatorTojeb:
leftOperand, leftOk := tryNumericOperand(match.Matched, handler).(float64)
operator := string(expr[tokenizer.Index : tokenizer.Index+1])
rightOperand, rightOk := tryNumericOperand(string(expr[tokenizer.Index+1:]), handler).(float64)
if !leftOk || !rightOk {
return Parse(expr, handler)
}
var floatResult float64
switch operator {
case "+":
floatResult = leftOperand + rightOperand
case "-":
floatResult = leftOperand - rightOperand
case "/":
if rightOperand == 0 { //division by zero issue
return Parse(expr, handler)
}
floatResult = leftOperand / rightOperand
case "*":
floatResult = leftOperand * rightOperand
case "^":
floatResult = math.Pow(leftOperand, rightOperand)
case "%":
floatResult = float64(int(leftOperand) % int(rightOperand))
default:
return Parse(expr, handler)
}
intResult := int(floatResult)
if floatResult == float64(intResult) {
return intResult
}
return floatResult
}
return Parse(expr, handler)
}
func tryNumericOperand(expression string, handler func(expression string, isUDF bool, argument interface{}) (interface{}, bool)) interface{} {
expression = strings.TrimSpace(expression)
if result, err := toolbox.ToFloat(expression); err == nil {
return result
}
left := expandEnclosed(expression, handler)
if result, err := toolbox.ToFloat(left); err == nil {
return result
}
left = Parse("$"+expression, handler)
if result, err := toolbox.ToFloat(left); err == nil {
return result
}
return expression
}
func asExpandedText(source interface{}) string {
if source != nil && (toolbox.IsSlice(source) || toolbox.IsMap(source)) {
buf := new(bytes.Buffer)
err := toolbox.NewJSONEncoderFactory().Create(buf).Encode(source)
if err == nil {
return buf.String()
}
}
return toolbox.AsString(source)
}
type fragments []interface{}
func (f *fragments) Append(item interface{}) {
if text, ok := item.(string); ok {
if text == "" {
return
}
}
*f = append(*f, item)
}
func (f fragments) Get() interface{} {
count := len(f)
if count == 0 {
return ""
}
var emptyCount = 0
var result interface{}
for _, item := range f {
if text, ok := item.(string); ok && strings.TrimSpace(text) == "" {
emptyCount++
} else {
result = item
}
}
if emptyCount == count-1 {
return result
}
var textResult = ""
for _, item := range f {
textResult += asExpandedText(item)
}
return textResult
}
|