Make driver keep track of line numbers and locations.

This commit is contained in:
2020-09-09 13:57:01 -07:00
parent 789f277780
commit 578d580683
2 changed files with 47 additions and 28 deletions

View File

@@ -1,6 +1,7 @@
#pragma once
#include <string>
#include <fstream>
#include <sstream>
#include "definition.hpp"
#include "location.hh"
#include "parser.hpp"
@@ -13,15 +14,17 @@ void scanner_destroy(yyscan_t* scanner);
struct parse_driver {
std::string file_name;
std::ifstream file_stream;
std::ostringstream string_stream;
yy::location location;
size_t file_offset;
std::vector<size_t> line_offsets;
definition_group global_defs;
std::string read_file;
parse_driver(const std::string& file)
: file_name(file) {}
: file_name(file), file_offset(0) {}
void run_parse() {
file_stream.open(file_name);
@@ -31,10 +34,28 @@ struct parse_driver {
yy::parser parser(scanner, *this);
parser();
scanner_destroy(&scanner);
read_file = string_stream.str();
}
int get() {
return file_stream.get();
int new_char = file_stream.get();
if(new_char == EOF) return EOF;
file_offset++;
if(new_char == '\n') line_offsets.push_back(file_offset);
string_stream.put(new_char);
return new_char;
}
size_t get_index(int line, int column) {
assert(line-1 < line_offsets.size());
size_t file_offset = line ? 0 : line_offsets[line-1];
file_offset += column - 1;
return file_offset;
}
size_t get_line_end(int line) {
assert(line < line_offsets.size());
return line_offsets[line] - 1;
}
};