eval.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  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. "bytes"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "reflect"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "github.com/CloudyKit/fastprinter"
  26. )
  27. var (
  28. funcType = reflect.TypeOf(Func(nil))
  29. stringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
  30. rangerType = reflect.TypeOf((*Ranger)(nil)).Elem()
  31. rendererType = reflect.TypeOf((*Renderer)(nil)).Elem()
  32. safeWriterType = reflect.TypeOf(SafeWriter(nil))
  33. pool_State = sync.Pool{
  34. New: func() interface{} {
  35. return &Runtime{scope: &scope{}, escapeeWriter: new(escapeeWriter)}
  36. },
  37. }
  38. )
  39. // Renderer is used to detect if a value has its own rendering logic. If the value an action evaluates to implements this
  40. // interface, it will not be printed using github.com/CloudyKit/fastprinter, instead, its Render() method will be called
  41. // and is responsible for writing the value to the render output.
  42. type Renderer interface {
  43. Render(*Runtime)
  44. }
  45. // RendererFunc func implementing interface Renderer
  46. type RendererFunc func(*Runtime)
  47. func (renderer RendererFunc) Render(r *Runtime) {
  48. renderer(r)
  49. }
  50. type escapeeWriter struct {
  51. Writer io.Writer
  52. escapee SafeWriter
  53. set *Set
  54. }
  55. func (w *escapeeWriter) Write(b []byte) (int, error) {
  56. if w.set.escapee == nil {
  57. w.Writer.Write(b)
  58. } else {
  59. w.set.escapee(w.Writer, b)
  60. }
  61. return 0, nil
  62. }
  63. // Runtime this type holds the state of the execution of an template
  64. type Runtime struct {
  65. *escapeeWriter
  66. *scope
  67. content func(*Runtime, Expression)
  68. translator Translator
  69. context reflect.Value
  70. }
  71. // Context returns the current context value
  72. func (r *Runtime) Context() reflect.Value {
  73. return r.context
  74. }
  75. func (st *Runtime) newScope() {
  76. st.scope = &scope{parent: st.scope, variables: make(VarMap), blocks: st.blocks}
  77. }
  78. func (st *Runtime) releaseScope() {
  79. st.scope = st.scope.parent
  80. }
  81. type scope struct {
  82. parent *scope
  83. variables VarMap
  84. blocks map[string]*BlockNode
  85. }
  86. // YieldBlock yields a block in the current context, will panic if the context is not available
  87. func (st *Runtime) YieldBlock(name string, context interface{}) {
  88. block, has := st.getBlock(name)
  89. if has == false {
  90. panic(fmt.Errorf("Block %q was not found!!", name))
  91. }
  92. if context != nil {
  93. current := st.context
  94. st.context = reflect.ValueOf(context)
  95. st.executeList(block.List)
  96. st.context = current
  97. }
  98. st.executeList(block.List)
  99. }
  100. func (st *scope) getBlock(name string) (block *BlockNode, has bool) {
  101. block, has = st.blocks[name]
  102. for !has && st.parent != nil {
  103. st = st.parent
  104. block, has = st.blocks[name]
  105. }
  106. return
  107. }
  108. func (state *Runtime) setValue(name string, val reflect.Value) error {
  109. // try changing existing variable in current or parent scope
  110. sc := state.scope
  111. for sc != nil {
  112. if _, ok := sc.variables[name]; ok {
  113. sc.variables[name] = val
  114. return nil
  115. }
  116. sc = sc.parent
  117. }
  118. return fmt.Errorf("could not assign %q = %v because variable %q is uninitialised", name, val, name)
  119. }
  120. // LetGlobal sets or initialises a variable in the top-most template scope.
  121. func (state *Runtime) LetGlobal(name string, val interface{}) {
  122. sc := state.scope
  123. // walk up to top-most valid scope
  124. for sc.parent != nil && sc.parent.variables != nil {
  125. sc = sc.parent
  126. }
  127. sc.variables[name] = reflect.ValueOf(val)
  128. }
  129. // Set sets an existing variable in the template scope it lives in.
  130. func (state *Runtime) Set(name string, val interface{}) error {
  131. return state.setValue(name, reflect.ValueOf(val))
  132. }
  133. // Let initialises a variable in the current template scope (possibly shadowing an existing variable of the same name in a parent scope).
  134. func (state *Runtime) Let(name string, val interface{}) {
  135. state.scope.variables[name] = reflect.ValueOf(val)
  136. }
  137. // SetOrLet calls Set() (if a variable with the given name is visible from the current scope) or Let() (if there is no variable with the given name in the current or any parent scope).
  138. func (state *Runtime) SetOrLet(name string, val interface{}) {
  139. _, err := state.resolve(name)
  140. if err != nil {
  141. state.Let(name, val)
  142. } else {
  143. state.Set(name, val)
  144. }
  145. }
  146. // Resolve resolves a value from the execution context.
  147. func (state *Runtime) resolve(name string) (reflect.Value, error) {
  148. if name == "." {
  149. return state.context, nil
  150. }
  151. // try current, then parent variable scopes
  152. sc := state.scope
  153. for sc != nil {
  154. v, ok := sc.variables[name]
  155. if ok {
  156. return indirectEface(v), nil
  157. }
  158. sc = sc.parent
  159. }
  160. // try globals
  161. state.set.gmx.RLock()
  162. v, ok := state.set.globals[name]
  163. state.set.gmx.RUnlock()
  164. if ok {
  165. return indirectEface(v), nil
  166. }
  167. // try default variables
  168. v, ok = defaultVariables[name]
  169. if ok {
  170. return indirectEface(v), nil
  171. }
  172. return reflect.Value{}, fmt.Errorf("identifier %q not available in current (%+v) or parent scope, global, or default variables", name, state.scope.variables)
  173. }
  174. // Resolve calls resolve() and ignores any errors, meaning it may return a zero reflect.Value.
  175. func (state *Runtime) Resolve(name string) reflect.Value {
  176. v, _ := state.resolve(name)
  177. return v
  178. }
  179. // Resolve calls resolve() and panics if there is an error.
  180. func (state *Runtime) MustResolve(name string) reflect.Value {
  181. v, err := state.resolve(name)
  182. if err != nil {
  183. panic(err)
  184. }
  185. return v
  186. }
  187. func (st *Runtime) recover(err *error) {
  188. // reset state scope and context just to be safe (they might not be cleared properly if there was a panic while using the state)
  189. st.scope = &scope{}
  190. st.context = reflect.Value{}
  191. pool_State.Put(st)
  192. if recovered := recover(); recovered != nil {
  193. var ok bool
  194. if _, ok = recovered.(runtime.Error); ok {
  195. panic(recovered)
  196. }
  197. *err, ok = recovered.(error)
  198. if !ok {
  199. panic(recovered)
  200. }
  201. }
  202. }
  203. func (st *Runtime) executeSet(left Expression, right reflect.Value) {
  204. typ := left.Type()
  205. if typ == NodeIdentifier {
  206. err := st.setValue(left.(*IdentifierNode).Ident, right)
  207. if err != nil {
  208. left.error(err)
  209. }
  210. return
  211. }
  212. var value reflect.Value
  213. var fields []string
  214. if typ == NodeChain {
  215. chain := left.(*ChainNode)
  216. value = st.evalPrimaryExpressionGroup(chain.Node)
  217. fields = chain.Field
  218. } else {
  219. fields = left.(*FieldNode).Ident
  220. value = st.context
  221. }
  222. lef := len(fields) - 1
  223. for i := 0; i < lef; i++ {
  224. var err error
  225. value, err = resolveIndex(value, reflect.ValueOf(fields[i]))
  226. if err != nil {
  227. left.errorf("%v", err)
  228. }
  229. }
  230. RESTART:
  231. switch value.Kind() {
  232. case reflect.Ptr:
  233. value = value.Elem()
  234. goto RESTART
  235. case reflect.Struct:
  236. value = value.FieldByName(fields[lef])
  237. if !value.IsValid() {
  238. left.errorf("identifier %q is not available in the current scope", fields[lef])
  239. }
  240. value.Set(right)
  241. case reflect.Map:
  242. value.SetMapIndex(reflect.ValueOf(&fields[lef]).Elem(), right)
  243. }
  244. }
  245. func (st *Runtime) executeSetList(set *SetNode) {
  246. if set.IndexExprGetLookup {
  247. value := st.evalPrimaryExpressionGroup(set.Right[0])
  248. st.executeSet(set.Left[0], value)
  249. if value.IsValid() {
  250. st.executeSet(set.Left[1], valueBoolTRUE)
  251. } else {
  252. st.executeSet(set.Left[1], valueBoolFALSE)
  253. }
  254. } else {
  255. for i := 0; i < len(set.Left); i++ {
  256. st.executeSet(set.Left[i], st.evalPrimaryExpressionGroup(set.Right[i]))
  257. }
  258. }
  259. }
  260. func (st *Runtime) executeLetList(set *SetNode) {
  261. if set.IndexExprGetLookup {
  262. value := st.evalPrimaryExpressionGroup(set.Right[0])
  263. st.variables[set.Left[0].(*IdentifierNode).Ident] = value
  264. if value.IsValid() {
  265. st.variables[set.Left[1].(*IdentifierNode).Ident] = valueBoolTRUE
  266. } else {
  267. st.variables[set.Left[1].(*IdentifierNode).Ident] = valueBoolFALSE
  268. }
  269. } else {
  270. for i := 0; i < len(set.Left); i++ {
  271. st.variables[set.Left[i].(*IdentifierNode).Ident] = st.evalPrimaryExpressionGroup(set.Right[i])
  272. }
  273. }
  274. }
  275. func (st *Runtime) executeYieldBlock(block *BlockNode, blockParam, yieldParam *BlockParameterList, expression Expression, content *ListNode) {
  276. needNewScope := len(blockParam.List) > 0 || len(yieldParam.List) > 0
  277. if needNewScope {
  278. st.newScope()
  279. for i := 0; i < len(yieldParam.List); i++ {
  280. p := &yieldParam.List[i]
  281. if p.Expression == nil {
  282. block.errorf("missing name for block parameter '%s'", blockParam.List[i].Identifier)
  283. }
  284. st.variables[p.Identifier] = st.evalPrimaryExpressionGroup(p.Expression)
  285. }
  286. for i := 0; i < len(blockParam.List); i++ {
  287. p := &blockParam.List[i]
  288. if _, found := st.variables[p.Identifier]; !found {
  289. if p.Expression == nil {
  290. st.variables[p.Identifier] = valueBoolFALSE
  291. } else {
  292. st.variables[p.Identifier] = st.evalPrimaryExpressionGroup(p.Expression)
  293. }
  294. }
  295. }
  296. }
  297. mycontent := st.content
  298. if content != nil {
  299. myscope := st.scope
  300. st.content = func(st *Runtime, expression Expression) {
  301. outscope := st.scope
  302. outcontent := st.content
  303. st.scope = myscope
  304. st.content = mycontent
  305. if expression != nil {
  306. context := st.context
  307. st.context = st.evalPrimaryExpressionGroup(expression)
  308. st.executeList(content)
  309. st.context = context
  310. } else {
  311. st.executeList(content)
  312. }
  313. st.scope = outscope
  314. st.content = outcontent
  315. }
  316. }
  317. if expression != nil {
  318. context := st.context
  319. st.context = st.evalPrimaryExpressionGroup(expression)
  320. st.executeList(block.List)
  321. st.context = context
  322. } else {
  323. st.executeList(block.List)
  324. }
  325. st.content = mycontent
  326. if needNewScope {
  327. st.releaseScope()
  328. }
  329. }
  330. func (st *Runtime) executeList(list *ListNode) (returnValue reflect.Value) {
  331. inNewScope := false // to use just one scope for multiple actions with variable declarations
  332. for i := 0; i < len(list.Nodes); i++ {
  333. node := list.Nodes[i]
  334. switch node.Type() {
  335. case NodeText:
  336. node := node.(*TextNode)
  337. _, err := st.Writer.Write(node.Text)
  338. if err != nil {
  339. node.error(err)
  340. }
  341. case NodeAction:
  342. node := node.(*ActionNode)
  343. if node.Set != nil {
  344. if node.Set.Let {
  345. if !inNewScope {
  346. st.newScope()
  347. inNewScope = true
  348. defer st.releaseScope()
  349. }
  350. st.executeLetList(node.Set)
  351. } else {
  352. st.executeSetList(node.Set)
  353. }
  354. }
  355. if node.Pipe != nil {
  356. v, safeWriter := st.evalPipelineExpression(node.Pipe)
  357. if !safeWriter && v.IsValid() {
  358. if v.Type().Implements(rendererType) {
  359. v.Interface().(Renderer).Render(st)
  360. } else {
  361. _, err := fastprinter.PrintValue(st.escapeeWriter, v)
  362. if err != nil {
  363. node.error(err)
  364. }
  365. }
  366. }
  367. }
  368. case NodeIf:
  369. node := node.(*IfNode)
  370. var isLet bool
  371. if node.Set != nil {
  372. if node.Set.Let {
  373. isLet = true
  374. st.newScope()
  375. st.executeLetList(node.Set)
  376. } else {
  377. st.executeSetList(node.Set)
  378. }
  379. }
  380. if isTrue(st.evalPrimaryExpressionGroup(node.Expression)) {
  381. returnValue = st.executeList(node.List)
  382. } else if node.ElseList != nil {
  383. returnValue = st.executeList(node.ElseList)
  384. }
  385. if isLet {
  386. st.releaseScope()
  387. }
  388. case NodeRange:
  389. node := node.(*RangeNode)
  390. var expression reflect.Value
  391. isSet := node.Set != nil
  392. isLet := false
  393. keyVarSlot := 0
  394. valVarSlot := -1
  395. context := st.context
  396. if isSet {
  397. if len(node.Set.Left) > 1 {
  398. valVarSlot = 1
  399. }
  400. expression = st.evalPrimaryExpressionGroup(node.Set.Right[0])
  401. if node.Set.Let {
  402. isLet = true
  403. st.newScope()
  404. }
  405. } else {
  406. expression = st.evalPrimaryExpressionGroup(node.Expression)
  407. }
  408. ranger, cleanup := getRanger(expression)
  409. if !ranger.ProvidesIndex() {
  410. if len(node.Set.Left) > 1 {
  411. // two-vars assignment with ranger that doesn't provide an index
  412. node.error(errors.New("two-var range over ranger that does not provide an index"))
  413. }
  414. keyVarSlot, valVarSlot = -1, 0
  415. }
  416. indexValue, rangeValue, end := ranger.Range()
  417. if !end {
  418. for !end && !returnValue.IsValid() {
  419. if isSet {
  420. if isLet {
  421. if keyVarSlot >= 0 {
  422. st.variables[node.Set.Left[keyVarSlot].String()] = indexValue
  423. }
  424. if valVarSlot >= 0 {
  425. st.variables[node.Set.Left[valVarSlot].String()] = rangeValue
  426. }
  427. } else {
  428. if keyVarSlot >= 0 {
  429. st.executeSet(node.Set.Left[keyVarSlot], indexValue)
  430. }
  431. if valVarSlot >= 0 {
  432. st.executeSet(node.Set.Left[valVarSlot], rangeValue)
  433. }
  434. }
  435. }
  436. if valVarSlot < 0 {
  437. st.context = rangeValue
  438. }
  439. returnValue = st.executeList(node.List)
  440. indexValue, rangeValue, end = ranger.Range()
  441. }
  442. } else if node.ElseList != nil {
  443. returnValue = st.executeList(node.ElseList)
  444. }
  445. cleanup()
  446. st.context = context
  447. if isLet {
  448. st.releaseScope()
  449. }
  450. case NodeTry:
  451. node := node.(*TryNode)
  452. returnValue = st.executeTry(node)
  453. case NodeYield:
  454. node := node.(*YieldNode)
  455. if node.IsContent {
  456. if st.content != nil {
  457. st.content(st, node.Expression)
  458. }
  459. } else {
  460. block, has := st.getBlock(node.Name)
  461. if has == false || block == nil {
  462. node.errorf("unresolved block %q!!", node.Name)
  463. }
  464. st.executeYieldBlock(block, block.Parameters, node.Parameters, node.Expression, node.Content)
  465. }
  466. case NodeBlock:
  467. node := node.(*BlockNode)
  468. block, has := st.getBlock(node.Name)
  469. if has == false {
  470. block = node
  471. }
  472. st.executeYieldBlock(block, block.Parameters, block.Parameters, block.Expression, block.Content)
  473. case NodeInclude:
  474. node := node.(*IncludeNode)
  475. returnValue = st.executeInclude(node)
  476. case NodeReturn:
  477. node := node.(*ReturnNode)
  478. returnValue = st.evalPrimaryExpressionGroup(node.Value)
  479. }
  480. }
  481. return returnValue
  482. }
  483. func (st *Runtime) executeTry(try *TryNode) (returnValue reflect.Value) {
  484. writer := st.Writer
  485. buf := new(bytes.Buffer)
  486. defer func() {
  487. r := recover()
  488. // copy buffered render output to writer only if no panic occured
  489. if r == nil {
  490. io.Copy(writer, buf)
  491. } else {
  492. // st.Writer is already set to its original value since the later defer ran first
  493. if try.Catch != nil {
  494. if try.Catch.Err != nil {
  495. st.newScope()
  496. st.scope.variables[try.Catch.Err.Ident] = reflect.ValueOf(r)
  497. }
  498. if try.Catch.List != nil {
  499. returnValue = st.executeList(try.Catch.List)
  500. }
  501. if try.Catch.Err != nil {
  502. st.releaseScope()
  503. }
  504. }
  505. }
  506. }()
  507. st.Writer = buf
  508. defer func() { st.Writer = writer }()
  509. return st.executeList(try.List)
  510. }
  511. func (st *Runtime) executeInclude(node *IncludeNode) (returnValue reflect.Value) {
  512. var templatePath string
  513. name := st.evalPrimaryExpressionGroup(node.Name)
  514. if name.Type().Implements(stringerType) {
  515. templatePath = name.String()
  516. } else if name.Kind() == reflect.String {
  517. templatePath = name.String()
  518. } else {
  519. node.errorf("evaluating name of template to include: unexpected expression type %q", getTypeString(name))
  520. }
  521. t, err := st.set.getSiblingTemplate(templatePath, node.TemplatePath)
  522. if err != nil {
  523. node.error(err)
  524. return reflect.Value{}
  525. }
  526. st.newScope()
  527. defer st.releaseScope()
  528. st.blocks = t.processedBlocks
  529. var context reflect.Value
  530. if node.Context != nil {
  531. context = st.context
  532. defer func() { st.context = context }()
  533. st.context = st.evalPrimaryExpressionGroup(node.Context)
  534. }
  535. Root := t.Root
  536. for t.extends != nil {
  537. t = t.extends
  538. Root = t.Root
  539. }
  540. return st.executeList(Root)
  541. }
  542. var (
  543. valueBoolTRUE = reflect.ValueOf(true)
  544. valueBoolFALSE = reflect.ValueOf(false)
  545. )
  546. func (st *Runtime) evalPrimaryExpressionGroup(node Expression) reflect.Value {
  547. switch node.Type() {
  548. case NodeAdditiveExpr:
  549. return st.evalAdditiveExpression(node.(*AdditiveExprNode))
  550. case NodeMultiplicativeExpr:
  551. return st.evalMultiplicativeExpression(node.(*MultiplicativeExprNode))
  552. case NodeComparativeExpr:
  553. return st.evalComparativeExpression(node.(*ComparativeExprNode))
  554. case NodeNumericComparativeExpr:
  555. return st.evalNumericComparativeExpression(node.(*NumericComparativeExprNode))
  556. case NodeLogicalExpr:
  557. return st.evalLogicalExpression(node.(*LogicalExprNode))
  558. case NodeNotExpr:
  559. return reflect.ValueOf(!isTrue(st.evalPrimaryExpressionGroup(node.(*NotExprNode).Expr)))
  560. case NodeTernaryExpr:
  561. node := node.(*TernaryExprNode)
  562. if isTrue(st.evalPrimaryExpressionGroup(node.Boolean)) {
  563. return st.evalPrimaryExpressionGroup(node.Left)
  564. }
  565. return st.evalPrimaryExpressionGroup(node.Right)
  566. case NodeCallExpr:
  567. node := node.(*CallExprNode)
  568. baseExpr := st.evalBaseExpressionGroup(node.BaseExpr)
  569. if baseExpr.Kind() != reflect.Func {
  570. node.errorf("node %q is not func kind %q", node.BaseExpr, baseExpr.Type())
  571. }
  572. return st.evalCallExpression(baseExpr, node.Args)
  573. case NodeIndexExpr:
  574. node := node.(*IndexExprNode)
  575. base := st.evalPrimaryExpressionGroup(node.Base)
  576. index := st.evalPrimaryExpressionGroup(node.Index)
  577. resolved, err := resolveIndex(base, index)
  578. if err != nil {
  579. node.error(err)
  580. }
  581. return resolved
  582. case NodeSliceExpr:
  583. node := node.(*SliceExprNode)
  584. baseExpression := st.evalPrimaryExpressionGroup(node.Base)
  585. var index, length int
  586. if node.Index != nil {
  587. indexExpression := st.evalPrimaryExpressionGroup(node.Index)
  588. if canNumber(indexExpression.Kind()) {
  589. index = int(castInt64(indexExpression))
  590. } else {
  591. node.Index.errorf("non numeric value in index expression kind %s", indexExpression.Kind().String())
  592. }
  593. }
  594. if node.EndIndex != nil {
  595. indexExpression := st.evalPrimaryExpressionGroup(node.EndIndex)
  596. if canNumber(indexExpression.Kind()) {
  597. length = int(castInt64(indexExpression))
  598. } else {
  599. node.EndIndex.errorf("non numeric value in index expression kind %s", indexExpression.Kind().String())
  600. }
  601. } else {
  602. length = baseExpression.Len()
  603. }
  604. return baseExpression.Slice(index, length)
  605. }
  606. return st.evalBaseExpressionGroup(node)
  607. }
  608. // notNil returns false when v.IsValid() == false
  609. // or when v's kind can be nil and v.IsNil() == true
  610. func notNil(v reflect.Value) bool {
  611. if !v.IsValid() {
  612. return false
  613. }
  614. switch v.Kind() {
  615. case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  616. return !v.IsNil()
  617. default:
  618. return true
  619. }
  620. }
  621. func (st *Runtime) isSet(node Node) (ok bool) {
  622. defer func() {
  623. if r := recover(); r != nil {
  624. // something panicked while evaluating node
  625. ok = false
  626. }
  627. }()
  628. nodeType := node.Type()
  629. switch nodeType {
  630. case NodeIndexExpr:
  631. node := node.(*IndexExprNode)
  632. if !st.isSet(node.Base) || !st.isSet(node.Index) {
  633. return false
  634. }
  635. base := st.evalPrimaryExpressionGroup(node.Base)
  636. index := st.evalPrimaryExpressionGroup(node.Index)
  637. resolved, err := resolveIndex(base, index)
  638. return err == nil && notNil(resolved)
  639. case NodeIdentifier:
  640. value, err := st.resolve(node.String())
  641. return err == nil && notNil(value)
  642. case NodeField:
  643. node := node.(*FieldNode)
  644. resolved := st.context
  645. for i := 0; i < len(node.Ident); i++ {
  646. var err error
  647. resolved, err = resolveIndex(resolved, reflect.ValueOf(node.Ident[i]))
  648. if err != nil || !notNil(resolved) {
  649. return false
  650. }
  651. }
  652. case NodeChain:
  653. node := node.(*ChainNode)
  654. resolved, err := st.evalChainNodeExpression(node)
  655. return err == nil && notNil(resolved)
  656. default:
  657. //todo: maybe work some edge cases
  658. if !(nodeType > beginExpressions && nodeType < endExpressions) {
  659. node.errorf("unexpected %q node in isset clause", node)
  660. }
  661. }
  662. return true
  663. }
  664. func (st *Runtime) evalNumericComparativeExpression(node *NumericComparativeExprNode) reflect.Value {
  665. left, right := st.evalPrimaryExpressionGroup(node.Left), st.evalPrimaryExpressionGroup(node.Right)
  666. isTrue := false
  667. kind := left.Kind()
  668. // 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
  669. // this is necessary for expressions like 4*1.23
  670. needFloatPromotion := !isFloat(kind) && isFloat(right.Kind())
  671. switch node.Operator.typ {
  672. case itemGreat:
  673. if isInt(kind) {
  674. if needFloatPromotion {
  675. isTrue = float64(left.Int()) > right.Float()
  676. } else {
  677. isTrue = left.Int() > toInt(right)
  678. }
  679. } else if isFloat(kind) {
  680. isTrue = left.Float() > toFloat(right)
  681. } else if isUint(kind) {
  682. if needFloatPromotion {
  683. isTrue = float64(left.Uint()) > right.Float()
  684. } else {
  685. isTrue = left.Uint() > toUint(right)
  686. }
  687. } else {
  688. node.Left.errorf("a non numeric value in numeric comparative expression")
  689. }
  690. case itemGreatEquals:
  691. if isInt(kind) {
  692. if needFloatPromotion {
  693. isTrue = float64(left.Int()) >= right.Float()
  694. } else {
  695. isTrue = left.Int() >= toInt(right)
  696. }
  697. } else if isFloat(kind) {
  698. isTrue = left.Float() >= toFloat(right)
  699. } else if isUint(kind) {
  700. if needFloatPromotion {
  701. isTrue = float64(left.Uint()) >= right.Float()
  702. } else {
  703. isTrue = left.Uint() >= toUint(right)
  704. }
  705. } else {
  706. node.Left.errorf("a non numeric value in numeric comparative expression")
  707. }
  708. case itemLess:
  709. if isInt(kind) {
  710. if needFloatPromotion {
  711. isTrue = float64(left.Int()) < right.Float()
  712. } else {
  713. isTrue = left.Int() < toInt(right)
  714. }
  715. } else if isFloat(kind) {
  716. isTrue = left.Float() < toFloat(right)
  717. } else if isUint(kind) {
  718. if needFloatPromotion {
  719. isTrue = float64(left.Uint()) < right.Float()
  720. } else {
  721. isTrue = left.Uint() < toUint(right)
  722. }
  723. } else {
  724. node.Left.errorf("a non numeric value in numeric comparative expression")
  725. }
  726. case itemLessEquals:
  727. if isInt(kind) {
  728. if needFloatPromotion {
  729. isTrue = float64(left.Int()) <= right.Float()
  730. } else {
  731. isTrue = left.Int() <= toInt(right)
  732. }
  733. } else if isFloat(kind) {
  734. isTrue = left.Float() <= toFloat(right)
  735. } else if isUint(kind) {
  736. if needFloatPromotion {
  737. isTrue = float64(left.Uint()) <= right.Float()
  738. } else {
  739. isTrue = left.Uint() <= toUint(right)
  740. }
  741. } else {
  742. node.Left.errorf("a non numeric value in numeric comparative expression")
  743. }
  744. }
  745. return reflect.ValueOf(isTrue)
  746. }
  747. func (st *Runtime) evalLogicalExpression(node *LogicalExprNode) reflect.Value {
  748. truthy := isTrue(st.evalPrimaryExpressionGroup(node.Left))
  749. if node.Operator.typ == itemAnd {
  750. truthy = truthy && isTrue(st.evalPrimaryExpressionGroup(node.Right))
  751. } else {
  752. truthy = truthy || isTrue(st.evalPrimaryExpressionGroup(node.Right))
  753. }
  754. return reflect.ValueOf(truthy)
  755. }
  756. func (st *Runtime) evalComparativeExpression(node *ComparativeExprNode) reflect.Value {
  757. left, right := st.evalPrimaryExpressionGroup(node.Left), st.evalPrimaryExpressionGroup(node.Right)
  758. equal := checkEquality(left, right)
  759. if node.Operator.typ == itemNotEquals {
  760. return reflect.ValueOf(!equal)
  761. }
  762. return reflect.ValueOf(equal)
  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. if isInt(kind) {
  895. if isAdditive {
  896. return reflect.ValueOf(+right.Int())
  897. } else {
  898. return reflect.ValueOf(-right.Int())
  899. }
  900. } else if isUint(kind) {
  901. if isAdditive {
  902. return right
  903. } else {
  904. return reflect.ValueOf(-int64(right.Uint()))
  905. }
  906. } else if isFloat(kind) {
  907. if isAdditive {
  908. return reflect.ValueOf(+right.Float())
  909. } else {
  910. return reflect.ValueOf(-right.Float())
  911. }
  912. }
  913. node.Left.errorf("additive expression: right side %s (%s) is not a numeric value (no left side)", node.Right, getTypeString(right))
  914. }
  915. left, right := st.evalPrimaryExpressionGroup(node.Left), st.evalPrimaryExpressionGroup(node.Right)
  916. kind := left.Kind()
  917. // 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
  918. // this is necessary for expressions like 4+1.23
  919. needFloatPromotion := !isFloat(kind) && kind != reflect.String && isFloat(right.Kind())
  920. if needFloatPromotion {
  921. if isInt(kind) {
  922. if isAdditive {
  923. left = reflect.ValueOf(float64(left.Int()) + right.Float())
  924. } else {
  925. left = reflect.ValueOf(float64(left.Int()) - right.Float())
  926. }
  927. } else if isUint(kind) {
  928. if isAdditive {
  929. left = reflect.ValueOf(float64(left.Uint()) + right.Float())
  930. } else {
  931. left = reflect.ValueOf(float64(left.Uint()) - right.Float())
  932. }
  933. } else {
  934. node.Left.errorf("additive expression: left side (%s (%s) needs float promotion but neither int nor uint)", node.Left, getTypeString(left))
  935. }
  936. } else {
  937. if isInt(kind) {
  938. if isAdditive {
  939. left = reflect.ValueOf(left.Int() + toInt(right))
  940. } else {
  941. left = reflect.ValueOf(left.Int() - toInt(right))
  942. }
  943. } else if isFloat(kind) {
  944. if isAdditive {
  945. left = reflect.ValueOf(left.Float() + toFloat(right))
  946. } else {
  947. left = reflect.ValueOf(left.Float() - toFloat(right))
  948. }
  949. } else if isUint(kind) {
  950. if isAdditive {
  951. left = reflect.ValueOf(left.Uint() + toUint(right))
  952. } else {
  953. left = reflect.ValueOf(left.Uint() - toUint(right))
  954. }
  955. } else if kind == reflect.String {
  956. if !isAdditive {
  957. node.Right.errorf("minus signal is not allowed with strings")
  958. }
  959. // converts []byte (and alias types of []byte) to string
  960. if right.Kind() == reflect.Slice && right.Type().Elem().Kind() == reflect.Uint8 {
  961. right = right.Convert(left.Type())
  962. }
  963. left = reflect.ValueOf(left.String() + fmt.Sprint(right))
  964. } else {
  965. node.Left.errorf("additive expression: left side %s (%s) is not a numeric value", node.Left, getTypeString(left))
  966. }
  967. }
  968. return left
  969. }
  970. func getTypeString(value reflect.Value) string {
  971. if value.IsValid() {
  972. return value.Type().String()
  973. }
  974. return "<invalid>"
  975. }
  976. func (st *Runtime) evalBaseExpressionGroup(node Node) reflect.Value {
  977. switch node.Type() {
  978. case NodeNil:
  979. return reflect.ValueOf(nil)
  980. case NodeBool:
  981. if node.(*BoolNode).True {
  982. return valueBoolTRUE
  983. }
  984. return valueBoolFALSE
  985. case NodeString:
  986. return reflect.ValueOf(&node.(*StringNode).Text).Elem()
  987. case NodeIdentifier:
  988. resolved, err := st.resolve(node.(*IdentifierNode).Ident)
  989. if err != nil {
  990. node.error(err)
  991. }
  992. return resolved
  993. case NodeField:
  994. node := node.(*FieldNode)
  995. resolved := st.context
  996. for i := 0; i < len(node.Ident); i++ {
  997. field, err := resolveIndex(resolved, reflect.ValueOf(node.Ident[i]))
  998. if err != nil {
  999. node.errorf("%v", err)
  1000. }
  1001. if !field.IsValid() {
  1002. node.errorf("there is no field or method '%s' in %s (.%s)", node.Ident[i], getTypeString(resolved), strings.Join(node.Ident, "."))
  1003. }
  1004. resolved = field
  1005. }
  1006. return resolved
  1007. case NodeChain:
  1008. resolved, err := st.evalChainNodeExpression(node.(*ChainNode))
  1009. if err != nil {
  1010. node.error(err)
  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.Args != nil {
  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. func (st *Runtime) evalChainNodeExpression(node *ChainNode) (reflect.Value, error) {
  1060. resolved := st.evalPrimaryExpressionGroup(node.Node)
  1061. for i := 0; i < len(node.Field); i++ {
  1062. field, err := resolveIndex(resolved, reflect.ValueOf(node.Field[i]))
  1063. if err != nil {
  1064. return reflect.Value{}, err
  1065. }
  1066. if !field.IsValid() {
  1067. if resolved.Kind() == reflect.Map && i == len(node.Field)-1 {
  1068. // return reflect.Zero(resolved.Type().Elem()), nil
  1069. return reflect.Value{}, nil
  1070. }
  1071. return reflect.Value{}, fmt.Errorf("there is no field or method '%s' in %s (%s)", node.Field[i], getTypeString(resolved), node)
  1072. }
  1073. resolved = field
  1074. }
  1075. return resolved, nil
  1076. }
  1077. type escapeWriter struct {
  1078. rawWriter io.Writer
  1079. safeWriter SafeWriter
  1080. }
  1081. func (w *escapeWriter) Write(b []byte) (int, error) {
  1082. w.safeWriter(w.rawWriter, b)
  1083. return 0, nil
  1084. }
  1085. func (st *Runtime) evalSafeWriter(term reflect.Value, node *CommandNode, v ...reflect.Value) {
  1086. sw := &escapeWriter{rawWriter: st.Writer, safeWriter: term.Interface().(SafeWriter)}
  1087. for i := 0; i < len(v); i++ {
  1088. fastprinter.PrintValue(sw, v[i])
  1089. }
  1090. for i := 0; i < len(node.Args); i++ {
  1091. fastprinter.PrintValue(sw, st.evalPrimaryExpressionGroup(node.Args[i]))
  1092. }
  1093. }
  1094. func (st *Runtime) evalCommandPipeExpression(node *CommandNode, value reflect.Value) (reflect.Value, bool) {
  1095. term := st.evalPrimaryExpressionGroup(node.BaseExpr)
  1096. if term.Kind() == reflect.Func {
  1097. if term.Type() == safeWriterType {
  1098. st.evalSafeWriter(term, node, value)
  1099. return reflect.Value{}, true
  1100. }
  1101. return st.evalCallExpression(term, node.Args, value), false
  1102. } else {
  1103. node.BaseExpr.errorf("pipe command %q type %s is not func", node.BaseExpr, term.Type())
  1104. }
  1105. return term, false
  1106. }
  1107. func (st *Runtime) evalPipelineExpression(node *PipeNode) (value reflect.Value, safeWriter bool) {
  1108. value, safeWriter = st.evalCommandExpression(node.Cmds[0])
  1109. for i := 1; i < len(node.Cmds); i++ {
  1110. if safeWriter {
  1111. node.Cmds[i].errorf("unexpected command %s, writer command should be the last command", node.Cmds[i])
  1112. }
  1113. value, safeWriter = st.evalCommandPipeExpression(node.Cmds[i], value)
  1114. }
  1115. return
  1116. }
  1117. func reflect_Call(arguments []reflect.Value, st *Runtime, fn reflect.Value, args []Expression, values ...reflect.Value) []reflect.Value {
  1118. typ := fn.Type()
  1119. numIn := typ.NumIn()
  1120. isVariadic := typ.IsVariadic()
  1121. if isVariadic {
  1122. numIn--
  1123. }
  1124. i, j := 0, 0
  1125. for ; i < numIn && i < len(values); i++ {
  1126. in := typ.In(i)
  1127. term := values[i]
  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 ; i < len(values); i++ {
  1136. term := values[i]
  1137. if !term.Type().AssignableTo(in) {
  1138. term = term.Convert(in)
  1139. }
  1140. arguments[i] = term
  1141. }
  1142. }
  1143. for ; i < numIn && j < len(args); i, j = i+1, j+1 {
  1144. in := typ.In(i)
  1145. term := st.evalPrimaryExpressionGroup(args[j])
  1146. if !term.Type().AssignableTo(in) {
  1147. term = term.Convert(in)
  1148. }
  1149. arguments[i] = term
  1150. }
  1151. if isVariadic {
  1152. in := typ.In(numIn).Elem()
  1153. for ; j < len(args); i, j = i+1, j+1 {
  1154. term := st.evalPrimaryExpressionGroup(args[j])
  1155. if !term.Type().AssignableTo(in) {
  1156. term = term.Convert(in)
  1157. }
  1158. arguments[i] = term
  1159. }
  1160. }
  1161. return fn.Call(arguments[0:i])
  1162. }
  1163. func reflect_Call10(i int, st *Runtime, fn reflect.Value, args []Expression, values ...reflect.Value) []reflect.Value {
  1164. var arguments [10]reflect.Value
  1165. return reflect_Call(arguments[0:i], st, fn, args, values...)
  1166. }
  1167. func isUint(kind reflect.Kind) bool {
  1168. return kind >= reflect.Uint && kind <= reflect.Uint64
  1169. }
  1170. func isInt(kind reflect.Kind) bool {
  1171. return kind >= reflect.Int && kind <= reflect.Int64
  1172. }
  1173. func isFloat(kind reflect.Kind) bool {
  1174. return kind == reflect.Float32 || kind == reflect.Float64
  1175. }
  1176. // checkEquality of two reflect values in the semantic of the jet runtime
  1177. func checkEquality(v1, v2 reflect.Value) bool {
  1178. v1 = indirectInterface(v1)
  1179. v2 = indirectInterface(v2)
  1180. if !v1.IsValid() || !v2.IsValid() {
  1181. return v1.IsValid() == v2.IsValid()
  1182. }
  1183. v1Type := v1.Type()
  1184. v2Type := v2.Type()
  1185. // fast path
  1186. if v1Type != v2Type && !v2Type.AssignableTo(v1Type) && !v2Type.ConvertibleTo(v1Type) {
  1187. return false
  1188. }
  1189. kind := v1.Kind()
  1190. if isInt(kind) {
  1191. return v1.Int() == toInt(v2)
  1192. }
  1193. if isFloat(kind) {
  1194. return v1.Float() == toFloat(v2)
  1195. }
  1196. if isUint(kind) {
  1197. return v1.Uint() == toUint(v2)
  1198. }
  1199. switch kind {
  1200. case reflect.Bool:
  1201. return v1.Bool() == isTrue(v2)
  1202. case reflect.String:
  1203. return v1.String() == v2.String()
  1204. case reflect.Array:
  1205. vlen := v1.Len()
  1206. if vlen == v2.Len() {
  1207. return false
  1208. }
  1209. for i := 0; i < vlen; i++ {
  1210. if !checkEquality(v1.Index(i), v2.Index(i)) {
  1211. return false
  1212. }
  1213. }
  1214. return true
  1215. case reflect.Slice:
  1216. if v1.IsNil() != v2.IsNil() {
  1217. return false
  1218. }
  1219. vlen := v1.Len()
  1220. if vlen != v2.Len() {
  1221. return false
  1222. }
  1223. if v1.CanAddr() && v2.CanAddr() && v1.Pointer() == v2.Pointer() {
  1224. return true
  1225. }
  1226. for i := 0; i < vlen; i++ {
  1227. if !checkEquality(v1.Index(i), v2.Index(i)) {
  1228. return false
  1229. }
  1230. }
  1231. return true
  1232. case reflect.Interface:
  1233. if v1.IsNil() || v2.IsNil() {
  1234. return v1.IsNil() == v2.IsNil()
  1235. }
  1236. return checkEquality(v1.Elem(), v2.Elem())
  1237. case reflect.Ptr:
  1238. return v1.Pointer() == v2.Pointer()
  1239. case reflect.Struct:
  1240. numField := v1.NumField()
  1241. for i, n := 0, numField; i < n; i++ {
  1242. if !checkEquality(v1.Field(i), v2.Field(i)) {
  1243. return false
  1244. }
  1245. }
  1246. return true
  1247. case reflect.Map:
  1248. if v1.IsNil() != v2.IsNil() {
  1249. return false
  1250. }
  1251. if v1.Len() != v2.Len() {
  1252. return false
  1253. }
  1254. if v1.Pointer() == v2.Pointer() {
  1255. return true
  1256. }
  1257. for _, k := range v1.MapKeys() {
  1258. val1 := v1.MapIndex(k)
  1259. val2 := v2.MapIndex(k)
  1260. if !val1.IsValid() || !val2.IsValid() || !checkEquality(v1.MapIndex(k), v2.MapIndex(k)) {
  1261. return false
  1262. }
  1263. }
  1264. return true
  1265. case reflect.Func:
  1266. return v1.IsNil() && v2.IsNil()
  1267. default:
  1268. // Normal equality suffices
  1269. return v1.Interface() == v2.Interface()
  1270. }
  1271. }
  1272. func isTrue(v reflect.Value) bool {
  1273. return v.IsValid() && !v.IsZero()
  1274. }
  1275. func canNumber(kind reflect.Kind) bool {
  1276. return isInt(kind) || isUint(kind) || isFloat(kind)
  1277. }
  1278. func castInt64(v reflect.Value) int64 {
  1279. kind := v.Kind()
  1280. switch {
  1281. case isInt(kind):
  1282. return v.Int()
  1283. case isUint(kind):
  1284. return int64(v.Uint())
  1285. case isFloat(kind):
  1286. return int64(v.Float())
  1287. }
  1288. return 0
  1289. }
  1290. var cachedStructsMutex = sync.RWMutex{}
  1291. var cachedStructsFieldIndex = map[reflect.Type]map[string][]int{}
  1292. // from text/template's exec.go:
  1293. //
  1294. // indirect returns the item at the end of indirection, and a bool to indicate
  1295. // if it's nil. If the returned bool is true, the returned value's kind will be
  1296. // either a pointer or interface.
  1297. func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
  1298. for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
  1299. if v.IsNil() {
  1300. return v, true
  1301. }
  1302. }
  1303. return v, false
  1304. }
  1305. // indirectInterface returns the concrete value in an interface value, or else v itself.
  1306. // That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
  1307. // the fact that x was an interface value is forgotten.
  1308. func indirectInterface(v reflect.Value) reflect.Value {
  1309. if v.Kind() == reflect.Interface {
  1310. return v.Elem()
  1311. }
  1312. return v
  1313. }
  1314. // indirectEface is the same as indirectInterface, but only indirects through v if its type
  1315. // is the empty interface and its value is not nil.
  1316. func indirectEface(v reflect.Value) reflect.Value {
  1317. if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 && !v.IsNil() {
  1318. return v.Elem()
  1319. }
  1320. return v
  1321. }
  1322. // mostly copied from text/template's evalField() (exec.go):
  1323. func resolveIndex(v, index reflect.Value) (reflect.Value, error) {
  1324. if !v.IsValid() {
  1325. return reflect.Value{}, fmt.Errorf("there is no field or method '%s' in %s (%s)", index, v, getTypeString(v))
  1326. }
  1327. v, isNil := indirect(v)
  1328. if v.Kind() == reflect.Interface && isNil {
  1329. // Calling a method on a nil interface can't work. The
  1330. // MethodByName method call below would panic.
  1331. return reflect.Value{}, fmt.Errorf("nil pointer evaluating %s.%s", v.Type(), index)
  1332. }
  1333. // Unless it's an interface, need to get to a value of type *T to guarantee
  1334. // we see all methods of T and *T.
  1335. if index.Kind() == reflect.String {
  1336. ptr := v
  1337. if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
  1338. ptr = ptr.Addr()
  1339. }
  1340. if method := ptr.MethodByName(index.String()); method.IsValid() {
  1341. return method, nil
  1342. }
  1343. }
  1344. // It's not a method on v; so now:
  1345. // - if v is array/slice/string, use index as numeric index
  1346. // - if v is a struct, use index as field name
  1347. // - if v is a map, use index as key
  1348. // - if v is (still) a pointer, indexing will fail but we check for nil to get a useful error
  1349. switch v.Kind() {
  1350. case reflect.Array, reflect.Slice, reflect.String:
  1351. x, err := indexArg(index, v.Len())
  1352. if err != nil {
  1353. return reflect.Value{}, err
  1354. }
  1355. return indirectEface(v.Index(x)), nil
  1356. case reflect.Struct:
  1357. if index.Kind() != reflect.String {
  1358. return reflect.Value{}, fmt.Errorf("can't use %s (%s, not string) as field name in struct type %s", index, index.Type(), v.Type())
  1359. }
  1360. tField, ok := v.Type().FieldByName(index.String())
  1361. if ok {
  1362. field := v.FieldByIndex(tField.Index)
  1363. if tField.PkgPath != "" { // field is unexported
  1364. return reflect.Value{}, fmt.Errorf("%s is an unexported field of struct type %s", index.String(), v.Type())
  1365. }
  1366. return indirectEface(field), nil
  1367. }
  1368. return reflect.Value{}, fmt.Errorf("can't use %s as field name in struct type %s", index, v.Type())
  1369. case reflect.Map:
  1370. // If it's a map, attempt to use the field name as a key.
  1371. if !index.Type().ConvertibleTo(v.Type().Key()) {
  1372. return reflect.Value{}, fmt.Errorf("can't use %s (%s) as key for map of type %s", index, index.Type(), v.Type())
  1373. }
  1374. index = index.Convert(v.Type().Key()) // noop in most cases, but not expensive
  1375. return indirectEface(v.MapIndex(index)), nil
  1376. case reflect.Ptr:
  1377. etyp := v.Type().Elem()
  1378. if etyp.Kind() == reflect.Struct && index.Kind() == reflect.String {
  1379. if _, ok := etyp.FieldByName(index.String()); !ok {
  1380. // If there's no such field, say "can't evaluate"
  1381. // instead of "nil pointer evaluating".
  1382. break
  1383. }
  1384. }
  1385. if isNil {
  1386. return reflect.Value{}, fmt.Errorf("nil pointer evaluating %s.%s", v.Type(), index)
  1387. }
  1388. }
  1389. return reflect.Value{}, fmt.Errorf("can't evaluate index %s (%s) in type %s", index, index.Type(), v.Type())
  1390. }
  1391. // from Go's text/template's funcs.go:
  1392. //
  1393. // indexArg checks if a reflect.Value can be used as an index, and converts it to int if possible.
  1394. func indexArg(index reflect.Value, cap int) (int, error) {
  1395. var x int64
  1396. switch index.Kind() {
  1397. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1398. x = index.Int()
  1399. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1400. x = int64(index.Uint())
  1401. case reflect.Float32, reflect.Float64:
  1402. x = int64(index.Float())
  1403. case reflect.Invalid:
  1404. return 0, fmt.Errorf("cannot index slice/array/string with nil")
  1405. default:
  1406. return 0, fmt.Errorf("cannot index slice/array/string with type %s", index.Type())
  1407. }
  1408. if int(x) < 0 || int(x) >= cap {
  1409. return 0, fmt.Errorf("index out of range: %d", x)
  1410. }
  1411. return int(x), nil
  1412. }
  1413. func buildCache(typ reflect.Type, cache map[string][]int, parent []int) {
  1414. numFields := typ.NumField()
  1415. max := len(parent) + 1
  1416. for i := 0; i < numFields; i++ {
  1417. index := make([]int, max)
  1418. copy(index, parent)
  1419. index[len(parent)] = i
  1420. field := typ.Field(i)
  1421. if field.Anonymous {
  1422. typ := field.Type
  1423. if typ.Kind() == reflect.Struct {
  1424. buildCache(typ, cache, index)
  1425. }
  1426. }
  1427. cache[field.Name] = index
  1428. }
  1429. }