Switch to github.com/antonmedv/expr for expression evaluation

pull/154/head
Simon Roberts 3 years ago
parent 89bab4e2af
commit 09b66439fc

@ -2,10 +2,10 @@ module github.com/miguelmota/cointop
require (
github.com/BurntSushi/toml v0.3.1
github.com/Knetic/govaluate v3.0.0+incompatible
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d
github.com/anaskhan96/soup v1.1.1 // indirect
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect
github.com/antonmedv/expr v1.9.0
github.com/creack/pty v1.1.11
github.com/fatih/color v1.9.0
github.com/gen2brain/beeep v0.0.0-20200526185328-e9c15c258e28

@ -1,8 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Knetic/govaluate v3.0.0+incompatible h1:7o6+MAPhYTCF0+fdvoz1xDedhRb4f6s9Tn1Tt7/WTEg=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo=
@ -13,6 +12,8 @@ github.com/anaskhan96/soup v1.1.1 h1:Duux/0htS2Va7XLJ9qIakCSey790hg9OFRm2FwlMTy0
github.com/anaskhan96/soup v1.1.1/go.mod h1:pT5vs4HXDwA5y4KQCsKvnkpQd3D+joP7IqpiGskfWW0=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antonmedv/expr v1.9.0 h1:j4HI3NHEdgDnN9p6oI6Ndr0G5QryMY0FNxT4ONrFDGU=
github.com/antonmedv/expr v1.9.0/go.mod h1:5qsM3oLGDND7sDmQGDXHkYfkjYMUX14qsgqmHhwGEk8=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
@ -26,12 +27,17 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/gdamore/tcell v1.3.0/go.mod h1:Hjvr+Ofd+gLglo7RYKxxnzCBmev3BzsS67MebKS4zMM=
github.com/gen2brain/beeep v0.0.0-20200526185328-e9c15c258e28 h1:M2Zt3G2w6Q57GZndOYk42p7RvMeO8izO8yKTfIxGqxA=
github.com/gen2brain/beeep v0.0.0-20200526185328-e9c15c258e28/go.mod h1:ElSskYZe3oM8kThaHGJ+kiN2yyUMVXMZ7WxF9QqLDS8=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
@ -73,9 +79,13 @@ github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvW
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lucasb-eyer/go-colorful v1.0.2/go.mod h1:0MS4r+7BZKSJ5mw4/S5MPN+qHFF1fYclkSPilDOKW0s=
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/maruel/panicparse v1.5.0 h1:etK4QAf/Spw8eyowKbOHRkOfhblp/kahGUy96RvbMjI=
github.com/maruel/panicparse v1.5.0/go.mod h1:aOutY/MUjdj80R0AEVI9qE2zHqig+67t2ffUDDiLzAM=
@ -87,7 +97,9 @@ github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hd
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.8/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
@ -112,6 +124,8 @@ github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaR
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
@ -122,8 +136,11 @@ github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rivo/tview v0.0.0-20200219210816-cd38d7432498/go.mod h1:6lkG1x+13OShEf0EaOCaTQYyB7d5nSbb181KtjlS+84=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sanity-io/litter v1.2.0/go.mod h1:JF6pZUFgu2Q0sBZ+HSV35P8TVPI1TTzEwyu9FXAw2W4=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
@ -137,8 +154,12 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v0.0.0-20161117074351-18a02ba4a312/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
@ -178,14 +199,17 @@ golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed h1:WBkVNH1zd9jg/dK4HCM4lNANnmd12EHC9z+LmcCG4ns=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@ -201,9 +225,11 @@ google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZi
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

@ -4,7 +4,7 @@ import (
"errors"
"strings"
"github.com/Knetic/govaluate"
"github.com/antonmedv/expr"
)
// EvaluateExpression evaulates a simple math expression string to a float64
@ -13,17 +13,17 @@ func EvaluateExpressionToFloat64(input string) (float64, error) {
if input == "" {
return 0, nil
}
expression, err := govaluate.NewEvaluableExpression(input)
if err != nil {
return 0, err
}
result, err := expression.Evaluate(nil)
result, err := expr.Eval(input, nil)
if err != nil {
return 0, err
}
f64, ok := result.(float64)
if !ok {
return 0, errors.New("could not type assert float64")
ival, ok := result.(int)
if !ok {
return 0, errors.New("could not type assert float64")
}
f64 = float64(ival)
}
return f64, nil
}

@ -1,28 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
coverage.out
manual_test.go
*.out
*.err

@ -1,10 +0,0 @@
language: go
script: ./test.sh
go:
- 1.2
- 1.3
- 1.4
- 1.5
- 1.6

@ -1,12 +0,0 @@
This library was authored by George Lester, and contains contributions from:
vjeantet (regex support)
iasci (ternary operator)
oxtoacart (parameter structures, deferred parameter retrieval)
wmiller848 (bitwise operators)
prashantv (optimization of bools)
dpaolella (exposure of variables used in an expression)
benpaxton (fix for missing type checks during literal elide process)
abrander (panic-finding testing tool)
xfennec (fix for dates being parsed in the current Location)
bgaifullin (lifting restriction on complex/struct types)

@ -1,272 +0,0 @@
package govaluate
import (
"errors"
"fmt"
)
const isoDateFormat string = "2006-01-02T15:04:05.999999999Z0700"
const shortCircuitHolder int = -1
var DUMMY_PARAMETERS = MapParameters(map[string]interface{}{})
/*
EvaluableExpression represents a set of ExpressionTokens which, taken together,
are an expression that can be evaluated down into a single value.
*/
type EvaluableExpression struct {
/*
Represents the query format used to output dates. Typically only used when creating SQL or Mongo queries from an expression.
Defaults to the complete ISO8601 format, including nanoseconds.
*/
QueryDateFormat string
/*
Whether or not to safely check types when evaluating.
If true, this library will return error messages when invalid types are used.
If false, the library will panic when operators encounter types they can't use.
This is exclusively for users who need to squeeze every ounce of speed out of the library as they can,
and you should only set this to false if you know exactly what you're doing.
*/
ChecksTypes bool
tokens []ExpressionToken
evaluationStages *evaluationStage
inputExpression string
}
/*
Parses a new EvaluableExpression from the given [expression] string.
Returns an error if the given expression has invalid syntax.
*/
func NewEvaluableExpression(expression string) (*EvaluableExpression, error) {
functions := make(map[string]ExpressionFunction)
return NewEvaluableExpressionWithFunctions(expression, functions)
}
/*
Similar to [NewEvaluableExpression], except that instead of a string, an already-tokenized expression is given.
This is useful in cases where you may be generating an expression automatically, or using some other parser (e.g., to parse from a query language)
*/
func NewEvaluableExpressionFromTokens(tokens []ExpressionToken) (*EvaluableExpression, error) {
var ret *EvaluableExpression
var err error
ret = new(EvaluableExpression)
ret.QueryDateFormat = isoDateFormat
err = checkBalance(tokens)
if err != nil {
return nil, err
}
err = checkExpressionSyntax(tokens)
if err != nil {
return nil, err
}
ret.tokens, err = optimizeTokens(tokens)
if err != nil {
return nil, err
}
ret.evaluationStages, err = planStages(ret.tokens)
if err != nil {
return nil, err
}
ret.ChecksTypes = true
return ret, nil
}
/*
Similar to [NewEvaluableExpression], except enables the use of user-defined functions.
Functions passed into this will be available to the expression.
*/
func NewEvaluableExpressionWithFunctions(expression string, functions map[string]ExpressionFunction) (*EvaluableExpression, error) {
var ret *EvaluableExpression
var err error
ret = new(EvaluableExpression)
ret.QueryDateFormat = isoDateFormat
ret.inputExpression = expression
ret.tokens, err = parseTokens(expression, functions)
if err != nil {
return nil, err
}
err = checkBalance(ret.tokens)
if err != nil {
return nil, err
}
err = checkExpressionSyntax(ret.tokens)
if err != nil {
return nil, err
}
ret.tokens, err = optimizeTokens(ret.tokens)
if err != nil {
return nil, err
}
ret.evaluationStages, err = planStages(ret.tokens)
if err != nil {
return nil, err
}
ret.ChecksTypes = true
return ret, nil
}
/*
Same as `Eval`, but automatically wraps a map of parameters into a `govalute.Parameters` structure.
*/
func (this EvaluableExpression) Evaluate(parameters map[string]interface{}) (interface{}, error) {
if parameters == nil {
return this.Eval(nil)
}
return this.Eval(MapParameters(parameters))
}
/*
Runs the entire expression using the given [parameters].
e.g., If the expression contains a reference to the variable "foo", it will be taken from `parameters.Get("foo")`.
This function returns errors if the combination of expression and parameters cannot be run,
such as if a variable in the expression is not present in [parameters].
In all non-error circumstances, this returns the single value result of the expression and parameters given.
e.g., if the expression is "1 + 1", this will return 2.0.
e.g., if the expression is "foo + 1" and parameters contains "foo" = 2, this will return 3.0
*/
func (this EvaluableExpression) Eval(parameters Parameters) (interface{}, error) {
if this.evaluationStages == nil {
return nil, nil
}
if parameters != nil {
parameters = &sanitizedParameters{parameters}
}
return this.evaluateStage(this.evaluationStages, parameters)
}
func (this EvaluableExpression) evaluateStage(stage *evaluationStage, parameters Parameters) (interface{}, error) {
var left, right interface{}
var err error
if stage.leftStage != nil {
left, err = this.evaluateStage(stage.leftStage, parameters)
if err != nil {
return nil, err
}
}
if stage.isShortCircuitable() {
switch stage.symbol {
case AND:
if left == false {
return false, nil
}
case OR:
if left == true {
return true, nil
}
case COALESCE:
if left != nil {
return left, nil
}
case TERNARY_TRUE:
if left == false {
right = shortCircuitHolder
}
case TERNARY_FALSE:
if left != nil {
right = shortCircuitHolder
}
}
}
if right != shortCircuitHolder && stage.rightStage != nil {
right, err = this.evaluateStage(stage.rightStage, parameters)
if err != nil {
return nil, err
}
}
if this.ChecksTypes {
if stage.typeCheck == nil {
err = typeCheck(stage.leftTypeCheck, left, stage.symbol, stage.typeErrorFormat)
if err != nil {
return nil, err
}
err = typeCheck(stage.rightTypeCheck, right, stage.symbol, stage.typeErrorFormat)
if err != nil {
return nil, err
}
} else {
// special case where the type check needs to know both sides to determine if the operator can handle it
if !stage.typeCheck(left, right) {
errorMsg := fmt.Sprintf(stage.typeErrorFormat, left, stage.symbol.String())
return nil, errors.New(errorMsg)
}
}
}
return stage.operator(left, right, parameters)
}
func typeCheck(check stageTypeCheck, value interface{}, symbol OperatorSymbol, format string) error {
if check == nil {
return nil
}
if check(value) {
return nil
}
errorMsg := fmt.Sprintf(format, value, symbol.String())
return errors.New(errorMsg)
}
/*
Returns an array representing the ExpressionTokens that make up this expression.
*/
func (this EvaluableExpression) Tokens() []ExpressionToken {
return this.tokens
}
/*
Returns the original expression used to create this EvaluableExpression.
*/
func (this EvaluableExpression) String() string {
return this.inputExpression
}
/*
Returns an array representing the variables contained in this EvaluableExpression.
*/
func (this EvaluableExpression) Vars() []string {
var varlist []string
for _, val := range this.Tokens() {
if val.Kind == VARIABLE {
varlist = append(varlist, val.Value.(string))
}
}
return varlist
}

@ -1,167 +0,0 @@
package govaluate
import (
"errors"
"fmt"
"regexp"
"time"
)
/*
Returns a string representing this expression as if it were written in SQL.
This function assumes that all parameters exist within the same table, and that the table essentially represents
a serialized object of some sort (e.g., hibernate).
If your data model is more normalized, you may need to consider iterating through each actual token given by `Tokens()`
to create your query.
Boolean values are considered to be "1" for true, "0" for false.
Times are formatted according to this.QueryDateFormat.
*/
func (this EvaluableExpression) ToSQLQuery() (string, error) {
var stream *tokenStream
var transactions *expressionOutputStream
var transaction string
var err error
stream = newTokenStream(this.tokens)
transactions = new(expressionOutputStream)
for stream.hasNext() {
transaction, err = this.findNextSQLString(stream, transactions)
if err != nil {
return "", err
}
transactions.add(transaction)
}
return transactions.createString(" "), nil
}
func (this EvaluableExpression) findNextSQLString(stream *tokenStream, transactions *expressionOutputStream) (string, error) {
var token ExpressionToken
var ret string
token = stream.next()
switch token.Kind {
case STRING:
ret = fmt.Sprintf("'%v'", token.Value)
case PATTERN:
ret = fmt.Sprintf("'%s'", token.Value.(*regexp.Regexp).String())
case TIME:
ret = fmt.Sprintf("'%s'", token.Value.(time.Time).Format(this.QueryDateFormat))
case LOGICALOP:
switch logicalSymbols[token.Value.(string)] {
case AND:
ret = "AND"
case OR:
ret = "OR"
}
case BOOLEAN:
if token.Value.(bool) {
ret = "1"
} else {
ret = "0"
}
case VARIABLE:
ret = fmt.Sprintf("[%s]", token.Value.(string))
case NUMERIC:
ret = fmt.Sprintf("%g", token.Value.(float64))
case COMPARATOR:
switch comparatorSymbols[token.Value.(string)] {
case EQ:
ret = "="
case NEQ:
ret = "<>"
case REQ:
ret = "RLIKE"
case NREQ:
ret = "NOT RLIKE"
default:
ret = fmt.Sprintf("%s", token.Value.(string))
}
case TERNARY:
switch ternarySymbols[token.Value.(string)] {
case COALESCE:
left := transactions.rollback()
right, err := this.findNextSQLString(stream, transactions)
if err != nil {
return "", err
}
ret = fmt.Sprintf("COALESCE(%v, %v)", left, right)
case TERNARY_TRUE:
fallthrough
case TERNARY_FALSE:
return "", errors.New("Ternary operators are unsupported in SQL output")
}
case PREFIX:
switch prefixSymbols[token.Value.(string)] {
case INVERT:
ret = fmt.Sprintf("NOT")
default:
right, err := this.findNextSQLString(stream, transactions)
if err != nil {
return "", err
}
ret = fmt.Sprintf("%s%s", token.Value.(string), right)
}
case MODIFIER:
switch modifierSymbols[token.Value.(string)] {
case EXPONENT:
left := transactions.rollback()
right, err := this.findNextSQLString(stream, transactions)
if err != nil {
return "", err
}
ret = fmt.Sprintf("POW(%s, %s)", left, right)
case MODULUS:
left := transactions.rollback()
right, err := this.findNextSQLString(stream, transactions)
if err != nil {
return "", err
}
ret = fmt.Sprintf("MOD(%s, %s)", left, right)
default:
ret = fmt.Sprintf("%s", token.Value.(string))
}
case CLAUSE:
ret = "("
case CLAUSE_CLOSE:
ret = ")"
case SEPARATOR:
ret = ","
default:
errorMsg := fmt.Sprintf("Unrecognized query token '%s' of kind '%s'", token.Value, token.Kind)
return "", errors.New(errorMsg)
}
return ret, nil
}

@ -1,9 +0,0 @@
package govaluate
/*
Represents a single parsed token.
*/
type ExpressionToken struct {
Kind TokenKind
Value interface{}
}

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014-2016 George Lester
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -1,176 +0,0 @@
govaluate
====
This library contains quite a lot of functionality, this document is meant to be formal documentation on the operators and features of it.
Some of this documentation may duplicate what's in README.md, but should never conflict.
# Types
This library only officially deals with four types; `float64`, `bool`, `string`, and arrays.
All numeric literals, with or without a radix, will be converted to `float64` for evaluation. For instance; in practice, there is no difference between the literals "1.0" and "1", they both end up as `float64`. This matters to users because if you intend to return numeric values from your expressions, then the returned value will be `float64`, not any other numeric type.
Any string _literal_ (not parameter) which is interpretable as a date will be converted to a `float64` representation of that date's unix time. Any `time.Time` parameters will not be operable with these date literals; such parameters will need to use the `time.Time.Unix()` method to get a numeric representation.
Arrays are untyped, and can be mixed-type. Internally they're all just `interface{}`. Only two operators can interact with arrays, `IN` and `,`. All other operators will refuse to operate on arrays.
# Operators
## Modifiers
### Addition, concatenation `+`
If either left or right sides of the `+` operator are a `string`, then this operator will perform string concatenation and return that result. If neither are string, then both must be numeric, and this will return a numeric result.
Any other case is invalid.
### Arithmetic `-` `*` `/` `**` `%`
`**` refers to "take to the power of". For instance, `3 ** 4` == 81.
* _Left side_: numeric
* _Right side_: numeric
* _Returns_: numeric
### Bitwise shifts, masks `>>` `<<` `|` `&` `^`
All of these operators convert their `float64` left and right sides to `int64`, perform their operation, and then convert back.
Given how this library assumes numeric are represented (as `float64`), it is unlikely that this behavior will change, even though it may cause havoc with extremely large or small numbers.
* _Left side_: numeric
* _Right side_: numeric
* _Returns_: numeric
### Negation `-`
Prefix only. This can never have a left-hand value.
* _Right side_: numeric
* _Returns_: numeric
### Inversion `!`
Prefix only. This can never have a left-hand value.
* _Right side_: bool
* _Returns_: bool
### Bitwise NOT `~`
Prefix only. This can never have a left-hand value.
* _Right side_: numeric
* _Returns_: numeric
## Logical Operators
For all logical operators, this library will short-circuit the operation if the left-hand side is sufficient to determine what to do. For instance, `true || expensiveOperation()` will not actually call `expensiveOperation()`, since it knows the left-hand side is `true`.
### Logical AND/OR `&&` `||`
* _Left side_: bool
* _Right side_: bool
* _Returns_: bool
### Ternary true `?`
Checks if the left side is `true`. If so, returns the right side. If the left side is `false`, returns `nil`.
In practice, this is commonly used with the other ternary operator.
* _Left side_: bool
* _Right side_: Any type.
* _Returns_: Right side or `nil`
### Ternary false `:`
Checks if the left side is `nil`. If so, returns the right side. If the left side is non-nil, returns the left side.
In practice, this is commonly used with the other ternary operator.
* _Left side_: Any type.
* _Right side_: Any type.
* _Returns_: Right side or `nil`
### Null coalescence `??`
Similar to the C# operator. If the left value is non-nil, it returns that. If not, then the right-value is returned.
* _Left side_: Any type.
* _Right side_: Any type.
* _Returns_: No specific type - whichever is passed to it.
## Comparators
### Numeric/lexicographic comparators `>` `<` `>=` `<=`
If both sides are numeric, this returns the usual greater/lesser behavior that would be expected.
If both sides are string, this returns the lexicographic comparison of the strings. This uses Go's standard lexicographic compare.
* _Accepts_: Left and right side must either be both string, or both numeric.
* _Returns_: bool
### Regex comparators `=~` `!~`
These use go's standard `regexp` flavor of regex. The left side is expected to be the candidate string, the right side is the pattern. `=~` returns whether or not the candidate string matches the regex pattern given on the right. `!~` is the inverted version of the same logic.
* _Left side_: string
* _Right side_: string
* _Returns_: bool
## Arrays
### Separator `,`
The separator, always paired with parenthesis, creates arrays. It must always have both a left and right-hand value, so for instance `(, 0)` and `(0,)` are invalid uses of it.
Again, this should always be used with parenthesis; like `(1, 2, 3, 4)`.
### Membership `IN`
The only operator with a text name, this operator checks the right-hand side array to see if it contains a value that is equal to the left-side value.
Equality is determined by the use of the `==` operator, and this library doesn't check types between the values. Any two values, when cast to `interface{}`, and can still be checked for equality with `==` will act as expected.
Note that you can use a parameter for the array, but it must be an `[]interface{}`.
* _Left side_: Any type.
* _Right side_: array
* _Returns_: bool
# Parameters
Parameters must be passed in every time the expression is evaluated. Parameters can be of any type, but will not cause errors unless actually used in an erroneous way. There is no difference in behavior for any of the above operators for parameters - they are type checked when used.
All `int` and `float` values of any width will be converted to `float64` before use.
At no point is the parameter structure, or any value thereof, modified by this library.
## Alternates to maps
The default form of parameters as a map may not serve your use case. You may have parameters in some other structure, you may want to change the no-parameter-found behavior, or maybe even just have some debugging print statements invoked when a parameter is accessed.
To do this, define a type that implements the `govaluate.Parameters` interface. When you want to evaluate, instead call `EvaluableExpression.Eval` and pass your parameter structure.
# Functions
During expression parsing (_not_ evaluation), a map of functions can be given to `govaluate.NewEvaluableExpressionWithFunctions` (the lengthiest and finest of function names). The resultant expression will be able to invoke those functions during evaluation. Once parsed, an expression cannot have functions added or removed - a new expression will need to be created if you want to change the functions, or behavior of said functions.
Functions always take the form `<name>(<parameters>)`, including parens. Functions can have an empty list of parameters, like `<name>()`, but still must have parens.
If the expression contains something that looks like it ought to be a function (such as `foo()`), but no such function was given to it, it will error on parsing.
Functions must be of type `map[string]govaluate.ExpressionFunction`. `ExpressionFunction`, for brevity, has the following signature:
`func(args ...interface{}) (interface{}, error)`
Where `args` is whatever is passed to the function when called. If a non-nil error is returned from a function during evaluation, the evaluation stops and ultimately returns that error to the caller of `Evaluate()` or `Eval()`.
## Built-in functions
There aren't any builtin functions. The author is opposed to maintaining a standard library of functions to be used.
Every use case of this library is different, and even in simple use cases (such as parameters, see above) different users need different behavior, naming, or even functionality. The author prefers that users make their own decisions about what functions they need, and how they operate.
# Equality
The `==` and `!=` operators involve a moderately complex workflow. They use [`reflect.DeepEqual`](https://golang.org/pkg/reflect/#DeepEqual). This is for complicated reasons, but there are some types in Go that cannot be compared with the native `==` operator. Arrays, in particular, cannot be compared - Go will panic if you try. One might assume this could be handled with the type checking system in `govaluate`, but unfortunately without reflection there is no way to know if a variable is a slice/array. Worse, structs can be incomparable if they _contain incomparable types_.
It's all very complicated. Fortunately, Go includes the `reflect.DeepEqual` function to handle all the edge cases. Currently, `govaluate` uses that for all equality/inequality.

@ -1,306 +0,0 @@
package govaluate
/*
Represents the valid symbols for operators.
*/
type OperatorSymbol int
const (
VALUE OperatorSymbol = iota
LITERAL
NOOP
EQ
NEQ
GT
LT
GTE
LTE
REQ
NREQ
IN
AND
OR
PLUS
MINUS
BITWISE_AND
BITWISE_OR
BITWISE_XOR
BITWISE_LSHIFT
BITWISE_RSHIFT
MULTIPLY
DIVIDE
MODULUS
EXPONENT
NEGATE
INVERT
BITWISE_NOT
TERNARY_TRUE
TERNARY_FALSE
COALESCE
FUNCTIONAL
SEPARATE
)
type operatorPrecedence int
const (
noopPrecedence operatorPrecedence = iota
valuePrecedence
functionalPrecedence
prefixPrecedence
exponentialPrecedence
additivePrecedence
bitwisePrecedence
bitwiseShiftPrecedence
multiplicativePrecedence
comparatorPrecedence
ternaryPrecedence
logicalAndPrecedence
logicalOrPrecedence
separatePrecedence
)
func findOperatorPrecedenceForSymbol(symbol OperatorSymbol) operatorPrecedence {
switch symbol {
case NOOP:
return noopPrecedence
case VALUE:
return valuePrecedence
case EQ:
fallthrough
case NEQ:
fallthrough
case GT:
fallthrough
case LT:
fallthrough
case GTE:
fallthrough
case LTE:
fallthrough
case REQ:
fallthrough
case NREQ:
fallthrough
case IN:
return comparatorPrecedence
case AND:
return logicalAndPrecedence
case OR:
return logicalOrPrecedence
case BITWISE_AND:
fallthrough
case BITWISE_OR:
fallthrough
case BITWISE_XOR:
return bitwisePrecedence
case BITWISE_LSHIFT:
fallthrough
case BITWISE_RSHIFT:
return bitwiseShiftPrecedence
case PLUS:
fallthrough
case MINUS:
return additivePrecedence
case MULTIPLY:
fallthrough
case DIVIDE:
fallthrough
case MODULUS:
return multiplicativePrecedence
case EXPONENT:
return exponentialPrecedence
case BITWISE_NOT:
fallthrough
case NEGATE:
fallthrough
case INVERT:
return prefixPrecedence
case COALESCE:
fallthrough
case TERNARY_TRUE:
fallthrough
case TERNARY_FALSE:
return ternaryPrecedence
case FUNCTIONAL:
return functionalPrecedence
case SEPARATE:
return separatePrecedence
}
return valuePrecedence
}
/*
Map of all valid comparators, and their string equivalents.
Used during parsing of expressions to determine if a symbol is, in fact, a comparator.
Also used during evaluation to determine exactly which comparator is being used.
*/
var comparatorSymbols = map[string]OperatorSymbol{
"==": EQ,
"!=": NEQ,
">": GT,
">=": GTE,
"<": LT,
"<=": LTE,
"=~": REQ,
"!~": NREQ,
"in": IN,
}
var logicalSymbols = map[string]OperatorSymbol{
"&&": AND,
"||": OR,
}
var bitwiseSymbols = map[string]OperatorSymbol{
"^": BITWISE_XOR,
"&": BITWISE_AND,
"|": BITWISE_OR,
}
var bitwiseShiftSymbols = map[string]OperatorSymbol{
">>": BITWISE_RSHIFT,
"<<": BITWISE_LSHIFT,
}
var additiveSymbols = map[string]OperatorSymbol{
"+": PLUS,
"-": MINUS,
}
var multiplicativeSymbols = map[string]OperatorSymbol{
"*": MULTIPLY,
"/": DIVIDE,
"%": MODULUS,
}
var exponentialSymbolsS = map[string]OperatorSymbol{
"**": EXPONENT,
}
var prefixSymbols = map[string]OperatorSymbol{
"-": NEGATE,
"!": INVERT,
"~": BITWISE_NOT,
}
var ternarySymbols = map[string]OperatorSymbol{
"?": TERNARY_TRUE,
":": TERNARY_FALSE,
"??": COALESCE,
}
// this is defined separately from additiveSymbols et al because it's needed for parsing, not stage planning.
var modifierSymbols = map[string]OperatorSymbol{
"+": PLUS,
"-": MINUS,
"*": MULTIPLY,
"/": DIVIDE,
"%": MODULUS,
"**": EXPONENT,
"&": BITWISE_AND,
"|": BITWISE_OR,
"^": BITWISE_XOR,
">>": BITWISE_RSHIFT,
"<<": BITWISE_LSHIFT,
}
var separatorSymbols = map[string]OperatorSymbol{
",": SEPARATE,
}
/*
Returns true if this operator is contained by the given array of candidate symbols.
False otherwise.
*/
func (this OperatorSymbol) IsModifierType(candidate []OperatorSymbol) bool {
for _, symbolType := range candidate {
if this == symbolType {
return true
}
}
return false
}
/*
Generally used when formatting type check errors.
We could store the stringified symbol somewhere else and not require a duplicated codeblock to translate
OperatorSymbol to string, but that would require more memory, and another field somewhere.
Adding operators is rare enough that we just stringify it here instead.
*/
func (this OperatorSymbol) String() string {
switch this {
case NOOP:
return "NOOP"
case VALUE:
return "VALUE"
case EQ:
return "="
case NEQ:
return "!="
case GT:
return ">"
case LT:
return "<"
case GTE:
return ">="
case LTE:
return "<="
case REQ:
return "=~"
case NREQ:
return "!~"
case AND:
return "&&"
case OR:
return "||"
case IN:
return "in"
case BITWISE_AND:
return "&"
case BITWISE_OR:
return "|"
case BITWISE_XOR:
return "^"
case BITWISE_LSHIFT:
return "<<"
case BITWISE_RSHIFT:
return ">>"
case PLUS:
return "+"
case MINUS:
return "-"
case MULTIPLY:
return "*"
case DIVIDE:
return "/"
case MODULUS:
return "%"
case EXPONENT:
return "**"
case NEGATE:
return "-"
case INVERT:
return "!"
case BITWISE_NOT:
return "~"
case TERNARY_TRUE:
return "?"
case TERNARY_FALSE:
return ":"
case COALESCE:
return "??"
}
return ""
}

@ -1,210 +0,0 @@
govaluate
====
[![Build Status](https://travis-ci.org/Knetic/govaluate.svg?branch=master)](https://travis-ci.org/Knetic/govaluate)
[![Godoc](https://godoc.org/github.com/Knetic/govaluate?status.png)](https://godoc.org/github.com/Knetic/govaluate)
Provides support for evaluating arbitrary C-like artithmetic/string expressions.
Why can't you just write these expressions in code?
--
Sometimes, you can't know ahead-of-time what an expression will look like, or you want those expressions to be configurable.
Perhaps you've got a set of data running through your application, and you want to allow your users to specify some validations to run on it before committing it to a database. Or maybe you've written a monitoring framework which is capable of gathering a bunch of metrics, then evaluating a few expressions to see if any metrics should be alerted upon, but the conditions for alerting are different for each monitor.
A lot of people wind up writing their own half-baked style of evaluation language that fits their needs, but isn't complete. Or they wind up baking the expression into the actual executable, even if they know it's subject to change. These strategies may work, but they take time to implement, time for users to learn, and induce technical debt as requirements change. This library is meant to cover all the normal C-like expressions, so that you don't have to reinvent one of the oldest wheels on a computer.
How do I use it?
--
You create a new EvaluableExpression, then call "Evaluate" on it.
```go
expression, err := govaluate.NewEvaluableExpression("10 > 0");
result, err := expression.Evaluate(nil);
// result is now set to "true", the bool value.
```
Cool, but how about with parameters?
```go
expression, err := govaluate.NewEvaluableExpression("foo > 0");
parameters := make(map[string]interface{}, 8)
parameters["foo"] = -1;
result, err := expression.Evaluate(parameters);
// result is now set to "false", the bool value.
```
That's cool, but we can almost certainly have done all that in code. What about a complex use case that involves some math?
```go
expression, err := govaluate.NewEvaluableExpression("(requests_made * requests_succeeded / 100) >= 90");
parameters := make(map[string]interface{}, 8)
parameters["requests_made"] = 100;
parameters["requests_succeeded"] = 80;
result, err := expression.Evaluate(parameters);
// result is now set to "false", the bool value.
```
Or maybe you want to check the status of an alive check ("smoketest") page, which will be a string?
```go
expression, err := govaluate.NewEvaluableExpression("http_response_body == 'service is ok'");
parameters := make(map[string]interface{}, 8)
parameters["http_response_body"] = "service is ok";
result, err := expression.Evaluate(parameters);
// result is now set to "true", the bool value.
```
These examples have all returned boolean values, but it's equally possible to return numeric ones.
```go
expression, err := govaluate.NewEvaluableExpression("(mem_used / total_mem) * 100");
parameters := make(map[string]interface{}, 8)
parameters["total_mem"] = 1024;
parameters["mem_used"] = 512;
result, err := expression.Evaluate(parameters);
// result is now set to "50.0", the float64 value.
```
You can also do date parsing, though the formats are somewhat limited. Stick to RF3339, ISO8061, unix date, or ruby date formats. If you're having trouble getting a date string to parse, check the list of formats actually used: [parsing.go:248](https://github.com/Knetic/govaluate/blob/0580e9b47a69125afa0e4ebd1cf93c49eb5a43ec/parsing.go#L258).
```go
expression, err := govaluate.NewEvaluableExpression("'2014-01-02' > '2014-01-01 23:59:59'");
result, err := expression.Evaluate(nil);
// result is now set to true
```
Expressions are parsed once, and can be re-used multiple times. Parsing is the compute-intensive phase of the process, so if you intend to use the same expression with different parameters, just parse it once. Like so;
```go
expression, err := govaluate.NewEvaluableExpression("response_time <= 100");
parameters := make(map[string]interface{}, 8)
for {
parameters["response_time"] = pingSomething();
result, err := expression.Evaluate(parameters)
}
```
The normal C-standard order of operators is respected. When writing an expression, be sure that you either order the operators correctly, or use parenthesis to clarify which portions of an expression should be run first.
Escaping characters
--
Sometimes you'll have parameters that have spaces, slashes, pluses, ampersands or some other character
that this library interprets as something special. For example, the following expression will not
act as one might expect:
"response-time < 100"
As written, the library will parse it as "[response] minus [time] is less than 100". In reality,
"response-time" is meant to be one variable that just happens to have a dash in it.
There are two ways to work around this. First, you can escape the entire parameter name:
"[response-time] < 100"
Or you can use backslashes to escape only the minus sign.
"response\\-time < 100"
Backslashes can be used anywhere in an expression to escape the very next character. Square bracketed parameter names can be used instead of plain parameter names at any time.
Functions
--
You may have cases where you want to call a function on a parameter during execution of the expression. Perhaps you want to aggregate some set of data, but don't know the exact aggregation you want to use until you're writing the expression itself. Or maybe you have a mathematical operation you want to perform, for which there is no operator; like `log` or `tan` or `sqrt`. For cases like this, you can provide a map of functions to `NewEvaluableExpressionWithFunctions`, which will then be able to use them during execution. For instance;
```go
functions := map[string]govaluate.ExpressionFunction {
"strlen": func(args ...interface{}) (interface{}, error) {
length := len(args[0].(string))
return (float64)(length), nil
},
}
expString := "strlen('someReallyLongInputString') <= 16"
expression, _ := govaluate.NewEvaluableExpressionWithFunctions(expString, functions)
result, _ := expression.Evaluate(nil)
// result is now "false", the boolean value
```
Functions can accept any number of arguments, correctly handles nested functions, and arguments can be of any type (even if none of this library's operators support evaluation of that type). For instance, each of these usages of functions in an expression are valid (assuming that the appropriate functions and parameters are given):
```go
"sqrt(x1 ** y1, x2 ** y2)"
"max(someValue, abs(anotherValue), 10 * lastValue)"
```
Functions cannot be passed as parameters, they must be known at the time when the expression is parsed, and are unchangeable after parsing.
What operators and types does this support?
--
* Modifiers: `+` `-` `/` `*` `&` `|` `^` `**` `%` `>>` `<<`
* Comparators: `>` `>=` `<` `<=` `==` `!=` `=~` `!~`
* Logical ops: `||` `&&`
* Numeric constants, as 64-bit floating point (`12345.678`)
* String constants (single quotes: `'foobar'`)
* Date constants (single quotes, using any permutation of RFC3339, ISO8601, ruby date, or unix date; date parsing is automatically tried with any string constant)
* Boolean constants: `true` `false`
* Parenthesis to control order of evaluation `(` `)`
* Arrays (anything separated by `,` within parenthesis: `(1, 2, 'foo')`)
* Prefixes: `!` `-` `~`
* Ternary conditional: `?` `:`
* Null coalescence: `??`
See [MANUAL.md](https://github.com/Knetic/govaluate/blob/master/MANUAL.md) for exacting details on what types each operator supports.
Types
--
Some operators don't make sense when used with some types. For instance, what does it mean to get the modulo of a string? What happens if you check to see if two numbers are logically AND'ed together?
Everyone has a different intuition about the answers to these questions. To prevent confusion, this library will _refuse to operate_ upon types for which there is not an unambiguous meaning for the operation. See [MANUAL.md](https://github.com/Knetic/govaluate/blob/master/MANUAL.md) for details about what operators are valid for which types.
Benchmarks
--
If you're concerned about the overhead of this library, a good range of benchmarks are built into this repo. You can run them with `go test -bench=.`. The library is built with an eye towards being quick, but has not been aggressively profiled and optimized. For most applications, though, it is completely fine.
For a very rough idea of performance, here are the results output from a benchmark run on a 3rd-gen Macbook Pro (Linux Mint 17.1).
```
BenchmarkSingleParse-12 1000000 1382 ns/op
BenchmarkSimpleParse-12 200000 10771 ns/op
BenchmarkFullParse-12 30000 49383 ns/op
BenchmarkEvaluationSingle-12 50000000 30.1 ns/op
BenchmarkEvaluationNumericLiteral-12 10000000 119 ns/op
BenchmarkEvaluationLiteralModifiers-12 10000000 236 ns/op
BenchmarkEvaluationParameters-12 5000000 260 ns/op
BenchmarkEvaluationParametersModifiers-12 3000000 547 ns/op
BenchmarkComplexExpression-12 2000000 963 ns/op
BenchmarkRegexExpression-12 100000 20357 ns/op
BenchmarkConstantRegexExpression-12 1000000 1392 ns/op
ok
```
API Breaks
--
While this library has very few cases which will ever result in an API break, it can (and [has](https://github.com/Knetic/govaluate/releases/tag/2.0.0)) happened. If you are using this in production, vendor the commit you've tested against, or use gopkg.in to redirect your import (e.g., `import "gopkg.in/Knetic/govaluate.v2"`). Master branch (while infrequent) _may_ at some point contain API breaking changes, and the author will have no way to communicate these to downstreams, other than creating a new major release.
Releases will explicitly state when an API break happens, and if they do not specify an API break it should be safe to upgrade.
License
--
This project is licensed under the MIT general use license. You're free to integrate, fork, and play with this code as you feel fit without consulting the author, as long as you provide proper credit to the author in your works.

@ -1,72 +0,0 @@
package govaluate
/*
Represents all valid types of tokens that a token can be.
*/
type TokenKind int
const (
UNKNOWN TokenKind = iota
PREFIX
NUMERIC
BOOLEAN
STRING
PATTERN
TIME
VARIABLE
FUNCTION
SEPARATOR
COMPARATOR
LOGICALOP
MODIFIER
CLAUSE
CLAUSE_CLOSE
TERNARY
)
/*
GetTokenKindString returns a string that describes the given TokenKind.
e.g., when passed the NUMERIC TokenKind, this returns the string "NUMERIC".
*/
func (kind TokenKind) String() string {
switch kind {
case PREFIX:
return "PREFIX"
case NUMERIC:
return "NUMERIC"
case BOOLEAN:
return "BOOLEAN"
case STRING:
return "STRING"
case PATTERN:
return "PATTERN"
case TIME:
return "TIME"
case VARIABLE:
return "VARIABLE"
case FUNCTION:
return "FUNCTION"
case SEPARATOR:
return "SEPARATOR"
case COMPARATOR:
return "COMPARATOR"
case LOGICALOP:
return "LOGICALOP"
case MODIFIER:
return "MODIFIER"
case CLAUSE:
return "CLAUSE"
case CLAUSE_CLOSE:
return "CLAUSE_CLOSE"
case TERNARY:
return "TERNARY"
}
return "UNKNOWN"
}

@ -1,359 +0,0 @@
package govaluate
import (
"errors"
"fmt"
"math"
"regexp"
"reflect"
)
const (
logicalErrorFormat string = "Value '%v' cannot be used with the logical operator '%v', it is not a bool"
modifierErrorFormat string = "Value '%v' cannot be used with the modifier '%v', it is not a number"
comparatorErrorFormat string = "Value '%v' cannot be used with the comparator '%v', it is not a number"
ternaryErrorFormat string = "Value '%v' cannot be used with the ternary operator '%v', it is not a bool"
prefixErrorFormat string = "Value '%v' cannot be used with the prefix '%v'"
)
type evaluationOperator func(left interface{}, right interface{}, parameters Parameters) (interface{}, error)
type stageTypeCheck func(value interface{}) bool
type stageCombinedTypeCheck func(left interface{}, right interface{}) bool
type evaluationStage struct {
symbol OperatorSymbol
leftStage, rightStage *evaluationStage
// the operation that will be used to evaluate this stage (such as adding [left] to [right] and return the result)
operator evaluationOperator
// ensures that both left and right values are appropriate for this stage. Returns an error if they aren't operable.
leftTypeCheck stageTypeCheck
rightTypeCheck stageTypeCheck
// if specified, will override whatever is used in "leftTypeCheck" and "rightTypeCheck".
// primarily used for specific operators that don't care which side a given type is on, but still requires one side to be of a given type
// (like string concat)
typeCheck stageCombinedTypeCheck
// regardless of which type check is used, this string format will be used as the error message for type errors
typeErrorFormat string
}
var (
_true = interface{}(true)
_false = interface{}(false)
)
func (this *evaluationStage) swapWith(other *evaluationStage) {
temp := *other
other.setToNonStage(*this)
this.setToNonStage(temp)
}
func (this *evaluationStage) setToNonStage(other evaluationStage) {
this.symbol = other.symbol
this.operator = other.operator
this.leftTypeCheck = other.leftTypeCheck
this.rightTypeCheck = other.rightTypeCheck
this.typeCheck = other.typeCheck
this.typeErrorFormat = other.typeErrorFormat
}
func (this *evaluationStage) isShortCircuitable() bool {
switch this.symbol {
case AND:
fallthrough
case OR:
fallthrough
case TERNARY_TRUE:
fallthrough
case TERNARY_FALSE:
fallthrough
case COALESCE:
return true
}
return false
}
func noopStageRight(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return right, nil
}
func addStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
// string concat if either are strings
if isString(left) || isString(right) {
return fmt.Sprintf("%v%v", left, right), nil
}
return left.(float64) + right.(float64), nil
}
func subtractStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return left.(float64) - right.(float64), nil
}
func multiplyStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return left.(float64) * right.(float64), nil
}
func divideStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return left.(float64) / right.(float64), nil
}
func exponentStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return math.Pow(left.(float64), right.(float64)), nil
}
func modulusStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return math.Mod(left.(float64), right.(float64)), nil
}
func gteStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
if isString(left) && isString(right) {
return boolIface(left.(string) >= right.(string)), nil
}
return boolIface(left.(float64) >= right.(float64)), nil
}
func gtStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
if isString(left) && isString(right) {
return boolIface(left.(string) > right.(string)), nil
}
return boolIface(left.(float64) > right.(float64)), nil
}
func lteStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
if isString(left) && isString(right) {
return boolIface(left.(string) <= right.(string)), nil
}
return boolIface(left.(float64) <= right.(float64)), nil
}
func ltStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
if isString(left) && isString(right) {
return boolIface(left.(string) < right.(string)), nil
}
return boolIface(left.(float64) < right.(float64)), nil
}
func equalStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return boolIface(reflect.DeepEqual(left, right)), nil
}
func notEqualStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return boolIface(!reflect.DeepEqual(left, right)), nil
}
func andStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return boolIface(left.(bool) && right.(bool)), nil
}
func orStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return boolIface(left.(bool) || right.(bool)), nil
}
func negateStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return -right.(float64), nil
}
func invertStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return boolIface(!right.(bool)), nil
}
func bitwiseNotStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return float64(^int64(right.(float64))), nil
}
func ternaryIfStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
if left.(bool) {
return right, nil
}
return nil, nil
}
func ternaryElseStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
if left != nil {
return left, nil
}
return right, nil
}
func regexStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
var pattern *regexp.Regexp
var err error
switch right.(type) {
case string:
pattern, err = regexp.Compile(right.(string))
if err != nil {
return nil, errors.New(fmt.Sprintf("Unable to compile regexp pattern '%v': %v", right, err))
}
case *regexp.Regexp:
pattern = right.(*regexp.Regexp)
}
return pattern.Match([]byte(left.(string))), nil
}
func notRegexStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
ret, err := regexStage(left, right, parameters)
if err != nil {
return nil, err
}
return !(ret.(bool)), nil
}
func bitwiseOrStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return float64(int64(left.(float64)) | int64(right.(float64))), nil
}
func bitwiseAndStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return float64(int64(left.(float64)) & int64(right.(float64))), nil
}
func bitwiseXORStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return float64(int64(left.(float64)) ^ int64(right.(float64))), nil
}
func leftShiftStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return float64(uint64(left.(float64)) << uint64(right.(float64))), nil
}
func rightShiftStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return float64(uint64(left.(float64)) >> uint64(right.(float64))), nil
}
func makeParameterStage(parameterName string) evaluationOperator {
return func(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
value, err := parameters.Get(parameterName)
if err != nil {
return nil, err
}
return value, nil
}
}
func makeLiteralStage(literal interface{}) evaluationOperator {
return func(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
return literal, nil
}
}
func makeFunctionStage(function ExpressionFunction) evaluationOperator {
return func(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
if right == nil {
return function()
}
switch right.(type) {
case []interface{}:
return function(right.([]interface{})...)
default:
return function(right)
}
}
}
func separatorStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
var ret []interface{}
switch left.(type) {
case []interface{}:
ret = append(left.([]interface{}), right)
default:
ret = []interface{}{left, right}
}
return ret, nil
}
func inStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) {
for _, value := range right.([]interface{}) {
if left == value {
return true, nil
}
}
return false, nil
}
//
func isString(value interface{}) bool {
switch value.(type) {
case string:
return true
}
return false
}
func isRegexOrString(value interface{}) bool {
switch value.(type) {
case string:
return true
case *regexp.Regexp:
return true
}
return false
}
func isBool(value interface{}) bool {
switch value.(type) {
case bool:
return true
}
return false
}
func isFloat64(value interface{}) bool {
switch value.(type) {
case float64:
return true
}
return false
}
/*
Addition usually means between numbers, but can also mean string concat.
String concat needs one (or both) of the sides to be a string.
*/
func additionTypeCheck(left interface{}, right interface{}) bool {
if isFloat64(left) && isFloat64(right) {
return true
}
if !isString(left) && !isString(right) {
return false
}
return true
}
/*
Comparison can either be between numbers, or lexicographic between two strings,
but never between the two.
*/
func comparatorTypeCheck(left interface{}, right interface{}) bool {
if isFloat64(left) && isFloat64(right) {
return true
}
if isString(left) && isString(right) {
return true
}
return false
}
func isArray(value interface{}) bool {
switch value.(type) {
case []interface{}:
return true
}
return false
}
/*
Converting a boolean to an interface{} requires an allocation.
We can use interned bools to avoid this cost.
*/
func boolIface(b bool) interface{} {
if b {
return _true
}
return _false
}

