Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.55 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. #include <map>
  6. #include <set>
  7. #include <stack>
  8. #include <functional>
  9. #include <sstream>
  10. #include <time.h>
  11. #include <memory>
  12.  
  13. #define DEBUG true
  14.  
  15. namespace parser_package
  16. {
  17. namespace _token
  18. {
  19. using namespace std;
  20.  
  21. template <class IDENT = string, class VAL = int>
  22. struct token
  23. {
  24. VAL value;
  25. IDENT id;
  26. string lexeme;
  27. int col;
  28. int row;
  29. bool empty;
  30.  
  31. token(IDENT id, string lexeme, VAL value, int col = 0, int row = 0);
  32. token(const token<IDENT, VAL>& other);
  33. token(token<IDENT, VAL>&& other);
  34. token(IDENT id);
  35. token();
  36.  
  37. token<IDENT, VAL>& operator=(const token<IDENT, VAL>& other);
  38. token<IDENT, VAL>& operator=(token<IDENT, VAL>&& other);
  39.  
  40. string to_string();
  41. };
  42.  
  43. template <class IDENT, class VAL>
  44. token<IDENT, VAL>::token(IDENT id, string lexeme, VAL value, int col, int row)
  45. {
  46. this->id = id;
  47. this->lexeme = lexeme;
  48. this->value = value;
  49. this->col = col;
  50. this->row = row;
  51. this->empty = false;
  52. }
  53.  
  54. template<class IDENT, class VAL>
  55. token<IDENT, VAL>::token(const token<IDENT, VAL>& other)
  56. {
  57. this->id = other.id;
  58. this->lexeme = other.lexeme;
  59. this->value = other.value;
  60. this->col = other.col;
  61. this->row = other.row;
  62. this->empty = other.empty;
  63. }
  64.  
  65. template<class IDENT, class VAL>
  66. token<IDENT, VAL>::token(token<IDENT, VAL>&& other)
  67. {
  68. this->id = other.id;
  69. this->lexeme = other.lexeme;
  70. this->value = other.value;
  71. this->col = other.col;
  72. this->row = other.row;
  73. this->empty = other.empty;
  74. }
  75.  
  76. template<class IDENT, class VAL>
  77. token<IDENT, VAL>::token(IDENT id)
  78. {
  79. this->id = id;
  80. this->lexeme = string();
  81. this->value = VAL();
  82. this->col = -1;
  83. this->row = -1;
  84. this->empty = false;
  85. }
  86.  
  87. template<class IDENT, class VAL>
  88. token<IDENT, VAL>::token()
  89. {
  90. this->id = IDENT();
  91. this->value = VAL();
  92. this->lexeme = string();
  93. this->col = 0;
  94. this->row = 0;
  95. this->empty = true;
  96. }
  97.  
  98. template<class IDENT, class VAL>
  99. token<IDENT, VAL>& token<IDENT, VAL>::operator=(const token<IDENT, VAL>& other)
  100. {
  101. this->id = other.id;
  102. this->lexeme = other.lexeme;
  103. this->value = other.value;
  104. this->col = other.col;
  105. this->row = other.row;
  106. this->empty = other.empty;
  107. return *this;
  108. }
  109.  
  110. template<class IDENT, class VAL>
  111. token<IDENT, VAL>& token<IDENT, VAL>::operator=(token<IDENT, VAL>&& other)
  112. {
  113. this->id = other.id;
  114. this->lexeme = other.lexeme;
  115. this->value = other.value;
  116. this->col = other.col;
  117. this->row = other.row;
  118. this->empty = other.empty;
  119. return *this;
  120. }
  121.  
  122. template<class IDENT, class VAL>
  123. string token<IDENT, VAL>::to_string()
  124. {
  125. stringstream temp;
  126. if (empty)
  127. return "empty\n";
  128. temp << "id: " << id << endl;
  129. temp << "lexeme: " << lexeme << endl;
  130. temp << "value: " << value << endl;
  131. temp << "row:col " << row << " : " << col << endl;
  132. return temp.str();
  133. }
  134. }
  135.  
  136. namespace _terminal
  137. {
  138. using namespace std;
  139. using namespace _token;
  140.  
  141. template <class IDENT = string, class VAL = int>
  142. class terminal
  143. {
  144. vector<string> symbols;
  145. bool using_symbols;
  146.  
  147. protected:
  148. function<VAL(const string&)> get_value;
  149. function<token<IDENT, VAL>(const string&, int)> comparison;
  150.  
  151. public:
  152. IDENT id;
  153.  
  154. terminal(IDENT id, vector<string> list = vector<string>(), function<VAL(const string&)> get_value = [](const string& str) -> int { return int(); });
  155. terminal(IDENT id, function<token<IDENT, VAL>(const string&, int)>, function<VAL(const string&)> get_value = [](const string& str) -> int { return int(); });
  156. terminal(terminal<IDENT, VAL>& other) = delete;
  157. terminal(terminal<IDENT, VAL>&& other) = delete;
  158.  
  159. virtual token<IDENT, VAL> compare(const string& str, int pos);
  160. };
  161.  
  162. template <class IDENT, class VAL>
  163. terminal<IDENT, VAL>::terminal(IDENT id, vector<string> list, function<VAL(const string&)> get_value)
  164. {
  165. this->id = move(id);
  166. this->symbols = move(list);
  167. this->get_value = move(get_value);
  168. this->using_symbols = true;
  169. }
  170.  
  171. template<class IDENT, class VAL>
  172. terminal<IDENT, VAL>::terminal(IDENT id, function<token<IDENT, VAL>(const string&, int)> comparison, function<VAL(const string&)> get_value)
  173. {
  174. this->id = move(id);
  175. this->comparison = move(comparison);
  176. this->get_value = move(get_value);
  177. this->using_symbols = false;
  178. }
  179.  
  180. template <class IDENT, class VAL>
  181. token<IDENT, VAL> terminal<IDENT, VAL>::compare(const string& str, int pos)
  182. {
  183. if (this->using_symbols)
  184. {
  185. for (auto& t : symbols)
  186. if (str.find(t, pos) == pos)
  187. return token<IDENT, VAL>(this->id, t, get_value(t), pos, -1);
  188. return token<IDENT, VAL>();
  189. }
  190. else
  191. return comparison(str, pos);
  192. }
  193. }
  194.  
  195. namespace _nonterminal
  196. {
  197. using namespace _terminal;
  198.  
  199. template <class IDENT = string>
  200. class nonterminal
  201. {
  202. vector<vector<IDENT>> variants;
  203.  
  204. public:
  205. IDENT id;
  206.  
  207. nonterminal(IDENT id, vector<vector<IDENT>> templates = vector<vector<IDENT>>());
  208. nonterminal(nonterminal<IDENT>& other) = delete;
  209. nonterminal(nonterminal<IDENT>&& other) = delete;
  210.  
  211. const vector<vector<IDENT>>& templates();
  212.  
  213. nonterminal<IDENT>& operator+=(vector<IDENT> templates);
  214. };
  215.  
  216. template<class IDENT>
  217. nonterminal<IDENT>::nonterminal(IDENT id, vector<vector<IDENT>> templates)
  218. {
  219. this->id = id;
  220. this->variants = move(templates);
  221. }
  222.  
  223. template<class IDENT>
  224. const vector<vector<IDENT>>& nonterminal<IDENT>::templates()
  225. {
  226. return variants;
  227. }
  228.  
  229. template<class IDENT>
  230. nonterminal<IDENT>& nonterminal<IDENT>::operator+=(vector<IDENT> templates)
  231. {
  232. variants.emplace_back(move(templates));
  233. return *this;
  234. }
  235. }
  236.  
  237. namespace _tree
  238. {
  239. using namespace std;
  240.  
  241. #define DEFAULT_TREE_SIZE 256
  242.  
  243. template<class T>
  244. class node
  245. {
  246. T value;
  247. vector<node<T>*> relations;
  248.  
  249. public:
  250. int level;
  251. int span;
  252.  
  253. node<T>& run(function<void(int, T&)>& action = function<void(int, T&)>([](int depth, T& t) -> void { return; }));
  254.  
  255. node();
  256. node(T t, int level = 0, int span = 0);
  257. node(const node<T>&) = delete;
  258. node(node<T>&&);
  259. ~node();
  260.  
  261. T& val();
  262. vector<node<T>*>& rel();
  263.  
  264. node<T>& operator<<(node<T>* temp);
  265. node<T>& operator=(node<T>&& temp);
  266. node<T>& operator=(const node<T>& temp) = delete;
  267. };
  268. template<class T>
  269. node<T>& node<T>::run(function<void(int, T&)>& action)
  270. {
  271. action(this->level, this->value);
  272. for (auto& t : this->relations)
  273. if (t != nullptr && t != NULL)
  274. t->run(action);
  275. return *this;
  276. }
  277. template<class T>
  278. node<T>::node()
  279. {
  280. this->value = T();
  281. this->level = 0;
  282. this->span = 0;
  283. }
  284. template<class T>
  285. node<T>::node(T t, int level, int span)
  286. {
  287. this->value = t;
  288. this->level = level;
  289. this->span = span;
  290. }
  291. template<class T>
  292. node<T>::node(node<T>&& other)
  293. {
  294. this->value = move(other.value);
  295. this->relations = move(other.relations);
  296. this->level = other.level;
  297. this->span = other.span;
  298.  
  299. other.value = T();
  300. other.level = 0;
  301. other.span = 0;
  302. }
  303. template<class T>
  304. node<T>::~node()
  305. {
  306. }
  307. template<class T>
  308. T & node<T>::val()
  309. {
  310. return value;
  311. }
  312. template<class T>
  313. vector<node<T>*>& node<T>::rel()
  314. {
  315. return relations;
  316. }
  317. template<class T>
  318. node<T>& node<T>::operator<<(node<T>* temp)
  319. {
  320. this->span += temp->span;
  321. this->relations.emplace_back(temp);
  322. return *this;
  323. }
  324. template<class T>
  325. node<T>& node<T>::operator=(node<T>&& other)
  326. {
  327. this->value = move(other.value);
  328. this->relations = move(other.relations);
  329. this->level = other.level;
  330. this->span = other.span;
  331.  
  332. other.value = T();
  333. other.level = 0;
  334. other.span = 0;
  335.  
  336. return *this;
  337. }
  338.  
  339. template<class T, class Allocator = allocator<node<T>>>
  340. class basic_tree
  341. {
  342. Allocator alloc;
  343. size_t top;
  344. size_t size;
  345. vector<pair<size_t, node<T>*>> heap;
  346.  
  347. void reserve_some();
  348.  
  349. public:
  350. node<T>* root;
  351.  
  352. basic_tree();
  353. basic_tree(const basic_tree&) = delete;
  354. basic_tree(basic_tree&&);
  355. ~basic_tree();
  356.  
  357. bool empty();
  358. template<class... Args> node<T>* new_node(Args&&... args);
  359. node<T>& run(node<T>* root, function<void(int, T&)>& action);
  360.  
  361. basic_tree<T, Allocator>& operator=(basic_tree<T, Allocator>&&);
  362. basic_tree<T, Allocator>& operator=(const basic_tree<T, Allocator>&) = delete;
  363. };
  364. template<class T, class Allocator>
  365. void basic_tree<T, Allocator>::reserve_some()
  366. {
  367. top = 0;
  368. size = heap.back().first * 2;
  369. heap.emplace_back(size, alloc.allocate(size));
  370. }
  371. template<class T, class Allocator>
  372. basic_tree<T, Allocator>::basic_tree()
  373. {
  374. this->top = 0;
  375. this->size = DEFAULT_TREE_SIZE;
  376. this->heap.emplace_back(this->size, this->alloc.allocate(this->size));
  377. this->root = nullptr;
  378. }
  379. template<class T, class Allocator>
  380. basic_tree<T, Allocator>::basic_tree(basic_tree && other)
  381. {
  382. this->alloc = move(other.alloc);
  383. this->heap = move(other.heap);
  384. this->top = other.top;
  385. this->size = other.size;
  386. this->root = other.root;
  387.  
  388. other.top = 0;
  389. other.size = DEFAULT_TREE_SIZE;
  390. other.heap.emplace_back(other.size, other.alloc.allocate(other.size));
  391. other.root = nullptr;
  392. }
  393. template<class T, class Allocator>
  394. basic_tree<T, Allocator>& basic_tree<T, Allocator>::operator=(basic_tree<T, Allocator>&& other)
  395. {
  396. this->alloc = move(other.alloc);
  397. this->heap = move(other.heap);
  398. this->top = other.top;
  399. this->size = other.size;
  400. this->root = other.root;
  401.  
  402. other.top = 0;
  403. other.size = DEFAULT_TREE_SIZE;
  404. other.heap.emplace_back(other.size, other.alloc.allocate(other.size));
  405. other.root = nullptr;
  406. }
  407. template<class T, class Allocator>
  408. basic_tree<T, Allocator>::~basic_tree()
  409. {
  410. for (int j = 0; j < heap.size() - 1; j++)
  411. {
  412. for (size_t i = 0; i < heap[j].first; i++)
  413. alloc.destroy(heap[j].second + i);
  414. alloc.deallocate(heap[j].second, heap[j].first);
  415. }
  416. for (int i = 0; i < top; i++)
  417. alloc.destroy(heap.back().second + i);
  418. alloc.deallocate(heap.back().second, size);
  419. }
  420. template<class T, class Allocator>
  421. bool basic_tree<T, Allocator>::empty()
  422. {
  423. return this->root == nullptr;
  424. }
  425. template<class T, class Allocator>
  426. node<T>& basic_tree<T, Allocator>::run(node<T>* root, function<void(int, T&)>& action)
  427. {
  428. action(root->level, root->value);
  429. for (auto& t : root->relations)
  430. if (t != nullptr && t != NULL)
  431. run(action, t);
  432. return *root;
  433. }
  434. template<class T, class Allocator>
  435. template<class ... Args>
  436. node<T>* basic_tree<T, Allocator>::new_node(Args && ...args)
  437. {
  438. if (top >= size)
  439. reserve_some();
  440. auto temp = heap.back().second + top++;
  441. alloc.construct(temp, forward<Args>(args)...);
  442. return temp;
  443. }
  444. }
  445.  
  446. namespace _parser
  447. {
  448. using namespace std;
  449. using namespace _terminal;
  450. using namespace _nonterminal;
  451. using namespace _tree;
  452.  
  453. template<class IDENT = string, class VAL = int>
  454. class parser
  455. {
  456. terminal<IDENT, VAL>* epsilon_symbol;
  457. map<IDENT, terminal<IDENT, VAL>*> terminals;
  458. map<IDENT, nonterminal<IDENT>*> nonterminals;
  459.  
  460. public:
  461. parser(terminal<IDENT, VAL>*);
  462. ~parser();
  463.  
  464. vector<token<IDENT, VAL>> lexify(const string& str);
  465. node<token<IDENT, VAL>>* analize(basic_tree<token<IDENT, VAL>>& parse_tree, IDENT id, typename vector<token<IDENT, VAL>>::iterator iter, int lvl);
  466.  
  467. basic_tree<token<IDENT, VAL>> parse(const string& str, const nonterminal<IDENT>& axiome);
  468.  
  469. parser<IDENT, VAL>& operator<<(terminal<IDENT, VAL>* temp);
  470. parser<IDENT, VAL>& operator<<(nonterminal<IDENT>* temp);
  471. };
  472.  
  473. template<class IDENT, class VAL>
  474. parser<IDENT, VAL>::parser(terminal<IDENT, VAL>* epsilon_symbol)
  475. {
  476. if (epsilon_symbol == NULL || epsilon_symbol == nullptr)
  477. throw string("Nope");
  478. this->epsilon_symbol = epsilon_symbol;
  479. }
  480.  
  481. template<class IDENT, class VAL>
  482. parser<IDENT, VAL>::~parser()
  483. {
  484. }
  485.  
  486. template<class IDENT, class VAL>
  487. node<token<IDENT, VAL>>* parser<IDENT, VAL>::analize(basic_tree<token<IDENT, VAL>>& parse_tree, IDENT id, typename vector<token<IDENT, VAL>>::iterator iter, int lvl)
  488. {
  489. if (id == epsilon_symbol->id)
  490. return parse_tree.new_node(token<IDENT, VAL>(epsilon_symbol->id, "", -1, iter->row, iter->col), lvl, 0);
  491.  
  492. if (terminals.count(id) != 0)
  493. {
  494. if (id == iter->id)
  495. return parse_tree.new_node(*iter, lvl, 1);
  496. else
  497. return nullptr;
  498. }
  499. else if (nonterminals.count(id) != 0)
  500. {
  501. nonterminal<IDENT>* templates = nonterminals[id];
  502.  
  503. for (auto& j : templates->templates())
  504. {
  505. bool f = false;
  506. token<IDENT, VAL> tok = token<IDENT, VAL>(id);
  507. node<token<IDENT, VAL>>* res = parse_tree.new_node(tok, lvl, 0),
  508. *temp = nullptr;
  509. for (auto& t : j)
  510. {
  511. temp = analize(parse_tree, t, iter + res->span, lvl + 1);
  512. f |= temp == nullptr;
  513. if (temp == nullptr)
  514. break;
  515. else
  516. *res << temp;
  517. }
  518. if (!f)
  519. return res;
  520. }
  521. return nullptr;
  522. }
  523. else
  524. {
  525. stringstream out;
  526. out << "syntax analysis failed at: " << iter->id << endl << iter->to_string();
  527. throw out.str();
  528. }
  529. }
  530.  
  531. template<class IDENT, class VAL>
  532. vector<token<IDENT, VAL>> parser<IDENT, VAL>::lexify(const string& str)
  533. {
  534. vector<token<IDENT, VAL>> tokens;
  535. int pos = 0, col = 0, row = 0;
  536. bool f = false;
  537. for (; pos < str.size(); f = false)
  538. {
  539. if (str[pos] == ' ')
  540. {
  541. pos++;
  542. col++;
  543. continue;
  544. }
  545. if (str[pos] == '\n')
  546. {
  547. col = 0;
  548. row++;
  549. continue;
  550. }
  551. for (const auto& t : terminals)
  552. {
  553. token<IDENT, VAL> temp = t.second->compare(str, pos);
  554. f |= !temp.empty;
  555. if (f)
  556. {
  557. temp.col = col;
  558. temp.row = row;
  559. tokens.push_back(temp);
  560. pos += temp.lexeme.size();
  561. col += temp.lexeme.size();
  562. break;
  563. }
  564. }
  565. if (!f)
  566. {
  567. stringstream out;
  568. out << "lexical analysis failed at " << row << ":" << col;
  569. throw out.str();
  570. }
  571. }
  572. token<IDENT, VAL> temp = epsilon_symbol->compare(str, pos);
  573. if (!temp.empty)
  574. {
  575. temp.col = col;
  576. temp.row = row;
  577. tokens.push_back(temp);
  578. pos += temp.lexeme.size();
  579. col += temp.lexeme.size();
  580. }
  581. else
  582. {
  583. stringstream out;
  584. out << "lexical analysis failed at " << row << ":" << col << endl << "epsylon symbol not found";
  585. throw out.str();
  586. }
  587. return move(tokens);
  588. }
  589.  
  590. template<class IDENT, class VAL>
  591. basic_tree<token<IDENT, VAL>> parser<IDENT, VAL>::parse(const string& str, const nonterminal<IDENT>& axiome)
  592. {
  593. vector<token<IDENT, VAL>> tokens;
  594. basic_tree<token<IDENT, VAL>> parse_tree;
  595.  
  596. tokens = move(lexify(str));
  597.  
  598. typename vector<token<IDENT, VAL>>::iterator iter = tokens.begin();
  599.  
  600. parse_tree.root = analize(parse_tree, axiome.id, iter, 0);
  601.  
  602. if (parse_tree.empty())
  603. throw string("syntax analisys failed at: tree is empty");
  604. if (iter + parse_tree.root->span + 1 != tokens.end())
  605. throw string("syntax analisys failed at:\n\n" + iter[parse_tree.root->span].to_string() + "\nexpected:\n\n" + tokens.back().to_string());
  606.  
  607. return move(parse_tree);
  608. }
  609.  
  610. template<class IDENT, class VAL>
  611. parser<IDENT, VAL>& parser<IDENT, VAL>::operator<<(terminal<IDENT, VAL>* temp)
  612. {
  613. terminals[temp->id] = temp;
  614. return *this;
  615. }
  616. template<class IDENT, class VAL>
  617. parser<IDENT, VAL>& parser<IDENT, VAL>::operator<<(nonterminal<IDENT>* temp)
  618. {
  619. nonterminals[temp->id] = temp;
  620. return *this;
  621. }
  622. }
  623. }
  624.  
  625. using namespace std;
  626. using namespace parser_package;
  627. using namespace _token;
  628. using namespace _terminal;
  629. using namespace _nonterminal;
  630. using namespace _parser;
  631.  
  632. /*
  633. <function> ::= <ident> ( <formal-args-list> ) := <expr> ;
  634. <formal-args-list> ::= <ident-list> | e
  635. <ident-list> ::= <ident> <ident-list'>
  636. <ident-list'> ::= , <ident-list> | e
  637. <expr> ::= <comparison_expr> <expr'>
  638. <expr'> ::= ? <comparison_expr> : <expr> | e
  639. <comparison_expr> ::= <arith_expr> <comparison_expr'>
  640. <comparison_expr'> ::= <comparison_op> <arith_expr> | e
  641. <comparison_op> ::= = | <> | < | > | <= | >=
  642. <arith_expr> ::= <term> <arith_expr'>
  643. <arith_expr'> ::= + <term> <arith_expr''> | - <term> <arith_expr''> | e
  644. <arith_expr''> := <arith_expr'> | e
  645. <term> ::= <factor> <term'>
  646. <term'> ::= * <factor> <term''> | / <factor> <term''> | e
  647. <term''> ::= <term'> | e
  648. <factor> ::= <number> | <ident> <factor'> | ( <expr> ) | - <factor>
  649. <factor'> ::= ( <actual_args_list> ) | e
  650. <actual_args_list> ::= <expr-list> | e
  651. <expr-list> ::= <expr> <expr-list'>
  652. <expr-list'> ::= , <expr-list> | e
  653. */
  654.  
  655. bool is_alphabetic(char c)
  656. {
  657. return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
  658. }
  659. bool is_numeral(char c)
  660. {
  661. return c >= '0' && c <= '9';
  662. }
  663.  
  664. class Func
  665. {
  666. public:
  667. set<string> incident;
  668.  
  669. int argc;
  670. set<string>* argv;
  671. vector<pair<string, int>>* inc_calls;
  672.  
  673. Func();
  674. ~Func();
  675. void dispose();
  676.  
  677. Func& operator<<(string str);
  678. };
  679. Func::Func()
  680. {
  681. this->argv = new set<string>();
  682. this->inc_calls = new vector<pair<string, int>>();
  683. }
  684. Func::~Func()
  685. {
  686. this->dispose();
  687. }
  688. void Func::dispose()
  689. {
  690. if (this->argv != nullptr && this->argv != NULL)
  691. delete this->argv, this->argv = nullptr;
  692. if (this->inc_calls != nullptr && this->inc_calls != NULL)
  693. delete this->inc_calls, this->inc_calls = nullptr;
  694. }
  695. Func & Func::operator<<(string str)
  696. {
  697. this->argv->insert(str);
  698. return *this;
  699. }
  700.  
  701. int count_args(node<token<string, int>>* t)
  702. {
  703. if (t->val().id == "ident-list" || t->val().id == "expr-list")
  704. return 1 + count_args(t->rel()[1]);
  705. if ((t->val().id == "ident-list'" || t->val().id == "expr-list'") && t->rel()[0]->val().id != "epsilon")
  706. return count_args(t->rel()[1]);
  707. return 0;
  708. }
  709.  
  710. void _run(node<token<string, int>>* t, Func* func)
  711. {
  712. auto inc = t->rel();
  713. if (t->val().id == "factor" && inc[0]->val().id == "ident")
  714. {
  715. if (inc[1]->rel()[0]->val().id == "epsilon")
  716. {
  717. if (func->argv->count(inc[0]->val().lexeme) == 0)
  718. throw string("unidentified identificator");
  719. }
  720. else if (inc[1]->rel()[1]->val().id == "actual_args_list")
  721. {
  722. func->incident.insert(inc[0]->val().lexeme);
  723. func->inc_calls->emplace_back(inc[0]->val().lexeme, count_args(inc[1]->rel()[1]->rel()[0]));
  724. for (auto& i : inc[1]->rel()[1]->rel())
  725. if (i != nullptr && i != NULL)
  726. _run(i, func);
  727. }
  728. }
  729. else
  730. for (auto& i : t->rel())
  731. if (i != nullptr && i != NULL)
  732. _run(i, func);
  733. }
  734.  
  735. void analize(node<token<string, int>>* root, map<string, Func*>& matr)
  736. {
  737. auto func = root->rel()[0]->val().lexeme;
  738. auto args = root->rel()[2];
  739. auto body = root->rel()[5];
  740.  
  741. matr[func] = new Func();
  742. matr[func]->argc = count_args(args->rel()[0]);
  743. auto action = function<void(int, token<string, int>&)>([&matr, &func](int depth, token<string, int>& t) -> void
  744. {
  745. if (t.id == "ident")
  746. *matr[func] << t.lexeme;
  747. });
  748. args->run(action);
  749.  
  750. _run(body, matr[func]);
  751. }
  752.  
  753. void check_calls(map<string, Func*>& matr)
  754. {
  755. for (auto& p : matr)
  756. for (auto& t : *p.second->inc_calls)
  757. {
  758. if (matr.count(t.first) == 0)
  759. throw string("usage of undeclared function");
  760. if (matr[t.first]->argc != t.second)
  761. throw string("argument quantity mismatch");
  762. }
  763. }
  764.  
  765. void parse(istream& fin, vector<vector<int>>& vertices)
  766. {
  767. terminal<>
  768. num("number", [](const string & str, int pos) -> token<string, int>
  769. {
  770. int i = pos;
  771.  
  772. if (!is_numeral(str[i++]))
  773. return token<>();
  774.  
  775. for (; i < str.size() && is_numeral(str[i]); i++);
  776.  
  777. string t = str.substr(pos, i - pos);
  778. return token<>("number", t, stoi(t), -1, -1);
  779. }),
  780. ident("ident", [](const string & str, int pos) -> token<string, int>
  781. {
  782. int i = pos;
  783. if (!is_alphabetic(str[i++]))
  784. return token<>();
  785.  
  786. for (; i < str.size() && (is_alphabetic(str[i]) || is_numeral(str[i])); i++);
  787.  
  788. string t = str.substr(pos, i - pos);
  789. return token<>("ident", t, -1, -1, -1);
  790. }),
  791. eps("epsilon", [](const string & str, int pos) -> token<string, int>
  792. {
  793. return token<>("epsilon", "", 1, pos, -1);
  794. }),
  795. cln(":", [](const string & str, int pos) -> token<string, int>
  796. {
  797. if (pos < str.size() && str[pos] == ':' && (pos + 1 >= str.size() || str[pos + 1] != '='))
  798. return token<>(":", ":", -1, -1, -1);
  799. else
  800. return token<>();
  801. }),
  802. sless("<", [](const string & str, int pos) -> token<string, int>
  803. {
  804. if (pos < str.size() && str[pos] == '<' && (pos + 1 >= str.size() || (str[pos + 1] != '=' && str[pos + 1] != '>')))
  805. return token<>("<", "<", -1, -1, -1);
  806. else
  807. return token<>();
  808. }),
  809. snless(">", [](const string & str, int pos) -> token<string, int>
  810. {
  811. if (pos < str.size() && str[pos] == '>' && (pos + 1 >= str.size() || str[pos + 1] != '='))
  812. return token<>(">", ">", -1, -1, -1);
  813. else
  814. return token<>();
  815. }),
  816. plus("+", { "+" }),
  817. minus("-", { "-" }),
  818. mul("*", { "*" }),
  819. div("/", { "/" }),
  820. less("<=", { "<=" }),
  821. nless(">=", { ">=" }),
  822. eq("=", { "=" }),
  823. neq("<>", { "<>" }),
  824. ceq(":=", { ":=" }),
  825. qs("?", { "?" }),
  826. com(",", { "," }),
  827. sclm(";", { ";" }),
  828. lbr("(", { "(" }),
  829. rbr(")", { ")" });
  830.  
  831. nonterminal<>
  832. func("function"),
  833. fal("formal-args-list"),
  834. idls("ident-list"),
  835. idlsm("ident-list'"),
  836. expr("expr"),
  837. exprm("expr'"),
  838. cexpr("comparison_expr"),
  839. cexprm("comparison_expr'"),
  840. cop("comparison_op"),
  841. aexpr("arith_expr"),
  842. aexprm("arith_expr'"),
  843. aexprmm("arith_expr''"),
  844. term("term"),
  845. termm("term'"),
  846. termmm("term''"),
  847. fact("factor"),
  848. factm("factor'"),
  849. acargls("actual_args_list"),
  850. exprls("expr-list"),
  851. exprlsm("expr-list'");
  852.  
  853. func += { "ident", "(", "formal-args-list", ")", ":=", "expr", ";" };
  854.  
  855. fal += { "ident-list" };
  856. fal += { "epsilon" };
  857.  
  858. idls += { "ident", "ident-list'" };
  859. idlsm += { ",", "ident-list" };
  860. idlsm += { "epsilon" };
  861.  
  862. expr += { "comparison_expr", "expr'" };
  863. exprm += { "?", "comparison_expr", ":", "expr" };
  864. exprm += { "epsilon" };
  865.  
  866. cexpr += { "arith_expr", "comparison_expr'" };
  867. cexprm += { "comparison_op", "arith_expr" };
  868. cexprm += { "epsilon" };
  869.  
  870. cop += { "=" };
  871. cop += { "<>" };
  872. cop += { "<" };
  873. cop += { ">" };
  874. cop += { "<=" };
  875. cop += { ">=" };
  876.  
  877. aexpr += { "term", "arith_expr'" };
  878. aexprm += { "+", "term", "arith_expr''" };
  879. aexprm += { "-", "term", "arith_expr''" };
  880. aexprm += { "epsilon" };
  881. aexprmm += { "arith_expr'" };
  882. aexprmm += { "epsilon" };
  883.  
  884. term += { "factor", "term'" };
  885. termm += { "*", "factor", "term''" };
  886. termm += { "/", "factor", "term''" };
  887. termm += { "epsilon" };
  888. termmm += { "term'" };
  889. termmm += { "epsilon" };
  890.  
  891. fact += { "number" };
  892. fact += { "ident", "factor'" };
  893. fact += { "(", "expr", ")" };
  894. fact += { "-", "factor" };
  895. factm += { "(", "actual_args_list", ")" };
  896. factm += { "epsilon" };
  897.  
  898. acargls += { "expr-list" };
  899. acargls += { "epsilon" };
  900.  
  901. exprls += { "expr", "expr-list'" };
  902. exprlsm += { ",", "expr-list" };
  903. exprlsm += { "epsilon" };
  904.  
  905. parser<string, int> p(&eps);
  906. p << &num << &ident << &cln;
  907. p << &plus << &minus << &mul << &div << &sless << &less << &snless << &nless << &eq << &neq << &ceq << &qs << &com << &sclm << &lbr << &rbr;
  908. p << &func << &fal << &idls << &idlsm << &expr << &exprm << &cexpr << &cexprm << &cop << &aexpr << &aexprm << &aexprmm << &term << &termm << &termmm << &fact << &factm << &acargls << &exprls << &exprlsm;
  909.  
  910. map<string, Func*> matr;
  911. string temp;
  912.  
  913. try
  914. {
  915. for (; !fin.eof(); )
  916. {
  917. getline(fin, temp);
  918. if (temp == "" || temp == "\n" || temp == "\0")
  919. continue;
  920. auto result = p.parse(temp, func);
  921. analize(result.root, matr);
  922. }
  923.  
  924. check_calls(matr);
  925. }
  926. catch (string str)
  927. {
  928. for (auto& p : matr)
  929. delete p.second;
  930. throw str;
  931. }
  932.  
  933. int i = 0;
  934. for (auto& p : matr)
  935. {
  936. p.second->dispose();
  937. p.second->argc = i++;
  938. }
  939.  
  940. vertices.reserve(matr.size());
  941. for (auto& p : matr)
  942. {
  943. vertices.emplace_back();
  944. vertices[p.second->argc].reserve(p.second->incident.size());
  945. for (auto& t : p.second->incident)
  946. vertices[p.second->argc].emplace_back(matr[t]->argc);
  947. }
  948.  
  949. for (auto& p : matr)
  950. delete p.second;
  951. }
  952.  
  953. int timer = 1;
  954. int counter = 1;
  955.  
  956. struct vertex
  957. {
  958. int t1;
  959. int comp;
  960. int low;
  961.  
  962. vertex(int t1 = 0, int comp = 0, int low = 0);
  963. };
  964. vertex::vertex(int t1, int comp, int low)
  965. {
  966. this->t1 = t1;
  967. this->comp = comp;
  968. this->low = low;
  969. }
  970.  
  971. void visit_vertex(vector<vector<int>>& matr, vector<vertex>& data, int v, stack<int>& s)
  972. {
  973. data[v].t1 = data[v].low = timer++;
  974. s.push(v);
  975. for (auto& u : matr[v])
  976. {
  977. if (data[u].t1 == 0)
  978. visit_vertex(matr, data, u, s);
  979. if (data[u].comp == 0 && data[v].low > data[u].low)
  980. data[v].low = data[u].low;
  981. }
  982. if (data[v].t1 == data[v].low)
  983. {
  984. int u;
  985. do
  986. {
  987. u = s.top();
  988. s.pop();
  989. data[u].comp = counter;
  990. } while (u != v);
  991. counter++;
  992. }
  993. }
  994.  
  995. int tarjan(vector<vector<int>>& matr)
  996. {
  997. stack<int> s;
  998. vector<vertex> data(matr.size(), vertex());
  999.  
  1000. for (int t = 0; t < matr.size(); t++)
  1001. if (data[t].t1 == 0)
  1002. visit_vertex(matr, data, t, s);
  1003.  
  1004. return counter - 1;
  1005. }
  1006.  
  1007. int main(int argc, char** argv)
  1008. {
  1009. time_t timer = clock();
  1010. ifstream fin("input.txt");
  1011. //auto& fin = cin;
  1012.  
  1013. vector<vector<int>> matr;
  1014.  
  1015. try
  1016. {
  1017. parse(fin, matr);
  1018. }
  1019. catch (string str)
  1020. {
  1021. if (DEBUG) cout << str << endl;
  1022. cout << "error" << endl;
  1023. if (DEBUG) system("PAUSE");
  1024. return 0;
  1025. }
  1026.  
  1027. cout << tarjan(matr) << endl;
  1028.  
  1029. cout << (clock() - timer) / CLOCKS_PER_SEC << "s " << (clock() - timer) % CLOCKS_PER_SEC << "ms " << endl;
  1030. fin.close();
  1031.  
  1032. if (DEBUG) system("PAUSE");
  1033. return 0;
  1034. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement