helper.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. /*
  11. Package scope contains the block scope implementation for the event condition language ECAL.
  12. */
  13. package scope
  14. import (
  15. "fmt"
  16. "devt.de/krotik/common/stringutil"
  17. "devt.de/krotik/ecal/parser"
  18. )
  19. /*
  20. Default scope names
  21. */
  22. const (
  23. GlobalScope = "GlobalScope"
  24. FuncPrefix = "func:"
  25. )
  26. /*
  27. NameFromASTNode returns a scope name from a given ASTNode.
  28. */
  29. func NameFromASTNode(node *parser.ASTNode) string {
  30. return fmt.Sprintf("block: %v (Line:%d Pos:%d)", node.Name, node.Token.Lline, node.Token.Lpos)
  31. }
  32. /*
  33. EvalToString should be used if a value should be converted into a string.
  34. */
  35. func EvalToString(v interface{}) string {
  36. return stringutil.ConvertToString(v)
  37. }
  38. /*
  39. ToObject converts a Scope into an object.
  40. */
  41. func ToObject(vs parser.Scope) map[interface{}]interface{} {
  42. res := make(map[interface{}]interface{})
  43. for k, v := range vs.(*varsScope).storage {
  44. res[k] = v
  45. }
  46. return res
  47. }
  48. /*
  49. ToScope converts a given object into a Scope.
  50. */
  51. func ToScope(name string, o map[interface{}]interface{}) parser.Scope {
  52. vs := NewScope(name)
  53. for k, v := range o {
  54. vs.SetValue(fmt.Sprint(k), v)
  55. }
  56. return vs
  57. }
  58. /*
  59. ConvertJSONToECALObject converts a JSON container structure into an object which
  60. can be used by ECAL.
  61. */
  62. func ConvertJSONToECALObject(v interface{}) interface{} {
  63. res := v
  64. if mapContainer, ok := v.(map[string]interface{}); ok {
  65. newRes := make(map[interface{}]interface{})
  66. for mk, mv := range mapContainer {
  67. newRes[mk] = ConvertJSONToECALObject(mv)
  68. }
  69. res = newRes
  70. } else if mapList, ok := v.([]interface{}); ok {
  71. newRes := make([]interface{}, len(mapList))
  72. for i, lv := range mapList {
  73. newRes[i] = ConvertJSONToECALObject(lv)
  74. }
  75. res = newRes
  76. }
  77. return res
  78. }