Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement conditions support #9

Merged
merged 3 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/data-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ Zynk offers several primitive data types:
- **Float (`float`)**: Represents numbers with decimals.
- **Bool (`bool`)**: Represents truth values, true or false (1 and 0).
- **String (`String`)**: Represents sequences of characters.
- **Null (`null`)**: Represents null value.
59 changes: 42 additions & 17 deletions src/execution/evaluator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ void Evaluator::evaluate(ASTBase* ast) {
case ASTType::Print:
evaluatePrint(static_cast<ASTPrint*>(ast));
break;
case ASTType::Condition:
evaluateCondition(static_cast<ASTCondition*>(ast));
break;
default:
throw ZynkError{ ZynkErrorType::RuntimeError, "Unknown AST type." };
}
Expand Down Expand Up @@ -69,6 +72,7 @@ void Evaluator::evaluateVariableModify(ASTVariableModify* variableModify) {
}

std::string Evaluator::evaluateExpression(ASTBase* expression) {
if (expression == nullptr) return "null";
switch (expression->type) {
case ASTType::Value:
return static_cast<ASTValue*>(expression)->value;
Expand All @@ -81,7 +85,7 @@ std::string Evaluator::evaluateExpression(ASTBase* expression) {
const std::string left = evaluateExpression(operation->left.get());
const std::string right = evaluateExpression(operation->right.get());
try {
return calculate<std::string>(left, right, operation->op);
return calculateString(left, right, operation->op);
} catch (const std::invalid_argument&) {
throw ZynkError{
ZynkErrorType::ExpressionError,
Expand All @@ -94,29 +98,50 @@ std::string Evaluator::evaluateExpression(ASTBase* expression) {
}
}

template <typename T>
T calculate(const T& left, const T& right, const std::string& op) {
if (op == "*") return left * right;
if (op == "-") return left - right;
if (op == "+") return left + right;
void Evaluator::evaluateCondition(ASTCondition* condition) {
const std::string value = evaluateExpression(condition->expression.get());
bool result = true;
if (value == "0" || value.empty() || value == "null" || value == "false") result = false;

env.enterNewBlock();
for (const std::unique_ptr<ASTBase>& child : result ? condition->body : condition->elseBody) {
evaluate(child.get());
}
env.exitCurrentBlock();
}

std::string calculate(const float left, const float right, const std::string& op) {
if (op == "*") return std::to_string(left * right);
if (op == "-") return std::to_string(left - right);
if (op == "+") return std::to_string(left + right);
if (op == "/") {
if (right == 0) throw ZynkError{ ZynkErrorType::RuntimeError, "division by zero" };
return left / right;
return std::to_string(left / right);
}
throw ZynkError{ZynkErrorType::RuntimeError, "Invalid operator: " + op + "."};
throw ZynkError{ ZynkErrorType::RuntimeError, "Invalid operator: " + op + "." };
}

template <>
std::string calculate<std::string>(const std::string& left_value, const std::string& right_value, const std::string& op) {
std::string calculateString(const std::string& left_value, const std::string& right_value, const std::string& op) {
// I don't like the way it's done, but I don't know how to do it better now.
if (op == ">") return left_value > right_value ? "true" : "false";
if (op == ">=") return left_value >= right_value ? "true" : "false";
if (op == "<") return left_value < right_value ? "true" : "false";
if (op == "<=") return left_value <= right_value ? "true" : "false";
if (op == "==") return left_value == right_value ? "true" : "false";
if (op == "!=") return left_value != right_value ? "true" : "false";

const bool leftIsFloat = left_value.find('.') != std::string::npos;
const bool rightIsFloat = right_value.find('.') != std::string::npos;

if (leftIsFloat || rightIsFloat) {
const float left = std::stof(left_value);
const float right = std::stof(right_value);
return std::to_string(calculate(left, right, op));
const float left = std::stof(left_value);
const float right = std::stof(right_value);
std::string result = calculate(left, right, op);

if (leftIsFloat || rightIsFloat) return result;

size_t dotPosition = result.find('.');
if (dotPosition != std::string::npos) {
result = result.substr(0, dotPosition);
}
const int left = std::stoi(left_value);
const int right = std::stoi(right_value);
return std::to_string(calculate(left, right, op));
return result;
}
8 changes: 3 additions & 5 deletions src/execution/include/evaluator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@ class Evaluator {
void evaluateFunctionDeclaration(ASTFunction* function);
void evaluateFunctionCall(ASTFunctionCall* functionCall);
void evaluatePrint(ASTPrint* print);
void evaluateCondition(ASTCondition* condition);
};

template <typename T>
T calculate(const T& left_value, const T& right_value, const std::string& op);

template <>
std::string calculate<std::string>(const std::string& left_value, const std::string& right_value, const std::string& op);
std::string calculate(const float left, const float right, const std::string& op);
std::string calculateString(const std::string& left_value, const std::string& right_value, const std::string& op);

#endif // EVALUATOR_H
11 changes: 10 additions & 1 deletion src/parsing/include/ast.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ enum class ASTType {
Print,
Value,
Variable,
BinaryOperation
BinaryOperation,
Condition
};

struct ASTBase {
Expand Down Expand Up @@ -80,4 +81,12 @@ struct ASTBinaryOperation : public ASTBase {
std::unique_ptr<ASTBase> right;
};

struct ASTCondition : public ASTBase {
ASTCondition(std::unique_ptr<ASTBase> expression)
: ASTBase(ASTType::Condition), expression(std::move(expression)) {}
std::unique_ptr<ASTBase> expression;
std::vector<std::unique_ptr<ASTBase>> body;
std::vector<std::unique_ptr<ASTBase>> elseBody;
};

#endif // AST_H
1 change: 1 addition & 0 deletions src/parsing/include/parser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Parser {
std::unique_ptr<ASTBase> parsePrint(bool newLine);
std::unique_ptr<ASTBase> parseExpression(int priority);
std::unique_ptr<ASTBase> parsePrimaryExpression();
std::unique_ptr<ASTBase> parseIfStatement();
public:
Parser(const std::vector<Token>& tokens);
std::unique_ptr<ASTProgram> parse();
Expand Down
9 changes: 6 additions & 3 deletions src/parsing/include/token.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
#include "string"

enum class TokenType {
DEF, PRINTLN, PRINT, VARIABLE, // Keywords.
DEF, PRINTLN, PRINT,
VARIABLE, CONDITION, ELSE, // Keywords.

INT, FLOAT, STRING, BOOL, // Types.
INT, FLOAT, STRING, BOOL, NONE, // Types.

ADD, SUBTRACT, MULTIPLY, // Operators.
DIVIDE, ASSIGN, NOT_EQUAL, EQUAL, // Assign is =, Equal is ==
DIVIDE, ASSIGN, NOT_EQUAL, EQUAL,
GREATER_THAN, LESS_THAN, GREATER_OR_EQUAL,
LESS_OR_EQUAL,

IDENTIFIER, COLON, LBRACE, // Syntax.
RBRACE, SEMICOLON, LBRACKET,
Expand Down
21 changes: 17 additions & 4 deletions src/parsing/lexer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ Token Lexer::next() {
case ';': return Token(TokenType::SEMICOLON, ";", currentLine);
case '(': return Token(TokenType::LBRACKET, "(", currentLine);
case ')': return Token(TokenType::RBRACKET, ")", currentLine);
case '<': {
if (peek() != '=') return Token(TokenType::LESS_THAN, "<", currentLine);
moveForward();
return Token(TokenType::LESS_OR_EQUAL, "<=", currentLine);
}
case '>': {
if (peek() != '=') return Token(TokenType::GREATER_THAN, ">", currentLine);
moveForward();
return Token(TokenType::GREATER_OR_EQUAL, ">=", currentLine);
}
case '=': {
if (peek() != '=') return Token(TokenType::ASSIGN, "=", currentLine);
moveForward();
Expand All @@ -72,11 +82,14 @@ Token Lexer::identifier() {
if (value == "println") return Token(TokenType::PRINTLN, value, line);
if (value == "print") return Token(TokenType::PRINT, value, line);
if (value == "true" || value == "false") return Token(TokenType::BOOL, value, line);
if (value == "int") return Token(TokenType::INT, "int", line);
if (value == "float") return Token(TokenType::FLOAT, "float", line);
if (value == "String") return Token(TokenType::STRING, "String", line);
if (value == "bool") return Token(TokenType::BOOL, "bool", line);
if (value == "int") return Token(TokenType::INT, value, line);
if (value == "float") return Token(TokenType::FLOAT, value, line);
if (value == "String") return Token(TokenType::STRING, value, line);
if (value == "bool") return Token(TokenType::BOOL, value, line);
if (value == "var") return Token(TokenType::VARIABLE, value, line);
if (value == "if") return Token(TokenType::CONDITION, value, line);
if (value == "else") return Token(TokenType::ELSE, value, line);
if (value == "null") return Token(TokenType::NONE, value, line);
return Token(TokenType::IDENTIFIER, value, line);
}

Expand Down
72 changes: 51 additions & 21 deletions src/parsing/parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ std::unique_ptr<ASTBase> Parser::parseCurrent() {
return parsePrint(false);
case TokenType::PRINTLN:
return parsePrint(true);
case TokenType::CONDITION:
return parseIfStatement();
case TokenType::IDENTIFIER:
moveForward();
if (currentToken().type == TokenType::LBRACKET) return parseFunctionCall();
Expand Down Expand Up @@ -91,6 +93,12 @@ std::unique_ptr<ASTBase> Parser::parseVariableDeclaration() {
&currentLine,
};
}
if (currentToken().type == TokenType::SEMICOLON) {
consume({ TokenType::SEMICOLON, ";", currentLine });
return std::make_unique<ASTVariableDeclaration>(
varName, varType, nullptr
);
}
consume({ TokenType::ASSIGN, "=", currentLine });
auto varDeclaration = std::make_unique<ASTVariableDeclaration>(
varName, varType, parseExpression(0)
Expand All @@ -113,29 +121,12 @@ std::unique_ptr<ASTBase> Parser::parseVariableModify() {

std::unique_ptr<ASTBase> Parser::parsePrint(bool newLine) {
const size_t currentLine = currentToken().line;
std::unique_ptr<ASTPrint> print;

if (newLine) {
consume({ TokenType::PRINTLN, "println", currentLine });
} else {
consume({ TokenType::PRINT, "print", currentLine });
}
if (newLine) consume({ TokenType::PRINTLN, "println", currentLine });
else consume({ TokenType::PRINT, "print", currentLine });
consume({ TokenType::LBRACKET, "(", currentLine });
switch (currentToken().type) {
case TokenType::STRING:
case TokenType::INT:
case TokenType::FLOAT:
case TokenType::BOOL:
case TokenType::IDENTIFIER:
print = std::make_unique<ASTPrint>(parseExpression(0), newLine);
break;
default:
throw ZynkError{
ZynkErrorType::ExpressionError,
"Invalid print expression. Expected value or variable, found: '" + currentToken().value + "' instead.",
&currentLine,
};
}

auto print = std::make_unique<ASTPrint>(parseExpression(0), newLine);
consume({ TokenType::RBRACKET, ")", currentLine });
consume({ TokenType::SEMICOLON, ";", currentLine });
return print;
Expand Down Expand Up @@ -185,6 +176,38 @@ std::unique_ptr<ASTBase> Parser::parsePrimaryExpression() {
}
}

std::unique_ptr<ASTBase> Parser::parseIfStatement() {
size_t currentLine = currentToken().line;
consume({ TokenType::CONDITION, "if", currentLine });
consume({ TokenType::LBRACKET, "(", currentLine });

auto condition = std::make_unique<ASTCondition>(parseExpression(0));
consume({ TokenType::RBRACKET, ")", currentLine });
bool shortCondition = currentToken().type != TokenType::LBRACE;

if(!shortCondition) consume({ TokenType::LBRACE, "{", currentLine });
while (currentToken().type != TokenType::RBRACE && !endOfFile()) {
condition->body.push_back(parseCurrent());
if (shortCondition) break;
}

if (!shortCondition) consume({ TokenType::RBRACE, "}", currentLine });
if (currentToken().type != TokenType::ELSE) return condition;
currentLine = currentToken().line;

// Parsing else block.
consume({ TokenType::ELSE, "else", currentLine });
bool shortElse = currentToken().type != TokenType::LBRACE;

if (!shortElse) consume({ TokenType::LBRACE, "{", currentLine });
while (currentToken().type != TokenType::RBRACE && !endOfFile()) {
condition->elseBody.push_back(parseCurrent());
if (shortElse) break;
}
if (!shortElse) consume({ TokenType::RBRACE, "}", currentLine });
return condition;
}

bool Parser::endOfFile() const {
return position > tokens.size() || tokens[position].type == TokenType::END_OF_FILE;
}
Expand All @@ -195,6 +218,12 @@ bool Parser::isOperator(TokenType type) const {
case TokenType::SUBTRACT:
case TokenType::MULTIPLY:
case TokenType::DIVIDE:
case TokenType::GREATER_THAN:
case TokenType::LESS_THAN:
case TokenType::GREATER_OR_EQUAL:
case TokenType::LESS_OR_EQUAL:
case TokenType::EQUAL:
case TokenType::NOT_EQUAL:
return true;
default:
return false;
Expand All @@ -214,6 +243,7 @@ int Parser::getPriority(TokenType type) const {
case TokenType::SUBTRACT:
return 1;
default:
if (isOperator(type)) return 1;
return 0;
}
}
Expand Down
63 changes: 62 additions & 1 deletion tests/test_evaluator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -328,4 +328,65 @@ TEST(EvaluatorTest, EvaluateVariableModifyMultipleTimes) {
Evaluator evaluator;
evaluator.evaluate(program.get());
ASSERT_EQ(testing::internal::GetCapturedStdout(), "1\n2\n3\n");
}
}

TEST(EvaluatorTest, EvaluateIfStatementTrueCondition) {
const std::string code = R"(
var x: int = 1;
if (x) {
println("Condition is true");
}
x = 0;
if (x) println("Condition is false");
)";
Lexer lexer(code);
const std::vector<Token> tokens = lexer.tokenize();

Parser parser(tokens);
const auto program = parser.parse();

testing::internal::CaptureStdout();
Evaluator evaluator;
evaluator.evaluate(program.get());
ASSERT_EQ(testing::internal::GetCapturedStdout(), "Condition is true\n");
}

TEST(EvaluatorTest, EvaluateIfElseStatement) {
const std::string code = R"(
var x: bool = false;
if (x) {
println("This should not be printed");
} else {
println("Condition is false, so this is printed");
}
)";
Lexer lexer(code);
const std::vector<Token> tokens = lexer.tokenize();

Parser parser(tokens);
const auto program = parser.parse();

testing::internal::CaptureStdout();
Evaluator evaluator;
evaluator.evaluate(program.get());
ASSERT_EQ(testing::internal::GetCapturedStdout(), "Condition is false, so this is printed\n");
}

TEST(EvaluatorTest, EvaluateShortIfStatement) {
const std::string code = R"(
var x: int = 0;
if (x) println(x);
else println(x + 1);
)";
Lexer lexer(code);
const std::vector<Token> tokens = lexer.tokenize();

Parser parser(tokens);
const auto program = parser.parse();

testing::internal::CaptureStdout();
Evaluator evaluator;
evaluator.evaluate(program.get());
ASSERT_EQ(testing::internal::GetCapturedStdout(), "1\n");
}

Loading