Add negation unary

This commit is contained in:
Sofia 2026-04-28 01:03:25 +03:00
parent 43df7efd6f
commit 5b776a1d66
5 changed files with 22 additions and 4 deletions

View File

@ -105,9 +105,12 @@ namespace AST {
case types::Unary::SubPrefix:
out << "--" << this->m_expr->formatted();
break;
case types::Unary::Negation:
case types::Unary::Not:
out << "!" << this->m_expr->formatted();
break;
case types::Unary::Negation:
out << "-" << this->m_expr->formatted();
break;
default:
break;
}

View File

@ -167,10 +167,10 @@ namespace types {
});
}
// Negation
// Not & Negation
for (auto& ty : { int_ty, char_ty, bool_ty }) {
definitions.push_back(UnopDefinition{
ty, types::Unary::Negation, ty,
ty, types::Unary::Not, ty,
[](codegen::Builder& builder, std::shared_ptr<Type> ty, llvm::Value* value) {
codegen::TypeMap structs {};
auto llvm_ty = ty->codegen(builder, structs);
@ -181,6 +181,12 @@ namespace types {
return builder.builder->CreateSelect(cmp, const_1, const_0, "not_select");
}
});
definitions.push_back(UnopDefinition{
ty, types::Unary::Negation, ty,
[](codegen::Builder& builder, std::shared_ptr<Type>, llvm::Value* value) {
return builder.builder->CreateNeg(value, "neg");
}
});
}
return definitions;

View File

@ -20,6 +20,7 @@ namespace types {
AddPrefix,
SubPostfix,
SubPrefix,
Not,
Negation,
};

View File

@ -334,6 +334,14 @@ namespace parsing {
};
}
else if (inner.peek().content == "!") {
inner.next();
auto expr = parse_primary_expression(inner, scope).unwrap();
stream.m_position = inner.m_position;
return std::unique_ptr<AST::Expression> {
new AST::UnaryExpression(before_meta + inner.metadata(), std::move(expr), types::Unary::Not)
};
}
else if (inner.peek().content == "-") {
inner.next();
auto expr = parse_primary_expression(inner, scope).unwrap();
stream.m_position = inner.m_position;

2
test.c
View File

@ -52,7 +52,7 @@ int main() {
printf("2d array: %d!\n", twod_array[0][0]);
int counter = 0;
int a = !0;
int a = -500;
printf("a: %d\n", a);
return 0;