tan  0.0.1
tokenized_source_file.cpp
1 #include "source_file/tokenized_source_file.h"
2 #include "source_file/token.h"
3 
4 using namespace tanlang;
5 
6 TokenizedSourceFile::TokenizedSourceFile(str filename, vector<Token *> tokens)
7  : _filename(std::move(filename)), _tokens(std::move(tokens)) {
8  if (_tokens.empty()) { // if empty, insert a token so that source location 0:0 is always valid
9  auto *f = new SourceFile();
10  f->from_string("\n");
11  _tokens.push_back(new Token(TokenType::COMMENTS, 0, 0, "", f));
12  }
13 }
14 
15 Token *TokenizedSourceFile::get_token(uint32_t loc) const {
16  TAN_ASSERT(loc < _tokens.size());
17  return _tokens[loc];
18 }
19 
20 uint32_t TokenizedSourceFile::get_line(uint32_t loc) const { return get_token(loc)->get_line() + 1; }
21 
22 uint32_t TokenizedSourceFile::get_col(uint32_t loc) const { return get_token(loc)->get_col() + 1; }
23 
24 str TokenizedSourceFile::get_token_str(uint32_t loc) const { return get_token(loc)->get_value(); }
25 
26 Token *TokenizedSourceFile::get_last_token() const { return _tokens.back(); }
27 
28 bool TokenizedSourceFile::is_eof(uint32_t loc) const { return loc >= _tokens.size(); }
29 
30 str TokenizedSourceFile::get_source_code(uint32_t start, uint32_t end) const {
31  str ret;
32 
33  Token *start_tok = get_token(start);
34  SrcLoc start_loc = Token::GetSrcLoc(start_tok);
35 
36  SourceFile *src = start_tok->src();
37 
38  // cover until the end of last token
39  SrcLoc end_loc = start_loc;
40  if (end >= _tokens.size()) {
41  end_loc = src->end();
42  } else {
43  end_loc = Token::GetSrcLoc(get_token(end + 1));
44  }
45 
46  ret = src->substr(start_loc, end_loc);
47 
48  // right trim
49  int i;
50  for (i = (int)ret.length() - 1; i >= 0; --i) {
51  if (!isspace(ret[(size_t)i]))
52  break;
53  }
54 
55  return ret.substr(0, (size_t)i + 1);
56 }
57 
58 str TokenizedSourceFile::get_filename() const { return _filename; }
59 
60 str TokenizedSourceFile::get_src_location_str(uint32_t loc) const {
61  return get_filename() + ":" + std::to_string(get_line(loc));
62 }
63 
64 SourceFile *TokenizedSourceFile::src() const { return _tokens[0]->src(); }
str substr(const SrcLoc &start) const
Get a substring from start to the end of the current line.
Definition: source_file.cpp:87
SrcLoc end() const
The end of source file (exclusive).