aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author_ov4 <ov4@ov4.org>2026-10-18 06:05:53 +0000
committer_ov4 <ov4@ov4.org>2026-10-18 06:05:53 +0000
commit16231050058131860f710073c17d3bca7c6637eb (patch)
tree1da2ca606f1d513822ccd04b3053d5eee69ac19d
parent1b0b287629e6e3b6d8eb6182db72b28fd0510574 (diff)
feat(operators): support global binary operator overloads
Resolve exact operand types and preserve declared operator return types. Reject implicit STRING to BOOLEAN conversion at typed expression boundaries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--CMakeLists.txt1
-rw-r--r--include/cps/CodeGen.h5
-rw-r--r--include/cps/FunctionAST.h3
-rw-r--r--include/cps/Lexer.h1
-rw-r--r--include/cps/Operator.h28
-rw-r--r--include/cps/Parser.h1
-rw-r--r--lib/CodeGen/ControlFlowGen.cc8
-rw-r--r--lib/CodeGen/ExpressionGen.cc11
-rw-r--r--lib/CodeGen/FunctionGen.cc23
-rw-r--r--lib/CodeGen/OperatorGen.cc20
-rw-r--r--lib/CodeGen/TypeCheckGen.cc4
-rw-r--r--lib/CodeGen/ValueTypeGen.cc8
-rw-r--r--lib/Lexer/Lexer.cc1
-rw-r--r--lib/Parser/ParserFunction.cc31
-rw-r--r--tests/i/operator-global/case.json1
-rw-r--r--tests/i/operator-global/expected.txt5
-rw-r--r--tests/i/operator-global/notes.md7
-rw-r--r--tests/i/operator-global/program.cps28
-rw-r--r--tests/iii/operator-global-errors/case.json24
-rw-r--r--tests/iii/operator-global-errors/notes.md3
-rw-r--r--tests/iii/operator-global-errors/program.cps22
21 files changed, 230 insertions, 5 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 420f2a2..fd86892 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -55,6 +55,7 @@ add_library(CPSParser STATIC
add_library(CPSCodeGen STATIC
lib/CodeGen/CodeGen.cc
lib/CodeGen/ExpressionGen.cc
+ lib/CodeGen/OperatorGen.cc
lib/CodeGen/StatementGen.cc
lib/CodeGen/GlobalGen.cc
lib/CodeGen/ConstantGen.cc
diff --git a/include/cps/CodeGen.h b/include/cps/CodeGen.h
index d81a82c..30e6d06 100644
--- a/include/cps/CodeGen.h
+++ b/include/cps/CodeGen.h
@@ -155,6 +155,11 @@ class CodeGen {
const std::vector<std::unique_ptr<ExprAST>> &ArgExprs, int Line);
const FuncSig *resolveCall(const std::string &Name,
const std::vector<std::unique_ptr<ExprAST>> &Args);
+ struct OperatorResolution {
+ const FuncSig *Signature = nullptr;
+ bool Ambiguous = false;
+ };
+ OperatorResolution resolveOperator(int Op, const TypeInfo *Left, const TypeInfo *Right = nullptr);
llvm::Value *emitVariadicArgument(ExprAST *Expr, const std::string &Callee, size_t Position);
bool marshalCallArgs(const FuncSig &Signature,
const std::vector<std::unique_ptr<ExprAST>> &ArgExprs,
diff --git a/include/cps/FunctionAST.h b/include/cps/FunctionAST.h
index 716f004..90ef5c4 100644
--- a/include/cps/FunctionAST.h
+++ b/include/cps/FunctionAST.h
@@ -34,6 +34,7 @@ class PrototypeAST {
std::string OwnerClass;
bool IsPublic;
bool IsVariadic = false;
+ int Operator = 0;
public:
PrototypeAST(const std::string &Name,
@@ -47,6 +48,8 @@ public:
const std::vector<ParamDecl> &getParams() const { return Params; }
const std::string &getReturnType() const { return ReturnType; }
bool isOverload() const { return IsOverload; }
+ int getOperator() const { return Operator; }
+ void setOperator(int Op) { Operator = Op; }
bool isExternal() const { return IsExternal; }
bool isVariadic() const { return IsVariadic; }
void setVariadic(bool V) { IsVariadic = V; }
diff --git a/include/cps/Lexer.h b/include/cps/Lexer.h
index e2f5fdc..449ff8d 100644
--- a/include/cps/Lexer.h
+++ b/include/cps/Lexer.h
@@ -67,6 +67,7 @@ enum Token {
tok_colon = -300, // :
+ tok_operator = -398,
tok_overload = -399,
tok_function = -400,
tok_endfunction = -401,
diff --git a/include/cps/Operator.h b/include/cps/Operator.h
new file mode 100644
index 0000000..7cbb5d9
--- /dev/null
+++ b/include/cps/Operator.h
@@ -0,0 +1,28 @@
+#pragma once
+#include "cps/Lexer.h"
+#include <string>
+
+namespace cps {
+
+inline std::string operatorSpelling(int Op) {
+ switch (Op) {
+ case '+': case '-': case '*': case '/': case '&': case '<': case '>':
+ return std::string(1, static_cast<char>(Op));
+ case tok_div: return "DIV";
+ case tok_mod: return "MOD";
+ case tok_eq: return "=";
+ case tok_ne: return "<>";
+ case tok_le: return "<=";
+ case tok_ge: return ">=";
+ case tok_and: return "AND";
+ case tok_or: return "OR";
+ case tok_not: return "NOT";
+ default: return {};
+ }
+}
+
+inline std::string operatorName(int Op) {
+ return "OPERATOR" + operatorSpelling(Op);
+}
+
+} // namespace cps
diff --git a/include/cps/Parser.h b/include/cps/Parser.h
index f877ae6..ad80876 100644
--- a/include/cps/Parser.h
+++ b/include/cps/Parser.h
@@ -43,6 +43,7 @@ class Parser {
std::unique_ptr<ExprAST> ParseNumberExpr();
std::unique_ptr<ExprAST> ParseIdentifierExpr();
+ std::string ParseOperatorName(int &Op);
std::unique_ptr<ExprAST> ParseParenExpr();
std::unique_ptr<MemberCallExprAST> ParseMemberCall(
const std::string &Name, std::vector<DesignatorAccess> Accesses, int Line);
diff --git a/lib/CodeGen/ControlFlowGen.cc b/lib/CodeGen/ControlFlowGen.cc
index 17f43f2..0cf0c34 100644
--- a/lib/CodeGen/ControlFlowGen.cc
+++ b/lib/CodeGen/ControlFlowGen.cc
@@ -204,6 +204,14 @@ void CodeGen::emitCaseStmt(CaseStmtAST *Stmt) {
return nullptr;
}
Value *LabelValue = emitExpr(Label);
+ auto Overload = resolveOperator(Op, SelectorType, LabelType);
+ if (Overload.Signature && !Overload.Ambiguous) {
+ const TypeInfo *Result = resolveType(Overload.Signature->ReturnTypeName);
+ if (!Result || Result->Kind != TypeKind::Boolean) {
+ reportError("CASE comparison must return BOOLEAN");
+ return nullptr;
+ }
+ }
return emitBinaryOp(Op, Selected, SelectorType, LabelValue, LabelType, Branch.Line);
};
if (!Branch.Lower) {
diff --git a/lib/CodeGen/ExpressionGen.cc b/lib/CodeGen/ExpressionGen.cc
index 79c5fb0..8fb13c9 100644
--- a/lib/CodeGen/ExpressionGen.cc
+++ b/lib/CodeGen/ExpressionGen.cc
@@ -4,6 +4,7 @@
#include "cps/MemoryHandler.h"
#include "cps/Lexer.h"
#include "cps/TypeAST.h"
+#include "cps/Operator.h"
#include "Builtins.h"
#include <climits>
#include <cstddef>
@@ -155,6 +156,16 @@ Value *CodeGen::emitBinaryOp(int Op, Value *L, const TypeInfo *LT,
Value *R, const TypeInfo *RT, int Line) {
SaveAndRestore<int> Location(DiagnosticLine, Line ? Line : DiagnosticLine);
if (!L || !R) return nullptr;
+ if (!LT || !RT) {
+ reportError("Cannot determine operand types for %s", operatorName(Op).c_str());
+ return nullptr;
+ }
+ auto Overload = resolveOperator(Op, LT, RT);
+ if (Overload.Ambiguous) {
+ reportError("Ambiguous overload for %s(%s, %s)", operatorName(Op).c_str(), LT->Name.c_str(), RT->Name.c_str());
+ return nullptr;
+ }
+ if (Overload.Signature) return FuncGen->emitCall(*Overload.Signature, {L, R});
if ((LT && LT->isC()) || (RT && RT->isC()))
return emitCBinaryOp(Op, L, LT, R, RT, Line);
if ((LT && LT->isUserKind()) || (RT && RT->isUserKind()))
diff --git a/lib/CodeGen/FunctionGen.cc b/lib/CodeGen/FunctionGen.cc
index 9559717..bccf397 100644
--- a/lib/CodeGen/FunctionGen.cc
+++ b/lib/CodeGen/FunctionGen.cc
@@ -2,6 +2,7 @@
#include "cps/FunctionGen.h"
#include "cps/CodeGen.h"
#include "cps/ExceptionHandler.h"
+#include "cps/Operator.h"
#include <cstdio>
#include <cstdarg>
@@ -122,6 +123,28 @@ const FuncSig *FunctionGen::getSignatureByLink(const std::string &Name) const {
Function *FunctionGen::emitPrototype(PrototypeAST *Proto) {
auto Registered = PrototypeLinks.find(Proto);
if (Registered != PrototypeLinks.end()) return Module.getFunction(Registered->second);
+ if (int Op = Proto->getOperator()) {
+ size_t Count = Proto->getParams().size() + !Proto->getOwnerClass().empty();
+ bool ValidCount = Op == '-' ? Count == 1 || Count == 2
+ : Op == tok_not ? Count == 1 : Count == 2;
+ if (!ValidCount) {
+ reportError("Invalid operand count for %s", Proto->getName().c_str());
+ return nullptr;
+ }
+ bool HasUserOperand = !Proto->getOwnerClass().empty();
+ for (const auto &P : Proto->getParams()) {
+ if (P.IsArray) {
+ reportError("An operator parameter cannot be a whole array");
+ return nullptr;
+ }
+ const TypeInfo *T = Types.resolve(P.TypeName);
+ HasUserOperand |= T && (T->isRecord() || T->isEnum());
+ }
+ if (!HasUserOperand) {
+ reportError("%s requires a record, class or enum operand", Proto->getName().c_str());
+ return nullptr;
+ }
+ }
if (Proto->isOverload() && Proto->getOwnerClass().empty() && sameIdentifier(Proto->getName(), "MAIN")) {
reportError("MAIN cannot be declared OVERLOAD");
return nullptr;
diff --git a/lib/CodeGen/OperatorGen.cc b/lib/CodeGen/OperatorGen.cc
new file mode 100644
index 0000000..83c515b
--- /dev/null
+++ b/lib/CodeGen/OperatorGen.cc
@@ -0,0 +1,20 @@
+#include "cps/CodeGen.h"
+#include "cps/Operator.h"
+
+using namespace cps;
+
+// Probing candidates must not evaluate operands or diagnose absent overloads:
+// both static typing and emission use this same selection.
+CodeGen::OperatorResolution CodeGen::resolveOperator(
+ int Op, const TypeInfo *Left, const TypeInfo *Right) {
+ OperatorResolution Result;
+ if (!Left) return Result;
+ for (const FuncSig *Sig : FuncGen->getOverloads(operatorName(Op))) {
+ if (Sig->Prototype->getOperator() != Op || Sig->Params.size() != (Right ? 2u : 1u)) continue;
+ if (!Left->sameType(resolveType(Sig->Params[0].TypeName))) continue;
+ if (Right && !Right->sameType(resolveType(Sig->Params[1].TypeName))) continue;
+ if (Result.Signature) Result.Ambiguous = true;
+ else Result.Signature = Sig;
+ }
+ return Result;
+}
diff --git a/lib/CodeGen/TypeCheckGen.cc b/lib/CodeGen/TypeCheckGen.cc
index 690d005..5d014f6 100644
--- a/lib/CodeGen/TypeCheckGen.cc
+++ b/lib/CodeGen/TypeCheckGen.cc
@@ -46,6 +46,10 @@ Value *CodeGen::emitCoercedExpr(ExprAST *E, const TypeInfo *Target) {
}
const TypeInfo *Src = getExprTypeInfo(E);
+ if (Src && Src->Kind == TypeKind::String && Target->Kind == TypeKind::Boolean) {
+ reportError("Cannot implicitly convert STRING to BOOLEAN");
+ return nullptr;
+ }
if (Target->isC() || (Src && Src->isC())) {
if (auto *Addr = dynamic_cast<AddrOfExprAST*>(E)) {
diff --git a/lib/CodeGen/ValueTypeGen.cc b/lib/CodeGen/ValueTypeGen.cc
index 3c1fc06..b09a5d9 100644
--- a/lib/CodeGen/ValueTypeGen.cc
+++ b/lib/CodeGen/ValueTypeGen.cc
@@ -81,6 +81,12 @@ const TypeInfo *CodeGen::getExprTypeInfo(ExprAST *Expr) {
}
if (auto *Bin = dynamic_cast<BinaryExprAST*>(Expr)) {
+ const TypeInfo *L = getExprTypeInfo(Bin->getLHS());
+ const TypeInfo *R = getExprTypeInfo(Bin->getRHS());
+ if (!L || !R || isWholeArrayVar(Bin->getLHS()) || isWholeArrayVar(Bin->getRHS())) return nullptr;
+ auto Overload = resolveOperator(Bin->getOp(), L, R);
+ if (Overload.Ambiguous) return nullptr;
+ if (Overload.Signature) return resolveType(Overload.Signature->ReturnTypeName);
switch (Bin->getOp()) {
case tok_eq:
case tok_ne:
@@ -99,8 +105,6 @@ const TypeInfo *CodeGen::getExprTypeInfo(ExprAST *Expr) {
break;
}
- const TypeInfo *L = getExprTypeInfo(Bin->getLHS());
- const TypeInfo *R = getExprTypeInfo(Bin->getRHS());
if ((L && L->isC()) || (R && R->isC())) return Types->commonCScalar(L, R);
// Enum arithmetic: E +/- INTEGER (enum on the left) yields the enum;
// every other user-kind combination has no type (emission rejects it).
diff --git a/lib/Lexer/Lexer.cc b/lib/Lexer/Lexer.cc
index 8f906ae..cebf335 100644
--- a/lib/Lexer/Lexer.cc
+++ b/lib/Lexer/Lexer.cc
@@ -134,6 +134,7 @@ int Lexer::readToken() {
if (IdentifierStr == "OR") return tok_or;
if (IdentifierStr == "NOT") return tok_not;
+ if (IdentifierStr == "OPERATOR") return tok_operator;
if (IdentifierStr == "OVERLOAD") return tok_overload;
if (IdentifierStr == "FUNCTION") return tok_function;
if (IdentifierStr == "ENDFUNCTION") return tok_endfunction;
diff --git a/lib/Parser/ParserFunction.cc b/lib/Parser/ParserFunction.cc
index 7686f51..3ff54da 100644
--- a/lib/Parser/ParserFunction.cc
+++ b/lib/Parser/ParserFunction.cc
@@ -1,6 +1,7 @@
#include "cps/Diagnostics.h"
#include "cps/Parser.h"
#include "cps/FunctionAST.h"
+#include "cps/Operator.h"
#include <cstdio>
using namespace cps;
@@ -130,6 +131,18 @@ std::optional<std::vector<ParamDecl>> Parser::ParsePrototypeArgs(bool AllowByRef
return Params;
}
+std::string Parser::ParseOperatorName(int &Op) {
+ getNextToken(); // OPERATOR
+ Op = CurTok;
+ if (operatorSpelling(Op).empty()) {
+ sourceDiagnostic(Lex.getLine(), "error: Expected a supported operator after OPERATOR at line %d\n", Lex.getLine());
+ getNextToken();
+ return {};
+ }
+ getNextToken();
+ return operatorName(Op);
+}
+
std::unique_ptr<FunctionDefAST> Parser::ParseFunction(const std::string &OwnerClass, bool IsPublic, bool IsOverload) {
int Line = Lex.getLine();
getNextToken();
@@ -141,13 +154,24 @@ std::unique_ptr<FunctionDefAST> Parser::ParseFunction(const std::string &OwnerCl
cps::sourceDiagnostic(Lex.getLine(), "error: constructor NEW must be a PROCEDURE at line %d\n", Line);
return nullptr;
}
- if (CurTok != tok_identifier) {
+ if (CurTok != tok_identifier && CurTok != tok_operator) {
cps::sourceDiagnostic(Lex.getLine(), "error: Expected function name\n");
return nullptr;
}
- std::string Name = Lex.IdentifierStr;
- getNextToken();
+ int Operator = 0;
+ std::string Name;
+ if (CurTok == tok_operator) {
+ Name = ParseOperatorName(Operator);
+ if (Name.empty()) return nullptr;
+ if (!IsOverload) {
+ sourceDiagnostic(Line, "error: An operator function must be declared OVERLOAD at line %d\n", Line);
+ return nullptr;
+ }
+ } else {
+ Name = Lex.IdentifierStr;
+ getNextToken();
+ }
auto Args = ParsePrototypeArgs(/*AllowByRef=*/false);
if (!Args) return nullptr;
@@ -168,6 +192,7 @@ std::unique_ptr<FunctionDefAST> Parser::ParseFunction(const std::string &OwnerCl
}
auto Proto = std::make_unique<PrototypeAST>(Name, std::move(*Args), RetType, false, OwnerClass, IsPublic, IsOverload);
+ Proto->setOperator(Operator);
std::vector<std::unique_ptr<StmtAST>> Body = ParseBlock({tok_endfunction});
diff --git a/tests/i/operator-global/case.json b/tests/i/operator-global/case.json
new file mode 100644
index 0000000..0967ef4
--- /dev/null
+++ b/tests/i/operator-global/case.json
@@ -0,0 +1 @@
+{}
diff --git a/tests/i/operator-global/expected.txt b/tests/i/operator-global/expected.txt
new file mode 100644
index 0000000..3460ce8
--- /dev/null
+++ b/tests/i/operator-global/expected.txt
@@ -0,0 +1,5 @@
+7
+2!
+comparison
+6
+5xyTRUE
diff --git a/tests/i/operator-global/notes.md b/tests/i/operator-global/notes.md
new file mode 100644
index 0000000..1026071
--- /dev/null
+++ b/tests/i/operator-global/notes.md
@@ -0,0 +1,7 @@
+# operator-global
+
+Human review: pending. Expected output was independently traced by AI, not captured from cpsc.
+
+Basis: operator overloading is a project extension, with exact parameter types.
+
+Trace: Box additions sum 2 + 3 + 2 to 7. Concatenation returns 2!. The comparison deliberately returns STRING, printed as comparison. Reversed INTEGER + Box gives 4 + 2 = 6. Builtin operations still print 5xyTRUE.
diff --git a/tests/i/operator-global/program.cps b/tests/i/operator-global/program.cps
new file mode 100644
index 0000000..9d27fcb
--- /dev/null
+++ b/tests/i/operator-global/program.cps
@@ -0,0 +1,28 @@
+TYPE Box
+DECLARE Value : INTEGER
+ENDTYPE
+OVERLOAD FUNCTION OPERATOR+(a : Box, b : Box) RETURNS Box
+DECLARE result : Box
+result.Value <- a.Value + b.Value
+RETURN result
+ENDFUNCTION
+OVERLOAD FUNCTION OPERATOR&(a : Box, b : STRING) RETURNS STRING
+RETURN NUM_TO_STR(a.Value) & b
+ENDFUNCTION
+OVERLOAD FUNCTION OPERATOR<(a : Box, b : Box) RETURNS STRING
+RETURN "comparison"
+ENDFUNCTION
+OVERLOAD FUNCTION OPERATOR+(a : INTEGER, b : Box) RETURNS INTEGER
+RETURN a + b.Value
+ENDFUNCTION
+DECLARE a : Box
+DECLARE b : Box
+DECLARE result : Box
+a.Value <- 2
+b.Value <- 3
+result <- a + b + a
+OUTPUT result.Value
+OUTPUT a & "!"
+OUTPUT a < b
+OUTPUT 4 + a
+OUTPUT 2 + 3, "x" & "y", 1 < 2
diff --git a/tests/iii/operator-global-errors/case.json b/tests/iii/operator-global-errors/case.json
new file mode 100644
index 0000000..eeb9965
--- /dev/null
+++ b/tests/iii/operator-global-errors/case.json
@@ -0,0 +1,24 @@
+{
+ "errors": [
+ {
+ "reason": "Cannot implicitly convert STRING to BOOLEAN",
+ "line": 12
+ },
+ {
+ "reason": "Operator \\+ cannot be applied to a record",
+ "line": 13
+ },
+ {
+ "reason": "requires a record, class or enum operand",
+ "line": 14
+ },
+ {
+ "reason": "Invalid operand count",
+ "line": 17
+ },
+ {
+ "reason": "cannot be redefined",
+ "line": 20
+ }
+ ]
+}
diff --git a/tests/iii/operator-global-errors/notes.md b/tests/iii/operator-global-errors/notes.md
new file mode 100644
index 0000000..24bb113
--- /dev/null
+++ b/tests/iii/operator-global-errors/notes.md
@@ -0,0 +1,3 @@
+# operator-global-errors
+
+Reject a STRING comparison result assigned to BOOLEAN, implicit INTEGER-to-REAL overload matching, builtin-only overloads, wrong arity and return-type-only duplicates.
diff --git a/tests/iii/operator-global-errors/program.cps b/tests/iii/operator-global-errors/program.cps
new file mode 100644
index 0000000..23bfae1
--- /dev/null
+++ b/tests/iii/operator-global-errors/program.cps
@@ -0,0 +1,22 @@
+TYPE Box
+DECLARE Value : INTEGER
+ENDTYPE
+OVERLOAD FUNCTION OPERATOR+(a : Box, b : REAL) RETURNS INTEGER
+RETURN 1
+ENDFUNCTION
+OVERLOAD FUNCTION OPERATOR<(a : Box, b : Box) RETURNS STRING
+RETURN "text"
+ENDFUNCTION
+DECLARE a : Box
+DECLARE flag : BOOLEAN
+flag <- a < a
+OUTPUT a + 1
+OVERLOAD FUNCTION OPERATOR&(a : INTEGER, b : STRING) RETURNS STRING
+RETURN b
+ENDFUNCTION
+OVERLOAD FUNCTION OPERATOR*(a : Box) RETURNS INTEGER
+RETURN 1
+ENDFUNCTION
+OVERLOAD FUNCTION OPERATOR+(a : Box, b : REAL) RETURNS REAL
+RETURN 2.0
+ENDFUNCTION