main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. /*
  2. * Copyright (c) 2021, Daniel Bertalan <dani@danielbertalan.dev>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/GenericLexer.h>
  7. #include <AK/HashTable.h>
  8. #include <AK/OwnPtr.h>
  9. #include <AK/SourceGenerator.h>
  10. #include <AK/String.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Types.h>
  13. #include <LibCore/ArgsParser.h>
  14. #include <LibCore/File.h>
  15. #include <ctype.h>
  16. struct Range {
  17. int begin;
  18. int end;
  19. };
  20. struct StateTransition {
  21. Optional<String> new_state;
  22. Optional<String> action;
  23. };
  24. struct MatchedAction {
  25. Range range;
  26. StateTransition action;
  27. };
  28. struct State {
  29. String name;
  30. Vector<MatchedAction> actions;
  31. Optional<String> entry_action;
  32. Optional<String> exit_action;
  33. };
  34. struct StateMachine {
  35. String name;
  36. String initial_state;
  37. Vector<State> states;
  38. Optional<State> anywhere;
  39. Optional<String> namespaces;
  40. };
  41. static OwnPtr<StateMachine>
  42. parse_state_machine(StringView input)
  43. {
  44. auto state_machine = make<StateMachine>();
  45. GenericLexer lexer(input);
  46. auto consume_whitespace = [&] {
  47. bool consumed = true;
  48. while (consumed) {
  49. consumed = lexer.consume_while(isspace).length() > 0;
  50. if (lexer.consume_specific("//")) {
  51. lexer.consume_line();
  52. consumed = true;
  53. }
  54. }
  55. };
  56. auto consume_identifier = [&] {
  57. consume_whitespace();
  58. return lexer.consume_while([](char c) { return isalnum(c) || c == '_'; });
  59. };
  60. auto get_hex_value = [&](char c) {
  61. if (isdigit(c))
  62. return c - '0';
  63. else
  64. return c - 'a' + 10;
  65. };
  66. auto consume_number = [&] {
  67. int num = 0;
  68. consume_whitespace();
  69. if (lexer.consume_specific("0x")) {
  70. auto hex_digits = lexer.consume_while([](char c) {
  71. if (isdigit(c)) return true;
  72. else {
  73. c = tolower(c);
  74. return (c >= 'a' && c <= 'f');
  75. } });
  76. for (auto c : hex_digits)
  77. num = 16 * num + get_hex_value(c);
  78. } else {
  79. lexer.consume_specific('\'');
  80. if (lexer.next_is('\\'))
  81. num = (int)lexer.consume_escaped_character('\\');
  82. else
  83. num = lexer.consume_until('\'').to_int().value();
  84. lexer.consume_specific('\'');
  85. }
  86. return num;
  87. };
  88. auto consume_condition = [&] {
  89. Range condition;
  90. consume_whitespace();
  91. if (lexer.consume_specific('[')) {
  92. consume_whitespace();
  93. condition.begin = consume_number();
  94. consume_whitespace();
  95. lexer.consume_specific("..");
  96. consume_whitespace();
  97. condition.end = consume_number();
  98. consume_whitespace();
  99. lexer.consume_specific(']');
  100. } else {
  101. auto num = consume_number();
  102. condition.begin = num;
  103. condition.end = num;
  104. }
  105. return condition;
  106. };
  107. auto consume_action = [&]() {
  108. StateTransition action;
  109. consume_whitespace();
  110. lexer.consume_specific("=>");
  111. consume_whitespace();
  112. lexer.consume_specific('(');
  113. consume_whitespace();
  114. if (!lexer.consume_specific("_"))
  115. action.new_state = consume_identifier();
  116. consume_whitespace();
  117. lexer.consume_specific(',');
  118. consume_whitespace();
  119. if (!lexer.consume_specific("_"))
  120. action.action = consume_identifier();
  121. consume_whitespace();
  122. lexer.consume_specific(')');
  123. return action;
  124. };
  125. auto consume_state_description
  126. = [&] {
  127. State state;
  128. consume_whitespace();
  129. state.name = consume_identifier();
  130. consume_whitespace();
  131. consume_whitespace();
  132. lexer.consume_specific('{');
  133. for (;;) {
  134. consume_whitespace();
  135. if (lexer.consume_specific('}')) {
  136. break;
  137. }
  138. if (lexer.consume_specific("@entry")) {
  139. consume_whitespace();
  140. state.entry_action = consume_identifier();
  141. } else if (lexer.consume_specific("@exit")) {
  142. consume_whitespace();
  143. state.exit_action = consume_identifier();
  144. } else if (lexer.next_is('@')) {
  145. auto directive = consume_identifier().to_string();
  146. fprintf(stderr, "Unimplemented @ directive %s\n", directive.characters());
  147. exit(1);
  148. } else {
  149. MatchedAction matched_action;
  150. matched_action.range = consume_condition();
  151. matched_action.action = consume_action();
  152. state.actions.append(matched_action);
  153. }
  154. }
  155. return state;
  156. };
  157. while (!lexer.is_eof()) {
  158. consume_whitespace();
  159. if (lexer.is_eof())
  160. break;
  161. if (lexer.consume_specific("@namespace")) {
  162. consume_whitespace();
  163. state_machine->namespaces = lexer.consume_while([](char c) { return isalpha(c) || c == ':'; });
  164. } else if (lexer.consume_specific("@begin")) {
  165. consume_whitespace();
  166. state_machine->initial_state = consume_identifier();
  167. } else if (lexer.consume_specific("@name")) {
  168. consume_whitespace();
  169. state_machine->name = consume_identifier();
  170. } else if (lexer.next_is("@anywhere")) {
  171. lexer.consume_specific('@');
  172. state_machine->anywhere = consume_state_description();
  173. } else if (lexer.consume_specific('@')) {
  174. auto directive = consume_identifier().to_string();
  175. fprintf(stderr, "Unimplemented @ directive %s\n", directive.characters());
  176. exit(1);
  177. } else {
  178. auto description = consume_state_description();
  179. state_machine->states.append(description);
  180. }
  181. }
  182. if (state_machine->initial_state.is_empty()) {
  183. fprintf(stderr, "Missing @begin directive\n");
  184. exit(1);
  185. } else if (state_machine->name.is_empty()) {
  186. fprintf(stderr, "Missing @name directive\n");
  187. exit(1);
  188. }
  189. if (state_machine->anywhere.has_value()) {
  190. state_machine->anywhere.value().name = "_Anywhere";
  191. }
  192. return state_machine;
  193. }
  194. void output_header(const StateMachine&, SourceGenerator&);
  195. int main(int argc, char** argv)
  196. {
  197. Core::ArgsParser args_parser;
  198. const char* path = nullptr;
  199. args_parser.add_positional_argument(path, "Path to parser description", "input", Core::ArgsParser::Required::Yes);
  200. args_parser.parse(argc, argv);
  201. auto file_or_error = Core::File::open(path, Core::OpenMode::ReadOnly);
  202. if (file_or_error.is_error()) {
  203. fprintf(stderr, "Cannot open %s\n", path);
  204. }
  205. auto content = file_or_error.value()->read_all();
  206. auto state_machine = parse_state_machine(content);
  207. StringBuilder builder;
  208. SourceGenerator generator { builder };
  209. output_header(*state_machine, generator);
  210. outln("{}", generator.as_string_view());
  211. return 0;
  212. }
  213. HashTable<String> actions(const StateMachine& machine)
  214. {
  215. HashTable<String> table;
  216. auto do_state = [&](const State& state) {
  217. if (state.entry_action.has_value())
  218. table.set(state.entry_action.value());
  219. if (state.exit_action.has_value())
  220. table.set(state.exit_action.value());
  221. for (auto action : state.actions) {
  222. if (action.action.action.has_value())
  223. table.set(action.action.action.value());
  224. }
  225. };
  226. for (auto state : machine.states) {
  227. do_state(state);
  228. }
  229. if (machine.anywhere.has_value())
  230. do_state(machine.anywhere.value());
  231. return move(table);
  232. }
  233. void generate_lookup_table(const StateMachine& machine, SourceGenerator& generator)
  234. {
  235. generator.append(R"~~~(
  236. static constexpr StateTransition STATE_TRANSITION_TABLE[][256] = {
  237. )~~~");
  238. auto generate_for_state = [&](const State& s) {
  239. auto table_generator = generator.fork();
  240. table_generator.set("active_state", s.name);
  241. table_generator.append("/* @active_state@ */ { ");
  242. VERIFY(!s.name.is_empty());
  243. Vector<StateTransition> row;
  244. for (int i = 0; i < 256; i++)
  245. row.append({ s.name, "_Ignore" });
  246. for (auto action : s.actions) {
  247. for (int range_element = action.range.begin; range_element <= action.range.end; range_element++) {
  248. row[range_element] = { action.action.new_state, action.action.action };
  249. }
  250. }
  251. for (int i = 0; i < 256; ++i) {
  252. auto cell_generator = table_generator.fork();
  253. cell_generator.set("cell_new_state", row[i].new_state.value_or(s.name));
  254. cell_generator.set("cell_action", row[i].action.value_or("_Ignore"));
  255. cell_generator.append(" {State::@cell_new_state@, Action::@cell_action@}, ");
  256. }
  257. table_generator.append("},\n");
  258. };
  259. if (machine.anywhere.has_value()) {
  260. generate_for_state(machine.anywhere.value());
  261. }
  262. for (auto s : machine.states) {
  263. generate_for_state(s);
  264. }
  265. generator.append(R"~~~(
  266. };
  267. )~~~");
  268. }
  269. void output_header(const StateMachine& machine, SourceGenerator& generator)
  270. {
  271. generator.set("class_name", machine.name);
  272. generator.set("initial_state", machine.initial_state);
  273. generator.set("state_count", String::number(machine.states.size() + 1));
  274. generator.append(R"~~~(
  275. #pragma once
  276. #include <AK/Function.h>
  277. #include <AK/Platform.h>
  278. #include <AK/Types.h>
  279. )~~~");
  280. if (machine.namespaces.has_value()) {
  281. generator.set("namespace", machine.namespaces.value());
  282. generator.append(R"~~~(
  283. namespace @namespace@ {
  284. )~~~");
  285. }
  286. generator.append(R"~~~(
  287. class @class_name@ {
  288. public:
  289. enum class Action : u8 {
  290. _Ignore,
  291. )~~~");
  292. for (auto a : actions(machine)) {
  293. if (a.is_empty())
  294. continue;
  295. auto action_generator = generator.fork();
  296. action_generator.set("action.name", a);
  297. action_generator.append(R"~~~(
  298. @action.name@,
  299. )~~~");
  300. }
  301. generator.append(R"~~~(
  302. }; // end Action
  303. using Handler = Function<void(Action, u8)>;
  304. @class_name@(Handler handler)
  305. : m_handler(move(handler))
  306. {
  307. }
  308. void advance(u8 byte)
  309. {
  310. auto next_state = lookup_state_transition(byte);
  311. bool state_will_change = next_state.new_state != m_state && next_state.new_state != State::_Anywhere;
  312. // only run exit directive if state is being changed
  313. if (state_will_change) {
  314. switch (m_state) {
  315. )~~~");
  316. for (auto s : machine.states) {
  317. auto state_generator = generator.fork();
  318. if (s.exit_action.has_value()) {
  319. state_generator.set("state_name", s.name);
  320. state_generator.set("action", s.exit_action.value());
  321. state_generator.append(R"~~~(
  322. case State::@state_name@:
  323. m_handler(Action::@action@, byte);
  324. break;
  325. )~~~");
  326. }
  327. }
  328. generator.append(R"~~~(
  329. default:
  330. break;
  331. }
  332. }
  333. if (next_state.action != Action::_Ignore)
  334. m_handler(next_state.action, byte);
  335. m_state = next_state.new_state;
  336. // only run entry directive if state is being changed
  337. if (state_will_change)
  338. {
  339. switch (next_state.new_state)
  340. {
  341. )~~~");
  342. for (auto state : machine.states) {
  343. auto state_generator = generator.fork();
  344. if (state.entry_action.has_value()) {
  345. state_generator.set("state_name", state.name);
  346. state_generator.set("action", state.entry_action.value());
  347. state_generator.append(R"~~~(
  348. case State::@state_name@:
  349. m_handler(Action::@action@, byte);
  350. break;
  351. )~~~");
  352. }
  353. }
  354. generator.append(R"~~~(
  355. default:
  356. break;
  357. }
  358. }
  359. }
  360. private:
  361. enum class State : u8 {
  362. _Anywhere,
  363. )~~~");
  364. int largest_state_value = 0;
  365. for (auto s : machine.states) {
  366. auto state_generator = generator.fork();
  367. state_generator.set("state.name", s.name);
  368. largest_state_value++;
  369. state_generator.append(R"~~~(
  370. @state.name@,
  371. )~~~");
  372. }
  373. generator.append(R"~~~(
  374. }; // end State
  375. struct StateTransition {
  376. State new_state;
  377. Action action;
  378. };
  379. State m_state { State::@initial_state@ };
  380. Handler m_handler;
  381. ALWAYS_INLINE StateTransition lookup_state_transition(u8 byte)
  382. {
  383. VERIFY((u8)m_state < @state_count@);
  384. )~~~");
  385. if (machine.anywhere.has_value()) {
  386. generator.append(R"~~~(
  387. auto anywhere_state = STATE_TRANSITION_TABLE[0][byte];
  388. if (anywhere_state.new_state != State::_Anywhere || anywhere_state.action != Action::_Ignore)
  389. return anywhere_state;
  390. else
  391. )~~~");
  392. }
  393. generator.append(R"~~~(
  394. return STATE_TRANSITION_TABLE[(u8)m_state][byte];
  395. }
  396. )~~~");
  397. auto table_generator = generator.fork();
  398. generate_lookup_table(machine, table_generator);
  399. generator.append(R"~~~(
  400. }; // end @class_name@
  401. )~~~");
  402. if (machine.namespaces.has_value()) {
  403. generator.append(R"~~~(
  404. } // end namespace
  405. )~~~");
  406. }
  407. }