-
Notifications
You must be signed in to change notification settings - Fork 745
/
wasm-s-parser.cpp
2612 lines (2458 loc) · 74.5 KB
/
wasm-s-parser.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
/*
* Copyright 2015 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "wasm-s-parser.h"
#include <cctype>
#include <cmath>
#include <limits>
#include "asm_v_wasm.h"
#include "asmjs/shared-constants.h"
#include "ir/branch-utils.h"
#include "shared-constants.h"
#include "wasm-binary.h"
#define abort_on(str) \
{ throw ParseException(std::string("abort_on ") + str); }
#define element_assert(condition) \
assert((condition) ? true : (std::cerr << "on: " << *this << '\n' && 0));
using cashew::IString;
namespace {
int unhex(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
throw wasm::ParseException("invalid hexadecimal");
}
} // namespace
namespace wasm {
static Address getCheckedAddress(const Element* s, const char* errorText) {
uint64_t num = atoll(s->c_str());
if (num > std::numeric_limits<Address::address_t>::max()) {
throw ParseException(errorText, s->line, s->col);
}
return num;
}
static bool elementStartsWith(Element& s, IString str) {
return s.isList() && s.size() > 0 && s[0]->isStr() && s[0]->str() == str;
}
Element::List& Element::list() {
if (!isList()) {
throw ParseException("expected list", line, col);
}
return list_;
}
Element* Element::operator[](unsigned i) {
if (!isList()) {
throw ParseException("expected list", line, col);
}
if (i >= list().size()) {
throw ParseException("expected more elements in list", line, col);
}
return list()[i];
}
IString Element::str() const {
if (!isStr()) {
throw ParseException("expected string", line, col);
}
return str_;
}
const char* Element::c_str() const {
if (!isStr()) {
throw ParseException("expected string", line, col);
}
return str_.str;
}
Element* Element::setString(IString str__, bool dollared__, bool quoted__) {
isList_ = false;
str_ = str__;
dollared_ = dollared__;
quoted_ = quoted__;
return this;
}
Element*
Element::setMetadata(size_t line_, size_t col_, SourceLocation* startLoc_) {
line = line_;
col = col_;
startLoc = startLoc_;
return this;
}
std::ostream& operator<<(std::ostream& o, Element& e) {
if (e.isList_) {
o << '(';
for (auto item : e.list_) {
o << ' ' << *item;
}
o << " )";
} else {
o << e.str_.str;
}
return o;
}
void Element::dump() {
std::cout << "dumping " << this << " : " << *this << ".\n";
}
SExpressionParser::SExpressionParser(char* input) : input(input) {
root = nullptr;
line = 1;
lineStart = input;
while (!root) { // keep parsing until we pass an initial comment
root = parse();
}
}
Element* SExpressionParser::parse() {
std::vector<Element*> stack;
std::vector<SourceLocation*> stackLocs;
Element* curr = allocator.alloc<Element>();
while (1) {
skipWhitespace();
if (input[0] == 0) {
break;
}
if (input[0] == '(') {
input++;
stack.push_back(curr);
curr = allocator.alloc<Element>()->setMetadata(
line, input - lineStart - 1, loc);
stackLocs.push_back(loc);
assert(stack.size() == stackLocs.size());
} else if (input[0] == ')') {
input++;
curr->endLoc = loc;
auto last = curr;
if (stack.empty()) {
throw ParseException("s-expr stack empty");
}
curr = stack.back();
assert(stack.size() == stackLocs.size());
stack.pop_back();
loc = stackLocs.back();
stackLocs.pop_back();
curr->list().push_back(last);
} else {
curr->list().push_back(parseString());
}
}
if (stack.size() != 0) {
throw ParseException("stack is not empty", curr->line, curr->col);
}
return curr;
}
void SExpressionParser::parseDebugLocation() {
// Extracting debug location (if valid)
char* debugLoc = input + 3; // skipping ";;@"
while (debugLoc[0] && debugLoc[0] == ' ') {
debugLoc++;
}
char* debugLocEnd = debugLoc;
while (debugLocEnd[0] && debugLocEnd[0] != '\n') {
debugLocEnd++;
}
char* pos = debugLoc;
while (pos < debugLocEnd && pos[0] != ':') {
pos++;
}
if (pos >= debugLocEnd) {
return; // no line number
}
std::string name(debugLoc, pos);
char* lineStart = ++pos;
while (pos < debugLocEnd && pos[0] != ':') {
pos++;
}
std::string lineStr(lineStart, pos);
if (pos >= debugLocEnd) {
return; // no column number
}
std::string colStr(++pos, debugLocEnd);
void* buf =
allocator.allocSpace(sizeof(SourceLocation), alignof(SourceLocation));
loc = new (buf) SourceLocation(
IString(name.c_str(), false), atoi(lineStr.c_str()), atoi(colStr.c_str()));
}
void SExpressionParser::skipWhitespace() {
while (1) {
while (isspace(input[0])) {
if (input[0] == '\n') {
line++;
lineStart = input + 1;
}
input++;
}
if (input[0] == ';' && input[1] == ';') {
if (input[2] == '@') {
parseDebugLocation();
}
while (input[0] && input[0] != '\n') {
input++;
}
line++;
if (!input[0]) {
return;
}
lineStart = ++input;
} else if (input[0] == '(' && input[1] == ';') {
// Skip nested block comments.
input += 2;
int depth = 1;
while (1) {
if (!input[0]) {
return;
}
if (input[0] == '(' && input[1] == ';') {
input += 2;
depth++;
} else if (input[0] == ';' && input[1] == ')') {
input += 2;
--depth;
if (depth == 0) {
break;
}
} else if (input[0] == '\n') {
line++;
lineStart = input;
input++;
} else {
input++;
}
}
} else {
return;
}
}
}
Element* SExpressionParser::parseString() {
bool dollared = false;
if (input[0] == '$') {
input++;
dollared = true;
}
char* start = input;
if (input[0] == '"') {
// parse escaping \", but leave code escaped - we'll handle escaping in
// memory segments specifically
input++;
std::string str;
while (1) {
if (input[0] == 0) {
throw ParseException("unterminated string", line, start - lineStart);
}
if (input[0] == '"') {
break;
}
if (input[0] == '\\') {
str += input[0];
if (input[1] == 0) {
throw ParseException(
"unterminated string escape", line, start - lineStart);
}
str += input[1];
input += 2;
continue;
}
str += input[0];
input++;
}
input++;
return allocator.alloc<Element>()
->setString(IString(str.c_str(), false), dollared, true)
->setMetadata(line, start - lineStart, loc);
}
while (input[0] && !isspace(input[0]) && input[0] != ')' && input[0] != '(' &&
input[0] != ';') {
input++;
}
if (start == input) {
throw ParseException("expected string", line, input - lineStart);
}
char temp = input[0];
input[0] = 0;
auto ret = allocator.alloc<Element>()
->setString(IString(start, false), dollared, false)
->setMetadata(line, start - lineStart, loc);
input[0] = temp;
return ret;
}
SExpressionWasmBuilder::SExpressionWasmBuilder(Module& wasm,
Element& module,
IRProfile profile,
Name* moduleName)
: wasm(wasm), allocator(wasm.allocator), profile(profile) {
if (module.size() == 0) {
throw ParseException("empty toplevel, expected module");
}
if (module[0]->str() != MODULE) {
throw ParseException("toplevel does not start with module");
}
if (module.size() == 1) {
return;
}
Index i = 1;
if (module[i]->dollared()) {
if (moduleName) {
*moduleName = module[i]->str();
}
i++;
}
if (i < module.size() && module[i]->isStr()) {
// these s-expressions contain a binary module, actually
std::vector<char> data;
while (i < module.size()) {
auto str = module[i++]->c_str();
if (auto size = strlen(str)) {
stringToBinary(str, size, data);
}
}
WasmBinaryBuilder binaryBuilder(wasm, data);
binaryBuilder.read();
return;
}
Index implementedFunctions = 0;
functionCounter = 0;
for (unsigned j = i; j < module.size(); j++) {
auto& s = *module[j];
preParseFunctionType(s);
preParseImports(s);
if (elementStartsWith(s, FUNC) && !isImport(s)) {
implementedFunctions++;
}
}
// we go through the functions again, now parsing them, and the counter begins
// from where imports ended
functionCounter -= implementedFunctions;
for (unsigned j = i; j < module.size(); j++) {
parseModuleElement(*module[j]);
}
}
bool SExpressionWasmBuilder::isImport(Element& curr) {
for (Index i = 0; i < curr.size(); i++) {
auto& x = *curr[i];
if (elementStartsWith(x, IMPORT)) {
return true;
}
}
return false;
}
void SExpressionWasmBuilder::preParseImports(Element& curr) {
IString id = curr[0]->str();
if (id == IMPORT) {
parseImport(curr);
}
if (isImport(curr)) {
if (id == FUNC) {
parseFunction(curr, true /* preParseImport */);
} else if (id == GLOBAL) {
parseGlobal(curr, true /* preParseImport */);
} else if (id == TABLE) {
parseTable(curr, true /* preParseImport */);
} else if (id == MEMORY) {
parseMemory(curr, true /* preParseImport */);
} else if (id == EVENT) {
parseEvent(curr, true /* preParseImport */);
} else {
throw ParseException(
"fancy import we don't support yet", curr.line, curr.col);
}
}
}
void SExpressionWasmBuilder::parseModuleElement(Element& curr) {
if (isImport(curr)) {
return; // already done
}
IString id = curr[0]->str();
if (id == START) {
return parseStart(curr);
}
if (id == FUNC) {
return parseFunction(curr);
}
if (id == MEMORY) {
return parseMemory(curr);
}
if (id == DATA) {
return parseData(curr);
}
if (id == EXPORT) {
return parseExport(curr);
}
if (id == IMPORT) {
return; // already done
}
if (id == GLOBAL) {
return parseGlobal(curr);
}
if (id == TABLE) {
return parseTable(curr);
}
if (id == ELEM) {
return parseElem(curr);
}
if (id == TYPE) {
return; // already done
}
if (id == EVENT) {
return parseEvent(curr);
}
std::cerr << "bad module element " << id.str << '\n';
throw ParseException("unknown module element", curr.line, curr.col);
}
Name SExpressionWasmBuilder::getFunctionName(Element& s) {
if (s.dollared()) {
return s.str();
} else {
// index
size_t offset = atoi(s.str().c_str());
if (offset >= functionNames.size()) {
throw ParseException(
"unknown function in getFunctionName", s.line, s.col);
}
return functionNames[offset];
}
}
Signature SExpressionWasmBuilder::getFunctionSignature(Element& s) {
if (s.dollared()) {
auto it = signatureIndices.find(s.str().str);
if (it == signatureIndices.end()) {
throw ParseException(
"unknown function type in getFunctionSignature", s.line, s.col);
}
return signatures[it->second];
} else {
// index
size_t offset = atoi(s.str().c_str());
if (offset >= signatures.size()) {
throw ParseException(
"unknown function type in getFunctionSignature", s.line, s.col);
}
return signatures[offset];
}
}
Name SExpressionWasmBuilder::getGlobalName(Element& s) {
if (s.dollared()) {
return s.str();
} else {
// index
size_t offset = atoi(s.str().c_str());
if (offset >= globalNames.size()) {
throw ParseException("unknown global in getGlobalName", s.line, s.col);
}
return globalNames[offset];
}
}
Name SExpressionWasmBuilder::getEventName(Element& s) {
if (s.dollared()) {
return s.str();
} else {
// index
size_t offset = atoi(s.str().c_str());
if (offset >= eventNames.size()) {
throw ParseException("unknown event in getEventName", s.line, s.col);
}
return eventNames[offset];
}
}
// Parse various forms of (param ...) or (local ...) element. This ignores all
// parameter or local names when specified.
std::vector<Type> SExpressionWasmBuilder::parseParamOrLocal(Element& s) {
size_t fakeIndex = 0;
std::vector<NameType> namedParams = parseParamOrLocal(s, fakeIndex);
std::vector<Type> params;
for (auto& p : namedParams) {
params.push_back(p.type);
}
return params;
}
// Parses various forms of (param ...) or (local ...) element:
// (param $name type) (e.g. (param $a i32))
// (param type+) (e.g. (param i32 f64))
// (local $name type) (e.g. (local $a i32))
// (local type+) (e.g. (local i32 f64))
// If the name is unspecified, it will create one using localIndex.
std::vector<NameType>
SExpressionWasmBuilder::parseParamOrLocal(Element& s, size_t& localIndex) {
assert(elementStartsWith(s, PARAM) || elementStartsWith(s, LOCAL));
std::vector<NameType> namedParams;
if (s.size() == 1) { // (param) or (local)
return namedParams;
}
for (size_t i = 1; i < s.size(); i++) {
IString name;
if (s[i]->dollared()) {
if (i != 1) {
throw ParseException("invalid wasm type", s[i]->line, s[i]->col);
}
if (i + 1 >= s.size()) {
throw ParseException("invalid param entry", s.line, s.col);
}
name = s[i]->str();
i++;
} else {
name = Name::fromInt(localIndex);
}
localIndex++;
Type type;
if (s[i]->isStr()) {
type = stringToType(s[i]->str());
} else {
if (elementStartsWith(s, PARAM)) {
throw ParseException(
"params may not have tuple types", s[i]->line, s[i]->col);
}
type = elementToType(*s[i]);
}
namedParams.emplace_back(name, type);
}
return namedParams;
}
// Parses (result type) element. (e.g. (result i32))
std::vector<Type> SExpressionWasmBuilder::parseResults(Element& s) {
assert(elementStartsWith(s, RESULT));
std::vector<Type> types;
for (size_t i = 1; i < s.size(); i++) {
types.push_back(stringToType(s[i]->str()));
}
return types;
}
// Parses an element that references an entry in the type section. The element
// should be in the form of (type name) or (type index).
// (e.g. (type $a), (type 0))
Signature SExpressionWasmBuilder::parseTypeRef(Element& s) {
assert(elementStartsWith(s, TYPE));
if (s.size() != 2) {
throw ParseException("invalid type reference", s.line, s.col);
}
return getFunctionSignature(*s[1]);
}
// Prases typeuse, a reference to a type definition. It is in the form of either
// (type index) or (type name), possibly augmented by inlined (param) and
// (result) nodes. (type) node can be omitted as well. Outputs are returned by
// parameter references.
// typeuse ::= (type index|name)+ |
// (type index|name)+ (param ..)* (result ..)* |
// (param ..)* (result ..)*
size_t
SExpressionWasmBuilder::parseTypeUse(Element& s,
size_t startPos,
Signature& functionSignature,
std::vector<NameType>& namedParams) {
std::vector<Type> params, results;
size_t i = startPos;
bool typeExists = false, paramsOrResultsExist = false;
if (i < s.size() && elementStartsWith(*s[i], TYPE)) {
typeExists = true;
functionSignature = parseTypeRef(*s[i++]);
}
size_t paramPos = i;
size_t localIndex = 0;
while (i < s.size() && elementStartsWith(*s[i], PARAM)) {
paramsOrResultsExist = true;
auto newParams = parseParamOrLocal(*s[i++], localIndex);
namedParams.insert(namedParams.end(), newParams.begin(), newParams.end());
for (auto p : newParams) {
params.push_back(p.type);
}
}
while (i < s.size() && elementStartsWith(*s[i], RESULT)) {
paramsOrResultsExist = true;
auto newResults = parseResults(*s[i++]);
results.insert(results.end(), newResults.begin(), newResults.end());
}
auto inlineSig = Signature(Type(params), Type(results));
// If none of type/param/result exists, this is equivalent to a type that does
// not have parameters and returns nothing.
if (!typeExists && !paramsOrResultsExist) {
paramsOrResultsExist = true;
}
if (!typeExists) {
functionSignature = inlineSig;
} else if (paramsOrResultsExist) {
// verify that (type) and (params)/(result) match
if (inlineSig != functionSignature) {
throw ParseException("type and param/result don't match",
s[paramPos]->line,
s[paramPos]->col);
}
}
// Add implicitly defined type to global list so it has an index
if (std::find(signatures.begin(), signatures.end(), functionSignature) ==
signatures.end()) {
signatures.push_back(functionSignature);
}
// If only (type) is specified, populate `namedParams`
if (!paramsOrResultsExist) {
size_t index = 0;
for (const auto& param : functionSignature.params) {
namedParams.emplace_back(Name::fromInt(index++), param);
}
}
return i;
}
// Parses a typeuse. Use this when only FunctionType* is needed.
size_t SExpressionWasmBuilder::parseTypeUse(Element& s,
size_t startPos,
Signature& functionSignature) {
std::vector<NameType> params;
return parseTypeUse(s, startPos, functionSignature, params);
}
void SExpressionWasmBuilder::preParseFunctionType(Element& s) {
IString id = s[0]->str();
if (id == TYPE) {
return parseType(s);
}
if (id != FUNC) {
return;
}
size_t i = 1;
Name name, exportName;
i = parseFunctionNames(s, name, exportName);
if (!name.is()) {
// unnamed, use an index
name = Name::fromInt(functionCounter);
}
functionNames.push_back(name);
functionCounter++;
Signature sig;
parseTypeUse(s, i, sig);
functionTypes[name] = sig.results;
}
size_t SExpressionWasmBuilder::parseFunctionNames(Element& s,
Name& name,
Name& exportName) {
size_t i = 1;
while (i < s.size() && i < 3 && s[i]->isStr()) {
if (s[i]->quoted()) {
// an export name
exportName = s[i]->str();
i++;
} else if (s[i]->dollared()) {
name = s[i]->str();
i++;
} else {
break;
}
}
if (i < s.size() && s[i]->isList()) {
auto& inner = *s[i];
if (elementStartsWith(inner, EXPORT)) {
exportName = inner[1]->str();
i++;
}
}
#if 0
if (exportName.is() && !name.is()) {
name = exportName; // useful for debugging
}
#endif
return i;
}
void SExpressionWasmBuilder::parseFunction(Element& s, bool preParseImport) {
brokeToAutoBlock = false;
Name name, exportName;
size_t i = parseFunctionNames(s, name, exportName);
if (!preParseImport) {
if (!name.is()) {
// unnamed, use an index
name = Name::fromInt(functionCounter);
}
functionCounter++;
} else {
// just preparsing, functionCounter was incremented by preParseFunctionType
if (!name.is()) {
// unnamed, use an index
name = functionNames[functionCounter - 1];
}
}
if (exportName.is()) {
auto ex = make_unique<Export>();
ex->name = exportName;
ex->value = name;
ex->kind = ExternalKind::Function;
if (wasm.getExportOrNull(ex->name)) {
throw ParseException("duplicate export", s.line, s.col);
}
wasm.addExport(ex.release());
}
// parse import
Name importModule, importBase;
if (i < s.size() && elementStartsWith(*s[i], IMPORT)) {
Element& curr = *s[i];
importModule = curr[1]->str();
importBase = curr[2]->str();
i++;
}
// parse typeuse: type/param/result
Signature sig;
std::vector<NameType> params;
i = parseTypeUse(s, i, sig, params);
// when (import) is inside a (func) element, this is not a function definition
// but an import.
if (importModule.is()) {
if (!importBase.size()) {
throw ParseException("module but no base for import", s.line, s.col);
}
if (!preParseImport) {
throw ParseException("!preParseImport in func", s.line, s.col);
}
auto im = make_unique<Function>();
im->name = name;
im->module = importModule;
im->base = importBase;
im->sig = sig;
functionTypes[name] = sig.results;
if (wasm.getFunctionOrNull(im->name)) {
throw ParseException("duplicate import", s.line, s.col);
}
wasm.addFunction(im.release());
if (currFunction) {
throw ParseException("import module inside function dec", s.line, s.col);
}
nameMapper.clear();
return;
}
// at this point this not an import but a real function definition.
if (preParseImport) {
throw ParseException("preParseImport in func", s.line, s.col);
}
size_t localIndex = params.size(); // local index for params and locals
// parse locals
std::vector<NameType> vars;
while (i < s.size() && elementStartsWith(*s[i], LOCAL)) {
auto newVars = parseParamOrLocal(*s[i++], localIndex);
vars.insert(vars.end(), newVars.begin(), newVars.end());
}
// make a new function
currFunction = std::unique_ptr<Function>(Builder(wasm).makeFunction(
name, std::move(params), sig.results, std::move(vars)));
currFunction->profile = profile;
// parse body
Block* autoBlock = nullptr; // may need to add a block for the very top level
auto ensureAutoBlock = [&]() {
if (!autoBlock) {
autoBlock = allocator.alloc<Block>();
autoBlock->list.push_back(currFunction->body);
currFunction->body = autoBlock;
}
};
while (i < s.size()) {
Expression* ex = parseExpression(*s[i++]);
if (!currFunction->body) {
currFunction->body = ex;
} else {
ensureAutoBlock();
autoBlock->list.push_back(ex);
}
}
if (brokeToAutoBlock) {
ensureAutoBlock();
autoBlock->name = FAKE_RETURN;
}
if (autoBlock) {
autoBlock->finalize(sig.results);
}
if (!currFunction->body) {
currFunction->body = allocator.alloc<Nop>();
}
if (s.startLoc) {
currFunction->prologLocation.insert(getDebugLocation(*s.startLoc));
}
if (s.endLoc) {
currFunction->epilogLocation.insert(getDebugLocation(*s.endLoc));
}
if (wasm.getFunctionOrNull(currFunction->name)) {
throw ParseException("duplicate function", s.line, s.col);
}
wasm.addFunction(currFunction.release());
nameMapper.clear();
}
Type SExpressionWasmBuilder::stringToType(const char* str,
bool allowError,
bool prefix) {
if (str[0] == 'i') {
if (str[1] == '3' && str[2] == '2' && (prefix || str[3] == 0)) {
return Type::i32;
}
if (str[1] == '6' && str[2] == '4' && (prefix || str[3] == 0)) {
return Type::i64;
}
}
if (str[0] == 'f') {
if (str[1] == '3' && str[2] == '2' && (prefix || str[3] == 0)) {
return Type::f32;
}
if (str[1] == '6' && str[2] == '4' && (prefix || str[3] == 0)) {
return Type::f64;
}
}
if (str[0] == 'v') {
if (str[1] == '1' && str[2] == '2' && str[3] == '8' &&
(prefix || str[4] == 0)) {
return Type::v128;
}
}
if (strncmp(str, "funcref", 7) == 0 && (prefix || str[7] == 0)) {
return Type::funcref;
}
if (strncmp(str, "externref", 9) == 0 && (prefix || str[9] == 0)) {
return Type::externref;
}
if (strncmp(str, "exnref", 6) == 0 && (prefix || str[6] == 0)) {
return Type::exnref;
}
if (allowError) {
return Type::none;
}
throw ParseException(std::string("invalid wasm type: ") + str);
}
HeapType SExpressionWasmBuilder::stringToHeapType(const char* str,
bool prefix) {
if (str[0] == 'a') {
if (str[1] == 'n' && str[2] == 'y' && (prefix || str[3] == 0)) {
return HeapType::AnyKind;
}
}
if (str[0] == 'e') {
if (str[1] == 'q' && (prefix || str[2] == 0)) {
return HeapType::EqKind;
}
if (str[1] == 'x') {
if (str[2] == 'n' && (prefix || str[3] == 0)) {
return HeapType::ExnKind;
}
if (str[2] == 't' && str[3] == 'e' && str[4] == 'r' && str[5] == 'n' &&
(prefix || str[6] == 0)) {
return HeapType::ExternKind;
}
}
}
if (str[0] == 'i') {
if (str[1] == '3' && str[2] == '1' && (prefix || str[3] == 0)) {
return HeapType::I31Kind;
}
}
if (str[0] == 'f') {
if (str[1] == 'u' && str[2] == 'n' && str[3] == 'c' &&
(prefix || str[4] == 0)) {
return HeapType::FuncKind;
}
}
throw ParseException(std::string("invalid wasm heap type: ") + str);
}
Type SExpressionWasmBuilder::elementToType(Element& s) {
if (s.isStr()) {
return stringToType(s.str(), false, false);
}
auto& tuple = s.list();
std::vector<Type> types;
for (size_t i = 0; i < s.size(); ++i) {
types.push_back(stringToType(tuple[i]->str()));
}
return Type(types);
}
Type SExpressionWasmBuilder::stringToLaneType(const char* str) {
if (strcmp(str, "i8x16") == 0) {
return Type::i32;
}
if (strcmp(str, "i16x8") == 0) {
return Type::i32;
}
if (strcmp(str, "i32x4") == 0) {
return Type::i32;
}
if (strcmp(str, "i64x2") == 0) {
return Type::i64;
}
if (strcmp(str, "f32x4") == 0) {
return Type::f32;
}
if (strcmp(str, "f64x2") == 0) {
return Type::f64;
}
return Type::none;
}
Function::DebugLocation
SExpressionWasmBuilder::getDebugLocation(const SourceLocation& loc) {
IString file = loc.filename;
auto& debugInfoFileNames = wasm.debugInfoFileNames;
auto iter = debugInfoFileIndices.find(file);
if (iter == debugInfoFileIndices.end()) {
Index index = debugInfoFileNames.size();
debugInfoFileNames.push_back(file.c_str());
debugInfoFileIndices[file] = index;
}
uint32_t fileIndex = debugInfoFileIndices[file];
return {fileIndex, loc.line, loc.column};
}
Expression* SExpressionWasmBuilder::parseExpression(Element& s) {
Expression* result = makeExpression(s);
if (s.startLoc && currFunction) {
currFunction->debugLocations[result] = getDebugLocation(*s.startLoc);
}
return result;
}
Expression* SExpressionWasmBuilder::makeExpression(Element& s){
#define INSTRUCTION_PARSER
#include "gen-s-parser.inc"
}
Expression* SExpressionWasmBuilder::makeUnreachable() {
return allocator.alloc<Unreachable>();
}
Expression* SExpressionWasmBuilder::makeNop() { return allocator.alloc<Nop>(); }
Expression* SExpressionWasmBuilder::makeBinary(Element& s, BinaryOp op) {
auto ret = allocator.alloc<Binary>();
ret->op = op;
ret->left = parseExpression(s[1]);
ret->right = parseExpression(s[2]);
ret->finalize();
return ret;
}
Expression* SExpressionWasmBuilder::makeUnary(Element& s, UnaryOp op) {
auto ret = allocator.alloc<Unary>();
ret->op = op;
ret->value = parseExpression(s[1]);
ret->finalize();
return ret;
}