Repository navigation
Expand file tree
/
Copy pathMLIRGenModule.cpp
More file actions
4145 lines (3615 loc) · 175 KB
/
Copy pathMLIRGenModule.cpp
File metadata and controls
4145 lines (3615 loc) · 175 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
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
// Module, discovery, include/import driver methods of MLIRGenImpl (see MLIRGenImpl.h).
// Included first, before MLIRGenImpl.h: MLIRGenImpl.h transitively pulls in ts-new-parser's
// config.h and MLIRGenContextDefines.h, which #define single-letter macros (S(x), V(x), ...)
// for terse AST/MLIR construction. llvm/Support/CommandLine.h and FormattedStream.h,
// transitively included by the two headers below, use those same letters as ordinary
// identifiers (parameter and member names), so those macros corrupt them if already active.
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
#include "TypeScript/ObjDumper.h"
#include "TypeScript/LibraryDeclarations.h"
#include "MLIRGenImpl.h"
#include "mlir/IR/Verifier.h"
#include "mlir/AsmParser/AsmParser.h"
#include "mlir/Dialect/DLTI/DLTI.h"
#include "mlir/Support/FileUtilities.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/Support/xxhash.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ToolOutputFile.h"
#include <set>
namespace typescript
{
namespace mlirgen
{
// the errors said so far: a statement that failed with one of its own needs no "failed statement" after it
static size_t errorCount(const mlir::SmallVector<std::unique_ptr<mlir::Diagnostic>> *messages)
{
if (!messages)
{
return 0;
}
return llvm::count_if(*messages, [](const std::unique_ptr<mlir::Diagnostic> &diag) {
return diag->getSeverity() == mlir::DiagnosticSeverity::Error;
});
}
mlir::LogicalResult MLIRGenImpl::report(SourceFile module, const std::vector<SourceFile> &includeFiles)
{
// output diag info
auto hasAnyError = false;
auto fileName = convertWideToUTF8(module->fileName);
for (auto diag : module->parseDiagnostics)
{
hasAnyError |= diag.category == DiagnosticCategory::Error;
if (diag.category == DiagnosticCategory::Error)
{
emitError(loc2(module, fileName, diag.start, diag.length), convertWideToUTF8(diag.messageText));
}
else
{
emitWarning(loc2(module, fileName, diag.start, diag.length), convertWideToUTF8(diag.messageText));
}
}
for (auto incFile : includeFiles)
{
auto fileName = convertWideToUTF8(incFile->fileName);
for (auto diag : incFile->parseDiagnostics)
{
hasAnyError |= diag.category == DiagnosticCategory::Error;
if (diag.category == DiagnosticCategory::Error)
{
emitError(loc2(incFile, fileName, diag.start, diag.length), convertWideToUTF8(diag.messageText));
}
else
{
emitWarning(loc2(incFile, fileName, diag.start, diag.length), convertWideToUTF8(diag.messageText));
}
}
}
return hasAnyError ? mlir::failure() : mlir::success();
}
std::pair<SourceFile, std::vector<SourceFile>> MLIRGenImpl::loadMainSourceFile()
{
const auto *sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
auto sourceFileLoc = mlir::FileLineColLoc::get(builder.getContext(),
sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0);
return loadSourceBuf(sourceFileLoc, sourceBuf, true);
}
std::pair<SourceFile, std::vector<SourceFile>> MLIRGenImpl::loadSourceFile(SMLoc loc)
{
const auto *sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.FindBufferContainingLoc(loc));
auto sourceFileLoc = mlir::FileLineColLoc::get(builder.getContext(),
sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0);
return loadSourceBuf(sourceFileLoc, sourceBuf, true);
}
std::string MLIRGenImpl::canonicalFilePath(StringRef filePath)
{
// real_path also folds a Windows spelling that differs only in case
SmallString<256> canonical;
if (!sys::fs::real_path(filePath, canonical))
{
return canonical.str().str();
}
// no such file: the path made absolute, with `.` and `..` removed
canonical = filePath;
sys::fs::make_absolute(canonical);
sys::path::remove_dots(canonical, /*remove_dot_dot=*/true);
return canonical.str().str();
}
std::string MLIRGenImpl::moduleSymbolSuffix(StringRef filePath)
{
std::string suffix(llvm::sys::path::stem(llvm::sys::path::filename(filePath)));
suffix.append("_");
suffix.append(std::to_string(llvm::xxh3_64bits(canonicalFilePath(filePath))));
return suffix;
}
std::string MLIRGenImpl::defaultExportName(StringRef filePath)
{
std::string name("default_");
for (auto c : moduleSymbolSuffix(filePath))
{
name.push_back(llvm::isAlnum(c) ? c : '_');
}
return name;
}
// `export default <expression>` (user ruling 11-20: supported): there is no per-module scope, so it is an
// exported constant of a name the module's path gives, `export const default_<stem>_<hash> = <expression>`.
// Made here, after parsing, every pass sees an exported constant: the module's own object defines it, an
// importer compiling the module as declarations declares it, and its initializer runs as any module
// constant's does. `export default function f` and `export default class C` keep their declarations; an
// unnamed one is given the constant's name.
// An implementation with fewer parameters than an overload signature of it (`f(a): T; f(a, b): T; f(a) {...}`),
// which TypeScript allows - a call through that overload passes arguments the implementation ignores: "Expected 1
// arguments, but got 2". Given the overload's further parameters, as optional and of type `any`, it takes them.
static void widenOverloadImplementations(SourceFile sourceFile)
{
NodeFactory nf(NodeFactoryFlags::None);
auto paramsOf = [](Node node) -> NodeArray<ParameterDeclaration> * {
if (node == SyntaxKind::FunctionDeclaration)
{
return &node.as<FunctionDeclaration>()->parameters;
}
if (node == SyntaxKind::MethodDeclaration)
{
return &node.as<MethodDeclaration>()->parameters;
}
if (node == SyntaxKind::Constructor)
{
return &node.as<ConstructorDeclaration>()->parameters;
}
return nullptr;
};
auto nameOf = [](Node node) -> std::string {
if (node == SyntaxKind::Constructor)
{
return "constructor";
}
auto name = node == SyntaxKind::FunctionDeclaration ? node.as<FunctionDeclaration>()->name
: node.as<MethodDeclaration>()->name.as<Node>();
return name && name == SyntaxKind::Identifier ? MLIRHelper::getName(name.as<Identifier>()) : std::string();
};
auto hasBody = [](Node node) {
return node == SyntaxKind::FunctionDeclaration ? !!node.as<FunctionDeclaration>()->body
: node == SyntaxKind::MethodDeclaration ? !!node.as<MethodDeclaration>()->body
: !!node.as<ConstructorDeclaration>()->body;
};
auto hasRest = [](NodeArray<ParameterDeclaration> ¶meters) {
return llvm::any_of(parameters, [](auto parameter) { return !!parameter->dotDotDotToken; });
};
auto widen = [&](auto &members) {
SmallVector<Node> overloads;
std::string groupName;
for (Node member : members)
{
auto parameters = paramsOf(member);
auto name = parameters ? nameOf(member) : std::string();
if (!parameters || name.empty())
{
overloads.clear();
continue;
}
if (name != groupName)
{
overloads.clear();
groupName = name;
}
if (!hasBody(member))
{
overloads.push_back(member);
continue;
}
// the implementation
Node widest;
for (auto overload : overloads)
{
auto overloadParameters = paramsOf(overload);
if (hasRest(*overloadParameters))
{
widest = Node();
break;
}
if (!widest || overloadParameters->size() > paramsOf(widest)->size())
{
widest = overload;
}
}
overloads.clear();
if (!widest || hasRest(*parameters) || paramsOf(widest)->size() <= parameters->size())
{
continue;
}
auto &widestParameters = *paramsOf(widest);
for (auto index = parameters->size(); index < widestParameters.size(); index++)
{
auto source = widestParameters[index];
auto parameter = nf.createParameterDeclaration(
undefined, undefined,
nf.createIdentifier(S("__overload_arg") + stows(std::to_string(index))),
nf.createToken(SyntaxKind::QuestionToken), nf.createToken(SyntaxKind::AnyKeyword));
parameter->pos = source->pos;
parameter->_end = source->_end;
parameters->push_back(parameter);
}
}
};
// through statements and class members only: an expression holds no declaration list, and a walk of every
// node overflowed the stack on a deep one (binderBinaryExpressionStress)
std::function<void(Node)> walk;
auto walkStatements = [&](NodeArray<Statement> &statements) {
widen(statements);
for (auto statement : statements)
{
walk(statement);
}
};
auto walkBody = [&](Node body) {
if (body && body == SyntaxKind::Block)
{
walkStatements(body.as<ts::Block>()->statements);
}
};
walk = [&](Node node) {
if (!node)
{
return;
}
switch ((SyntaxKind)node)
{
case SyntaxKind::Block:
walkStatements(node.as<ts::Block>()->statements);
break;
case SyntaxKind::ModuleDeclaration:
if (auto body = node.as<ModuleDeclaration>()->body)
{
if (body == SyntaxKind::ModuleBlock)
{
walkStatements(body.as<ModuleBlock>()->statements);
}
else
{
walk(body);
}
}
break;
case SyntaxKind::FunctionDeclaration:
walkBody(node.as<FunctionDeclaration>()->body);
break;
case SyntaxKind::ClassDeclaration:
widen(node.as<ClassDeclaration>()->members);
for (auto member : node.as<ClassDeclaration>()->members)
{
if (member == SyntaxKind::MethodDeclaration)
{
walkBody(member.as<MethodDeclaration>()->body);
}
else if (member == SyntaxKind::Constructor)
{
walkBody(member.as<ConstructorDeclaration>()->body);
}
}
break;
case SyntaxKind::IfStatement:
walk(node.as<IfStatement>()->thenStatement);
walk(node.as<IfStatement>()->elseStatement);
break;
case SyntaxKind::ForStatement:
walk(node.as<ForStatement>()->statement);
break;
case SyntaxKind::ForInStatement:
walk(node.as<ForInStatement>()->statement);
break;
case SyntaxKind::ForOfStatement:
walk(node.as<ForOfStatement>()->statement);
break;
case SyntaxKind::WhileStatement:
walk(node.as<WhileStatement>()->statement);
break;
case SyntaxKind::DoStatement:
walk(node.as<DoStatement>()->statement);
break;
case SyntaxKind::LabeledStatement:
walk(node.as<LabeledStatement>()->statement);
break;
case SyntaxKind::TryStatement:
walk(node.as<TryStatement>()->tryBlock);
if (node.as<TryStatement>()->catchClause)
{
walk(node.as<TryStatement>()->catchClause->block);
}
walk(node.as<TryStatement>()->finallyBlock);
break;
default:
break;
}
};
walkStatements(sourceFile->statements);
}
// Properties a function is given after it (`function foo() {} foo.bar = 12; foo["baz"] = "ok";`, a const holding an
// arrow or a function expression too): TypeScript's expando declarations, a namespace merged with the function.
// The first assignment of each property, at the file's top level, is that namespace's exported `let` with the
// value assigned (`namespace foo { export let bar = 12; }`); a later one assigns it, and `foo.bar` reads it
// (mlirGenPropertyAccessExpressionLogic). They were "access expression is not applicable to () => void" (TSLANG 191).
static void lowerExpandoAssignments(SourceFile sourceFile)
{
// the functions of the file's top level, and whether each is exported
llvm::StringMap<bool> functions;
// the string constants of the top level (`const strMem = "strMemName"`), for `foo[strMem] = ...`
llvm::StringMap<std::string> stringConstants;
for (auto &statement : sourceFile->statements)
{
if (statement == SyntaxKind::FunctionDeclaration)
{
auto functionDeclaration = statement.as<FunctionDeclaration>();
if (functionDeclaration->name && functionDeclaration->body)
{
functions[MLIRHelper::getName(functionDeclaration->name)] = hasModifier(statement, SyntaxKind::ExportKeyword);
}
}
else if (statement == SyntaxKind::VariableStatement)
{
auto declarationList = statement.as<VariableStatement>()->declarationList;
if ((declarationList->flags & NodeFlags::Const) != NodeFlags::Const)
{
continue;
}
for (auto variable : declarationList->declarations)
{
if (variable->name != SyntaxKind::Identifier || !variable->initializer)
{
continue;
}
auto name = MLIRHelper::getName(variable->name.as<Identifier>());
if (variable->initializer == SyntaxKind::ArrowFunction || variable->initializer == SyntaxKind::FunctionExpression)
{
functions[name] = hasModifier(statement, SyntaxKind::ExportKeyword);
}
else if (variable->initializer == SyntaxKind::StringLiteral)
{
stringConstants[name] = convertWideToUTF8(variable->initializer.as<ts::StringLiteral>()->text);
}
}
}
}
if (functions.empty())
{
return;
}
auto isIdentifierName = [](StringRef name) {
if (name.empty() || !(llvm::isAlpha(name[0]) || name[0] == '_' || name[0] == '$'))
{
return false;
}
return llvm::all_of(name, [](char c) { return llvm::isAlnum(c) || c == '_' || c == '$'; });
};
NodeFactory nf(NodeFactoryFlags::None);
llvm::StringSet<> declared;
for (auto &statement : sourceFile->statements)
{
if (statement != SyntaxKind::ExpressionStatement)
{
continue;
}
auto expression = statement.as<ExpressionStatement>()->expression;
if (expression != SyntaxKind::BinaryExpression
|| expression.as<BinaryExpression>()->operatorToken != SyntaxKind::EqualsToken)
{
continue;
}
auto assignment = expression.as<BinaryExpression>();
Expression target;
std::string property;
if (assignment->left == SyntaxKind::PropertyAccessExpression)
{
auto access = assignment->left.as<PropertyAccessExpression>();
target = access->expression;
if (access->name == SyntaxKind::Identifier)
{
property = MLIRHelper::getName(access->name.as<Identifier>());
}
}
else if (assignment->left == SyntaxKind::ElementAccessExpression)
{
auto access = assignment->left.as<ElementAccessExpression>();
target = access->expression;
auto key = access->argumentExpression;
if (key == SyntaxKind::StringLiteral)
{
property = convertWideToUTF8(key.as<ts::StringLiteral>()->text);
}
else if (key == SyntaxKind::NoSubstitutionTemplateLiteral)
{
property = convertWideToUTF8(key.as<NoSubstitutionTemplateLiteral>()->text);
}
else if (key == SyntaxKind::Identifier)
{
auto constant = stringConstants.find(MLIRHelper::getName(key.as<Identifier>()));
if (constant != stringConstants.end())
{
property = constant->second;
}
}
}
if (!target || target != SyntaxKind::Identifier || !isIdentifierName(property))
{
continue;
}
auto functionName = MLIRHelper::getName(target.as<Identifier>());
auto function = functions.find(functionName);
if (function == functions.end())
{
continue;
}
auto propertyName = nf.createIdentifier(convertUTF8toWide(property));
if (!declared.insert(functionName + "." + property).second)
{
// a later assignment: the namespace's `let`, read as the function's property
if (assignment->left == SyntaxKind::ElementAccessExpression)
{
auto access = nf.createPropertyAccessExpression(target, propertyName);
access->pos = assignment->left->pos;
access->_end = assignment->left->_end;
assignment->left = access;
}
continue;
}
NodeArray<VariableDeclaration> declarations;
auto declaration = nf.createVariableDeclaration(propertyName, undefined, undefined, assignment->right);
declaration->pos = statement->pos;
declaration->_end = statement->_end;
declarations.push_back(declaration);
ModifiersArray letModifiers;
letModifiers.push_back(nf.createToken(SyntaxKind::ExportKeyword));
auto declarationList = nf.createVariableDeclarationList(declarations, NodeFlags::Let);
declarationList->pos = statement->pos;
declarationList->_end = statement->_end;
auto variableStatement = nf.createVariableStatement(letModifiers, declarationList);
variableStatement->pos = statement->pos;
variableStatement->_end = statement->_end;
NodeArray<Statement> blockStatements;
blockStatements.push_back(variableStatement);
auto block = nf.createModuleBlock(blockStatements);
block->pos = statement->pos;
block->_end = statement->_end;
NodeArray<ModifierLike> namespaceModifiers;
if (function->second)
{
namespaceModifiers.push_back(nf.createToken(SyntaxKind::ExportKeyword));
}
auto namespaceName = nf.createIdentifier(convertUTF8toWide(functionName));
auto namespaceDeclaration = nf.createModuleDeclaration(namespaceModifiers, namespaceName, block, NodeFlags::Namespace);
namespaceDeclaration->pos = statement->pos;
namespaceDeclaration->_end = statement->_end;
namespaceDeclaration->parent = sourceFile;
statement = namespaceDeclaration;
}
}
void MLIRGenImpl::lowerDefaultExports(SourceFile sourceFile, StringRef filePath)
{
if (!sourceFile)
{
return;
}
widenOverloadImplementations(sourceFile);
lowerExpandoAssignments(sourceFile);
for (auto statement : sourceFile->statements)
{
if (statement == SyntaxKind::ModuleDeclaration)
{
recordAmbientModule(statement.as<ModuleDeclaration>());
}
}
auto canonicalPath = canonicalFilePath(filePath);
auto name = defaultExportName(filePath);
NodeFactory nf(NodeFactoryFlags::None);
// a JSON module (`import b = require("./b.json")`, `import b from "./b.json"`): its value is what it exports,
// `export = <the JSON>`, lowered below as any `export =` of an expression (TSLANG 191)
if (sys::path::extension(filePath) == ".json" && sourceFile->statements.size() == 1 &&
sourceFile->statements[0] == SyntaxKind::ExpressionStatement)
{
auto &statement = sourceFile->statements[0];
auto exportAssignment = nf.createExportAssignment(undefined, true, statement.as<ExpressionStatement>()->expression);
exportAssignment->pos = statement->pos;
exportAssignment->_end = statement->_end;
exportAssignment->parent = sourceFile;
statement = exportAssignment;
}
// A module has one default export, and the first is what `import x from` binds. Another (an error in
// TypeScript, but compiled as before) gets a name of its own, `<name>_<n>`: two unnamed functions given
// the one name were a redefinition. Counted per load, as a file may be loaded again and must give
// the same names.
auto unnamed = 0;
auto nextName = [&]() { return unnamed++ == 0 ? name : name + "_" + std::to_string(unnamed - 1); };
std::string defaultExport;
auto found = [&](StringRef exported) {
if (defaultExport.empty())
{
defaultExport = exported.str();
defaultExportByFile[canonicalPath] = defaultExport;
}
};
// the names the file declares as types only (an interface, a type alias) and not as values too: `export
// default Foo` of one exports a type, which no value stands for ("failed to legalize 'ts.InterfaceRef'")
llvm::StringSet<> typeOnlyNames;
llvm::StringSet<> valueNames;
for (auto &statement : sourceFile->statements)
{
// each read through its own node type: their layouts differ, and a `name` read through another
// (NamedDeclaration) was a crash under gcc
if (statement == SyntaxKind::InterfaceDeclaration)
{
typeOnlyNames.insert(MLIRHelper::getName(statement.as<InterfaceDeclaration>()->name));
}
else if (statement == SyntaxKind::TypeAliasDeclaration)
{
typeOnlyNames.insert(MLIRHelper::getName(statement.as<TypeAliasDeclaration>()->name));
}
else if (statement == SyntaxKind::ClassDeclaration)
{
if (auto declarationName = statement.as<ClassDeclaration>()->name)
{
valueNames.insert(MLIRHelper::getName(declarationName));
}
}
else if (statement == SyntaxKind::FunctionDeclaration)
{
if (auto declarationName = statement.as<FunctionDeclaration>()->name)
{
valueNames.insert(MLIRHelper::getName(declarationName));
}
}
else if (statement == SyntaxKind::EnumDeclaration)
{
valueNames.insert(MLIRHelper::getName(statement.as<EnumDeclaration>()->name));
}
else if (statement == SyntaxKind::ModuleDeclaration)
{
valueNames.insert(MLIRHelper::getName(statement.as<ModuleDeclaration>()->name));
}
else if (statement == SyntaxKind::VariableStatement)
{
for (auto variable : statement.as<VariableStatement>()->declarationList->declarations)
{
if (variable->name == SyntaxKind::Identifier)
{
valueNames.insert(MLIRHelper::getName(variable->name.as<Identifier>()));
}
}
}
}
// the top-level statements that declare a name (a function's overloads are several)
auto declarationsOf = [&](StringRef wanted) {
SmallVector<Statement *> found;
for (auto &statement : sourceFile->statements)
{
Node declarationName;
if (statement == SyntaxKind::InterfaceDeclaration)
{
declarationName = statement.as<InterfaceDeclaration>()->name;
}
else if (statement == SyntaxKind::TypeAliasDeclaration)
{
declarationName = statement.as<TypeAliasDeclaration>()->name;
}
else if (statement == SyntaxKind::ClassDeclaration)
{
declarationName = statement.as<ClassDeclaration>()->name;
}
else if (statement == SyntaxKind::FunctionDeclaration)
{
declarationName = statement.as<FunctionDeclaration>()->name;
}
else if (statement == SyntaxKind::EnumDeclaration)
{
declarationName = statement.as<EnumDeclaration>()->name;
}
else if (statement == SyntaxKind::ModuleDeclaration)
{
declarationName = statement.as<ModuleDeclaration>()->name;
}
else if (statement == SyntaxKind::VariableStatement)
{
for (auto variable : statement.as<VariableStatement>()->declarationList->declarations)
{
if (variable->name == SyntaxKind::Identifier && MLIRHelper::getName(variable->name.as<Identifier>()) == wanted)
{
found.push_back(&statement);
break;
}
}
continue;
}
if (declarationName && declarationName == SyntaxKind::Identifier &&
MLIRHelper::getName(declarationName.as<Identifier>()) == wanted)
{
found.push_back(&statement);
}
}
return found;
};
auto markExported = [&](StringRef wanted) {
auto found = declarationsOf(wanted);
for (auto *statement : found)
{
if (!hasModifier(*statement, SyntaxKind::ExportKeyword))
{
(*statement)->modifiers.push_back(nf.createToken(SyntaxKind::ExportKeyword));
}
}
return !found.empty();
};
// `export { a, b as c }` of the file's own declarations: each is exported, as `export` written on it would
// make it; `c` is another name for `b`, which the statement registers where it is generated (an import's
// alias). `export { a as default }` makes a the default export. They were "'export { ... }' statements are
// not supported" (TSLANG 191).
// `export = X` (CommonJS): X is what `import x = require("./m")` binds x to - a declaration of the file,
// exported, or the value of an expression, kept in an exported constant as `export default <expression>` is
for (auto &statement : sourceFile->statements)
{
if (statement == SyntaxKind::ExportDeclaration && !statement.as<ExportDeclaration>()->moduleSpecifier)
{
auto exportClause = statement.as<ExportDeclaration>()->exportClause;
if (exportClause && exportClause == SyntaxKind::NamedExports)
{
for (auto element : exportClause.as<NamedExports>()->elements)
{
auto local = MLIRHelper::getName(element->propertyName ? element->propertyName : element->name);
auto exported = MLIRHelper::getName(element->name);
markExported(local);
if (exported == "default")
{
found(local);
}
}
}
continue;
}
if (statement == SyntaxKind::ExportAssignment && statement.as<ExportAssignment>()->isExportEquals)
{
auto exportAssignment = statement.as<ExportAssignment>();
std::string exportedName;
if (exportAssignment->expression == SyntaxKind::Identifier)
{
exportedName = MLIRHelper::getName(exportAssignment->expression.as<Identifier>());
markExported(exportedName);
auto emptyStatement = nf.createEmptyStatement();
emptyStatement->pos = statement->pos;
emptyStatement->_end = statement->_end;
statement = emptyStatement;
}
else
{
exportedName = nextName();
NodeArray<VariableDeclaration> declarations;
auto declaration = nf.createVariableDeclaration(nf.createIdentifier(convertUTF8toWide(exportedName)),
undefined, undefined, exportAssignment->expression);
declaration->pos = exportAssignment->pos;
declaration->_end = exportAssignment->_end;
declarations.push_back(declaration);
ModifiersArray modifiers;
modifiers.push_back(nf.createToken(SyntaxKind::ExportKeyword));
auto declarationList = nf.createVariableDeclarationList(declarations, NodeFlags::Const);
declarationList->pos = exportAssignment->pos;
declarationList->_end = exportAssignment->_end;
auto variableStatement = nf.createVariableStatement(modifiers, declarationList);
variableStatement->pos = exportAssignment->pos;
variableStatement->_end = exportAssignment->_end;
variableStatement->parent = sourceFile;
statement = variableStatement;
}
exportEqualsByFile[canonicalPath] = exportedName;
found(exportedName);
}
}
for (auto &statement : sourceFile->statements)
{
if (statement == SyntaxKind::ExportAssignment && !statement.as<ExportAssignment>()->isExportEquals
&& statement.as<ExportAssignment>()->expression == SyntaxKind::Identifier)
{
auto exportedName = MLIRHelper::getName(statement.as<ExportAssignment>()->expression.as<Identifier>());
if (typeOnlyNames.contains(exportedName) && !valueNames.contains(exportedName))
{
auto emptyStatement = nf.createEmptyStatement();
emptyStatement->pos = statement->pos;
emptyStatement->_end = statement->_end;
statement = emptyStatement;
continue;
}
}
if (statement == SyntaxKind::ExportAssignment && !statement.as<ExportAssignment>()->isExportEquals)
{
auto constantName = nextName();
auto exportAssignment = statement.as<ExportAssignment>();
NodeArray<VariableDeclaration> declarations;
auto declaration = nf.createVariableDeclaration(nf.createIdentifier(convertUTF8toWide(constantName)), undefined,
undefined, exportAssignment->expression);
declaration->pos = exportAssignment->pos;
declaration->_end = exportAssignment->_end;
declaration->internalFlags |= InternalFlags::DefaultExport;
declarations.push_back(declaration);
ModifiersArray modifiers;
modifiers.push_back(nf.createToken(SyntaxKind::ExportKeyword));
auto declarationList = nf.createVariableDeclarationList(declarations, NodeFlags::Const);
declarationList->pos = exportAssignment->pos;
declarationList->_end = exportAssignment->_end;
auto variableStatement = nf.createVariableStatement(modifiers, declarationList);
variableStatement->pos = exportAssignment->pos;
variableStatement->_end = exportAssignment->_end;
variableStatement->parent = sourceFile;
statement = variableStatement;
found(constantName);
continue;
}
// (a function's overloads are one default export: the first named one is kept)
if ((statement == SyntaxKind::FunctionDeclaration || statement == SyntaxKind::ClassDeclaration)
&& hasModifier(statement, SyntaxKind::ExportKeyword) && hasModifier(statement, SyntaxKind::DefaultKeyword))
{
auto declaration = statement.as<NamedDeclaration>();
if (!declaration->name)
{
declaration->name = nf.createIdentifier(convertUTF8toWide(nextName()));
}
found(MLIRHelper::getName(declaration->name));
}
}
}
static std::string fileKey(SourceFile sourceFile)
{
return convertWideToUTF8(sourceFile->resolvedPath);
}
// A source file's text as the parser's UTF-16 units. A file saved as UTF-16 (a byte order mark FF FE or
// FE FF) is read as UTF-16; any other is UTF-8, and a byte that isn't valid UTF-8 there is U+FFFD. Read
// with stows() as UTF-8 regardless, a UTF-16 file and an invalid byte (`/\xA0/u`) aborted the compiler.
static std::wstring decodeSourceText(llvm::StringRef bytes)
{
std::wstring text;
auto *data = reinterpret_cast<const unsigned char *>(bytes.data());
auto size = bytes.size();
if (size >= 2 && ((data[0] == 0xFF && data[1] == 0xFE) || (data[0] == 0xFE && data[1] == 0xFF)))
{
auto littleEndian = data[0] == 0xFF;
text.reserve(size / 2);
for (size_t i = 2; i + 1 < size; i += 2)
{
auto unit = littleEndian ? (data[i] | (data[i + 1] << 8)) : ((data[i] << 8) | data[i + 1]);
text.push_back(static_cast<wchar_t>(unit));
}
return text;
}
text.reserve(size);
llvm::SmallVector<llvm::UTF16, 2> units(2);
auto *source = reinterpret_cast<const llvm::UTF8 *>(data);
auto *sourceEnd = source + size;
while (source < sourceEnd)
{
if (*source < 0x80)
{
text.push_back(static_cast<wchar_t>(*source++));
continue;
}
// one character at a time, so that a bad one costs only itself
auto length = static_cast<size_t>(llvm::getNumBytesForUTF8(*source));
auto *target = units.data();
if (length > static_cast<size_t>(sourceEnd - source)
|| llvm::ConvertUTF8toUTF16(&source, source + length, &target, units.data() + units.size(),
llvm::strictConversion) != llvm::conversionOK)
{
text.push_back(static_cast<wchar_t>(0xFFFD));
source++;
continue;
}
for (auto *unit = units.data(); unit < target; ++unit)
{
text.push_back(static_cast<wchar_t>(*unit));
}
}
return text;
}
std::pair<SourceFile, std::vector<SourceFile>> MLIRGenImpl::loadSourceBuf(mlir::Location location, const llvm::MemoryBuffer *sourceBuf, bool isMain)
{
std::vector<SourceFile> includeFiles;
std::vector<string> filesToProcess;
LocationHelper lh(builder.getContext());
auto [file, lineAndColumn] = lh.getLineAndColumnAndFile(location);
auto dirName = file.getDirectory();
auto sourceFileName = file.getName();
SmallString<256> fullPath;
sys::path::append(fullPath, dirName.getValue());
sys::path::append(fullPath, sourceFileName.getValue());
auto fullPathW = stows(fullPath.str().str());
Parser parser;
auto sourceFile = parser.parseSourceFile(
fullPathW,
decodeSourceText(sourceBuf->getBuffer()),
ScriptTarget::Latest);
auto sourceFilePath = canonicalFilePath(fullPath);
sourceFile->resolvedPath = convertUTF8toWide(sourceFilePath);
lowerDefaultExports(sourceFile, sourceFilePath);
// add default lib
if (isMain)
{
if (sourceFile->hasNoDefaultLib)
{
compileOptions.noDefaultLib = true;
}
if (!compileOptions.noDefaultLib)
{
// S(DEFAULT_LIB_DIR "/lib.d.ts")
filesToProcess.push_back(convertUTF8toWide(compileOptions.defaultDeclarationTSFile));
}
auto strictNull = sourceFile->pragmas.find(S("strict-null"));
if (strictNull != sourceFile->pragmas.end())
{
auto option = strictNull->second.front().find(S("option"));
if (option != strictNull->second.front().end())
{
compileOptions.strictNullChecks = option->second._arg.value == S("true");
mth.setStrictNullChecks(compileOptions.strictNullChecks);
}
}
}
// Every file referenced, directly or through another, is loaded once, and comes after the
// files it references, so a declaration precedes its uses: for a diamond (b and c both
// reference common) that is common, b, c. The file being loaded is already seen, so a
// reference back to it, or a reference cycle, ends there.
llvm::StringSet<> seenFiles;
seenFiles.insert(sourceFilePath);
// A file that is not there fails the load: the program would otherwise be compiled
// without the declarations it asked for.
auto anyMissing = false;
// `referencing` holds the reference (null for the default lib), in the directory
// `referencingDir`: a relative path is that file's, as in TypeScript, so it is looked for
// there first. Then as before - the working directory, the main file's directory, the
// default lib's - which a reference relative to the main file from a file elsewhere
// still relies on. `fromDefaultLib`: the file is the default lib or one it references.
std::function<void(const string &, SourceFile, const ts::data::FileReference *, StringRef, bool)> loadReferencedFile =
[&](const string &includeFileName, SourceFile referencing, const ts::data::FileReference *reference, StringRef referencingDir,
bool fromDefaultLib) {
auto includeFileNameUtf8 = convertWideToUTF8(includeFileName);
std::string actualFilePath;
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> includeBuf = std::make_error_code(std::errc::no_such_file_or_directory);
if (!sys::path::has_root_path(includeFileNameUtf8) && !referencingDir.empty())
{
SmallString<256> besideReferencing(referencingDir);
sys::path::append(besideReferencing, includeFileNameUtf8);
if (sys::fs::is_regular_file(besideReferencing))
{
includeBuf = sourceMgr.OpenIncludeFile(besideReferencing.str().str(), actualFilePath);
}
}
if (!includeBuf)
{
includeBuf = sourceMgr.OpenIncludeFile(includeFileNameUtf8, actualFilePath);
}
mlir::Location referenceLocation = location;
if (reference)
{
auto start = reference->pos.textPos > 0 ? reference->pos.textPos : reference->pos.pos;
referenceLocation = loc2(referencing, convertWideToUTF8(referencing->fileName), start,
static_cast<int>(reference->_end) - start);
}
if (!includeBuf)
{
emitError(referenceLocation, "can't open file: ") << includeFileNameUtf8;
anyMissing = true;
return;
}
// the declarations tslang wrote beside a shared library: see loadIncludeFile
if (isLibraryDeclarationsText((*includeBuf)->getBuffer()))
{
emitError(referenceLocation) << "'" << includeFileNameUtf8
<< "' holds the declarations of a shared library, which `import` reads "
"beside the library; the library itself is not there";
anyMissing = true;
return;
}
auto includeFilePath = canonicalFilePath(actualFilePath);
if (!seenFiles.insert(includeFilePath).second)
{
return;
}
if (fromDefaultLib)
{
defaultLibFiles.insert(includeFilePath);
}