model_parser.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. local string = string
  2. local table = table
  3. local io = io
  4. local lyaml = require("lyaml")
  5. local M = {}
  6. -- Parameters that do not get inherited.
  7. local NO_INHERIT = {abstract = true}
  8. local MODEL_PATH = "./config/model/"
  9. local function camel2snake(src)
  10. return string.lower(
  11. string.gsub(
  12. string.gsub (src, "^pas:", ""), -- Strip namespace.
  13. "([^^])(%u)", "%1_%2" -- Uppercase (except initial) to underscore.
  14. )
  15. )
  16. end
  17. M.parse_model = function(mod_id)
  18. local hierarchy = {}
  19. local function traverse(mod_id)
  20. print("traversing:", mod_id)
  21. local fname = camel2snake (mod_id)
  22. local fh = assert(io.open(MODEL_PATH .. fname .. ".yml"), "r")
  23. local yml_data = fh:read("a")
  24. fh:close()
  25. local model = lyaml.load(yml_data)
  26. model.id = mod_id
  27. --print("Model: ")
  28. --for k, v in pairs(model) do print (k, v) end
  29. -- Prepend to hierarchy.
  30. table.insert(hierarchy, 1, model)
  31. if model.broader then traverse(model.broader) end
  32. end
  33. traverse(mod_id)
  34. local lineage = {} -- Config ID lineage, from ancestor to leaf.
  35. for _, mod in ipairs(hierarchy) do table.insert(lineage, mod.id) end
  36. --[[
  37. for k, v in ipairs(hierarchy) do
  38. for kk, vv in pairs(v) do print(k, kk, vv) end
  39. end
  40. --]]
  41. local function merge(src, dest)
  42. for k, v in pairs(src) do
  43. if NO_INHERIT[k] then goto continue end
  44. if type(v) == "table" then
  45. merge(v, dest[k] or {})
  46. else
  47. dest[k] = v
  48. end
  49. ::continue::
  50. end
  51. end
  52. local config = {}
  53. for _, src_config in ipairs(hierarchy) do
  54. print("Merging:", src_config)
  55. merge(src_config, config)
  56. end
  57. return config
  58. end
  59. return M