@ -1,8 +0,0 @@
package govaluate
/*
Represents a function that can be called from within an expression.
This method must return an error if, for any reason, it is unable to produce exactly one unambiguous result.
An error returned will halt execution of the expression.
*/
type ExpressionFunction func(arguments ...interface{}) (interface{}, error)

@ -1,46 +0,0 @@
package govaluate
import (
"bytes"
)
/*
Holds a series of "transactions" which represent each token as it is output by an outputter (such as ToSQLQuery()).
Some outputs (such as SQL) require a function call or non-c-like syntax to represent an expression.
To accomplish this, this struct keeps track of each translated token as it is output, and can return and rollback those transactions.
*/
type expressionOutputStream struct {
transactions []string
}
func (this *expressionOutputStream) add(transaction string) {
this.transactions = append(this.transactions, transaction)
}
func (this *expressionOutputStream) rollback() string {
index := len(this.transactions) - 1
ret := this.transactions[index]
this.transactions = this.transactions[:index]
return ret
}
func (this *expressionOutputStream) createString(delimiter string) string {
var retBuffer bytes.Buffer
var transaction string
penultimate := len(this.transactions) - 1
for i := 0; i < penultimate; i++ {
transaction = this.transactions[i]
retBuffer.WriteString(transaction)
retBuffer.WriteString(delimiter)
}
retBuffer.WriteString(this.transactions[penultimate])
return retBuffer.String()
}

