stdlib.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. package stdlib
  11. import (
  12. "fmt"
  13. "strings"
  14. "devt.de/krotik/ecal/util"
  15. )
  16. /*
  17. GetStdlibSymbols returns all available packages of stdlib and their constant
  18. and function symbols.
  19. */
  20. func GetStdlibSymbols() ([]string, []string, []string) {
  21. var constSymbols, funcSymbols []string
  22. var packageNames []string
  23. packageSet := make(map[string]bool)
  24. addSym := func(sym string, suffix string, symMap map[interface{}]interface{},
  25. ret []string) []string {
  26. if strings.HasSuffix(sym, suffix) {
  27. trimSym := strings.TrimSuffix(sym, suffix)
  28. packageSet[trimSym] = true
  29. for k := range symMap {
  30. ret = append(ret, fmt.Sprintf("%v.%v", trimSym, k))
  31. }
  32. }
  33. return ret
  34. }
  35. for k, v := range genStdlib {
  36. sym := fmt.Sprint(k)
  37. symMap := v.(map[interface{}]interface{})
  38. constSymbols = addSym(sym, "-const", symMap, constSymbols)
  39. funcSymbols = addSym(sym, "-func", symMap, funcSymbols)
  40. }
  41. for k := range packageSet {
  42. packageNames = append(packageNames, k)
  43. }
  44. return packageNames, constSymbols, funcSymbols
  45. }
  46. /*
  47. GetStdlibConst looks up a constant from stdlib.
  48. */
  49. func GetStdlibConst(name string) (interface{}, bool) {
  50. m, n := splitModuleAndName(name)
  51. if n != "" {
  52. if cmap, ok := genStdlib[fmt.Sprintf("%v-const", m)]; ok {
  53. if cv, ok := cmap.(map[interface{}]interface{})[n]; ok {
  54. return cv.(interface{}), true
  55. }
  56. }
  57. }
  58. return nil, false
  59. }
  60. /*
  61. GetStdlibFunc looks up a function from stdlib.
  62. */
  63. func GetStdlibFunc(name string) (util.ECALFunction, bool) {
  64. m, n := splitModuleAndName(name)
  65. if n != "" {
  66. if fmap, ok := genStdlib[fmt.Sprintf("%v-func", m)]; ok {
  67. if fn, ok := fmap.(map[interface{}]interface{})[n]; ok {
  68. return fn.(util.ECALFunction), true
  69. }
  70. }
  71. }
  72. return nil, false
  73. }
  74. func splitModuleAndName(fullname string) (string, string) {
  75. var module, name string
  76. ccSplit := strings.SplitN(fullname, ".", 2)
  77. if len(ccSplit) != 0 {
  78. module = ccSplit[0]
  79. name = strings.Join(ccSplit[1:], "")
  80. }
  81. return module, name
  82. }