indentAction

This commit is contained in:
bronku 2025-11-25 15:48:15 +01:00
parent 4def48d206
commit 7f24975092
3 changed files with 15 additions and 11 deletions

View file

@ -1,5 +1,11 @@
#pragma once #pragma once
#include <stack> #include <stack>
enum class IndentAction
{
Indent,
Dedent,
None
};
class IndentHelper class IndentHelper
{ {
@ -9,19 +15,19 @@ class IndentHelper
public: public:
IndentHelper() { indent_stack.push(0); } IndentHelper() { indent_stack.push(0); }
int processLine(int spaces) IndentAction processLine(int spaces)
{ {
int current = indent_stack.top(); int current = indent_stack.top();
if (spaces == current) if (spaces == current)
{ {
return 0; return IndentAction::None;
} }
if (spaces > current) if (spaces > current)
{ {
indent_stack.push(spaces); indent_stack.push(spaces);
return 1; return IndentAction::Indent;
} }
pending_dedents = 0; pending_dedents = 0;
@ -34,10 +40,10 @@ public:
if (pending_dedents > 0) if (pending_dedents > 0)
{ {
pending_dedents--; pending_dedents--;
return -1; return IndentAction::Dedent;
} }
return 0; return IndentAction::None;
} }
// returns false on failure // returns false on failure

View file

@ -18,9 +18,9 @@
for (int i = 0; i < yyleng; i++) for (int i = 0; i < yyleng; i++)
spaces += (yytext[i] == '\t') ? 8 : 1; spaces += (yytext[i] == '\t') ? 8 : 1;
int result = indent_helper.processLine(spaces); IndentAction result = indent_helper.processLine(spaces);
if (result > 0) return yy::parser::token::TOK_INDENT; if (result == IndentAction::Indent) return yy::parser::token::TOK_INDENT;
if (result < 0) return yy::parser::token::TOK_DEDENT; if (result == IndentAction::Dedent) return yy::parser::token::TOK_DEDENT;
} }
\n { return yy::parser::token::TOK_NEWLINE; } \n { return yy::parser::token::TOK_NEWLINE; }

View file

@ -25,9 +25,7 @@ public:
if (token == yy::parser::token::TOK_EOF) if (token == yy::parser::token::TOK_EOF)
{ {
int result = indent_helper.processLine(0); if (indent_helper.processLine(0) == IndentAction::Dedent)
if (result == -1)
{ {
return yy::parser::token::TOK_DEDENT; return yy::parser::token::TOK_DEDENT;
} }