A Hugo incarnation of the blog.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

parse_driver.cpp 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "parse_driver.hpp"
  2. #include "scanner.hpp"
  3. #include <sstream>
  4. file_mgr::file_mgr() : file_offset(0) {
  5. line_offsets.push_back(0);
  6. }
  7. void file_mgr::write(const char* buf, size_t len) {
  8. string_stream.write(buf, len);
  9. file_offset += len;
  10. }
  11. void file_mgr::mark_line() {
  12. line_offsets.push_back(file_offset);
  13. }
  14. void file_mgr::finalize() {
  15. file_contents = string_stream.str();
  16. }
  17. size_t file_mgr::get_index(int line, int column) const {
  18. assert(line > 0 && line <= line_offsets.size());
  19. return line_offsets.at(line-1) + column - 1;
  20. }
  21. size_t file_mgr::get_line_end(int line) const {
  22. if(line == line_offsets.size()) return file_contents.size();
  23. return get_index(line+1, 1);
  24. }
  25. void file_mgr::print_location(
  26. std::ostream& stream,
  27. const yy::location& loc,
  28. bool highlight) const {
  29. size_t print_start = get_index(loc.begin.line, 1);
  30. size_t highlight_start = get_index(loc.begin.line, loc.begin.column);
  31. size_t highlight_end = get_index(loc.end.line, loc.end.column);
  32. size_t print_end = get_line_end(loc.end.line);
  33. const char* content = file_contents.c_str();
  34. stream.write(content + print_start, highlight_start - print_start);
  35. if(highlight) stream << "\033[4;31m";
  36. stream.write(content + highlight_start, highlight_end - highlight_start);
  37. if(highlight) stream << "\033[0m";
  38. stream.write(content + highlight_end, print_end - highlight_end);
  39. }
  40. bool parse_driver::operator()() {
  41. FILE* stream = fopen(file_name.c_str(), "r");
  42. if(!stream) return false;
  43. yyscan_t scanner;
  44. yylex_init(&scanner);
  45. yyset_in(stream, scanner);
  46. yy::parser parser(scanner, *this);
  47. parser();
  48. yylex_destroy(scanner);
  49. fclose(stream);
  50. file_m->finalize();
  51. return true;
  52. }
  53. yy::location& parse_driver::get_current_location() {
  54. return location;
  55. }
  56. file_mgr& parse_driver::get_file_manager() const {
  57. return *file_m;
  58. }
  59. definition_group& parse_driver::get_global_defs() const {
  60. return *global_defs;
  61. }