-
Notifications
You must be signed in to change notification settings - Fork 603
Expand file tree
/
Copy pathmain.cpp
More file actions
611 lines (561 loc) · 19.4 KB
/
main.cpp
File metadata and controls
611 lines (561 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Copyright (C) 2022-2026 Exaloop Inc. <https://exaloop.io>
#include <algorithm>
#include <cstdio>
#include <dirent.h>
#include <fcntl.h>
#include <fstream>
#include <gc.h>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <tuple>
#include <unistd.h>
#include <vector>
#include "codon/cir/analyze/dataflow/capture.h"
#include "codon/cir/analyze/dataflow/reaching.h"
#include "codon/cir/util/inlining.h"
#include "codon/cir/util/irtools.h"
#include "codon/cir/util/operator.h"
#include "codon/cir/util/outlining.h"
#include "codon/compiler/compiler.h"
#include "codon/compiler/error.h"
#include "codon/parser/common.h"
#include "codon/util/common.h"
#include "gtest/gtest.h"
using namespace codon;
using namespace std;
class TestOutliner : public ir::transform::OperatorPass {
int successes = 0;
int failures = 0;
ir::ReturnInstr *successesReturn = nullptr;
ir::ReturnInstr *failuresReturn = nullptr;
const std::string KEY = "test-outliner-pass";
std::string getKey() const override { return KEY; }
void handle(ir::SeriesFlow *v) override {
auto *M = v->getModule();
auto begin = v->begin(), end = v->end();
bool sawBegin = false, sawEnd = false;
for (auto it = v->begin(); it != v->end(); ++it) {
if (ir::util::isCallOf(*it, "__outline_begin__") && !sawBegin) {
begin = it;
sawBegin = true;
} else if (ir::util::isCallOf(*it, "__outline_end__") && !sawEnd) {
end = it;
sawEnd = true;
}
}
if (sawBegin && sawEnd) {
auto result = ir::util::outlineRegion(ir::cast<ir::BodiedFunc>(getParentFunc()),
v, begin, end);
++(result ? successes : failures);
if (successesReturn)
successesReturn->setValue(M->getInt(successes));
if (failuresReturn)
failuresReturn->setValue(M->getInt(failures));
}
}
void handle(ir::ReturnInstr *v) override {
auto *M = v->getModule();
if (getParentFunc()->getUnmangledName() == "__outline_successes__") {
v->setValue(M->getInt(successes));
successesReturn = v;
}
if (getParentFunc()->getUnmangledName() == "__outline_failures__") {
v->setValue(M->getInt(failures));
failuresReturn = v;
}
}
};
class TestInliner : public ir::transform::OperatorPass {
const std::string KEY = "test-inliner-pass";
std::string getKey() const override { return KEY; }
void handle(ir::CallInstr *v) override {
auto *M = v->getModule();
auto *f = ir::cast<ir::BodiedFunc>(ir::util::getFunc(v->getCallee()));
auto *neg = M->getOrRealizeMethod(M->getIntType(), ir::Module::NEG_MAGIC_NAME,
{M->getIntType()});
if (!f)
return;
auto name = f->getUnmangledName();
if (name.find("inline_me") != std::string::npos) {
auto aggressive = name.find("aggressive") != std::string::npos;
auto res = ir::util::inlineCall(v, aggressive);
if (!res)
return;
for (auto *var : res.newVars)
ir::cast<ir::BodiedFunc>(getParentFunc())->push_back(var);
v->replaceAll(ir::util::call(neg, {res.result}));
}
}
};
struct PartitionArgsByEscape : public ir::util::Operator {
std::vector<ir::analyze::dataflow::CaptureInfo> expected;
std::vector<ir::Value *> calls;
void handle(ir::CallInstr *v) override {
using namespace codon::ir;
if (auto *f = cast<Func>(util::getFunc(v->getCallee()))) {
if (f->getUnmangledName() == "expect_capture") {
// Format is:
// - Return captures (bool)
// - Extern captures (bool)
// - Captured arg indices (int tuple)
std::vector<Value *> args(v->begin(), v->end());
seqassertn(args.size() == 3, "bad escape-test call (size)");
seqassertn(isA<BoolConst>(args[0]) && isA<BoolConst>(args[1]),
"bad escape-test call (arg types)");
ir::analyze::dataflow::CaptureInfo info;
info.returnCaptures = cast<BoolConst>(args[0])->getVal();
info.externCaptures = cast<BoolConst>(args[1])->getVal();
auto *tuple = cast<CallInstr>(args[2]);
seqassertn(tuple,
"last escape-test call argument should be a const tuple literal");
for (auto *arg : *tuple) {
seqassertn(isA<IntConst>(arg), "final args should be int");
info.argCaptures.push_back(cast<IntConst>(arg)->getVal());
}
expected.push_back(info);
calls.push_back(v);
}
}
}
};
struct EscapeValidator : public ir::transform::Pass {
const std::string KEY = "test-escape-validator-pass";
std::string getKey() const override { return KEY; }
std::string capAnalysisKey;
explicit EscapeValidator(const std::string &capAnalysisKey)
: ir::transform::Pass(), capAnalysisKey(capAnalysisKey) {}
void run(ir::Module *m) override {
using namespace codon::ir;
auto *capResult =
getAnalysisResult<ir::analyze::dataflow::CaptureResult>(capAnalysisKey);
for (auto *var : *m) {
if (auto *f = cast<Func>(var)) {
PartitionArgsByEscape pabe;
f->accept(pabe);
auto expected = pabe.expected;
if (expected.empty())
continue;
auto it = capResult->results.find(f->getId());
seqassertn(it != capResult->results.end(),
"function not found in capture results");
auto received = it->second;
seqassertn(expected.size() == received.size(),
"size mismatch in capture results");
for (unsigned i = 0; i < expected.size(); i++) {
auto exp = expected[i];
auto got = received[i];
std::sort(exp.argCaptures.begin(), exp.argCaptures.end());
std::sort(got.argCaptures.begin(), got.argCaptures.end());
bool good = (exp.returnCaptures == got.returnCaptures) &&
(exp.externCaptures == got.externCaptures) &&
(exp.argCaptures == got.argCaptures);
pabe.calls[i]->replaceAll(m->getBool(good));
}
}
}
}
};
vector<string> splitLines(const string &output) {
vector<string> result;
string line;
istringstream stream(output);
const char delim = '\n';
while (getline(stream, line, delim))
result.push_back(line);
return result;
}
static pair<bool, string> findExpectOnLine(const string &line) {
for (auto EXPECT_STR : vector<pair<bool, string>>{
{false, "# EXPECT: "}, {false, "#: "}, {true, "#! "}}) {
size_t pos = line.find(EXPECT_STR.second);
if (pos != string::npos)
return {EXPECT_STR.first, line.substr(pos + EXPECT_STR.second.length())};
}
return {false, ""};
}
static pair<vector<string>, bool> findExpects(const string &filename, bool isCode) {
vector<string> result;
bool isError = false;
string line;
if (!isCode) {
ifstream file(filename);
if (!file.good()) {
cerr << "error: could not open " << filename << endl;
exit(EXIT_FAILURE);
}
while (getline(file, line)) {
auto expect = findExpectOnLine(line);
if (!expect.second.empty()) {
result.push_back(expect.second);
isError |= expect.first;
}
}
file.close();
} else {
istringstream file(filename);
while (getline(file, line)) {
auto expect = findExpectOnLine(line);
if (!expect.second.empty()) {
result.push_back(expect.second);
isError |= expect.first;
}
}
}
return {result, isError};
}
string argv0;
void seq_exc_init(int flags);
class SeqTest
: public testing::TestWithParam<tuple<
string /*filename*/, bool /*debug*/, string /* case name */,
string /* case code */, int /* case line */, bool /* barebones stdlib */,
bool /* Python numerics */, bool /* run */>> {
vector<char> buf;
int out_pipe[2];
pid_t pid;
public:
SeqTest() : buf(65536), out_pipe(), pid() {}
string getFilename(const string &basename) {
return string(TEST_DIR) + "/" + basename;
}
int runInChildProcess(bool avoidFork = false) {
auto fn = [this]() {
auto file = getFilename(get<0>(GetParam()));
bool debug = get<1>(GetParam());
auto code = get<3>(GetParam());
auto startLine = get<4>(GetParam());
int testFlags = 1 + get<5>(GetParam());
bool pyNumerics = get<6>(GetParam());
bool run = get<7>(GetParam());
auto compiler = std::make_unique<Compiler>(
argv0, debug, /*disabledPasses=*/std::vector<std::string>{}, /*isTest=*/true,
pyNumerics);
// make sure we abort() on runtime error
compiler->getLLVMVisitor()->setStandalone(true);
llvm::handleAllErrors(code.empty()
? compiler->parseFile(file, testFlags)
: compiler->parseCode(file, code, startLine, testFlags),
[](const error::ParserErrorInfo &e) {
for (auto &group : e.getErrors()) {
for (auto &msg : group) {
getLogger().level = 0;
printf("%s\n", msg.getMessage().c_str());
}
}
fflush(stdout);
exit(EXIT_FAILURE);
});
auto *pm = compiler->getPassManager();
pm->registerPass(std::make_unique<TestOutliner>());
pm->registerPass(std::make_unique<TestInliner>());
auto capKey =
pm->registerAnalysis(std::make_unique<ir::analyze::dataflow::CaptureAnalysis>(
ir::analyze::dataflow::RDAnalysis::KEY,
ir::analyze::dataflow::DominatorAnalysis::KEY),
{ir::analyze::dataflow::RDAnalysis::KEY,
ir::analyze::dataflow::DominatorAnalysis::KEY});
pm->registerPass(std::make_unique<EscapeValidator>(capKey), /*insertBefore=*/"",
{capKey});
llvm::cantFail(compiler->compile());
if (run)
compiler->getLLVMVisitor()->run({file});
fflush(stdout);
};
assert(pipe(out_pipe) != -1);
pid = fork();
GC_atfork_prepare();
assert(pid != -1);
if (pid == 0) {
GC_atfork_child();
dup2(out_pipe[1], STDOUT_FILENO);
close(out_pipe[0]);
close(out_pipe[1]);
fn();
exit(EXIT_SUCCESS);
} else {
GC_atfork_parent();
int status = -1;
close(out_pipe[1]);
buf.clear();
char temp_buf[4096];
ssize_t n;
while ((n = read(out_pipe[0], temp_buf, sizeof(temp_buf))) > 0) {
buf.insert(buf.end(), temp_buf, temp_buf + n);
}
buf.push_back('\0');
assert(waitpid(pid, &status, 0) == pid);
close(out_pipe[0]);
return status;
}
return -1;
}
string result() { return string(buf.data()); }
};
static string
getTestNameFromParam(const testing::TestParamInfo<SeqTest::ParamType> &info) {
const string basename = get<0>(info.param);
const bool debug = get<1>(info.param);
// normalize basename
// size_t found1 = basename.find('/');
// size_t found2 = basename.find('.');
// assert(found1 != string::npos);
// assert(found2 != string::npos);
// assert(found2 > found1);
// string normname = basename.substr(found1 + 1, found2 - found1 - 1);
string normname = basename;
replace(normname.begin(), normname.end(), '/', '_');
replace(normname.begin(), normname.end(), '.', '_');
return normname + (debug ? "_debug" : "");
}
static string
getTypeTestNameFromParam(const testing::TestParamInfo<SeqTest::ParamType> &info) {
return getTestNameFromParam(info) + "_" + get<2>(info.param);
}
TEST_P(SeqTest, Run) {
const string file = get<0>(GetParam());
int status;
bool isCase = !get<2>(GetParam()).empty();
if (!isCase)
status = runInChildProcess();
else
status = runInChildProcess();
if (!WIFEXITED(status))
std::cerr << result() << std::endl;
ASSERT_TRUE(WIFEXITED(status));
string output = result();
auto expects = findExpects(!isCase ? getFilename(file) : get<3>(GetParam()), isCase);
if (WEXITSTATUS(status) != int(expects.second))
fprintf(stderr, "%s\n", output.c_str());
ASSERT_EQ(WEXITSTATUS(status), int(expects.second));
const bool assertsFailed = output.find("TEST FAILED") != string::npos;
EXPECT_FALSE(assertsFailed);
if (assertsFailed)
std::cerr << output << std::endl;
if (!expects.first.empty()) {
vector<string> results = splitLines(output);
for (unsigned i = 0; i < min(results.size(), expects.first.size()); i++)
if (expects.second)
EXPECT_EQ(results[i].substr(0, expects.first[i].size()), expects.first[i]);
else
EXPECT_EQ(results[i], expects.first[i]);
EXPECT_EQ(results.size(), expects.first.size());
}
}
auto getTypeTests(const vector<string> &files) {
vector<tuple<string, bool, string, string, int, bool, bool, bool>> cases;
for (auto &f : files) {
bool barebones = false;
string l;
ifstream fin(string(TEST_DIR) + "/" + f);
string code, testName;
int test = 0;
int codeLine = 0;
int line = 0;
while (getline(fin, l)) {
if (l.substr(0, 3) == "#%%") {
if (line && testName != "__ignore__") {
cases.emplace_back(make_tuple(f, true, to_string(line) + "_" + testName, code,
codeLine, barebones, false, true));
}
auto t = ast::split(l.substr(4), ',');
barebones = (t.size() > 1 && t[1] == "barebones");
testName = t[0];
code = l + "\n";
codeLine = line;
test++;
} else {
code += l + "\n";
}
line++;
}
if (line && testName != "__ignore__") {
cases.emplace_back(make_tuple(f, true, to_string(line) + "_" + testName, code,
codeLine, barebones, false, true));
}
}
return cases;
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(
TypeTests, SeqTest,
testing::ValuesIn(getTypeTests({
"parser/typecheck/test_access.codon",
"parser/typecheck/test_assign.codon",
"parser/typecheck/test_basic.codon",
"parser/typecheck/test_call.codon",
"parser/typecheck/test_class.codon",
"parser/typecheck/test_collections.codon",
"parser/typecheck/test_cond.codon",
"parser/typecheck/test_ctx.codon",
"parser/typecheck/test_error.codon",
"parser/typecheck/test_function.codon",
"parser/typecheck/test_import.codon",
"parser/typecheck/test_infer.codon",
"parser/typecheck/test_loops.codon",
"parser/typecheck/test_op.codon",
"parser/typecheck/test_parser.codon",
"parser/typecheck/test_python.codon",
"parser/typecheck/test_typecheck.codon"
})),
getTypeTestNameFromParam);
INSTANTIATE_TEST_SUITE_P(
CoreTests, SeqTest,
testing::Combine(
testing::Values(
"core/helloworld.codon",
"core/arithmetic.codon",
"core/parser.codon",
"core/generics.codon",
"core/generators.codon",
"core/exceptions.codon",
"core/containers.codon",
"core/trees.codon",
"core/range.codon",
"core/bltin.codon",
"core/arguments.codon",
"core/match.codon",
"core/serialization.codon",
"core/pipeline.codon",
"core/empty.codon",
"core/vec_simd.codon"
),
testing::Values(true, false),
testing::Values(""),
testing::Values(""),
testing::Values(0),
testing::Values(false),
testing::Values(false),
testing::Values(true)
),
getTestNameFromParam);
INSTANTIATE_TEST_SUITE_P(
NumericsTests, SeqTest,
testing::Combine(
testing::Values(
"core/numerics.codon"
),
testing::Values(true, false),
testing::Values(""),
testing::Values(""),
testing::Values(0),
testing::Values(false),
testing::Values(true),
testing::Values(true)
),
getTestNameFromParam);
INSTANTIATE_TEST_SUITE_P(
StdlibTests, SeqTest,
testing::Combine(
testing::Values(
"stdlib/llvm_test.codon",
"stdlib/str_test.codon",
"stdlib/re_test.codon",
"stdlib/math_test.codon",
"stdlib/cmath_test.codon",
"stdlib/datetime_test.codon",
"stdlib/itertools_test.codon",
"stdlib/bisect_test.codon",
"stdlib/random_test.codon",
"stdlib/statistics_test.codon",
"stdlib/sort_test.codon",
"stdlib/heapq_test.codon",
"stdlib/operator_test.codon",
"stdlib/asyncio_test.codon",
"python/pybridge.codon"
),
testing::Values(true, false),
testing::Values(""),
testing::Values(""),
testing::Values(0),
testing::Values(false),
testing::Values(false),
testing::Values(true)
),
getTestNameFromParam);
INSTANTIATE_TEST_SUITE_P(
OptTests, SeqTest,
testing::Combine(
testing::Values(
"transform/canonical.codon",
"transform/dict_opt.codon",
"transform/escapes.codon",
"transform/folding.codon",
"transform/for_lowering.codon",
"transform/io_opt.codon",
"transform/inlining.codon",
"transform/list_opt.codon",
"transform/omp.codon",
"transform/outlining.codon",
"transform/str_opt.codon"
),
testing::Values(true, false),
testing::Values(""),
testing::Values(""),
testing::Values(0),
testing::Values(false),
testing::Values(false),
testing::Values(true)
),
getTestNameFromParam);
INSTANTIATE_TEST_SUITE_P(
GpuTests, SeqTest,
testing::Combine(
testing::Values(
"transform/kernels.codon"
),
testing::Values(true, false),
testing::Values(""),
testing::Values(""),
testing::Values(0),
testing::Values(false),
testing::Values(false),
testing::Values(false) // do not run by default, just compile
),
getTestNameFromParam);
INSTANTIATE_TEST_SUITE_P(
NumPyTests, SeqTest,
testing::Combine(
testing::Values(
"numpy/random_tests/test_mt19937.codon",
"numpy/random_tests/test_pcg64.codon",
"numpy/random_tests/test_philox.codon",
"numpy/random_tests/test_sfc64.codon",
"numpy/test_dtype.codon",
"numpy/test_elision.codon",
"numpy/test_fft.codon",
"numpy/test_functional.codon",
// "numpy/test_fusion.codon", // TODO: uses a lot of RAM
"numpy/test_indexing.codon",
"numpy/test_io.codon",
"numpy/test_lib.codon",
"numpy/test_linalg.codon",
"numpy/test_loops.codon",
// "numpy/test_misc.codon", // TODO: takes forever in debug mode
"numpy/test_ndmath.codon",
"numpy/test_npdatetime.codon",
"numpy/test_pybridge.codon",
"numpy/test_reductions.codon",
"numpy/test_routines.codon",
"numpy/test_sorting.codon",
"numpy/test_statistics.codon",
"numpy/test_ufunc.codon",
"numpy/test_window.codon"
),
testing::Values(true, false),
testing::Values(""),
testing::Values(""),
testing::Values(0),
testing::Values(false),
testing::Values(false),
testing::Values(true)
),
getTestNameFromParam);
// clang-format on
int main(int argc, char *argv[]) {
argv0 = ast::Filesystem::executable_path(argv[0]);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}