Preprocess tabs when printing error context

This commit is contained in:
Nikita Lisitsa 2025-12-20 12:52:23 +03:00
parent 99418bdf6a
commit 26ab539d3c
2 changed files with 20 additions and 3 deletions

View file

@ -25,16 +25,33 @@ std::string extract_nth_line(std::filesystem::path const & path, std::size_t n)
return {};
}
std::size_t replace_tabs_with_spaces(std::string & str, std::size_t count)
{
std::string replaced;
for (char c : str)
{
if (c == '\t')
replaced.append(count, ' ');
else
replaced.append(1, c);
}
std::swap(str, replaced);
return str.size() - replaced.size();
}
void print_error_context(std::filesystem::path const & file, pslang::ast::location const & location)
{
if (location.begin.line == location.end.line)
{
std::size_t max_line_number_digits = std::floor(std::log10(location.begin.line)) + 1;
auto line = extract_nth_line(file, location.begin.line);
auto extra = replace_tabs_with_spaces(line, 2);
std::cerr << std::endl;
std::cerr << "line " << std::setw(max_line_number_digits) << std::right << location.begin.line << ": ";
std::cerr << extract_nth_line(file, location.begin.line) << std::endl;
std::cerr << std::string(std::max<std::size_t>(location.begin.column, 1) - 1 + max_line_number_digits + 7, ' ') << std::string(location.end.column - location.begin.column, '^') << std::endl;
std::cerr << line << std::endl;
std::cerr << std::string(std::max<std::size_t>(location.begin.column, 1) - 1 + max_line_number_digits + 7 + extra, ' ') << std::string(location.end.column - location.begin.column, '^') << std::endl;
}
}

View file

@ -4,6 +4,7 @@ Future plans:
* Introduce type checking & inference as a separate pre-execution/compilation AST pass + add type information into expression nodes
* Pointers: pointer types, address-of operator (&), dereferencing, scope-based lifetime tracking in interpreter
* Function overloading: separate functions from values (again) in interpreter, allow casting to specific function type to take function value
* C FFI: `foreign func sin(x : f32) -> f32`
* Const propagation: annotate expression AST nodes that are computable in compile-time
* Generic parameters: can be either values or `t : type`, but always compile-time
* Generic structs: `struct <t : type, n : u64> array:`, require explicitly specifying parameters when instantiated (used as a type or creating a value)
@ -14,7 +15,6 @@ Future plans:
Backlog:
* Mutually recursive functions
* Figure out indentation: keep tabs - what to do with printing errors? Enforce e.g. 4 spaces?
* Default-constructing primitive types
* Empty array expression
* Calling functions as methods