@ -1,350 +0,0 @@
package govaluate
import (
"errors"
"fmt"
)
type lexerState struct {
isEOF bool
isNullable bool
kind TokenKind
validNextKinds []TokenKind
}
// lexer states.
// Constant for all purposes except compiler.
var validLexerStates = []lexerState{
lexerState{
kind: UNKNOWN,
isEOF: false,
isNullable: true,
validNextKinds: []TokenKind{
PREFIX,
NUMERIC,
BOOLEAN,
VARIABLE,
PATTERN,
FUNCTION,
STRING,
TIME,
CLAUSE,
},
},
lexerState{
kind: CLAUSE,
isEOF: false,
isNullable: true,
validNextKinds: []TokenKind{
PREFIX,
NUMERIC,
BOOLEAN,
VARIABLE,
PATTERN,
FUNCTION,
STRING,
TIME,
CLAUSE,
CLAUSE_CLOSE,
},
},
lexerState{
kind: CLAUSE_CLOSE,
isEOF: true,
isNullable: true,
validNextKinds: []TokenKind{
COMPARATOR,
MODIFIER,
NUMERIC,
BOOLEAN,
VARIABLE,
STRING,
PATTERN,
TIME,
CLAUSE,
CLAUSE_CLOSE,
LOGICALOP,
TERNARY,
SEPARATOR,
},
},
lexerState{
kind: NUMERIC,
isEOF: true,
isNullable: false,
validNextKinds: []TokenKind{
MODIFIER,
COMPARATOR,
LOGICALOP,
CLAUSE_CLOSE,
TERNARY,
SEPARATOR,
},
},
lexerState{
kind: BOOLEAN,
isEOF: true,
isNullable: false,
validNextKinds: []TokenKind{
MODIFIER,
COMPARATOR,
LOGICALOP,
CLAUSE_CLOSE,
TERNARY,
SEPARATOR,
},
},
lexerState{
kind: STRING,
isEOF: true,
isNullable: false,
validNextKinds: []TokenKind{
MODIFIER,
COMPARATOR,
LOGICALOP,
CLAUSE_CLOSE,
TERNARY,
SEPARATOR,
},
},
lexerState{
kind: TIME,
isEOF: true,
isNullable: false,
validNextKinds: []TokenKind{
MODIFIER,
COMPARATOR,
LOGICALOP,
CLAUSE_CLOSE,
SEPARATOR,
},
},
lexerState{
kind: PATTERN,
isEOF: true,
isNullable: false,
validNextKinds: []TokenKind{
MODIFIER,
COMPARATOR,
LOGICALOP,
CLAUSE_CLOSE,
SEPARATOR,
},
},
lexerState{
kind: VARIABLE,
isEOF: true,
isNullable: false,
validNextKinds: []TokenKind{
MODIFIER,
COMPARATOR,
LOGICALOP,
CLAUSE_CLOSE,
TERNARY,
SEPARATOR,
},
},
lexerState{
kind: MODIFIER,
isEOF: false,
isNullable: false,
validNextKinds: []TokenKind{
PREFIX,
NUMERIC,
VARIABLE,
FUNCTION,
STRING,
BOOLEAN,
CLAUSE,
CLAUSE_CLOSE,
},
},
lexerState{
kind: COMPARATOR,
isEOF: false,
isNullable: false,
validNextKinds: []TokenKind{
PREFIX,
NUMERIC,
BOOLEAN,
VARIABLE,
FUNCTION,
STRING,
TIME,
CLAUSE,
CLAUSE_CLOSE,
PATTERN,
},
},
lexerState{
kind: LOGICALOP,
isEOF: false,
isNullable: false,
validNextKinds: []TokenKind{
PREFIX,
NUMERIC,
BOOLEAN,
VARIABLE,
FUNCTION,
STRING,
TIME,
CLAUSE,
CLAUSE_CLOSE,
},
},
lexerState{
kind: PREFIX,
isEOF: false,
isNullable: false,
validNextKinds: []TokenKind{
NUMERIC,
BOOLEAN,
VARIABLE,
FUNCTION,
CLAUSE,
CLAUSE_CLOSE,
},
},
lexerState{
kind: TERNARY,
isEOF: false,
isNullable: false,
validNextKinds: []TokenKind{
PREFIX,
NUMERIC,
BOOLEAN,
STRING,
TIME,
VARIABLE,
FUNCTION,
CLAUSE,
SEPARATOR,
},
},
lexerState{
kind: FUNCTION,
isEOF: false,
isNullable: false,
validNextKinds: []TokenKind{
CLAUSE,
},
},
lexerState{
kind: SEPARATOR,
isEOF: false,
isNullable: true,
validNextKinds: []TokenKind{
PREFIX,
NUMERIC,
BOOLEAN,
STRING,
TIME,
VARIABLE,
FUNCTION,
CLAUSE,
},
},
}
func (this lexerState) canTransitionTo(kind TokenKind) bool {
for _, validKind := range this.validNextKinds {
if validKind == kind {
return true
}
}
return false
}
func checkExpressionSyntax(tokens []ExpressionToken) error {
var state lexerState
var lastToken ExpressionToken
var err error
state = validLexerStates[0]
for _, token := range tokens {
if !state.canTransitionTo(token.Kind) {
// call out a specific error for tokens looking like they want to be functions.
if lastToken.Kind == VARIABLE && token.Kind == CLAUSE {
return errors.New("Undefined function " + lastToken.Value.(string))
}
firstStateName := fmt.Sprintf("%s [%v]", state.kind.String(), lastToken.Value)
nextStateName := fmt.Sprintf("%s [%v]", token.Kind.String(), token.Value)
return errors.New("Cannot transition token types from " + firstStateName + " to " + nextStateName)
}
state, err = getLexerStateForToken(token.Kind)
if err != nil {
return err
}
if !state.isNullable && token.Value == nil {
errorMsg := fmt.Sprintf("Token kind '%v' cannot have a nil value", token.Kind.String())
return errors.New(errorMsg)
}
lastToken = token
}
if !state.isEOF {
return errors.New("Unexpected end of expression")
}
return nil
}
func getLexerStateForToken(kind TokenKind) (lexerState, error) {
for _, possibleState := range validLexerStates {
if possibleState.kind == kind {
return possibleState, nil
}
}
errorMsg := fmt.Sprintf("No lexer state found for token kind '%v'\n", kind.String())
return validLexerStates[0], errors.New(errorMsg)
}

