Skip to content
This repository was archived by the owner on Dec 8, 2022. It is now read-only.

Commit dd60291

Browse files
committed
Merge branch 'develop'
2 parents 55a852a + 371c81b commit dd60291

File tree

13 files changed

+147
-54
lines changed

13 files changed

+147
-54
lines changed

compiler/lang/lang.cpp

+38-18
Original file line numberDiff line numberDiff line change
@@ -442,13 +442,13 @@ StructType *TryCatch::getExcType(LLVMContext &context) {
442442
}
443443

444444
GlobalVariable *TryCatch::getTypeIdxVar(Module *module,
445-
types::Type *catchType) {
445+
const std::string &name) {
446446
LLVMContext &context = module->getContext();
447447
auto *typeInfoType = getTypeInfoType(context);
448448
const std::string typeVarName =
449-
"seq.typeidx." + (catchType ? catchType->getName() : "<all>");
449+
"seq.typeidx." + (name.empty() ? "<all>" : name);
450450
GlobalVariable *tidx = module->getGlobalVariable(typeVarName);
451-
int idx = catchType ? catchType->getID() : 0;
451+
int idx = types::Type::getID(name);
452452
if (!tidx)
453453
tidx = new GlobalVariable(
454454
*module, typeInfoType, true, GlobalValue::PrivateLinkage,
@@ -459,6 +459,11 @@ GlobalVariable *TryCatch::getTypeIdxVar(Module *module,
459459
return tidx;
460460
}
461461

462+
GlobalVariable *TryCatch::getTypeIdxVar(Module *module,
463+
types::Type *catchType) {
464+
return getTypeIdxVar(module, catchType ? catchType->getName() : "");
465+
}
466+
462467
void TryCatch::resolveTypes() {
463468
scope->resolveTypes();
464469
for (auto *block : catchBlocks)
@@ -1352,7 +1357,7 @@ Continue *Continue::clone(Generic *ref) {
13521357
SEQ_RETURN_CLONE(x);
13531358
}
13541359

1355-
Assert::Assert(Expr *expr) : Stmt("assert"), expr(expr) {}
1360+
Assert::Assert(Expr *expr, Expr *msg) : Stmt("assert"), expr(expr), msg(msg) {}
13561361

13571362
void Assert::resolveTypes() { expr->resolveTypes(); }
13581363

@@ -1365,32 +1370,47 @@ void Assert::codegen0(BasicBlock *&block) {
13651370
LLVMContext &context = block->getContext();
13661371
Module *module = block->getModule();
13671372
Function *func = block->getParent();
1368-
13691373
const bool test = isTest(getBase());
1370-
auto *assertFail = cast<Function>(module->getOrInsertFunction(
1371-
test ? "seq_test_failed" : "seq_assert_failed", Type::getVoidTy(context),
1372-
types::Str->getLLVMType(context), types::Int->getLLVMType(context)));
1373-
assertFail->setDoesNotThrow();
1374-
if (!test)
1375-
assertFail->setDoesNotReturn();
1374+
13761375
Value *check = expr->codegen(getBase(), block);
13771376
check = expr->getType()->boolValue(check, block, getTryCatch());
1378-
Value *file = StrExpr(getSrcInfo().file).codegen(getBase(), block);
1379-
Value *line = IntExpr(getSrcInfo().line).codegen(getBase(), block);
1377+
1378+
Value *msgVal = nullptr;
1379+
if (msg) {
1380+
msgVal = msg->codegen(getBase(), block);
1381+
msgVal = msg->getType()->strValue(msgVal, block, getTryCatch());
1382+
} else {
1383+
msgVal = StrExpr("").codegen(getBase(), block);
1384+
}
13801385

13811386
BasicBlock *fail = BasicBlock::Create(context, "assert_fail", func);
13821387
BasicBlock *pass = BasicBlock::Create(context, "assert_pass", func);
13831388

13841389
IRBuilder<> builder(block);
13851390
check = builder.CreateTrunc(check, builder.getInt1Ty());
13861391
builder.CreateCondBr(check, pass, fail);
1387-
13881392
builder.SetInsertPoint(fail);
1389-
builder.CreateCall(assertFail, {file, line});
1390-
if (test)
1393+
if (test) {
1394+
Function *testFailed = Func::getBuiltin("_test_failed")->getFunc(module);
1395+
Value *file = StrExpr(getSrcInfo().file).codegen(getBase(), fail);
1396+
Value *line = IntExpr(getSrcInfo().line).codegen(getBase(), fail);
1397+
builder.CreateCall(testFailed, {file, line, msgVal});
13911398
builder.CreateBr(pass);
1392-
else
1399+
} else {
1400+
Func *f = Func::getBuiltin("_make_assert_error");
1401+
Function *assertExc = f->getFunc(module);
1402+
types::Type *assertErrorType = f->getFuncType()->getBaseType(0);
1403+
1404+
Value *excVal = builder.CreateCall(assertExc, msgVal);
1405+
ValueExpr excArg(assertErrorType, excVal);
1406+
Throw raise(&excArg);
1407+
raise.setBase(getBase());
1408+
raise.setSrcInfo(getSrcInfo());
1409+
raise.codegen(fail);
1410+
1411+
builder.SetInsertPoint(fail);
13931412
builder.CreateUnreachable();
1413+
}
13941414

13951415
block = pass;
13961416
}
@@ -1399,7 +1419,7 @@ Assert *Assert::clone(Generic *ref) {
13991419
if (ref->seenClone(this))
14001420
return (Assert *)ref->getClone(this);
14011421

1402-
auto *x = new Assert(expr->clone(ref));
1422+
auto *x = new Assert(expr->clone(ref), msg ? msg->clone(ref) : msg);
14031423
ref->addClone(this, x);
14041424
Stmt::setCloneBase(x, ref);
14051425
SEQ_RETURN_CLONE(x);

compiler/lang/lang.h

+4-1
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,8 @@ class TryCatch : public Stmt {
167167
TryCatch *clone(Generic *ref) override;
168168
static llvm::StructType *getPadType(llvm::LLVMContext &context);
169169
static llvm::StructType *getExcType(llvm::LLVMContext &context);
170+
static llvm::GlobalVariable *getTypeIdxVar(llvm::Module *module,
171+
const std::string &name);
170172
static llvm::GlobalVariable *getTypeIdxVar(llvm::Module *module,
171173
types::Type *catchType);
172174
};
@@ -268,9 +270,10 @@ class Continue : public Stmt {
268270
class Assert : public Stmt {
269271
private:
270272
Expr *expr;
273+
Expr *msg;
271274

272275
public:
273-
explicit Assert(Expr *expr);
276+
explicit Assert(Expr *expr, Expr *msg = nullptr);
274277
void resolveTypes() override;
275278
void codegen0(llvm::BasicBlock *&block) override;
276279
Assert *clone(Generic *ref) override;

compiler/parser/context.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ struct ImportCache {
126126

127127
std::unordered_map<std::string, std::shared_ptr<Context>> imports;
128128

129-
ImportCache(const std::string &a = "") : argv0(""), stdlib(nullptr) {}
129+
ImportCache(const std::string &a = "") : argv0(a), stdlib(nullptr) {}
130130
std::string getImportFile(const std::string &what,
131131
const std::string &relativeTo,
132132
bool forceStdlib = false);

compiler/parser/ocaml.cpp

+10-4
Original file line numberDiff line numberDiff line change
@@ -449,12 +449,18 @@ unique_ptr<Expr> parse_expr(string code, const seq::SrcInfo &offset) {
449449
}
450450

451451
unique_ptr<SuiteStmt> parse_file(string file) {
452-
ifstream fin(file);
453452
string result, line;
454-
while (getline(fin, line)) {
455-
result += line + "\n";
453+
if (file == "-") {
454+
while (getline(cin, line)) {
455+
result += line + "\n";
456+
}
457+
} else {
458+
ifstream fin(file);
459+
while (getline(fin, line)) {
460+
result += line + "\n";
461+
}
462+
fin.close();
456463
}
457-
fin.close();
458464
return parse_code(file, result, 0, 0);
459465
}
460466

compiler/types/types.cpp

+16-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include <cstdlib>
33
#include <iostream>
44
#include <typeinfo>
5+
#include <unordered_map>
56
#include <vector>
67

78
using namespace seq;
@@ -12,10 +13,23 @@ types::Type::Type(std::string name, types::Type *parent, bool abstract,
1213
: name(std::move(name)), parent(parent), abstract(abstract),
1314
extendable(extendable) {}
1415

15-
int types::Type::getID() const {
16-
return (int)std::hash<std::string>()(getName());
16+
int types::Type::getID(const std::string &name) {
17+
static std::unordered_map<std::string, int> cache;
18+
static int next = 1000;
19+
if (name.empty())
20+
return 0;
21+
auto id = cache.find(name);
22+
if (id != cache.end()) {
23+
return id->second;
24+
} else {
25+
const int myID = next++;
26+
cache[name] = myID;
27+
return myID;
28+
}
1729
}
1830

31+
int types::Type::getID() const { return getID(getName()); }
32+
1933
std::string types::Type::getName() const {
2034
std::string nameFull = name;
2135
if (numBaseTypes() > 0) {

compiler/types/types.h

+4
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ class Type {
7575
Type(std::string name, Type *parent, bool abstract = false,
7676
bool extendable = false);
7777

78+
/// Returns a unique identifier for this type, based on
79+
/// the given name.
80+
static int getID(const std::string &name);
81+
7882
/// Returns a unique identifier for this type, based on
7983
/// \ref getName() "getName()".
8084
virtual int getID() const;

runtime/exc.cpp

+6
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,12 @@ SEQ_FUNC void seq_terminate(void *exc) {
205205
auto *base = (OurBaseException_t *)((char *)exc + seq_exc_offset());
206206
void *obj = base->obj;
207207
auto *hdr = (SeqExcHeader_t *)obj;
208+
209+
if (std::string(hdr->type.str, hdr->type.len) == "SystemExit") {
210+
seq_int_t status = *(seq_int_t *)(hdr + 1);
211+
exit((int)status);
212+
}
213+
208214
fprintf(stderr, "\033[1m");
209215
fwrite(hdr->type.str, 1, (size_t)hdr->type.len, stderr);
210216
if (hdr->msg.len > 0) {

runtime/lib.cpp

-9
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,6 @@ SEQ_FUNC seq_int_t seq_time_monotonic() {
6868
return nanos;
6969
}
7070

71-
SEQ_FUNC void seq_assert_failed(seq_str_t file, seq_int_t line) {
72-
fprintf(stderr, "assertion failed on line %d (%s)\n", (int)line, file.str);
73-
exit(EXIT_FAILURE);
74-
}
75-
76-
SEQ_FUNC void seq_test_failed(seq_str_t file, seq_int_t line) {
77-
printf("\033[1;31mTEST FAILED:\033[0m %s (line %d)\n", file.str, (int)line);
78-
}
79-
8071
extern char **environ;
8172
SEQ_FUNC char **seq_env() { return environ; }
8273

stdlib/core/err.seq

+56
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,63 @@ class StopIteration:
162162
def message(self: StopIteration):
163163
return self._hdr.msg
164164

165+
class AssertionError:
166+
_hdr: ExcHeader
167+
168+
def __init__(self: AssertionError):
169+
self._hdr = ('AssertionError', '', '', '', 0, 0)
170+
171+
def __init__(self: AssertionError, message: str):
172+
self._hdr = ('AssertionError', message, '', '', 0, 0)
173+
174+
@property
175+
def message(self: AssertionError):
176+
return self._hdr.msg
177+
178+
class SystemExit:
179+
_hdr: ExcHeader
180+
_status: int
181+
182+
def __init__(self: SystemExit):
183+
self._hdr = ('SystemExit', '', '', '', 0, 0)
184+
self._status = 0
185+
186+
def __init__(self: SystemExit, status: int):
187+
self._hdr = ('SystemExit', '', '', '', 0, 0)
188+
self._status = status
189+
190+
def __init__(self: SystemExit, message: str):
191+
self._hdr = ('SystemExit', message, '', '', 0, 0)
192+
self._status = 0
193+
194+
def __init__(self: SystemExit, message: str, status: int):
195+
self._hdr = ('SystemExit', message, '', '', 0, 0)
196+
self._status = status
197+
198+
@property
199+
def message(self: SystemExit):
200+
return self._hdr.msg
201+
202+
@property
203+
def status(self: SystemExit):
204+
return self._status
205+
165206
def check_errno(prefix: str):
166207
msg = _C.seq_check_errno()
167208
if msg:
168209
raise OSError(prefix + msg)
210+
211+
@builtin
212+
def _make_assert_error(msg: str) -> AssertionError:
213+
return AssertionError(msg)
214+
215+
@builtin
216+
def _test_failed(file: str, line: int, msg: str):
217+
s = "\033[1;31mTEST FAILED:\033[0m " + file + " (line " + str(line) + ")"
218+
if msg:
219+
s += ": " + msg
220+
print s
221+
222+
@builtin
223+
def _handle_exit(e: SystemExit):
224+
_C.exit(e.status)

stdlib/core/sort.seq

+7-9
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def sorted[S,T](
99
v: generator[T],
1010
key: optional[function[S,T]] = None,
1111
algorithm: optional[str] = None,
12-
reversed: bool = False
12+
reverse: bool = False
1313
):
1414
"""
1515
sorted(v)
@@ -19,14 +19,14 @@ def sorted[S,T](
1919
newlist = [a for a in v]
2020
if key:
2121
if algorithm:
22-
newlist.sort(~key, ~algorithm, reversed)
22+
newlist.sort(~key, ~algorithm, reverse)
2323
else:
24-
newlist.sort(~key, None, reversed)
24+
newlist.sort(~key, None, reverse)
2525
else:
2626
if algorithm:
27-
newlist.sort(None, ~algorithm, reversed)
27+
newlist.sort(None, ~algorithm, reverse)
2828
else:
29-
newlist.sort(None, None, reversed)
29+
newlist.sort(None, None, reverse)
3030
return newlist
3131

3232
def _sort_list[T,S](self: list[T], key: function[S,T], algorithm: str):
@@ -49,7 +49,7 @@ extend list[T]:
4949
self: list[T],
5050
key: optional[function[S,T]] = None,
5151
algorithm: optional[str] = None,
52-
reversed: bool = False
52+
reverse: bool = False
5353
):
5454
def ident[T](x: T):
5555
return x
@@ -59,7 +59,5 @@ extend list[T]:
5959
_sort_list(self, ~key, alg)
6060
else:
6161
_sort_list(self, ident[T], alg)
62-
if reversed:
62+
if reverse:
6363
self.reverse()
64-
65-

stdlib/sys.seq

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ stdin = File(_C.seq_stdin())
44
stdout = File(_C.seq_stdout())
55
stderr = File(_C.seq_stderr())
66

7-
exit = _C.exit
7+
def exit(status: int = 0):
8+
raise SystemExit(status)

stdlib/threading.seq

-6
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,3 @@ def get_native_id():
4242

4343
def get_ident():
4444
return get_native_id() + 1
45-
46-
extend list[T]:
47-
def lock_append(self: list[T], it: T, lock: Lock):
48-
with lock:
49-
self.append(it)
50-

test/core/sort.seq

+3-3
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,8 @@ def test_stable():
110110
assert tim_sort(data_list, compare_dict) == sorted_list
111111

112112
### Stdlib sort tests ###
113-
print_test(sorted(list[int](), compare_less, reversed=True), list[int]()) # EXPECT: []
114-
print_test(sorted([3, 2, 1], reversed=True), [3, 2, 1]) # EXPECT: [3, 2, 1]
113+
print_test(sorted(list[int](), compare_less, reverse=True), list[int]()) # EXPECT: []
114+
print_test(sorted([3, 2, 1], reverse=True), [3, 2, 1]) # EXPECT: [3, 2, 1]
115115
print_test(sorted([1, 2, 3], compare_greater), [3, 2, 1]) # EXPECT: [3, 2, 1]
116-
print_test(sorted([1, 2, 3], compare_greater, reversed=True), [1, 2, 3]) # EXPECT: [1, 2, 3]
116+
print_test(sorted([1, 2, 3], compare_greater, reverse=True), [1, 2, 3]) # EXPECT: [1, 2, 3]
117117

0 commit comments

Comments
 (0)