-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathlpython.cpp
1275 lines (1151 loc) · 50.6 KB
/
lpython.cpp
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <chrono>
#include <iostream>
#include <stdlib.h>
#include <cstdlib>
#define CLI11_HAS_FILESYSTEM 0
#include <bin/CLI11.hpp>
#include <libasr/stacktrace.h>
#include <lpython/pickle.h>
#include <lpython/semantics/python_ast_to_asr.h>
#include <libasr/codegen/asr_to_llvm.h>
#include <libasr/codegen/asr_to_cpp.h>
#include <libasr/codegen/asr_to_c.h>
#include <libasr/codegen/asr_to_py.h>
#include <libasr/codegen/asr_to_x86.h>
#include <lpython/python_evaluator.h>
#include <libasr/codegen/evaluator.h>
#include <libasr/pass/pass_manager.h>
#include <libasr/asr_utils.h>
#include <libasr/asr_verify.h>
#include <libasr/modfile.h>
#include <libasr/config.h>
#include <libasr/string_utils.h>
#include <libasr/lsp_interface.h>
#include <lpython/utils.h>
#include <lpython/python_serialization.h>
#include <lpython/parser/tokenizer.h>
#include <lpython/parser/parser.h>
#include <cpp-terminal/terminal.h>
#include <cpp-terminal/prompt0.h>
#ifdef HAVE_LFORTRAN_RAPIDJSON
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#endif
namespace {
using LFortran::endswith;
using LFortran::CompilerOptions;
using LFortran::parse_python_file;
enum Backend {
llvm, cpp, x86
};
std::string remove_extension(const std::string& filename) {
size_t lastdot = filename.find_last_of(".");
if (lastdot == std::string::npos) return filename;
return filename.substr(0, lastdot);
}
std::string remove_path(const std::string& filename) {
size_t lastslash = filename.find_last_of("/");
if (lastslash == std::string::npos) return filename;
return filename.substr(lastslash+1);
}
std::string get_kokkos_dir()
{
char *env_p = std::getenv("LFORTRAN_KOKKOS_DIR");
if (env_p) return env_p;
std::cerr << "The code C++ generated by the C++ LFortran backend uses the Kokkos library" << std::endl;
std::cerr << "(https://github.com/kokkos/kokkos). Please define the LFORTRAN_KOKKOS_DIR" << std::endl;
std::cerr << "environment variable to point to the Kokkos installation." << std::endl;
throw LFortran::LCompilersException("LFORTRAN_KOKKOS_DIR is not defined");
}
#ifdef HAVE_LFORTRAN_LLVM
#endif
int emit_tokens(const std::string &infile, bool line_numbers, const CompilerOptions &compiler_options)
{
std::string input = LFortran::read_file(infile);
// Src -> Tokens
Allocator al(64*1024*1024);
std::vector<int> toks;
std::vector<LFortran::YYSTYPE> stypes;
std::vector<LFortran::Location> locations;
LFortran::diag::Diagnostics diagnostics;
auto res = LFortran::tokens(al, input, diagnostics, &stypes, &locations);
LFortran::LocationManager lm;
lm.in_filename = infile;
lm.init_simple(input);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (res.ok) {
toks = res.result;
} else {
LFORTRAN_ASSERT(diagnostics.has_error())
return 1;
}
for (size_t i=0; i < toks.size(); i++) {
std::cout << LFortran::pickle_token(toks[i], stypes[i]);
if (line_numbers) {
std::cout << " " << locations[i].first << ":" << locations[i].last;
}
std::cout << std::endl;
}
return 0;
}
int emit_ast(const std::string &infile,
const std::string &runtime_library_dir,
CompilerOptions &compiler_options)
{
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::Result<LFortran::LPython::AST::ast_t*> r = parse_python_file(
al, runtime_library_dir, infile, diagnostics, compiler_options.new_parser);
if (diagnostics.diagnostics.size() > 0) {
LFortran::LocationManager lm;
lm.in_filename = infile;
// TODO: only read this once, and pass it as an argument to parse_python_file()
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
std::cerr << diagnostics.render(input, lm, compiler_options);
}
if (!r.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 1;
}
LFortran::LPython::AST::ast_t* ast = r.result;
if (compiler_options.tree) {
std::cout << LFortran::LPython::pickle_tree_python(*ast,
compiler_options.use_colors) << std::endl;
} else {
std::cout << LFortran::LPython::pickle_python(*ast,
compiler_options.use_colors, compiler_options.indent) << std::endl;
}
return 0;
}
int emit_asr(const std::string &infile,
LCompilers::PassManager& pass_manager,
const std::string &runtime_library_dir,
bool with_intrinsic_modules, CompilerOptions &compiler_options)
{
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
LFortran::Result<LFortran::LPython::AST::ast_t*> r1 = parse_python_file(
al, runtime_library_dir, infile, diagnostics, compiler_options.new_parser);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r1.ok) {
return 1;
}
LFortran::LPython::AST::ast_t* ast = r1.result;
diagnostics.diagnostics.clear();
LFortran::Result<LFortran::ASR::TranslationUnit_t*>
r = LFortran::LPython::python_ast_to_asr(al, *ast, diagnostics, true,
compiler_options.disable_main, compiler_options.symtab_only, infile);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 2;
}
LFortran::ASR::TranslationUnit_t* asr = r.result;
LCompilers::PassOptions pass_options;
pass_options.run_fun = "f";
pass_options.always_run = true;
pass_manager.apply_passes(al, asr, pass_options);
if (compiler_options.tree) {
std::cout << LFortran::pickle_tree(*asr, compiler_options.use_colors,
with_intrinsic_modules) << std::endl;
} else {
std::cout << LFortran::pickle(*asr, compiler_options.use_colors, compiler_options.indent,
with_intrinsic_modules) << std::endl;
}
return 0;
}
int emit_cpp(const std::string &infile,
const std::string &runtime_library_dir,
CompilerOptions &compiler_options)
{
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
LFortran::Result<LFortran::LPython::AST::ast_t*> r = parse_python_file(
al, runtime_library_dir, infile, diagnostics, compiler_options.new_parser);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r.ok) {
return 1;
}
LFortran::LPython::AST::ast_t* ast = r.result;
diagnostics.diagnostics.clear();
LFortran::Result<LFortran::ASR::TranslationUnit_t*>
r1 = LFortran::LPython::python_ast_to_asr(al, *ast, diagnostics, true,
compiler_options.disable_main, compiler_options.symtab_only, infile);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r1.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 2;
}
LFortran::ASR::TranslationUnit_t* asr = r1.result;
diagnostics.diagnostics.clear();
auto res = LFortran::asr_to_cpp(al, *asr, diagnostics,
compiler_options.platform, 0);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!res.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 3;
}
std::cout << res.result;
return 0;
}
int emit_c(const std::string &infile,
const std::string &runtime_library_dir,
CompilerOptions &compiler_options)
{
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
LFortran::Result<LFortran::LPython::AST::ast_t*> r = parse_python_file(
al, runtime_library_dir, infile, diagnostics, compiler_options.new_parser);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r.ok) {
return 1;
}
LFortran::LPython::AST::ast_t* ast = r.result;
diagnostics.diagnostics.clear();
LFortran::Result<LFortran::ASR::TranslationUnit_t*>
r1 = LFortran::LPython::python_ast_to_asr(al, *ast, diagnostics, true,
compiler_options.disable_main, compiler_options.symtab_only, infile);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r1.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 2;
}
LFortran::ASR::TranslationUnit_t* asr = r1.result;
diagnostics.diagnostics.clear();
auto res = LFortran::asr_to_c(al, *asr, diagnostics,
compiler_options.platform, 0);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!res.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 3;
}
std::cout << res.result;
return 0;
}
#ifdef HAVE_LFORTRAN_RAPIDJSON
int get_symbols (const std::string &infile,
const std::string &runtime_library_dir,
CompilerOptions &compiler_options) {
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
LFortran::Result<LFortran::LPython::AST::ast_t*> r1 = LFortran::parse_python_file(
al, runtime_library_dir, infile, diagnostics, compiler_options.new_parser);
if (r1.ok) {
LFortran::LPython::AST::ast_t* ast = r1.result;
LFortran::Result<LFortran::ASR::TranslationUnit_t*>
x = LFortran::LPython::python_ast_to_asr(al, *ast, diagnostics, true,
compiler_options.disable_main, compiler_options.symtab_only, infile);
if (!x.ok) {
std::cout << "{}\n";
return 0;
}
std::vector<LFortran::LPython::document_symbols> symbol_lists;
LFortran::LPython::document_symbols loc;
for (auto &a : x.result->m_global_scope->get_scope()) {
std::string symbol_name = a.first;
uint32_t first_line;
uint32_t last_line;
uint32_t first_column;
uint32_t last_column;
lm.pos_to_linecol(a.second->base.loc.first, first_line, first_column);
lm.pos_to_linecol(a.second->base.loc.last, last_line, last_column);
loc.first_column = first_column;
loc.last_column = last_column;
loc.first_line = first_line-1;
loc.last_line = last_line-1;
loc.symbol_name = symbol_name;
symbol_lists.push_back(loc);
}
rapidjson::Document test_output(rapidjson::kArrayType);
rapidjson::Document range_object(rapidjson::kObjectType);
rapidjson::Document start_detail(rapidjson::kObjectType);
rapidjson::Document end_detail(rapidjson::kObjectType);
rapidjson::Document location_object(rapidjson::kObjectType);
rapidjson::Document test_capture(rapidjson::kObjectType);
test_output.SetArray();
for (auto symbol : symbol_lists) {
uint32_t start_character = symbol.first_column;
uint32_t start_line = symbol.first_line;
uint32_t end_character = symbol.last_column;
uint32_t end_line = symbol.last_line;
std::string name = symbol.symbol_name;
range_object.SetObject();
rapidjson::Document::AllocatorType &allocator = range_object.GetAllocator();
start_detail.SetObject();
start_detail.AddMember("character", rapidjson::Value().SetInt(start_character), allocator);
start_detail.AddMember("line", rapidjson::Value().SetInt(start_line), allocator);
range_object.AddMember("start", start_detail, allocator);
end_detail.SetObject();
end_detail.AddMember("character", rapidjson::Value().SetInt(end_character), allocator);
end_detail.AddMember("line", rapidjson::Value().SetInt(end_line), allocator);
range_object.AddMember("end", end_detail, allocator);
location_object.SetObject();
location_object.AddMember("range", range_object, allocator);
location_object.AddMember("uri", rapidjson::Value().SetString("uri", allocator), allocator);
test_capture.SetObject();
test_capture.AddMember("kind", rapidjson::Value().SetInt(1), allocator);
test_capture.AddMember("location", location_object, allocator);
test_capture.AddMember("name", rapidjson::Value().SetString(name.c_str(), allocator), allocator);
test_output.PushBack(test_capture, test_output.GetAllocator());
}
rapidjson::StringBuffer buffer;
buffer.Clear();
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
test_output.Accept(writer);
std::string resp_str( buffer.GetString() );
std::cout << resp_str;
}
else {
std::cout << "{}\n";
}
return 0;
}
int get_errors (const std::string &infile,
const std::string &runtime_library_dir,
CompilerOptions &compiler_options) {
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
LFortran::Result<LFortran::LPython::AST::ast_t*>
r1 = LFortran::parse_python_file(al, runtime_library_dir, infile,
diagnostics, compiler_options.new_parser);
if (r1.ok) {
LFortran::LPython::AST::ast_t* ast = r1.result;
LFortran::Result<LFortran::ASR::TranslationUnit_t*>
r = LFortran::LPython::python_ast_to_asr(al, *ast, diagnostics, true,
compiler_options.disable_main, compiler_options.symtab_only, infile);
}
std::vector<LFortran::LPython::error_highlight> diag_lists;
LFortran::LPython::error_highlight h;
for (auto &d : diagnostics.diagnostics) {
if (compiler_options.no_warnings && d.level != LFortran::diag::Level::Error) {
continue;
}
h.message = d.message;
h.severity = d.level;
for (auto label : d.labels) {
for (auto span : label.spans) {
uint32_t first_line;
uint32_t first_column;
uint32_t last_line;
uint32_t last_column;
lm.pos_to_linecol(span.loc.first, first_line, first_column);
lm.pos_to_linecol(span.loc.last, last_line, last_column);
h.first_column = first_column;
h.last_column = last_column;
h.first_line = first_line-1;
h.last_line = last_line-1;
diag_lists.push_back(h);
}
}
}
rapidjson::Document range_obj(rapidjson::kObjectType);
rapidjson::Document start_detail(rapidjson::kObjectType);
rapidjson::Document end_detail(rapidjson::kObjectType);
rapidjson::Document diag_results(rapidjson::kArrayType);
rapidjson::Document diag_capture(rapidjson::kObjectType);
rapidjson::Document message_send(rapidjson::kObjectType);
for (auto diag : diag_lists) {
uint32_t start_line = diag.first_line;
uint32_t start_column = diag.first_column;
uint32_t end_line = diag.last_line;
uint32_t end_column = diag.last_column;
uint32_t severity = diag.severity;
std::string msg = diag.message;
range_obj.SetObject();
rapidjson::Document::AllocatorType &allocator = range_obj.GetAllocator();
start_detail.SetObject();
start_detail.AddMember("line", rapidjson::Value().SetInt(start_line), allocator);
start_detail.AddMember("character", rapidjson::Value().SetInt(start_column), allocator);
range_obj.AddMember("start", start_detail, allocator);
end_detail.SetObject();
end_detail.AddMember("line", rapidjson::Value().SetInt(end_line), allocator);
end_detail.AddMember("character", rapidjson::Value().SetInt(end_column), allocator);
range_obj.AddMember("end", end_detail, allocator);
diag_results.SetArray();
diag_capture.AddMember("source", rapidjson::Value().SetString("lpyth", allocator), allocator);
diag_capture.AddMember("range", range_obj, allocator);
diag_capture.AddMember("message", rapidjson::Value().SetString(msg.c_str(), allocator), allocator);
diag_capture.AddMember("severity", rapidjson::Value().SetInt(severity), allocator);
diag_results.PushBack(diag_capture, allocator);
message_send.SetObject();
message_send.AddMember("uri", rapidjson::Value().SetString("uri", allocator), allocator);
message_send.AddMember("diagnostics", diag_results, allocator);
}
rapidjson::StringBuffer buffer;
buffer.Clear();
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
message_send.Accept(writer);
std::string resp_str( buffer.GetString() );
std::cout << resp_str;
return 0;
}
bool input_in_scope_identifier(int input_location,
std::pair<int, int> token_location) {
return token_location.first <= input_location &&
input_location <= token_location.second;
}
bool find_tok_in_scopes(const std::string &infile,
const std::string &runtime_library_dir,
CompilerOptions &compiler_options,
const std::string tok_name) {
Allocator al(4 * 1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
LFortran::Result<LFortran::LPython::AST::ast_t *> r1 =
LFortran::parse_python_file(al, runtime_library_dir, infile, diagnostics,
compiler_options.new_parser);
if (r1.ok) {
LFortran::LPython::AST::ast_t *ast = r1.result;
LFortran::Result<LFortran::ASR::TranslationUnit_t *> x =
LFortran::LPython::python_ast_to_asr(
al, *ast, diagnostics, true, compiler_options.disable_main,
compiler_options.symtab_only, infile);
if (!x.ok) {
std::cout << "{}\n";
return false;
}
std::vector<LFortran::LPython::document_symbols> symbol_lists;
LFortran::LPython::document_symbols loc;
for (auto &a : x.result->m_global_scope->get_scope()) {
std::string symbol_name = a.first;
uint32_t first_line;
uint32_t last_line;
uint32_t first_column;
uint32_t last_column;
lm.pos_to_linecol(a.second->base.loc.first, first_line, first_column);
lm.pos_to_linecol(a.second->base.loc.last, last_line, last_column);
loc.first_column = first_column;
loc.last_column = last_column;
loc.first_line = first_line - 1;
loc.last_line = last_line - 1;
loc.symbol_name = symbol_name;
if (loc.symbol_name == tok_name) {
rapidjson::Document test_output(rapidjson::kArrayType);
rapidjson::Document range_object(rapidjson::kObjectType);
rapidjson::Document start_detail(rapidjson::kObjectType);
rapidjson::Document end_detail(rapidjson::kObjectType);
rapidjson::Document location_object(rapidjson::kObjectType);
rapidjson::Document test_capture(rapidjson::kObjectType);
test_output.SetArray();
uint32_t start_character = loc.first_column;
uint32_t start_line = loc.first_line;
uint32_t end_character = loc.last_column;
uint32_t end_line = loc.last_line;
std::string name = loc.symbol_name;
range_object.SetObject();
rapidjson::Document::AllocatorType &allocator =
range_object.GetAllocator();
start_detail.SetObject();
start_detail.AddMember(
"character", rapidjson::Value().SetInt(start_character), allocator);
start_detail.AddMember("line", rapidjson::Value().SetInt(start_line),
allocator);
range_object.AddMember("start", start_detail, allocator);
end_detail.SetObject();
end_detail.AddMember("character",
rapidjson::Value().SetInt(end_character), allocator);
end_detail.AddMember("line", rapidjson::Value().SetInt(end_line),
allocator);
range_object.AddMember("end", end_detail, allocator);
location_object.SetObject();
location_object.AddMember("range", range_object, allocator);
location_object.AddMember(
"uri", rapidjson::Value().SetString("uri", allocator), allocator);
test_capture.SetObject();
test_capture.AddMember("kind", rapidjson::Value().SetInt(1), allocator);
test_capture.AddMember("location", location_object, allocator);
test_capture.AddMember(
"name", rapidjson::Value().SetString(name.c_str(), allocator),
allocator);
test_output.PushBack(test_capture, test_output.GetAllocator());
rapidjson::StringBuffer buffer;
buffer.Clear();
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
test_output.Accept(writer);
std::string resp_str(buffer.GetString());
std::cout << resp_str;
return true;
}
}
std::cout << "{}\n";
return false;
}
std::cout << "{}\n";
return false;
}
std::pair<std::pair<int, int>, std::pair<int, int>>
return_goto_def(const std::string &infile,
const std::string &runtime_library_dir,
CompilerOptions compiler_options, int index) {
std::string input = LFortran::read_file(infile);
// Src -> Tokens
Allocator al(64 * 1024 * 1024);
std::vector<int> toks;
std::vector<LFortran::YYSTYPE> stypes;
std::vector<LFortran::Location> locations;
LFortran::diag::Diagnostics diagnostics;
auto res = LFortran::tokens(al, input, diagnostics, &stypes, &locations);
LFortran::LocationManager lm;
lm.in_filename = infile;
lm.init_simple(input);
// std::cerr << diagnostics.render(input, lm, compiler_options);
if (res.ok) {
toks = res.result;
} else {
std::cout << "{}\n";
return {};
}
for (size_t i = 0; i < toks.size(); ++i) {
if (input_in_scope_identifier(
index,
std::make_pair<int, int>(locations[i].first, locations[i].last))) {
auto token_name = LFortran::get_token_name(toks[i], stypes[i]);
if (find_tok_in_scopes(infile, runtime_library_dir, compiler_options,
token_name)) {
return {};
}
}
}
std::cout << "{}\n";
return {};
}
#endif
#ifdef HAVE_LFORTRAN_LLVM
int emit_llvm(const std::string &infile,
const std::string &runtime_library_dir,
LCompilers::PassManager& pass_manager,
CompilerOptions &compiler_options)
{
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::string input = LFortran::read_file(infile);
lm.init_simple(input);
LFortran::Result<LFortran::LPython::AST::ast_t*> r = parse_python_file(
al, runtime_library_dir, infile, diagnostics, compiler_options.new_parser);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r.ok) {
return 1;
}
// Src -> AST -> ASR
LFortran::LPython::AST::ast_t* ast = r.result;
diagnostics.diagnostics.clear();
LFortran::Result<LFortran::ASR::TranslationUnit_t*>
r1 = LFortran::LPython::python_ast_to_asr(al, *ast, diagnostics, true,
compiler_options.disable_main, compiler_options.symtab_only, infile);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r1.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 2;
}
LFortran::ASR::TranslationUnit_t* asr = r1.result;
diagnostics.diagnostics.clear();
// ASR -> LLVM
LFortran::PythonCompiler fe(compiler_options);
LFortran::Result<std::unique_ptr<LFortran::LLVMModule>>
res = fe.get_llvm3(*asr, pass_manager, diagnostics);
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!res.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
return 3;
}
std::cout << (res.result)->str();
return 0;
}
void print_time_report(std::vector<std::pair<std::string, double>> ×, bool time_report) {
if (time_report) {
for (auto &stage :times) {
std::cout << stage.first << ": " << stage.second << "ms" << std::endl;
}
}
}
int compile_python_to_object_file(
const std::string &infile,
const std::string &outfile,
const std::string &runtime_library_dir,
LCompilers::PassManager& pass_manager,
CompilerOptions &compiler_options,
bool time_report)
{
Allocator al(4*1024);
LFortran::diag::Diagnostics diagnostics;
LFortran::LocationManager lm;
lm.in_filename = infile;
std::vector<std::pair<std::string, double>>times;
auto file_reading_start = std::chrono::high_resolution_clock::now();
std::string input = LFortran::read_file(infile);
auto file_reading_end = std::chrono::high_resolution_clock::now();
times.push_back(std::make_pair("File reading", std::chrono::duration<double, std::milli>(file_reading_end - file_reading_start).count()));
lm.init_simple(input);
auto parsing_start = std::chrono::high_resolution_clock::now();
LFortran::Result<LFortran::LPython::AST::ast_t*> r = parse_python_file(
al, runtime_library_dir, infile, diagnostics, compiler_options.new_parser);
auto parsing_end = std::chrono::high_resolution_clock::now();
times.push_back(std::make_pair("Parsing", std::chrono::duration<double, std::milli>(parsing_end - parsing_start).count()));
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r.ok) {
print_time_report(times, time_report);
return 1;
}
// Src -> AST -> ASR
LFortran::LPython::AST::ast_t* ast = r.result;
diagnostics.diagnostics.clear();
auto ast_to_asr_start = std::chrono::high_resolution_clock::now();
LFortran::Result<LFortran::ASR::TranslationUnit_t*>
r1 = LFortran::LPython::python_ast_to_asr(al, *ast, diagnostics, true,
compiler_options.disable_main, compiler_options.symtab_only, infile);
auto ast_to_asr_end = std::chrono::high_resolution_clock::now();
times.push_back(std::make_pair("AST to ASR", std::chrono::duration<double, std::milli>(ast_to_asr_end - ast_to_asr_start).count()));
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!r1.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
print_time_report(times, time_report);
return 2;
}
LFortran::ASR::TranslationUnit_t* asr = r1.result;
diagnostics.diagnostics.clear();
// ASR -> LLVM
LFortran::PythonCompiler fe(compiler_options);
LFortran::LLVMEvaluator e(compiler_options.target);
std::unique_ptr<LFortran::LLVMModule> m;
auto asr_to_llvm_start = std::chrono::high_resolution_clock::now();
LFortran::Result<std::unique_ptr<LFortran::LLVMModule>>
res = fe.get_llvm3(*asr, pass_manager, diagnostics);
auto asr_to_llvm_end = std::chrono::high_resolution_clock::now();
times.push_back(std::make_pair("ASR to LLVM", std::chrono::duration<double, std::milli>(asr_to_llvm_end - asr_to_llvm_start).count()));
std::cerr << diagnostics.render(input, lm, compiler_options);
if (!res.ok) {
LFORTRAN_ASSERT(diagnostics.has_error())
print_time_report(times, time_report);
return 3;
}
m = std::move(res.result);
auto llvm_start = std::chrono::high_resolution_clock::now();
e.save_object_file(*(m->m_m), outfile);
auto llvm_end = std::chrono::high_resolution_clock::now();
times.push_back(std::make_pair("LLVM to binary", std::chrono::duration<double, std::milli>(llvm_end - llvm_start).count()));
print_time_report(times, time_report);
return 0;
}
#endif
void do_print_rtlib_header_dir() {
std::string rtlib_header_dir = LFortran::get_runtime_library_header_dir();
std::cout << rtlib_header_dir << std::endl;
}
// infile is an object file
// outfile will become the executable
int link_executable(const std::vector<std::string> &infiles,
const std::string &outfile,
const std::string &runtime_library_dir, Backend backend,
bool static_executable, bool kokkos,
CompilerOptions &compiler_options)
{
/*
The `gcc` line for dynamic linking that is constructed below:
gcc -o $outfile $infile \
-Lsrc/runtime -Wl,-rpath=src/runtime -llpython_runtime
is equivalent to the following:
ld -o $outfile $infile \
-Lsrc/runtime -rpath=src/runtime -llpython_runtime \
-dynamic-linker /lib64/ld-linux-x86-64.so.2 \
/usr/lib/x86_64-linux-gnu/Scrt1.o /usr/lib/x86_64-linux-gnu/libc.so
and this for static linking:
gcc -static -o $outfile $infile \
-Lsrc/runtime -Wl,-rpath=src/runtime -llpython_runtime_static
is equivalent to:
ld -o $outfile $infile \
-Lsrc/runtime -rpath=src/runtime -llpython_runtime_static \
/usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o \
/usr/lib/x86_64-linux-gnu/libc.a \
/usr/lib/gcc/x86_64-linux-gnu/7/libgcc_eh.a \
/usr/lib/x86_64-linux-gnu/libc.a \
/usr/lib/gcc/x86_64-linux-gnu/7/libgcc.a \
/usr/lib/x86_64-linux-gnu/crtn.o
This was tested on Ubuntu 18.04.
The `gcc` and `ld` approaches are equivalent except:
1. The `gcc` command knows how to find and link the `libc` library,
while in `ld` we must do that manually
2. For dynamic linking, we must also specify the dynamic linker for `ld`
Notes:
* We can use `lld` to do the linking via the `ld` approach, so `ld` is
preferable if we can mitigate the issues 1. and 2.
* If we ship our own libc (such as musl), then we know how to find it
and link it, which mitigates the issue 1.
* If we link `musl` statically, then issue 2. does not apply.
* If we link `musl` dynamically, then we have to find the dynamic
linker (doable), which mitigates the issue 2.
One way to find the default dynamic linker is by:
$ readelf -e /bin/bash | grep ld-linux
[Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
There are probably simpler ways.
*/
#ifdef HAVE_LFORTRAN_LLVM
std::string t = (compiler_options.target == "") ? LFortran::LLVMEvaluator::get_default_target_triple() : compiler_options.target;
#else
std::string t = (compiler_options.platform == LFortran::Platform::Windows) ? "x86_64-pc-windows-msvc" : compiler_options.target;
#endif
if (backend == Backend::llvm) {
if (t == "x86_64-pc-windows-msvc") {
std::string cmd = "link /NOLOGO /OUT:" + outfile + " ";
for (auto &s : infiles) {
cmd += s + " ";
}
cmd += runtime_library_dir + "\\lpython_runtime_static.lib";
int err = system(cmd.c_str());
if (err) {
std::cout << "The command '" + cmd + "' failed." << std::endl;
return 10;
}
} else {
std::string CC = "cc";
char *env_CC = std::getenv("LFORTRAN_CC");
if (env_CC) CC = env_CC;
std::string base_path = "\"" + runtime_library_dir + "\"";
std::string options;
std::string runtime_lib = "lpython_runtime";
if (static_executable) {
if (compiler_options.platform != LFortran::Platform::macOS_Intel
&& compiler_options.platform != LFortran::Platform::macOS_ARM) {
options += " -static ";
}
runtime_lib = "lpython_runtime_static";
}
std::string cmd = CC + options + " -o " + outfile + " ";
for (auto &s : infiles) {
cmd += s + " ";
}
cmd += + " -L"
+ base_path + " -Wl,-rpath," + base_path + " -l" + runtime_lib + " -lm";
int err = system(cmd.c_str());
if (err) {
std::cout << "The command '" + cmd + "' failed." << std::endl;
return 10;
}
}
return 0;
} else if (backend == Backend::cpp) {
std::string CXX = "g++";
std::string options, post_options;
if (static_executable) {
options += " -static ";
}
if (compiler_options.openmp) {
options += " -fopenmp ";
}
if (kokkos) {
std::string kokkos_dir = get_kokkos_dir();
post_options += kokkos_dir + "/lib/libkokkoscontainers.a "
+ kokkos_dir + "/lib/libkokkoscore.a -ldl";
}
std::string cmd = CXX + options + " -o " + outfile + " ";
for (auto &s : infiles) {
cmd += s + " ";
}
cmd += + " -L";
cmd += " " + post_options + " -lm";
int err = system(cmd.c_str());
if (err) {
std::cout << "The command '" + cmd + "' failed." << std::endl;
return 10;
}
return 0;
} else if (backend == Backend::x86) {
std::string cmd = "cp " + infiles[0] + " " + outfile;
int err = system(cmd.c_str());
if (err) {
std::cout << "The command '" + cmd + "' failed." << std::endl;
return 10;
}
return 0;
} else {
LFORTRAN_ASSERT(false);
return 1;
}
}
// int emit_c_preprocessor(const std::string &infile, CompilerOptions &compiler_options)
// {
// std::string input = read_file(infile);
//
// LFortran::CPreprocessor cpp(compiler_options);
// LFortran::LocationManager lm;
// lm.in_filename = infile;
// std::string s = cpp.run(input, lm, cpp.macro_definitions);
// std::cout << s;
// return 0;
// }
} // anonymous namespace
int main(int argc, char *argv[])
{
LFortran::initialize();
#if defined(HAVE_LFORTRAN_STACKTRACE)
LFortran::print_stack_on_segfault();
#endif
try {
int dirname_length;
LFortran::get_executable_path(LFortran::binary_executable_path, dirname_length);
std::string runtime_library_dir = LFortran::get_runtime_library_dir();
std::string rtlib_header_dir = LFortran::get_runtime_library_header_dir();
Backend backend;
bool arg_S = false;
bool arg_c = false;
bool arg_v = false;
// bool arg_E = false;
// bool arg_g = false;
// std::string arg_J;
// std::vector<std::string> arg_I;
// std::vector<std::string> arg_l;
// std::vector<std::string> arg_L;
std::string arg_o;
std::vector<std::string> arg_files;
bool arg_version = false;
bool show_tokens = false;
bool show_ast = false;
bool show_asr = false;
bool show_cpp = false;
bool show_c = false;
bool show_document_symbols = false;
int goto_def_index = -1;
bool show_errors = false;
bool with_intrinsic_modules = false;
std::string arg_pass;
bool arg_no_color = false;
bool show_llvm = false;
bool show_asm = false;
bool time_report = false;
bool static_link = false;
std::string arg_backend = "llvm";
std::string arg_kernel_f;
bool print_targets = false;
bool print_rtlib_header_dir = false;
std::string arg_fmt_file;
// int arg_fmt_indent = 4;
// bool arg_fmt_indent_unit = false;
// bool arg_fmt_inplace = false;
// bool arg_fmt_no_color = false;
std::string arg_mod_file;
// bool arg_mod_show_asr = false;
// bool arg_mod_no_color = false;
std::string arg_pywrap_file;
std::string arg_pywrap_array_order="f";
CompilerOptions compiler_options;
LCompilers::PassManager lpython_pass_manager;
CLI::App app{"LPython: modern interactive LLVM-based Python compiler"};
// Standard options compatible with gfortran, gcc or clang
// We follow the established conventions
app.add_option("files", arg_files, "Source files");
// Should the following Options required for LPython??
// Instead we need support all the options from Python 3
app.add_flag("-S", arg_S, "Emit assembly, do not assemble or link");
app.add_flag("-c", arg_c, "Compile and assemble, do not link");
app.add_option("-o", arg_o, "Specify the file to place the output into");
app.add_flag("-v", arg_v, "Be more verbose");
// app.add_flag("-E", arg_E, "Preprocess only; do not compile, assemble or link");
// app.add_option("-l", arg_l, "Link library option");
// app.add_option("-L", arg_L, "Library path option");
// app.add_option("-I", arg_I, "Include path")->allow_extra_args(false);
// app.add_option("-J", arg_J, "Where to save mod files");
// app.add_flag("-g", arg_g, "Compile with debugging information");
// app.add_option("-D", compiler_options.c_preprocessor_defines, "Define <macro>=<value> (or 1 if <value> omitted)")->allow_extra_args(false);
app.add_flag("--version", arg_version, "Display compiler version information");
// LPython specific options
app.add_flag("--cpp", compiler_options.c_preprocessor, "Enable C preprocessing");
app.add_flag("--show-tokens", show_tokens, "Show tokens for the given python file and exit");
app.add_flag("--new-parser", compiler_options.new_parser, "Use the new LPython parser");
app.add_flag("--show-ast", show_ast, "Show AST for the given python file and exit");
app.add_flag("--show-asr", show_asr, "Show ASR for the given python file and exit");
app.add_flag("--show-llvm", show_llvm, "Show LLVM IR for the given file and exit");
app.add_flag("--show-cpp", show_cpp, "Show C++ translation source for the given python file and exit");
app.add_flag("--show-c", show_c, "Show C translation source for the given python file and exit");
app.add_flag("--show-asm", show_asm, "Show assembly for the given file and exit");
app.add_flag("--show-stacktrace", compiler_options.show_stacktrace, "Show internal stacktrace on compiler errors");
app.add_flag("--with-intrinsic-mods", with_intrinsic_modules, "Show intrinsic modules in ASR");
app.add_flag("--no-color", arg_no_color, "Turn off colored AST/ASR");
app.add_flag("--indent", compiler_options.indent, "Indented print ASR/AST");
app.add_flag("--tree", compiler_options.tree, "Tree structure print ASR/AST");
app.add_option("--pass", arg_pass, "Apply the ASR pass and show ASR (implies --show-asr)");
app.add_flag("--disable-main", compiler_options.disable_main, "Do not generate any code for the `main` function");
app.add_flag("--symtab-only", compiler_options.symtab_only, "Only create symbol tables in ASR (skip executable stmt)");
app.add_flag("--time-report", time_report, "Show compilation time report");
app.add_flag("--static", static_link, "Create a static executable");
app.add_flag("--no-warnings", compiler_options.no_warnings, "Turn off all warnings");
app.add_flag("--no-error-banner", compiler_options.no_error_banner, "Turn off error banner");
app.add_option("--backend", arg_backend, "Select a backend (llvm, cpp, x86)")->capture_default_str();
app.add_flag("--openmp", compiler_options.openmp, "Enable openmp");
app.add_flag("--fast", compiler_options.fast, "Best performance (disable strict standard compliance)");