@ -1,39 +0,0 @@
package govaluate
type lexerStream struct {
source []rune
position int
length int
}
func newLexerStream(source string) *lexerStream {
var ret *lexerStream
var runes []rune
for _, character := range source {
runes = append(runes, character)
}
ret = new(lexerStream)
ret.source = runes
ret.length = len(runes)
return ret
}
func (this *lexerStream) readCharacter() rune {
var character rune
character = this.source[this.position]
this.position += 1
return character
}
func (this *lexerStream) rewind(amount int) {
this.position -= amount
}
func (this lexerStream) canRead() bool {
return this.position < this.length
}

@ -1,32 +0,0 @@
package govaluate
import (
"errors"
)
/*
Parameters is a collection of named parameters that can be used by an EvaluableExpression to retrieve parameters
when an expression tries to use them.
*/
type Parameters interface {
/*
Get gets the parameter of the given name, or an error if the parameter is unavailable.
Failure to find the given parameter should be indicated by returning an error.
*/
Get(name string) (interface{}, error)
}
type MapParameters map[string]interface{}
func (p MapParameters) Get(name string) (interface{}, error) {
value, found := p[name]
if !found {
errorMessage := "No parameter '" + name + "' found."
return nil, errors.New(errorMessage)
}
return value, nil
}

