eval.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. // Copyright 2016 José Santos <henrique_1609@me.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jet
  15. import (
  16. "fmt"
  17. "github.com/CloudyKit/fastprinter"
  18. "io"
  19. "reflect"
  20. "runtime"
  21. "strconv"
  22. "sync"
  23. )
  24. var (
  25. funcType = reflect.TypeOf(Func(nil))
  26. stringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
  27. rangerType = reflect.TypeOf((*Ranger)(nil)).Elem()
  28. rendererType = reflect.TypeOf((*Renderer)(nil)).Elem()
  29. safeWriterType = reflect.TypeOf(SafeWriter(nil))
  30. pool_State = sync.Pool{
  31. New: func() interface{} {
  32. return &Runtime{scope: &scope{}, escapeeWriter: new(escapeeWriter)}
  33. },
  34. }
  35. )
  36. // Renderer any resulting value from an expression in an action that implements this
  37. // interface will not be printed, instead, we will invoke his Render() method which will be responsible
  38. // to render his self
  39. type Renderer interface {
  40. Render(*Runtime)
  41. }
  42. // RendererFunc func implementing interface Renderer
  43. type RendererFunc func(*Runtime)
  44. func (renderer RendererFunc) Render(r *Runtime) {
  45. renderer(r)
  46. }
  47. // Ranger a value implementing a ranger interface is able to iterate on his value
  48. // and can be used directly in a range statement
  49. type Ranger interface {
  50. Range() (reflect.Value, reflect.Value, bool)
  51. }
  52. type escapeeWriter struct {
  53. Writer io.Writer
  54. escapee SafeWriter
  55. set *Set
  56. }
  57. func (w *escapeeWriter) Write(b []byte) (int, error) {
  58. if w.set.escapee == nil {
  59. w.Writer.Write(b)
  60. } else {
  61. w.set.escapee(w.Writer, b)
  62. }
  63. return 0, nil
  64. }
  65. // Runtime this type holds the state of the execution of an template
  66. type Runtime struct {
  67. *escapeeWriter
  68. *scope
  69. content func(*Runtime, Expression)
  70. translator Translator
  71. context reflect.Value
  72. }
  73. // Context returns the current context value
  74. func (r *Runtime) Context() reflect.Value {
  75. return r.context
  76. }
  77. func (st *Runtime) newScope() {
  78. st.scope = &scope{parent: st.scope, variables: make(VarMap), blocks: st.blocks}
  79. }
  80. func (st *Runtime) releaseScope() {
  81. st.scope = st.scope.parent
  82. }
  83. type scope struct {
  84. parent *scope
  85. variables VarMap
  86. blocks map[string]*BlockNode
  87. }
  88. // YieldBlock yields a block in the current context, will panic if the context is not available
  89. func (st *Runtime) YieldBlock(name string, context interface{}) {
  90. block, has := st.getBlock(name)
  91. if has == false {
  92. panic(fmt.Errorf("Block %q was not found!!", name))
  93. }
  94. if context != nil {
  95. current := st.context
  96. st.context = reflect.ValueOf(context)
  97. st.executeList(block.List)
  98. st.context = current
  99. }
  100. st.executeList(block.List)
  101. }
  102. func (st *scope) getBlock(name string) (block *BlockNode, has bool) {
  103. block, has = st.blocks[name]
  104. for !has && st.parent != nil {
  105. st = st.parent
  106. block, has = st.blocks[name]
  107. }
  108. return
  109. }
  110. // YieldTemplate yields a template same as include
  111. func (st *Runtime) YieldTemplate(name string, context interface{}) {
  112. t, err := st.set.GetTemplate(name)
  113. if err != nil {
  114. panic(fmt.Errorf("include: template %q was not found", name))
  115. }
  116. st.newScope()
  117. st.blocks = t.processedBlocks
  118. Root := t.Root
  119. if t.extends != nil {
  120. Root = t.extends.Root
  121. }
  122. if context != nil {
  123. c := st.context
  124. st.context = reflect.ValueOf(context)
  125. st.executeList(Root)
  126. st.context = c
  127. } else {
  128. st.executeList(Root)
  129. }
  130. st.releaseScope()
  131. }
  132. // Set sets variable ${name} in the current template scope
  133. func (state *Runtime) Set(name string, val interface{}) {
  134. state.setValue(name, reflect.ValueOf(val))
  135. }
  136. func (state *Runtime) setValue(name string, val reflect.Value) bool {
  137. sc := state.scope
  138. initial := sc
  139. // try to resolve variables in the current scope
  140. _, ok := sc.variables[name]
  141. // if not found walks parent scopes
  142. for !ok && sc.parent != nil {
  143. sc = sc.parent
  144. _, ok = sc.variables[name]
  145. }
  146. if ok {
  147. sc.variables[name] = val
  148. return false
  149. }
  150. for initial.variables == nil && initial.parent != nil {
  151. initial = initial.parent
  152. }
  153. if initial.variables != nil {
  154. sc.variables[name] = val
  155. return false
  156. }
  157. return true
  158. }
  159. // Resolve resolves a value from the execution context
  160. func (state *Runtime) Resolve(name string) reflect.Value {
  161. if name == "." {
  162. return state.context
  163. }
  164. sc := state.scope
  165. // try to resolve variables in the current scope
  166. vl, ok := sc.variables[name]
  167. // if not found walks parent scopes
  168. for !ok && sc.parent != nil {
  169. sc = sc.parent
  170. vl, ok = sc.variables[name]
  171. }
  172. // if not found check globals
  173. if !ok {
  174. state.set.gmx.RLock()
  175. vl, ok = state.set.globals[name]
  176. state.set.gmx.RUnlock()
  177. // not found check defaultVariables
  178. if !ok {
  179. vl, ok = defaultVariables[name]
  180. }
  181. }
  182. return vl
  183. }
  184. func (st *Runtime) recover(err *error) {
  185. pool_State.Put(st)
  186. if recovered := recover(); recovered != nil {
  187. var is bool
  188. if _, is = recovered.(runtime.Error); is {
  189. panic(recovered)
  190. }
  191. *err, is = recovered.(error)
  192. if !is {
  193. panic(recovered)
  194. }
  195. }
  196. }
  197. func (st *Runtime) executeSet(left Expression, right reflect.Value) {
  198. typ := left.Type()
  199. if typ == NodeIdentifier {
  200. st.setValue(left.(*IdentifierNode).Ident, right)
  201. return
  202. }
  203. var value reflect.Value
  204. var fields []string
  205. if typ == NodeChain {
  206. chain := left.(*ChainNode)
  207. value = st.evalPrimaryExpressionGroup(chain.Node)
  208. fields = chain.Field
  209. } else {
  210. fields = left.(*FieldNode).Ident
  211. value = st.context
  212. }
  213. lef := len(fields) - 1
  214. for i := 0; i < lef; i++ {
  215. value = getFieldOrMethodValue(fields[i], value)
  216. if !value.IsValid() {
  217. left.errorf("identifier %q is not available in the current scope", fields[i])
  218. }
  219. }
  220. RESTART:
  221. switch value.Kind() {
  222. case reflect.Ptr:
  223. value = value.Elem()
  224. goto RESTART
  225. case reflect.Struct:
  226. value = value.FieldByName(fields[lef])
  227. if !value.IsValid() {
  228. left.errorf("identifier %q is not available in the current scope", fields[lef])
  229. }
  230. value.Set(right)
  231. case reflect.Map:
  232. value.SetMapIndex(reflect.ValueOf(&fields[lef]).Elem(), right)
  233. }
  234. }
  235. func (st *Runtime) executeSetList(set *SetNode) {
  236. if set.IndexExprGetLookup {
  237. value := st.evalPrimaryExpressionGroup(set.Right[0])
  238. st.executeSet(set.Left[0], value)
  239. if value.IsValid() {
  240. st.executeSet(set.Left[1], valueBoolTRUE)
  241. } else {
  242. st.executeSet(set.Left[1], valueBoolFALSE)
  243. }
  244. } else {
  245. for i := 0; i < len(set.Left); i++ {
  246. st.executeSet(set.Left[i], st.evalPrimaryExpressionGroup(set.Right[i]))
  247. }
  248. }
  249. }
  250. func (st *Runtime) executeLetList(set *SetNode) {
  251. if set.IndexExprGetLookup {
  252. value := st.evalPrimaryExpressionGroup(set.Right[0])
  253. st.variables[set.Left[0].(*IdentifierNode).Ident] = value
  254. if value.IsValid() {
  255. st.variables[set.Left[1].(*IdentifierNode).Ident] = valueBoolTRUE
  256. } else {
  257. st.variables[set.Left[1].(*IdentifierNode).Ident] = valueBoolFALSE
  258. }
  259. } else {
  260. for i := 0; i < len(set.Left); i++ {
  261. st.variables[set.Left[i].(*IdentifierNode).Ident] = st.evalPrimaryExpressionGroup(set.Right[i])
  262. }
  263. }
  264. }
  265. func (st *Runtime) executeYieldBlock(block *BlockNode, blockParam, yieldParam *BlockParameterList, expression Expression, content *ListNode) {
  266. needNewScope := len(blockParam.List) > 0 || len(yieldParam.List) > 0
  267. if needNewScope {
  268. st.newScope()
  269. for i := 0; i < len(yieldParam.List); i++ {
  270. p := &yieldParam.List[i]
  271. st.variables[p.Identifier] = st.evalPrimaryExpressionGroup(p.Expression)
  272. }
  273. for i := 0; i < len(blockParam.List); i++ {
  274. p := &blockParam.List[i]
  275. if _, found := st.variables[p.Identifier]; !found {
  276. if p.Expression == nil {
  277. st.variables[p.Identifier] = valueBoolFALSE
  278. } else {
  279. st.variables[p.Identifier] = st.evalPrimaryExpressionGroup(p.Expression)
  280. }
  281. }
  282. }
  283. }
  284. mycontent := st.content
  285. if content != nil {
  286. myscope := st.scope
  287. st.content = func(st *Runtime, expression Expression) {
  288. outscope := st.scope
  289. outcontent := st.content
  290. st.scope = myscope
  291. st.content = mycontent
  292. if expression != nil {
  293. context := st.context
  294. st.context = st.evalPrimaryExpressionGroup(expression)
  295. st.executeList(content)
  296. st.context = context
  297. } else {
  298. st.executeList(content)
  299. }
  300. st.scope = outscope
  301. st.content = outcontent
  302. }
  303. }
  304. if expression != nil {
  305. context := st.context
  306. st.context = st.evalPrimaryExpressionGroup(expression)
  307. st.executeList(block.List)
  308. st.context = context
  309. } else {
  310. st.executeList(block.List)
  311. }
  312. st.content = mycontent
  313. if needNewScope {
  314. st.releaseScope()
  315. }
  316. }
  317. func (st *Runtime) executeList(list *ListNode) {
  318. inNewSCOPE := false
  319. for i := 0; i < len(list.Nodes); i++ {
  320. node := list.Nodes[i]
  321. switch node.Type() {
  322. case NodeText:
  323. node := node.(*TextNode)
  324. _, err := st.Writer.Write(node.Text)
  325. if err != nil {
  326. node.error(err)
  327. }
  328. case NodeAction:
  329. node := node.(*ActionNode)
  330. if node.Set != nil {
  331. if node.Set.Let {
  332. if !inNewSCOPE {
  333. st.newScope() //creates new scope in the back state
  334. inNewSCOPE = true
  335. }
  336. st.executeLetList(node.Set)
  337. } else {
  338. st.executeSetList(node.Set)
  339. }
  340. }
  341. if node.Pipe != nil {
  342. v, safeWriter := st.evalPipelineExpression(node.Pipe)
  343. if !safeWriter && v.IsValid() {
  344. if v.Type().Implements(rendererType) {
  345. v.Interface().(Renderer).Render(st)
  346. } else {
  347. _, err := fastprinter.PrintValue(st.escapeeWriter, v)
  348. if err != nil {
  349. node.error(err)
  350. }
  351. }
  352. }
  353. }
  354. case NodeIf:
  355. node := node.(*IfNode)
  356. var isLet bool
  357. if node.Set != nil {
  358. if node.Set.Let {
  359. isLet = true
  360. st.newScope()
  361. st.executeLetList(node.Set)
  362. } else {
  363. st.executeSetList(node.Set)
  364. }
  365. }
  366. if castBoolean(st.evalPrimaryExpressionGroup(node.Expression)) {
  367. st.executeList(node.List)
  368. } else if node.ElseList != nil {
  369. st.executeList(node.ElseList)
  370. }
  371. if isLet {
  372. st.releaseScope()
  373. }
  374. case NodeRange:
  375. node := node.(*RangeNode)
  376. var expression reflect.Value
  377. isSet := node.Set != nil
  378. isLet := false
  379. isKeyVal := false
  380. context := st.context
  381. if isSet {
  382. isKeyVal = len(node.Set.Left) > 1
  383. expression = st.evalPrimaryExpressionGroup(node.Set.Right[0])
  384. if node.Set.Let {
  385. isLet = true
  386. st.newScope()
  387. }
  388. } else {
  389. expression = st.evalPrimaryExpressionGroup(node.Expression)
  390. }
  391. ranger := getRanger(expression)
  392. indexValue, rangeValue, end := ranger.Range()
  393. if !end {
  394. for !end {
  395. if isSet {
  396. if isLet {
  397. if isKeyVal {
  398. st.variables[node.Set.Left[0].String()] = indexValue
  399. st.variables[node.Set.Left[1].String()] = rangeValue
  400. } else {
  401. st.variables[node.Set.Left[0].String()] = rangeValue
  402. }
  403. } else {
  404. if isKeyVal {
  405. st.executeSet(node.Set.Left[0], indexValue)
  406. st.executeSet(node.Set.Left[1], rangeValue)
  407. } else {
  408. st.executeSet(node.Set.Left[0], rangeValue)
  409. }
  410. }
  411. } else {
  412. st.context = rangeValue
  413. }
  414. st.executeList(node.List)
  415. indexValue, rangeValue, end = ranger.Range()
  416. }
  417. } else if node.ElseList != nil {
  418. st.executeList(node.ElseList)
  419. }
  420. st.context = context
  421. if isLet {
  422. st.releaseScope()
  423. }
  424. case NodeYield:
  425. node := node.(*YieldNode)
  426. if node.IsContent {
  427. if st.content != nil {
  428. st.content(st, node.Expression)
  429. }
  430. } else {
  431. block, has := st.getBlock(node.Name)
  432. if has == false || block == nil {
  433. node.errorf("unresolved block %q!!", node.Name)
  434. }
  435. st.executeYieldBlock(block, block.Parameters, node.Parameters, node.Expression, node.Content)
  436. }
  437. case NodeBlock:
  438. node := node.(*BlockNode)
  439. block, has := st.getBlock(node.Name)
  440. if has == false {
  441. block = node
  442. }
  443. st.executeYieldBlock(block, block.Parameters, block.Parameters, block.Expression, block.Content)
  444. case NodeInclude:
  445. node := node.(*IncludeNode)
  446. var Name string
  447. name := st.evalPrimaryExpressionGroup(node.Name)
  448. if name.Type().Implements(stringerType) {
  449. Name = name.String()
  450. } else if name.Kind() == reflect.String {
  451. Name = name.String()
  452. } else {
  453. node.errorf("unexpected expression type %q in template yielding", getTypeString(name))
  454. }
  455. t, err := st.set.getTemplate(Name, node.TemplateName)
  456. if err != nil {
  457. node.error(err)
  458. } else {
  459. st.newScope()
  460. st.blocks = t.processedBlocks
  461. var context reflect.Value
  462. if node.Expression != nil {
  463. context = st.context
  464. st.context = st.evalPrimaryExpressionGroup(node.Expression)
  465. }
  466. Root := t.Root
  467. for t.extends != nil {
  468. t = t.extends
  469. Root = t.Root
  470. }
  471. st.executeList(Root)
  472. st.releaseScope()
  473. if node.Expression != nil {
  474. st.context = context
  475. }
  476. }
  477. }
  478. }
  479. if inNewSCOPE {
  480. st.releaseScope()
  481. }
  482. }
  483. var (
  484. valueBoolTRUE = reflect.ValueOf(true)
  485. valueBoolFALSE = reflect.ValueOf(false)
  486. )
  487. func (st *Runtime) evalPrimaryExpressionGroup(node Expression) reflect.Value {
  488. switch node.Type() {
  489. case NodeAdditiveExpr:
  490. return st.evalAdditiveExpression(node.(*AdditiveExprNode))
  491. case NodeMultiplicativeExpr:
  492. return st.evalMultiplicativeExpression(node.(*MultiplicativeExprNode))
  493. case NodeComparativeExpr:
  494. return st.evalComparativeExpression(node.(*ComparativeExprNode))
  495. case NodeNumericComparativeExpr:
  496. return st.evalNumericComparativeExpression(node.(*NumericComparativeExprNode))
  497. case NodeLogicalExpr:
  498. return st.evalLogicalExpression(node.(*LogicalExprNode))
  499. case NodeNotExpr:
  500. return boolValue(!castBoolean(st.evalPrimaryExpressionGroup(node.(*NotExprNode).Expr)))
  501. case NodeTernaryExpr:
  502. node := node.(*TernaryExprNode)
  503. if castBoolean(st.evalPrimaryExpressionGroup(node.Boolean)) {
  504. return st.evalPrimaryExpressionGroup(node.Left)
  505. }
  506. return st.evalPrimaryExpressionGroup(node.Right)
  507. case NodeCallExpr:
  508. node := node.(*CallExprNode)
  509. baseExpr := st.evalBaseExpressionGroup(node.BaseExpr)
  510. if baseExpr.Kind() != reflect.Func {
  511. node.errorf("node %q is not func kind %q", node.BaseExpr, baseExpr.Type())
  512. }
  513. return st.evalCallExpression(baseExpr, node.Args)
  514. case NodeIndexExpr:
  515. node := node.(*IndexExprNode)
  516. baseExpression := st.evalPrimaryExpressionGroup(node.Base)
  517. indexExpression := st.evalPrimaryExpressionGroup(node.Index)
  518. indexType := indexExpression.Type()
  519. if baseExpression.Kind() == reflect.Interface {
  520. baseExpression = baseExpression.Elem()
  521. }
  522. if baseExpression.Kind() == reflect.Ptr {
  523. baseExpression = baseExpression.Elem()
  524. }
  525. switch baseExpression.Kind() {
  526. case reflect.Map:
  527. key := baseExpression.Type().Key()
  528. if !indexType.AssignableTo(key) {
  529. if indexType.ConvertibleTo(key) {
  530. indexExpression = indexExpression.Convert(key)
  531. } else {
  532. node.errorf("%s is not assignable|convertible to map key %s", indexType.String(), key.String())
  533. }
  534. }
  535. return baseExpression.MapIndex(indexExpression)
  536. case reflect.Array, reflect.String, reflect.Slice:
  537. if canNumber(indexType.Kind()) {
  538. return baseExpression.Index(int(castInt64(indexExpression)))
  539. } else {
  540. node.errorf("non numeric value in index expression kind %s", baseExpression.Kind().String())
  541. }
  542. case reflect.Struct:
  543. if canNumber(indexType.Kind()) {
  544. return baseExpression.Field(int(castInt64(indexExpression)))
  545. } else if indexType.Kind() == reflect.String {
  546. return getFieldOrMethodValue(indexExpression.String(), baseExpression)
  547. } else {
  548. node.errorf("non numeric value in index expression kind %s", baseExpression.Kind().String())
  549. }
  550. default:
  551. node.errorf("indexing is not supported in value type %s", baseExpression.Kind().String())
  552. }
  553. case NodeSliceExpr:
  554. node := node.(*SliceExprNode)
  555. baseExpression := st.evalPrimaryExpressionGroup(node.Base)
  556. var index, length int
  557. if node.Index != nil {
  558. indexExpression := st.evalPrimaryExpressionGroup(node.Index)
  559. if canNumber(indexExpression.Kind()) {
  560. index = int(castInt64(indexExpression))
  561. } else {
  562. node.Index.errorf("non numeric value in index expression kind %s", indexExpression.Kind().String())
  563. }
  564. }
  565. if node.EndIndex != nil {
  566. indexExpression := st.evalPrimaryExpressionGroup(node.EndIndex)
  567. if canNumber(indexExpression.Kind()) {
  568. length = int(castInt64(indexExpression))
  569. } else {
  570. node.EndIndex.errorf("non numeric value in index expression kind %s", indexExpression.Kind().String())
  571. }
  572. } else {
  573. length = baseExpression.Len()
  574. }
  575. return baseExpression.Slice(index, length)
  576. }
  577. return st.evalBaseExpressionGroup(node)
  578. }
  579. func (st *Runtime) isSet(node Node) bool {
  580. nodeType := node.Type()
  581. switch nodeType {
  582. case NodeIndexExpr:
  583. node := node.(*IndexExprNode)
  584. if !st.isSet(node.Base) {
  585. return false
  586. }
  587. if !st.isSet(node.Index) {
  588. return false
  589. }
  590. baseExpression := st.evalPrimaryExpressionGroup(node.Base)
  591. indexExpression := st.evalPrimaryExpressionGroup(node.Index)
  592. indexType := indexExpression.Type()
  593. if baseExpression.Kind() == reflect.Ptr {
  594. baseExpression = baseExpression.Elem()
  595. }
  596. switch baseExpression.Kind() {
  597. case reflect.Map:
  598. key := baseExpression.Type().Key()
  599. if !indexType.AssignableTo(key) {
  600. if indexType.ConvertibleTo(key) {
  601. indexExpression = indexExpression.Convert(key)
  602. } else {
  603. node.errorf("%s is not assignable|convertible to map key %s", indexType.String(), key.String())
  604. }
  605. }
  606. return baseExpression.MapIndex(indexExpression).IsValid()
  607. case reflect.Array, reflect.String, reflect.Slice:
  608. if canNumber(indexType.Kind()) {
  609. i := int(castInt64(indexExpression))
  610. return i >= 0 && i < baseExpression.Len()
  611. } else {
  612. node.errorf("non numeric value in index expression kind %s", baseExpression.Kind().String())
  613. }
  614. case reflect.Struct:
  615. if canNumber(indexType.Kind()) {
  616. i := int(castInt64(indexExpression))
  617. return i >= 0 && i < baseExpression.NumField()
  618. } else if indexType.Kind() == reflect.String {
  619. return getFieldOrMethodValue(indexExpression.String(), baseExpression).IsValid()
  620. } else {
  621. node.errorf("non numeric value in index expression kind %s", baseExpression.Kind().String())
  622. }
  623. default:
  624. node.errorf("indexing is not supported in value type %s", baseExpression.Kind().String())
  625. }
  626. case NodeIdentifier:
  627. if st.Resolve(node.String()).IsValid() == false {
  628. return false
  629. }
  630. case NodeField:
  631. node := node.(*FieldNode)
  632. resolved := st.context
  633. for i := 0; i < len(node.Ident); i++ {
  634. resolved = getFieldOrMethodValue(node.Ident[i], resolved)
  635. if !resolved.IsValid() {
  636. return false
  637. }
  638. }
  639. case NodeChain:
  640. node := node.(*ChainNode)
  641. var value = st.evalPrimaryExpressionGroup(node.Node)
  642. if !value.IsValid() {
  643. return false
  644. }
  645. for i := 0; i < len(node.Field); i++ {
  646. value := getFieldOrMethodValue(node.Field[i], value)
  647. if !value.IsValid() {
  648. return false
  649. }
  650. }
  651. default:
  652. //todo: maybe work some edge cases
  653. if !(nodeType > beginExpressions && nodeType < endExpressions) {
  654. node.errorf("unexpected %q node in isset clause", node)
  655. }
  656. }
  657. return true
  658. }
  659. func (st *Runtime) evalNumericComparativeExpression(node *NumericComparativeExprNode) reflect.Value {
  660. left, right := st.evalPrimaryExpressionGroup(node.Left), st.evalPrimaryExpressionGroup(node.Right)
  661. isTrue := false
  662. kind := left.Kind()
  663. // if the left value is not a float and the right is, we need to promote the left value to a float before the calculation
  664. // this is necessary for expressions like 4*1.23
  665. needFloatPromotion := !isFloat(kind) && isFloat(right.Kind())
  666. switch node.Operator.typ {
  667. case itemGreat:
  668. if isInt(kind) {
  669. if needFloatPromotion {
  670. isTrue = float64(left.Int()) > right.Float()
  671. } else {
  672. isTrue = left.Int() > toInt(right)
  673. }
  674. } else if isFloat(kind) {
  675. isTrue = left.Float() > toFloat(right)
  676. } else if isUint(kind) {
  677. if needFloatPromotion {
  678. isTrue = float64(left.Uint()) > right.Float()
  679. } else {
  680. isTrue = left.Uint() > toUint(right)
  681. }
  682. } else {
  683. node.Left.errorf("a non numeric value in numeric comparative expression")
  684. }
  685. case itemGreatEquals:
  686. if isInt(kind) {
  687. if needFloatPromotion {
  688. isTrue = float64(left.Int()) >= right.Float()
  689. } else {
  690. isTrue = left.Int() >= toInt(right)
  691. }
  692. } else if isFloat(kind) {
  693. isTrue = left.Float() >= toFloat(right)
  694. } else if isUint(kind) {
  695. if needFloatPromotion {
  696. isTrue = float64(left.Uint()) >= right.Float()
  697. } else {
  698. isTrue = left.Uint() >= toUint(right)
  699. }
  700. } else {
  701. node.Left.errorf("a non numeric value in numeric comparative expression")
  702. }
  703. case itemLess:
  704. if isInt(kind) {
  705. if needFloatPromotion {
  706. isTrue = float64(left.Int()) < right.Float()
  707. } else {
  708. isTrue = left.Int() < toInt(right)
  709. }
  710. } else if isFloat(kind) {
  711. isTrue = left.Float() < toFloat(right)
  712. } else if isUint(kind) {
  713. if needFloatPromotion {
  714. isTrue = float64(left.Uint()) < right.Float()
  715. } else {
  716. isTrue = left.Uint() < toUint(right)
  717. }
  718. } else {
  719. node.Left.errorf("a non numeric value in numeric comparative expression")
  720. }
  721. case itemLessEquals:
  722. if isInt(kind) {
  723. if needFloatPromotion {
  724. isTrue = float64(left.Int()) <= right.Float()
  725. } else {
  726. isTrue = left.Int() <= toInt(right)
  727. }
  728. } else if isFloat(kind) {
  729. isTrue = left.Float() <= toFloat(right)
  730. } else if isUint(kind) {
  731. if needFloatPromotion {
  732. isTrue = float64(left.Uint()) <= right.Float()
  733. } else {
  734. isTrue = left.Uint() <= toUint(right)
  735. }
  736. } else {
  737. node.Left.errorf("a non numeric value in numeric comparative expression")
  738. }
  739. }
  740. return boolValue(isTrue)
  741. }
  742. func (st *Runtime) evalLogicalExpression(node *LogicalExprNode) reflect.Value {
  743. isTrue := castBoolean(st.evalPrimaryExpressionGroup(node.Left))
  744. if node.Operator.typ == itemAnd {
  745. isTrue = isTrue && castBoolean(st.evalPrimaryExpressionGroup(node.Right))
  746. } else {
  747. isTrue = isTrue || castBoolean(st.evalPrimaryExpressionGroup(node.Right))
  748. }
  749. return boolValue(isTrue)
  750. }
  751. func boolValue(isTrue bool) reflect.Value {
  752. if isTrue {
  753. return valueBoolTRUE
  754. }
  755. return valueBoolFALSE
  756. }
  757. func (st *Runtime) evalComparativeExpression(node *ComparativeExprNode) reflect.Value {
  758. left, right := st.evalPrimaryExpressionGroup(node.Left), st.evalPrimaryExpressionGroup(node.Right)
  759. if node.Operator.typ == itemNotEquals {
  760. return boolValue(!checkEquality(left, right))
  761. }
  762. return boolValue(checkEquality(left, right))
  763. }
  764. func toInt(v reflect.Value) int64 {
  765. kind := v.Kind()
  766. if isInt(kind) {
  767. return v.Int()
  768. } else if isFloat(kind) {
  769. return int64(v.Float())
  770. } else if isUint(kind) {
  771. return int64(v.Uint())
  772. } else if kind == reflect.String {
  773. n, e := strconv.ParseInt(v.String(), 10, 0)
  774. if e != nil {
  775. panic(e)
  776. }
  777. return n
  778. } else if kind == reflect.Bool {
  779. if v.Bool() {
  780. return 0
  781. }
  782. return 1
  783. }
  784. panic(fmt.Errorf("type: %q can't be converted to int64", v.Type()))
  785. }
  786. func toUint(v reflect.Value) uint64 {
  787. kind := v.Kind()
  788. if isUint(kind) {
  789. return v.Uint()
  790. } else if isInt(kind) {
  791. return uint64(v.Int())
  792. } else if isFloat(kind) {
  793. return uint64(v.Float())
  794. } else if kind == reflect.String {
  795. n, e := strconv.ParseUint(v.String(), 10, 0)
  796. if e != nil {
  797. panic(e)
  798. }
  799. return n
  800. } else if kind == reflect.Bool {
  801. if v.Bool() {
  802. return 0
  803. }
  804. return 1
  805. }
  806. panic(fmt.Errorf("type: %q can't be converted to uint64", v.Type()))
  807. }
  808. func toFloat(v reflect.Value) float64 {
  809. kind := v.Kind()
  810. if isFloat(kind) {
  811. return v.Float()
  812. } else if isInt(kind) {
  813. return float64(v.Int())
  814. } else if isUint(kind) {
  815. return float64(v.Uint())
  816. } else if kind == reflect.String {
  817. n, e := strconv.ParseFloat(v.String(), 0)
  818. if e != nil {
  819. panic(e)
  820. }
  821. return n
  822. } else if kind == reflect.Bool {
  823. if v.Bool() {
  824. return 0
  825. }
  826. return 1
  827. }
  828. panic(fmt.Errorf("type: %q can't be converted to float64", v.Type()))
  829. }
  830. func (st *Runtime) evalMultiplicativeExpression(node *MultiplicativeExprNode) reflect.Value {
  831. left, right := st.evalPrimaryExpressionGroup(node.Left), st.evalPrimaryExpressionGroup(node.Right)
  832. kind := left.Kind()
  833. // if the left value is not a float and the right is, we need to promote the left value to a float before the calculation
  834. // this is necessary for expressions like 4*1.23
  835. needFloatPromotion := !isFloat(kind) && isFloat(right.Kind())
  836. switch node.Operator.typ {
  837. case itemMul:
  838. if isInt(kind) {
  839. if needFloatPromotion {
  840. // do the promotion and calculates
  841. left = reflect.ValueOf(float64(left.Int()) * right.Float())
  842. } else {
  843. // do not need float promotion
  844. left = reflect.ValueOf(left.Int() * toInt(right))
  845. }
  846. } else if isFloat(kind) {
  847. left = reflect.ValueOf(left.Float() * toFloat(right))
  848. } else if isUint(kind) {
  849. if needFloatPromotion {
  850. left = reflect.ValueOf(float64(left.Uint()) * right.Float())
  851. } else {
  852. left = reflect.ValueOf(left.Uint() * toUint(right))
  853. }
  854. } else {
  855. node.Left.errorf("a non numeric value in multiplicative expression")
  856. }
  857. case itemDiv:
  858. if isInt(kind) {
  859. if needFloatPromotion {
  860. left = reflect.ValueOf(float64(left.Int()) / right.Float())
  861. } else {
  862. left = reflect.ValueOf(left.Int() / toInt(right))
  863. }
  864. } else if isFloat(kind) {
  865. left = reflect.ValueOf(left.Float() / toFloat(right))
  866. } else if isUint(kind) {
  867. if needFloatPromotion {
  868. left = reflect.ValueOf(float64(left.Uint()) / right.Float())
  869. } else {
  870. left = reflect.ValueOf(left.Uint() / toUint(right))
  871. }
  872. } else {
  873. node.Left.errorf("a non numeric value in multiplicative expression")
  874. }
  875. case itemMod:
  876. if isInt(kind) {
  877. left = reflect.ValueOf(left.Int() % toInt(right))
  878. } else if isFloat(kind) {
  879. left = reflect.ValueOf(int64(left.Float()) % toInt(right))
  880. } else if isUint(kind) {
  881. left = reflect.ValueOf(left.Uint() % toUint(right))
  882. } else {
  883. node.Left.errorf("a non numeric value in multiplicative expression")
  884. }
  885. }
  886. return left
  887. }
  888. func (st *Runtime) evalAdditiveExpression(node *AdditiveExprNode) reflect.Value {
  889. isAdditive := node.Operator.typ == itemAdd
  890. if node.Left == nil {
  891. right := st.evalPrimaryExpressionGroup(node.Right)
  892. kind := right.Kind()
  893. // todo: optimize
  894. // todo:
  895. if isInt(kind) {
  896. if isAdditive {
  897. return reflect.ValueOf(+right.Int())
  898. } else {
  899. return reflect.ValueOf(-right.Int())
  900. }
  901. } else if isUint(kind) {
  902. if isAdditive {
  903. return right
  904. } else {
  905. return reflect.ValueOf(-int64(right.Uint()))
  906. }
  907. } else if isFloat(kind) {
  908. if isAdditive {
  909. return reflect.ValueOf(+right.Float())
  910. } else {
  911. return reflect.ValueOf(-right.Float())
  912. }
  913. }
  914. node.Left.errorf("a non numeric value in additive expression")
  915. }
  916. left, right := st.evalPrimaryExpressionGroup(node.Left), st.evalPrimaryExpressionGroup(node.Right)
  917. kind := left.Kind()
  918. // if the left value is not a float and the right is, we need to promote the left value to a float before the calculation
  919. // this is necessary for expressions like 4+1.23
  920. needFloatPromotion := !isFloat(kind) && kind != reflect.String && isFloat(right.Kind())
  921. if needFloatPromotion {
  922. if isInt(kind) {
  923. if isAdditive {
  924. left = reflect.ValueOf(float64(left.Int()) + right.Float())
  925. } else {
  926. left = reflect.ValueOf(float64(left.Int()) - right.Float())
  927. }
  928. } else if isUint(kind) {
  929. if isAdditive {
  930. left = reflect.ValueOf(float64(left.Uint()) + right.Float())
  931. } else {
  932. left = reflect.ValueOf(float64(left.Uint()) - right.Float())
  933. }
  934. } else {
  935. node.Left.errorf("a non numeric value in additive expression")
  936. }
  937. } else {
  938. if isInt(kind) {
  939. if isAdditive {
  940. left = reflect.ValueOf(left.Int() + toInt(right))
  941. } else {
  942. left = reflect.ValueOf(left.Int() - toInt(right))
  943. }
  944. } else if isFloat(kind) {
  945. if isAdditive {
  946. left = reflect.ValueOf(left.Float() + toFloat(right))
  947. } else {
  948. left = reflect.ValueOf(left.Float() - toFloat(right))
  949. }
  950. } else if isUint(kind) {
  951. if isAdditive {
  952. left = reflect.ValueOf(left.Uint() + toUint(right))
  953. } else {
  954. left = reflect.ValueOf(left.Uint() - toUint(right))
  955. }
  956. } else if kind == reflect.String {
  957. if isAdditive {
  958. left = reflect.ValueOf(left.String() + fmt.Sprint(right))
  959. } else {
  960. node.Right.errorf("minus signal is not allowed with strings")
  961. }
  962. } else {
  963. node.Left.errorf("a non numeric value in additive expression")
  964. }
  965. }
  966. return left
  967. }
  968. func getTypeString(value reflect.Value) string {
  969. if value.IsValid() {
  970. return value.Type().String()
  971. }
  972. return "nil"
  973. }
  974. func (st *Runtime) evalBaseExpressionGroup(node Node) reflect.Value {
  975. switch node.Type() {
  976. case NodeNil:
  977. return reflect.ValueOf(nil)
  978. case NodeBool:
  979. if node.(*BoolNode).True {
  980. return valueBoolTRUE
  981. }
  982. return valueBoolFALSE
  983. case NodeString:
  984. return reflect.ValueOf(&node.(*StringNode).Text).Elem()
  985. case NodeIdentifier:
  986. resolved := st.Resolve(node.(*IdentifierNode).Ident)
  987. if !resolved.IsValid() {
  988. node.errorf("identifier %q is not available in the current scope %v", node, st.variables)
  989. }
  990. return resolved
  991. case NodeField:
  992. node := node.(*FieldNode)
  993. resolved := st.context
  994. for i := 0; i < len(node.Ident); i++ {
  995. fieldResolved := getFieldOrMethodValue(node.Ident[i], resolved)
  996. if !fieldResolved.IsValid() {
  997. node.errorf("there is no field or method %q in %s", node.Ident[i], getTypeString(resolved))
  998. }
  999. resolved = fieldResolved
  1000. }
  1001. return resolved
  1002. case NodeChain:
  1003. node := node.(*ChainNode)
  1004. var resolved = st.evalPrimaryExpressionGroup(node.Node)
  1005. for i := 0; i < len(node.Field); i++ {
  1006. fieldValue := getFieldOrMethodValue(node.Field[i], resolved)
  1007. if !fieldValue.IsValid() {
  1008. node.errorf("there is no field or method %q in %s", node.Field[i], getTypeString(resolved))
  1009. }
  1010. resolved = fieldValue
  1011. }
  1012. return resolved
  1013. case NodeNumber:
  1014. node := node.(*NumberNode)
  1015. if node.IsFloat {
  1016. return reflect.ValueOf(&node.Float64).Elem()
  1017. }
  1018. if node.IsInt {
  1019. return reflect.ValueOf(&node.Int64).Elem()
  1020. }
  1021. if node.IsUint {
  1022. return reflect.ValueOf(&node.Uint64).Elem()
  1023. }
  1024. }
  1025. node.errorf("unexpected node type %s in unary expression evaluating", node)
  1026. return reflect.Value{}
  1027. }
  1028. func (st *Runtime) evalCallExpression(baseExpr reflect.Value, args []Expression, values ...reflect.Value) reflect.Value {
  1029. if funcType.AssignableTo(baseExpr.Type()) {
  1030. return baseExpr.Interface().(Func)(Arguments{runtime: st, argExpr: args, argVal: values})
  1031. }
  1032. i := len(args) + len(values)
  1033. var returns []reflect.Value
  1034. if i <= 10 {
  1035. returns = reflect_Call10(i, st, baseExpr, args, values...)
  1036. } else {
  1037. returns = reflect_Call(make([]reflect.Value, i, i), st, baseExpr, args, values...)
  1038. }
  1039. if len(returns) == 0 {
  1040. return reflect.Value{}
  1041. }
  1042. return returns[0]
  1043. }
  1044. func (st *Runtime) evalCommandExpression(node *CommandNode) (reflect.Value, bool) {
  1045. term := st.evalPrimaryExpressionGroup(node.BaseExpr)
  1046. if node.Call {
  1047. if term.Kind() == reflect.Func {
  1048. if term.Type() == safeWriterType {
  1049. st.evalSafeWriter(term, node)
  1050. return reflect.Value{}, true
  1051. }
  1052. return st.evalCallExpression(term, node.Args), false
  1053. } else {
  1054. node.Args[0].errorf("command %q type %s is not func", node.Args[0], term.Type())
  1055. }
  1056. }
  1057. return term, false
  1058. }
  1059. type escapeWriter struct {
  1060. rawWriter io.Writer
  1061. safeWriter SafeWriter
  1062. }
  1063. func (w *escapeWriter) Write(b []byte) (int, error) {
  1064. w.safeWriter(w.rawWriter, b)
  1065. return 0, nil
  1066. }
  1067. func (st *Runtime) evalSafeWriter(term reflect.Value, node *CommandNode, v ...reflect.Value) {
  1068. sw := &escapeWriter{rawWriter: st.Writer, safeWriter: term.Interface().(SafeWriter)}
  1069. for i := 0; i < len(v); i++ {
  1070. fastprinter.PrintValue(sw, v[i])
  1071. }
  1072. for i := 0; i < len(node.Args); i++ {
  1073. fastprinter.PrintValue(sw, st.evalPrimaryExpressionGroup(node.Args[i]))
  1074. }
  1075. }
  1076. func (st *Runtime) evalCommandPipeExpression(node *CommandNode, value reflect.Value) (reflect.Value, bool) {
  1077. term := st.evalPrimaryExpressionGroup(node.BaseExpr)
  1078. if term.Kind() == reflect.Func {
  1079. if term.Type() == safeWriterType {
  1080. st.evalSafeWriter(term, node, value)
  1081. return reflect.Value{}, true
  1082. }
  1083. return st.evalCallExpression(term, node.Args, value), false
  1084. } else {
  1085. node.BaseExpr.errorf("pipe command %q type %s is not func", node.BaseExpr, term.Type())
  1086. }
  1087. return term, false
  1088. }
  1089. func (st *Runtime) evalPipelineExpression(node *PipeNode) (value reflect.Value, safeWriter bool) {
  1090. value, safeWriter = st.evalCommandExpression(node.Cmds[0])
  1091. for i := 1; i < len(node.Cmds); i++ {
  1092. if safeWriter {
  1093. node.Cmds[i].errorf("unexpected command %s, writer command should be the last command", node.Cmds[i])
  1094. }
  1095. value, safeWriter = st.evalCommandPipeExpression(node.Cmds[i], value)
  1096. }
  1097. return
  1098. }
  1099. func reflect_Call(arguments []reflect.Value, st *Runtime, fn reflect.Value, args []Expression, values ...reflect.Value) []reflect.Value {
  1100. typ := fn.Type()
  1101. numIn := typ.NumIn()
  1102. isVariadic := typ.IsVariadic()
  1103. if isVariadic {
  1104. numIn--
  1105. }
  1106. i, j := 0, 0
  1107. for ; i < numIn && i < len(values); i++ {
  1108. in := typ.In(i)
  1109. term := values[i]
  1110. if !term.Type().AssignableTo(in) {
  1111. term = term.Convert(in)
  1112. }
  1113. arguments[i] = term
  1114. }
  1115. if isVariadic {
  1116. in := typ.In(numIn).Elem()
  1117. for ; i < len(values); i++ {
  1118. term := values[i]
  1119. if !term.Type().AssignableTo(in) {
  1120. term = term.Convert(in)
  1121. }
  1122. arguments[i] = term
  1123. }
  1124. }
  1125. for ; i < numIn && j < len(args); i, j = i+1, j+1 {
  1126. in := typ.In(i)
  1127. term := st.evalPrimaryExpressionGroup(args[j])
  1128. if !term.Type().AssignableTo(in) {
  1129. term = term.Convert(in)
  1130. }
  1131. arguments[i] = term
  1132. }
  1133. if isVariadic {
  1134. in := typ.In(numIn).Elem()
  1135. for ; j < len(args); i, j = i+1, j+1 {
  1136. term := st.evalPrimaryExpressionGroup(args[j])
  1137. if !term.Type().AssignableTo(in) {
  1138. term = term.Convert(in)
  1139. }
  1140. arguments[i] = term
  1141. }
  1142. }
  1143. return fn.Call(arguments[0:i])
  1144. }
  1145. func reflect_Call10(i int, st *Runtime, fn reflect.Value, args []Expression, values ...reflect.Value) []reflect.Value {
  1146. var arguments [10]reflect.Value
  1147. return reflect_Call(arguments[0:i], st, fn, args, values...)
  1148. }
  1149. func isUint(kind reflect.Kind) bool {
  1150. return kind >= reflect.Uint && kind <= reflect.Uint64
  1151. }
  1152. func isInt(kind reflect.Kind) bool {
  1153. return kind >= reflect.Int && kind <= reflect.Int64
  1154. }
  1155. func isFloat(kind reflect.Kind) bool {
  1156. return kind == reflect.Float32 || kind == reflect.Float64
  1157. }
  1158. // checkEquality of two reflect values in the semantic of the jet runtime
  1159. func checkEquality(v1, v2 reflect.Value) bool {
  1160. if !v1.IsValid() || !v2.IsValid() {
  1161. return v1.IsValid() == v2.IsValid()
  1162. }
  1163. v1Type := v1.Type()
  1164. v2Type := v2.Type()
  1165. // fast path
  1166. if v1Type != v2.Type() && !v2Type.AssignableTo(v1Type) && !v2Type.ConvertibleTo(v1Type) {
  1167. return false
  1168. }
  1169. kind := v1.Kind()
  1170. if isInt(kind) {
  1171. return v1.Int() == toInt(v2)
  1172. }
  1173. if isFloat(kind) {
  1174. return v1.Float() == toFloat(v2)
  1175. }
  1176. if isUint(kind) {
  1177. return v1.Uint() == toUint(v2)
  1178. }
  1179. switch kind {
  1180. case reflect.Bool:
  1181. return v1.Bool() == castBoolean(v2)
  1182. case reflect.String:
  1183. return v1.String() == v2.String()
  1184. case reflect.Array:
  1185. vlen := v1.Len()
  1186. if vlen == v2.Len() {
  1187. return false
  1188. }
  1189. for i := 0; i < vlen; i++ {
  1190. if !checkEquality(v1.Index(i), v2.Index(i)) {
  1191. return false
  1192. }
  1193. }
  1194. return true
  1195. case reflect.Slice:
  1196. if v1.IsNil() != v2.IsNil() {
  1197. return false
  1198. }
  1199. vlen := v1.Len()
  1200. if vlen != v2.Len() {
  1201. return false
  1202. }
  1203. if v1.CanAddr() && v2.CanAddr() && v1.Pointer() == v2.Pointer() {
  1204. return true
  1205. }
  1206. for i := 0; i < vlen; i++ {
  1207. if !checkEquality(v1.Index(i), v2.Index(i)) {
  1208. return false
  1209. }
  1210. }
  1211. return true
  1212. case reflect.Interface:
  1213. if v1.IsNil() || v2.IsNil() {
  1214. return v1.IsNil() == v2.IsNil()
  1215. }
  1216. return checkEquality(v1.Elem(), v2.Elem())
  1217. case reflect.Ptr:
  1218. return v1.Pointer() == v2.Pointer()
  1219. case reflect.Struct:
  1220. numField := v1.NumField()
  1221. for i, n := 0, numField; i < n; i++ {
  1222. if !checkEquality(v1.Field(i), v2.Field(i)) {
  1223. return false
  1224. }
  1225. }
  1226. return true
  1227. case reflect.Map:
  1228. if v1.IsNil() != v2.IsNil() {
  1229. return false
  1230. }
  1231. if v1.Len() != v2.Len() {
  1232. return false
  1233. }
  1234. if v1.Pointer() == v2.Pointer() {
  1235. return true
  1236. }
  1237. for _, k := range v1.MapKeys() {
  1238. val1 := v1.MapIndex(k)
  1239. val2 := v2.MapIndex(k)
  1240. if !val1.IsValid() || !val2.IsValid() || !checkEquality(v1.MapIndex(k), v2.MapIndex(k)) {
  1241. return false
  1242. }
  1243. }
  1244. return true
  1245. case reflect.Func:
  1246. return v1.IsNil() && v2.IsNil()
  1247. default:
  1248. // Normal equality suffices
  1249. return v1.Interface() == v2.Interface()
  1250. }
  1251. }
  1252. func castBoolean(v reflect.Value) bool {
  1253. kind := v.Kind()
  1254. switch kind {
  1255. case reflect.Ptr:
  1256. return v.IsNil() == false
  1257. case reflect.Bool:
  1258. return v.Bool()
  1259. case reflect.Array:
  1260. numItems := v.Len()
  1261. for i, n := 0, numItems; i < n; i++ {
  1262. if !castBoolean(v.Index(i)) {
  1263. return false
  1264. }
  1265. }
  1266. return true
  1267. case reflect.Struct:
  1268. numField := v.NumField()
  1269. for i, n := 0, numField; i < n; i++ {
  1270. if !castBoolean(v.Field(i)) {
  1271. return false
  1272. }
  1273. }
  1274. return true
  1275. case reflect.Map, reflect.Slice, reflect.String:
  1276. return v.Len() > 0
  1277. default:
  1278. if isInt(kind) {
  1279. return v.Int() > 0
  1280. }
  1281. if isUint(kind) {
  1282. return v.Uint() > 0
  1283. }
  1284. if isFloat(kind) {
  1285. return v.Float() > 0
  1286. }
  1287. }
  1288. return false
  1289. }
  1290. func canNumber(kind reflect.Kind) bool {
  1291. return isInt(kind) || isUint(kind) || isFloat(kind)
  1292. }
  1293. func castInt64(v reflect.Value) int64 {
  1294. kind := v.Kind()
  1295. switch {
  1296. case isInt(kind):
  1297. return v.Int()
  1298. case isUint(kind):
  1299. return int64(v.Uint())
  1300. case isFloat(kind):
  1301. return int64(v.Float())
  1302. }
  1303. return 0
  1304. }
  1305. var cachedStructsMutex = sync.RWMutex{}
  1306. var cachedStructsFieldIndex = map[reflect.Type]map[string][]int{}
  1307. func getFieldOrMethodValue(key string, v reflect.Value) reflect.Value {
  1308. value := getValue(key, v)
  1309. if value.Kind() == reflect.Interface {
  1310. value = value.Elem()
  1311. }
  1312. return value
  1313. }
  1314. func getValue(key string, v reflect.Value) reflect.Value {
  1315. if !v.IsValid() {
  1316. return reflect.Value{}
  1317. }
  1318. value := v.MethodByName(key)
  1319. if value.IsValid() {
  1320. return value
  1321. }
  1322. k := v.Kind()
  1323. if k == reflect.Ptr || k == reflect.Interface {
  1324. v = v.Elem()
  1325. k = v.Kind()
  1326. value = v.MethodByName(key)
  1327. if value.IsValid() {
  1328. return value
  1329. }
  1330. } else if v.CanAddr() {
  1331. value = v.Addr().MethodByName(key)
  1332. if value.IsValid() {
  1333. return value
  1334. }
  1335. }
  1336. if k == reflect.Struct {
  1337. typ := v.Type()
  1338. cachedStructsMutex.RLock()
  1339. cache, ok := cachedStructsFieldIndex[typ]
  1340. cachedStructsMutex.RUnlock()
  1341. if !ok {
  1342. cachedStructsMutex.Lock()
  1343. if cache, ok = cachedStructsFieldIndex[typ]; !ok {
  1344. cache = make(map[string][]int)
  1345. buildCache(typ, cache, nil)
  1346. cachedStructsFieldIndex[typ] = cache
  1347. }
  1348. cachedStructsMutex.Unlock()
  1349. }
  1350. if id, ok := cache[key]; ok {
  1351. return v.FieldByIndex(id)
  1352. }
  1353. return reflect.Value{}
  1354. } else if k == reflect.Map {
  1355. return v.MapIndex(reflect.ValueOf(key))
  1356. }
  1357. return reflect.Value{}
  1358. }
  1359. func buildCache(typ reflect.Type, cache map[string][]int, parent []int) {
  1360. numFields := typ.NumField()
  1361. max := len(parent) + 1
  1362. for i := 0; i < numFields; i++ {
  1363. index := make([]int, max)
  1364. copy(index, parent)
  1365. index[len(parent)] = i
  1366. field := typ.Field(i)
  1367. if field.Anonymous {
  1368. typ := field.Type
  1369. if typ.Kind() == reflect.Struct {
  1370. buildCache(typ, cache, index)
  1371. }
  1372. }
  1373. cache[field.Name] = index
  1374. }
  1375. }
  1376. func getRanger(v reflect.Value) Ranger {
  1377. tuP := v.Type()
  1378. if tuP.Implements(rangerType) {
  1379. return v.Interface().(Ranger)
  1380. }
  1381. k := tuP.Kind()
  1382. switch k {
  1383. case reflect.Ptr, reflect.Interface:
  1384. v = v.Elem()
  1385. k = v.Kind()
  1386. fallthrough
  1387. case reflect.Slice, reflect.Array:
  1388. sliceranger := pool_sliceRanger.Get().(*sliceRanger)
  1389. sliceranger.i = -1
  1390. sliceranger.len = v.Len()
  1391. sliceranger.v = v
  1392. return sliceranger
  1393. case reflect.Map:
  1394. mapranger := pool_mapRanger.Get().(*mapRanger)
  1395. *mapranger = mapRanger{v: v, keys: v.MapKeys(), len: v.Len()}
  1396. return mapranger
  1397. case reflect.Chan:
  1398. chanranger := pool_chanRanger.Get().(*chanRanger)
  1399. *chanranger = chanRanger{v: v}
  1400. return chanranger
  1401. }
  1402. panic(fmt.Errorf("type %s is not rangeable", tuP))
  1403. }
  1404. var (
  1405. pool_sliceRanger = sync.Pool{
  1406. New: func() interface{} {
  1407. return new(sliceRanger)
  1408. },
  1409. }
  1410. pool_mapRanger = sync.Pool{
  1411. New: func() interface{} {
  1412. return new(mapRanger)
  1413. },
  1414. }
  1415. pool_chanRanger = sync.Pool{
  1416. New: func() interface{} {
  1417. return new(chanRanger)
  1418. },
  1419. }
  1420. )
  1421. type sliceRanger struct {
  1422. v reflect.Value
  1423. len int
  1424. i int
  1425. }
  1426. func (s *sliceRanger) Range() (index, value reflect.Value, end bool) {
  1427. s.i++
  1428. index = reflect.ValueOf(&s.i).Elem()
  1429. if s.i < s.len {
  1430. value = s.v.Index(s.i)
  1431. return
  1432. }
  1433. pool_sliceRanger.Put(s)
  1434. end = true
  1435. return
  1436. }
  1437. type chanRanger struct {
  1438. v reflect.Value
  1439. }
  1440. func (s *chanRanger) Range() (_, value reflect.Value, end bool) {
  1441. value, end = s.v.Recv()
  1442. if end {
  1443. pool_chanRanger.Put(s)
  1444. }
  1445. return
  1446. }
  1447. type mapRanger struct {
  1448. v reflect.Value
  1449. keys []reflect.Value
  1450. len int
  1451. i int
  1452. }
  1453. func (s *mapRanger) Range() (index, value reflect.Value, end bool) {
  1454. if s.i < s.len {
  1455. index = s.keys[s.i]
  1456. value = s.v.MapIndex(index)
  1457. s.i++
  1458. return
  1459. }
  1460. end = true
  1461. pool_mapRanger.Put(s)
  1462. return
  1463. }