Brainf[数据删除]k语言的一个轻量级IDE(终端)
BFs_YYDS
·
·
科技·工程
#include<iostream>
#include<fstream>
#include<vector>
#include<unordered_map>
#include<conio.h>
#include<windows.h>
#include<algorithm>
#include <cstdio> // 用于文件操作
#pragma warning(disable:4996)
using namespace std;
ofstream logo("log.log");
size_t memory_size;
int g_cell_init_value = 0;
bool g_show_warnings = true;
int g_input_mode = 0;
bool g_show_steps = false;
bool g_show_code = false;
bool g_debug_mode = false;
// 自动换行相关设置
bool g_auto_wrap = false;
int g_wrap_column = 80;
string g_code; // 编辑器内容
void show_editor(const string&, size_t);
void editor();
void execute(char*);
void settings();
void load_code_from_file(string&, size_t&);
void save_code_to_file(const string&);
int memory_show_size = 16;
// ===================== 编辑器显示 =====================
void show_editor(const string& code, size_t cursor_pos) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
system("cls");
printf("Brainfuck 编辑器 (ESC:退出, F5:运行, F6:调试, F2:设置, F3:保存, F4:加载)\n");
printf("方向键移动,输入编辑,DEL/BKSP删除,Enter换行\n\n");
// 按内容分行,换行符算作内容(code_pos和cursor_pos都计入)
vector<string> lines;
vector<bool> is_manual_newline;
string cur_line;
int col_count = 0;
size_t code_pos = 0;
for (size_t i = 0; i < code.size(); ++i, ++code_pos) {
char c = code[i];
if (c == '\n') {
cur_line += c; // 换行符算作内容
lines.push_back(cur_line);
is_manual_newline.push_back(true);
cur_line.clear();
col_count = 0;
}
else {
cur_line += c;
col_count++;
if (g_auto_wrap && col_count >= g_wrap_column) {
lines.push_back(cur_line);
is_manual_newline.push_back(false);
cur_line.clear();
col_count = 0;
}
}
}
if (!cur_line.empty() || code.empty()) {
lines.push_back(cur_line);
is_manual_newline.push_back(true);
}
// 计算光标所在行和列(列号包含换行符)
size_t line = 0, col = 0, pos = 0;
for (size_t i = 0; i < lines.size(); ++i) {
if (cursor_pos < pos + lines[i].size()) {
line = i;
col = cursor_pos - pos;
break;
}
pos += lines[i].size();
}
// 括号匹配分析
vector<int> bracket_stack;
vector<bool> unmatched(code.size(), false);
vector<int> unmatched_indices;
for (size_t i = 0; i < code.size(); ++i) {
if (code[i] == '[') {
bracket_stack.push_back((int)i);
}
else if (code[i] == ']') {
if (!bracket_stack.empty()) {
bracket_stack.pop_back();
}
else {
unmatched[i] = true;
unmatched_indices.push_back((int)i);
}
}
}
for (int idx : bracket_stack) {
unmatched[idx] = true;
unmatched_indices.push_back(idx);
}
vector<bool> highlight_green(code.size(), false);
for (int idx : unmatched_indices) {
for (int offset = -3; offset <= 3; ++offset) {
int pos = idx + offset;
if (pos >= 0 && pos < (int)code.size() && !unmatched[pos]) {
highlight_green[pos] = true;
}
}
}
// 显示代码并高亮,手动换行显示行号,自动换行不显示
code_pos = 0;
size_t line_number = 1;
for (size_t i = 0; i < lines.size(); ++i) {
if (is_manual_newline[i]) {
printf("%3zu ", line_number++);
}
else {
printf(" ");
}
for (size_t j = 0; j < lines[i].size(); ++j, ++code_pos) {
if (code_pos == cursor_pos) {
SetConsoleTextAttribute(hConsole, BACKGROUND_RED | BACKGROUND_GREEN | FOREGROUND_INTENSITY);
}
else if (unmatched[code_pos]) {
SetConsoleTextAttribute(hConsole, BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_INTENSITY);
}
else if (highlight_green[code_pos]) {
SetConsoleTextAttribute(hConsole, BACKGROUND_GREEN | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
else if (strchr("+-<>[],.", lines[i][j])) {
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
else {
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
// 显示内容,包括换行符
if (lines[i][j] == '\n') {
printf("\\n");
}
else {
printf("%c", lines[i][j]);
}
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
// 光标在行尾时显示
if (code_pos == cursor_pos && col == lines[i].size()) {
SetConsoleTextAttribute(hConsole, BACKGROUND_RED | BACKGROUND_GREEN | FOREGROUND_INTENSITY);
printf(" ");
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
printf("\n");
}
printf("\n光标位置:第 %zu 行,第 %zu 列\n", line + 1, col + 1);
// 括号不匹配警告
if (!unmatched_indices.empty()) {
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("警告:括号不匹配!\n");
for (int idx : unmatched_indices) {
printf("未匹配括号位置 %d: ", idx);
printf("[");
for (int offset = -3; offset <= 3; ++offset) {
int pos = idx + offset;
if (pos >= 0 && pos < (int)code.size()) {
if (pos == idx) {
SetConsoleTextAttribute(hConsole, BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_INTENSITY);
}
else {
SetConsoleTextAttribute(hConsole, BACKGROUND_GREEN | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
if (code[pos] == '\n') {
printf("\\n");
}
else {
printf("%c", code[pos]);
}
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
}
printf("]\n");
}
printf("请检查您的代码!\n");
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
}
// ===================== 编辑器主循环 =====================
void editor() {
g_code = "";
size_t cursor = 0;
show_editor(g_code, cursor);
while (true) {
printf("当前代码长度: %zu\n", g_code.size());
int ch = _getch();
logo << "ch=" << ch << endl;
if (ch == 0 || ch == 224) {
int func = _getch();
logo << "func=" << func << endl;
// 分行处理
vector<size_t> line_starts;
size_t pos = 0;
line_starts.push_back(0);
for (size_t i = 0; i < g_code.size(); ++i) {
if (g_code[i] == '\n') line_starts.push_back(i + 1);
else if (g_auto_wrap && (i - line_starts.back()) >= g_wrap_column) line_starts.push_back(i);
}
size_t line = 0, col = 0;
for (size_t i = 0; i < line_starts.size(); ++i) {
if (cursor < line_starts[i]) break;
line = i;
}
col = cursor - line_starts[line];
switch (func) {
case 75: // 左
if (cursor > 0) cursor--;
break;
case 77: // 右
if (cursor < g_code.size()) cursor++;
break;
case 72: // 上
if (line > 0) {
size_t prev_len = (line_starts[line] - line_starts[line - 1]);
cursor = line_starts[line - 1] + min(col, prev_len - 1);
}
break;
case 80: // 下
if (line + 1 < line_starts.size()) {
size_t next_len = (line_starts[line + 1] - line_starts[line]);
cursor = line_starts[line + 1] + min(col, next_len - 1);
}
break;
case 83: // DEL
if (cursor < g_code.size()) g_code.erase(cursor, 1);
break;
case 61: // F3 保存
save_code_to_file(g_code);
break;
case 62: // F4 加载
load_code_from_file(g_code, cursor);
break;
case 60: // F2
settings();
break;
case 63: // F5
execute(nullptr);
cout << endl;
system("pause");
break;
case 64: // F6
g_debug_mode = true;
execute(nullptr);
g_debug_mode = false;
break;
}
}
else if (ch == 27) { // ESC
return;
}
else if (ch == 8) { // BKSP
if (cursor > 0) {
g_code.erase(cursor - 1, 1);
cursor--;
}
}
else if (ch == 13) { // Enter 换行
g_code.insert(cursor, 1, '\n');
cursor++;
}
else if (ch >= 32 && ch <= 126) { // 可见字符
g_code.insert(cursor, 1, (char)ch);
cursor++;
}
show_editor(g_code, cursor);
}
}
// ===================== 解释器 =====================
void execute(char* file) {
system("cls");
vector<unsigned char> memory(memory_size, g_cell_init_value);
auto cur = memory.begin();
string program;
if (file) {
ifstream code(file);
if (!code.is_open()) {
cout << "无法打开文件: " << file << endl;
return;
}
program.assign((istreambuf_iterator<char>(code)), istreambuf_iterator<char>());
}
else {
program = g_code;
}
// 过滤掉 \r \n \t 和空格
string filtered;
for (char c : program) {
if (c != '\r' && c != '\n' && c != '\t' && c != ' ') {
filtered += c;
}
}
program = filtered;
printf("已加载代码:\n");
for (size_t i = 0; i < program.size(); ++i) {
printf("%c", program[i]);
}
printf("\n\n");
printf("代码长度: %zu\n", program.size());
size_t pc = 0;
int cnt = 1;
unordered_map<size_t, size_t> loop_map;
vector<size_t> stack;
for (size_t i = 0; i < program.size(); ++i) {
if (program[i] == '[') stack.push_back(i);
else if (program[i] == ']') {
if (stack.empty()) {
cout << "字符 " << (i + 1) << ": 程序中有多余的 ']' " << endl;
return;
}
size_t open = stack.back();
stack.pop_back();
loop_map[open] = i;
loop_map[i] = open;
}
}
if (!stack.empty()) {
cout << "字符 " << (stack.back() + 1) << ": 程序中有多余的 '[' " << endl;
return;
}
vector<size_t> breakpoints;
bool step_mode = g_debug_mode;
while (pc < program.size()) {
char now = program[pc];
if (g_show_steps || step_mode) {
printf("步骤 %d: '%c' | 指针: %zd | 值: %d\n", cnt, now, cur - memory.begin(), *cur);
}
if (g_show_code || step_mode) {
printf("当前代码: ");
for (size_t i = 0; i < program.size(); ++i) {
if (i == pc)
printf("[%c]", program[i]);
else
printf("%c", program[i]);
}
printf("\n");
}
// 只在 step_mode==true 时进入调试命令等待
if (g_debug_mode && step_mode) {
bool wait_debug_cmd = true;
while (wait_debug_cmd) {
printf("调试器 (n:下一步, c:继续, b:断点, l:代码列表, m:内存, p:指针, q:退出): ");
char cmd = _getch();
if (cmd == 'q') return;
if (cmd == 'b') {
printf("\n设置断点位置 (0-%zu): ", program.size() - 1);
size_t bp_pos;
if (scanf("%zu", &bp_pos) == 1 && bp_pos < program.size()) {
breakpoints.push_back(bp_pos);
printf("断点已设置在 %zu\n", bp_pos);
}
else {
printf("无效位置!\n");
}
fflush(stdin);
wait_debug_cmd = true;
}
if (cmd == 'l') {
printf("\n代码列表:\n");
for (size_t i = 0; i < program.size(); ++i) {
if (i == pc)
printf("->%4zu: [%c]\n", i, program[i]);
else
printf(" %4zu: %c\n", i, program[i]);
}
wait_debug_cmd = true;
}
if (cmd == 'm') {
printf("\n内存转储 (以指针为中心, %d 单元):\n", memory_show_size);
int half = memory_show_size / 2;
int ptr = (int)(cur - memory.begin());
int start = max(0, ptr - half);
int end = min((int)memory.size(), ptr + half);
for (int i = start; i < end; ++i) {
if (i == ptr)
printf("[*%d]=%d ", i, memory[i]);
else
printf("[%d]=%d ", i, memory[i]);
}
printf("\n");
wait_debug_cmd = true;
}
if (cmd == 'p') {
printf("\n指针位置: %zd, 当前值: %d\n", cur - memory.begin(), *cur);
wait_debug_cmd = true;
}
if (cmd == 'c') {
step_mode = false;
wait_debug_cmd = false;
}
if (cmd == 'n') {
step_mode = true;
wait_debug_cmd = false;
}
}
}
switch (now) {
case '+':
++(*cur);
break;
case '-':
--(*cur);
break;
case '<':
if (cur == memory.begin()) {
cout << "步骤 " << cnt << ": 指针越界" << endl;
break;
}
--cur;
break;
case '>':
if (++cur == memory.end()) {
cout << "步骤 " << cnt << ": 指针越界" << endl;
--cur;
break;
}
break;
case '.':
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, BACKGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
cout << static_cast<char>(*cur);
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
break;
case ',':
{
char input;
cin >> input;
*cur = input;
}
break;
case '[':
if (*cur == 0) {
pc = loop_map[pc];
}
break;
case ']':
if (*cur != 0) {
pc = loop_map[pc];
}
break;
default:
if (now != ' ' && now != '\t' && g_show_warnings) {
cout << "步骤 " << cnt << ": 非法字符 '" << now << "' 出现在程序中" << endl;
}
break;
}
++pc;
++cnt;
if ((g_show_steps || step_mode) && !g_debug_mode) {
system("pause");
}
if (g_debug_mode && !step_mode) {
for (size_t bp : breakpoints) {
if (pc == bp) {
printf("\n命中断点 %zu\n", pc);
step_mode = true;
break;
}
}
}
}
}
// ===================== 设置界面 =====================
void settings() {
const int min_size = 16;
const int max_size = 65536;
int selected = 0;
size_t temp_memory_size = memory_size ? memory_size : 30000;
int cell_init_value = g_cell_init_value;
bool show_warnings = g_show_warnings;
int input_mode = g_input_mode;
bool show_steps = g_show_steps;
bool show_code = g_show_code;
bool debug_mode = g_debug_mode;
int temp_memory_show_size = memory_show_size;
bool auto_wrap = g_auto_wrap;
int wrap_column = g_wrap_column;
const char* items[] = {
"【内存设置】",
"内存大小",
"单元初值",
"内存显示单元数",
"【显示设置】",
"显示警告",
"显示步骤",
"显示代码",
"【调试设置】",
"调试模式",
"【编辑器设置】",
"自动换行",
"换行列数",
"【应用设置】",
"应用"
};
const int item_count = sizeof(items) / sizeof(items[0]);
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
while (true) {
system("cls");
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
printf("设置 (方向键移动, 回车选择)\n\n");
for (int i = 0; i < item_count; ++i) {
if (strstr(items[i], "【") == items[i]) {
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
printf("%s\n", items[i]);
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
continue;
}
if (i == selected) {
SetConsoleTextAttribute(hConsole, BACKGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
printf(" > ");
}
else {
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
printf(" ");
}
printf("%s", items[i]);
switch (i) {
case 1: printf(": %zu", temp_memory_size); break;
case 2: printf(": %d", cell_init_value); break;
case 3: printf(": %d", temp_memory_show_size); break;
case 5: printf(": %s", show_warnings ? "开" : "关"); break;
case 6: printf(": %s", show_steps ? "开" : "关"); break;
case 7: printf(": %s", show_code ? "开" : "关"); break;
case 9: printf(": %s", debug_mode ? "开" : "关"); break;
case 11: printf(": %s", auto_wrap ? "开" : "关"); break;
case 12: printf(": %d", wrap_column); break;
}
printf("\n");
}
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
int ch = _getch();
if (ch == 0 || ch == 224) {
ch = _getch();
switch (ch) {
case 72: // 上
{
int tries = 0;
do {
if (selected == 0) break;
selected--;
tries++;
} while (strstr(items[selected], "【") == items[selected] && tries < item_count);
}
break;
case 80: // 下
{
int tries = 0;
do {
if (selected == item_count - 1) break;
selected++;
tries++;
} while (strstr(items[selected], "【") == items[selected] && tries < item_count);
}
break;
case 75: // 左
if (selected == 1 && temp_memory_size > min_size) temp_memory_size /= 2;
if (selected == 2 && cell_init_value > 0) cell_init_value--;
if (selected == 3 && temp_memory_show_size > 4) temp_memory_show_size -= 4;
if (selected == 5) show_warnings = !show_warnings;
if (selected == 6) show_steps = !show_steps;
if (selected == 7) show_code = !show_code;
if (selected == 9) debug_mode = !debug_mode;
if (selected == 11) auto_wrap = !auto_wrap;
if (selected == 12 && wrap_column > 20) wrap_column -= 10;
break;
case 77: // 右
if (selected == 1 && temp_memory_size < max_size) temp_memory_size *= 2;
if (selected == 2 && cell_init_value < 255) cell_init_value++;
if (selected == 3 && temp_memory_show_size < 128) temp_memory_show_size += 4;
if (selected == 5) show_warnings = !show_warnings;
if (selected == 6) show_steps = !show_steps;
if (selected == 7) show_code = !show_code;
if (selected == 9) debug_mode = !debug_mode;
if (selected == 11) auto_wrap = !auto_wrap;
if (selected == 12 && wrap_column < 200) wrap_column += 10;
break;
}
}
else if (ch == 13) {
switch (selected) {
case 1: {
printf("\n请输入新的内存大小 (%d-%d): ", min_size, max_size);
size_t val;
if (scanf("%zu", &val) == 1 && val >= min_size && val <= max_size) temp_memory_size = val;
fflush(stdin);
break;
}
case 2: {
printf("\n请输入新的单元初值 (0-255): ");
int val;
if (scanf("%d", &val) == 1 && val >= 0 && val <= 255) cell_init_value = val;
fflush(stdin);
break;
}
case 3: {
printf("\n请输入内存显示单元数 (4-128): ");
int val;
if (scanf("%d", &val) == 1 && val >= 4 && val <= 128) temp_memory_show_size = val;
fflush(stdin);
break;
}
case 5: show_warnings = !show_warnings; break;
case 6: show_steps = !show_steps; break;
case 7: show_code = !show_code; break;
case 9: debug_mode = !debug_mode; break;
case 11: auto_wrap = !auto_wrap; break;
case 12: {
printf("\n请输入换行列数 (20-200): ");
int val;
if (scanf("%d", &val) == 1 && val >= 20 && val <= 200) wrap_column = val;
fflush(stdin);
break;
}
case 14: {
memory_size = temp_memory_size;
g_cell_init_value = cell_init_value;
g_show_warnings = show_warnings;
g_input_mode = input_mode;
g_show_steps = show_steps;
g_show_code = show_code;
g_debug_mode = debug_mode;
memory_show_size = temp_memory_show_size;
g_auto_wrap = auto_wrap;
g_wrap_column = wrap_column;
return;
}
}
}
}
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
// ===================== 文件保存/加载 =====================
void save_code_to_file(const string& code) {
printf("\n请输入要保存的文件名: ");
char filename[256];
scanf("%255s", filename);
FILE* fp = fopen(filename, "w");
if (!fp) {
printf("无法打开文件进行写入!\n");
return;
}
fwrite(code.c_str(), 1, code.size(), fp);
fclose(fp);
printf("代码已保存到 %s\n", filename);
system("pause");
}
void load_code_from_file(string& code, size_t& cursor) {
printf("\n请输入要加载的文件名: ");
char filename[256];
scanf("%255s", filename);
FILE* fp = fopen(filename, "r");
if (!fp) {
printf("无法打开文件进行读取!\n");
return;
}
code.clear();
char buf[1024];
while (size_t n = fread(buf, 1, sizeof(buf), fp)) {
code.append(buf, n);
}
fclose(fp);
cursor = code.size();
printf("代码已从 %s 加载\n", filename);
system("pause");
}
// ===================== 主函数 =====================
int main() {
memory_size = 30000;
settings();
editor();
return 0;
}
/*
用户指南:
欢迎来到 Brainfuck 集成开发环境和调试器!
1. 启动与设置:
- 启动程序时,您将进入设置菜单。
- 您可以配置内存大小、单元初始值、警告、输入模式(字符/整数)、步长显示、代码显示、调试模式以及在内存转储中显示多少个内存单元。
- 使用箭头键在选项之间移动,按回车键选择,使用左右箭头键调整值。
2. 编辑器使用说明:
- 设置完成后,您将进入代码编辑器。
- 直接输入 Brainfuck 代码。编辑器支持所有标准的 Brainfuck 指令:+ - < > [ ] .,
- 使用方向键移动光标。
- DEL 键删除光标处的字符;BKSP 键删除光标前的字符。
- F2 键随时打开设置菜单。
- F5 键运行代码。
- F6 键进入调试器。
- F3 保存代码到文件
- F4 从文件加载代码
3. 语法高亮显示和括号匹配:
- Brainfuck 指令以绿色高亮显示。
- 光标位置以黄色高亮显示。
- 未匹配的括号(无论是 [ 还是 ])以红色高亮显示。
- 如果存在未匹配的括号,编辑器下方会显示警告。
4. 运行与调试:
- F5 正常运行代码。
- F6 启动调试器。在调试模式下,您可以:
- n:执行下一条指令(单步执行)。
- c:继续运行,直到下一个断点或程序结束。
- b:在特定代码位置设置断点。
- l:列出代码,突出显示当前位置。
- m:显示以指针为中心的内存转储,可配置单元数量。
- p:显示指针位置和当前单元值。
- q:退出调试。
5. 断点:
- 在调试模式下,使用“b”设置断点。输入代码位置(基于 0 的索引)。
- 当您按“c”时,程序将运行直至遇到断点或结束。
6. 内存与指针:
- 内存转储(m)会显示指针周围的单元格,指针所在的单元格会被标记。
- 您可以在设置中配置要显示的单元格数量。
7. 输入/输出:
- “,” 从输入中读取一个字符(如果输入模式设置为整数,则读取一个整数)。
- “.” 将当前单元格作为字符输出。
8. 错误与警告:
- 如果启用了警告功能,使用非 Brainfuck 字符将会显示警告。
- 指针越界和括号不匹配也会触发警告。
9. 保存与加载:
- F3 保存代码到文件
- F4 从文件加载代码
10. 退出:
- 在编辑器中按 ESC 键退出程序。
提示:
- 运行代码前务必检查括号是否匹配。
- 使用断点和单步模式调试复杂的循环。
- 根据不同的 Brainfuck 程序调整内存大小和单元初始值。
- 该集成开发环境旨在快速原型设计、学习和调试 Brainfuck 代码。
尽情编写brainfuck吧!
*/