@ -1,450 +0,0 @@
package govaluate
import (
"bytes"
"errors"
"fmt"
"regexp"
"strconv"
"time"
"unicode"
)
func parseTokens(expression string, functions map[string]ExpressionFunction) ([]ExpressionToken, error) {
var ret []ExpressionToken
var token ExpressionToken
var stream *lexerStream
var state lexerState
var err error
var found bool
stream = newLexerStream(expression)
state = validLexerStates[0]
for stream.canRead() {
token, err, found = readToken(stream, state, functions)
if err != nil {
return ret, err
}
if !found {
break
}
state, err = getLexerStateForToken(token.Kind)
if err != nil {
return ret, err
}
// append this valid token
ret = append(ret, token)
}
err = checkBalance(ret)
if err != nil {
return nil, err
}
return ret, nil
}
func readToken(stream *lexerStream, state lexerState, functions map[string]ExpressionFunction) (ExpressionToken, error, bool) {
var function ExpressionFunction
var ret ExpressionToken
var tokenValue interface{}
var tokenTime time.Time
var tokenString string
var kind TokenKind
var character rune
var found bool
var completed bool
var err error
// numeric is 0-9, or .
// string starts with '
// variable is alphanumeric, always starts with a letter
// bracket always means variable
// symbols are anything non-alphanumeric
// all others read into a buffer until they reach the end of the stream
for stream.canRead() {
character = stream.readCharacter()
if unicode.IsSpace(character) {
continue
}
kind = UNKNOWN
// numeric constant
if isNumeric(character) {
tokenString = readTokenUntilFalse(stream, isNumeric)
tokenValue, err = strconv.ParseFloat(tokenString, 64)
if err != nil {
errorMsg := fmt.Sprintf("Unable to parse numeric value '%v' to float64\n", tokenString)
return ExpressionToken{}, errors.New(errorMsg), false
}
kind = NUMERIC
break
}
// comma, separator
if character == ',' {
tokenValue = ","
kind = SEPARATOR
break
}
// escaped variable
if character == '[' {
tokenValue, completed = readUntilFalse(stream, true, false, true, isNotClosingBracket)
kind = VARIABLE
if !completed {
return ExpressionToken{}, errors.New("Unclosed parameter bracket"), false
}
// above method normally rewinds us to the closing bracket, which we want to skip.
stream.rewind(-1)
break
}
// regular variable - or function?
if unicode.IsLetter(character) {
tokenString = readTokenUntilFalse(stream, isVariableName)
tokenValue = tokenString
kind = VARIABLE
// boolean?
if tokenValue == "true" {
kind = BOOLEAN
tokenValue = true
} else {
if tokenValue == "false" {
kind = BOOLEAN
tokenValue = false
}
}
// textual operator?
if tokenValue == "in" || tokenValue == "IN" {
// force lower case for consistency
tokenValue = "in"
kind = COMPARATOR
}
// function?
function, found = functions[tokenString]
if found {
kind = FUNCTION
tokenValue = function
}
break
}
if !isNotQuote(character) {
tokenValue, completed = readUntilFalse(stream, true, false, true, isNotQuote)
if !completed {
return ExpressionToken{}, errors.New("Unclosed string literal"), false
}
// advance the stream one position, since reading until false assumes the terminator is a real token
stream.rewind(-1)
// check to see if this can be parsed as a time.
tokenTime, found = tryParseTime(tokenValue.(string))
if found {
kind = TIME
tokenValue = tokenTime
} else {
kind = STRING
}
break
}
if character == '(' {
tokenValue = character
kind = CLAUSE
break
}
if character == ')' {
tokenValue = character
kind = CLAUSE_CLOSE
break
}
// must be a known symbol
tokenString = readTokenUntilFalse(stream, isNotAlphanumeric)
tokenValue = tokenString
// quick hack for the case where "-" can mean "prefixed negation" or "minus", which are used
// very differently.
if state.canTransitionTo(PREFIX) {
_, found = prefixSymbols[tokenString]
if found {
kind = PREFIX
break
}
}
_, found = modifierSymbols[tokenString]
if found {
kind = MODIFIER
break
}
_, found = logicalSymbols[tokenString]
if found {
kind = LOGICALOP
break
}
_, found = comparatorSymbols[tokenString]
if found {
kind = COMPARATOR
break
}
_, found = ternarySymbols[tokenString]
if found {
kind = TERNARY
break
}
errorMessage := fmt.Sprintf("Invalid token: '%s'", tokenString)
return ret, errors.New(errorMessage), false
}
ret.Kind = kind
ret.Value = tokenValue
return ret, nil, (kind != UNKNOWN)
}
func readTokenUntilFalse(stream *lexerStream, condition func(rune) bool) string {
var ret string
stream.rewind(1)
ret, _ = readUntilFalse(stream, false, true, true, condition)
return ret
}
/*
Returns the string that was read until the given [condition] was false, or whitespace was broken.
Returns false if the stream ended before whitespace was broken or condition was met.
*/
func readUntilFalse(stream *lexerStream, includeWhitespace bool, breakWhitespace bool, allowEscaping bool, condition func(rune) bool) (string, bool) {
var tokenBuffer bytes.Buffer
var character rune
var conditioned bool
conditioned = false
for stream.canRead() {
character = stream.readCharacter()
// Use backslashes to escape anything
if allowEscaping && character == '\\' {
character = stream.readCharacter()
tokenBuffer.WriteString(string(character))
continue
}
if unicode.IsSpace(character) {
if breakWhitespace && tokenBuffer.Len() > 0 {
conditioned = true
break
}
if !includeWhitespace {
continue
}
}
if condition(character) {
tokenBuffer.WriteString(string(character))
} else {
conditioned = true
stream.rewind(1)
break
}
}
return tokenBuffer.String(), conditioned
}
/*
Checks to see if any optimizations can be performed on the given [tokens], which form a complete, valid expression.
The returns slice will represent the optimized (or unmodified) list of tokens to use.
*/
func optimizeTokens(tokens []ExpressionToken) ([]ExpressionToken, error) {
var token ExpressionToken
var symbol OperatorSymbol
var err error
var index int
for index, token = range tokens {
// if we find a regex operator, and the right-hand value is a constant, precompile and replace with a pattern.
if token.Kind != COMPARATOR {
continue
}
symbol = comparatorSymbols[token.Value.(string)]
if symbol != REQ && symbol != NREQ {
continue
}
index++
token = tokens[index]
if token.Kind == STRING {
token.Kind = PATTERN
token.Value, err = regexp.Compile(token.Value.(string))
if err != nil {
return tokens, err
}
tokens[index] = token
}
}
return tokens, nil
}
/*
Checks the balance of tokens which have multiple parts, such as parenthesis.
*/
func checkBalance(tokens []ExpressionToken) error {
var stream *tokenStream
var token ExpressionToken
var parens int
stream = newTokenStream(tokens)
for stream.hasNext() {
token = stream.next()
if token.Kind == CLAUSE {
parens++
continue
}
if token.Kind == CLAUSE_CLOSE {
parens--
continue
}
}
if parens != 0 {
return errors.New("Unbalanced parenthesis")
}
return nil
}
func isNumeric(character rune) bool {
return unicode.IsDigit(character) || character == '.'
}
func isNotQuote(character rune) bool {
return character != '\'' && character != '"'
}
func isNotAlphanumeric(character rune) bool {
return !(unicode.IsDigit(character) ||
unicode.IsLetter(character) ||
character == '(' ||
character == ')' ||
!isNotQuote(character))
}
func isVariableName(character rune) bool {
return unicode.IsLetter(character) ||
unicode.IsDigit(character) ||
character == '_'
}
func isNotClosingBracket(character rune) bool {
return character != ']'
}
/*
Attempts to parse the [candidate] as a Time.
Tries a series of standardized date formats, returns the Time if one applies,
otherwise returns false through the second return.
*/
func tryParseTime(candidate string) (time.Time, bool) {
var ret time.Time
var found bool
timeFormats := [...]string{
time.ANSIC,
time.UnixDate,
time.RubyDate,
time.Kitchen,
time.RFC3339,
time.RFC3339Nano,
"2006-01-02", // RFC 3339
"2006-01-02 15:04", // RFC 3339 with minutes
"2006-01-02 15:04:05", // RFC 3339 with seconds
"2006-01-02 15:04:05-07:00", // RFC 3339 with seconds and timezone
"2006-01-02T15Z0700", // ISO8601 with hour
"2006-01-02T15:04Z0700", // ISO8601 with minutes
"2006-01-02T15:04:05Z0700", // ISO8601 with seconds
"2006-01-02T15:04:05.999999999Z0700", // ISO8601 with nanoseconds
}
for _, format := range timeFormats {
ret, found = tryParseExactTime(candidate, format)
if found {
return ret, true
}
}
return time.Now(), false
}
func tryParseExactTime(candidate string, format string) (time.Time, bool) {
var ret time.Time
var err error
ret, err = time.ParseInLocation(format, candidate, time.Local)
if err != nil {
return time.Now(), false
}
return ret, true
}

