navid/haze / ea08ceb46539df9cf3ac396bc0bd66fc4f6b9adc630e1596e79b8e4d3101673a / src/formatter.cpp
formatter.cpp
← src · 15903 bytes · raw · download
#include "haze.h"
#include <algorithm>
#include <cctype>
#include <string>
#include <vector>
namespace haze {
namespace {
struct FmtToken {
enum class Kind { Word, Number, String, Comment, Op, Punct, Raw };
Kind kind = Kind::Punct;
std::string text;
};
struct FmtLine {
std::vector<FmtToken> tokens;
bool raw = false;
bool removed = false;
};
bool is_wordlike(const FmtToken& t) {
return t.kind == FmtToken::Kind::Word || t.kind == FmtToken::Kind::Number ||
t.kind == FmtToken::Kind::String;
}
bool is_operator(const std::string& s) {
static const std::vector<std::string> ops = {
"=>", "==", "!=", "<=", ">=", "&&", "||", "=", "+=", "-=", "*=", "/=",
"%=", "+", "-", "*", "/", "%", "<", ">", "..", "++", "--"};
for (auto& op : ops)
if (s == op)
return true;
return false;
}
bool is_control_keyword(const std::string& s) {
return s == "if" || s == "else" || s == "for" || s == "while" || s == "match" ||
s == "return";
}
std::string rstrip(std::string s) {
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r'))
s.pop_back();
return s;
}
std::string lstrip(const std::string& s) {
size_t i = 0;
while (i < s.size() && (s[i] == ' ' || s[i] == '\t'))
i++;
return s.substr(i);
}
bool starts_with(const std::string& s, const std::string& prefix) {
return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}
std::vector<std::string> split_lines(const std::string& src) {
std::vector<std::string> lines;
std::string cur;
for (char c : src) {
if (c == '\n') {
lines.push_back(cur);
cur.clear();
} else {
cur.push_back(c);
}
}
lines.push_back(cur);
return lines;
}
std::vector<FmtToken> tokenize_line(const std::string& line, bool& block_comment,
bool& multiline_string) {
std::vector<FmtToken> out;
size_t i = 0;
while (i < line.size()) {
char c = line[i];
if (c == ' ' || c == '\t' || c == '\r') {
i++;
continue;
}
if (c == '\\' && i + 1 < line.size() && line[i + 1] == '\\') {
out.push_back(FmtToken{FmtToken::Kind::String, line.substr(i)});
multiline_string = true;
break;
}
if (c == '/' && i + 1 < line.size() && line[i + 1] == '/') {
out.push_back(FmtToken{FmtToken::Kind::Comment, line.substr(i)});
break;
}
if (c == '/' && i + 1 < line.size() && line[i + 1] == '*') {
size_t end = line.find("*/", i + 2);
if (end == std::string::npos) {
out.push_back(FmtToken{FmtToken::Kind::Comment, line.substr(i)});
block_comment = true;
break;
}
out.push_back(FmtToken{FmtToken::Kind::Comment, line.substr(i, end + 2 - i)});
i = end + 2;
continue;
}
if (c == '"') {
size_t start = i++;
while (i < line.size()) {
if (line[i] == '\\' && i + 1 < line.size()) {
i += 2;
continue;
}
if (line[i] == '"') {
i++;
break;
}
i++;
}
out.push_back(FmtToken{FmtToken::Kind::String, line.substr(start, i - start)});
continue;
}
if (std::isalpha(static_cast<unsigned char>(c)) || c == '_') {
size_t start = i++;
while (i < line.size() &&
(std::isalnum(static_cast<unsigned char>(line[i])) || line[i] == '_'))
i++;
out.push_back(FmtToken{FmtToken::Kind::Word, line.substr(start, i - start)});
continue;
}
if (std::isdigit(static_cast<unsigned char>(c))) {
size_t start = i++;
while (i < line.size() &&
(std::isalnum(static_cast<unsigned char>(line[i])) || line[i] == '_'))
i++;
out.push_back(FmtToken{FmtToken::Kind::Number, line.substr(start, i - start)});
continue;
}
static const char* multi[] = {"=>", "==", "!=", "<=", ">=", "&&", "||",
"+=", "-=", "*=", "/=", "%=", "++", "--",
"..", "::"};
bool matched = false;
for (auto op : multi) {
size_t n = std::char_traits<char>::length(op);
if (line.compare(i, n, op) == 0) {
out.push_back(FmtToken{FmtToken::Kind::Op, op});
i += n;
matched = true;
break;
}
}
if (matched)
continue;
out.push_back(FmtToken{FmtToken::Kind::Punct, std::string(1, c)});
i++;
}
return out;
}
std::vector<FmtLine> scan_lines(const std::string& src) {
std::vector<std::string> raw = split_lines(src);
std::vector<FmtLine> lines;
bool block_comment = false;
bool multiline_string = false;
for (auto& source_line : raw) {
FmtLine line;
std::string text = rstrip(source_line);
std::string trimmed = lstrip(text);
if (block_comment) {
line.raw = true;
line.tokens.push_back(FmtToken{FmtToken::Kind::Raw, trimmed});
if (trimmed.find("*/") != std::string::npos)
block_comment = false;
lines.push_back(std::move(line));
continue;
}
if (multiline_string) {
if (starts_with(trimmed, "\\\\")) {
line.raw = true;
line.tokens.push_back(FmtToken{FmtToken::Kind::Raw, trimmed});
lines.push_back(std::move(line));
continue;
}
multiline_string = false;
}
if (starts_with(trimmed, "\\\\")) {
multiline_string = true;
line.raw = true;
line.tokens.push_back(FmtToken{FmtToken::Kind::Raw, trimmed});
lines.push_back(std::move(line));
continue;
}
line.tokens = tokenize_line(text, block_comment, multiline_string);
lines.push_back(std::move(line));
}
return lines;
}
bool line_starts_with(const FmtLine& line, const std::string& text) {
for (auto& t : line.tokens) {
if (t.kind == FmtToken::Kind::Comment)
return false;
return t.text == text;
}
return false;
}
size_t last_code_index(const FmtLine& line) {
for (size_t i = line.tokens.size(); i > 0; i--)
if (line.tokens[i - 1].kind != FmtToken::Kind::Comment)
return i - 1;
return line.tokens.size();
}
bool has_code(const FmtLine& line) {
for (auto& t : line.tokens)
if (t.kind != FmtToken::Kind::Comment)
return true;
return false;
}
void join_open_braces(std::vector<FmtLine>& lines) {
for (size_t i = 1; i < lines.size(); i++) {
if (lines[i].raw || lines[i].removed)
continue;
size_t code_count = 0;
size_t code_index = 0;
for (size_t k = 0; k < lines[i].tokens.size(); k++) {
if (lines[i].tokens[k].kind == FmtToken::Kind::Comment)
continue;
code_count++;
code_index = k;
}
if (code_count != 1 || lines[i].tokens[code_index].text != "{")
continue;
size_t prev = i;
while (prev > 0 && (lines[prev - 1].removed || !has_code(lines[prev - 1])))
prev--;
if (prev == 0 || lines[prev - 1].removed)
continue;
if (line_starts_with(lines[prev - 1], ":"))
continue;
size_t insert_at = last_code_index(lines[prev - 1]);
if (insert_at >= lines[prev - 1].tokens.size())
lines[prev - 1].tokens.push_back(lines[i].tokens[code_index]);
else
lines[prev - 1].tokens.insert(lines[prev - 1].tokens.begin() + insert_at + 1,
lines[i].tokens[code_index]);
lines[i].removed = true;
}
}
void join_else_lines(std::vector<FmtLine>& lines) {
for (size_t i = 1; i < lines.size(); i++) {
if (lines[i].raw || lines[i].removed || !line_starts_with(lines[i], "else"))
continue;
size_t prev = i;
while (prev > 0 && (lines[prev - 1].removed || !has_code(lines[prev - 1])))
prev--;
if (prev == 0)
continue;
size_t last = last_code_index(lines[prev - 1]);
if (last >= lines[prev - 1].tokens.size() ||
lines[prev - 1].tokens[last].text != "}")
continue;
for (auto& t : lines[i].tokens)
lines[prev - 1].tokens.push_back(t);
lines[i].removed = true;
}
}
bool line_is_chain_header(const FmtLine& line) {
size_t i = 0;
while (i < line.tokens.size() && line.tokens[i].kind == FmtToken::Kind::Word &&
(line.tokens[i].text == "pub" || line.tokens[i].text == "pure"))
i++;
if (i >= line.tokens.size())
return false;
const std::string& word = line.tokens[i].text;
return word == "fn" || word == "for" || word == "contract";
}
void move_braces_after_chains(std::vector<FmtLine>& lines) {
for (size_t i = 0; i + 1 < lines.size(); i++) {
if (lines[i].raw || lines[i].removed)
continue;
if (!line_is_chain_header(lines[i]))
continue;
size_t j = i + 1;
while (j < lines.size() && !lines[j].raw && !lines[j].removed &&
line_starts_with(lines[j], ":"))
j++;
if (j == i + 1)
continue;
FmtLine& last = lines[j - 1];
size_t code = last_code_index(last);
if (code >= last.tokens.size() || last.tokens[code].text != "{")
continue;
last.tokens.erase(last.tokens.begin() + code);
FmtLine brace;
brace.tokens.push_back(FmtToken{FmtToken::Kind::Punct, "{"});
lines.insert(lines.begin() + j, std::move(brace));
i = j;
}
}
bool token_is_unary(const std::vector<FmtToken>& tokens, size_t i) {
if (!tokens[i].text.empty() && tokens[i].text == "!")
return true;
if (tokens[i].text != "-")
return false;
if (i == 0)
return true;
const std::string& prev = tokens[i - 1].text;
return is_operator(prev) || prev == "(" || prev == "[" || prev == "," || prev == ":" ||
prev == "{" || prev == "return";
}
bool need_space(const std::vector<FmtToken>& tokens, size_t i) {
const std::string& cur = tokens[i].text;
const std::string& prev = tokens[i - 1].text;
if (cur == "," || cur == ")" || cur == "]" || cur == "." || cur == "::")
return false;
if (prev == "(" || prev == "[" || prev == "." || prev == "::")
return false;
if (cur == ":")
return false;
if (prev == ":")
return true;
if (cur == "(")
return is_control_keyword(prev);
if (cur == "[")
return !(is_wordlike(tokens[i - 1]) || prev == ")" || prev == "]");
if (cur == "{")
return prev != "{";
if (cur == "}")
return prev != "{";
if (prev == "{")
return cur != "}";
if (prev == ",")
return true;
if (cur == ".." || prev == "..")
return false;
if (cur == "++" || cur == "--" || prev == "++" || prev == "--")
return false;
if (is_operator(cur) || is_operator(prev)) {
if (is_operator(prev) && token_is_unary(tokens, i - 1))
return false;
return true;
}
return true;
}
std::string format_tokens(const std::vector<FmtToken>& tokens) {
std::string code;
size_t i = 0;
for (; i < tokens.size(); i++) {
if (tokens[i].kind == FmtToken::Kind::Comment) {
if (!code.empty())
code += " ";
code += tokens[i].text;
i++;
break;
}
if (!code.empty() && need_space(tokens, i))
code += ' ';
code += tokens[i].text;
}
for (; i < tokens.size(); i++) {
if (tokens[i].kind == FmtToken::Kind::Comment) {
if (!code.empty())
code += " ";
code += tokens[i].text;
}
}
return code;
}
std::string indent(int depth) {
return std::string(static_cast<size_t>(depth < 0 ? 0 : depth) * 4, ' ');
}
} // namespace
std::string format_source(const std::string& source) {
std::vector<FmtLine> lines = scan_lines(source);
join_open_braces(lines);
join_else_lines(lines);
move_braces_after_chains(lines);
std::vector<std::string> output;
int depth = 0;
int bracket_depth = 0;
bool previous_blank = false;
for (auto& line : lines) {
if (line.removed)
continue;
bool blank = false;
if (line.raw) {
blank = line.tokens.empty() || line.tokens[0].text.empty();
} else {
blank = !has_code(line) &&
std::none_of(line.tokens.begin(), line.tokens.end(),
[](const FmtToken& t) {
return t.kind == FmtToken::Kind::Comment;
});
}
if (blank) {
if (!output.empty() && !previous_blank) {
output.push_back("");
previous_blank = true;
}
continue;
}
previous_blank = false;
if (line.raw) {
std::string text = line.tokens.empty() ? "" : line.tokens[0].text;
output.push_back(rstrip(indent(depth) + text));
continue;
}
int leading_closers = 0;
size_t first_code = 0;
bool have_first = false;
for (size_t k = 0; k < line.tokens.size(); k++) {
if (line.tokens[k].kind == FmtToken::Kind::Comment)
break;
if (!have_first) {
first_code = k;
have_first = true;
}
if (line.tokens[k].text == "}") {
leading_closers++;
continue;
}
break;
}
int continuation = 0;
if (have_first) {
const std::string& first = line.tokens[first_code].text;
if (bracket_depth > 0 && first != ")" && first != "]")
continuation = 1;
if (first == "." || first == "::" || is_operator(first))
continuation = 1;
}
int line_depth = depth - leading_closers + continuation;
if (line_depth < 0)
line_depth = 0;
if (line_starts_with(line, ":"))
line_depth = depth + 1;
std::string text = format_tokens(line.tokens);
output.push_back(rstrip(indent(line_depth) + text));
for (auto& t : line.tokens)
if (t.kind != FmtToken::Kind::Comment) {
if (t.text == "{")
depth++;
else if (t.text == "}")
depth--;
else if (t.text == "(" || t.text == "[")
bracket_depth++;
else if (t.text == ")" || t.text == "]")
bracket_depth--;
}
if (depth < 0)
depth = 0;
if (bracket_depth < 0)
bracket_depth = 0;
}
while (!output.empty() && output.back().empty())
output.pop_back();
if (output.empty())
return "";
std::string result;
for (size_t i = 0; i < output.size(); i++) {
if (i)
result.push_back('\n');
result += output[i];
}
result.push_back('\n');
return result;
}
} // namespace haze