forked from apache/tvm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.cc
More file actions
1985 lines (1771 loc) · 66 KB
/
parser.cc
File metadata and controls
1985 lines (1771 loc) · 66 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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* \file parser.cc
* \brief A parser for TVM IR.
*/
#include <tvm/ir/module.h>
#include <tvm/node/reflection.h>
#include <tvm/parser/parser.h>
#include <tvm/relay/adt.h>
#include <tvm/relay/expr.h>
#include <tvm/relay/function.h>
#include <tvm/relay/transform.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/object.h>
#include <tvm/runtime/registry.h>
#include <tvm/target/virtual_device.h>
#include <fstream>
#include "../support/scalars.h"
#include "./meta_ref.h"
#include "./op_table.h"
#include "./span_check.h"
#include "./tokenizer.h"
#include "tvm/runtime/builtin_fp16.h"
namespace tvm {
namespace parser {
using namespace relay;
using Expr = relay::Expr;
/*! \brief The meta table maps from type key to a sequence of objects. */
using MetaTable = Map<String, Array<ObjectRef>>;
using tvm::transform::CreateModulePass;
using tvm::transform::PassContext;
/*! \brief A helper for passing around spans with data structures with
* no span field.
*/
template <typename T>
struct Spanned {
T data;
Span span;
Spanned() = default;
Spanned(const Spanned<T>& other) = default;
Spanned(T data, Span span) : data(data), span(span) {}
};
/*! \brief A wrapper structure for capturing the result of parsing
* a global definition *before* we add it to the IRModule.
*
* This enables the parser to parse everything in one pass before
* constructing the IRModule.
*/
struct GlobalFunc {
GlobalVar global;
Function function;
GlobalFunc() : global(), function() {}
GlobalFunc(GlobalVar global, Function function) : global(global), function(function) {}
GlobalFunc(const GlobalFunc& gfunc) {
this->global = gfunc.global;
this->function = gfunc.function;
}
};
/*! \brief A wrapper structure for capturing all top-level definitions
* when parsing a module.
*/
struct Definitions {
/*! \brief The set of global functions. */
std::vector<GlobalFunc> funcs;
/*! \brief The set of type definitions. */
std::vector<TypeData> types;
// TODO(@jroesch): contain meta-table below
};
/*! \brief A structure representing the semantic versioning information
* for a Relay program.
*/
class SemVer {
public:
int major_version;
int minor_version;
int patch_version;
SemVer() : major_version(0), minor_version(0), patch_version(0) {}
SemVer(int major_version, int minor_version, int patch_version)
: major_version(major_version), minor_version(minor_version), patch_version(patch_version) {}
SemVer(const SemVer& other)
: major_version(other.major_version),
minor_version(other.minor_version),
patch_version(other.patch_version) {}
};
/*! \brief A simple wrapper around a mapping from raw string names
* to a TVM variable, type variable or other binder type.
*/
template <typename T>
struct Scope {
/*! \brief The internal map. */
std::unordered_map<std::string, T> name_map;
};
/*! \brief A stack of scopes.
*
* In order to properly handle scoping we must maintain a stack of scopes.
*
* A stack allows users to write programs which contain repeated variable
* names and to properly handle both nested scopes and removal of variables
* when they go out of scope.
*
* This is the classic approach to lexical scoping.
*/
template <typename T>
class ScopeStack {
private:
std::vector<Scope<T>> scope_stack;
std::unordered_map<std::string, T> free_vars;
public:
/*! \brief Adds a variable binding to the current scope. */
void Add(const std::string& name, const T& value) {
if (!this->scope_stack.size()) {
LOG(FATAL) << "internal issue";
}
this->scope_stack.back().name_map.insert({name, value});
}
void AddFreeVar(const std::string& name, const T& value) { free_vars.insert({name, value}); }
/*! \brief Looks up a variable name in the scope stack returning the matching variable
* in most recent scope. */
T Lookup(const std::string& name) {
for (auto scope = this->scope_stack.rbegin(); scope != this->scope_stack.rend(); ++scope) {
auto it = scope->name_map.find(name);
if (it != scope->name_map.end()) {
return it->second;
}
}
// Check if we bound a free variable declaration.
auto it = free_vars.find(name);
if (it != free_vars.end()) {
return it->second;
}
return T();
}
/*! \brief Adds a fresh scope. */
void PushStack() { this->scope_stack.push_back(Scope<T>()); }
/*! \brief Removes the most recent scope. */
void PopStack() { this->scope_stack.pop_back(); }
};
struct DuplicateKeyError : public Error {
explicit DuplicateKeyError(const std::string& msg) : Error(msg) {}
};
/*! \brief A table of interning strings as global function and type names. */
template <typename T>
struct InternTable {
/*! \brief The internal table mapping strings to a unique allocation. */
std::unordered_map<std::string, T> table;
DiagnosticContext* ctx;
/*! \brief Add the unique allocation. */
void Add(const std::string& name, const T& t) {
auto it = table.find(name);
if (it != table.end()) {
throw DuplicateKeyError("duplicate key name in intern table");
} else {
table.insert({name, t});
}
}
/*! \brief Return the unique allocation. */
Optional<T> Get(const std::string& name) const {
auto it = table.find(name);
if (it != table.end()) {
return Optional<T>(it->second);
} else {
return Optional<T>();
}
}
};
GlobalVar AddOrGet(InternTable<GlobalVar>* table, const std::string& name) {
auto var = table->Get(name);
if (var) {
return var.value();
} else {
auto gvar = GlobalVar(name);
table->Add(name, gvar);
return gvar;
}
}
GlobalTypeVar AddOrGet(InternTable<GlobalTypeVar>* table, const std::string& name,
TypeKind kind = TypeKind::kType) {
auto var = table->Get(name);
if (var) {
auto tvar = var.value();
TypeKind& tvar_kind = const_cast<TypeKind&>(tvar->kind);
tvar_kind = kind;
return tvar;
} else {
auto gvar = GlobalTypeVar(name, kind);
table->Add(name, gvar);
return gvar;
}
}
/*! \brief The parser class is the main interface to the parser.
* the parser is not currently exposed beyond this .cc file.
*
* The parser is initialized with a diagnostic context, an
* operator table, and a token stream.
*
* The rest of the internal state is used to map the human readable
* form to in-memory IR representation.
*
* The main entry point to the parser are a set of parsing methods
* such as `ParseModule` and `ParseExpr`.
*
* As with traditional recursive descent parsers the parsing methods
* are factored recursively just as one would do with a formal language
* grammar.
*
* You can view a recursive descent parser as a human friendly way to specify
* a state machine, and thus this factoring is necessary as the 'state' of this
* machine is the combination of the current parsing method and the next token.
*
* Parsing proceeds by matching a token and then dispatching to the appropriate
* method to parse the next tokens in the stream.
*
* For example if we are parsing a type and encounter a "Tensor" token we switch
* into a mode for parsing `[`, a shape, a comma, a data type and then a `]`.
*
* Certain matches like this are unambiguous and proceed in a straight line fashion
* once the initial token is found. Other parsing is more complex and requires some
* tricks to correctly parse.
*
* For example when we find a '(' in an expression context, it may be part of
* a tuple, the arguments to a call, or a parenthesized expression. The below code
* disambiguate these cases by factoring expression parsing into a series of methods
* which encode the parsing context and thus how to interpret the parenthesis.
*
* For more information one should be able to read the code in order starting with
* `ParseModule` or `ParseExpr`.
*/
class Parser {
public:
/*! \brief The version that the parser is parsing. */
SemVer version;
/*! \brief The IRModule we are building. */
IRModule module;
/*! \brief The diagnostic context used for error reporting. */
DiagnosticContext diag_ctx;
const Source& source;
/*! \brief The current position in the token stream. */
int pos;
/*! \brief The token stream for the parser. */
std::vector<Token> tokens;
/*! \brief The configured operator table. */
OperatorTable op_table;
/*! \brief Configure the whitespace mode, right now we ignore all whitespace. */
bool ignore_whitespace;
/*! \brief A global mapping for GlobalVar. */
InternTable<GlobalVar> global_names;
/*! \brief A global mapping for type definitions. */
InternTable<GlobalTypeVar> type_names;
/*! \brief A global mapping for constructor names. */
InternTable<Constructor> ctors;
/*! \brief A mapping from graph variable to expression, i.e., `%0 = expr`. */
std::unordered_map<int, Expr> graph_ctx;
/*! \brief The set of type scopes used for generics. */
ScopeStack<TypeVar> type_scopes;
/*! \brief The set of expression scopes used for lexical scope. */
ScopeStack<Var> expr_scopes;
/*! \brief The metadata section. */
MetaTable meta_table;
Parser(IRModule module, DiagnosticContext ctx, const Source& source, std::vector<Token> tokens,
OperatorTable op_table, MetaTable table)
: module(module),
diag_ctx(ctx),
source(source),
pos(0),
tokens(tokens),
op_table(op_table),
ignore_whitespace(true),
meta_table(table) {
InitializeGlobals();
InitializeTypeDefs();
}
/*! If we are parsing into a module with previously loaded data types we need to
* map constructor names and variable names in the global tables.
*/
void InitializeTypeDefs() {
for (auto pair : this->module->type_definitions) {
type_names.Add(pair.first->name_hint, pair.first);
for (auto ctor : pair.second->constructors) {
ctors.Add(ctor->name_hint, ctor);
}
}
}
void InitializeGlobals() {
for (auto pair : this->module->functions) {
global_names.Add(pair.first->name_hint, pair.first);
}
}
/*! \brief Examine the next token in the stream, the current parser is configured to be
* whitespace insensitive so we will skip all whitespace or comment tokens. */
Token Peek() {
// For now we ignore all whitespace tokens and comments.
// We can tweak this behavior later to enable white space sensitivity in the parser.
while (pos < static_cast<int64_t>(tokens.size()) && ignore_whitespace &&
(tokens.at(pos)->token_type == TokenType::kWhitespace ||
tokens.at(pos)->token_type == TokenType::kNewline ||
tokens.at(pos)->token_type == TokenType::kLineComment ||
tokens.at(pos)->token_type == TokenType::kComment)) {
pos++;
}
if (pos < static_cast<int64_t>(tokens.size())) {
return Token(this->tokens.at(pos));
} else {
return Token::Null();
}
}
/*! \brief Lookahead by N tokens.
* \param n The number of tokens to lookahead.
* \return The Nth token.
*/
Token Lookahead(int n) {
ICHECK_GE(n, 1) << "lookahead is only valid when n >= 1";
// We intend to skip n - 1 tokens, then return the nth.
auto old_pos = pos;
for (int i = 0; i < n - 1; i++) {
Peek();
pos++;
}
auto tok = Peek();
pos = old_pos;
return tok;
}
/*! \brief Consume a token, this method is the lowest level way to consume a token
* and will not ignore white space or look ahead in anyway.
*
* /param token_type The token type to match.
*/
void Consume(const TokenType& token_type) {
if (tokens[pos]->token_type != token_type) {
this->diag_ctx.EmitFatal(Diagnostic::Error(tokens[pos]->span)
<< "expected a " << Pretty(token_type) << " found "
<< Pretty(Peek()->token_type));
}
pos++;
}
/*! Match a token in the stream, this will first invoke Peek, ignoring tokens such
* as whitespace or comments returning the first meaningful token.
*
* We then try and consume the requested token, this will trigger an error if the
* current token does not match the token_type.
*/
Token Match(const TokenType& token_type) {
auto tok = Peek();
Consume(token_type);
return tok;
}
/*! Conditionally consume a token when it matches, this will never trigger an error
* as we guard against consuming the token before we do.
*
* Useful for matching optional tokens, effectively looksahead by one.
*/
bool WhenMatch(const TokenType& token_type) {
VLOG(9) << "Parser::WhenMatch: Peek() == " << Peek();
if (Peek()->token_type == token_type) {
Consume(token_type);
return true;
} else {
return false;
}
}
/* \brief Add a graph binding to the parsing context
*
* For example if we parse %0 = add(...), map 0 -> add(...), etc.
*/
void AddGraphBinding(const Token& token, const Expr& expr) {
auto graph_no = token.ToNumber();
this->graph_ctx.insert({graph_no, expr});
}
/* \brief Lookup a previously bound graph variable.
*
* Note: we take tokens in all lookup methods so that we
* that we can do error reporting based on token location.
*/
Expr LookupGraphBinding(const Token& token) {
auto graph_no = token.ToNumber();
auto it = this->graph_ctx.find(graph_no);
if (it != this->graph_ctx.end()) {
return it->second;
} else {
LOG(FATAL) << "Local variable %" << graph_no << " has not yet been defined";
throw;
}
}
/*! \brief Bind a local variable in the expression scope.
*
* "x" -> Var("x"), these are needed to map from the raw string names
* to unique variable nodes.
* If a virtual device is specified, sets the virtual device of the variable.
*/
Var BindVar(const std::string& name, const relay::Type& type_annotation,
Optional<VirtualDevice> virtual_device = Optional<VirtualDevice>()) {
auto var = Var(name, type_annotation);
var->virtual_device_ = virtual_device.value_or(VirtualDevice::FullyUnconstrained());
VLOG(1) << "Binding var named " << name << " to variable node " << PrettyPrint(var);
this->expr_scopes.Add(name, var);
return var;
}
/*! \brief Bind a local variable in the expression scope.
*
* "x" -> Var("x"), these are needed to map from the raw string names
* to unique variable nodes.
*/
Var BindFreeVar(const std::string& name, const relay::Type& type_annotation) {
auto var = Var(name, type_annotation);
this->expr_scopes.AddFreeVar(name, var);
return var;
}
/*! \brief Bind a type variable in the type scope.
*
* "A" -> TypeVar("A", ...), these are needed to map from raw string names
* to unique type variable nodes.
*/
TypeVar BindTypeVar(const std::string& name, const TypeKind type_kind) {
auto type_var = TypeVar(name, type_kind);
this->type_scopes.Add(name, type_var);
return type_var;
}
/*! \brief Lookup a variable in the expression scope.
*
* Note: all lookup methods take tokens intentionally for error reporting information.
*/
Var LookupLocal(const Token& local) {
auto var = this->expr_scopes.Lookup(local.ToString());
if (!var.defined()) {
diag_ctx.Emit(Diagnostic::Error(local->span)
<< "this local variable has not been previously declared");
}
return var;
}
/*! \brief Lookup a variable in the type scope.
*
* Note: all lookup methods take tokens intentionally for error reporting information.
*/
TypeVar LookupTypeVar(const Token& ident) {
auto var = this->type_scopes.Lookup(ident.ToString());
return var;
}
/*! \brief Add an expression scope to the scope stack. */
void PushScope() { this->expr_scopes.PushStack(); }
/*! \brief Remove N expression scopes from the scope stack. */
void PopScopes(int n) {
for (int i = 0; i < n; i++) {
this->expr_scopes.PopStack();
}
}
/*! \brief Add an type scope to the scope stack. */
void PushTypeScope() { this->type_scopes.PushStack(); }
/*! \brief Remove N type scopes from the scope stack. */
void PopTypeScopes(int n) {
for (int i = 0; i < n; i++) {
this->type_scopes.PopStack();
}
}
/*! \brief Convert a numeric token to an NDArray for embedding into the Relay program. */
NDArray NumberToNDArray(const Token& token) {
if (token->token_type == TokenType::kInteger) {
return support::IntImmToNDArray(Downcast<tvm::IntImm>(token->data));
} else if (token->token_type == TokenType::kFloat) {
return support::FloatImmToNDArray(Downcast<tvm::FloatImm>(token->data));
} else {
LOG(FATAL) << "internal error: should only call this function on numeric tokens";
return {};
}
}
[[noreturn]] void ParseError(const Token& token, const std::string& msg) {
throw std::runtime_error(msg);
}
/*! \brief A parsing helper for a bracketed expression <start> <parser> <stop>. */
template <typename R>
R Bracket(TokenType open, TokenType close, std::function<R()> parser) {
Match(open);
R result = parser();
Match(close);
return result;
}
/*! \brief Parse `(` parser() `)`. */
template <typename R>
R Parens(std::function<R()> parser) {
return Bracket(TokenType::kOpenParen, TokenType::kCloseParen, parser);
}
/*! \brief Parse `{` parser() `}`. */
template <typename R>
R Block(std::function<R()> parser) {
return Bracket(TokenType::kLCurly, TokenType::kRCurly, parser);
}
template <typename R>
R WithSpan(std::function<R()> parser) {
auto start_span = Peek()->span;
VLOG(9) << "WithSpan: start_span = " << start_span;
R ast = parser();
if (ast.defined()) {
// The token at the head of the stream is now 1 past where we parsed. So we find its start
// position as its start and end, so that when we merge we only grow the spanned region
// to the start of the current stream.
auto span_pos = pos - 1;
while ((tokens.at(span_pos)->token_type == TokenType::kWhitespace ||
tokens.at(span_pos)->token_type == TokenType::kNewline ||
tokens.at(span_pos)->token_type == TokenType::kLineComment ||
tokens.at(span_pos)->token_type == TokenType::kComment)) {
span_pos--;
}
auto end_token = tokens.at(span_pos);
VLOG(9) << "WithSpan: end_span = " << end_token->span;
ast->span = start_span.Merge(end_token->span);
}
return ast;
}
struct MetaRef {
std::string type_key;
uint64_t node_index;
Span span;
MetaRef(std::string type_key, uint64_t node_index, Span span)
: type_key(type_key), node_index(node_index), span(span) {}
};
MetaRef MetaRefFromToken(const Token& tok) {
Call ref = Downcast<Call>(tok->data);
auto attrs = ref->attrs.as<MetaRefAttrs>();
auto type_key = attrs->node_type_key;
auto index = attrs->node_index;
return MetaRef(type_key, index, ref->span);
}
/*! \brief Parse a meta reference of the form `meta[type_key][node_index]`.
* For example `meta[relay.Constant][0]` references the first constant, `meta[relay.Constant][1]`
* the second, and so on.
*/
ObjectRef ParseMetaRef() {
auto meta_ref_tok = Match(TokenType::kMetaReference);
auto meta_ref = MetaRefFromToken(meta_ref_tok);
auto it = this->meta_table.find(meta_ref.type_key);
if (it != this->meta_table.end()) {
auto nodes = (*it).second;
if (meta_ref.node_index < nodes.size()) {
return nodes[meta_ref.node_index];
} else {
this->diag_ctx.Emit(Diagnostic::Error(meta_ref.span)
<< "the node index `" << meta_ref.node_index
<< "` is out of bounds for `" << meta_ref.type_key << "`");
return ObjectRef();
}
} else {
this->diag_ctx.Emit(Diagnostic::Error(meta_ref.span)
<< "no entry in the meta table for `" << meta_ref.type_key << "`");
return ObjectRef();
}
}
/*! \brief Parses a sequence beginning with a start token, seperated by a seperator token, and
* ending with a stop token.
*
* The simple form being <start> (<parse()> <seperator>)* <stop>.
*
* This also provides a fourth argument which is allowed to run when the sequence which matches
* the inner sequence can not proceed.
*
* This is useful for parsing things like attributes which don't match the standard expression
* parsers but are contained within the stop token.
*/
template <typename T>
Array<T> ParseSequence(TokenType start, TokenType sep, TokenType stop, std::function<T()> parse,
std::function<bool()> before_stop = nullptr) {
VLOG(9) << "Parser::ParseSequence: start=" << ToString(start) << " sep=" << ToString(sep)
<< " stop=" << ToString(stop);
Match(start);
// This is for the empty arguments list case, if we have <start> <leftovers> <stop> token stream
// we must parse leftovers, then match a stop token.
if (before_stop) {
auto did_parse = before_stop();
if (did_parse) {
Match(stop);
return {};
}
}
// This is the case in which we find an empty arguments lists and no leftovers.
if (WhenMatch(stop)) {
return Array<T>();
} else {
VLOG(9) << "Parser::ParseSequence: parse first";
auto data = parse();
Array<T> elements = {data};
if (WhenMatch(stop)) {
return elements;
// parse '( expr ',' * ')'
} else if (WhenMatch(sep)) {
while (true) {
VLOG(9) << "Parser::ParseSequence: parse element";
if (WhenMatch(stop)) {
break;
} else {
// If before stop is
if (before_stop) {
auto did_parse = before_stop();
if (did_parse) {
Match(stop);
return elements;
}
}
auto data = parse();
WhenMatch(sep);
elements.push_back(data);
}
}
return elements;
} else {
auto next = Peek();
this->diag_ctx.EmitFatal(Diagnostic::Error(next->span)
<< "expected a " << Pretty(stop) << " found "
<< Pretty(next->token_type));
return Array<T>(nullptr);
}
}
}
/*! \brief Parse a full IRModule. */
IRModule ParseModule() {
// Parse the semver header at the top of the module.
this->version = ParseSemVer();
// Parse the definitions.
auto defs = ParseDefinitions();
// Parse the metadata section at the end.
auto metadata = ParseMetadata();
Match(TokenType::kEndOfFile);
for (auto type_def : defs.types) {
module->AddTypeDef(type_def->header, type_def);
}
for (auto func : defs.funcs) {
module->Add(func.global, func.function, true);
}
return module;
}
/*! \brief Parse the semantic versioning header. */
SemVer ParseSemVer(bool required = true) {
if (Peek()->token_type == TokenType::kVersion) {
auto version = Match(TokenType::kVersion);
// TODO(@jroesch): we currently only support 0.0.5.
if (version.ToString() != "\"0.0.5\"") {
this->diag_ctx.Emit(Diagnostic::Error(version->span)
<< "invalid semantic version `" << version.ToString() << "`");
}
} else if (required) {
this->diag_ctx.Emit(Diagnostic::Error(Peek()->span)
<< "expected text format semantic version, found a "
<< PrettyPrint(Peek()));
this->diag_ctx.Emit(Diagnostic::Help(Peek()->span)
<< "you can annotate it as #[version = \"0.0.5\"]");
}
return SemVer(0, 0, 5);
}
/*! \brief Parse zero or more Relay definitions. */
Definitions ParseDefinitions() {
Definitions defs;
while (true) {
auto next = Peek();
switch (next->token_type) {
case TokenType::kDefn: {
Consume(TokenType::kDefn);
auto global_tok = Match(TokenType::kGlobal);
auto global_name = global_tok.ToString();
auto global = AddOrGet(&global_names, global_name);
auto func = WithSpan<relay::Function>([&]() { return ParseFunctionDef(); });
ICHECK(func->span.defined()) << "spans must be set in parser";
defs.funcs.push_back(GlobalFunc(global, func));
continue;
}
case TokenType::kTypeDef: {
defs.types.push_back(ParseTypeDef());
continue;
}
case TokenType::kExtern: {
Consume(TokenType::kExtern);
auto type_def = ParseTypeDef();
if (type_def->constructors.size()) {
diag_ctx.Emit(Diagnostic::Error(next->span)
<< "an external type may not have any constructors");
}
defs.types.push_back(type_def);
}
default:
return defs;
}
}
}
/*! \brief Parse zero or more Relay type definitions. */
TypeData ParseTypeDef() {
// Match the `type` keyword.
Match(TokenType::kTypeDef);
// Parse the type's identifier.
auto type_tok = Match(TokenType::kIdentifier);
auto type_id = type_tok.ToString();
auto type_global = AddOrGet(&type_names, type_id, TypeKind::kAdtHandle);
Array<TypeVar> generics;
bool should_pop = false;
if (Peek()->token_type == TokenType::kLSquare) {
// If we have generics we need to add a type scope.
PushTypeScope();
should_pop = true;
generics = ParseSequence<TypeVar>(
TokenType::kLSquare, TokenType::kComma, TokenType::kRSquare, [&]() {
auto type_var_name = Match(TokenType::kIdentifier).ToString();
return BindTypeVar(type_var_name, TypeKind::kType);
});
}
Array<tvm::Constructor> ctors;
if (Peek()->token_type == TokenType::kLCurly) {
// Parse the list of constructors.
ctors = ParseSequence<tvm::Constructor>(
TokenType::kLCurly, TokenType::kComma, TokenType::kRCurly, [&]() {
// First match the name of the constructor.
auto ctor_tok = Match(TokenType::kIdentifier);
auto ctor_name = ctor_tok.ToString();
Constructor ctor;
// Match the optional field list.
if (Peek()->token_type != TokenType::kOpenParen) {
ctor = tvm::Constructor(ctor_name, {}, type_global);
} else {
auto arg_types =
ParseSequence<Type>(TokenType::kOpenParen, TokenType::kComma,
TokenType::kCloseParen, [&]() { return ParseType(); });
ctor = tvm::Constructor(ctor_name, arg_types, type_global);
}
ICHECK(ctor.defined());
try {
this->ctors.Add(ctor_name, ctor);
} catch (const DuplicateKeyError& e) {
this->diag_ctx.EmitFatal(Diagnostic::Error(ctor_tok->span)
<< "a constructor with the name "
<< "`" << ctor_name << "` "
<< "was previously defined");
}
return ctor;
});
}
// Now pop the type scope.
if (should_pop) {
PopTypeScopes(1);
}
return TypeData(type_global, generics, ctors);
}
std::string HackTokensAsString(int n) {
std::stringstream key;
n = std::min(static_cast<int>(tokens.size() - pos), n);
for (int i = 0; i < n; i++) {
key << ToString(tokens.at(pos + i)->token_type);
}
return key.str();
}
std::vector<Rule> ParseOp() {
std::vector<Rule> matched;
Peek();
for (int i = 4; i > 0; i--) {
auto key = HackTokensAsString(i);
auto it = this->op_table.this_is_a_hack.find(key);
if (it != this->op_table.this_is_a_hack.end()) {
pos = pos + i;
matched.push_back(it->second);
}
}
return matched;
}
/*! \brief Parse a single Relay expression. */
Expr ParseExpr() {
VLOG(9) << "Parser::ParseExpr";
return WithSpan<Expr>([this] {
std::vector<Expr> exprs;
while (true) {
VLOG(9) << "Parser::ParseExpr: parsing a single expression";
auto next = Peek();
switch (next->token_type) {
// For graph or let, match first rhs, then invoke ParseBindingExpr
// ParseBindingExpression then parse_lhs() parse_rhs() ';' continue
case TokenType::kLCurly: {
// NB: Might need to optimize to remove deep recursion.
// Stack should only grow proportionally to the number of
// nested scopes.
// Parses `{` expression `}`.
auto block = WithSpan<Expr>([&]() {
return Bracket<Expr>(TokenType::kLCurly, TokenType::kRCurly, [&]() {
PushScope();
auto expr = ParseExpr();
PopScopes(1);
return expr;
});
});
exprs.push_back(block);
break;
}
case TokenType::kFreeVar: {
Consume(TokenType::kFreeVar);
auto var_token = Match(TokenType::kLocal);
Type type;
if (WhenMatch(TokenType::kColon)) {
type = ParseType();
} else {
type = IncompleteType();
}
BindFreeVar(var_token.ToString(), type);
break;
}
// Parses `let ...`;
case TokenType::kLet:
exprs.push_back(ParseBindingExpr());
break;
case TokenType::kMatch:
case TokenType::kPartialMatch: {
bool is_total = next->token_type == TokenType::kMatch;
Consume(next->token_type);
exprs.push_back(ParseMatch(is_total));
break;
}
// %x ...
case TokenType::kGraph:
if (Lookahead(2)->token_type == TokenType::kEqual) {
exprs.push_back(ParseBindingExpr());
break;
}
// intentional fall through here.
default: {
exprs.push_back(ParseExprBinOp());
break;
}
}
if (!WhenMatch(TokenType::kSemicolon)) {
break;
}
}
ICHECK_GE(exprs.size(), 1);
if (exprs.size() == 1) {
// ICHECK(exprs[0].defined() && exprs[0]->span.defined())
// << "parser must set expression spans.\n"
// << exprs[0];
return exprs[0];
} else {
auto body = exprs.back();
exprs.pop_back();
while (exprs.size()) {
auto value = exprs.back();
ICHECK(value->span.defined()) << "parser must set expression spans.";
exprs.pop_back();
body = relay::Let(Var("", IncompleteType()), value, body, value->span.Merge(body->span));
}
ICHECK(body->span.defined()) << "parser must set expression spans.";
return body;
}
});
}
/*! \brief Parse a "binding expression"; an expression where
* a graph or let variable is bound.
*
* In order to avoid stack overflow this is implemented in a special
* iterative way to keep stack depth constant in a long chain of bindings.
*/
Expr ParseBindingExpr() {
// We use a loop here so that the stack depth
// does not grow linearly with a sequence of
// graph or let bindings.
//
// Assuming we start at call depth k, we will
// enter k + c call frames to parse the RHS
// of the bindings where `c` is the depth
// of recursion needed by RHS.
//
// If RHS is a call expresssion the c=1.
//
// Once we have parsed the RHS we will be
// back at depth K, and will return to
// this loop header to parse another
// graph or let binding.
//
// This ensures for n sequential bindings
// the call depth will be the same before
// and after parsing the n bindings.
VLOG(9) << "Parser::ParseBindingExpr";
std::vector<std::tuple<Var, Expr, Span>> bindings;
int scopes = 0;
while (true) {
auto next = Peek();
if (next->token_type == TokenType::kGraph && Lookahead(2)->token_type == TokenType::kEqual) {
Match(TokenType::kGraph);