@ -1,71 +0,0 @@
package govaluate
// sanitizedParameters is a wrapper for Parameters that does sanitization as
// parameters are accessed.
type sanitizedParameters struct {
orig Parameters
}
func (p sanitizedParameters) Get(key string) (interface{}, error) {
value, err := p.orig.Get(key)
if err != nil {
return nil, err
}
// should be converted to fixed point?
if isFixedPoint(value) {
return castFixedPoint(value), nil
}
return value, nil
}
func isFixedPoint(value interface{}) bool {
switch value.(type) {
case uint8:
return true
case uint16:
return true
case uint32:
return true
case uint64:
return true
case int8:
return true
case int16:
return true
case int32:
return true
case int64:
return true
case int:
return true
}
return false
}
func castFixedPoint(value interface{}) float64 {
switch value.(type) {
case uint8:
return float64(value.(uint8))
case uint16:
return float64(value.(uint16))
case uint32:
return float64(value.(uint32))
case uint64:
return float64(value.(uint64))
case int8:
return float64(value.(int8))
case int16:
return float64(value.(int16))
case int32:
return float64(value.(int32))
case int64:
return float64(value.(int64))
case int:
return float64(value.(int))
}
return 0.0
}

@ -1,675 +0,0 @@
package govaluate
import (
"errors"
"time"
"fmt"
)
var stageSymbolMap = map[OperatorSymbol]evaluationOperator{
EQ: equalStage,
NEQ: notEqualStage,
GT: gtStage,
LT: ltStage,
GTE: gteStage,
LTE: lteStage,
REQ: regexStage,
NREQ: notRegexStage,
AND: andStage,
OR: orStage,
IN: inStage,
BITWISE_OR: bitwiseOrStage,
BITWISE_AND: bitwiseAndStage,
BITWISE_XOR: bitwiseXORStage,
BITWISE_LSHIFT: leftShiftStage,
BITWISE_RSHIFT: rightShiftStage,
PLUS: addStage,
MINUS: subtractStage,
MULTIPLY: multiplyStage,
DIVIDE: divideStage,
MODULUS: modulusStage,
EXPONENT: exponentStage,
NEGATE: negateStage,
INVERT: invertStage,
BITWISE_NOT: bitwiseNotStage,
TERNARY_TRUE: ternaryIfStage,
TERNARY_FALSE: ternaryElseStage,
COALESCE: ternaryElseStage,
SEPARATE: separatorStage,
}
/*
A "precedent" is a function which will recursively parse new evaluateionStages from a given stream of tokens.
It's called a `precedent` because it is expected to handle exactly what precedence of operator,
and defer to other `precedent`s for other operators.
*/
type precedent func(stream *tokenStream) (*evaluationStage, error)
/*
A convenience function for specifying the behavior of a `precedent`.
Most `precedent` functions can be described by the same function, just with different type checks, symbols, and error formats.
This struct is passed to `makePrecedentFromPlanner` to create a `precedent` function.
*/
type precedencePlanner struct {
validSymbols map[string]OperatorSymbol
validKinds []TokenKind
typeErrorFormat string
next precedent
nextRight precedent
}
var planPrefix precedent
var planExponential precedent
var planMultiplicative precedent
var planAdditive precedent
var planBitwise precedent
var planShift precedent
var planComparator precedent
var planLogicalAnd precedent
var planLogicalOr precedent
var planTernary precedent
var planSeparator precedent
func init() {
// all these stages can use the same code (in `planPrecedenceLevel`) to execute,
// they simply need different type checks, symbols, and recursive precedents.
// While not all precedent phases are listed here, most can be represented this way.
planPrefix = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: prefixSymbols,
validKinds: []TokenKind{PREFIX},
typeErrorFormat: prefixErrorFormat,
nextRight: planFunction,
})
planExponential = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: exponentialSymbolsS,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: modifierErrorFormat,
next: planFunction,
})
planMultiplicative = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: multiplicativeSymbols,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: modifierErrorFormat,
next: planExponential,
})
planAdditive = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: additiveSymbols,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: modifierErrorFormat,
next: planMultiplicative,
})
planShift = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: bitwiseShiftSymbols,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: modifierErrorFormat,
next: planAdditive,
})
planBitwise = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: bitwiseSymbols,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: modifierErrorFormat,
next: planShift,
})
planComparator = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: comparatorSymbols,
validKinds: []TokenKind{COMPARATOR},
typeErrorFormat: comparatorErrorFormat,
next: planBitwise,
})
planLogicalAnd = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: map[string]OperatorSymbol{"&&": AND},
validKinds: []TokenKind{LOGICALOP},
typeErrorFormat: logicalErrorFormat,
next: planComparator,
})
planLogicalOr = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: map[string]OperatorSymbol{"||": OR},
validKinds: []TokenKind{LOGICALOP},
typeErrorFormat: logicalErrorFormat,
next: planLogicalAnd,
})
planTernary = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: ternarySymbols,
validKinds: []TokenKind{TERNARY},
typeErrorFormat: ternaryErrorFormat,
next: planLogicalOr,
})
planSeparator = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: separatorSymbols,
validKinds: []TokenKind{SEPARATOR},
next: planTernary,
})
}
/*
Given a planner, creates a function which will evaluate a specific precedence level of operators,
and link it to other `precedent`s which recurse to parse other precedence levels.
*/
func makePrecedentFromPlanner(planner *precedencePlanner) precedent {
var generated precedent
var nextRight precedent
generated = func(stream *tokenStream) (*evaluationStage, error) {
return planPrecedenceLevel(
stream,
planner.typeErrorFormat,
planner.validSymbols,
planner.validKinds,
nextRight,
planner.next,
)
}
if planner.nextRight != nil {
nextRight = planner.nextRight
} else {
nextRight = generated
}
return generated
}
/*
Creates a `evaluationStageList` object which represents an execution plan (or tree)
which is used to completely evaluate a set of tokens at evaluation-time.
The three stages of evaluation can be thought of as parsing strings to tokens, then tokens to a stage list, then evaluation with parameters.
*/
func planStages(tokens []ExpressionToken) (*evaluationStage, error) {
stream := newTokenStream(tokens)
stage, err := planTokens(stream)
if err != nil {
return nil, err
}
// while we're now fully-planned, we now need to re-order same-precedence operators.
// this could probably be avoided with a different planning method
reorderStages(stage)
stage = elideLiterals(stage)
return stage, nil
}
func planTokens(stream *tokenStream) (*evaluationStage, error) {
if !stream.hasNext() {
return nil, nil
}
return planSeparator(stream)
}
/*
The most usual method of parsing an evaluation stage for a given precedence.
Most stages use the same logic
*/
func planPrecedenceLevel(
stream *tokenStream,
typeErrorFormat string,
validSymbols map[string]OperatorSymbol,
validKinds []TokenKind,
rightPrecedent precedent,
leftPrecedent precedent) (*evaluationStage, error) {
var token ExpressionToken
var symbol OperatorSymbol
var leftStage, rightStage *evaluationStage
var checks typeChecks
var err error
var keyFound bool
if leftPrecedent != nil {
leftStage, err = leftPrecedent(stream)
if err != nil {
return nil, err
}
}
for stream.hasNext() {
token = stream.next()
if len(validKinds) > 0 {
keyFound = false
for _, kind := range validKinds {
if kind == token.Kind {
keyFound = true
break
}
}
if !keyFound {
break
}
}
if validSymbols != nil {
if !isString(token.Value) {
break
}
symbol, keyFound = validSymbols[token.Value.(string)]
if !keyFound {
break
}
}
if rightPrecedent != nil {
rightStage, err = rightPrecedent(stream)
if err != nil {
return nil, err
}
}
checks = findTypeChecks(symbol)
return &evaluationStage{
symbol: symbol,
leftStage: leftStage,
rightStage: rightStage,
operator: stageSymbolMap[symbol],
leftTypeCheck: checks.left,
rightTypeCheck: checks.right,
typeCheck: checks.combined,
typeErrorFormat: typeErrorFormat,
}, nil
}
stream.rewind()
return leftStage, nil
}
/*
A special case where functions need to be of higher precedence than values, and need a special wrapped execution stage operator.
*/
func planFunction(stream *tokenStream) (*evaluationStage, error) {
var token ExpressionToken
var rightStage *evaluationStage
var err error
token = stream.next()
if token.Kind != FUNCTION {
stream.rewind()
return planValue(stream)
}
rightStage, err = planValue(stream)
if err != nil {
return nil, err
}
return &evaluationStage{
symbol: FUNCTIONAL,
rightStage: rightStage,
operator: makeFunctionStage(token.Value.(ExpressionFunction)),
typeErrorFormat: "Unable to run function '%v': %v",
}, nil
}
/*
A truly special precedence function, this handles all the "lowest-case" errata of the process, including literals, parmeters,
clauses, and prefixes.
*/
func planValue(stream *tokenStream) (*evaluationStage, error) {
var token ExpressionToken
var symbol OperatorSymbol
var ret *evaluationStage
var operator evaluationOperator
var err error
token = stream.next()
switch token.Kind {
case CLAUSE:
ret, err = planTokens(stream)
if err != nil {
return nil, err
}
// advance past the CLAUSE_CLOSE token. We know that it's a CLAUSE_CLOSE, because at parse-time we check for unbalanced parens.
stream.next()
// the stage we got represents all of the logic contained within the parens
// but for technical reasons, we need to wrap this stage in a "noop" stage which breaks long chains of precedence.
// see github #33.
ret = &evaluationStage {
rightStage: ret,
operator: noopStageRight,
symbol: NOOP,
}
return ret, nil
case CLAUSE_CLOSE:
// when functions have empty params, this will be hit. In this case, we don't have any evaluation stage to do,
// so we just return nil so that the stage planner continues on its way.
stream.rewind()
return nil, nil
case VARIABLE:
operator = makeParameterStage(token.Value.(string))
case NUMERIC:
fallthrough
case STRING:
fallthrough
case PATTERN:
fallthrough
case BOOLEAN:
symbol = LITERAL
operator = makeLiteralStage(token.Value)
case TIME:
symbol = LITERAL
operator = makeLiteralStage(float64(token.Value.(time.Time).Unix()))
case PREFIX:
stream.rewind()
return planPrefix(stream)
}
if operator == nil {
errorMsg := fmt.Sprintf("Unable to plan token kind: '%s', value: '%v'", token.Kind.String(), token.Value)
return nil, errors.New(errorMsg)
}
return &evaluationStage{
symbol: symbol,
operator: operator,
}, nil
}
/*
Convenience function to pass a triplet of typechecks between `findTypeChecks` and `planPrecedenceLevel`.
Each of these members may be nil, which indicates that type does not matter for that value.
*/
type typeChecks struct {
left stageTypeCheck
right stageTypeCheck
combined stageCombinedTypeCheck
}
/*
Maps a given [symbol] to a set of typechecks to be used during runtime.
*/
func findTypeChecks(symbol OperatorSymbol) typeChecks {
switch symbol {
case GT:
fallthrough
case LT:
fallthrough
case GTE:
fallthrough
case LTE:
return typeChecks{
combined: comparatorTypeCheck,
}
case REQ:
fallthrough
case NREQ:
return typeChecks{
left: isString,
right: isRegexOrString,
}
case AND:
fallthrough
case OR:
return typeChecks{
left: isBool,
right: isBool,
}
case IN:
return typeChecks{
right: isArray,
}
case BITWISE_LSHIFT:
fallthrough
case BITWISE_RSHIFT:
fallthrough
case BITWISE_OR:
fallthrough
case BITWISE_AND:
fallthrough
case BITWISE_XOR:
return typeChecks{
left: isFloat64,
right: isFloat64,
}
case PLUS:
return typeChecks{
combined: additionTypeCheck,
}
case MINUS:
fallthrough
case MULTIPLY:
fallthrough
case DIVIDE:
fallthrough
case MODULUS:
fallthrough
case EXPONENT:
return typeChecks{
left: isFloat64,
right: isFloat64,
}
case NEGATE:
return typeChecks{
right: isFloat64,
}
case INVERT:
return typeChecks{
right: isBool,
}
case BITWISE_NOT:
return typeChecks{
right: isFloat64,
}
case TERNARY_TRUE:
return typeChecks{
left: isBool,
}
// unchecked cases
case EQ:
fallthrough
case NEQ:
return typeChecks{}
case TERNARY_FALSE:
fallthrough
case COALESCE:
fallthrough
default:
return typeChecks{}
}
}
/*
During stage planning, stages of equal precedence are parsed such that they'll be evaluated in reverse order.
For commutative operators like "+" or "-", it's no big deal. But for order-specific operators, it ruins the expected result.
*/
func reorderStages(rootStage *evaluationStage) {
// traverse every rightStage until we find multiples in a row of the same precedence.
var identicalPrecedences []*evaluationStage
var currentStage, nextStage *evaluationStage
var precedence, currentPrecedence operatorPrecedence
nextStage = rootStage
precedence = findOperatorPrecedenceForSymbol(rootStage.symbol)
for nextStage != nil {
currentStage = nextStage
nextStage = currentStage.rightStage
// left depth first, since this entire method only looks for precedences down the right side of the tree
if currentStage.leftStage != nil {
reorderStages(currentStage.leftStage)
}
currentPrecedence = findOperatorPrecedenceForSymbol(currentStage.symbol)
if currentPrecedence == precedence {
identicalPrecedences = append(identicalPrecedences, currentStage)
continue
}
// precedence break.
// See how many in a row we had, and reorder if there's more than one.
if len(identicalPrecedences) > 1 {
mirrorStageSubtree(identicalPrecedences)
}
identicalPrecedences = []*evaluationStage{currentStage}
precedence = currentPrecedence
}
if len(identicalPrecedences) > 1 {
mirrorStageSubtree(identicalPrecedences)
}
}
/*
Performs a "mirror" on a subtree of stages.
This mirror functionally inverts the order of execution for all members of the [stages] list.
That list is assumed to be a root-to-leaf (ordered) list of evaluation stages, where each is a right-hand stage of the last.
*/
func mirrorStageSubtree(stages []*evaluationStage) {
var rootStage, inverseStage, carryStage, frontStage *evaluationStage
stagesLength := len(stages)
// reverse all right/left
for _, frontStage = range stages {
carryStage = frontStage.rightStage
frontStage.rightStage = frontStage.leftStage
frontStage.leftStage = carryStage
}
// end left swaps with root right
rootStage = stages[0]
frontStage = stages[stagesLength-1]
carryStage = frontStage.leftStage
frontStage.leftStage = rootStage.rightStage
rootStage.rightStage = carryStage
// for all non-root non-end stages, right is swapped with inverse stage right in list
for i := 0; i < (stagesLength-2)/2+1; i++ {
frontStage = stages[i+1]
inverseStage = stages[stagesLength-i-1]
carryStage = frontStage.rightStage
frontStage.rightStage = inverseStage.rightStage
inverseStage.rightStage = carryStage
}
// swap all other information with inverse stages
for i := 0; i < stagesLength/2; i++ {
frontStage = stages[i]
inverseStage = stages[stagesLength-i-1]
frontStage.swapWith(inverseStage)
}
}
/*
Recurses through all operators in the entire tree, eliding operators where both sides are literals.
*/
func elideLiterals(root *evaluationStage) *evaluationStage {
if root.leftStage != nil {
root.leftStage = elideLiterals(root.leftStage)
}
if root.rightStage != nil {
root.rightStage = elideLiterals(root.rightStage)
}
return elideStage(root)
}
/*
Elides a specific stage, if possible.
Returns the unmodified [root] stage if it cannot or should not be elided.
Otherwise, returns a new stage representing the condensed value from the elided stages.
*/
func elideStage(root *evaluationStage) *evaluationStage {
var leftValue, rightValue, result interface{}
var err error
// right side must be a non-nil value. Left side must be nil or a value.
if root.rightStage == nil ||
root.rightStage.symbol != LITERAL ||
root.leftStage == nil ||
root.leftStage.symbol != LITERAL {
return root
}
// don't elide some operators
switch root.symbol {
case SEPARATE:
fallthrough
case IN:
return root
}
// both sides are values, get their actual values.
// errors should be near-impossible here. If we encounter them, just abort this optimization.
leftValue, err = root.leftStage.operator(nil, nil, nil)
if err != nil {
return root
}
rightValue, err = root.rightStage.operator(nil, nil, nil)
if err != nil {
return root
}
// typcheck, since the grammar checker is a bit loose with which operator symbols go together.
err = typeCheck(root.leftTypeCheck, leftValue, root.symbol, root.typeErrorFormat)
if err != nil {
return root
}
err = typeCheck(root.rightTypeCheck, rightValue, root.symbol, root.typeErrorFormat)
if err != nil {
return root
}
if root.typeCheck != nil && !root.typeCheck(leftValue, rightValue) {
return root
}
// pre-calculate, and return a new stage representing the result.
result, err = root.operator(leftValue, rightValue, nil)
if err != nil {
return root
}
return &evaluationStage {
symbol: LITERAL,
operator: makeLiteralStage(result),
}
}

