config.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #include "config.h"
  2. #include "markup.h"
  3. #include "ini.h"
  4. #include <library/cpp/archive/yarchive.h>
  5. #include <library/cpp/json/json_reader.h>
  6. #include <library/cpp/json/json_writer.h>
  7. #include <library/cpp/lua/eval.h>
  8. #include <util/string/cast.h>
  9. #include <util/string/strip.h>
  10. #include <util/string/type.h>
  11. #include <util/stream/output.h>
  12. #include <util/stream/file.h>
  13. #include <util/memory/blob.h>
  14. #include <util/generic/singleton.h>
  15. #include <util/stream/str.h>
  16. using namespace NConfig;
  17. using namespace NJson;
  18. namespace {
  19. const unsigned char CODE[] = {
  20. #include "code.inc"
  21. };
  22. struct TCode: public TArchiveReader {
  23. inline TCode()
  24. : TArchiveReader(TBlob::NoCopy(CODE, sizeof(CODE)))
  25. {
  26. }
  27. static inline TCode& Instance() {
  28. return *Singleton<TCode>();
  29. }
  30. };
  31. class TPreprocessor: public IInputStream {
  32. public:
  33. inline TPreprocessor(const TGlobals& g, IInputStream* in)
  34. : I_(nullptr, 0)
  35. , S_(in)
  36. {
  37. E_.SetVars(g);
  38. }
  39. size_t DoRead(void* ptr, size_t len) override {
  40. while (true) {
  41. const size_t read = I_.Read(ptr, len);
  42. if (read) {
  43. return read;
  44. }
  45. do {
  46. if (!S_.ReadLine(C_)) {
  47. return 0;
  48. }
  49. } while (IsComment(C_));
  50. C_ = E_.Preprocess(C_);
  51. C_.append('\n');
  52. I_.Reset(C_.data(), C_.size());
  53. }
  54. }
  55. static inline bool IsComment(TStringBuf s) {
  56. s = StripString(s);
  57. return !s.empty() && s[0] == '#';
  58. }
  59. private:
  60. TMemoryInput I_;
  61. TBufferedInput S_;
  62. TLuaEval E_;
  63. TString C_;
  64. };
  65. }
  66. void TConfig::DumpJson(IOutputStream& out) const {
  67. TString tmp;
  68. {
  69. TStringOutput out2(tmp);
  70. ToJson(out2);
  71. }
  72. {
  73. TJsonValue v;
  74. TStringInput in(tmp);
  75. ReadJsonTree(&in, &v);
  76. WriteJson(&out, &v, true, true);
  77. }
  78. }
  79. TConfig TConfig::FromJson(IInputStream& in, const TGlobals& g) {
  80. class TJSONReader: public TJsonCallbacks {
  81. public:
  82. inline TJSONReader()
  83. : Cur(nullptr)
  84. {
  85. }
  86. inline bool OnBoolean(bool b) override {
  87. *Next() = ConstructValue(b);
  88. return true;
  89. }
  90. inline bool OnInteger(long long i) override {
  91. *Next() = ConstructValue((i64)i);
  92. return true;
  93. }
  94. inline bool OnUInteger(unsigned long long i) override {
  95. *Next() = ConstructValue((ui64)i);
  96. return true;
  97. }
  98. inline bool OnDouble(double d) override {
  99. *Next() = ConstructValue(d);
  100. return true;
  101. }
  102. inline bool OnString(const TStringBuf& s) override {
  103. *Next() = ConstructValue(ToString(s));
  104. return true;
  105. }
  106. inline bool OnOpenMap() override {
  107. Push(ConstructValue(TDict()));
  108. return true;
  109. }
  110. inline bool OnCloseMap() override {
  111. Pop();
  112. return true;
  113. }
  114. inline bool OnOpenArray() override {
  115. Push(ConstructValue(TArray()));
  116. return true;
  117. }
  118. inline bool OnCloseArray() override {
  119. Pop();
  120. return true;
  121. }
  122. inline bool OnMapKey(const TStringBuf& k) override {
  123. if (S.empty()) {
  124. ythrow yexception() << "shit happen";
  125. }
  126. Cur = &S.back().GetNonConstant<TDict>()[ToString(k)];
  127. return true;
  128. }
  129. inline void Push(const TConfig& el) {
  130. *Next() = el;
  131. S.push_back(el);
  132. }
  133. inline void Pop() {
  134. if (S.empty()) {
  135. ythrow yexception() << "shit happen";
  136. }
  137. S.pop_back();
  138. }
  139. inline TConfig* Next() {
  140. if (S.empty()) {
  141. return &Root;
  142. }
  143. TConfig& top = S.back();
  144. if (top.IsA<TArray>()) {
  145. TArray& arr = top.GetNonConstant<TArray>();
  146. arr.emplace_back();
  147. return &arr.back();
  148. }
  149. if (top.IsA<TDict>()) {
  150. if (Cur) {
  151. TConfig* ret = Cur;
  152. Cur = nullptr;
  153. return ret;
  154. }
  155. }
  156. ythrow yexception() << "shit happen";
  157. }
  158. inline void OnError(size_t off, TStringBuf reason) override {
  159. Y_UNUSED(off);
  160. if (!FirstErrorReason) {
  161. FirstErrorReason = reason;
  162. }
  163. }
  164. TConfig Root;
  165. TConfig* Cur;
  166. TVector<TConfig> S;
  167. TString FirstErrorReason;
  168. };
  169. TJSONReader r;
  170. TString data = in.ReadAll();
  171. TMemoryInput mi(data.data(), data.size());
  172. TPreprocessor p(g, &mi);
  173. if (!NJson::ReadJson(&p, false, true, &r)) {
  174. if (!!r.FirstErrorReason) {
  175. ythrow TConfigParseError() << "Error parsing json: " << r.FirstErrorReason;
  176. } else {
  177. ythrow TConfigParseError() << "Could not parse json " << data.Quote();
  178. }
  179. }
  180. return r.Root;
  181. }
  182. namespace {
  183. struct TData {
  184. const char* Prologue;
  185. const char* Epilogue;
  186. };
  187. const TData DATA[] = {
  188. {"", "\nassert(not (instance == nil))\nreturn instance\n"},
  189. {"", "\nassert(not (main == nil))\nreturn main\n"},
  190. {"return ", "\n"},
  191. {"", "\n"},
  192. };
  193. }
  194. TConfig TConfig::FromLua(IInputStream& in, const TGlobals& g) {
  195. const TString& data = in.ReadAll();
  196. TString json;
  197. for (size_t i = 0; i < Y_ARRAY_SIZE(DATA); ++i) {
  198. TStringStream ss;
  199. ss << TStringBuf("local function configgen()")
  200. << DATA[i].Prologue << data << DATA[i].Epilogue
  201. << TStringBuf("end\n\nreturn require('json').encode(configgen())\n");
  202. try {
  203. json = TLuaEval().SetVars(g).EvalRaw(ss.Str());
  204. break;
  205. } catch (...) {
  206. if (i == (Y_ARRAY_SIZE(DATA) - 1)) {
  207. throw;
  208. }
  209. }
  210. }
  211. TMemoryInput mi(json.data(), json.size());
  212. return FromJson(mi);
  213. }
  214. TConfig TConfig::FromMarkup(IInputStream& in, const TGlobals& g) {
  215. TPreprocessor pin(g, &in);
  216. return ParseRawMarkup(pin);
  217. }
  218. TConfig TConfig::FromIni(IInputStream& in, const TGlobals& g) {
  219. TPreprocessor pin(g, &in);
  220. return ParseIni(pin);
  221. }
  222. void TConfig::DumpLua(IOutputStream& out) const {
  223. TLuaEval e;
  224. TStringStream ss;
  225. ToJson(ss);
  226. e.SetVariable("jsonval", ss.Str());
  227. out << "return " << e.EvalRaw(TCode::Instance().ObjectByKey("/pp.lua")->ReadAll() + "\nreturn prettify(require('json').decode(jsonval))\n");
  228. }
  229. TConfig TConfig::FromStream(IInputStream& in, const TGlobals& g) {
  230. const TString& tmp = in.ReadAll();
  231. TString luaParsingError = "";
  232. try {
  233. TMemoryInput mi(tmp.data(), tmp.size());
  234. return FromLua(mi, g);
  235. } catch (const yexception& e) {
  236. luaParsingError = e.AsStrBuf();
  237. } catch (...) {
  238. luaParsingError = "unknown error";
  239. }
  240. TMemoryInput mi(tmp.data(), tmp.size());
  241. try {
  242. return FromJson(mi, g);
  243. } catch (const yexception& e) {
  244. const TStringBuf& jsonParsingError = e.AsStrBuf();
  245. ythrow yexception() << "Could not parse config:\nParsing as lua: " << luaParsingError << "\nParsing as json: " << jsonParsingError;
  246. }
  247. }
  248. TConfig TConfig::ReadJson(TStringBuf in, const TGlobals& g) {
  249. TMemoryInput mi(in.data(), in.size());
  250. return FromJson(mi, g);
  251. }
  252. TConfig TConfig::ReadLua(TStringBuf in, const TGlobals& g) {
  253. TMemoryInput mi(in.data(), in.size());
  254. return FromLua(mi, g);
  255. }
  256. TConfig TConfig::ReadMarkup(TStringBuf in, const TGlobals& g) {
  257. TMemoryInput mi(in.data(), in.size());
  258. return FromMarkup(mi, g);
  259. }
  260. TConfig TConfig::ReadIni(TStringBuf in, const TGlobals& g) {
  261. TMemoryInput mi(in.data(), in.size());
  262. return FromIni(mi, g);
  263. }
  264. void TConfig::Load(IInputStream* input) {
  265. TString string;
  266. ::Load(input, string);
  267. TStringInput stream(string);
  268. *this = FromJson(stream);
  269. }
  270. void TConfig::Save(IOutputStream* output) const {
  271. TString result;
  272. TStringOutput stream(result);
  273. DumpJson(stream);
  274. ::Save(output, result);
  275. }
  276. bool TConfig::Has(const TStringBuf& key) const {
  277. return !operator[](key).IsNull();
  278. }
  279. const TConfig& TConfig::operator[](const TStringBuf& key) const {
  280. return Get<TDict>().Find(key);
  281. }
  282. const TConfig& TConfig::At(const TStringBuf& key) const {
  283. return Get<TDict>().At(key);
  284. }
  285. const TConfig& TConfig::operator[](size_t index) const {
  286. return Get<TArray>().Index(index);
  287. }
  288. size_t TConfig::GetArraySize() const {
  289. return Get<TArray>().size();
  290. }
  291. const TConfig& TDict::Find(const TStringBuf& key) const {
  292. const_iterator it = find(key);
  293. if (it == end()) {
  294. return Default<TConfig>();
  295. }
  296. return it->second;
  297. }
  298. const TConfig& TDict::At(const TStringBuf& key) const {
  299. const_iterator it = find(key);
  300. Y_ENSURE_BT(it != end(), "missing key '" << key << "'");
  301. return it->second;
  302. }
  303. const TConfig& TArray::Index(size_t index) const {
  304. if (index < size()) {
  305. return (*this)[index];
  306. }
  307. return Default<TConfig>();
  308. }
  309. const TConfig& TArray::At(size_t index) const {
  310. Y_ENSURE_BT(index < size(), "index " << index << " is out of bounds");
  311. return (*this)[index];
  312. }
  313. THolder<IInputStream> NConfig::CreatePreprocessor(const TGlobals& g, IInputStream& in) {
  314. return MakeHolder<TPreprocessor>(g, &in);
  315. }