@ -1,32 +0,0 @@
#!/bin/bash
# Script that runs tests, code coverage, and benchmarks all at once.
# Builds a symlink in /tmp, mostly to avoid messing with GOPATH at the user's shell level.
TEMPORARY_PATH="/tmp/govaluate_test"
SRC_PATH="${TEMPORARY_PATH}/src"
FULL_PATH="${TEMPORARY_PATH}/src/govaluate"
# set up temporary directory
rm -rf "${FULL_PATH}"
mkdir -p "${SRC_PATH}"
ln -s $(pwd) "${FULL_PATH}"
export GOPATH="${TEMPORARY_PATH}"
pushd "${TEMPORARY_PATH}/src/govaluate"
# run the actual tests.
export GOVALUATE_TORTURE_TEST="true"
go test -bench=. -benchmem -coverprofile coverage.out
status=$?
if [ "${status}" != 0 ];
then
exit $status
fi
# coverage
go tool cover -func=coverage.out
popd

@ -1,36 +0,0 @@
package govaluate
type tokenStream struct {
tokens []ExpressionToken
index int
tokenLength int
}
func newTokenStream(tokens []ExpressionToken) *tokenStream {
var ret *tokenStream
ret = new(tokenStream)
ret.tokens = tokens
ret.tokenLength = len(tokens)
return ret
}
func (this *tokenStream) rewind() {
this.index -= 1
}
func (this *tokenStream) next() ExpressionToken {
var token ExpressionToken
token = this.tokens[this.index]
this.index += 1
return token
}
func (this tokenStream) hasNext() bool {
return this.index < this.tokenLength
}

13
vendor/modules.txt vendored

@ -1,13 +1,22 @@
# github.com/BurntSushi/toml v0.3.1
github.com/BurntSushi/toml
# github.com/Knetic/govaluate v3.0.0+incompatible
github.com/Knetic/govaluate
# github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d
github.com/acarl005/stripansi
# github.com/anaskhan96/soup v1.1.1
github.com/anaskhan96/soup
# github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be
github.com/anmitsu/go-shlex
# github.com/antonmedv/expr v1.9.0
github.com/antonmedv/expr
github.com/antonmedv/expr/ast
github.com/antonmedv/expr/checker
github.com/antonmedv/expr/compiler
github.com/antonmedv/expr/conf
github.com/antonmedv/expr/file
github.com/antonmedv/expr/optimizer
github.com/antonmedv/expr/parser
github.com/antonmedv/expr/parser/lexer
github.com/antonmedv/expr/vm
# github.com/creack/pty v1.1.11
github.com/creack/pty
# github.com/fatih/color v1.9.0

Loading…
Cancel
Save